Readme.md

Pantagruel74/CollectionGenerator


Language / Язык

  • All descriptions in that package duplicated on two languages: English and Russian.
  • Все описания и появнения к данному пакету дублируются на двух языках: Русском и Английском.

Description / Описание

ENG

  • The package is designed to generate collections of objects.
  • Using collections simplifies the use of sets of objects, allows you to make the code more readable.
  • Using collections allows you to save on validations, reduce the number of errors, and achieve set persistence.
  • Using collections is more in line with the object style, allows you to use OOP patterns for collections of objects.
  • Using collections allows you to use lambda functions, work with sets more declaratively.
  • This package is intended to compensate for the lack of generics and typed arrays in PHP.

RUS

  • Пакет предназначен для генерации коллекций объектов.
  • Использование коллекций упрощает использование наборов объектов, позволяет сделать код читабельнее.
  • Использование коллекций позволяет сэкономить на валидациях, снизить кол-во ошибок, добиться персистентности набора.
  • Использование коллекций больше соответствует объектному стилю, позволяет использовать ООП паттерны для наборов объектов.
  • Использование коллекций позволяет применять люмбда-функции, работать с наборами более декларативно.
  • Данный пакет призван компенсировать нехатку Дженериков и типизированных массивов в PHP.

Usage / Использование

ENG

  • Use the Pantagruel74\CollectionGenerator\CollectionGenerator->generateForClass(<YourClassFullName>) object method.
  • This method will generate the class <YourClassNamespace>\collections\<YourClassShortName>Collection into the appropriate directory.
  • For convenience, create a command in your CLI to generate collections using CollectionGenerator.
  • When installed via composer, a CLI script is generated: /vendor/bin/collection-generator, which can also be used to generate collections. See the "Installation" section for details on setting up and using it.

RUS

  • Используйте метод объекта Pantagruel74\CollectionGenerator\CollectionGenerator->generateForClass(<YourClassFullName>).
  • Даннный метод сгенерирует класс <YourClassNamespace>\collections\<YourClassShortName>Collection в соответствующую директорию.
  • Для удобства, создайте в вашем CLI команду, для генерации коллекиций, используя CollectionGenerator.
  • При установке через композер генерируется CLI-скрипт: /vendor/bin/collection-generator, который тоже можно использовать для генерации коллекций. Подробнее о его настройке и использовании смотрите в разделе "Установка".

Collections methods / Методы коллекций

ENG

  • public function add(<YourClass> $object): void - adding an element to the collection.
  • public function getAll(): <YourClass>[] - getting all elements from the collection.
  • public function removeObject(<YourClass> $object): void - remove an element from the collection.
    • Non-strict comparison "==" is used for searching.
    • The first occurrence is removed.
  • public function removeAll(<YourClass> $object): int - removal of all such elements from the collection.
    • Non-strict comparison "==" is used for searching.
    • All occurrences are removed.
  • public function filter(callable $callbackFunction): self - filters the objects in the array.
    • The result is returned as a new collection.
    • The original collection remains unchanged.
  • public function map(callable $callbackFunction): array - Converts a set from a collection to a new set and returns it.
    • The result is returned as an array of new objects.
    • The original collection remains unchanged.
  • public function apply(callable $callbackFunction): void - Applies the callback function to all elements of the collection.
    • Modifies the elements of the original collection.
    • The callback function must return an object of the same type as the base type of the collection (<YourClass>).
  • public function count(): int - returns the number of elements in the collection
  • public function getByIndex(int $index): ?<YourClass> - returns an element of the collection by its index
  • public function getNextIndex(int $index): ?int - Returns the index of the next element
  • public function getFirstIndex(): int - Returns the index of the first element
  • public function getIterator(): \Iterator - Returns an iterator
  • public function jsonSerialize(): <YourClass>[] - Returns data. available for serialization
  • public function getFirst(): <YourClass>[] - Returns the first element of the collection
    • Throws a RuntimeException if the collection is empty
  • public function getLast(): <YourClass>[] - Returns the last element of the collection
    • Throws a RuntimeException if the collection is empty
  • public function getFirstOrNull(): ?<YourClass>[] - Returns the first element of the collection, or null (if empty)
  • public function getLastOrNull(): ?<YourClass>[] - Returns the last element of the collection, or null (if empty)

Assertion methods

Allows you to declare checks inside filter/get call chains. If the collection does not meet the specified requirements, it raises an error (AssertionError by default). Avoids invariant calls to the next methods in the chain after filtering or removing from the collection multiple elements.

  • public function assertCountEquals(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection has exactly $count elements
  • public function assertCountNotEquals(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection contains exactly no $count elements
  • public function assertCountGreaterThen(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection has strictly more than $count elements
  • public function assertCountNotGreaterThen(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection has no more (less than or equal) than $count elements
  • public function assertCountLesserThen(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection has strictly less than $count elements
  • public function assertCountNotLesserThen(int $count, ?\Error $error = null): <YourClass>Collection - Checks that the collection has at least (greater than or equal to) $count elements

RUS

  • public function add(<YourClass> $object): void - добавление элемента в коллекцию.
  • public function getAll(): <YourClass>[] - получение всех элементов из коллекции.
  • public function removeObject(<YourClass> $object): void - удаление элемента из коллекции.
    • Для поиска используется нестрогое сравнение "==").
    • Удаляется первое вхождение.
  • public function removeAll(<YourClass> $object): int - удаление всех подобных элементов из коллекции.
    • Для поиска используется нестрогое сравнение "==").
    • Удаляются все вхождения.
  • public function filter(callable $callbackFunction): self - фильтрует объекты в массиве.
    • Результат возвращается в виде новой коллекции.
    • Исходная коллекция остается неизменной.
  • public function map(callable $callbackFunction): array - Преобразует набор из коллекции в новый набор и возвращает его.
    • Результат возвращается в виде массива новых объектов.
    • Исходная коллекция остается неизменной.
  • public function apply(callable $callbackFunction): void - Применяет callback-функцию ко всем элементам коллекции.
    • Изменяет элементы исходной коллекции.
    • Callback функиця должна возвращать объект соответствующего типа, что и базовый тип коллекции (<YourClass>).
  • public function count(): int - возврящает кол-во элементов в коллекции
  • public function getByIndex(int $index): ?<YourClass> - возвращает элемент коллекции по его индексу
  • public function getNextIndex(int $index): ?int - Возвращает индекс следующего элемента
  • public function getFirstIndex(): int - Возвращает индекс первого элемента
  • public function getIterator(): \Iterator - Возвращает итератор
  • public function jsonSerialize(): <YourClass>[] - Возвращает данные. доступные для сериализации
  • public function getFirst(): <YourClass>[] - Возвращает первый элемент коллекции
    • Выбрасывает RuntimeException если коллекция пуста
  • public function getLast(): <YourClass>[] - Возвращает последний элемент коллекции
    • Выбрасывает RuntimeException если коллекция пуста
  • public function getFirstOrNull(): ?<YourClass>[] - Возвращает первый элемент коллекции или null (если она пуста)
  • public function getLastOrNull(): ?<YourClass>[] - Возвращает последний элемент коллекции или null (если она пуста)

Assertion-методы

Позволяют объявлять проверки внутри filter/get цепочек вызовов. Если коллекция не соответствует указанным требованиям - вызывает ошибку (по умолчанию AssertionError). Позволяет избежать инвариантных вызовов следующих в цепочке методов, после фильтрации или удаления из коллекции нескольких элментов.

  • public function assertCountEquals(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции ровно $count элементов
  • public function assertCountNotEquals(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции ровно не $count элементов
  • public function assertCountGreaterThen(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции строго больше чем $count элементов
  • public function assertCountNotGreaterThen(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции не больше (меньше либо равно) чем $count элементов
  • public function assertCountLesserThen(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции строго меньше чем $count элементов
  • public function assertCountNotLesserThen(int $count, ?\Error $error = null): <YourClass>Сollection - Проверяет, что в коллекции не меньше (больше либо равно) чем $count элементов

Requirements / Требования

  • PHP: >=7.4

Installation / Установка

ENG

Install via Composer

  • In the project folder, run the command: composer require "pantagruel74/collection-generator"
  • The package will be installed to the vendor/pantagruel74/collection-generator folder and will be available by namespace Pantagruel74\CollectionGenerator
  • Alternatively, specify a package "pantagruel74/collection-generator": "*" to the require section of the composer.json file and run the command: composer update

Usage with composer CLI (terminal)

It is possible to use the composer terminal to generate collections. For this:
  • Install the package with composer as above
  • In the composer.json file, find or create a "scripts" section: {...}
  • In the scripts section, add the value: "generate:collection": "collection-generator"
  • The final content of the section should look like this:
//composer.json file:
{
... //some content
"scripts": {
... //some other scripts
"generate:collection": "collection-generator"
},
... //some content
}
  • Update the application configuration with the command: composer update
  • Test the script with composer generate:collection. You should get the message "Not point class for collection generation" - it means the script is connected correctly
  • Use the command: composer generate:collection <Full class name including namespace> to generate a collection for this class.
  • In case of successful generation, the terminal will display the line Success!
  • A collections folder will be created in the folder with the original class, the created collection will be located in it.

RUS

Установка через Composer

  • В папке проекта выполните команду: composer require "pantagruel74/collection-generator"
  • Пакет установится в папку vendor/pantagruel74/collection-generator и будет доступен по namespace'у Pantagruel74\CollectionGenerator
  • В качестве альтернативного способа, укажите пакет "pantagruel74/collection-generator": "*" в секцию require фала composer.json и выполните команду: composer update

Использование с помощью composer CLI (терминала)

Существует возможность использования composer-терминала для генерации коллекций. Для этого:
  • Установите пакет с помощью composer как указано выше
  • В файле composer.json найдите или создайте секцию "scripts": {...}
  • В секции scripts добавьте значение: "generate:collection": "collection-generator"
  • Итоговое содержание секции должно выглядеть так:
//composer.json файл:
{
... //какое-то содержание
"scripts": {
... //какие-то другие скрипты
"generate:collection": "collection-generator"
},
... //какое-то содержание
}
  • Обновите конфигурацию приложения командой: composer update
  • Проверьте работу скрипта командой composer generate:collection. Вы должны получить сообщение "Not point class for collection generation" - значит скрипт подключен корректно
  • Используйте команду: composer generate:collection <Полное имя класса включая namespace> для генерации коллекции для этого класса.
  • В случае успешной генерации в терминале отобразится строка Success!
  • В папке с исходным классом будет создана папка collections, созданная коллекция будет находиться в ней.

License / Лицензия

  • MIT

Author / Автор

  • Anatoly Starodubtsev
  • Email: tostar74@mail.ru
Конвейеры
0 успешных
0 с ошибкой