Skip to content

Commit

Permalink
v1.6.0 Release (#10)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Asisyas authored Feb 16, 2023
1 parent 049ae22 commit 8a4bff6
Show file tree
Hide file tree
Showing 46 changed files with 980 additions and 164 deletions.
49 changes: 41 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,62 @@ composer require micro/dto

``` xml
<?xml version="1.0"?>
<dto xmlns="micro:dto-01"
<dto xmlns="micro:dto-1.6"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="micro:dto-01 https://raw.githubusercontent.com/Micro-PHP/dto/master/src/Resource/schema/dto-01.xsd">
xsi:schemaLocation="micro:dto-1.6 https://raw.githubusercontent.com/Micro-PHP/dto/master/src/Resource/schema/dto-1.6.xsd">
<class name="User\User">
<property name="email" type="string"/>
<property name="age" type="int"/>
<property name="email" type="string">
<validation>
<not_blank grou/>
<length min="6" max="50"/>
<regex pattern="/^(.[aA-zA]+)$/"/>
</validation>
</property>
<property name="age" type="int">
<validation>
<not_blank groups="put"/>
<greater_than value="18" />
<less_than value="100" groups="put, patch" />
</validation>
</property>
<property name="updatedAt" type="datetime" />
<property name="parent" type="User\User" />
</class>
</dto>
```
* And run generator
```php
use Micro\Library\DTO\ClassGeneratorFacadeDefault;

$classGenerator = new ClassGeneratorFacadeDefault(
$classGenerator = new \Micro\Library\DTO\ClassGeneratorFacadeDefault(
['./example.xml'], // List of class declaration files
'./out', // Path to the folder where to generate
'Transfer' // Suffix for the all DTO classes (optional)
);

$classGenerator->generate();

// Usage example
$user = new \User\User();
$user
->setAge(19)
->setEmail('[email protected]');
// OR
//
$user['age'] = 19;
$user['email'] = '[email protected]';

// Validation example
$validator = new \Micro\Library\DTO\ValidatorFacadeDefault();
$validator->validate($user); // Validation groups by default ["Default"]
$validator->validate($user, ['patch', 'put']); // Set validation groups ["patch", "put"]

// Serialize example
$serializer = new \Micro\Library\DTO\SerializerFacadeDefault();
$serializer->toArray($user); // Simple array
$serializer->toJson($user); // Simple Json

// Deserialize example
$serialized = $serializer->toJsonTransfer($user);
$deserialized = $serializer->fromJsonTransfer($serialized);

```

### [See full example](./example/)
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
}
],
"require": {
"php": ">= 8.1",
"php": ">= 8.0",
"ext-dom": "*",
"ext-intl": "*",
"ext-libxml": "*",
Expand Down
3 changes: 2 additions & 1 deletion example/out/Simple/SimpleUserTransfer.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class SimpleUserTransfer extends \Micro\Library\DTO\Object\AbstractDto
protected string|null $json = null;

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

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

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

#[\Symfony\Component\Validator\Constraints\NotBlank(groups: ['Default'], allowNull: false)]
Expand Down
83 changes: 46 additions & 37 deletions example/test.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,86 +2,95 @@

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

// Create Logger
$logger = new class extends \Psr\Log\NullLogger {
public function debug(\Stringable|string $message, array $context = []): void
{
print_r("$message\r\n");
}
};

// Create default class generator facade
/**
* Create default class generator facade
*/
$classGenerator = new \Micro\Library\DTO\ClassGeneratorFacadeDefault(
['./example.xml'],
'./out',
'Transfer',
'Transfer',
$logger
);

$classGenerator->generate();

// Require generated classes
/**
* Require generated classes
*/
require_once 'out/Simple/SimpleObjectTransfer.php';
require_once 'out/Simple/SimpleUserTransfer.php';
require_once 'out/UserTransfer.php';

use Transfer\UserTransfer;
use Transfer\Simple\SimpleObjectTransfer;
use Micro\Library\DTO\SerializerFacadeDefault;
use Micro\Library\DTO\ValidatorFacadeDefault;
use Transfer\Simple\SimpleUserTransfer;

$user = new \Transfer\UserTransfer();
/**
* Iterate DTO values
*/
$user = new UserTransfer();
$user
->setFirstName('Stas')
->setUsername('Asisyas')
->setUpdatedAt(new DateTime('11.08.1989'))
->setBooks(
[
(new Transfer\Simple\SimpleObjectTransfer())
(new SimpleObjectTransfer())
->setHeight(1)
->setWeight(20)
->setParent(
(new Transfer\Simple\SimpleObjectTransfer())
(new SimpleObjectTransfer())
->setHeight(100)
->setWeight(2000)
)
])
->setSomeclass(
(new \Transfer\Simple\SimpleObjectTransfer())
(new SimpleObjectTransfer())
->setWeight(1)
->setHeight(2)
)
;

// Iterate as array
foreach ($user as $key => $value) {
// print_r("\r\nPROPERTY: " . $key . " ==== " . (is_scalar($value) ? $value : serialize($value)));
print_r("\r\nPROPERTY: " . $key . " ==== " . (is_scalar($value) ? $value : serialize($value)));
}

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

/**
* Array access example
*/
print_r("\r\n\r\nFISRT BOOK HEIGHT : " . $user['books'][0]['height'] . "\r\n");
print_r('FISRT BOOK PARENT HEIGHT : ' . $user['books'][0]['parent']['height'] . "\r\n\r\n");
// Allowed too
$user['books'][0]['height'] = 12;

$classSerializerFacade = new \Micro\Library\DTO\SerializerFacadeDefault();
/**
* Serialization example
*/
$classSerializerFacade = new SerializerFacadeDefault();
$jsonDto = $classSerializerFacade->toJsonTransfer($user);
$json = $classSerializerFacade->toJson($user);

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

$json = $classSerializerFacade->toJsonTransfer($user);
$deserialized = $classSerializerFacade->fromJsonTransfer($jsonDto);

//dump($json);
$className = get_class($user);
$okNo = get_class($deserialized) === $className ?'true' : 'false';
print_r( "Deserialize $className: $okNo \r\n");

$result = $classSerializerFacade->fromJsonTransfer($json);

$mf = new \Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory(new \Symfony\Component\Validator\Mapping\Loader\AnnotationLoader());

$vb = \Symfony\Component\Validator\Validation::createValidatorBuilder();
$vb->setMetadataFactory($mf);
$vb->disableAnnotationMapping();
$validator = $vb->getValidator();

$simpleUserParent = new \Transfer\Simple\SimpleObjectTransfer();
/**
* Validate DTO example
*/
$simpleUserParent = new SimpleObjectTransfer();
$simpleUserParent
->setWeight(9)
->setHeight(8);

$simpleUser = new \Transfer\Simple\SimpleUserTransfer();
$simpleUser = new SimpleUserTransfer();
$simpleUser
->setParent($simpleUserParent)
->setIp('192.168.0.1')
Expand All @@ -105,10 +114,10 @@ public function debug(\Stringable|string $message, array $context = []): void
->setIsin('US0378331005')
;

$validator = new ValidatorFacadeDefault();
$constraints = $validator->validate($simpleUser);

dump($constraints);

//dump($result);
$validationStatus = !count($constraints) ? 'Validated': 'Validation error';

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

11 changes: 5 additions & 6 deletions src/ClassGeneratorFacadeDefault.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
namespace Micro\Library\DTO;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

class ClassGeneratorFacadeDefault extends GeneratorFacade
{
Expand All @@ -26,11 +25,11 @@ class ClassGeneratorFacadeDefault extends GeneratorFacade
* @param LoggerInterface|null $logger
*/
public function __construct(
private readonly array $filesSchemeCollection,
private readonly string $outputPath,
private readonly string $namespaceGeneral = '',
private readonly string $classSuffix = 'Transfer',
private readonly null|LoggerInterface $logger = new NullLogger(),
private array $filesSchemeCollection,
private string $outputPath,
private string $namespaceGeneral = '',
private string $classSuffix = 'Transfer',
private null|LoggerInterface $logger = null
) {
parent::__construct($this->createDefaultDependencyInjectionObject());
}
Expand Down
14 changes: 9 additions & 5 deletions src/DependencyInjection.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IpStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IsbnStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IsinStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\IssnStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\JsonStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\LengthStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\LessThanOrEqualStrategy;
Expand All @@ -56,6 +57,7 @@
use Micro\Library\DTO\Preparation\Processor\Property\Assert\PositiveStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\RangeStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\RegexStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\TimeStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\TimeZoneStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\UrlStrategy;
use Micro\Library\DTO\Preparation\Processor\Property\Assert\UuidStrategy;
Expand Down Expand Up @@ -85,11 +87,11 @@ class DependencyInjection implements DependencyInjectionInterface
* @param string[] $filesSchemeCollection
*/
public function __construct(
private readonly array $filesSchemeCollection,
private readonly string $namespaceGeneral,
private readonly string $classSuffix,
private readonly string $outputPath,
private readonly ?LoggerInterface $logger
private array $filesSchemeCollection,
private string $namespaceGeneral,
private string $classSuffix,
private string $outputPath,
private ?LoggerInterface $logger
) {
}

Expand Down Expand Up @@ -182,6 +184,7 @@ protected function createPropertyValidationProcessorCollection(): iterable
new JsonStrategy(),
new UuidStrategy(),
new DateStrategy(),
new TimeStrategy(),
new DateTimeStrategy(),
new TimeZoneStrategy(),
new NegativeStrategy(),
Expand All @@ -204,6 +207,7 @@ protected function createPropertyValidationProcessorCollection(): iterable
new IbanStrategy(),
new IsbnStrategy(),
new IsinStrategy(),
new IssnStrategy(),
];
}
}
10 changes: 5 additions & 5 deletions src/Generator/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@
class Generator
{
public function __construct(
private readonly ReaderInterface $reader,
private readonly WriterInterface $writer,
private readonly RendererInterface $renderer,
private readonly CollectionPreparationInterface $classCollectionPreparation,
private readonly LoggerInterface $logger
private ReaderInterface $reader,
private WriterInterface $writer,
private RendererInterface $renderer,
private CollectionPreparationInterface $classCollectionPreparation,
private LoggerInterface $logger
) {
}

Expand Down
2 changes: 1 addition & 1 deletion src/GeneratorFacade.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
class GeneratorFacade implements GeneratorFacadeInterface
{
public function __construct(
private readonly DependencyInjectionInterface $dependencyInjection
private DependencyInjectionInterface $dependencyInjection
) {
}

Expand Down
4 changes: 2 additions & 2 deletions src/Helper/ClassMetadataHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ class ClassMetadataHelper implements ClassMetadataHelperInterface
* @param string $classSuffix
*/
public function __construct(
private readonly string $namespaceGeneral,
private readonly string $classSuffix
private string $namespaceGeneral,
private string $classSuffix
) {
}

Expand Down
2 changes: 1 addition & 1 deletion src/Merger/Merger.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Merger implements MergerInterface
/**
* @param array<int, mixed> $classCollection
*/
public function __construct(private readonly array $classCollection)
public function __construct(private array $classCollection)
{
}

Expand Down
2 changes: 1 addition & 1 deletion src/Preparation/CollectionPreparation.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class CollectionPreparation implements CollectionPreparationInterface
/**
* @param iterable<PreparationProcessorInterface> $preparationProcessor
*/
public function __construct(private readonly iterable $preparationProcessor)
public function __construct(private iterable $preparationProcessor)
{
}

Expand Down
2 changes: 1 addition & 1 deletion src/Preparation/Processor/ClassNameProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

class ClassNameProcessor implements PreparationProcessorInterface
{
public function __construct(private readonly ClassMetadataHelperInterface $classMetadataHelper)
public function __construct(private ClassMetadataHelperInterface $classMetadataHelper)
{
}

Expand Down
2 changes: 1 addition & 1 deletion src/Preparation/Processor/ClassPropertyProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ClassPropertyProcessor implements PreparationProcessorInterface
/**
* @param iterable<PropertyProcessorInterface> $propertyProcessorCollection
*/
public function __construct(private readonly iterable $propertyProcessorCollection)
public function __construct(private iterable $propertyProcessorCollection)
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

class MethodAttributesMetadataProcessor implements PreparationProcessorInterface
{
public function __construct(private readonly NameNormalizerInterface $nameNormalizer)
public function __construct(private NameNormalizerInterface $nameNormalizer)
{
}

Expand Down
Loading

0 comments on commit 8a4bff6

Please sign in to comment.