Skip to content

Commit

Permalink
Добавил контейнер в карты #4
Browse files Browse the repository at this point in the history
  • Loading branch information
alexpts committed May 28, 2020
1 parent 7818c16 commit 2832de7
Show file tree
Hide file tree
Showing 8 changed files with 197 additions and 60 deletions.
38 changes: 37 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ return [
'email' => [
'pipe' => [
[
'populate' => 'strtolower',
'populate' => 'strtolower', // any callable
'extract' => 'strtoupper'
]
]
Expand Down Expand Up @@ -122,3 +122,39 @@ $model2 = $dataTransformer->toModel(UserModel::class, [
]
], 'deepDto');
```


### Логика в pipe обработчиках
Обработчики pipe позволяют описывать callable методы и писать любую логику, которая будет применяться к значению.
В pipe фильтрах можно кастить типы например. Либо шифровать поля перед записью в БД.
В случае необходимости, чтобы вся логика маппинга была в 1 месте, вы может прокинуть любые зависимости через замыкание
в функцию pipe, доставл ее из контейнера.

```php
<?php
/**
* @var MapsManager $this
*/

use PTS\DataTransformer\MapsManager;

$encrypter = $this->getContainer()->get('encrypter');

return [
'id' => [],
'creAt' => [],
'name' => [],
'password' => [
'pipe' => [
[
'extract' => function(string $openPassword) use($encrypter) {
return $encrypter->encrypt($openPassword, false);
},
'populate' => static function(string $ePassword) use($encrypter) {
return $encrypter->decrypt($ePassword, false);
},
]
]
],

];
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"minimum-stability": "stable",
"require": {
"php": "^7.4",
"alexpts/php-hydrator": "^3.0"
"alexpts/php-hydrator": "^3.0",
"psr/container": "^1.0"
},
"require-dev": {
"fzaninotto/faker": "^1.9",
Expand Down
51 changes: 50 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 21 additions & 1 deletion src/MapsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,34 @@

namespace PTS\DataTransformer;

use Psr\Container\ContainerInterface;

class MapsManager
{
protected array $cache = [];
/** @var string[] */
protected array $mapsDirs = [];
protected NormalizerInterface $normalizer;
protected string $defaultMapsDirs = '';
protected ?ContainerInterface $container = null;

public function __construct(NormalizerInterface $normalizer = null, string $dir = '')
{
$this->normalizer = $normalizer ?? new Normalizer;
$this->setDefaultMapDir($dir);
}

public function setContainer(ContainerInterface $container): self
{
$this->container = $container;
return $this;
}

public function getContainer(): ?ContainerInterface
{
return $this->container;
}

public function setDefaultMapDir(string $dir): void
{
$this->defaultMapsDirs = $dir;
Expand All @@ -32,13 +46,19 @@ public function getMap(string $entityName, string $mapName = 'dto'): array
$map = $this->cache[$entityName][$mapName] ?? null;
if ($map === null) {
$dir = $this->getMapDir($entityName);
$rules = require $dir.DIRECTORY_SEPARATOR.$mapName.'.php';
$rules = $this->includeMap($dir.DIRECTORY_SEPARATOR.$mapName.'.php');
$this->setMap($rules, $entityName, $mapName);
}

return $this->cache[$entityName][$mapName];
}

protected function includeMap(string $file): array
{
return require $file;
}


public function getMapDir(string $entityName): string
{
$dir = $this->mapsDirs[$entityName] ?? null;
Expand Down
99 changes: 54 additions & 45 deletions test/unit/MapsManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,52 +5,61 @@
use PTS\DataTransformer\MapsManager;

require_once __DIR__ . '/data/UserModel.php';
require_once __DIR__ . '/data/Container.php';

class MapsManagerTest extends TestCase
{
protected MapsManager $manager;

public function setUp(): void
{
$this->manager = new MapsManager;
}

public function testSetMapDir(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$result = $this->manager->getMap('model.user');
self::assertNotNull($result);
}

public function testGetMap(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$map = $this->manager->getMap('model.user');
self::assertCount(3, $map);
self::assertCount(6, $map['rules']);
self::assertCount(2, $map['pipe']);
self::assertCount(0, $map['refs']);
}

public function testGetMapWithCache(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$map = $this->manager->getMap('model.user');
$map2 = $this->manager->getMap('model.user');
self::assertCount(3, $map2);
self::assertCount(6, $map2['rules']);
self::assertCount(2, $map2['pipe']);
self::assertCount(0, $map2['refs']);
self::assertSame($map, $map2);
}

public function testGetMapFromDefaultDir(): void
{
$this->manager->setDefaultMapDir(__DIR__ . '/data');
$map = $this->manager->getMap('Namespace\UserModel');
self::assertCount(3, $map);
self::assertCount(6, $map['rules']);
self::assertCount(2, $map['pipe']);
self::assertCount(0, $map['refs']);
}
protected MapsManager $manager;

public function setUp(): void
{
$this->manager = new MapsManager;
}

public function testSetMapDir(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$result = $this->manager->getMap('model.user');
self::assertNotNull($result);
}

public function testGetMap(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$map = $this->manager->getMap('model.user');
self::assertCount(3, $map);
self::assertCount(6, $map['rules']);
self::assertCount(2, $map['pipe']);
self::assertCount(0, $map['refs']);
}

public function testGetMapWithCache(): void
{
$this->manager->setMapDir('model.user', __DIR__ . '/data');
$map = $this->manager->getMap('model.user');
$map2 = $this->manager->getMap('model.user');
self::assertCount(3, $map2);
self::assertCount(6, $map2['rules']);
self::assertCount(2, $map2['pipe']);
self::assertCount(0, $map2['refs']);
self::assertSame($map, $map2);
}

public function testGetMapFromDefaultDir(): void
{
$this->manager->setDefaultMapDir(__DIR__ . '/data');
$map = $this->manager->getMap('Namespace\UserModel');
self::assertCount(3, $map);
self::assertCount(6, $map['rules']);
self::assertCount(2, $map['pipe']);
self::assertCount(0, $map['refs']);
}

public function testContainer(): void
{
$container = new Container;
$this->manager->setContainer($container);
$value = $this->manager->getContainer()->get('any');
static::assertSame(1, $value);
}
}
19 changes: 19 additions & 0 deletions test/unit/data/Container.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);

use Psr\Container\ContainerInterface;

class Container implements ContainerInterface
{

public function get($id)
{
$mock = 1;
return $mock;
}

public function has($id)
{
return true;
}
}
20 changes: 9 additions & 11 deletions test/unit/data/UserModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,20 @@

namespace PTS\DataTransformer;

use DateTimeInterface;

class UserModel
{
protected $id;
protected string $name = '';
/** @var string */
protected $name;
/** @var string */
protected $login;
/** @var \DateTime */
protected $creAt;
/** @var bool */
protected $active;

/** @var UserModel|null */
public $refModel;
protected string $login;
protected DateTimeInterface $creAt;
protected bool $active;

public ?UserModel $refModel = null;
/** @var UserModel[] */
public $refModels = [];
public array $refModels = [];

public function __construct()
{
Expand Down
5 changes: 5 additions & 0 deletions test/unit/data/dto.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
<?php
/**
* @var MapsManager $this
*/

use PTS\DataTransformer\MapsManager;

return [
'id' => [],
Expand Down

0 comments on commit 2832de7

Please sign in to comment.