Common and useful classes, methods, exceptions etc.
Meritoo\Common\Collection\BaseCollection
It's a set of some elements with the same type, e.g. objects. It's iterable and countable. Provides very useful methods. Some of them:
getFirst()- returns the first element in the collectiongetLast()- returns the last element in the collectionisEmpty()- returns information if collection is emptyadd($element, $index = null)- adds given element (at the end of collection)addMultiple($elements, $useIndexes = false)- adds given elements (at the end of collection)prepend($element)- prepends given element (adds given element at the beginning of collection)remove($element)- removes given element
You have to implement:
abstract protected function isValidType($element): bool;This method verifies 1 element before it will be added to collection. Returns information if the element has valid, expected type.
Example (from Meritoo\Common\Collection\Templates class):
protected function isValidType($element): bool
{
return $element instanceof Template;
}You can, if you wish, overwrite these methods:
-
To prepare elements used to initialize the collection in your own way:
protected function prepareElements(array $elements): array
-
To validate type of elements in your own way:
protected function getElementsWithValidType(array $elements): array
use Meritoo\Common\Collection\StringCollection;
$emptyCollection = new StringCollection();
var_dump($emptyCollection->isEmpty()); // bool(true)
$elements = [
'lorem',
'ipsum',
123 => 'dolor',
345 => 'sit',
];
$simpleCollection = new StringCollection($elements);
var_dump($simpleCollection->has('dolor')); // bool(true)