1
|
|
|
<?php |
2
|
|
|
namespace PTS\DataTransformer; |
3
|
|
|
|
4
|
|
|
use Symfony\Component\Yaml\Exception\ParseException; |
5
|
|
|
|
6
|
|
|
class DataTransformer implements DataTransformerInterface |
7
|
|
|
{ |
8
|
|
|
/** @var ModelClosure */ |
9
|
|
|
protected $closuresFn; |
10
|
|
|
/** @var TypeConverter */ |
11
|
|
|
protected $typeConverter; |
12
|
|
|
/** @var MapsManager */ |
13
|
|
|
protected $mapsManager; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @param TypeConverter $converter |
17
|
|
|
* @param MapsManager $mapsManager |
18
|
|
|
* @param ModelClosure $closuresFn |
19
|
|
|
*/ |
20
|
4 |
|
public function __construct(TypeConverter $converter, MapsManager $mapsManager, ModelClosure $closuresFn) |
21
|
|
|
{ |
22
|
4 |
|
$this->mapsManager = $mapsManager; |
23
|
4 |
|
$this->typeConverter = $converter; |
24
|
4 |
|
$this->closuresFn = $closuresFn; |
25
|
4 |
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @return MapsManager |
29
|
|
|
*/ |
30
|
4 |
|
public function getMapsManager() |
31
|
|
|
{ |
32
|
4 |
|
return $this->mapsManager; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* @param ModelInterface $model |
37
|
|
|
* @param string $mapType |
38
|
|
|
* @return array |
39
|
|
|
* |
40
|
|
|
* @throws ParseException |
41
|
|
|
*/ |
42
|
2 |
View Code Duplication |
public function getData(ModelInterface $model, $mapType = 'dto') |
|
|
|
|
43
|
|
|
{ |
44
|
2 |
|
$class = get_class($model); |
45
|
2 |
|
$fn = \Closure::bind($this->closuresFn->getToDataFn(), $model, $class); |
46
|
2 |
|
$map = $this->mapsManager->getMap($class, $mapType); |
47
|
2 |
|
return $fn($map, $this->typeConverter); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param array $data |
52
|
|
|
* @param ModelInterface $model |
53
|
|
|
* @param string $mapType |
54
|
|
|
* |
55
|
|
|
* @throws ParseException |
56
|
|
|
*/ |
57
|
1 |
View Code Duplication |
public function fillModel(array $data, ModelInterface $model, $mapType = 'dto') |
|
|
|
|
58
|
|
|
{ |
59
|
1 |
|
$class = get_class($model); |
60
|
1 |
|
$fn = \Closure::bind($this->closuresFn->getFillFn(), $model, $class); |
61
|
1 |
|
$map = $this->mapsManager->getMap($class, $mapType); |
62
|
1 |
|
$fn($data, $map, $this->typeConverter); |
63
|
1 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $class |
67
|
|
|
* @return ModelInterface |
68
|
|
|
*/ |
69
|
1 |
|
public function createModel($class) |
70
|
|
|
{ |
71
|
1 |
|
$emptyModel = new \ReflectionClass($class); |
72
|
1 |
|
return $emptyModel->newInstanceWithoutConstructor(); |
73
|
|
|
} |
74
|
|
|
} |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.