├── CHANGELOG.md ├── src ├── AutoCastingJsonResourceServiceProvider.php └── AutoCastingJsonResource.php ├── LICENSE.md ├── composer.json └── README.md /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `auto-casting-json-resource` will be documented in this file. 4 | 5 | ## First release - 2022-09-14 6 | 7 | Initial release 8 | -------------------------------------------------------------------------------- /src/AutoCastingJsonResourceServiceProvider.php: -------------------------------------------------------------------------------- 1 | name('auto-casting-json-resource'); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) oguzhankrcb 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 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "oguzhankrcb/auto-casting-json-resource", 3 | "description": "This Laravel package automatically casts your JsonResource data using the casting functions you have defined before.", 4 | "keywords": [ 5 | "oguzhankrcb", 6 | "laravel", 7 | "auto-casting-json-resource" 8 | ], 9 | "homepage": "https://github.com/oguzhankrcb/auto-casting-json-resource", 10 | "license": "MIT", 11 | "authors": [ 12 | { 13 | "name": "Oğuzhan KARACABAY", 14 | "email": "oguzhankrcb@gmail.com", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.0", 20 | "spatie/laravel-package-tools": "^1.9.2", 21 | "laravel/framework": "^8.0 || ^9.0" 22 | }, 23 | "require-dev": { 24 | "brick/money": "^0.6.0", 25 | "nunomaduro/collision": "^6.0", 26 | "orchestra/testbench": "^7.7", 27 | "phpunit/phpunit": "^9.5", 28 | "spatie/laravel-ray": "^1.26" 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "Oguzhankrcb\\AutoCastingJsonResource\\": "src" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "Tests\\": "tests/" 38 | } 39 | }, 40 | "scripts": { 41 | "test": "vendor/bin/phpunit" 42 | }, 43 | "config": { 44 | "sort-packages": true 45 | }, 46 | "extra": { 47 | "laravel": { 48 | "providers": [ 49 | "Oguzhankrcb\\AutoCastingJsonResource\\AutoCastingJsonResourceServiceProvider" 50 | ] 51 | } 52 | }, 53 | "prefer-stable": true 54 | } 55 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # This Laravel package automatically casts your JsonResource data using the casting functions you have defined before. 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/oguzhankrcb/auto-casting-json-resource.svg?style=flat-square)](https://packagist.org/packages/oguzhankrcb/auto-casting-json-resource) 4 | [![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/oguzhankrcb/auto-casting-json-resource/run-tests?label=tests)](https://github.com/oguzhankrcb/auto-casting-json-resource/actions?query=workflow%3Arun-tests+branch%3Amain) 5 | [![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/oguzhankrcb/auto-casting-json-resource/Check%20&%20fix%20styling?label=code%20style)](https://github.com/oguzhankrcb/auto-casting-json-resource/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain) 6 | 7 | This package makes easier to add global castings to your `JsonResource` files 8 | 9 | ## Installation 10 | 11 | You can install the package via composer: 12 | 13 | ```bash 14 | composer require oguzhankrcb/auto-casting-json-resource 15 | ``` 16 | 17 | ## Usage 18 | 19 | Just add this trait to your `JsonResource` 20 | ```php 21 | use AutoCastingJsonResource; 22 | ``` 23 | 24 | And then you can cast whatever you want in `casts` array 25 | 26 | ```php 27 | /** 28 | * Transform the resource into an array. 29 | * 30 | * @param \Illuminate\Http\Request $request 31 | * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable 32 | */ 33 | public function toArray($request) 34 | { 35 | return $this->autoCast(parent::toArray($request)); 36 | } 37 | 38 | public function casts(): array 39 | { 40 | return [ 41 | 'integer' => fn ($value) => (int) ($value / 100), // It will divide all integer objects with 100 42 | Money::class => fn (Money $value) => $value->getMinorAmount()->toInt() / 2, // It will cast all Brick\Money\Money objects to integer and divide them with 2 43 | ]; 44 | } 45 | ``` 46 | 47 | You can exclude columns if you want (`id` column is excluded by default) 48 | 49 | ```php 50 | public function excludedColumns(): array 51 | { 52 | return [ 53 | 'id', // id column will be excluded from castings 54 | ]; 55 | } 56 | ``` 57 | 58 | ## Testing 59 | 60 | ```bash 61 | composer test 62 | ``` 63 | 64 | ## Changelog 65 | 66 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 67 | 68 | ## Contributing 69 | 70 | Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details. 71 | 72 | ## Security Vulnerabilities 73 | 74 | Please review [our security policy](../../security/policy) on how to report security vulnerabilities. 75 | 76 | ## Credits 77 | 78 | - [Oğuzhan KARACABAY](https://github.com/oguzhankrcb) 79 | - [Emre Deligöz](https://github.com/deligoez) 80 | - [Turan Karatuğ](https://github.com/tkaratug) 81 | - [All Contributors](../../contributors) 82 | 83 | ## License 84 | 85 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 86 | -------------------------------------------------------------------------------- /src/AutoCastingJsonResource.php: -------------------------------------------------------------------------------- 1 | casts()) 41 | : array_key_exists(get_class($value), $this->casts()); 42 | } 43 | 44 | /** 45 | * @param string $valueType 46 | * @return bool 47 | */ 48 | private function isValueIsKnownType(string $valueType): bool 49 | { 50 | if (in_array($valueType, $this->getKnownTypes())) { 51 | return true; 52 | } 53 | 54 | return false; 55 | } 56 | 57 | /** 58 | * @param string $key 59 | * @param array $data 60 | * @return bool 61 | * 62 | * @see \Tests\Unit\AutoCastingJsonResourceTest::it_must_exclude_columns_in_excluded_columns_array() 63 | */ 64 | private function isKeyExcluded(string $key): bool 65 | { 66 | return in_array($key, $this->excludedColumns()); 67 | } 68 | 69 | /** 70 | * @param $key 71 | * @param $value 72 | * @param array $data 73 | * @return bool 74 | * 75 | * @see \Tests\Unit\AutoCastingJsonResourceTest::it_must_cast_object_type_values() 76 | */ 77 | private function isValueIsObjectAndInCastings($key, $value, array &$data): bool 78 | { 79 | if ( 80 | is_object($value) && 81 | $this->isValueInCastings($value, true) 82 | ) { 83 | $castingFunction = $this->casts()[get_class($value)]; 84 | $newValue = $castingFunction($value); 85 | 86 | $data[$key] = $newValue; 87 | 88 | return true; 89 | } 90 | 91 | return false; 92 | } 93 | 94 | /** 95 | * @param $key 96 | * @param $value 97 | * @param array $data 98 | * @return bool 99 | * 100 | * @see \Tests\Unit\AutoCastingJsonResourceTest::it_must_cast_known_types() 101 | */ 102 | private function isValueIsKnownTypeAndInCastings($key, $value, array &$data): bool 103 | { 104 | $valueType = gettype($value); 105 | 106 | if ($this->isValueIsKnownType($valueType) && $this->isValueInCastings($valueType)) { 107 | $castingType = $this->casts()[$valueType]; 108 | $newValue = $value; 109 | 110 | if (is_callable($castingType)) { 111 | $newValue = $castingType($newValue); 112 | } else { 113 | settype($newValue, (string) $castingType); 114 | } 115 | 116 | $data[$key] = $newValue; 117 | 118 | return true; 119 | } 120 | 121 | return false; 122 | } 123 | 124 | /** 125 | * @param $data 126 | * @return mixed 127 | */ 128 | public function autoCast($data) 129 | { 130 | foreach ($data as $key => $value) { 131 | if ( 132 | $this->isKeyExcluded($key) || 133 | $this->isValueIsObjectAndInCastings($key, $value, $data) || 134 | $this->isValueIsKnownTypeAndInCastings($key, $value, $data) 135 | ) { 136 | continue; 137 | } 138 | 139 | 140 | if (is_array($value)) { 141 | $data[$key] = $this->autoCast($value); 142 | } 143 | } 144 | 145 | return $data; 146 | } 147 | } 148 | --------------------------------------------------------------------------------