This commit is contained in:
2022-02-05 07:43:27 +00:00
committed by Gitea
parent db19655b60
commit 944c4cb564
34 changed files with 1936 additions and 8 deletions
+2 -1
View File
@@ -29,7 +29,8 @@
"erusev/parsedown-extra": "^0.8.1",
"nette/caching": "^3.0",
"illuminate/database": "^8.61",
"illuminate/events": "^8.61"
"illuminate/events": "^8.61",
"spatie/data-transfer-object": "^3.7"
},
"autoload": {
"psr-4": {
Generated
+64 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "94cfbcb22b9f475e421ad5009391006f",
"content-hash": "1983b89436fd8017db508592ddf542e4",
"packages": [
{
"name": "brandonwamboldt/utilphp",
@@ -2636,6 +2636,69 @@
},
"time": "2021-06-29T04:31:23+00:00"
},
{
"name": "spatie/data-transfer-object",
"version": "3.7.3",
"source": {
"type": "git",
"url": "https://github.com/spatie/data-transfer-object.git",
"reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
"reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
"shasum": ""
},
"require": {
"php": "^8.0"
},
"require-dev": {
"illuminate/collections": "^8.36",
"jetbrains/phpstorm-attributes": "^1.0",
"larapack/dd": "^1.1",
"phpunit/phpunit": "^9.0"
},
"type": "library",
"autoload": {
"psr-4": {
"Spatie\\DataTransferObject\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brent Roose",
"email": "brent@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Data transfer objects with batteries included",
"homepage": "https://github.com/spatie/data-transfer-object",
"keywords": [
"data-transfer-object",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/data-transfer-object/issues",
"source": "https://github.com/spatie/data-transfer-object/tree/3.7.3"
},
"funding": [
{
"url": "https://spatie.be/open-source/support-us",
"type": "custom"
},
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"time": "2021-12-30T20:31:10+00:00"
},
{
"name": "symfony/console",
"version": "v5.3.10",
+11 -2
View File
@@ -29,7 +29,7 @@ private static $installed = array (
'aliases' =>
array (
),
'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
'name' => 'sammo-hid/sammo',
),
'versions' =>
@@ -450,7 +450,7 @@ private static $installed = array (
'aliases' =>
array (
),
'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
),
'sergeytsalkov/meekrodb' =>
array (
@@ -461,6 +461,15 @@ private static $installed = array (
),
'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5',
),
'spatie/data-transfer-object' =>
array (
'pretty_version' => '3.7.3',
'version' => '3.7.3.0',
'aliases' =>
array (
),
'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72',
),
'symfony/console' =>
array (
'pretty_version' => 'v5.3.10',
+1
View File
@@ -27,6 +27,7 @@ return array(
'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'),
'Symfony\\Component\\Lock\\' => array($vendorDir . '/symfony/lock'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Spatie\\DataTransferObject\\' => array($vendorDir . '/spatie/data-transfer-object/src'),
'Sabre\\Event\\' => array($vendorDir . '/sabre/event/lib'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
+5
View File
@@ -76,6 +76,7 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a
'Symfony\\Component\\String\\' => 25,
'Symfony\\Component\\Lock\\' => 23,
'Symfony\\Component\\Console\\' => 26,
'Spatie\\DataTransferObject\\' => 26,
'Sabre\\Event\\' => 12,
),
'P' =>
@@ -217,6 +218,10 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a
array (
0 => __DIR__ . '/..' . '/symfony/console',
),
'Spatie\\DataTransferObject\\' =>
array (
0 => __DIR__ . '/..' . '/spatie/data-transfer-object/src',
),
'Sabre\\Event\\' =>
array (
0 => __DIR__ . '/..' . '/sabre/event/lib',
+66
View File
@@ -2722,6 +2722,72 @@
},
"install-path": "../sergeytsalkov/meekrodb"
},
{
"name": "spatie/data-transfer-object",
"version": "3.7.3",
"version_normalized": "3.7.3.0",
"source": {
"type": "git",
"url": "https://github.com/spatie/data-transfer-object.git",
"reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
"reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72",
"shasum": ""
},
"require": {
"php": "^8.0"
},
"require-dev": {
"illuminate/collections": "^8.36",
"jetbrains/phpstorm-attributes": "^1.0",
"larapack/dd": "^1.1",
"phpunit/phpunit": "^9.0"
},
"time": "2021-12-30T20:31:10+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Spatie\\DataTransferObject\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brent Roose",
"email": "brent@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"description": "Data transfer objects with batteries included",
"homepage": "https://github.com/spatie/data-transfer-object",
"keywords": [
"data-transfer-object",
"spatie"
],
"support": {
"issues": "https://github.com/spatie/data-transfer-object/issues",
"source": "https://github.com/spatie/data-transfer-object/tree/3.7.3"
},
"funding": [
{
"url": "https://spatie.be/open-source/support-us",
"type": "custom"
},
{
"url": "https://github.com/spatie",
"type": "github"
}
],
"install-path": "../spatie/data-transfer-object"
},
{
"name": "symfony/console",
"version": "v5.3.10",
+11 -2
View File
@@ -6,7 +6,7 @@
'aliases' =>
array (
),
'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
'name' => 'sammo-hid/sammo',
),
'versions' =>
@@ -427,7 +427,7 @@
'aliases' =>
array (
),
'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6',
'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd',
),
'sergeytsalkov/meekrodb' =>
array (
@@ -438,6 +438,15 @@
),
'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5',
),
'spatie/data-transfer-object' =>
array (
'pretty_version' => '3.7.3',
'version' => '3.7.3.0',
'aliases' =>
array (
),
'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72',
),
'symfony/console' =>
array (
'pretty_version' => 'v5.3.10',
+2 -2
View File
@@ -4,8 +4,8 @@
$issues = array();
if (!(PHP_VERSION_ID >= 70400)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.';
if (!(PHP_VERSION_ID >= 80000)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
@@ -0,0 +1,55 @@
# Contributing
Contributions are **welcome** and will be fully **credited**.
Please read and understand the contribution guide before creating an issue or pull request.
## Etiquette
This project is open source, and as such, the maintainers give their free time to build and maintain the source code
held within. They make the code freely available in the hope that it will be of use to other developers. It would be
extremely unfair for them to suffer abuse or anger for their hard work.
Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
world that developers are civilized and selfless people.
It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
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.
## Viability
When requesting or submitting new features, first consider whether it might be useful to others. Open
source projects are used by many developers, who may have entirely different needs to your own. Think about
whether or not your feature is likely to be used by other users of the project.
## Procedure
Before filing an issue:
- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
- Check to make sure your feature suggestion isn't already present within the project.
- Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
- Check the pull requests tab to ensure that the feature isn't already in progress.
Before submitting a pull request:
- Check the codebase to ensure that your feature doesn't already exist.
- Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
## Requirements
If the project maintainer has any additional requirements, you will find them listed here.
- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
- **Add tests!** - Your patch won't be accepted if it doesn't have tests.
- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
- **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.
**Happy coding**!
@@ -0,0 +1,2 @@
github: spatie
custom: https://spatie.be/open-source/support-us
@@ -0,0 +1,23 @@
name: Check & fix styling
on: [push]
jobs:
php-cs-fixer:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
ref: ${{ github.head_ref }}
- name: Run PHP CS Fixer
uses: docker://oskarstark/php-cs-fixer-ga
with:
args: --config=.php-cs-fixer.dist.php --allow-risky=yes
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: Fix styling
@@ -0,0 +1,28 @@
name: "Update Changelog"
on:
release:
types: [released]
jobs:
update:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
ref: main
- name: Update Changelog
uses: stefanzweifel/changelog-updater-action@v1
with:
latest-version: ${{ github.event.release.name }}
release-notes: ${{ github.event.release.body }}
- name: Commit updated CHANGELOG
uses: stefanzweifel/git-auto-commit-action@v4
with:
branch: main
commit_message: Update CHANGELOG
file_pattern: CHANGELOG.md
@@ -0,0 +1,41 @@
<?php
$finder = Symfony\Component\Finder\Finder::create()
->notPath('docs/*')
->notPath('vendor')
->in([
__DIR__.'/src',
__DIR__.'/tests',
])
->name('*.php')
->ignoreDotFiles(true)
->ignoreVCS(true);
return (new PhpCsFixer\Config())
->setRules([
'@PSR12' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sort_algorithm' => 'alpha'],
'no_unused_imports' => true,
'not_operator_with_successor_space' => true,
'trailing_comma_in_multiline' => true,
'phpdoc_scalar' => true,
'unary_operator_spaces' => true,
'binary_operator_spaces' => true,
'logical_operators' => true,
'blank_line_before_statement' => [
'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'],
],
'phpdoc_single_line_var_spacing' => true,
'phpdoc_var_without_name' => true,
'class_attributes_separation' => [
'elements' => [
'method' => 'one'
],
],
'method_argument_space' => [
'on_multiline' => 'ensure_fully_multiline',
'keep_multiple_spaces_after_comma' => true,
],
])
->setFinder($finder);
+248
View File
@@ -0,0 +1,248 @@
# Changelog
All notable changes to `data-transfer-object` will be documented in this file
## 3.7.2 - 2021-09-17
- `#[Strict]` is passed down the inheritance chain so children are strict when parent is strict (#239)
## 3.7.1 - 2021-09-09
- Cast properties with self or parent type (#236)
## 3.7.0 - 2021-08-26
- Add `#[MapTo]` support (#233)
## 3.6.2 - 2021-08-25
- Correct behavior of Arr::forget with dot keys (#231)
## 3.6.1 - 2021-08-17
- Fix array assignment bug with strict dto's (#225)
## 3.6.0 - 2021-08-12
- Support mapped properties (#224)
## 3.5.0 - 2021-08-11
- Support union types in casters (#210)
## 3.4.0 - 2021-08-10
- Fix for an empty value being created when casting `ArrayAccess` objects (#216)
- Add logic exception when attempting to cast `ArrayAccess` objects that are not traversable (#216)
- Allow the `ArrayCaster` to retain values that are already instances of the `itemType` (#217)
## 3.3.0 - 2021-06-01
- Expose DTO and validation error array in ValidationException (#213)
## 3.2.0 - 2021-05-31
- Support generic casters (#199)
- Add `ArrayCaster`
- Add casting of objects that implement `ArrayAccess` to the `ArrayCaster` (#206)
- Fix for caster subclass check (#204)
## 3.1.1 - 2021-04-26
- Make `DefaultCast` repeatable (#202)
## 3.1.0 - 2021-04-21
- Add `DataTransferObject::clone(...$args)`
## 3.0.4 - 2021-04-14
- Support union types (#185)
- Resolve default cast from parent classes (#189)
- Support default values (#191)
## 3.0.3 - 2021-04-08
- Fix when nested DTO have casted field (#178)
## 3.0.2 - 2021-04-02
- Allow valid DTOs to be passed to caster (#177)
## 3.0.1 - 2021-04-02
- Fix for null values with casters
## 3.0.0 - 2021-04-02
This package now focuses only on object creation by adding easy-to-use casting and data validation functionality. All runtime type checks are gone in favour of the improved type system in PHP 8.
- Require `php:^8.0`
- Removed all runtime type checking functionality, you should use typed properties and a static analysis tool like Psalm or PhpStan
- Removed `Spatie\DataTransferObject\DataTransferObjectCollection`
- Removed `Spatie\DataTransferObject\FlexibleDataTransferObject`, all DTOs are now considered flexible
- Removed runtime immutable DTOs, you should use static analysis instead
- Added `Spatie\DataTransferObject\Validator`
- Added `Spatie\DataTransferObject\Validation\ValidationResult`
- Added `#[DefaultCast]`
- Added `#[CastWith]`
- Added `Spatie\DataTransferObject\Caster`
- Added `#[Strict]`
## 2.8.3 - 2021-02-12
- Add support for using `collection` internally
## 2.8.2 - 2021-02-11
This might be a breaking change, but it was required for a bugfix
- Prevent DataTransferObjectCollection from iterating over array copy (#166)
## 2.8.1 - 2021-02-10
- Fix for incorrect return type (#164)
## 2.8.0 - 2021-01-27
- Allow the traversal of collections with string keys
## 2.7.0 - 2021-01-21
- Cast nested collections (#117)
## 2.6.0 - 2020-11-26
- Support PHP 8
## 2.5.0 - 2020-08-28
- Group type errors (#130)
## 2.4.0 - 2020-08-28
- Support for `array<int, string>` syntax (#136)
## 2.3.0 - 2020-08-19
- Add PHPStan extension to support `checkUninitializedProperties: true` (#135)
## 2.2.1 - 2020-05-13
- Validator for typed 7.4 properties (#109)
## 2.2.0 - 2020-05-08
- Add support for typed properties to DTO casting in PHP 7.4
## 2.0.0 - 2020-04-28
- Bump minimum required PHP version to 7.4
- Support for nested immutable DTOs (#86)
## 1.13.3 - 2020-01-29
- Ignore static properties when serializing (#88)
## 1.13.2 - 2020-01-08
- DataTransferObjectError::invalidType : get actual type before mutating $value for the error message (#81)
## 1.13.1 - 2020-01-08
- Improve extendability of DTOs (#80)
## 1.13.0 - 2020-01-08
- Ignore static properties (#82)
- Add `DataTransferObject::arrayOf` (#83)
## 1.12.0 - 2019-12-19
- Improved performance by adding a cache (#79)
- Add `FlexibleDataTransferObject` which allows for unknown properties to be ignored
## 1.11.0 - 2019-11-28 (#71)
- Add `iterable` and `iterable<\Type>` support
## 1.10.0 - 2019-10-16
- Allow a DTO to be constructed without an array (#68)
## 1.9.1 - 2019-10-03
- Improve type error message
## 1.9.0 - 2019-08-30
- Add DataTransferObjectCollection::items()
## 1.8.0 - 2019-03-18
- Support immutability
## 1.7.1 - 2019-02-11
- Fixes #47, allowing empty dto's to be cast to using an empty array.
## 1.7.0 - 2019-02-04
- Nested array DTO casting supported.
## 1.6.6 - 2018-12-04
- Properly support `float`.
## 1.6.5 - 2018-11-20
- Fix uninitialised error with default value.
## 1.6.4 - 2018-11-15
- Don't use `allValues` anymore.
## 1.6.3 - 2018-11-14
- Support nested collections in collections
- Cleanup code
## 1.6.2 - 2018-11-14
- Remove too much magic in nested array casting
## 1.6.1 - 2018-11-14
- Support nested `toArray` in collections.
## 1.6.0 - 2018-11-14
- Support nested `toArray`.
## 1.5.1 - 2018-11-07
- Add strict type declarations
## 1.5.0 - 2018-11-07
- Add auto casting of nested DTOs
## 1.4.0 - 2018-11-05
- Rename to data-transfer-object
## 1.2.0 - 2018-10-30
- Add uninitialized errors.
## 1.1.1 - 2018-10-25
- Support instanceof on interfaces when type checking
## 1.1.0 - 2018-10-24
- proper support for collections of value objects
## 1.0.0 - 2018-10-24
- initial release
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+504
View File
@@ -0,0 +1,504 @@
# Data transfer objects with batteries included
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/spatie/data-transfer-object)
![Test](https://github.com/spatie/data-transfer-object/workflows/Test/badge.svg)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/spatie/data-transfer-object)
## Installation
You can install the package via composer:
```bash
composer require spatie/data-transfer-object
```
* **Note**: v3 of this package only supports `php:^8.0`. If you're looking for the older version, check out [v2](https://github.com/spatie/data-transfer-object/tree/v2).
## Support us
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/data-transfer-object.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/data-transfer-object)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Usage
The goal of this package is to make constructing objects from arrays of (serialized) data as easy as possible. Here's what a DTO looks like:
```php
use Spatie\DataTransferObject\DataTransferObject;
class MyDTO extends DataTransferObject
{
public OtherDTO $otherDTO;
public OtherDTOCollection $collection;
#[CastWith(ComplexObjectCaster::class)]
public ComplexObject $complexObject;
public ComplexObjectWithCast $complexObjectWithCast;
#[NumberBetween(1, 100)]
public int $a;
#[MapFrom('address.city')]
public string $city;
}
```
You could construct this DTO like so:
```php
$dto = new MyDTO(
a: 5,
collection: [
['id' => 1],
['id' => 2],
['id' => 3],
],
complexObject: [
'name' => 'test',
],
complexObjectWithCast: [
'name' => 'test',
],
otherDTO: ['id' => 5],
);
```
Let's discuss all possibilities one by one.
## Named arguments
Constructing a DTO can be done with named arguments. It's also possible to still use the old array notation. This example is equivalent to the one above.
```php
$dto = new MyDTO([
'a' => 5,
'collection' => [
['id' => 1],
['id' => 2],
['id' => 3],
],
'complexObject' => [
'name' => 'test',
],
'complexObjectWithCast' => [
'name' => 'test',
],
'otherDTO' => ['id' => 5],
]);
```
## Value casts
If a DTO has a property that is another DTO or a DTO collection, the package will take care of automatically casting arrays of data to those DTOs:
```php
$dto = new MyDTO(
collection: [ // This will become an object of class OtherDTOCollection
['id' => 1],
['id' => 2], // Each item will be an instance of OtherDTO
['id' => 3],
],
otherDTO: ['id' => 5], // This data will be cast to OtherDTO
);
```
### Custom casters
You can build your own caster classes, which will take whatever input they are given, and will cast that input to the desired result.
Take a look at the `ComplexObject`:
```php
class ComplexObject
{
public string $name;
}
```
And its caster `ComplexObjectCaster`:
```php
use Spatie\DataTransferObject\Caster;
class ComplexObjectCaster implements Caster
{
/**
* @param array|mixed $value
*
* @return mixed
*/
public function cast(mixed $value): ComplexObject
{
return new ComplexObject(
name: $value['name']
);
}
}
```
### Class-specific casters
Instead of specifying which caster should be used for each property, you can also define that caster on the target class itself:
```php
class MyDTO extends DataTransferObject
{
public ComplexObjectWithCast $complexObjectWithCast;
}
```
```php
#[CastWith(ComplexObjectWithCastCaster::class)]
class ComplexObjectWithCast
{
public string $name;
}
```
### Default casters
It's possible to define default casters on a DTO class itself. These casters will be used whenever a property with a given type is encountered within the DTO class.
```php
#[
DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class),
DefaultCast(MyEnum::class, EnumCaster::class),
]
abstract class BaseDataTransferObject extends DataTransferObject
{
public MyEnum $status; // EnumCaster will be used
public DateTimeImmutable $date; // DateTimeImmutableCaster will be used
}
```
### Using custom caster arguments
Any caster can be passed custom arguments, the built-in [`ArrayCaster` implementation](https://github.com/spatie/data-transfer-object/blob/master/src/Casters/ArrayCaster.php) is a good example of how this may be used.
Using named arguments when passing input to your caster will help make your code more clear, but they are not required.
For example:
```php
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, itemType: Foo::class)]
public array $collectionWithNamedArguments;
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, Foo::class)]
public array $collectionWithoutNamedArguments;
```
Note that the first argument passed to the caster constructor is always the array with type(s) of the value being casted.
All other arguments will be the ones passed as extra arguments in the `CastWith` attribute.
## Validation
This package doesn't offer any specific validation functionality, but it does give you a way to build your own validation attributes. For example, `NumberBetween` is a user-implemented validation attribute:
```php
class MyDTO extends DataTransferObject
{
#[NumberBetween(1, 100)]
public int $a;
}
```
It works like this under the hood:
```php
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
class NumberBetween implements Validator
{
public function __construct(
private int $min,
private int $max
) {
}
public function validate(mixed $value): ValidationResult
{
if ($value < $this->min) {
return ValidationResult::invalid("Value should be greater than or equal to {$this->min}");
}
if ($value > $this->max) {
return ValidationResult::invalid("Value should be less than or equal to {$this->max}");
}
return ValidationResult::valid();
}
}
```
## Mapping
You can map a DTO property from a source property with a different name using the `#[MapFrom]` attribute.
It works with a "dot" notation property name or an index.
```php
class PostDTO extends DataTransferObject
{
#[MapFrom('postTitle')]
public string $title;
#[MapFrom('user.name')]
public string $author;
}
$dto = new PostDTO([
'postTitle' => 'Hello world',
'user' => [
'name' => 'John Doe'
]
]);
```
```php
class UserDTO extends DataTransferObject
{
#[MapFrom(0)]
public string $firstName;
#[MapFrom(1)]
public string $lastName;
}
$dto = new UserDTO(['John', 'Doe']);
```
Sometimes you also want to map them during the transformation to Array.
A typical usecase would be transformation from camel case to snake case.
For that you can use the `#[MapTo]` attribute.
```php
class UserDTO extends DataTransferObject
{
#[MapFrom(0)]
#[MapTo('first_name')]
public string $firstName;
#[MapFrom(1)]
#[MapTo('last_name')]
public string $lastName;
}
$dto = new UserDTO(['John', 'Doe']);
$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe'];
$dto->only('first_name')->toArray() // ['first_name' => 'John'];
```
## Strict DTOs
The previous version of this package added the `FlexibleDataTransferObject` class which allowed you to ignore properties that didn't exist on the DTO. This behaviour has been changed, all DTOs are flexible now by default, but you can make them strict by using the `#[Strict]` attribute:
```php
class NonStrictDto extends DataTransferObject
{
public string $name;
}
// This works
new NonStrictDto(
name: 'name',
unknown: 'unknown'
);
```
```php
use \Spatie\DataTransferObject\Attributes\Strict;
#[Strict]
class StrictDto extends DataTransferObject
{
public string $name;
}
// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception
new StrictDto(
name: 'name',
unknown: 'unknown'
);
```
## Helper functions
There are also some helper functions provided for working with multiple properties at once.
```php
$postData->all();
$postData
->only('title', 'body')
->toArray();
$postData
->except('author')
->toArray();
```
Note that `all()` will simply return all properties, while `toArray()` will cast nested DTOs to arrays as well.
You can chain the `except()` and `only()` methods:
```php
$postData
->except('title')
->except('body')
->toArray();
```
It's important to note that `except()` and `only()` are immutable, they won't change the original data transfer object.
## Immutable DTOs and cloning
This package doesn't force immutable objects since PHP doesn't support them, but you're always encouraged to keep your DTOs immutable. To help you, there's a `clone` method on every DTO which accepts data to override:
```php
$clone = $original->clone(other: ['name' => 'a']);
```
Note that no data in `$original` is changed.
## Collections of DTOs
This version removes the `DataTransferObjectCollection` class. Instead you can use simple casters and your own collection classes.
Here's an example of casting a collection of DTOs to an array of DTOs:
```php
class Bar extends DataTransferObject
{
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(FooArrayCaster::class)]
public array $collectionOfFoo;
}
class Foo extends DataTransferObject
{
public string $name;
}
```
```php
class FooArrayCaster implements Caster
{
public function cast(mixed $value): array
{
if (! is_array($value)) {
throw new Exception("Can only cast arrays to Foo");
}
return array_map(
fn (array $data) => new Foo(...$data),
$value
);
}
}
```
If you don't want the redundant typehint, or want extended collection functionality; you could create your own collection classes using any collection implementation. In this example, we use Laravel's:
```php
class Bar extends DataTransferObject
{
#[CastWith(FooCollectionCaster::class)]
public CollectionOfFoo $collectionOfFoo;
}
class Foo extends DataTransferObject
{
public string $name;
}
```
```php
use Illuminate\Support\Collection;
class CollectionOfFoo extends Collection
{
// Add the correct return type here for static analyzers to know which type of array this is
public function offsetGet($key): Foo
{
return parent::offsetGet($key);
}
}
```
```php
class FooCollectionCaster implements Caster
{
public function cast(mixed $value): CollectionOfFoo
{
return new CollectionOfFoo(array_map(
fn (array $data) => new Foo(...$data),
$value
));
}
}
```
## Simple arrays of DTOs
For a simple array of DTOs, or an object that implements PHP's built-in `ArrayAccess`, consider using the `ArrayCaster` which requires an item type to be provided:
```php
class Bar extends DataTransferObject
{
/** @var \Spatie\DataTransferObject\Tests\Foo[] */
#[CastWith(ArrayCaster::class, itemType: Foo::class)]
public array $collectionOfFoo;
}
```
## Testing
``` bash
composer test
```
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributing
Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.
### Security
If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker.
## Postcardware
You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.
We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards).
## External tools
- [json2dto](https://json2dto.atymic.dev): a GUI to convert JSON objects to DTO classes (with nesting support). Also provides a [CLI tool](https://github.com/atymic/json2dto#cli-tool) for local usage.
- [Data Transfer Object Factory](https://github.com/anteris-dev/data-transfer-object-factory): Intelligently generates a DTO instance using the correct content for your properties based on its name and type.
## Credits
- [Brent Roose](https://github.com/brendt)
- [All Contributors](../../contributors)
Our `Arr` class contains functions copied from Laravels `Arr` helper.
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.
+44
View File
@@ -0,0 +1,44 @@
{
"name": "spatie/data-transfer-object",
"description": "Data transfer objects with batteries included",
"keywords": [
"spatie",
"data-transfer-object"
],
"homepage": "https://github.com/spatie/data-transfer-object",
"license": "MIT",
"authors": [
{
"name": "Brent Roose",
"email": "brent@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"require": {
"php": "^8.0"
},
"require-dev": {
"illuminate/collections": "^8.36",
"larapack/dd": "^1.1",
"phpunit/phpunit": "^9.0",
"jetbrains/phpstorm-attributes": "^1.0"
},
"autoload": {
"psr-4": {
"Spatie\\DataTransferObject\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Spatie\\DataTransferObject\\Tests\\": "tests"
}
},
"scripts": {
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
namespace Spatie\DataTransferObject;
use ArrayAccess;
class Arr
{
public static function only($array, $keys): array
{
return array_intersect_key($array, array_flip((array) $keys));
}
public static function except($array, $keys): array
{
return static::forget($array, $keys);
}
public static function forget($array, $keys): array
{
$keys = (array) $keys;
if (count($keys) === 0) {
return $array;
}
foreach ($keys as $key) {
// If the exact key exists in the top-level, remove it
if (static::exists($array, $key)) {
unset($array[$key]);
continue;
}
// Check if the key is using dot-notation
if (! str_contains($key, '.')) {
continue;
}
// If we are dealing with dot-notation, recursively handle i
$parts = explode('.', $key);
$key = array_shift($parts);
if (static::exists($array, $key) && static::accessible($array[$key])) {
$array[$key] = static::forget($array[$key], implode('.', $parts));
if (count($array[$key]) === 0) {
unset($array[$key]);
}
}
}
return $array;
}
public static function get($array, $key, $default = null)
{
if (! static::accessible($array)) {
return $default;
}
if (is_null($key)) {
return $array;
}
if (static::exists($array, $key)) {
return $array[$key];
}
if (strpos($key, '.') === false) {
return $array[$key] ?? $default;
}
foreach (explode('.', $key) as $segment) {
if (static::accessible($array) && static::exists($array, $segment)) {
$array = $array[$segment];
} else {
return $default;
}
}
return $array;
}
public static function accessible($value)
{
return is_array($value) || $value instanceof ArrayAccess;
}
public static function exists($array, $key): bool
{
if ($array instanceof ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
}
@@ -0,0 +1,24 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\Exceptions\InvalidCasterClass;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class CastWith
{
public array $args;
public function __construct(
public string $casterClass,
mixed ...$args
) {
if (! is_subclass_of($this->casterClass, Caster::class)) {
throw new InvalidCasterClass($this->casterClass);
}
$this->args = $args;
}
}
@@ -0,0 +1,53 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
use JetBrains\PhpStorm\Immutable;
use ReflectionNamedType;
use ReflectionProperty;
use ReflectionUnionType;
use Spatie\DataTransferObject\Caster;
#[Attribute(Attribute::TARGET_CLASS | Attribute::IS_REPEATABLE)]
class DefaultCast
{
public function __construct(
#[Immutable]
private string $targetClass,
#[Immutable]
private string $casterClass,
) {
}
public function accepts(ReflectionProperty $property): bool
{
$type = $property->getType();
/** @var \ReflectionNamedType[]|null $types */
$types = match ($type::class) {
ReflectionNamedType::class => [$type],
ReflectionUnionType::class => $type->getTypes(),
default => null,
};
if (! $types) {
return false;
}
foreach ($types as $type) {
if ($type->getName() !== $this->targetClass) {
continue;
}
return true;
}
return false;
}
public function resolveCaster(): Caster
{
return new $this->casterClass();
}
}
@@ -0,0 +1,14 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class MapFrom
{
public function __construct(
public string | int $name,
) {
}
}
@@ -0,0 +1,14 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_PROPERTY)]
class MapTo
{
public function __construct(
public string $name,
) {
}
}
@@ -0,0 +1,10 @@
<?php
namespace Spatie\DataTransferObject\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_CLASS)]
class Strict
{
}
+8
View File
@@ -0,0 +1,8 @@
<?php
namespace Spatie\DataTransferObject;
interface Caster
{
public function cast(mixed $value): mixed;
}
@@ -0,0 +1,70 @@
<?php
namespace Spatie\DataTransferObject\Casters;
use ArrayAccess;
use LogicException;
use Spatie\DataTransferObject\Caster;
use Traversable;
class ArrayCaster implements Caster
{
public function __construct(
private array $types,
private string $itemType,
) {
}
public function cast(mixed $value): array | ArrayAccess
{
foreach ($this->types as $type) {
if ($type == 'array') {
return $this->mapInto(
destination: [],
items: $value
);
}
if (is_subclass_of($type, ArrayAccess::class)) {
return $this->mapInto(
destination: new $type(),
items: $value
);
}
}
throw new LogicException(
"Caster [ArrayCaster] may only be used to cast arrays or objects that implement ArrayAccess."
);
}
private function mapInto(array | ArrayAccess $destination, mixed $items): array | ArrayAccess
{
if ($destination instanceof ArrayAccess && ! is_subclass_of($destination, Traversable::class)) {
throw new LogicException(
"Caster [ArrayCaster] may only be used to cast ArrayAccess objects that are traversable."
);
}
foreach ($items as $key => $item) {
$destination[$key] = $this->castItem($item);
}
return $destination;
}
private function castItem(mixed $data)
{
if ($data instanceof $this->itemType) {
return $data;
}
if (is_array($data)) {
return new $this->itemType(...$data);
}
throw new LogicException(
"Caster [ArrayCaster] each item must be an array or an instance of the specified item type [{$this->itemType}]."
);
}
}
@@ -0,0 +1,25 @@
<?php
namespace Spatie\DataTransferObject\Casters;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\DataTransferObject;
class DataTransferObjectCaster implements Caster
{
public function __construct(
private array $classNames
) {
}
public function cast(mixed $value): DataTransferObject
{
foreach ($this->classNames as $className) {
if ($value instanceof $className) {
return $value;
}
}
return new $this->classNames[0](...$value);
}
}
@@ -0,0 +1,125 @@
<?php
namespace Spatie\DataTransferObject;
use ReflectionClass;
use ReflectionProperty;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\MapTo;
use Spatie\DataTransferObject\Casters\DataTransferObjectCaster;
use Spatie\DataTransferObject\Exceptions\UnknownProperties;
use Spatie\DataTransferObject\Reflection\DataTransferObjectClass;
#[CastWith(DataTransferObjectCaster::class)]
abstract class DataTransferObject
{
protected array $exceptKeys = [];
protected array $onlyKeys = [];
public function __construct(...$args)
{
if (is_array($args[0] ?? null)) {
$args = $args[0];
}
$class = new DataTransferObjectClass($this);
foreach ($class->getProperties() as $property) {
$property->setValue(Arr::get($args, $property->name) ?? $this->{$property->name} ?? null);
$args = Arr::forget($args, $property->name);
}
if ($class->isStrict() && count($args)) {
throw UnknownProperties::new(static::class, array_keys($args));
}
$class->validate();
}
public static function arrayOf(array $arrayOfParameters): array
{
return array_map(
fn (mixed $parameters) => new static($parameters),
$arrayOfParameters
);
}
public function all(): array
{
$data = [];
$class = new ReflectionClass(static::class);
$properties = $class->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($properties as $property) {
if ($property->isStatic()) {
continue;
}
$mapToAttribute = $property->getAttributes(MapTo::class);
$name = count($mapToAttribute) ? $mapToAttribute[0]->newInstance()->name : $property->getName();
$data[$name] = $property->getValue($this);
}
return $data;
}
public function only(string ...$keys): static
{
$dataTransferObject = clone $this;
$dataTransferObject->onlyKeys = [...$this->onlyKeys, ...$keys];
return $dataTransferObject;
}
public function except(string ...$keys): static
{
$dataTransferObject = clone $this;
$dataTransferObject->exceptKeys = [...$this->exceptKeys, ...$keys];
return $dataTransferObject;
}
public function clone(...$args): static
{
return new static(...array_merge($this->toArray(), $args));
}
public function toArray(): array
{
if (count($this->onlyKeys)) {
$array = Arr::only($this->all(), $this->onlyKeys);
} else {
$array = Arr::except($this->all(), $this->exceptKeys);
}
$array = $this->parseArray($array);
return $array;
}
protected function parseArray(array $array): array
{
foreach ($array as $key => $value) {
if ($value instanceof DataTransferObject) {
$array[$key] = $value->toArray();
continue;
}
if (! is_array($value)) {
continue;
}
$array[$key] = $this->parseArray($value);
}
return $array;
}
}
@@ -0,0 +1,18 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
use Spatie\DataTransferObject\Caster;
class InvalidCasterClass extends Exception
{
public function __construct(string $className)
{
$expected = Caster::class;
parent::__construct(
"Class `{$className}` doesn't implement {$expected} and can't be used as a caster"
);
}
}
@@ -0,0 +1,15 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
class UnknownProperties extends Exception
{
public static function new(string $dtoClass, array $fields): self
{
$properties = json_encode($fields);
return new self("Unknown properties provided to `{$dtoClass}`: {$properties}");
}
}
@@ -0,0 +1,27 @@
<?php
namespace Spatie\DataTransferObject\Exceptions;
use Exception;
use Spatie\DataTransferObject\DataTransferObject;
class ValidationException extends Exception
{
public function __construct(
public DataTransferObject $dataTransferObject,
public array $validationErrors,
) {
$className = $dataTransferObject::class;
$messages = [];
foreach ($validationErrors as $fieldName => $errorsForField) {
/** @var \Spatie\DataTransferObject\Validation\ValidationResult $errorForField */
foreach ($errorsForField as $errorForField) {
$messages[] = "\t - `{$className}->{$fieldName}`: {$errorForField->message}";
}
}
parent::__construct("Validation errors:" . PHP_EOL . implode(PHP_EOL, $messages));
}
}
@@ -0,0 +1,84 @@
<?php
namespace Spatie\DataTransferObject\Reflection;
use ReflectionClass;
use ReflectionProperty;
use Spatie\DataTransferObject\Attributes\Strict;
use Spatie\DataTransferObject\DataTransferObject;
use Spatie\DataTransferObject\Exceptions\ValidationException;
class DataTransferObjectClass
{
private ReflectionClass $reflectionClass;
private DataTransferObject $dataTransferObject;
private bool $isStrict;
public function __construct(DataTransferObject $dataTransferObject)
{
$this->reflectionClass = new ReflectionClass($dataTransferObject);
$this->dataTransferObject = $dataTransferObject;
}
/**
* @return \Spatie\DataTransferObject\Reflection\DataTransferObjectProperty[]
*/
public function getProperties(): array
{
$publicProperties = array_filter(
$this->reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC),
fn (ReflectionProperty $property) => ! $property->isStatic()
);
return array_map(
fn (ReflectionProperty $property) => new DataTransferObjectProperty(
$this->dataTransferObject,
$property
),
$publicProperties
);
}
public function validate(): void
{
$validationErrors = [];
foreach ($this->getProperties() as $property) {
$validators = $property->getValidators();
foreach ($validators as $validator) {
$result = $validator->validate($property->getValue());
if ($result->isValid) {
continue;
}
$validationErrors[$property->name][] = $result;
}
}
if (count($validationErrors)) {
throw new ValidationException($this->dataTransferObject, $validationErrors);
}
}
public function isStrict(): bool
{
if (! isset($this->isStrict)) {
$attribute = null;
$reflectionClass = $this->reflectionClass;
while ($attribute === null && $reflectionClass !== false) {
$attribute = $reflectionClass->getAttributes(Strict::class)[0] ?? null;
$reflectionClass = $reflectionClass->getParentClass();
}
$this->isStrict = $attribute !== null;
}
return $this->isStrict;
}
}
@@ -0,0 +1,182 @@
<?php
namespace Spatie\DataTransferObject\Reflection;
use JetBrains\PhpStorm\Immutable;
use ReflectionAttribute;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;
use ReflectionType;
use ReflectionUnionType;
use Spatie\DataTransferObject\Attributes\CastWith;
use Spatie\DataTransferObject\Attributes\DefaultCast;
use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\Caster;
use Spatie\DataTransferObject\DataTransferObject;
use Spatie\DataTransferObject\Validator;
class DataTransferObjectProperty
{
#[Immutable]
public string $name;
private DataTransferObject $dataTransferObject;
private ReflectionProperty $reflectionProperty;
private ?Caster $caster;
public function __construct(
DataTransferObject $dataTransferObject,
ReflectionProperty $reflectionProperty
) {
$this->dataTransferObject = $dataTransferObject;
$this->reflectionProperty = $reflectionProperty;
$this->name = $this->resolveMappedProperty();
$this->caster = $this->resolveCaster();
}
public function setValue(mixed $value): void
{
if ($this->caster && $value !== null) {
$value = $this->caster->cast($value);
}
$this->reflectionProperty->setValue($this->dataTransferObject, $value);
}
/**
* @return \Spatie\DataTransferObject\Validator[]
*/
public function getValidators(): array
{
$attributes = $this->reflectionProperty->getAttributes(
Validator::class,
ReflectionAttribute::IS_INSTANCEOF
);
return array_map(
fn (ReflectionAttribute $attribute) => $attribute->newInstance(),
$attributes
);
}
public function getValue(): mixed
{
return $this->reflectionProperty->getValue($this->dataTransferObject);
}
private function resolveCaster(): ?Caster
{
$attributes = $this->reflectionProperty->getAttributes(CastWith::class);
if (! count($attributes)) {
$attributes = $this->resolveCasterFromType();
}
if (! count($attributes)) {
return $this->resolveCasterFromDefaults();
}
/** @var \Spatie\DataTransferObject\Attributes\CastWith $attribute */
$attribute = $attributes[0]->newInstance();
return new $attribute->casterClass(
array_map(fn ($type) => $this->resolveTypeName($type), $this->extractTypes()),
...$attribute->args
);
}
private function resolveCasterFromType(): array
{
foreach ($this->extractTypes() as $type) {
$name = $this->resolveTypeName($type);
if (! class_exists($name)) {
continue;
}
$reflectionClass = new ReflectionClass($name);
do {
$attributes = $reflectionClass->getAttributes(CastWith::class);
$reflectionClass = $reflectionClass->getParentClass();
} while (! count($attributes) && $reflectionClass);
if (count($attributes) > 0) {
return $attributes;
}
}
return [];
}
private function resolveCasterFromDefaults(): ?Caster
{
$defaultCastAttributes = [];
$class = $this->reflectionProperty->getDeclaringClass();
do {
array_push($defaultCastAttributes, ...$class->getAttributes(DefaultCast::class));
$class = $class->getParentClass();
} while ($class !== false);
if (! count($defaultCastAttributes)) {
return null;
}
foreach ($defaultCastAttributes as $defaultCastAttribute) {
/** @var \Spatie\DataTransferObject\Attributes\DefaultCast $defaultCast */
$defaultCast = $defaultCastAttribute->newInstance();
if ($defaultCast->accepts($this->reflectionProperty)) {
return $defaultCast->resolveCaster();
}
}
return null;
}
private function resolveMappedProperty(): string | int
{
$attributes = $this->reflectionProperty->getAttributes(MapFrom::class);
if (! count($attributes)) {
return $this->reflectionProperty->name;
}
return $attributes[0]->newInstance()->name;
}
/**
* @return ReflectionNamedType[]
*/
private function extractTypes(): array
{
$type = $this->reflectionProperty->getType();
if (! $type) {
return [];
}
return match ($type::class) {
ReflectionNamedType::class => [$type],
ReflectionUnionType::class => $type->getTypes(),
};
}
private function resolveTypeName(ReflectionType $type): string
{
return match ($type->getName()) {
'self' => $this->dataTransferObject::class,
'parent' => get_parent_class($this->dataTransferObject),
default => $type->getName(),
};
}
}
@@ -0,0 +1,31 @@
<?php
namespace Spatie\DataTransferObject\Validation;
use JetBrains\PhpStorm\Immutable;
class ValidationResult
{
public function __construct(
#[Immutable]
public bool $isValid,
#[Immutable]
public ?string $message = null
) {
}
public static function valid(): self
{
return new self(
isValid: true,
);
}
public static function invalid(string $message): self
{
return new self(
isValid: false,
message: $message,
);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace Spatie\DataTransferObject;
use Spatie\DataTransferObject\Validation\ValidationResult;
interface Validator
{
public function validate(mixed $value): ValidationResult;
}