Skip to content

Commit e5f35c6

Browse files
authored
Merge pull request #5 from alexpts/v6
Change pipes
2 parents a863718 + fbc2a76 commit e5f35c6

File tree

9 files changed

+124
-95
lines changed

9 files changed

+124
-95
lines changed

.scrutinizer.yml

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,17 @@
11
filter:
2-
paths:
3-
- 'src/*'
4-
checks:
5-
php:
6-
uppercase_constants: true
7-
simplify_boolean_return: true
8-
return_doc_comments: true
9-
properties_in_camelcaps: true
10-
phpunit_assertions: true
11-
parameters_in_camelcaps: true
12-
parameter_doc_comments: true
13-
14-
coding_style:
15-
php: { }
16-
17-
tools:
18-
external_code_coverage: false
2+
paths: ['src/*']
193

204
build:
215
environment:
226
php:
237
version: 8.0
24-
258
tests:
269
override:
27-
-
28-
command: 'vendor/bin/phpunit --configuration ./test/phpunit.xml --coverage-clover=test/clover.xml'
10+
- php-scrutinizer-run --enable-security-analysis
11+
- command: 'XDEBUG_MODE=coverage ./vendor/bin/phpunit --config test/phpunit.xml --coverage-clover=test/clover.xml'
2912
coverage:
3013
file: 'test/clover.xml'
3114
format: 'clover'
15+
16+
tools:
17+
external_code_coverage: false

README.md

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
представить в виде строки в формате ISO8601.
3232

3333
```php
34+
use PTS\DataTransformer\DataTransformer;
35+
3436
$dataTransformer = new DataTransformer;
3537
$dataTransformer->getMapsManager()->setMapDir(UserModel::class, __DIR__ . '/data');
3638

@@ -45,7 +47,7 @@ $dto = $dataTransformer->toDTO($model, 'dto');
4547
$dtoForDb = $dataTransformer->toDTO($model, 'db');
4648
```
4749

48-
А еще у нас может быть просто более компактное представлеиние этой же модели, без лишних деталей.
50+
А еще может быть просто более компактное представлеиние этой же модели, без лишних деталей.
4951

5052
```php
5153
$shortFormatDto = $dataTransformer->toDTO($model, 'short.dto');
@@ -59,7 +61,7 @@ $shortFormatDto = $dataTransformer->toDTO($model, 'short.dto');
5961
$mapName = 'dto';
6062
$excludedFields = ['name'];
6163
$dtoCollection = $dataTransformer->toDtoCollection($models, $mapName, [
62-
'excludeFields' => $excludedFields
64+
'excludeFields' => $excludedFields
6365
]);
6466
```
6567

@@ -76,15 +78,14 @@ return [
7678
'name' => [],
7779
'login' => [],
7880
'active' => [
79-
'pipe' => ['boolval']
81+
'pipe-populate' => ['boolval'],
82+
'pipe-extract' => ['boolval'],
8083
],
8184
'email' => [
82-
'pipe' => [
83-
[
84-
'populate' => 'strtolower', // any callable
85-
'extract' => 'strtoupper'
86-
]
87-
]
85+
'pipe-populate' => [ // any callable
86+
'strval',
87+
'strtolower',
88+
]
8889
],
8990
'refModel' => [
9091
'ref' => [
@@ -134,8 +135,8 @@ $model2 = $dataTransformer->toModel(UserModel::class, [
134135
### Логика в pipe обработчиках
135136

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

140141
```php
141142
<?php
@@ -152,16 +153,22 @@ return [
152153
'creAt' => [],
153154
'name' => [],
154155
'password' => [
155-
'pipe' => [
156-
[
157-
'extract' => function(string $openPassword) use($encrypter) {
158-
return $encrypter->encrypt($openPassword, false);
159-
},
160-
'populate' => static function(string $ePassword) use($encrypter) {
161-
return $encrypter->decrypt($ePassword, false);
162-
},
163-
]
164-
]
156+
'pipe-populate' => [
157+
'strtolower',
158+
function(string $openPassword) use($encrypter) {
159+
return $encrypter->encrypt($openPassword);
160+
},
161+
],
162+
'pipe-extract' => [
163+
function(string $ePassword) use($encrypter) {
164+
return $encrypter->decrypt($ePassword);
165+
},
166+
'strtolower'
165167
],
168+
];
169+
170+
171+
### migrates
172+
173+
[update 5 to 6](https://github.com/alexpts/php-data-transformer2/blob/master/docs/migrate5to6.md)
166174

167-
];

docs/migrate5to6.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Migrate 5 to 6
2+
3+
Change pipe format in map:
4+
```php
5+
// 5
6+
$mapOld = [
7+
'active' => [
8+
'pipe' => [
9+
[
10+
'populate' => 'boolval',
11+
'extract' => 'boolval',
12+
]
13+
]
14+
],
15+
'email' => [
16+
'pipe-populate' => ['strtolower'],
17+
'pipe-extract' => ['strtolower'],
18+
'pipe' => [
19+
'strtolower'
20+
]
21+
],
22+
];
23+
24+
// 6
25+
$mapNew = [
26+
'active' => [
27+
'pipe-populate' => [
28+
'boolval',
29+
],
30+
'pipe-extract' => [
31+
'boolval',
32+
]
33+
],
34+
'email' => [
35+
'pipe-populate' => ['strtolower'],
36+
'pipe-extract' => ['strtolower'],
37+
],
38+
];
39+
40+
```

src/DataTransformer.php

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,9 @@
66
use PTS\Hydrator\ExtractorInterface;
77
use PTS\Hydrator\Hydrator;
88
use PTS\Hydrator\HydratorInterface;
9-
use function get_class;
10-
use function is_callable;
119

1210
class DataTransformer implements DataTransformerInterface
1311
{
14-
protected const FILTER_TYPE_POPULATE = 'populate';
15-
protected const FILTER_TYPE_EXTRACT = 'extract';
16-
1712
protected ExtractorInterface $extractor;
1813
protected HydratorInterface $hydrator;
1914
protected MapsManager $mapsManager;
@@ -37,19 +32,16 @@ public function toModel(string $class, array $dto, string $mapName = 'dto'): obj
3732
{
3833
$map = $this->mapsManager->getMap($class, $mapName);
3934
$dto = $map['refs'] ? $this->resolveRefPopulate($dto, $map['refs']) : $dto;
40-
$dto = $map['pipe'] ? $this->applyPipes($dto, $map['pipe']) : $dto;
35+
$dto = $map['pipe-populate'] ? $this->pipes($dto, $map['pipe-populate']) : $dto;
4136
return $this->hydrator->hydrate($dto, $class, $map['rules']);
4237
}
4338

4439
public function toModelsCollection(string $model, iterable $dtoCollection, string $mapType = 'dto'): array
4540
{
46-
$map = $this->mapsManager->getMap($model, $mapType);
47-
4841
$models = [];
49-
foreach ($dtoCollection as $dto) {
50-
$dto = $map['refs'] ? $this->resolveRefPopulate($dto, $map['refs']) : $dto;
51-
$dto = $map['pipe'] ? $this->applyPipes($dto, $map['pipe']) : $dto;
52-
$models[] = $this->hydrator->hydrate($dto, $model, $map['rules']);
42+
foreach ($dtoCollection as $key => $dto) {
43+
$dto = $this->toModel($model, $dto, $mapType);
44+
$models[$key] = $dto;
5345
}
5446

5547
return $models;
@@ -59,7 +51,7 @@ public function fillModel(object $model, array $dto, string $mapName = 'dto'): o
5951
{
6052
$map = $this->mapsManager->getMap($model::class, $mapName);
6153
$dto = $map['refs'] ? $this->resolveRefPopulate($dto, $map['refs']) : $dto;
62-
$dto = $map['pipe'] ? $this->applyPipes($dto, $map['pipe']) : $dto;
54+
$dto = $map['pipe-populate'] ? $this->pipes($dto, $map['pipe-populate']) : $dto;
6355
$this->hydrator->hydrateModel($dto, $model, $map['rules']);
6456

6557
return $model;
@@ -86,7 +78,7 @@ public function toDTO(object $model, string $mapName = 'dto', array $options = [
8678
}
8779

8880
$dto = $this->extractor->extract($model, $map['rules']);
89-
$dto = $map['pipe'] ? $this->applyPipes($dto, $map['pipe'], self::FILTER_TYPE_EXTRACT) : $dto;
81+
$dto = $map['pipe-extract'] ? $this->pipes($dto, $map['pipe-extract']) : $dto;
9082
return $map['refs'] ? $this->resolveRefExtract($dto, $map['refs']) : $dto;
9183
}
9284

@@ -124,28 +116,18 @@ protected function resolveRefPopulate(array $dto, array $refsRules): array
124116
return $dto;
125117
}
126118

127-
protected function applyPipes(array $dto, array $pipes, string $type = self::FILTER_TYPE_POPULATE): array
119+
protected function pipes(array $dto, array $pipes): array
128120
{
129121
$fieldsPipes = array_intersect_key($pipes, $dto);
130122
foreach ($fieldsPipes as $name => $filters) {
131123
$value = $dto[$name] ?? null;
132-
$dto[$name] = $this->applyFilters($value, $filters, $type);
133-
}
134-
135-
return $dto;
136-
}
137-
138-
protected function applyFilters($value, array $filters, string $type): mixed
139-
{
140-
foreach ($filters as $filter) {
141-
if (is_callable($filter)) {
124+
foreach ($filters as $filter) {
142125
$value = $filter($value);
143-
continue;
144126
}
145127

146-
$value = ($filter[$type] ?? false) ? $filter[$type]($value) : $value;
128+
$dto[$name] = $value;
147129
}
148130

149-
return $value;
131+
return $dto;
150132
}
151133
}

src/Normalizer.php

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,22 @@ class Normalizer implements NormalizerInterface
99
public function normalize(array $rules): array
1010
{
1111
$map = [
12-
'pipe' => [],
12+
'pipe-populate' => [],
13+
'pipe-extract' => [],
1314
'rules' => $rules,
1415
'refs' => [],
1516
];
1617

1718
foreach ($map['rules'] as $name => &$rule) {
1819
$rule['prop'] ??= $name;
1920
$map['refs'][$name] = $rule['ref'] ?? null;
20-
$map['pipe'][$name] = $rule['pipe'] ?? null;
21+
$map['pipe-populate'][$name] = $rule['pipe-populate'] ?? null;
22+
$map['pipe-extract'][$name] = $rule['pipe-extract'] ?? null;
2123
}
2224

2325
$map['refs'] = array_filter($map['refs']);
24-
$map['pipe'] = array_filter($map['pipe']);
26+
$map['pipe-populate'] = array_filter($map['pipe-populate']);
27+
$map['pipe-extract'] = array_filter($map['pipe-extract']);
2528

2629
return $map;
2730
}

test/unit/MapsManagerTest.php

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ public function testGetMap(): void
2727
{
2828
$this->manager->setMapDir('model.user', __DIR__ . '/data');
2929
$map = $this->manager->getMap('model.user');
30-
static::assertCount(3, $map);
30+
static::assertCount(4, $map);
3131
static::assertCount(6, $map['rules']);
32-
static::assertCount(2, $map['pipe']);
32+
static::assertCount(2, $map['pipe-populate']);
33+
static::assertCount(2, $map['pipe-extract']);
3334
static::assertCount(0, $map['refs']);
3435
}
3536

@@ -38,9 +39,10 @@ public function testGetMapWithCache(): void
3839
$this->manager->setMapDir('model.user', __DIR__ . '/data');
3940
$map = $this->manager->getMap('model.user');
4041
$map2 = $this->manager->getMap('model.user');
41-
static::assertCount(3, $map2);
42+
static::assertCount(4, $map2);
4243
static::assertCount(6, $map2['rules']);
43-
static::assertCount(2, $map2['pipe']);
44+
static::assertCount(2, $map2['pipe-populate']);
45+
static::assertCount(2, $map2['pipe-extract']);
4446
static::assertCount(0, $map2['refs']);
4547
static::assertSame($map, $map2);
4648
}
@@ -49,9 +51,10 @@ public function testGetMapFromDefaultDir(): void
4951
{
5052
$this->manager->setDefaultMapDir(__DIR__ . '/data');
5153
$map = $this->manager->getMap('Namespace\UserModel');
52-
static::assertCount(3, $map);
54+
static::assertCount(4, $map);
5355
static::assertCount(6, $map['rules']);
54-
static::assertCount(2, $map['pipe']);
56+
static::assertCount(2, $map['pipe-populate']);
57+
static::assertCount(2, $map['pipe-extract']);
5558
static::assertCount(0, $map['refs']);
5659
}
5760

test/unit/data/UserModel/dto.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,27 @@
66
'name' => [],
77
'login' => [],
88
'active' => [
9-
'pipe' => [
10-
[
11-
'populate' => 'boolval',
12-
'extract' => 'boolval',
13-
]
9+
// 'pipe' => [
10+
// [
11+
// 'populate' => 'boolval',
12+
// 'extract' => 'boolval',
13+
// ],
14+
// ],
15+
'pipe-populate' => [
16+
'boolval'
17+
],
18+
'pipe-extract' => [
19+
'boolval'
1420
]
1521
],
1622
'email' => [
17-
'pipe' => [
23+
// 'pipe' => [
24+
// 'strtolower',
25+
// ],
26+
'pipe-populate' => [
27+
'strtolower'
28+
],
29+
'pipe-extract' => [
1830
'strtolower'
1931
]
2032
],

test/unit/data/dto.php

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,11 @@
1111
'name' => [],
1212
'login' => [],
1313
'active' => [
14-
'pipe' => [
15-
[
16-
'populate' => 'boolval',
17-
'extract' => 'boolval',
18-
]
19-
]
14+
'pipe-populate' => ['boolval'],
15+
'pipe-extract' => ['boolval'],
2016
],
2117
'email' => [
22-
'pipe' => [
23-
'strtolower'
24-
]
18+
'pipe-populate' => ['strtolower'],
19+
'pipe-extract' => ['strtolower'],
2520
],
2621
];

test/unit/data/withRefs.map.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
'name' => [],
99
'login' => [],
1010
'active' => [
11-
'pipe' => ['boolval']
11+
'pipe-populate' => ['boolval'],
12+
'pipe-extract' => ['boolval'],
1213
],
1314
'email' => [],
1415
'refModel' => [

0 commit comments

Comments
 (0)