|
4 | 4 |
|
5 | 5 | class UnderscoreBase implements \ArrayAccess, \Countable, \IteratorAggregate, \JsonSerializable
|
6 | 6 | {
|
7 |
| - const VERSION = '0.0.1'; |
| 7 | + const VERSION = '0.0.2'; |
8 | 8 |
|
9 | 9 | /** @var array The array manipulated by this Underscore instance */
|
10 | 10 | protected $data;
|
11 | 11 |
|
| 12 | + /** @var array Custom userland functionality through named callbacks */ |
| 13 | + protected static $mixins = []; |
| 14 | + |
12 | 15 | /**
|
13 | 16 | * Constructor.
|
14 | 17 | *
|
@@ -205,6 +208,8 @@ public function count()
|
205 | 208 |
|
206 | 209 | /**
|
207 | 210 | * Alias of count().
|
| 211 | + * |
| 212 | + * @return int |
208 | 213 | */
|
209 | 214 | public function size()
|
210 | 215 | {
|
@@ -328,10 +333,76 @@ public function omit($index)
|
328 | 333 | return $this->pick($indices);
|
329 | 334 | }
|
330 | 335 |
|
| 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 | + |
331 | 402 | /**
|
332 | 403 | * A static shortcut to constructor.
|
333 | 404 | *
|
334 |
| - * @param mixed $data |
| 405 | + * @param array|mixed $data Array or array like or array convertible. |
335 | 406 | *
|
336 | 407 | * @return self
|
337 | 408 | */
|
|
0 commit comments