1
|
|
|
<?php declare(strict_types=1); |
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
|
|
|
*/ |
27
|
3 |
|
public function setProperty(NodeInterface $node, \DOMElement $element) : void |
28
|
|
|
{ |
29
|
3 |
|
if ($node instanceof ItemInterface) { |
30
|
3 |
|
$author = $node->newAuthor(); |
31
|
3 |
|
$author->setName($element->nodeValue); |
32
|
3 |
|
$node->setAuthor($author); |
33
|
|
|
} |
34
|
3 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Tells if the node contains the expected value |
38
|
|
|
* |
39
|
|
|
* @param NodeInterface $node |
40
|
|
|
* @return bool |
41
|
|
|
*/ |
42
|
4 |
|
protected function hasValue(NodeInterface $node) : bool |
43
|
|
|
{ |
44
|
4 |
|
return $node instanceof ItemInterface && !! $node->getAuthor(); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Creates and adds the element(s) to the docuement's rootElement |
49
|
|
|
* |
50
|
|
|
* @param \DomDocument $document |
51
|
|
|
* @param \DOMElement $rootElement |
52
|
|
|
* @param NodeInterface $node |
53
|
|
|
*/ |
54
|
1 |
|
protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void |
55
|
|
|
{ |
56
|
1 |
|
$rootElement->appendChild($document->createElement($this->getNodeName(), $node->getAuthor()->getName())); |
|
|
|
|
57
|
1 |
|
} |
58
|
|
|
} |
59
|
|
|
|
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: