Completed
Pull Request — master (#11889)
by Mike
12:12
created

WC_Cart_Item::get_weight()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
if ( ! defined( 'ABSPATH' ) ) {
3
	exit;
4
}
5
6
/**
7
 * Cart Item.
8
 *
9
 * @version		2.7.0
10
 * @package		WooCommerce/Classes
11
 * @category	Class
12
 * @author 		WooThemes
13
 */
14
class WC_Cart_Item implements ArrayAccess {
15
16
	/**
17
	 * Cart Data array.
18
	 * @since 2.7.0
19
	 * @var array
20
	 */
21
	protected $data = array(
22
		'product_id' => 0,
23
		'quantity'   => 0,
24
		'variation'  => array(),
25
	);
26
27
	/**
28
	 * Product this item represents.
29
	 * @var WC_Product
30
	 */
31
	protected $product = null;
32
33
	/**
34
	 * Constructor.
35
	 * @param array $data
36
	 */
37
	public function __construct( $data = array() ) {
38
		$this->set_data( $data );
39
	}
40
41
	/**
42
	 * offsetGet for ArrayAccess/Backwards compatibility.
43
	 * @deprecated Add deprecation notices in future release.
44
	 * @param string $offset
45
	 * @return mixed
46
	 */
47
	public function offsetGet( $offset ) {
48
		switch ( $offset ) {
49
			case 'data' :
50
				return $this->get_product();
51
			case 'variation_id' :
52
				return is_callable( array( $this, 'get_variation_id' ) ) ? $this->get_product()->get_variation_id() : 0;
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class WC_Product as the method get_variation_id() does only exist in the following sub-classes of WC_Product: WC_Product_Variation. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
53
		}
54
		return isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : '';
55
	}
56
57
	/**
58
	 * offsetSet for ArrayAccess/Backwards compatibility.
59
	 * @deprecated Add deprecation notices in future release.
60
	 * @param string $offset
61
	 * @param mixed $value
62
	 */
63
	public function offsetSet( $offset, $value ) {
64
		switch ( $offset ) {
65
			case 'data' :
66
				$this->set_product( $value );
67
				break;
68
			case 'variation_id' :
69
				$this->set_product( wc_get_product( $value ) );
0 ignored issues
show
Documentation introduced by
wc_get_product($value) is of type object<WC_Product>, but the function expects a integer.

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...
70
				break;
71
			default :
72
				$this->data[ $offset ] = $value;
73
				break;
74
		}
75
	}
76
77
	/**
78
	 * offsetExists for ArrayAccess
79
	 * @param string $offset
80
	 * @return bool
81
	 */
82
	public function offsetExists( $offset ) {
83 View Code Duplication
		if ( in_array( $offset, array( 'data' ) ) || isset( $this->data[ $offset ] ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
			return true;
85
		}
86
		return false;
87
	}
88
89
	/**
90
	 * offsetUnset for ArrayAccess
91
	 * @param string $offset
92
	 */
93
	public function offsetUnset( $offset ) {
94
		unset( $this->data[ $offset ] );
95
	}
96
97
	/**
98
	 * Gets price of the product.
99
	 * @return float
100
	 */
101
	public function get_price() {
102
		return $this->get_product() ? $this->get_product()->get_price() : 0;
103
	}
104
105
	/**
106
	 * Gets price of the product.
107
	 * @return float
108
	 */
109
	public function get_weight() {
110
		return $this->get_product() ? $this->get_product()->get_weight() : 0;
111
	}
112
113
	/**
114
	 * Gets price of the product.
115
	 * @return float
116
	 */
117
	public function get_tax_class() {
118
		return $this->get_product() ? $this->get_product()->get_tax_class() : '';
119
	}
120
121
	/**
122
	 * Set product.
123
	 * @param int $value
124
	 */
125
	public function set_product( $value ) {
126
		$this->product = $value;
0 ignored issues
show
Documentation Bug introduced by
It seems like $value of type integer is incompatible with the declared type object<WC_Product> of property $product.

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...
127
		$this->data['product_id'] = is_callable( array( $this->product, 'get_variation_id' ) ) ? $this->product->get_variation_id() : $this->product->get_id();
0 ignored issues
show
Bug introduced by
The method get_variation_id cannot be called on $this->product (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
Bug introduced by
The method get_id cannot be called on $this->product (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
128
	}
129
130
	/**
131
	 * Get product object.
132
	 * @return WC_Product
133
	 */
134
	public function get_product() {
135
		return ! is_null( $this->product ) ? $this->product : ( $this->product = wc_get_product( $this->get_product_id() ) );
136
	}
137
138
	/**
139
	 * Get all item data.
140
	 * @return array
141
	 */
142
	public function get_data() {
143
		return $this->data;
144
	}
145
146
	/**
147
	 * Product or variation ID this item represents.
148
	 * @return int
149
	 */
150
	public function get_product_id() {
151
		return $this->data['product_id'];
152
	}
153
154
	/**
155
	 * Get quantity in cart.
156
	 * @return int
157
	 */
158
	public function get_quantity() {
159
		return $this->data['quantity'];
160
	}
161
162
	/**
163
	 * Get variation data.
164
	 * @return array
165
	 */
166
	public function get_variation() {
167
		return $this->data['variation'];
168
	}
169
170
	/**
171
	 * Set product ID.
172
	 * @param int $value
173
	 */
174
	public function set_product_id( $value ) {
175
		$this->data['product_id'] = absint( $value );
176
		$this->product = null;
177
	}
178
179
	/**
180
	 * Set Quantity.
181
	 * @param int $value
182
	 */
183
	public function set_quantity( $value ) {
184
		$this->data['quantity'] = wc_stock_amount( $value );
185
	}
186
187
	/**
188
	 * Set variation data.
189
	 * @param array $value
190
	 */
191
	public function set_variation( $value ) {
192
		$this->data['variation'] = (array) $value;
193
	}
194
195
	/**
196
	 * Set all data.
197
	 * @param array $value
0 ignored issues
show
Documentation introduced by
There is no parameter named $value. Did you maybe mean $values?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

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

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

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

Loading history...
198
	 */
199
	public function set_data( $values ) {
200
		if ( is_a( $values, 'WC_Cart_Item' ) ) {
201
			$values = $values->get_data();
202
		}
203
		foreach ( $values as $key => $value ) {
204
			if ( in_array( $key, array( 'quantity', 'product_id', 'variation', 'product' ) ) ) {
205
				$this->{ "set_$key" }( $value );
206
			} else {
207
				$this->data[ $key ] = $value;
208
			}
209
		}
210
	}
211
}
212