EntityReferenceConverter::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
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
10
/**
11
 * Convert the entity reference class to value.
12
 *
13
 * Class DefaultConverter.
14
 */
15
class EntityReferenceConverter implements ConverterInterface
16
{
17
    /**
18
     * @var EntityWrapper
19
     */
20
    private $entityWrapper;
21
22
    /**
23
     * @var EntityTypeManagerInterface
24
     */
25
    private $entityManager;
26
27
    /**
28
     * @param EntityWrapper              $entityWrapper
29
     * @param EntityTypeManagerInterface $entityManager
30
     */
31
    public function __construct(EntityWrapper $entityWrapper,
32
        EntityTypeManagerInterface $entityManager)
33
    {
34
        $this->entityWrapper = $entityWrapper;
35
        $this->entityManager = $entityManager;
36
    }
37
38
    /**
39
     * @param FieldItemInterface $value
40
     */
41
    public function convert(FieldItemInterface $value)
42
    {
43
        $type = str_replace('default:', '', $value->getParent()->getSettings()['handler']);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Drupal\Core\TypedData\Tr...sableTypedDataInterface as the method getSettings() does only exist in the following implementations of said interface: Drupal\Core\Field\ChangedFieldItemList, Drupal\Core\Field\EntityReferenceFieldItemList, Drupal\Core\Field\FieldItemBase, Drupal\Core\Field\FieldItemList, Drupal\Core\Field\MapFieldItemList, Drupal\Core\Field\Plugin...d\FieldType\BooleanItem, Drupal\Core\Field\Plugin...d\FieldType\ChangedItem, Drupal\Core\Field\Plugin...d\FieldType\CreatedItem, Drupal\Core\Field\Plugin...d\FieldType\DecimalItem, Drupal\Core\Field\Plugin\Field\FieldType\EmailItem, Drupal\Core\Field\Plugin...ype\EntityReferenceItem, Drupal\Core\Field\Plugin\Field\FieldType\FloatItem, Drupal\Core\Field\Plugin...d\FieldType\IntegerItem, Drupal\Core\Field\Plugin...\FieldType\LanguageItem, Drupal\Core\Field\Plugin\Field\FieldType\MapItem, Drupal\Core\Field\Plugin...eldType\NumericItemBase, Drupal\Core\Field\Plugin...\FieldType\PasswordItem, Drupal\Core\Field\Plugin...ld\FieldType\StringItem, Drupal\Core\Field\Plugin...ieldType\StringItemBase, Drupal\Core\Field\Plugin...ieldType\StringLongItem, Drupal\Core\Field\Plugin...FieldType\TimestampItem, Drupal\Core\Field\Plugin\Field\FieldType\UriItem, Drupal\Core\Field\Plugin\Field\FieldType\UuidItem, Drupal\color_field\Plugi...ieldType\ColorFieldType, Drupal\comment\CommentFieldItemList, Drupal\comment\Plugin\Field\FieldType\CommentItem, Drupal\content_moderatio...ationStateFieldItemList, Drupal\datetime\Plugin\F...e\DateTimeFieldItemList, Drupal\datetime\Plugin\F...\FieldType\DateTimeItem, Drupal\datetime_range\Pl...\DateRangeFieldItemList, Drupal\datetime_range\Pl...FieldType\DateRangeItem, Drupal\entity_reference\...ableEntityReferenceItem, Drupal\entity_test\Plugi...mputedTestFieldItemList, Drupal\entity_test\Plugi...utoIncrementingTestItem, Drupal\entity_test\Plugi...eldType\ChangedTestItem, Drupal\entity_test\Plugi...FieldType\FieldTestItem, Drupal\entity_test\Plugi...alPropertyTestFieldItem, Drupal\entity_test\Plugi...eld\FieldType\ShapeItem, Drupal\entity_test\Plugi...dType\ShapeItemRequired, Drupal\entity_test_updat...Type\MultiValueTestItem, Drupal\field_collection\...eldType\FieldCollection, Drupal\field_test\Plugin...ieldType\HiddenTestItem, Drupal\field_test\Plugin\Field\FieldType\TestItem, Drupal\field_test\Plugin...estItemWithDependencies, Drupal\field_test\Plugin...ithPreconfiguredOptions, Drupal\field_test\Plugin...ieldType\TestObjectItem, Drupal\file\Plugin\Field...dType\FileFieldItemList, Drupal\file\Plugin\Field\FieldType\FileItem, Drupal\file\Plugin\Field\FieldType\FileUriItem, Drupal\image\Plugin\Field\FieldType\ImageItem, Drupal\language\DefaultLanguageItem, Drupal\layout_builder\Field\LayoutSectionItemList, Drupal\layout_builder\Pl...dType\LayoutSectionItem, Drupal\link\Plugin\Field\FieldType\LinkItem, Drupal\options\Plugin\Fi...FieldType\ListFloatItem, Drupal\options\Plugin\Fi...eldType\ListIntegerItem, Drupal\options\Plugin\Field\FieldType\ListItemBase, Drupal\options\Plugin\Fi...ieldType\ListStringItem, Drupal\path\Plugin\Field...dType\PathFieldItemList, Drupal\path\Plugin\Field\FieldType\PathItem, Drupal\telephone\Plugin\...FieldType\TelephoneItem, Drupal\text\Plugin\Field\FieldType\TextItem, Drupal\text\Plugin\Field\FieldType\TextItemBase, Drupal\text\Plugin\Field\FieldType\TextLongItem, Drupal\text\Plugin\Field...ype\TextWithSummaryItem, Drupal\user\StatusItem, Drupal\user\TimeZoneItem, Drupal\user\UserNameItem.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

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

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
44
        $node = $this->entityManager->getStorage($type)->load($value->getValue()['target_id']);
45
46
        return $this->entityWrapper->wrap($node);
0 ignored issues
show
Bug introduced by
It seems like $node defined by $this->entityManager->ge...etValue()['target_id']) on line 44 can be null; however, Drupal\easy_entity_reader\EntityWrapper::wrap() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
47
    }
48
49
    /**
50
     * Returns whether the FieldItemInterface can be converted or not.
51
     *
52
     * @param FieldItemInterface $value
53
     *
54
     * @return bool
55
     */
56
    public function canConvert(FieldItemInterface $value) : bool
57
    {
58
        return $value instanceof EntityReferenceItem;
59
    }
60
}
61