From 1d1e9b61ef9c9f478cd6f6ac33e58e7dc996b682 Mon Sep 17 00:00:00 2001 From: Reza Date: Tue, 6 Oct 2015 12:29:33 +0330 Subject: [PATCH] - addiing toObj method - adding merge metho - enhancing getArrayableItems --- readme.md | 8 ++++---- src/Ary.php | 28 +++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/readme.md b/readme.md index 6fcfdb3..c8810d5 100644 --- a/readme.md +++ b/readme.md @@ -2,9 +2,9 @@ Ary === Are you tired from casting objects and arrays to each other? Don't do that anymore! Ary is a light class/function that makes accessing array items more convenient. -1. You can access array items using `->` or `[]` syntax. -2. You will get `null` if an index does not exists. -3. You can specify a default value for a missing index. +1. You can access array items using `->` or `['']` syntax. +2. You will get `null` if an index does not exists (instead of a nasty notification!) +3. You can specify a default value for missing indexes. * The class (`Ary()`) requires PHP 5.4 or newer. * The helper function (`ary()`) requires PHP 5.6 or newer. @@ -18,7 +18,7 @@ $ary = ary(); //setting and getting array items. $ary = ary(2, 4, 6, 8); //or -$ary = ary([2, 4, 6, 8]); //or +$ary = ary([2, 4, 6, 8]); $ary = ary(['x' => 'foo', 'y' => 'bar']); $foo = $ary->x; //or diff --git a/src/Ary.php b/src/Ary.php index 90ca06b..c912202 100644 --- a/src/Ary.php +++ b/src/Ary.php @@ -58,7 +58,12 @@ class Ary implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable if ($items instanceof self) { return $items->all(); } - + if (method_exists($items, 'toArray')) { + return $items->toArray(); + } + if ($items instanceof JsonSerializable) { + return json_decode(json_encode($items), true); + } return (array)$items; } @@ -124,6 +129,17 @@ class Ary implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable return $this->all(); } + /** + * Merge the collection with the given items. + * + * @param mixed $items + * @return static + */ + public function merge($items) + { + return new static(array_merge($this->items, $this->getArrayableItems($items))); + } + /** * Get a CachingIterator instance. * @@ -241,4 +257,14 @@ class Ary implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable { return $this->offsetExists($key); } + + /** + * Get the collection of items as a plain object. + * + * @return object + */ + public function toObject() + { + return (object)$this->all(); + } } \ No newline at end of file