Skip to content

Commit 2832de7

Browse files
committed
Добавил контейнер в карты #4
1 parent 7818c16 commit 2832de7

File tree

8 files changed

+197
-60
lines changed

8 files changed

+197
-60
lines changed

README.md

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ return [
7373
'email' => [
7474
'pipe' => [
7575
[
76-
'populate' => 'strtolower',
76+
'populate' => 'strtolower', // any callable
7777
'extract' => 'strtoupper'
7878
]
7979
]
@@ -122,3 +122,39 @@ $model2 = $dataTransformer->toModel(UserModel::class, [
122122
]
123123
], 'deepDto');
124124
```
125+
126+
127+
### Логика в pipe обработчиках
128+
Обработчики pipe позволяют описывать callable методы и писать любую логику, которая будет применяться к значению.
129+
В pipe фильтрах можно кастить типы например. Либо шифровать поля перед записью в БД.
130+
В случае необходимости, чтобы вся логика маппинга была в 1 месте, вы может прокинуть любые зависимости через замыкание
131+
в функцию pipe, доставл ее из контейнера.
132+
133+
```php
134+
<?php
135+
/**
136+
* @var MapsManager $this
137+
*/
138+
139+
use PTS\DataTransformer\MapsManager;
140+
141+
$encrypter = $this->getContainer()->get('encrypter');
142+
143+
return [
144+
'id' => [],
145+
'creAt' => [],
146+
'name' => [],
147+
'password' => [
148+
'pipe' => [
149+
[
150+
'extract' => function(string $openPassword) use($encrypter) {
151+
return $encrypter->encrypt($openPassword, false);
152+
},
153+
'populate' => static function(string $ePassword) use($encrypter) {
154+
return $encrypter->decrypt($ePassword, false);
155+
},
156+
]
157+
]
158+
],
159+
160+
];

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
"minimum-stability": "stable",
2525
"require": {
2626
"php": "^7.4",
27-
"alexpts/php-hydrator": "^3.0"
27+
"alexpts/php-hydrator": "^3.0",
28+
"psr/container": "^1.0"
2829
},
2930
"require-dev": {
3031
"fzaninotto/faker": "^1.9",

composer.lock

Lines changed: 50 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/MapsManager.php

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,34 @@
33

44
namespace PTS\DataTransformer;
55

6+
use Psr\Container\ContainerInterface;
7+
68
class MapsManager
79
{
810
protected array $cache = [];
911
/** @var string[] */
1012
protected array $mapsDirs = [];
1113
protected NormalizerInterface $normalizer;
1214
protected string $defaultMapsDirs = '';
15+
protected ?ContainerInterface $container = null;
1316

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

23+
public function setContainer(ContainerInterface $container): self
24+
{
25+
$this->container = $container;
26+
return $this;
27+
}
28+
29+
public function getContainer(): ?ContainerInterface
30+
{
31+
return $this->container;
32+
}
33+
2034
public function setDefaultMapDir(string $dir): void
2135
{
2236
$this->defaultMapsDirs = $dir;
@@ -32,13 +46,19 @@ public function getMap(string $entityName, string $mapName = 'dto'): array
3246
$map = $this->cache[$entityName][$mapName] ?? null;
3347
if ($map === null) {
3448
$dir = $this->getMapDir($entityName);
35-
$rules = require $dir.DIRECTORY_SEPARATOR.$mapName.'.php';
49+
$rules = $this->includeMap($dir.DIRECTORY_SEPARATOR.$mapName.'.php');
3650
$this->setMap($rules, $entityName, $mapName);
3751
}
3852

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

56+
protected function includeMap(string $file): array
57+
{
58+
return require $file;
59+
}
60+
61+
4262
public function getMapDir(string $entityName): string
4363
{
4464
$dir = $this->mapsDirs[$entityName] ?? null;

test/unit/MapsManagerTest.php

Lines changed: 54 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -5,52 +5,61 @@
55
use PTS\DataTransformer\MapsManager;
66

77
require_once __DIR__ . '/data/UserModel.php';
8+
require_once __DIR__ . '/data/Container.php';
89

910
class MapsManagerTest extends TestCase
1011
{
11-
protected MapsManager $manager;
12-
13-
public function setUp(): void
14-
{
15-
$this->manager = new MapsManager;
16-
}
17-
18-
public function testSetMapDir(): void
19-
{
20-
$this->manager->setMapDir('model.user', __DIR__ . '/data');
21-
$result = $this->manager->getMap('model.user');
22-
self::assertNotNull($result);
23-
}
24-
25-
public function testGetMap(): void
26-
{
27-
$this->manager->setMapDir('model.user', __DIR__ . '/data');
28-
$map = $this->manager->getMap('model.user');
29-
self::assertCount(3, $map);
30-
self::assertCount(6, $map['rules']);
31-
self::assertCount(2, $map['pipe']);
32-
self::assertCount(0, $map['refs']);
33-
}
34-
35-
public function testGetMapWithCache(): void
36-
{
37-
$this->manager->setMapDir('model.user', __DIR__ . '/data');
38-
$map = $this->manager->getMap('model.user');
39-
$map2 = $this->manager->getMap('model.user');
40-
self::assertCount(3, $map2);
41-
self::assertCount(6, $map2['rules']);
42-
self::assertCount(2, $map2['pipe']);
43-
self::assertCount(0, $map2['refs']);
44-
self::assertSame($map, $map2);
45-
}
46-
47-
public function testGetMapFromDefaultDir(): void
48-
{
49-
$this->manager->setDefaultMapDir(__DIR__ . '/data');
50-
$map = $this->manager->getMap('Namespace\UserModel');
51-
self::assertCount(3, $map);
52-
self::assertCount(6, $map['rules']);
53-
self::assertCount(2, $map['pipe']);
54-
self::assertCount(0, $map['refs']);
55-
}
12+
protected MapsManager $manager;
13+
14+
public function setUp(): void
15+
{
16+
$this->manager = new MapsManager;
17+
}
18+
19+
public function testSetMapDir(): void
20+
{
21+
$this->manager->setMapDir('model.user', __DIR__ . '/data');
22+
$result = $this->manager->getMap('model.user');
23+
self::assertNotNull($result);
24+
}
25+
26+
public function testGetMap(): void
27+
{
28+
$this->manager->setMapDir('model.user', __DIR__ . '/data');
29+
$map = $this->manager->getMap('model.user');
30+
self::assertCount(3, $map);
31+
self::assertCount(6, $map['rules']);
32+
self::assertCount(2, $map['pipe']);
33+
self::assertCount(0, $map['refs']);
34+
}
35+
36+
public function testGetMapWithCache(): void
37+
{
38+
$this->manager->setMapDir('model.user', __DIR__ . '/data');
39+
$map = $this->manager->getMap('model.user');
40+
$map2 = $this->manager->getMap('model.user');
41+
self::assertCount(3, $map2);
42+
self::assertCount(6, $map2['rules']);
43+
self::assertCount(2, $map2['pipe']);
44+
self::assertCount(0, $map2['refs']);
45+
self::assertSame($map, $map2);
46+
}
47+
48+
public function testGetMapFromDefaultDir(): void
49+
{
50+
$this->manager->setDefaultMapDir(__DIR__ . '/data');
51+
$map = $this->manager->getMap('Namespace\UserModel');
52+
self::assertCount(3, $map);
53+
self::assertCount(6, $map['rules']);
54+
self::assertCount(2, $map['pipe']);
55+
self::assertCount(0, $map['refs']);
56+
}
57+
58+
public function testContainer(): void
59+
{
60+
$container = new Container;
61+
$this->manager->setContainer($container);
62+
$value = $this->manager->getContainer()->get('any');
63+
static::assertSame(1, $value);
64+
}
5665
}

test/unit/data/Container.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
declare(strict_types=1);
3+
4+
use Psr\Container\ContainerInterface;
5+
6+
class Container implements ContainerInterface
7+
{
8+
9+
public function get($id)
10+
{
11+
$mock = 1;
12+
return $mock;
13+
}
14+
15+
public function has($id)
16+
{
17+
return true;
18+
}
19+
}

test/unit/data/UserModel.php

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,20 @@
33

44
namespace PTS\DataTransformer;
55

6+
use DateTimeInterface;
7+
68
class UserModel
79
{
810
protected $id;
11+
protected string $name = '';
912
/** @var string */
10-
protected $name;
11-
/** @var string */
12-
protected $login;
13-
/** @var \DateTime */
14-
protected $creAt;
15-
/** @var bool */
16-
protected $active;
17-
18-
/** @var UserModel|null */
19-
public $refModel;
13+
protected string $login;
14+
protected DateTimeInterface $creAt;
15+
protected bool $active;
16+
17+
public ?UserModel $refModel = null;
2018
/** @var UserModel[] */
21-
public $refModels = [];
19+
public array $refModels = [];
2220

2321
public function __construct()
2422
{

test/unit/data/dto.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
<?php
2+
/**
3+
* @var MapsManager $this
4+
*/
5+
6+
use PTS\DataTransformer\MapsManager;
27

38
return [
49
'id' => [],

0 commit comments

Comments
 (0)