Completed
Push — 2.0 ( 3b582e...88c91b )
by Mark
8s
created

WeightShippingModifier::value()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 25
ccs 0
cts 14
cp 0
rs 8.439
cc 6
eloc 15
nc 5
nop 1
crap 42
1
<?php
2
3
/**
4
 * Calculates the shipping cost of an order, by taking the products
5
 * and calculating the shipping weight, based on an array set in _config
6
 *
7
 * ASSUMPTION: The total order weight can be at maximum the last item
8
 * in the $shippingCosts array.
9
 *
10
 * @package    shop
11
 * @subpackage modifiers
12
 */
13
class WeightShippingModifier extends ShippingModifier
14
{
15
    /**
16
     * Weight to price mapping.
17
     * Should be an associative array, with the weight as key (KG) and the corresponding price as value.
18
     * Can be set via Config API, eg.
19
     * <code>
20
     * WeightShippingModifier:
21
     *   weight_cost:
22
     *     '0.5': 12
23
     *     '1.0': 15
24
     *     '2.0': 20
25
     * </code>
26
     * @config
27
     * @var array
28
     */
29
    protected static $weight_cost = array();
30
31
    protected $weight = 0;
32
33
    /**
34
     * Calculates shipping cost based on Product Weight.
35
     */
36
    public function value($subtotal = 0)
37
    {
38
        $totalWeight = $this->Weight();
39
        if (!$totalWeight) {
40
            return $this->Amount = 0;
0 ignored issues
show
Documentation introduced by
The property Amount does not exist on object<WeightShippingModifier>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
41
        }
42
        $amount = 0;
43
44
        $table = $this->config()->weight_cost;
45
        if(!empty($table) && is_array($table)){
46
            // ensure table is sorted
47
            ksort($table, SORT_NUMERIC);
48
            // set the amount to the highest value. In case the weight is higher than the max value in
49
            // the table, use the highest shipping cost and not 0!
50
            $amount = end($table);
51
            reset($table);
52
            foreach ($table as $weight => $cost) {
53
                if ($totalWeight <= $weight) {
54
                    $amount = $cost;
55
                    break;
56
                }
57
            }
58
        }
59
        return $this->Amount = $amount;
0 ignored issues
show
Documentation introduced by
The property Amount does not exist on object<WeightShippingModifier>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
60
    }
61
62
    public function TableTitle()
63
    {
64
        return _t(
65
            'WeightShippingModifier.TableTitle',
66
            'Shipping ({Kilograms} kg)',
67
            '',
68
            array('Kilograms' => $this->Weight())
0 ignored issues
show
Documentation introduced by
array('Kilograms' => $this->Weight()) is of type array<string,integer|dou...ams":"integer|double"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
69
        );
70
    }
71
72
    /**
73
     * Calculate the total weight of the order
74
     *
75
     * @return number
76
     */
77
    public function Weight()
78
    {
79
        if ($this->weight) {
80 2
            return $this->weight;
81
        }
82
        $weight = 0;
83
        $order = $this->Order();
0 ignored issues
show
Documentation Bug introduced by
The method Order does not exist on object<WeightShippingModifier>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
84
        if ($order && $orderItems = $order->Items()) {
85
            foreach ($orderItems as $orderItem) {
86
                if ($product = $orderItem->Product()) {
87
                    $weight = $weight + ($product->Weight * $orderItem->Quantity);
88
                }
89
            }
90
        }
91
        return $this->weight = $weight;
0 ignored issues
show
Documentation Bug introduced by
It seems like $weight can also be of type double. However, the property $weight is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
92
    }
93
}
94