Completed
Pull Request — master (#62)
by Adam
03:14
created

Complex::jsonSerialize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
ccs 4
cts 4
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 0
crap 1
1
<?php
2
3
namespace ValueObjects\Number;
4
5
use ValueObjects\Util\Util;
6
use ValueObjects\ValueObjectInterface;
7
8
class Complex implements ValueObjectInterface, NumberInterface
9
{
10
    /** @var Real */
11
    protected $real;
12
13
    /** @var Real */
14
    protected $im;
15
16
    /**
17
     * Returns a new Complex object from native PHP arguments
18
     *
19
     * @param  float                        $real Real part of the complex number
0 ignored issues
show
Bug introduced by
There is no parameter named $real. 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...
20
     * @param  float                        $im   Imaginary part of the complex number
0 ignored issues
show
Bug introduced by
There is no parameter named $im. 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...
21
     * @return Complex|ValueObjectInterface
22
     * @throws \BadMethodCallException
23
     */
24 3
    public static function fromNative()
25
    {
26 3
        $args = \func_get_args();
27
28 3
        if (\count($args) != 2) {
29 1
            throw new \BadMethodCallException('You must provide 2 arguments: 1) real part, 2) imaginary part');
30
        }
31
32 2
        $real    = Real::fromNative($args[0]);
33 2
        $im      = Real::fromNative($args[1]);
34 2
        $complex = new self($real, $im);
35
36 2
        return $complex;
37
    }
38
39
    /**
40
     * Returns a Complex given polar coordinates
41
     *
42
     * @param  Real    $modulus
43
     * @param  Real    $argument
44
     * @return Complex
45
     */
46 1
    public static function fromPolar(Real $modulus, Real $argument)
47
    {
48 1
        $realValue = $modulus->toNative() * \cos($argument->toNative());
49 1
        $imValue   = $modulus->toNative() * \sin($argument->toNative());
50 1
        $real      = new Real($realValue);
51 1
        $im        = new Real($imValue);
52 1
        $complex   = new self($real, $im);
53
54 1
        return $complex;
55
    }
56
57
    /**
58
     * Returns a Complex object give its real and imaginary parts as parameters
59
     *
60
     * @param Real $real
61
     * @param Real $im
62
     */
63 11
    public function __construct(Real $real, Real $im)
64
    {
65 11
        $this->real = $real;
66 11
        $this->im   = $im;
67 11
    }
68
69 2
    public function sameValueAs(ValueObjectInterface $complex)
70
    {
71 2
        if (false === Util::classEquals($this, $complex)) {
72 1
            return false;
73
        }
74
75 1
        return $this->getReal()->sameValueAs($complex->getReal()) &&
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 getReal() does only exist in the following implementations of said interface: ValueObjects\Number\Complex.

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...
76 1
               $this->getIm()->sameValueAs($complex->getIm());
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 getIm() does only exist in the following implementations of said interface: ValueObjects\Number\Complex.

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...
77
    }
78
79
    /**
80
     * Returns the native value of the real and imaginary parts as an array
81
     *
82
     * @return array
83
     */
84 1
    public function toNative()
85
    {
86
        return array(
87 1
            $this->getReal()->toNative(),
88 1
            $this->getIm()->toNative()
89 1
        );
90
    }
91
92
    /**
93
     * Returns the real part of the complex number
94
     *
95
     * @return Real
96
     */
97 8
    public function getReal()
98
    {
99 8
        return clone $this->real;
100
    }
101
102
    /**
103
     * Returns the imaginary part of the complex number
104
     *
105
     * @return Real
106
     */
107 8
    public function getIm()
108
    {
109 8
        return clone $this->im;
110
    }
111
112
    /**
113
     * Returns the modulus (or absolute value or magnitude) of the Complex number
114
     *
115
     * @return Real
116
     */
117 2
    public function getModulus()
118
    {
119 2
        $real = $this->getReal()->toNative();
120 2
        $im   = $this->getIm()->toNative();
121 2
        $mod  = \sqrt(\pow($real, 2) + \pow($im, 2));
122
123 2
        return new Real($mod);
124
    }
125
126
    /**
127
     * Returns the argument (or phase) of the Complex number
128
     *
129
     * @return Real
130
     */
131 2
    public function getArgument()
132
    {
133 2
        $real = $this->getReal()->toNative();
134 2
        $im   = $this->getIm()->toNative();
135 2
        $arg  = \atan2($im, $real);
136
137 2
        return new Real($arg);
138
    }
139
140
    /**
141
     * Returns a native string version of the Complex object in format "${real} +|- ${complex}i"
142
     *
143
     * @return string
144
     */
145 1
    public function __toString()
146
    {
147 1
        $format = '%g %+gi';
148 1
        $real   = $this->getReal()->toNative();
149 1
        $im     = $this->getIm()->toNative();
150 1
        $string = \sprintf($format, $real, $im);
151
152 1
        return \preg_replace('/(\+|-)/', '$1 ', $string);
153
    }
154
155 1
    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...
156
    {
157
        return [
158 1
            'real' => $this->getReal()->toNative(),
159 1
            'im' => $this->getIm()->toNative()
160 1
        ];
161
    }
162
163
164
}
165