|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Drupal\easy_entity_reader\Converters; |
|
4
|
|
|
|
|
5
|
|
|
use Drupal\Core\Field\FieldItemInterface; |
|
6
|
|
|
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem; |
|
7
|
|
|
use Drupal\easy_entity_reader\EntityWrapper; |
|
8
|
|
|
use Drupal\Core\Entity\EntityTypeManagerInterface; |
|
9
|
|
|
use Drupal\file\Plugin\Field\FieldType\FileItem; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Convert the file item class to value. |
|
13
|
|
|
* |
|
14
|
|
|
* Class FileItemConverter. |
|
15
|
|
|
*/ |
|
16
|
|
|
class FileItemConverter implements ConverterInterface |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* @var EntityWrapper |
|
20
|
|
|
*/ |
|
21
|
|
|
private $entityWrapper; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* @var EntityTypeManagerInterface |
|
25
|
|
|
*/ |
|
26
|
|
|
private $entityManager; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @param EntityWrapper $entityWrapper |
|
30
|
|
|
* @param EntityTypeManagerInterface $entityManager |
|
31
|
|
|
*/ |
|
32
|
|
|
public function __construct(EntityWrapper $entityWrapper, |
|
33
|
|
|
EntityTypeManagerInterface $entityManager) |
|
34
|
|
|
{ |
|
35
|
|
|
$this->entityWrapper = $entityWrapper; |
|
36
|
|
|
$this->entityManager = $entityManager; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* @param FieldItemInterface $value |
|
41
|
|
|
*/ |
|
42
|
|
|
public function convert(FieldItemInterface $value) |
|
43
|
|
|
{ |
|
44
|
|
|
$node = null; |
|
45
|
|
|
$values = $value->getValue(); |
|
46
|
|
|
$type = str_replace('default:', '', $value->getParent()->getSettings()['handler']); |
|
|
|
|
|
|
47
|
|
|
if(isset($values['target_id'])) { |
|
48
|
|
|
$node = $this->entityManager->getStorage($type)->load($values['target_id']); |
|
49
|
|
|
} |
|
50
|
|
|
elseif(isset($value->getValue()['fids'][0])) { |
|
51
|
|
|
$node = $this->entityManager->getStorage($type)->load($value->getValue()['fids'][0]); |
|
52
|
|
|
} |
|
53
|
|
|
if($node !== null) { |
|
54
|
|
|
return $this->entityWrapper->wrap($node); |
|
55
|
|
|
} |
|
56
|
|
|
else { |
|
57
|
|
|
return null; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* Returns whether the FieldItemInterface can be converted or not. |
|
63
|
|
|
* |
|
64
|
|
|
* @param FieldItemInterface $value |
|
65
|
|
|
* |
|
66
|
|
|
* @return bool |
|
67
|
|
|
*/ |
|
68
|
|
|
public function canConvert(FieldItemInterface $value) : bool |
|
69
|
|
|
{ |
|
70
|
|
|
return $value instanceof FileItem; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
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: