get_items()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 25
c 0
b 0
f 0
nc 6
nop 1
dl 0
loc 41
rs 9.52
1
<?php
2
/**
3
 * REST API top sellers controller
4
 *
5
 * Handles requests to the reports/top_sellers endpoint.
6
 *
7
 * @package GetPaid
8
 * @subpackage REST API
9
 * @since   2.0.0
10
 */
11
12
defined( 'ABSPATH' ) || exit;
13
14
/**
15
 * GetPaid REST top sellers controller class.
16
 *
17
 * @package GetPaid
18
 */
19
class GetPaid_REST_Report_Top_Sellers_Controller extends GetPaid_REST_Report_Sales_Controller {
20
21
	/**
22
	 * Route base.
23
	 *
24
	 * @var string
25
	 */
26
	protected $rest_base = 'reports/top_sellers';
27
28
	/**
29
	 * Get top sellers report.
30
	 *
31
	 * @param WP_REST_Request $request
32
	 * @return array|WP_Error
33
	 */
34
	public function get_items( $request ) {
35
36
		// Prepare items.
37
		$this->report_range = $this->get_date_range( $request );
38
		$report_data        = $this->get_report_data();
39
40
		$top_sellers = array();
41
42
		foreach ( $report_data as $item ) {
43
44
			$item_obj  = new WPInv_Item( $item );
0 ignored issues
show
Unused Code introduced by
The assignment to $item_obj is dead and can be removed.
Loading history...
45
			$item_name = $item->invoice_item_name;
46
			$item_qty  = floatval( $item->invoice_item_qty );
47
			$item_id   = absint( $item->invoice_item_id );
48
			$price     = sanitize_text_field( wpinv_price( $item->invoice_item_price ) );
49
50
			$item_obj  = new WPInv_Item( $item_id );
51
52
			if ( $item_obj->exists() ) {
53
				$item_name = $item_obj->get_name();
54
			} else {
55
				$item_id   = 0;
56
			}
57
58
			$top_sellers[] = array(
59
				'name'               => sanitize_text_field( $item_name ),
60
				'item_id'            => $item_id,
61
				'quantity'           => $item_qty,
62
				'earnings'           => wpinv_round_amount( $item->invoice_item_price ),
63
				'earnings_formatted' => sanitize_text_field( wpinv_price( $price ) ),
0 ignored issues
show
Bug introduced by
$price of type string is incompatible with the type double expected by parameter $amount of wpinv_price(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

63
				'earnings_formatted' => sanitize_text_field( wpinv_price( /** @scrutinizer ignore-type */ $price ) ),
Loading history...
64
			);
65
66
		}
67
68
		$data = array();
69
		foreach ( $top_sellers as $top_seller ) {
70
			$item   = $this->prepare_item_for_response( (object) $top_seller, $request );
71
			$data[] = $this->prepare_response_for_collection( $item );
72
		}
73
74
		return rest_ensure_response( $data );
0 ignored issues
show
Bug Best Practice introduced by
The expression return rest_ensure_response($data) returns the type WP_REST_Response which is incompatible with the documented return type WP_Error|array.
Loading history...
75
76
	}
77
78
	/**
79
	 * Prepare a report sales object for serialization.
80
	 *
81
	 * @param stdClass $top_seller
82
	 * @param WP_REST_Request $request Request object.
83
	 * @return WP_REST_Response $response Response data.
84
	 */
85
	public function prepare_item_for_response( $top_seller, $request ) {
86
		$data    = (array) $top_seller;
87
88
		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';
89
		$data    = $this->add_additional_fields_to_object( $data, $request );
90
		$data    = $this->filter_response_by_context( $data, $context );
91
92
		// Wrap the data in a response object.
93
		$response = rest_ensure_response( $data );
94
		$links = array(
95
			'about' => array(
96
				'href' => rest_url( sprintf( '%s/reports', $this->namespace ) ),
97
			),
98
		);
99
100
		if ( ! empty( $top_seller->item_id ) ) {
101
			$links['item']   = array(
102
				'href'       => rest_url( sprintf( '/%s/items/%s', $this->namespace, $top_seller->item_id ) ),
103
				'embeddable' => true,
104
			);
105
		}
106
107
		$response->add_links( $links );
108
		return apply_filters( 'getpaid_rest_prepare_report_' . $this->rest_base, $response, $top_seller, $request );
109
	}
110
111
	/**
112
	 * Get all data needed for this report and store in the class.
113
	 */
114
	protected function query_report_data() {
115
116
		$this->report_data = GetPaid_Reports_Helper::get_invoice_report_data(
0 ignored issues
show
Documentation Bug introduced by
It seems like GetPaid_Reports_Helper::...> $this->report_range)) can also be of type string. However, the property $report_data is declared as type stdClass. 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...
117
			array(
118
				'data'         => array(
119
					'quantity'  => array(
120
						'type'     => 'invoice_item',
121
						'function' => 'SUM',
122
						'name'     => 'invoice_item_qty',
123
					),
124
					'item_id'   => array(
125
						'type'     => 'invoice_item',
126
						'function' => '',
127
						'name'     => 'invoice_item_id',
128
					),
129
					'item_name' => array(
130
						'type'     => 'invoice_item',
131
						'function' => '',
132
						'name'     => 'invoice_item_name',
133
					),
134
					'price'     => array(
135
						'type'     => 'invoice_item',
136
						'function' => 'SUM',
137
						'name'     => 'invoice_item_price',
138
					),
139
				),
140
				'group_by'     => 'invoice_item_id',
141
				'order_by'     => 'invoice_item_qty DESC',
142
				'query_type'   => 'get_results',
143
				'limit'        => 10,
144
				'filter_range' => $this->report_range,
145
			)
146
		);
147
148
	}
149
150
	/**
151
	 * Get the Report's schema, conforming to JSON Schema.
152
	 *
153
	 * @return array
154
	 */
155
	public function get_item_schema() {
156
		$schema = array(
157
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
158
			'title'      => $this->rest_base,
159
			'type'       => 'object',
160
			'properties' => array(
161
				'name'                => array(
162
					'description' => __( 'Item name.', 'invoicing' ),
163
					'type'        => 'string',
164
					'context'     => array( 'view' ),
165
					'readonly'    => true,
166
				),
167
				'item_id'             => array(
168
					'description' => __( 'Item ID.', 'invoicing' ),
169
					'type'        => 'integer',
170
					'context'     => array( 'view' ),
171
					'readonly'    => true,
172
				),
173
				'quantity'            => array(
174
					'description' => __( 'Total number of purchases.', 'invoicing' ),
175
					'type'        => 'number',
176
					'context'     => array( 'view' ),
177
					'readonly'    => true,
178
				),
179
				'earnings'            => array(
180
					'description' => __( 'Total earnings for the item.', 'invoicing' ),
181
					'type'        => 'number',
182
					'context'     => array( 'view' ),
183
					'readonly'    => true,
184
				),
185
				'earnings_formatted"' => array(
186
					'description' => __( 'Total earnings (formatted) for the item.', 'invoicing' ),
187
					'type'        => 'string',
188
					'context'     => array( 'view' ),
189
					'readonly'    => true,
190
				),
191
			),
192
		);
193
194
		return $this->add_additional_fields_schema( $schema );
195
	}
196
}
197