Completed
Push — 1.0 ( ba8fdc...8ff026 )
by David
10s
created

ImageItemConverter::canConvert()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace Drupal\easy_entity_reader\Converters;
4
5
use Drupal\Core\Field\FieldItemInterface;
6
use Drupal\easy_entity_reader\EntityWrapper;
7
use Drupal\Core\Entity\EntityTypeManagerInterface;
8
use Drupal\image\Plugin\Field\FieldType\ImageItem;
9
use Drupal\easy_entity_reader\CompositeArrayAccess;
10
11
/**
12
 * Convert image class to value.
13
 *
14
 * Class DefaultConverter.
15
 */
16
class ImageItemConverter 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
        $values = $value->getValue();
45
        $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\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\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...utoIncrementingTestItem, Drupal\entity_test\Plugi...eldType\ChangedTestItem, Drupal\entity_test\Plugi...FieldType\FieldTestItem, Drupal\entity_test\Plugi...eld\FieldType\ShapeItem, Drupal\entity_test\Plugi...dType\ShapeItemRequired, 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\image\Plugin\Field\FieldType\ImageItem, Drupal\language\DefaultLanguageItem, 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\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...
46
        $node = $this->entityManager->getStorage($type)->load($values['target_id']);
47
48
        $frontArray = [];
49
        if (isset($values['alt'])) {
50
            $frontArray['alt'] = $values['alt'];
51
        }
52
        if (isset($values['title'])) {
53
            $frontArray['title'] = $values['title'];
54
        }
55
        if (isset($values['width'])) {
56
            $frontArray['width'] = $values['width'];
57
        }
58
        if (isset($values['height'])) {
59
            $frontArray['height'] = $values['height'];
60
        }
61
        $wrap = $this->entityWrapper->wrap($node);
0 ignored issues
show
Bug introduced by
It seems like $node defined by $this->entityManager->ge...d($values['target_id']) on line 46 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...
62
63
        return new CompositeArrayAccess([$frontArray, $wrap]);
64
    }
65
66
    /**
67
     * Returns whether the FieldItemInterface can be converted or not.
68
     *
69
     * @param FieldItemInterface $value
70
     *
71
     * @return bool
72
     */
73
    public function canConvert(FieldItemInterface $value) : bool
74
    {
75
        return $value instanceof ImageItem;
76
    }
77
}
78