1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace WyriHaximus\Travis\Transport; |
5
|
|
|
|
6
|
|
|
use GeneratedHydrator\Configuration; |
7
|
|
|
use WyriHaximus\Travis\Resource\RepositoryInterface; |
8
|
|
|
use WyriHaximus\Travis\Resource\ResourceInterface; |
9
|
|
|
|
10
|
|
|
class Hydrator |
11
|
|
|
{ |
12
|
|
|
const RESOURCE_NAMESPACE = 'WyriHaximus\Travis\Resource\\'; |
13
|
|
|
|
14
|
|
|
protected $options; |
15
|
|
|
protected $transport; |
16
|
|
|
protected $hydrators = []; |
17
|
|
|
|
18
|
44 |
|
public function __construct(Client $transport, array $options) |
19
|
|
|
{ |
20
|
44 |
|
$this->transport = $transport; |
21
|
44 |
|
$this->options = $options; |
22
|
44 |
|
} |
23
|
|
|
|
24
|
44 |
|
public function hydrateFQCN($class, $json): ResourceInterface |
25
|
|
|
{ |
26
|
44 |
|
return $this->getHydrator($class)->hydrate($json, $this->createObject($class)); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function hydrate($class, $json): ResourceInterface |
30
|
|
|
{ |
31
|
|
|
$fullClassName = self::RESOURCE_NAMESPACE . $this->options['resource_namespace'] . '\\' . $class; |
32
|
|
|
return $this->hydrateFQCN($fullClassName, $json); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
public function extractFQCN($class, $object): array |
36
|
|
|
{ |
37
|
|
|
return $this->getHydrator($class)->extract($object); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function extract($class, $object): array |
41
|
|
|
{ |
42
|
|
|
$fullClassName = self::RESOURCE_NAMESPACE . $this->options['resource_namespace'] . '\\' . $class; |
43
|
|
|
return $this->extractFQCN($fullClassName, $object); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function buildAsyncFromSync($resource, $object): RepositoryInterface |
47
|
|
|
{ |
48
|
|
|
return $this->hydrateFQCN( |
49
|
|
|
static::RESOURCE_NAMESPACE . 'Async\\' . $resource, |
50
|
|
|
$this->extractFQCN( |
51
|
|
|
static::RESOURCE_NAMESPACE . 'Sync\\' . $resource, |
52
|
|
|
$object |
53
|
|
|
) |
54
|
|
|
); |
55
|
|
|
} |
56
|
|
|
|
57
|
44 |
|
protected function getHydrator($class) |
58
|
|
|
{ |
59
|
44 |
|
if (isset($this->hydrators[$class])) { |
60
|
|
|
return $this->hydrators[$class]; |
61
|
|
|
} |
62
|
|
|
|
63
|
44 |
|
$config = new Configuration($class); |
64
|
44 |
|
if (isset($this->options['resource_hydrator_cache_dir'])) { |
65
|
|
|
$config->setGeneratedClassesTargetDir($this->options['resource_hydrator_cache_dir']); |
66
|
|
|
} |
67
|
44 |
|
$hydrator = $config->createFactory()->getHydratorClass(); |
68
|
44 |
|
$this->hydrators[$class] = new $hydrator; |
69
|
|
|
|
70
|
44 |
|
return $this->hydrators[$class]; |
71
|
|
|
} |
72
|
|
|
|
73
|
44 |
|
protected function createObject($class): ResourceInterface |
74
|
|
|
{ |
75
|
44 |
|
$object = new $class(); |
76
|
44 |
|
$object->setTransport($this->transport); |
77
|
44 |
|
return $object; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|