1
|
|
|
<?php |
2
|
|
|
/* |
3
|
|
|
* This file is part of the feed-io package. |
4
|
|
|
* |
5
|
|
|
* (c) Alexandre Debril <[email protected]> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace FeedIo\Rule; |
12
|
|
|
|
13
|
|
|
use FeedIo\Feed\ItemInterface; |
14
|
|
|
use FeedIo\Feed\NodeInterface; |
15
|
|
|
use FeedIo\RuleAbstract; |
16
|
|
|
|
17
|
|
|
class Author extends RuleAbstract |
18
|
|
|
{ |
19
|
|
|
const NODE_NAME = 'author'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Sets the accurate $item property according to the DomElement content |
23
|
|
|
* |
24
|
|
|
* @param NodeInterface $node |
25
|
|
|
* @param \DOMElement $element |
26
|
|
|
* @return mixed |
27
|
|
|
*/ |
28
|
3 |
|
public function setProperty(NodeInterface $node, \DOMElement $element) |
29
|
|
|
{ |
30
|
3 |
|
if ($node instanceof ItemInterface) { |
31
|
3 |
|
$author = $node->newAuthor(); |
32
|
3 |
|
$author->setName($element->nodeValue); |
33
|
3 |
|
$node->setAuthor($author); |
34
|
|
|
} |
35
|
|
|
|
36
|
3 |
|
return $this; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Tells if the node contains the expected value |
41
|
|
|
* |
42
|
|
|
* @param NodeInterface $node |
43
|
|
|
* @return bool |
44
|
|
|
*/ |
45
|
4 |
|
protected function hasValue(NodeInterface $node) : bool |
46
|
|
|
{ |
47
|
4 |
|
return $node instanceof ItemInterface && !! $node->getAuthor(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Creates and adds the element(s) to the docuement's rootElement |
52
|
|
|
* |
53
|
|
|
* @param \DomDocument $document |
54
|
|
|
* @param \DOMElement $rootElement |
55
|
|
|
* @param NodeInterface $node |
56
|
|
|
*/ |
57
|
1 |
|
protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void |
58
|
|
|
{ |
59
|
1 |
|
$rootElement->appendChild($document->createElement($this->getNodeName(), $node->getAuthor()->getName())); |
|
|
|
|
60
|
1 |
|
} |
61
|
|
|
} |
62
|
|
|
|
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: