Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Model;
- use Nette\Utils\Json;
- use Tracy\Debugger;
- class Arrays extends \Nette\Utils\Arrays
- {
- public static function filter(array $arr, callable $callback): array
- {
- return array_filter($arr, $callback, ARRAY_FILTER_USE_BOTH);
- }
- public static function collect($arr): Collection
- {
- $col = new Collection($arr);
- return $col;
- }
- }
- class Collection
- {
- /** @var array */
- protected $items;
- public function __construct($list)
- {
- $this->items = $this->tryConvertToArray($list);
- return $this;
- }
- /**
- * @throws \RuntimeException
- */
- public function tryConvertToArray($list): array
- {
- if (is_array($list)) {
- return $list;
- } else if ($list instanceof \Traversable) {
- return iterator_to_array($list);
- } else {
- throw new \RuntimeException();
- }
- }
- public function map(callable $function): self
- {
- $this->items = Arrays::map($this->items, $function);
- return $this;
- }
- public function filter(callable $function): self
- {
- $this->items = Arrays::filter($this->items, $function);
- return $this;
- }
- public function column($key): self
- {
- $this->items = array_column($this->items, $key);
- return $this;
- }
- /**
- * @param $key mixed
- * @param mixed|null $default
- * @return mixed
- */
- public function get($key, $default = null)
- {
- return Arrays::get($this->items, $key, $default);
- }
- public function shuffle(): self
- {
- $this->shuffle($this->items);
- return $this;
- }
- public function flatten(): self
- {
- $this->items = Arrays::flatten($this->items);
- return $this;
- }
- public function values(): self
- {
- $this->items = array_values($this->items);
- return $this;
- }
- public function keys(): self
- {
- $this->items = array_keys($this->items);
- return $this;
- }
- public function dump(bool $bar = false, $barName = null): self
- {
- if ($bar) {
- Debugger::barDump($this->items, $barName);
- } else {
- dump($this->items);
- }
- return $this;
- }
- public function assoc(string $path): self
- {
- $this->items = Arrays::associate($this->items, $path);
- return $this;
- }
- public function flip(): self
- {
- $this->items = array_flip($this->items);
- return $this;
- }
- public function reverse(): self
- {
- $this->items = array_reverse($this->items);
- return $this;
- }
- public function toList(): array
- {
- return array_values($this->items);
- }
- public function toArray(): array
- {
- return array_values($this->items);
- }
- public function toJson($opts = null): string
- {
- return Json::encode($this->items, $opts);
- }
- public function count(): int
- {
- return count($this->items);
- }
- }
Add Comment
Please, Sign In to add comment