Skip to content

Commit 8a4bff6

Browse files
authored
v1.6.0 Release (#10)
* v1.6.0 Release * v1.6.0 [bugfix] ClassGeneratorFacadeDefault - logger as optional parameter * v1.6.0 [compatibility] php version 8.0 < 8.2 tested * v1.6.0 [examples] Add usage examples * v1.6.0 [doc] Update README.md
1 parent 049ae22 commit 8a4bff6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+980
-164
lines changed

README.md

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,29 +19,62 @@ composer require micro/dto
1919

2020
``` xml
2121
<?xml version="1.0"?>
22-
<dto xmlns="micro:dto-01"
22+
<dto xmlns="micro:dto-1.6"
2323
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
24-
xsi:schemaLocation="micro:dto-01 https://raw.githubusercontent.com/Micro-PHP/dto/master/src/Resource/schema/dto-01.xsd">
24+
xsi:schemaLocation="micro:dto-1.6 https://raw.githubusercontent.com/Micro-PHP/dto/master/src/Resource/schema/dto-1.6.xsd">
2525
<class name="User\User">
26-
<property name="email" type="string"/>
27-
<property name="age" type="int"/>
26+
<property name="email" type="string">
27+
<validation>
28+
<not_blank grou/>
29+
<length min="6" max="50"/>
30+
<regex pattern="/^(.[aA-zA]+)$/"/>
31+
</validation>
32+
</property>
33+
<property name="age" type="int">
34+
<validation>
35+
<not_blank groups="put"/>
36+
<greater_than value="18" />
37+
<less_than value="100" groups="put, patch" />
38+
</validation>
39+
</property>
2840
<property name="updatedAt" type="datetime" />
2941
<property name="parent" type="User\User" />
3042
</class>
3143
</dto>
3244
```
3345
* And run generator
3446
```php
35-
use Micro\Library\DTO\ClassGeneratorFacadeDefault;
36-
37-
$classGenerator = new ClassGeneratorFacadeDefault(
47+
$classGenerator = new \Micro\Library\DTO\ClassGeneratorFacadeDefault(
3848
['./example.xml'], // List of class declaration files
3949
'./out', // Path to the folder where to generate
4050
'Transfer' // Suffix for the all DTO classes (optional)
4151
);
42-
4352
$classGenerator->generate();
4453

54+
// Usage example
55+
$user = new \User\User();
56+
$user
57+
->setAge(19)
58+
->setEmail('[email protected]');
59+
// OR
60+
//
61+
$user['age'] = 19;
62+
$user['email'] = '[email protected]';
63+
64+
// Validation example
65+
$validator = new \Micro\Library\DTO\ValidatorFacadeDefault();
66+
$validator->validate($user); // Validation groups by default ["Default"]
67+
$validator->validate($user, ['patch', 'put']); // Set validation groups ["patch", "put"]
68+
69+
// Serialize example
70+
$serializer = new \Micro\Library\DTO\SerializerFacadeDefault();
71+
$serializer->toArray($user); // Simple array
72+
$serializer->toJson($user); // Simple Json
73+
74+
// Deserialize example
75+
$serialized = $serializer->toJsonTransfer($user);
76+
$deserialized = $serializer->fromJsonTransfer($serialized);
77+
4578
```
4679

4780
### [See full example](./example/)

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
}
2121
],
2222
"require": {
23-
"php": ">= 8.1",
23+
"php": ">= 8.0",
2424
"ext-dom": "*",
2525
"ext-intl": "*",
2626
"ext-libxml": "*",

example/out/Simple/SimpleUserTransfer.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ final class SimpleUserTransfer extends \Micro\Library\DTO\Object\AbstractDto
4444
protected string|null $json = null;
4545

4646
#[\Symfony\Component\Validator\Constraints\NotBlank(groups: ['Default'], allowNull: false)]
47-
#[\Symfony\Component\Validator\Constraints\Uuid(groups: ['Default'], versions: [1, 2, 3, 4, 5, 6, 7], strict: true)]
47+
#[\Symfony\Component\Validator\Constraints\Uuid(groups: ['Default'], versions: [1, 2, 3, 4, 5, 6], strict: true)]
4848
protected string|null $uuid = null;
4949

5050
#[\Symfony\Component\Validator\Constraints\DateTime(groups: ['Default'], format: 'Y-m-d H:i:s')]
@@ -78,6 +78,7 @@ final class SimpleUserTransfer extends \Micro\Library\DTO\Object\AbstractDto
7878
protected string|null $isbn = null;
7979

8080
#[\Symfony\Component\Validator\Constraints\NotBlank(groups: ['Default'], allowNull: false)]
81+
#[\Symfony\Component\Validator\Constraints\Issn(groups: ['Default'])]
8182
protected string|null $issn = null;
8283

8384
#[\Symfony\Component\Validator\Constraints\NotBlank(groups: ['Default'], allowNull: false)]

example/test.php

Lines changed: 46 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,86 +2,95 @@
22

33
require dirname(__FILE__) . '/../vendor/autoload.php';
44

5-
// Create Logger
6-
$logger = new class extends \Psr\Log\NullLogger {
7-
public function debug(\Stringable|string $message, array $context = []): void
8-
{
9-
print_r("$message\r\n");
10-
}
11-
};
12-
13-
// Create default class generator facade
5+
/**
6+
* Create default class generator facade
7+
*/
148
$classGenerator = new \Micro\Library\DTO\ClassGeneratorFacadeDefault(
159
['./example.xml'],
1610
'./out',
1711
'Transfer',
1812
'Transfer',
19-
$logger
2013
);
2114

2215
$classGenerator->generate();
2316

24-
// Require generated classes
17+
/**
18+
* Require generated classes
19+
*/
2520
require_once 'out/Simple/SimpleObjectTransfer.php';
2621
require_once 'out/Simple/SimpleUserTransfer.php';
2722
require_once 'out/UserTransfer.php';
2823

24+
use Transfer\UserTransfer;
25+
use Transfer\Simple\SimpleObjectTransfer;
26+
use Micro\Library\DTO\SerializerFacadeDefault;
27+
use Micro\Library\DTO\ValidatorFacadeDefault;
28+
use Transfer\Simple\SimpleUserTransfer;
2929

30-
$user = new \Transfer\UserTransfer();
30+
/**
31+
* Iterate DTO values
32+
*/
33+
$user = new UserTransfer();
3134
$user
3235
->setFirstName('Stas')
3336
->setUsername('Asisyas')
3437
->setUpdatedAt(new DateTime('11.08.1989'))
3538
->setBooks(
3639
[
37-
(new Transfer\Simple\SimpleObjectTransfer())
40+
(new SimpleObjectTransfer())
3841
->setHeight(1)
3942
->setWeight(20)
4043
->setParent(
41-
(new Transfer\Simple\SimpleObjectTransfer())
44+
(new SimpleObjectTransfer())
4245
->setHeight(100)
4346
->setWeight(2000)
4447
)
4548
])
4649
->setSomeclass(
47-
(new \Transfer\Simple\SimpleObjectTransfer())
50+
(new SimpleObjectTransfer())
4851
->setWeight(1)
4952
->setHeight(2)
5053
)
5154
;
5255

53-
// Iterate as array
5456
foreach ($user as $key => $value) {
55-
// print_r("\r\nPROPERTY: " . $key . " ==== " . (is_scalar($value) ? $value : serialize($value)));
57+
print_r("\r\nPROPERTY: " . $key . " ==== " . (is_scalar($value) ? $value : serialize($value)));
5658
}
5759

58-
//
59-
//print_r('FISRT BOOK HEIGHT : ' . $user['books'][0]['height'] . "\r\n");
60-
//print_r('FISRT BOOK PARENT HEIGHT : ' . $user['books'][0]['parent']['height'] . "\r\n");
6160

61+
/**
62+
* Array access example
63+
*/
64+
print_r("\r\n\r\nFISRT BOOK HEIGHT : " . $user['books'][0]['height'] . "\r\n");
65+
print_r('FISRT BOOK PARENT HEIGHT : ' . $user['books'][0]['parent']['height'] . "\r\n\r\n");
66+
// Allowed too
67+
$user['books'][0]['height'] = 12;
6268

63-
$classSerializerFacade = new \Micro\Library\DTO\SerializerFacadeDefault();
69+
/**
70+
* Serialization example
71+
*/
72+
$classSerializerFacade = new SerializerFacadeDefault();
73+
$jsonDto = $classSerializerFacade->toJsonTransfer($user);
74+
$json = $classSerializerFacade->toJson($user);
6475

76+
print_r('Serialized DTO: ' . $jsonDto . "\r\n\r\n");
77+
print_r('Serialize DTO as JSON: ' . $json . "\r\n\r\n");
6578

66-
$json = $classSerializerFacade->toJsonTransfer($user);
79+
$deserialized = $classSerializerFacade->fromJsonTransfer($jsonDto);
6780

68-
//dump($json);
81+
$className = get_class($user);
82+
$okNo = get_class($deserialized) === $className ?'true' : 'false';
83+
print_r( "Deserialize $className: $okNo \r\n");
6984

70-
$result = $classSerializerFacade->fromJsonTransfer($json);
71-
72-
$mf = new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader());
73-
74-
$vb = \Symfony\Component\Validator\Validation::createValidatorBuilder();
75-
$vb->setMetadataFactory($mf);
76-
$vb->disableAnnotationMapping();
77-
$validator = $vb->getValidator();
78-
79-
$simpleUserParent = new \Transfer\Simple\SimpleObjectTransfer();
85+
/**
86+
* Validate DTO example
87+
*/
88+
$simpleUserParent = new SimpleObjectTransfer();
8089
$simpleUserParent
8190
->setWeight(9)
8291
->setHeight(8);
8392

84-
$simpleUser = new \Transfer\Simple\SimpleUserTransfer();
93+
$simpleUser = new SimpleUserTransfer();
8594
$simpleUser
8695
->setParent($simpleUserParent)
8796
->setIp('192.168.0.1')
@@ -105,10 +114,10 @@ public function debug(\Stringable|string $message, array $context = []): void
105114
->setIsin('US0378331005')
106115
;
107116

117+
$validator = new ValidatorFacadeDefault();
108118
$constraints = $validator->validate($simpleUser);
109119

110-
dump($constraints);
111-
112-
//dump($result);
120+
$validationStatus = !count($constraints) ? 'Validated': 'Validation error';
113121

122+
print_r("Validation status: $validationStatus\r\n");
114123

src/ClassGeneratorFacadeDefault.php

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
namespace Micro\Library\DTO;
1515

1616
use Psr\Log\LoggerInterface;
17-
use Psr\Log\NullLogger;
1817

1918
class ClassGeneratorFacadeDefault extends GeneratorFacade
2019
{
@@ -26,11 +25,11 @@ class ClassGeneratorFacadeDefault extends GeneratorFacade
2625
* @param LoggerInterface|null $logger
2726
*/
2827
public function __construct(
29-
private readonly array $filesSchemeCollection,
30-
private readonly string $outputPath,
31-
private readonly string $namespaceGeneral = '',
32-
private readonly string $classSuffix = 'Transfer',
33-
private readonly null|LoggerInterface $logger = new NullLogger(),
28+
private array $filesSchemeCollection,
29+
private string $outputPath,
30+
private string $namespaceGeneral = '',
31+
private string $classSuffix = 'Transfer',
32+
private null|LoggerInterface $logger = null
3433
) {
3534
parent::__construct($this->createDefaultDependencyInjectionObject());
3635
}

src/DependencyInjection.php

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IpStrategy;
4343
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IsbnStrategy;
4444
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IsinStrategy;
45+
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IssnStrategy;
4546
use Micro\Library\DTO\Preparation\Processor\Property\Assert\JsonStrategy;
4647
use Micro\Library\DTO\Preparation\Processor\Property\Assert\LengthStrategy;
4748
use Micro\Library\DTO\Preparation\Processor\Property\Assert\LessThanOrEqualStrategy;
@@ -56,6 +57,7 @@
5657
use Micro\Library\DTO\Preparation\Processor\Property\Assert\PositiveStrategy;
5758
use Micro\Library\DTO\Preparation\Processor\Property\Assert\RangeStrategy;
5859
use Micro\Library\DTO\Preparation\Processor\Property\Assert\RegexStrategy;
60+
use Micro\Library\DTO\Preparation\Processor\Property\Assert\TimeStrategy;
5961
use Micro\Library\DTO\Preparation\Processor\Property\Assert\TimeZoneStrategy;
6062
use Micro\Library\DTO\Preparation\Processor\Property\Assert\UrlStrategy;
6163
use Micro\Library\DTO\Preparation\Processor\Property\Assert\UuidStrategy;
@@ -85,11 +87,11 @@ class DependencyInjection implements DependencyInjectionInterface
8587
* @param string[] $filesSchemeCollection
8688
*/
8789
public function __construct(
88-
private readonly array $filesSchemeCollection,
89-
private readonly string $namespaceGeneral,
90-
private readonly string $classSuffix,
91-
private readonly string $outputPath,
92-
private readonly ?LoggerInterface $logger
90+
private array $filesSchemeCollection,
91+
private string $namespaceGeneral,
92+
private string $classSuffix,
93+
private string $outputPath,
94+
private ?LoggerInterface $logger
9395
) {
9496
}
9597

@@ -182,6 +184,7 @@ protected function createPropertyValidationProcessorCollection(): iterable
182184
new JsonStrategy(),
183185
new UuidStrategy(),
184186
new DateStrategy(),
187+
new TimeStrategy(),
185188
new DateTimeStrategy(),
186189
new TimeZoneStrategy(),
187190
new NegativeStrategy(),
@@ -204,6 +207,7 @@ protected function createPropertyValidationProcessorCollection(): iterable
204207
new IbanStrategy(),
205208
new IsbnStrategy(),
206209
new IsinStrategy(),
210+
new IssnStrategy(),
207211
];
208212
}
209213
}

src/Generator/Generator.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,11 @@
2323
class Generator
2424
{
2525
public function __construct(
26-
private readonly ReaderInterface $reader,
27-
private readonly WriterInterface $writer,
28-
private readonly RendererInterface $renderer,
29-
private readonly CollectionPreparationInterface $classCollectionPreparation,
30-
private readonly LoggerInterface $logger
26+
private ReaderInterface $reader,
27+
private WriterInterface $writer,
28+
private RendererInterface $renderer,
29+
private CollectionPreparationInterface $classCollectionPreparation,
30+
private LoggerInterface $logger
3131
) {
3232
}
3333

src/GeneratorFacade.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
class GeneratorFacade implements GeneratorFacadeInterface
1919
{
2020
public function __construct(
21-
private readonly DependencyInjectionInterface $dependencyInjection
21+
private DependencyInjectionInterface $dependencyInjection
2222
) {
2323
}
2424

src/Helper/ClassMetadataHelper.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ class ClassMetadataHelper implements ClassMetadataHelperInterface
2222
* @param string $classSuffix
2323
*/
2424
public function __construct(
25-
private readonly string $namespaceGeneral,
26-
private readonly string $classSuffix
25+
private string $namespaceGeneral,
26+
private string $classSuffix
2727
) {
2828
}
2929

src/Merger/Merger.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class Merger implements MergerInterface
1818
/**
1919
* @param array<int, mixed> $classCollection
2020
*/
21-
public function __construct(private readonly array $classCollection)
21+
public function __construct(private array $classCollection)
2222
{
2323
}
2424

0 commit comments

Comments
 (0)