Completed
Pull Request — master (#62)
by Adam
04:18
created

Street::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 0
cts 5
cp 0
rs 9.4285
cc 1
eloc 7
nc 1
nop 0
crap 2
1
<?php
2
3
namespace ValueObjects\Geography;
4
5
use ValueObjects\StringLiteral\StringLiteral;
6
use ValueObjects\Util\Util;
7
use ValueObjects\ValueObjectInterface;
8
9
class Street implements ValueObjectInterface
10
{
11
    /** @var StringLiteral */
12
    protected $name;
13
14
    /** @var StringLiteral */
15
    protected $number;
16
17
    /** @var String Building, floor and unit */
18
    protected $elements;
19
20
    /**
21
     * @var String __toString() format
22
     * Use properties corresponding placeholders: %name%, %number%, %elements%
23
     */
24
    protected $format;
25
26
    /**
27
     * Returns a new Street from native PHP string name and number.
28
     *
29
     * @param string $name
0 ignored issues
show
Bug introduced by
There is no parameter named $name. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
30
     * @param string $number
0 ignored issues
show
Bug introduced by
There is no parameter named $number. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
31
     * @param string $elements
0 ignored issues
show
Bug introduced by
There is no parameter named $elements. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
32
     *
33
     * @return Street
34
     * @throws \BadFunctionCallException
35
     */
36 2
    public static function fromNative()
37
    {
38 2
        $args = func_get_args();
39
40 2
        if (\count($args) < 2) {
41 1
            throw new \BadMethodCallException('You must provide from 2 to 4 arguments: 1) street name, 2) street number, 3) elements, 4) format (optional)');
42
        }
43
44 1
        $nameString = $args[0];
45 1
        $numberString = $args[1];
46 1
        $elementsString = isset($args[2]) ? $args[2] : NULL;
47 1
        $formatString = isset($args[3]) ? $args[3] : NULL;
48
49 1
        $name = new StringLiteral($nameString);
50 1
        $number = new StringLiteral($numberString);
51 1
        $elements = $elementsString ? new StringLiteral($elementsString) : NULL;
52 1
        $format = $formatString ? new StringLiteral($formatString) : NULL;
53
54 1
        return new self($name, $number, $elements, $format);
55
    }
56
57
    /**
58
     * Returns a new Street object
59
     *
60
     * @param String $name
61
     * @param String $number
62
     */
63 18
    public function __construct(StringLiteral $name, StringLiteral $number, StringLiteral $elements = NULL, StringLiteral $format = NULL)
64
    {
65 18
        $this->name = $name;
66 18
        $this->number = $number;
67
68 18
        if ($elements === NULL) {
69 12
            $elements = new StringLiteral('');
70
        }
71 18
        $this->elements = $elements;
0 ignored issues
show
Documentation Bug introduced by
It seems like $elements of type object<ValueObjects\StringLiteral\StringLiteral> is incompatible with the declared type string of property $elements.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
72
73 18
        if ($format === NULL) {
74 13
            $format = new StringLiteral('%number% %name%');
75
        }
76 18
        $this->format = $format;
0 ignored issues
show
Documentation Bug introduced by
It seems like $format of type object<ValueObjects\StringLiteral\StringLiteral> is incompatible with the declared type string of property $format.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
77 18
    }
78
79
    /**
80
     * Tells whether two Street objects are equal
81
     *
82
     * @param  ValueObjectInterface $street
83
     *
84
     * @return bool
85
     */
86 5
    public function sameValueAs(ValueObjectInterface $street)
87
    {
88 5
        if (FALSE === Util::classEquals($this, $street)) {
89 1
            return FALSE;
90
        }
91
92 5
        return $this->getName()->sameValueAs($street->getName()) &&
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ValueObjects\ValueObjectInterface as the method getName() does only exist in the following implementations of said interface: ValueObjects\DateTime\Month, ValueObjects\DateTime\TimeZone, ValueObjects\DateTime\WeekDay, ValueObjects\Enum\Enum, ValueObjects\Geography\Address, ValueObjects\Geography\Continent, ValueObjects\Geography\Country, ValueObjects\Geography\CountryCode, ValueObjects\Geography\DistanceFormula, ValueObjects\Geography\DistanceUnit, ValueObjects\Geography\Ellipsoid, ValueObjects\Geography\Street, ValueObjects\Money\CurrencyCode, ValueObjects\Number\RoundingMode, ValueObjects\Person\Gender, ValueObjects\Web\IPAddressVersion.

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...
93 5
        $this->getNumber()->sameValueAs($street->getNumber()) &&
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ValueObjects\ValueObjectInterface as the method getNumber() does only exist in the following implementations of said interface: ValueObjects\Geography\Street.

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...
94 5
        $this->getElements()->sameValueAs($street->getElements());;
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface ValueObjects\ValueObjectInterface as the method getElements() does only exist in the following implementations of said interface: ValueObjects\Geography\Street.

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...
95
    }
96
97
    /**
98
     * Returns street name
99
     *
100
     * @return String
101
     */
102 8
    public function getName()
103
    {
104 8
        return clone $this->name;
105
    }
106
107
    /**
108
     * Returns street number
109
     *
110
     * @return String
111
     */
112 8
    public function getNumber()
113
    {
114 8
        return clone $this->number;
115
    }
116
117
    /**
118
     * Returns street elements
119
     *
120
     * @return String
121
     */
122 8
    public function getElements()
123
    {
124 8
        return clone $this->elements;
125
    }
126
127
    /**
128
     * Returns a string representation of the StringLiteral in the format defined in the constructor
129
     *
130
     * @return string
131
     */
132 2
    public function __toString()
133
    {
134
        $replacements = [
135 2
            "%name%"     => $this->getName(),
136 2
            "%number%"   => $this->getNumber(),
137 2
            "%elements%" => $this->getElements(),
138
        ];
139
140 2
        $streetString = str_replace(array_keys($replacements), array_values($replacements), $this->format);
141
142 2
        return $streetString;
143
    }
144
145
    function jsonSerialize()
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for jsonSerialize.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
146
    {
147
        return [
148
            'parts'     => [
149
                'name'     => $this->getName(),
150
                'number'   => $this->getNumber(),
151
                'elements' => $this->getElements(),
152
            ],
153
            'formatted' => (string)$this,
154
        ];
155
156
    }
157
158
159
}
160