Skip to content

Commit c825515

Browse files
committed
feat(_base): add clon, tap, valueof; support mixin
1 parent 2e7356c commit c825515

File tree

1 file changed

+73
-2
lines changed

1 file changed

+73
-2
lines changed

src/UnderscoreBase.php

Lines changed: 73 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@
44

55
class UnderscoreBase implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
66
{
7-
const VERSION = '0.0.1';
7+
const VERSION = '0.0.2';
88

99
/** @var array The array manipulated by this Underscore instance */
1010
protected $data;
1111

12+
/** @var array Custom userland functionality through named callbacks */
13+
protected static $mixins = [];
14+
1215
/**
1316
* Constructor.
1417
*
@@ -205,6 +208,8 @@ public function count()
205208

206209
/**
207210
* Alias of count().
211+
*
212+
* @return int
208213
*/
209214
public function size()
210215
{
@@ -328,10 +333,76 @@ public function omit($index)
328333
return $this->pick($indices);
329334
}
330335

336+
/**
337+
* Creates a shallow copy.
338+
*
339+
* @return self
340+
*/
341+
public function clon()
342+
{
343+
return clone $this;
344+
}
345+
346+
/**
347+
* Invokes callback fn with clone and returns original self.
348+
*
349+
* @param callable $fn
350+
*
351+
* @return self
352+
*/
353+
public function tap(callable $fn)
354+
{
355+
$fn($this->clon());
356+
357+
return $this;
358+
}
359+
360+
/**
361+
* Adds a custom handler/method to instance. The handler is bound to this instance.
362+
*
363+
* @param string $name
364+
* @param \Closure $fn
365+
*
366+
* @return self
367+
*/
368+
public static function mixin($name, \Closure $fn)
369+
{
370+
static::$mixins[$name] = $fn;
371+
}
372+
373+
/**
374+
* Calls the registered mixin by its name.
375+
*
376+
* @param string $name
377+
* @param array $args
378+
*
379+
* @return self
380+
*/
381+
public function __call($method, $args)
382+
{
383+
if (isset(static::$mixins[$method])) {
384+
$method = \Closure::bind(static::$mixins[$method], $this);
385+
386+
return $method($args);
387+
}
388+
389+
throw new UnderscoreException("The mixin with name '$method' is not defined");
390+
}
391+
392+
/**
393+
* Get string value (JSON representation) of this instance.
394+
*
395+
* @return string
396+
*/
397+
public function valueOf()
398+
{
399+
return (string) $this;
400+
}
401+
331402
/**
332403
* A static shortcut to constructor.
333404
*
334-
* @param mixed $data
405+
* @param array|mixed $data Array or array like or array convertible.
335406
*
336407
* @return self
337408
*/

0 commit comments

Comments
 (0)