Completed
Push — master ( 01abf8...56bab1 )
by Andy
02:13
created

PopoloObject::__toString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace mySociety\EveryPoliticianPopolo\Objects;
4
5
class PopoloObject
6
{
7
    use \mySociety\EveryPoliticianPopolo\Traits\ArrayGetterTrait;
8
9
    protected $properties = [];
10
    protected $baseProperties = [
11
        'keyForHash',
12
    ];
13
    protected $data;
14
    protected $allPopolo;
15
16
    /**
17
     *
18
     */
19 222
    public function __construct($data, $allPopolo)
20
    {
21 222
        $this->data = $data;
22 222
        $this->allPopolo = $allPopolo;
23 222
    }
24
25 222 View Code Duplication
    public function __get($prop)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
26
    {
27 222
        $properties = array_merge($this->baseProperties, $this->properties);
28 222
        if (in_array($prop, $properties)) {
29 222
            $getter = 'get' . ucfirst($prop);
30 222
            return $this->$getter();
31
        }
32 3
        trigger_error('Undefined property: '.__CLASS__.'::$'.$prop, E_USER_ERROR);
33
    }
34
35 201
    protected function getKeyForHash()
36 2
    {
37 201
         return $this->getId();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class mySociety\EveryPoliticia...lo\Objects\PopoloObject as the method getId() does only exist in the following sub-classes of mySociety\EveryPoliticia...lo\Objects\PopoloObject: mySociety\EveryPoliticianPopolo\Objects\Area, mySociety\EveryPoliticianPopolo\Objects\Event, mySociety\EveryPoliticia...lo\Objects\Organization, mySociety\EveryPoliticianPopolo\Objects\Person, mySociety\EveryPoliticianPopolo\Objects\Post. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
38
    }
39
40 27
    private function getRelatedObjects($popoloArray)
41
    {
42 27
        return $this->arrGet($this->data, $popoloArray, []);
43
    }
44
45 24
    protected function getDate($attr, $default = null)
46
    {
47 24
        $d = $this->arrGet($this->data, $attr);
48 24
        if ($d) {
49 21
            return new \DateTime($d);
50
        }
51 3
        return $default;
52
    }
53
54 27
    private function getRelatedValues($popoloArray, $infoTypeKey, $infoType, $infoValueKey)
55
    {
56
        /* Get a value from one of the Popolo related objects
57
         *
58
         * For example, if you have a person with related links, like
59
         * this:
60
         *
61
         *     {
62
         *         "name": "Dale Cooper",
63
         *         "links": [
64
         *             {
65
         *                 "note": "wikipedia",
66
         *                 "url": "https://en.wikipedia.org/wiki/Dale_Cooper"
67
         *             }
68
         *         ]
69
         *     }
70
         *
71
         * When calling this method to get the Wikipedia URL, you would use:
72
         *
73
         *     popoloArray  = 'links'
74
         *     infoTypeKey  = 'note'
75
         *     infoType     = 'wikipedia'
76
         *     infoValueKey = 'url'
77
         *
78
         * ... so the following would work:
79
         *
80
         *     $this->getRelatedValue('links', 'note', 'wikipedia', 'url')
81
         *     # => 'https://en.wikipedia.org/wiki/Dale_Cooper'
82
         */
83 27
        $relatedValues = [];
84 27
        $relatedObjects = $this->getRelatedObjects($popoloArray);
85 27
        foreach ($relatedObjects as $o) {
86 21
            if ($o[$infoTypeKey] === $infoType) {
87 21
                $relatedValues[] = $o[$infoValueKey];
88 14
            }
89 18
        }
90 27
        return $relatedValues;
91
    }
92
93 12
    public function identifierValues($scheme)
94
    {
95 12
        return $this->getRelatedValues('identifiers', 'scheme', $scheme, 'identifier');
96
    }
97
98 12
    public function identifierValue($scheme)
99
    {
100 12
        $identifierValues = $this->identifierValues($scheme);
101 12
        return (count($identifierValues) > 0) ? $identifierValues[0] : null;
102
    }
103
104 12
    public function linkValues($note)
105
    {
106 12
        return $this->getRelatedValues('links', 'note', $note, 'url');
107
    }
108
109 9
    public function linkValue($note)
110
    {
111 9
        $linkValues = $this->linkValues($note);
112 9
        return (count($linkValues) > 0) ? $linkValues[0] : null;
113
    }
114
115 12
    public function contactDetailValues($contactType)
116
    {
117 12
        return $this->getRelatedValues('contact_details', 'type', $contactType, 'value');
118
    }
119
120 12
    public function contactDetailValue($contactType)
121
    {
122 12
        $contactDetailValues = $this->contactDetailValues($contactType);
123 12
        return (count($contactDetailValues) > 0) ? $contactDetailValues[0] : null;
124
    }
125
126 21 View Code Duplication
    public function equals($other)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
127
    {
128 21
        if (get_class($other) == get_class($this)) {
129 21
            return $this->id == $other->id;
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<mySociety\EveryPo...o\Objects\PopoloObject>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
130
        }
131
        throw new \BadMethodCallException;
132
    }
133
134 51
    public function getRelatedObjectArr($popoloArray)
135 2
    {
136 51
        return $this->arrGet($this->data, $popoloArray, []);
137
    }
138
}
139