1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Twitter\Serializer; |
4
|
|
|
|
5
|
|
|
use Twitter\Object\TwitterCoordinates; |
6
|
|
|
use Twitter\TwitterSerializable; |
7
|
|
|
use Twitter\TwitterSerializer; |
8
|
|
|
|
9
|
|
|
class TwitterCoordinatesSerializer implements TwitterSerializer |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @param TwitterSerializable $object |
13
|
|
|
* @return \stdClass |
14
|
|
|
*/ |
15
|
6 |
|
public function serialize(TwitterSerializable $object) |
16
|
|
|
{ |
17
|
6 |
|
if (!$this->canSerialize($object)) { |
18
|
3 |
|
throw new \InvalidArgumentException('$object must be an instance of TwitterCoordinates'); |
19
|
|
|
} |
20
|
|
|
|
21
|
3 |
|
$coords = new \stdClass(); |
22
|
3 |
|
$coords->coordinates = [$object->getLongitude(), $object->getLatitude()]; |
|
|
|
|
23
|
3 |
|
$coords->type = $object->getType(); |
|
|
|
|
24
|
|
|
|
25
|
3 |
|
return $coords; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param \stdClass $obj |
30
|
|
|
* @param array $context |
31
|
|
|
* @return TwitterCoordinates |
32
|
|
|
*/ |
33
|
3 |
|
public function unserialize($obj, array $context = []) |
34
|
|
|
{ |
35
|
3 |
|
if (!$this->canUnserialize($obj)) { |
36
|
|
|
throw new \InvalidArgumentException('$object is not unserializable'); |
37
|
3 |
|
} |
38
|
|
|
|
39
|
|
|
$coords = $obj->coordinates; |
40
|
|
|
|
41
|
|
|
return TwitterCoordinates::create($coords[0], $coords[1], $obj->type); |
42
|
|
|
} |
43
|
15 |
|
|
44
|
|
|
/** |
45
|
15 |
|
* @param TwitterSerializable $object |
46
|
|
|
* @return boolean |
47
|
|
|
*/ |
48
|
|
|
public function canSerialize(TwitterSerializable $object) |
49
|
|
|
{ |
50
|
|
|
return $object instanceof TwitterCoordinates; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param \stdClass $object |
55
|
|
|
* @return boolean |
56
|
|
|
*/ |
57
|
|
|
public function canUnserialize($object) |
58
|
|
|
{ |
59
|
|
|
return isset($object->coordinates); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @return TwitterCoordinatesSerializer |
64
|
|
|
*/ |
65
|
|
|
public static function build() |
66
|
|
|
{ |
67
|
|
|
return new self(); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: