├── .editorconfig ├── .github ├── CONTRIBUTING.md ├── FUNDING.yml ├── SECURITY.md └── workflows │ ├── bc-check.yml │ ├── phpstan.yml │ ├── pint.yml │ └── run-tests.yml ├── .gitignore ├── LICENSE.md ├── README.md ├── composer.json ├── config └── loop-functions.php ├── phpstan.neon ├── phpunit.xml.dist ├── pint.json ├── src ├── LoopFunctionServiceProvider.php └── Traits │ ├── HelpsLoopFunctions.php │ ├── LoopFunctions.php │ └── WithDynamicProperties.php └── tests ├── ArrayMappingTest.php ├── AttributeMappingTest.php ├── Boilerplate ├── TestClass.php └── TestModel.php ├── DynamicPropertiesTest.php ├── LoggingTest.php ├── RecursiveArrayMappingTest.php ├── RecursiveClassDumpTest.php └── TestCase.php /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_size = 4 6 | indent_style = space 7 | end_of_line = lf 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - # **[PSR-12 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-extended-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | custom: ["https://paypal.me/observername"] 2 | -------------------------------------------------------------------------------- /.github/SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | If you discover any security related issues, please email contact@observer.name instead of using the issue tracker. 4 | -------------------------------------------------------------------------------- /.github/workflows/bc-check.yml: -------------------------------------------------------------------------------- 1 | name: bc-check 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | backwards-compatibility-check: 13 | name: Backwards Compatibility Check 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v2 17 | with: 18 | fetch-depth: 0 19 | - name: "Install PHP" 20 | uses: shivammathur/setup-php@v2 21 | with: 22 | php-version: "8.0" 23 | - name: "Install dependencies" 24 | run: "composer install" 25 | - name: "Check for BC breaks" 26 | run: "vendor/bin/roave-backward-compatibility-check --format=github-actions" 27 | -------------------------------------------------------------------------------- /.github/workflows/phpstan.yml: -------------------------------------------------------------------------------- 1 | name: phpstan 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | larastan: 11 | name: "Running Larastan check" 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@v2 18 | with: 19 | php-version: '8.0' 20 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv 21 | coverage: none 22 | 23 | - name: Cache composer dependencies 24 | uses: actions/cache@v2 25 | with: 26 | path: vendor 27 | key: composer-${{ hashFiles('composer.lock') }} 28 | 29 | - name: Run composer install 30 | run: composer install -n --prefer-dist 31 | 32 | - name: Run phpstan 33 | run: ./vendor/bin/phpstan 34 | -------------------------------------------------------------------------------- /.github/workflows/pint.yml: -------------------------------------------------------------------------------- 1 | name: "Laravel Pint" 2 | on: 3 | pull_request: 4 | types: [opened, synchronize, reopened, ready_for_review] 5 | 6 | jobs: 7 | pint: 8 | name: "Running Laravel Pint check" 9 | runs-on: ubuntu-latest 10 | if: github.event.pull_request.draft == false 11 | steps: 12 | - uses: actions/checkout@v2 13 | 14 | - name: Setup PHP 15 | uses: shivammathur/setup-php@v2 16 | with: 17 | php-version: '8.1' 18 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, intl, gd, exif, iconv 19 | coverage: none 20 | 21 | - name: Cache composer dependencies 22 | uses: actions/cache@v2 23 | with: 24 | path: vendor 25 | key: composer-${{ hashFiles('composer.lock') }} 26 | 27 | - name: Run composer install 28 | run: composer install -n --prefer-dist 29 | 30 | - name: Run Laravel Pint 31 | run: ./vendor/bin/pint --test 32 | -------------------------------------------------------------------------------- /.github/workflows/run-tests.yml: -------------------------------------------------------------------------------- 1 | name: run-tests 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | test: 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | fail-fast: true 14 | matrix: 15 | os: [ubuntu-latest, windows-latest] 16 | php: [8.0, 8.1, 8.2] 17 | laravel: [9.*, 10.*] 18 | stability: [prefer-lowest, prefer-stable] 19 | exclude: 20 | - laravel: 10.* 21 | php: 8.0 22 | 23 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} 24 | 25 | steps: 26 | - name: Checkout code 27 | uses: actions/checkout@v3 28 | 29 | - name: Setup PHP 30 | uses: shivammathur/setup-php@v2 31 | with: 32 | php-version: ${{ matrix.php }} 33 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, intl, fileinfo, sodium 34 | coverage: pcov 35 | 36 | - name: Setup problem matchers 37 | run: | 38 | echo "::add-matcher::${{ runner.tool_cache }}/php.json" 39 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" 40 | 41 | - name: Install dependencies 42 | run: | 43 | composer require "laravel/framework:${{ matrix.laravel }}" "nesbot/carbon:^2.64.1" --dev --no-interaction --no-update 44 | composer update --${{ matrix.stability }} --prefer-dist --no-interaction 45 | 46 | - name: Execute tests 47 | run: vendor/bin/phpunit --coverage-clover build/clover.xml 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .php_cs 3 | .php_cs.cache 4 | .phpunit.result.cache 5 | build 6 | composer.lock 7 | coverage 8 | docs 9 | phpunit.xml 10 | psalm.xml 11 | testbench.yaml 12 | vendor 13 | node_modules 14 | .php-cs-fixer.cache 15 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Michael Rubel 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Laravel Loop Functions](https://user-images.githubusercontent.com/37669560/197970105-a3ea9090-ebae-495b-ac13-729b0565d75a.png) 2 | 3 | # Laravel Loop Functions 4 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/michael-rubel/laravel-loop-functions.svg?style=flat-square&logo=packagist)](https://packagist.org/packages/michael-rubel/laravel-loop-functions) 5 | [![Total Downloads](https://img.shields.io/packagist/dt/michael-rubel/laravel-loop-functions.svg?style=flat-square&logo=packagist)](https://packagist.org/packages/michael-rubel/laravel-loop-functions) 6 | [![Code Quality](https://img.shields.io/scrutinizer/quality/g/michael-rubel/laravel-loop-functions.svg?style=flat-square&logo=scrutinizer)](https://scrutinizer-ci.com/g/michael-rubel/laravel-loop-functions/?branch=main) 7 | [![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/michael-rubel/laravel-loop-functions.svg?style=flat-square&logo=scrutinizer)](https://scrutinizer-ci.com/g/michael-rubel/laravel-loop-functions/?branch=main) 8 | [![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/michael-rubel/laravel-loop-functions/run-tests.yml?branch=main&style=flat-square&label=tests&logo=github)](https://github.com/michael-rubel/laravel-loop-functions/actions) 9 | [![PHPStan](https://img.shields.io/github/actions/workflow/status/michael-rubel/laravel-loop-functions/phpstan.yml?branch=main&style=flat-square&label=larastan&logo=laravel)](https://github.com/michael-rubel/laravel-loop-functions/actions) 10 | 11 | The package provides the collection of methods to loop over your data. 12 | 13 | The package requires `PHP 8` or higher and `Laravel 9` or higher. 14 | 15 | ## #StandWithUkraine 16 | [![SWUbanner](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://github.com/vshymanskyy/StandWithUkraine/blob/main/docs/README.md) 17 | 18 | ## Installation 19 | Install the package using composer: 20 | ```bash 21 | composer require michael-rubel/laravel-loop-functions 22 | ``` 23 | 24 | ## Usage 25 | ```php 26 | use LoopFunctions; 27 | ``` 28 | 29 | #### Assign Eloquent model attributes to class properties: 30 | ```php 31 | $this->propertiesFrom($model); 32 | ``` 33 | 34 | #### Assign array key values to class properties: 35 | ```php 36 | $this->propertiesFrom($array); 37 | ``` 38 | 39 | If you want to use dynamic properties, adjust the `dynamic_properties` key in the config and add the following trait if your class is not already implementing the `get/set` magic methods: 40 | ```php 41 | use WithDynamicProperties; 42 | ``` 43 | 44 | `Note: if you use the Livewire components, it already has similar definitions under the hood.` 45 | 46 | #### Dump class properties: 47 | ```php 48 | $this->dumpProperties(); 49 | ``` 50 | 51 | ## Ignored property names 52 | By default, the package ignores `id` and `password` properties to avoid conflicts in Livewire/auth components. 53 | You can customize the ignore list by editing the config. 54 | 55 | ```bash 56 | php artisan vendor:publish --tag="loop-functions-config" 57 | ``` 58 | 59 | ## Logging 60 | The functions don't throw an exception in case of failed assignment (e.g. type incompatibility) but log such an event. 61 | You can disable exception logging if you wish so in the config. 62 | 63 | ## Testing 64 | ```bash 65 | composer test 66 | ``` 67 | 68 | ## License 69 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 70 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "michael-rubel/laravel-loop-functions", 3 | "description": "Collection of functions to loop over your data.", 4 | "keywords": [ 5 | "michael-rubel", 6 | "laravel", 7 | "laravel-loop-functions" 8 | ], 9 | "homepage": "https://github.com/michael-rubel/laravel-loop-functions", 10 | "license": "MIT", 11 | "authors": [ 12 | { 13 | "name": "Michael Rubel", 14 | "email": "contact@observer.name", 15 | "role": "Maintainer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.0", 20 | "illuminate/contracts": "^9.0|^10.0", 21 | "spatie/laravel-package-tools": "^1.9" 22 | }, 23 | "require-dev": { 24 | "brianium/paratest": "^6.3", 25 | "laravel/pint": "^1.0", 26 | "mockery/mockery": "^1.4.4", 27 | "nunomaduro/collision": "^6.0", 28 | "nunomaduro/larastan": "^2.0", 29 | "orchestra/testbench": "^7.0|^8.0", 30 | "phpunit/phpunit": "^9.5", 31 | "roave/backward-compatibility-check": "^7.0|^8.0" 32 | }, 33 | "autoload": { 34 | "psr-4": { 35 | "MichaelRubel\\LoopFunctions\\": "src" 36 | } 37 | }, 38 | "autoload-dev": { 39 | "psr-4": { 40 | "MichaelRubel\\LoopFunctions\\Tests\\": "tests" 41 | } 42 | }, 43 | "scripts": { 44 | "test": "./vendor/bin/testbench package:test --no-coverage", 45 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 46 | }, 47 | "config": { 48 | "sort-packages": true 49 | }, 50 | "extra": { 51 | "laravel": { 52 | "providers": [ 53 | "MichaelRubel\\LoopFunctions\\LoopFunctionServiceProvider" 54 | ] 55 | } 56 | }, 57 | "minimum-stability": "dev", 58 | "prefer-stable": true 59 | } 60 | -------------------------------------------------------------------------------- /config/loop-functions.php: -------------------------------------------------------------------------------- 1 | true, 15 | 16 | /* 17 | | 18 | | Determine if you want to allow dynamic properties. 19 | | 20 | */ 21 | 22 | 'dynamic_properties' => true, 23 | 24 | /* 25 | | 26 | | Determine if you want to ignore some attributes. 27 | | 28 | */ 29 | 30 | 'ignore_keys' => ['id', 'password'], 31 | 32 | ]; 33 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | includes: 2 | - ./vendor/nunomaduro/larastan/extension.neon 3 | 4 | parameters: 5 | 6 | paths: 7 | - src 8 | 9 | level: max 10 | 11 | checkMissingIterableValueType: false 12 | 13 | reportUnmatchedIgnoredErrors: false 14 | 15 | checkOctaneCompatibility: true 16 | -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 21 | 22 | 23 | tests 24 | 25 | 26 | 27 | 28 | ./src 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /pint.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "laravel", 3 | "rules": { 4 | "phpdoc_separation": false, 5 | "concat_space": { 6 | "spacing": "one" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/LoopFunctionServiceProvider.php: -------------------------------------------------------------------------------- 1 | name('laravel-loop-functions') 22 | ->hasConfigFile(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Traits/HelpsLoopFunctions.php: -------------------------------------------------------------------------------- 1 | canAssignValue($key)) { 22 | rescue( 23 | fn () => $this->{$key} = $value, 24 | $rescue, 25 | config('loop-functions.log') ?? false 26 | ); 27 | } 28 | } 29 | 30 | /** 31 | * @param int|string $key 32 | * @return bool 33 | * 34 | * @throws \ReflectionException 35 | */ 36 | private function canAssignValue(int|string $key): bool 37 | { 38 | return is_string($key) 39 | && $this->checksPropertyExists($key) 40 | && (empty($this->{$key}) || $this->hasDefaultValue($key)); 41 | } 42 | 43 | /** 44 | * @param int|string $key 45 | * @return bool 46 | */ 47 | private function checksPropertyExists(int|string $key): bool 48 | { 49 | if ($this->allowsDynamicProperties()) { 50 | return true; 51 | } 52 | 53 | return property_exists($this, $key); 54 | } 55 | 56 | /** 57 | * @param int|string $key 58 | * @return bool 59 | * 60 | * @throws \ReflectionException 61 | */ 62 | private function hasDefaultValue(int|string $key): bool 63 | { 64 | $default = (new \ReflectionProperty($this, $key)) 65 | ->getDefaultValue(); 66 | 67 | return ! empty($default); 68 | } 69 | 70 | /** 71 | * @param mixed $value 72 | * @return bool 73 | */ 74 | private function canWalkRecursively(mixed $value): bool 75 | { 76 | return is_iterable($value); 77 | } 78 | 79 | /** 80 | * @return bool 81 | */ 82 | private function allowsDynamicProperties(): bool 83 | { 84 | return config('loop-functions.dynamic_properties', true); 85 | } 86 | 87 | /** 88 | * @return array 89 | */ 90 | private function ignoredPropertyNames(): array 91 | { 92 | return config('loop-functions.ignore_keys', ['id', 'password']); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/Traits/LoopFunctions.php: -------------------------------------------------------------------------------- 1 | $this->attributesToProperties($data, $rescue), 26 | default => $this->arrayToProperties($data, $rescue), 27 | }; 28 | } 29 | } 30 | 31 | /** 32 | * Maps your model attributes to local class properties. 33 | * 34 | * @param Model|null $model 35 | * @param mixed $rescue 36 | * @return void 37 | */ 38 | public function attributesToProperties(?Model $model = null, mixed $rescue = null): void 39 | { 40 | collect($model?->getAttributes()) 41 | ->except($this->ignoredPropertyNames()) 42 | ->each( 43 | fn ($value, $property) => $this->assignValue( 44 | $property, 45 | $model->{$property}, 46 | $rescue 47 | ) 48 | ); 49 | } 50 | 51 | /** 52 | * Map array data to class properties. 53 | * 54 | * @param array|\ArrayAccess|null $data 55 | * @param mixed|null $rescue 56 | * @return void 57 | */ 58 | public function arrayToProperties(array|\ArrayAccess|null $data, mixed $rescue = null): void 59 | { 60 | collect($data ?? []) 61 | ->except($this->ignoredPropertyNames()) 62 | ->each(function ($value, $key) use ($rescue) { 63 | $this->assignValue($key, $value, $rescue); 64 | 65 | if ($this->canWalkRecursively($value)) { 66 | $this->propertiesFrom($value, $rescue); 67 | } 68 | }); 69 | } 70 | 71 | /** 72 | * Dump class properties as key-valued array. 73 | * 74 | * @param string|object|null $class 75 | * @param int|null $filter 76 | * @param bool $asCollection 77 | * @return array|Collection 78 | * 79 | * @throws \ReflectionException 80 | */ 81 | public function dumpProperties( 82 | string|object|null $class = null, 83 | bool $asCollection = false, 84 | ?int $filter = null, 85 | ): array|Collection { 86 | $class = match (true) { 87 | is_string($class) => app($class), 88 | is_object($class) => $class, 89 | default => $this, 90 | }; 91 | 92 | $properties = (new \ReflectionClass($class)) 93 | ->getProperties($filter); 94 | 95 | $collection = collect($properties)->mapWithKeys( 96 | function (\ReflectionProperty $property) use ($class) { 97 | $property->setAccessible(true); 98 | 99 | return [$property->getName() => $property->getValue($class)]; 100 | } 101 | ); 102 | 103 | return ! $asCollection 104 | ? $collection->all() 105 | : $collection; 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/Traits/WithDynamicProperties.php: -------------------------------------------------------------------------------- 1 | {$name}; 14 | } 15 | 16 | /** 17 | * @param string $name 18 | * @param mixed $value 19 | * @return void 20 | */ 21 | public function __set(string $name, mixed $value): void 22 | { 23 | $this->{$name} = $value; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/ArrayMappingTest.php: -------------------------------------------------------------------------------- 1 | test); 32 | unset($this->name); 33 | unset($this->additional_data); 34 | unset($this->array); 35 | unset($this->supportCollection); 36 | unset($this->eloquentCollection); 37 | } 38 | 39 | /** @test */ 40 | public function testCanMapAnArrayToProperties() 41 | { 42 | $array = [ 43 | 'test' => true, 44 | 'name' => 'Michael Rubel', 45 | 'password' => 'p@$$w0rd', 46 | ]; 47 | 48 | $this->arrayToProperties($array); 49 | 50 | $this->assertTrue($this->test); 51 | $this->assertStringContainsString('Michael', $this->name); 52 | $this->assertNull($this->password); 53 | } 54 | 55 | /** @test */ 56 | public function testCanMapAnArray() 57 | { 58 | $array = [ 59 | 'test' => true, 60 | 'name' => 'Michael Rubel', 61 | 'password' => 'p@$$w0rd', 62 | 'additional_data' => [ 63 | 'next' => 'test', 64 | ], 65 | ]; 66 | 67 | $this->arrayToProperties($array); 68 | 69 | $this->assertTrue($this->test); 70 | $this->assertStringContainsString('Michael', $this->name); 71 | $this->assertNull($this->password); 72 | $this->assertArrayHasKey('next', $this->additional_data); 73 | } 74 | 75 | /** @test */ 76 | public function testAlreadyInitializedPropertiesArentOverridenByNestedArrays() 77 | { 78 | $array = [ 79 | 'name' => 'Michael Rubel', 80 | 'additional_data' => [ 81 | 'name' => 'test', 82 | ], 83 | ]; 84 | 85 | $this->arrayToProperties($array); 86 | 87 | $this->assertStringContainsString('Michael', $this->name); 88 | } 89 | 90 | /** @test */ 91 | public function testArrayIsAssignedAsIs() 92 | { 93 | $array = [ 94 | 'name' => 'Michael Rubel', 95 | 'array' => [ 96 | 'test' => true, 97 | ], 98 | ]; 99 | 100 | $this->arrayToProperties($array); 101 | 102 | $this->assertStringContainsString('Michael', $this->name); 103 | $this->assertArrayHasKey('test', $this->array); 104 | $this->assertTrue($this->array['test']); 105 | } 106 | 107 | /** @test */ 108 | public function testCollectionAssignmentIsOk() 109 | { 110 | $array = [ 111 | 'supportCollection' => collect([ 112 | 'test' => true, 113 | ]), 114 | 'eloquentCollection' => new EloquentCollection(), 115 | ]; 116 | 117 | $this->arrayToProperties($array); 118 | 119 | $this->assertArrayHasKey('test', $this->supportCollection->toArray()); 120 | $this->assertTrue($this->supportCollection->toArray()['test']); 121 | } 122 | 123 | /** @test */ 124 | public function testCanMapUsingPropertiesFrom() 125 | { 126 | $array = [ 127 | 'test' => true, 128 | 'additional_data' => [ 129 | 'next' => [ 130 | 'test' => true, 131 | ], 132 | ], 133 | ]; 134 | 135 | $this->propertiesFrom($array); 136 | 137 | $this->assertArrayHasKey('next', $this->additional_data); 138 | 139 | $this->propertiesFrom(null); 140 | 141 | $this->assertArrayHasKey('next', $this->additional_data); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /tests/AttributeMappingTest.php: -------------------------------------------------------------------------------- 1 | 1, 34 | 'test' => true, 35 | 'name' => 'mapped', 36 | 'files' => collect('/img/src/screen.png'), 37 | ]); 38 | 39 | $this->attributesToProperties($model); 40 | 41 | $this->assertTrue($this->test); 42 | $this->assertIsString($this->name); 43 | $this->assertStringContainsString('mapped', $this->name); 44 | $this->assertInstanceOf(Collection::class, $this->files); 45 | } 46 | 47 | /** @test */ 48 | public function testMappingIgnoresDifferentTypes() 49 | { 50 | $model = new TestModel([ 51 | 'id' => 1, 52 | 'test' => true, 53 | 'name' => 100.1, 54 | 'files' => null, 55 | 'default' => fn () => true, 56 | ]); 57 | 58 | $this->attributesToProperties($model); 59 | 60 | $this->assertFalse(isset($this->name)); 61 | $this->assertFalse(isset($this->files)); 62 | 63 | $this->assertInstanceOf(\Closure::class, $this->default); 64 | $this->assertTrue(($this->default)()); 65 | } 66 | 67 | /** @test */ 68 | public function testMappingWorksWithCollections() 69 | { 70 | $model = new TestModel([ 71 | 'id' => 1, 72 | 'collection' => new Collection(), 73 | ]); 74 | 75 | $this->attributesToProperties($model); 76 | 77 | $this->assertInstanceOf(Collection::class, $this->collection); 78 | } 79 | 80 | /** @test */ 81 | public function testMappingWithCasts() 82 | { 83 | $model = new TestModel([ 84 | 'collection' => [ 85 | 0 => true, 86 | 1 => false, 87 | ], 88 | 'intAsString' => 100, 89 | ]); 90 | 91 | $this->attributesToProperties($model); 92 | 93 | $this->assertInstanceOf(Collection::class, $this->collection); 94 | $this->assertIsString($this->intAsString); 95 | } 96 | 97 | /** @test */ 98 | public function testIdAndPasswordIsIgnored() 99 | { 100 | $model = new TestModel([ 101 | 'id' => 1, 102 | 'password' => 'hash', 103 | 'test' => true, 104 | ]); 105 | 106 | $this->attributesToProperties($model); 107 | 108 | $this->assertTrue($this->test); 109 | $this->assertFalse((new \ReflectionProperty($this, 'id'))->isInitialized($this)); 110 | $this->assertFalse((new \ReflectionProperty($this, 'password'))->isInitialized($this)); 111 | } 112 | 113 | /** @test */ 114 | public function testSetsDefaultValueWithWrongConfig() 115 | { 116 | config(['loop-functions.ignore_attributes' => 123]); 117 | 118 | $model = new TestModel([ 119 | 'id' => 1, 120 | 'password' => 'hash', 121 | 'test' => true, 122 | ]); 123 | 124 | $this->attributesToProperties($model); 125 | 126 | $this->assertTrue($this->test); 127 | $this->assertFalse((new \ReflectionProperty($this, 'id'))->isInitialized($this)); 128 | $this->assertFalse((new \ReflectionProperty($this, 'password'))->isInitialized($this)); 129 | } 130 | 131 | /** @test */ 132 | public function testCanMapUsingPropertiesFrom() 133 | { 134 | $model = new TestModel([ 135 | 'collection' => [ 136 | 0 => true, 137 | 1 => false, 138 | ], 139 | 'intAsString' => 100, 140 | ]); 141 | 142 | $this->propertiesFrom($model); 143 | 144 | $this->assertInstanceOf(Collection::class, $this->collection); 145 | $this->assertIsString($this->intAsString); 146 | 147 | $this->propertiesFrom(null); 148 | 149 | $this->assertInstanceOf(Collection::class, $this->collection); 150 | $this->assertIsString($this->intAsString); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /tests/Boilerplate/TestClass.php: -------------------------------------------------------------------------------- 1 | false]; 31 | 32 | protected static string|array|null $static_union_type = 'test'; 33 | 34 | public function __construct() 35 | { 36 | $this->bool = true; 37 | $this->string = 'new string'; 38 | $this->nullable_string = null; 39 | $this->array = ['array' => true]; 40 | $this->nullable_array = null; 41 | $this->collection = new Collection; 42 | $this->nullable_collection = null; 43 | $this->union_type = ['test' => true]; 44 | 45 | self::$static = ['static' => true]; 46 | self::$nullable_static_array = null; 47 | self::$static_union_type = ['test' => true]; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/Boilerplate/TestModel.php: -------------------------------------------------------------------------------- 1 | AsCollection::class, 20 | 'intAsString' => 'string', 21 | ]; 22 | } 23 | -------------------------------------------------------------------------------- /tests/DynamicPropertiesTest.php: -------------------------------------------------------------------------------- 1 | true]); 16 | 17 | $array = [ 18 | 'test' => true, 19 | ]; 20 | 21 | $this->propertiesFrom($array); 22 | 23 | $this->assertTrue($this->test); 24 | } 25 | 26 | /** @test */ 27 | public function testDynamicPropertiesDisabled() 28 | { 29 | config(['loop-functions.dynamic_properties' => false]); 30 | 31 | $this->expectException(\ErrorException::class); 32 | 33 | $array = [ 34 | 'test' => true, 35 | ]; 36 | 37 | $this->propertiesFrom($array); 38 | 39 | $this->assertFalse($this->test); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/LoggingTest.php: -------------------------------------------------------------------------------- 1 | once() 20 | ->withArgs(function ($message) { 21 | return str_contains($message, 'Cannot assign'); 22 | }); 23 | 24 | $model = new TestModel([ 25 | 'number' => false, 26 | ]); 27 | 28 | $this->attributesToProperties($model); 29 | } 30 | 31 | /** @test */ 32 | public function testMapperDoesntLogIfDisabled() 33 | { 34 | config(['loop-functions.log' => false]); 35 | 36 | Log::shouldReceive('error')->never(); 37 | 38 | $model = new TestModel([ 39 | 'number' => false, 40 | ]); 41 | 42 | $this->attributesToProperties($model); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/RecursiveArrayMappingTest.php: -------------------------------------------------------------------------------- 1 | collect([ 31 | 'first_name' => 'Michael', 32 | 'last_name' => 'Rubel', 33 | ]), 34 | 'last_name' => 'Rubel', 35 | 'array' => [ 36 | 'test' => true, 37 | 'full_name' => 'Michael Rubel', 38 | 'first_name' => 'Tester', 39 | 'last_name' => 'Field', 40 | 'nice' => 'yes', 41 | ], 42 | 'nice' => 'yes', 43 | ]; 44 | 45 | $this->propertiesFrom($data); 46 | 47 | $this->assertTrue($this->test); 48 | $this->assertArrayHasKey('test', $this->array); 49 | $this->assertArrayHasKey('first_name', $this->collection); 50 | $this->assertStringContainsString('Michael', $this->first_name); 51 | $this->assertStringContainsString('Rubel', $this->last_name); 52 | $this->assertStringContainsString('Michael Rubel', $this->full_name); 53 | $this->assertStringContainsString('yes', $this->nice); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /tests/RecursiveClassDumpTest.php: -------------------------------------------------------------------------------- 1 | dumpProperties(); 14 | 15 | $this->assertTrue($properties['bool']); 16 | $this->assertStringContainsString('new string', $properties['string']); 17 | $this->assertArrayHasKey('array', $properties['array']); 18 | $this->assertTrue($properties['collection']->isEmpty()); 19 | $this->assertArrayHasKey('static', $properties['static']); 20 | $this->assertArrayHasKey('test', $properties['union_type']); 21 | $this->assertArrayHasKey('test', $properties['static_union_type']); 22 | 23 | $this->assertNull($properties['nullable_string']); 24 | $this->assertNull($properties['nullable_array']); 25 | $this->assertNull($properties['nullable_collection']); 26 | $this->assertNull($properties['nullable_static_array']); 27 | } 28 | 29 | /** @test */ 30 | public function testCanDumpPassedObjectProperties() 31 | { 32 | $properties = app(TestClass::class)->dumpProperties(Collection::class); 33 | 34 | $this->assertArrayHasKey('items', $properties); 35 | $this->assertArrayHasKey('escapeWhenCastingToString', $properties); 36 | $this->assertFalse($properties['escapeWhenCastingToString']); 37 | } 38 | 39 | /** @test */ 40 | public function testCanDumpAsCollection() 41 | { 42 | $properties = app(TestClass::class)->dumpProperties( 43 | class: Collection::class, 44 | asCollection: true, 45 | ); 46 | 47 | $this->assertInstanceOf(Collection::class, $properties); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | set('testing'); 25 | } 26 | } 27 | --------------------------------------------------------------------------------