Completed
Push — develop ( 515643...e2e58e )
by
unknown
08:08
created

GeoSelectHydratorStrategy::hydrate()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 2
nop 2
1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @license MIT
7
 * @copyright  2013 - 2017 Cross Solution <http://cross-solution.de>
8
 */
9
  
10
/** */
11
namespace Geo\Form;
12
13
use Geo\Service\AbstractClient;
14
use Jobs\Entity\Location;
15
use Zend\Hydrator\Strategy\StrategyInterface;
16
17
/**
18
 * ${CARET}
19
 * 
20
 * @author Mathias Gelhausen <[email protected]>
21
 * @todo write test 
22
 */
23
class GeoSelectHydratorStrategy implements StrategyInterface
24
{
25
    protected $geoClient;
26
27
    protected $locationEntityPrototype;
28
29
    public function __construct(AbstractClient $client)
30
    {
31
        $this->geoClient = $client;
32
    }
33
34
    /**
35
     * @param mixed $locationEntityPrototype
36
     *
37
     * @return self
38
     */
39
    public function setLocationEntityPrototype($locationEntityPrototype)
40
    {
41
        $this->locationEntityPrototype =
42
            is_string($locationEntityPrototype)
43
            ? new $locationEntityPrototype
44
            : $locationEntityPrototype;
45
46
        return $this;
47
    }
48
49
    /**
50
     * @return mixed
51
     */
52
    public function getLocationEntity()
53
    {
54
        return clone $this->locationEntityPrototype;
55
    }
56
57
58
59
    /**
60
     * Converts the given value so that it can be extracted by the hydrator.
61
     *
62
     * @param mixed  $value  The original value.
63
     *
64
     * @return mixed Returns the value that should be extracted.
65
     */
66
    public function extract($value, $object = null)
67
    {
68
        if ($value instanceOf Location) {
69
            return $value->toString();
70
        }
71
72
        if (0 === strpos($value, '{')) {
73
            return $value;
74
        }
75
76
        $data = $this->geoClient->queryOne($value);
77
        return $data['id'];
78
    }
79
80
    /**
81
     * Converts the given value so that it can be hydrated by the hydrator.
82
     *
83
     * @param mixed $value The original value.
84
     * @param array $data  (optional) The original data for context.
85
     *
86
     * @return mixed Returns the value that should be hydrated.
87
     */
88
    public function hydrate($value, $data = [])
89
    {
90
        if (empty($value) || 0 !== strpos($value, '{')) {
91
            return null;
92
        }
93
94
        $location = $this->getLocationEntity();
95
        return $location->fromString($value);
96
    }
97
}