Skip to content

Commit

Permalink
Create new Base object and Collection is now extending it and final.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Aug 30, 2019
1 parent c8aca3c commit b3e0d19
Show file tree
Hide file tree
Showing 30 changed files with 168 additions and 202 deletions.
67 changes: 67 additions & 0 deletions src/Base.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

declare(strict_types=1);

namespace drupol\collection;

use drupol\collection\Contract\Base as BaseInterface;
use drupol\collection\Iterator\ClosureIterator;

/**
* Class Base.
*/
abstract class Base implements BaseInterface
{
/**
* @var \Closure
*/
protected $source;

/**
* Base constructor.
*
* @param \Closure|iterable|mixed $data
*/
public function __construct($data = [])
{
switch (true) {
case $data instanceof \Closure:
$this->source = $data;

break;
case \is_iterable($data):
$this->source = static function () use ($data) {
foreach ($data as $k => $v) {
yield $k => $v;
}
};

break;

default:
$this->source = static function () use ($data) {
foreach ((array) $data as $k => $v) {
yield $k => $v;
}
};
}
}

/**
* {@inheritdoc}
*/
public function getIterator(): ClosureIterator
{
return new ClosureIterator($this->source);
}

/**
* @param array $data
*
* @return \drupol\collection\Contract\Base
*/
public static function with($data = []): BaseInterface
{
return new static($data);
}
}

0 comments on commit b3e0d19

Please sign in to comment.