1
|
|
|
<?php |
2
|
|
|
/****************************************************************************** |
3
|
|
|
* Copyright (c) 2017 Constantin Galbenu <[email protected]> * |
4
|
|
|
******************************************************************************/ |
5
|
|
|
|
6
|
|
|
namespace Gica\Serialize\ObjectHydrator\AdapterLocator; |
7
|
|
|
|
8
|
|
|
|
9
|
|
|
use Gica\Serialize\ObjectHydrator\Exception\AdapterNotFoundException; |
10
|
|
|
use Gica\Serialize\ObjectHydrator\ObjectUnserializer; |
11
|
|
|
|
12
|
|
|
abstract class LocalAdapterLocator implements ObjectUnserializer |
13
|
|
|
{ |
14
|
2 |
|
protected function locateUnserializerForClass(string $className, $serializedValue):?ObjectUnserializer |
15
|
|
|
{ |
16
|
2 |
|
$hydratorName = $this->getNamespace() . '\\' . $className . '\\From' . ucfirst($this->getNameFromSerializedValue($serializedValue)); |
17
|
|
|
|
18
|
2 |
|
if (class_exists($hydratorName)) { |
19
|
1 |
|
return new $hydratorName; |
20
|
|
|
} |
21
|
|
|
|
22
|
1 |
|
return null; |
23
|
|
|
} |
24
|
|
|
|
25
|
2 |
|
public function tryToUnserializeValue(string $objectClassName, $serializedValue) |
26
|
|
|
{ |
27
|
2 |
|
$adapter = $this->locateUnserializerForClass($objectClassName, $serializedValue); |
28
|
|
|
|
29
|
2 |
|
if ($adapter) { |
30
|
1 |
|
return $adapter->tryToUnserializeValue($objectClassName, $serializedValue); |
31
|
|
|
} |
32
|
|
|
|
33
|
1 |
|
throw new AdapterNotFoundException(sprintf("Adapter for %s not found", $objectClassName)); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
abstract protected function getNamespace(): string; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param $serializedValue |
40
|
|
|
* @return string |
41
|
|
|
*/ |
42
|
2 |
|
private function getNameFromSerializedValue($serializedValue) |
43
|
|
|
{ |
44
|
2 |
|
if (is_object($serializedValue)) { |
45
|
1 |
|
return $this->getShortClassName($serializedValue); |
46
|
|
|
} |
47
|
|
|
|
48
|
2 |
|
return gettype($serializedValue); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
private function getShortClassName($serializedValue): string |
52
|
|
|
{ |
53
|
1 |
|
$parts = explode('\\', get_class($serializedValue)); |
54
|
|
|
|
55
|
1 |
|
return array_pop($parts); |
56
|
|
|
} |
57
|
|
|
} |