mnemesong/collection-generator

Collection generator tool

2.0.0 2023-08-17 20:13 UTC

This package is not auto-updated.

Last update: 2024-04-21 08:50:18 UTC


README

Latest Stable Version PHPUnit PHPStan-lvl9 PHP Version Require License

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.
  • Collections are completely immutable. all modifying methods create a clone of the collection with the required image changed composition.

RUS

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

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

ENG

  • Use the Mnemesong\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

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

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

ENG

  • public function withNewOneItem(<YourClass> $object): self - Creates a collection instance, complete with specified element
  • public function withManyNewItems(<YourClass>[] $objects): self - Creates a collection instance, complete with specified elements
  • public function getAll(): <YourClass>[] - Get all elements from the collection.
  • public function withoutObjectsLike(<YourClass> $object, int $limit): void - Creates a collection instance, without $limit of specified objects. Equality comparison of all fields. If $limit is negative then deletion starts from the end. If $limit = 0, then all occurrences of such an object are removed.
  • public function filteredBy(callable $callbackFunction): self - Creates an instance of the collection, filtered according to the specified callable function.
  • public function map(callable $callbackFunction): array - Returns an array of any type given applying the specified callable function to all elements of the collection.
  • public function reworkedBy(callable $callbackFunction): void - Creates an instance of a collection whose elements changed by the callback function. The callable function must return an element of the same type as the elements of the collection.
  • public function sortedBy(callable $callbackFunction): void - Creates an instance of a collection whose elements sorted by the callback function using the uasort() method.
  • public function count(): int - Returns the number of elements in the collection
  • public function jsonSerialize(): <YourClass>[] - Returns data. available for serialization
  • public function assertCount(callable $callbackFunction): self - Applies a callback function to the count value, throws a RuntimeException if the check is not true ($callbackFunction($count) !== true), otherwise returns an instance of the collection on which the method was run. Used to check the state of a collection in method chains.
  • public function getFirstAsserted(): <YourClass>[] - Returns the first element of the collection, checking if it is not empty. Throws a RuntimeException if the first element cannot be retrieved because the collection is empty.
  • public function getLastAsserted(): <YourClass>[] - Returns the last element of the collection, checking if it is not empty. Throws a RuntimeException if the first element cannot be retrieved because 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)

RUS

  • public function withNewOneItem(<YourClass> $object): self - Создает экземпляр коллекции, дополненный указанным элементом
  • public function withManyNewItems(<YourClass>[] $objects): self - Создает экземпляр коллекции, дополненный указанными элементами
  • public function getAll(): <YourClass>[] - Получение всех элементов из коллекции.
  • public function withoutObjectsLike(<YourClass> $object, int $limit): void - Создает экземпляр коллекции, без $limit указанных объектов. Сравнение по равенству всех полей. Если $limit отрицательный, то удаление начинается с конца. Если $limit = 0, то удаляются все вхождения подобного объекта.
  • public function filteredBy(callable $callbackFunction): self - Создает экземпляр коллекции, отфильтрованный согласно указанной callable функции.
  • public function map(callable $callbackFunction): array - Возвразщает массив любого типа полученный применением указанной callable функции ко всем элементам коллекции.
  • public function reworkedBy(callable $callbackFunction): void - Создает экземпляр коллекции, элементы которой изменены callback-функцией. Callable функция должна возвращать элемент того-же типа, что и элементы коллекции.
  • public function sortedBy(callable $callbackFunction): void - Создает экземпляр коллекции, элементы которой отсортированны callback-функцией методом uasort().
  • public function count(): int - Возвращает кол-во элементов в коллекции
  • public function jsonSerialize(): <YourClass>[] - Возвращает данные. доступные для сериализации
  • public function assertCount(callable $callbackFunction): self - Применяет callback-функцию к значению count, выбрасывает RuntimeException в случае не истинности проверки ($callbackFunction($count) !== true), иначе возвращает экземпляр коллекции с которой был запущен метод. Используется для проверки состояния коллекции в цепочках методов.
  • public function getFirstAsserted(): <YourClass>[] - Возвращает первый элемент коллекции, проверяя его непустоту. Выбрасывает RuntimeException, в случае, если нельзя получить первый элемент по причине пустоты коллекции.
  • public function getLastAsserted(): <YourClass>[] - Возвращает последний элемент коллекции, проверяя его непустоту. Выбрасывает RuntimeException, в случае, если нельзя получить первый элемент по причине пустоты коллекции.
  • public function getFirstOrNull(): ?<YourClass>[] - Возвращает первый элемент коллекции или null (если она пуста)
  • public function getLastOrNull(): ?<YourClass>[] - Возвращает последний элемент коллекции или null (если она пуста)

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

  • PHP: >=7.4

Installation / Установка

ENG

Install via Composer

  • In the project folder, run the command: composer require "mnemesong/collection-generator"
  • The package will be installed to the vendor/mnemesong/collection-generator folder and will be available by namespace Mnemesong\CollectionGenerator
  • Alternatively, specify a package "mnemesong/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 "mnemesong/collection-generator"
  • Пакет установится в папку vendor/mnemesong/collection-generator и будет доступен по namespace'у Mnemesong\CollectionGenerator
  • В качестве альтернативного способа, укажите пакет "mnemesong/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