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

EasyEntityAdapter::offsetGet()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
cc 5
eloc 14
nc 5
nop 1
1
<?php
2
3
namespace Drupal\easy_entity_reader;
4
5
use Drupal\Core\Entity\EntityInterface;
6
7
/**
8
 * Adapts an entity class in an easy access array.
9
 *
10
 * Class EntityAdapter.
11
 */
12
class EasyEntityAdapter implements \ArrayAccess
13
{
14
    /**
15
     * @var EntityInterface
16
     */
17
    private $entity;
18
19
    /**
20
     * @var EntityWrapper
21
     */
22
    private $entityWrapper;
23
24
    /**
25
     * @param EntityInterface $entity
26
     * @param EntityWrapper   $entityWrapper
27
     */
28
    public function __construct(EntityInterface $entity, EntityWrapper $entityWrapper)
29
    {
30
        $this->entity = $entity;
31
        $this->entityWrapper = $entityWrapper;
32
    }
33
34
    /**
35
     * @param $offset
36
     */
37
    public function offsetExists($offset)
38
    {
39
        return isset($this->entity->getFields()[$offset]);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Drupal\Core\Entity\EntityInterface as the method getFields() does only exist in the following implementations of said interface: Drupal\Core\Entity\ContentEntityBase, Drupal\Core\Entity\RevisionableContentEntityBase, Drupal\Tests\Core\Entity\EntityManagerTestEntity, Drupal\aggregator\Entity\Feed, Drupal\aggregator\Entity\Item, Drupal\block_content\Entity\BlockContent, Drupal\comment\Entity\Comment, Drupal\contact\Entity\Message, Drupal\content_moderatio...\ContentModerationState, Drupal\content_translati...estTranslatableNoUISkip, Drupal\content_translati...yTestTranslatableUISkip, Drupal\entity_test\Entity\EntityTest, Drupal\entity_test\Entity\EntityTestAdminRoutes, Drupal\entity_test\Entit...ityTestBaseFieldDisplay, Drupal\entity_test\Entity\EntityTestCache, Drupal\entity_test\Entit...TestCompositeConstraint, Drupal\entity_test\Entit...TestConstraintViolation, Drupal\entity_test\Entity\EntityTestConstraints, Drupal\entity_test\Entity\EntityTestDefaultAccess, Drupal\entity_test\Entity\EntityTestDefaultValue, Drupal\entity_test\Entity\EntityTestFieldMethods, Drupal\entity_test\Entity\EntityTestFieldOverride, Drupal\entity_test\Entity\EntityTestLabel, Drupal\entity_test\Entity\EntityTestLabelCallback, Drupal\entity_test\Entity\EntityTestMul, Drupal\entity_test\Entity\EntityTestMulChanged, Drupal\entity_test\Entit...tityTestMulDefaultValue, Drupal\entity_test\Entity\EntityTestMulLangcodeKey, Drupal\entity_test\Entity\EntityTestMulRev, Drupal\entity_test\Entity\EntityTestMulRevChanged, Drupal\entity_test\Entit...TestMultiValueBasefield, Drupal\entity_test\Entity\EntityTestNew, Drupal\entity_test\Entity\EntityTestNoId, Drupal\entity_test\Entity\EntityTestNoLabel, Drupal\entity_test\Entity\EntityTestRev, Drupal\entity_test\Entity\EntityTestStringId, Drupal\entity_test\Entity\EntityTestUpdate, Drupal\entity_test\Entity\EntityTestViewBuilder, Drupal\entity_test\Entity\EntityTestWithBundle, Drupal\entity_test\Entit...tityTestWithRevisionLog, Drupal\field_collection\Entity\FieldCollectionItem, Drupal\file\Entity\File, Drupal\language_test\Entity\NoLanguageEntityTest, Drupal\menu_link_content\Entity\MenuLinkContent, Drupal\migrate_entity_te...tity\StringIdEntityTest, Drupal\node\Entity\Node, Drupal\shortcut\Entity\Shortcut, Drupal\taxonomy\Entity\Term, Drupal\user\Entity\User.

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...
40
    }
41
42
    /**
43
     * @param $offset
44
     */
45
    public function offsetGet($offset)
46
    {
47
        if ($this->offsetExists($offset)) {
48
            if (isset($this->entity->$offset)) {
49
                $values = $this->entity->$offset;
50
                $cardinality = $values->getDataDefinition()->getFieldStorageDefinition()->getCardinality();
51
                if (1 === $cardinality) {
52
                    if ($values[0] === null) {
53
                        return null;
54
                    }
55
56
                    return $this->entityWrapper->convert($values[0]);
57
                } else {
58
                    return array_map([$this->entityWrapper, 'convert'], iterator_to_array($values));
59
                }
60
            }
61
        } else {
62
            return null;
63
        }
64
        throw new \Exception('The index "'.$offset.'" doesn\'t exist');
65
    }
66
67
    /**
68
     * @param $offset
69
     * @param $value
70
     */
71
    public function offsetSet($offset, $value)
72
    {
73
        throw new \Exception('Not supported');
74
    }
75
76
    /**
77
     * @param $offset
78
     */
79
    public function offsetUnset($offset)
80
    {
81
        throw new \Exception('Not supported');
82
    }
83
}
84