Completed
Push — master ( dd0de2...7f19c4 )
by Roman
04:08
created

TableShippingMethod::requiresAddress()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 3
nop 0
1
<?php
2
3
/**
4
 * Work out shipping rate from a pre-defined table of regions - to - weights and dimensions.
5
 *
6
 * @package silvershop-shipping
7
 */
8
class TableShippingMethod extends ShippingMethod
9
{
10
    private static $defaults = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
11
        'Name'        => 'Table Shipping',
12
        'Description' => 'Works out shipping from a pre-defined table'
13
    );
14
15
    private static $has_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
16
        "Rates" => "TableShippingRate"
17
    );
18
19
    public function getCMSFields()
20
    {
21
        $fields = parent::getCMSFields();
22
23
        $fieldList = array(
0 ignored issues
show
Unused Code introduced by
$fieldList is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
24
            "Country"     => "Country",
25
            "State"       => "State",
26
            "City"        => "City",
27
            "PostalCode"  => "PostCode",
28
            "WeightMin"   => "WeightMin",
29
            "WeightMax"   => "WeightMax",
30
            "VolumeMin"   => "VolumeMin",
31
            "VolumeMax"   => "VolumeMax",
32
            "ValueMin"    => "ValueMin",
33
            "ValueMax"    => "ValueMax",
34
            "QuantityMin" => "QuantityMin",
35
            "QuantityMax" => "QuantityMax",
36
            "Rate"        => "Rate"
37
        );
38
39
        $fields->fieldByName('Root')->removeByName("Rates");
40
        if ($this->isInDB()) {
41
            $tablefield = new GridField("Rates", "TableShippingRate", $this->Rates(), new GridFieldConfig_RecordEditor());
0 ignored issues
show
Documentation Bug introduced by
The method Rates does not exist on object<TableShippingMethod>? 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...
42
            $fields->addFieldToTab("Root.Main", $tablefield);
43
        }
44
45
        return $fields;
46
    }
47
48
    /**
49
     * Find the appropriate shipping rate from stored table range metrics
50
     */
51
    public function calculateRate(ShippingPackage $package, Address $address)
52
    {
53
        $rate = null;
54
        $packageconstraints = array(
55
            "Weight"   => 'weight',
56
            "Volume"   => 'volume',
57
            "Value"    => 'value',
58
            "Quantity" => 'quantity'
59
        );
60
        $constraintfilters = array();
61
        $emptyconstraint = array();
62
        foreach ($packageconstraints as $db => $pakval) {
63
            $mincol = "\"TableShippingRate\".\"{$db}Min\"";
64
            $maxcol = "\"TableShippingRate\".\"{$db}Max\"";
65
            //constrain to rates with valid constraints
66
            $constraintfilters[] =
67
                "(" .
68
                "$mincol >= 0" .
69
                " AND $mincol <= " . $package->{$pakval}() .
70
                " AND $maxcol > 0" . //ignore constraints with maxvalue = 0
71
                " AND $maxcol >= " . $package->{$pakval}() .
72
                " AND $mincol < $maxcol" . //sanity check
73
                ")";
74
            //also include a special case where all constraints are empty
75
            $emptyconstraint[] = "($mincol = 0 AND $maxcol = 0)";
76
        }
77
        $constraintfilters[] = "(" . implode(" AND ", $emptyconstraint) . ")";
78
79
        $filter = "(" . implode(") AND (", array(
80
                "\"ShippingMethodID\" = " . $this->ID,
81
                RegionRestriction::address_filter($address), //address restriction
82
                implode(" OR ", $constraintfilters) //metrics restriction
83
            )) . ")";
84
        if ($tr = DataObject::get_one("TableShippingRate", $filter, true, "LENGTH(\"RegionRestriction\".\"PostalCode\") DESC, Rate ASC")) {
85
            $rate = $tr->Rate;
86
        }
87
        $this->CalculatedRate = $rate;
0 ignored issues
show
Documentation introduced by
The property CalculatedRate does not exist on object<TableShippingMethod>. 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...
88
89
        return $rate;
90
    }
91
92
    /**
93
     * If this shipping method has any @TableShippingRate with any @RegionRestriction where either Country, State, City or PostalCode are submitted, this method returns true
94
     * Else it returns false (@ShippingMethod::requiresAddress());
95
     *
96
     * @return bool
97
     */
98
    public function requiresAddress()
99
    {
100
        if ($this->Rates()->exists()) {
0 ignored issues
show
Documentation Bug introduced by
The method Rates does not exist on object<TableShippingMethod>? 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...
101
            $defaults = RegionRestriction::config()->get('defaults');
102
            $filter = [];
103
            foreach($defaults as $field => $val){
104
                $filter[$field . ':not'] = $val;
105
            }
106
            $rates = $this->Rates()->filterAny($filter);
0 ignored issues
show
Documentation Bug introduced by
The method Rates does not exist on object<TableShippingMethod>? 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...
107
            if($rates->exists()){
108
                return true;
109
            }
110
        }
111
112
        return parent::requiresAddress();
113
    }
114
}
115
116
/**
117
 * Adds extra metric ranges to restrict with, rather than just region.
118
 */
119
class TableShippingRate extends RegionRestriction
120
{
121
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
122
        //constraint values
123
        "WeightMin"   => "Decimal",
124
        "WeightMax"   => "Decimal",
125
        "VolumeMin"   => "Decimal",
126
        "VolumeMax"   => "Decimal",
127
        "ValueMin"    => "Currency",
128
        "ValueMax"    => "Currency",
129
        "QuantityMin" => "Int",
130
        "QuantityMax" => "Int",
131
132
        "Rate" => "Currency"
133
    );
134
135
    private static $has_one = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
136
        "ShippingMethod" => "TableShippingMethod"
137
    );
138
139
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
140
        'Country',
141
        'State',
142
        'City',
143
        'PostalCode',
144
        'WeightMin',
145
        'WeightMax',
146
        'VolumeMin',
147
        'VolumeMax',
148
        'ValueMin',
149
        'ValueMax',
150
        'QuantityMin',
151
        'QuantityMax',
152
        'Rate'
153
    );
154
155
    private static $default_sort = "\"Country\" ASC, \"State\" ASC, \"City\" ASC, \"PostalCode\" ASC, \"Rate\" ASC";
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
156
157
    public function getCMSFields()
158
    {
159
        $fields = parent::getCMSFields();
160
        $fields->removeByName('ShippingMethodID');
161
162
        return $fields;
163
    }
164
}
165