Convert a value to a Collection instance

@param mixed       $collection mixed Value can be a single value, an array or a Collection
@param string|null $restrictTo Restricts the values of the collection to a given type

@return static
321257
public static function cast($collection, string $restrictTo = null)
    {
        if ($collection instanceof Collection) {
            return $collection;
        }

        return new static($collection, $restrictTo);
    }
479577
private function validateCollection($collection)
    {
        if ($collection === false)
            return $collection;
        $resolver = new OptionsResolver();
        $resolver->setRequired([
            'form',
            'rows',
        ]);
        $resolver->setDefaults([
            'buttons' => [],
            'sortBy' => false,
            'headerRow' => false,
        ]);
        $resolver->setAllowedTypes('form', ['string']);
        $resolver->setAllowedTypes('rows', ['array']);
        $resolver->setAllowedTypes('buttons', ['array']);
        $resolver->setAllowedTypes('sortBy', ['array', 'boolean']);
        $resolver->setAllowedTypes('headerRow', ['array', 'boolean']);
        $collection = $resolver->resolve($collection);
        $this->addFormTabMap($collection['form']);
        $collection['rows'] = $this->validateRows($collection['rows']);
        $collection['headerRow'] = $this->validateRow($collection['headerRow']);
        $collection['buttons'] = $this->validateButtons($collection['buttons']);
        if (is_array($collection['sortBy']) && count($collection['sortBy']) > 3)
            trigger_error(sprintf('The depth of sort for a collection is limited to 3 levels. %d > 3', count($collection['sortBy'])), E_USER_ERROR);
        
        return $collection;
    }
104720
private function initCollection(string $collection, string $class = null): void
    {
        $this->$collection = new Collection();
        $this->$collection->macroObject('createItem',
            function () use ($class): ?Assignable {
                if (null === $class) {
                    return null;
                }
                if (!class_exists($class)) {
                    throw new InvalidArgumentException(sprintf('Can not load class: %s', $class));
                }
                $item = new $class;
                if (!$item instanceof Assignable) {
                    throw new InvalidArgumentException(sprintf('%s must implement Assignable', $class));
                }

                return $item;
            });
    }
698211
public function take($limit): CollectionInterface
    {
        if ($limit >= 0) {
            return $this->takeFirst($limit);
        } else {
            return $this->takeLast(abs($limit));
        }
    }
1362986
public function groupBy($collection=null, $iterator=null) {
    list($collection, $iterator) = self::_wrapArgs(func_get_args(), 2);
    
    $result = array();
    $collection = (array) $collection;
    foreach($collection as $k=>$v) {
      $key = (is_callable($iterator)) ? $iterator($v, $k) : $v[$iterator];
      if(!array_key_exists($key, $result)) $result[$key] = array();
      $result[$key][] = $v;
    }
    return $result;
  }
676438
public function setCollection($collection)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');
        
        if ($collection != self::COLLECTION
        && !is_subclass_of($collection, self::COLLECTION)) {
            Exception::i()
                ->setMessage(Exception::NOT_SUB_COLLECTION)
                ->addVariable($collection)
                ->trigger();
        }
        
        $this->collection = $collection;
        return $this;
    }
1051523
protected function convertJsonCollectionToArray()
    {
        if (!is_array($this->value) && is_object($this->value)) {
            $orientObjects = array();

            $refClass = new \ReflectionObject($this->value);
            $properties = $refClass->getProperties(\ReflectionProperty::IS_PUBLIC);

            foreach ($properties as $property) {
                $orientObjects[$property->name] = $this->value->{$property->name};
            }

            $this->setValue($orientObjects);
        }
    }
322498
public function intersect(AbstractCollection $collection)
    {
        if (get_class($this) === get_class($collection)) {
            $newData = array_intersect($this->dataPlaceHolder, $collection->getDataPlaceHolder());

            return new static($newData);
        } else {
            $msg = "Intersection may apply only on two collections of the same type.";
            throw new InvalidArgumentException($msg);
        }
    }
878395
public function transform($collection)
    {   
        if (!$collection instanceof Collection) {  
            return null; 
        }
        
        $data = array();
        $accessor = PropertyAccess::createPropertyAccessor();
        
        foreach ($collection as $ref){
            if (!$ref instanceof Select2SortableInterface){
                throw new \InvalidArgumentException('Reference class must be instance of Select2SortableInterface');  
            }
            
            $data[] = $accessor->getValue($ref, $this->inversedProperty)->getId();
        }
        
        $this->collection = $collection;
        
        return implode(',', $data);
    }
1212344
public function toCollection($collection, $resultSetType = null)
    {
        $resultSetType = $resultSetType ?: $this->resultSetType;

        if ($resultSetType && false !== strpos($resultSetType, '\\')) {
            $collection = new $resultSetType($collection);
        } else {
            $collection = new ModelCollection($collection);
        }

        return $collection;
    }
137404
protected function toCollection($data, $collectionClass)
    {
        if ($data instanceof $collectionClass) {
            return $data;
        }

        $data = $data ?: array();
        if (!is_array($data) && !$data instanceof Collection) {
            throw new \InvalidArgumentException('Can transform only Collections or arrays.');
        }

        return new $collectionClass(
            is_array($data) ? $data : $data->toArray()
        );
    }
496033
public static function toKeyValue($collection, $key, $value, $useDotSyntax = false)
    {
        $keyValueArray = [];
        foreach ($collection as $item) {
            $itemArray = is_array($item) ? $item : (method_exists($item, 'toArray') ? $item->toArray() : []);
            $keyValue = self::get($itemArray, $key, null, $useDotSyntax);
            $keyValueArray[$keyValue] = $itemArray[$value];
        }

        return $keyValueArray;
    }
19552
public function diff(AbstractCollection $collection)
    {
        if (get_class($this) === get_class($collection)) {
            $newData = array_diff($this->dataPlaceHolder, $collection->getDataPlaceHolder());

            return new static($newData);
        } else {
            $msg = "Difference may apply only on two collections of the same type.";
            throw new InvalidArgumentException($msg);
        }
    }
98896
public function first(int $count = 1) : Collection
    {
        $i = 0;
        $new = [];
        foreach ($this as $k => $v) {
            if (++$i > $count) {
                break;
            }
            $new[$k] = $v;
        }
        return new static($new);
    }
1111526
public function values($collection=null) {
    list($collection) = self::_wrapArgs(func_get_args(), 1);
    
    return self::_wrap(array_values((array) $collection));
  }
183129
public function validate(Collection $collection = null)
    {
        $this->errors = [];
        foreach ($this->getValuesAsArray() as $index => $value) {
            # skip fields with a null value if they are not required
            if ($value === null && $this->hasRule(Rule::REQUIRED) === false) {
                continue;
            }

            foreach ($this->rules as $name => $rule) {
                $rule->setValue($value);
                $rule->setField($this, $index);
                $rule->setCollection($collection);
                if ($rule->validate() === true) {
                    $fmtValue = $rule->getValue();
                    if ($fmtValue !== $value) {
                        $value = $fmtValue;
                        $this->setValue($fmtValue, $index);
                    }
                }
                else {
                    $this->errors[] = $rule->getError();
                    break;
                }
            }
        }
        return count($this->errors) === 0;
    }
737855
private function isCollection($property, $value)
    {
        if (!$value instanceof Collection) {
            $got = is_object($value) ? get_class($value) : gettype($value);

            throw new \InvalidArgumentException(
                sprintf('Value of "%s" property must be an instance of Collection, got %s.', $property, $got)
            );
        }
    }