Completed
Push — master ( 9e79a2...d4f851 )
by Andrii
03:09
created

FixedDiscount::isRelative()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * PHP Billing Library
4
 *
5
 * @link      https://github.com/hiqdev/php-billing
6
 * @package   php-billing
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2017-2018, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hiqdev\php\billing\charge\modifiers;
12
13
use hiqdev\php\billing\action\ActionInterface;
14
use hiqdev\php\billing\charge\Charge;
15
use hiqdev\php\billing\charge\ChargeInterface;
16
use hiqdev\php\billing\charge\modifiers\addons\Discount;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, hiqdev\php\billing\charge\modifiers\Discount.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
17
use hiqdev\php\billing\price\SinglePrice;
18
use hiqdev\php\billing\target\Target;
19
use hiqdev\php\billing\type\Type;
20
use hiqdev\php\units\Quantity;
21
use Money\Money;
22
23
/**
24
 * Fixed discount.
25
 *
26
 * @author Andrii Vasyliev <[email protected]>
27
 */
28
class FixedDiscount extends Modifier
29
{
30
    const VALUE = 'value';
31
32 6
    public function __construct($value, array $addons = [])
33
    {
34 6
        parent::__construct($addons);
35 6
        $this->addAddon(self::VALUE, new Discount($value));
36 6
    }
37
38 11
    public function getNext()
39
    {
40 11
        return $this;
41
    }
42
43 5
    public function getValue(ChargeInterface $charge = null): Discount
44
    {
45 5
        return $this->getAddon(self::VALUE);
46
    }
47
48 3
    public function isAbsolute()
49
    {
50 3
        return $this->getAddon(self::VALUE)->isAbsolute();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface hiqdev\php\billing\charge\modifiers\AddonInterface as the method isAbsolute() does only exist in the following implementations of said interface: hiqdev\php\billing\charg...difiers\addons\Discount, hiqdev\php\billing\charg...difiers\addons\Extremum, hiqdev\php\billing\charge\modifiers\addons\Maximum, hiqdev\php\billing\charge\modifiers\addons\Minimum, hiqdev\php\billing\charge\modifiers\addons\Step.

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...
51
    }
52
53 5
    public function isRelative()
54
    {
55 5
        return !$this->isAbsolute();
56
    }
57
58 4
    public function calculateSum(ChargeInterface $charge = null): Money
59
    {
60 4
        return $this->getValue($charge)->calculateSum($charge);
0 ignored issues
show
Bug introduced by
It seems like $charge defined by parameter $charge on line 58 can be null; however, hiqdev\php\billing\charg...iscount::calculateSum() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
61
    }
62
63 4
    public function buildPrice(Money $sum)
64
    {
65 4
        $type = $this->getType();
66 4
        $target = $this->getTarget();
67 4
        $prepaid = Quantity::items(0);
68
69 4
        return new SinglePrice(null, $type, $target, null, $prepaid, $sum);
70
    }
71
72 4
    public function getType()
73
    {
74 4
        return new Type(Type::ANY, 'discount');
75
    }
76
77 4
    public function getTarget()
78
    {
79 4
        return new Target(Target::ANY, Target::ANY);
80
    }
81
82 4
    public function modifyCharge(?ChargeInterface $charge, ActionInterface $action): array
83
    {
84 4
        if ($charge === null) {
85
            return [];
86
        }
87
88 4
        $month = $action->getTime()->modify('first day of this month midnight');
89 4
        if (!$this->checkPeriod($month)) {
90
            return [$charge];
91
        }
92
93 4
        $sum = $this->calculateSum($charge);
94 4
        $usage  = Quantity::items(1);
95 4
        $price = $this->buildPrice($sum);
96 4
        $discount = new Charge(null, $action, $price, $usage, $sum);
97 4
        $reason = $this->getReason();
98 4
        if ($reason) {
99
            $discount->setComment($reason->getValue());
100
        }
101
102 4
        return [$charge, $discount];
103
    }
104
}
105