Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
99.17% covered (success)
99.17%
120 / 121
90.91% covered (success)
90.91%
10 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
Report_Executor
99.17% covered (success)
99.17%
120 / 121
90.91% covered (success)
90.91%
10 / 11
46
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 execute
97.30% covered (success)
97.30%
36 / 37
0.00% covered (danger)
0.00%
0 / 1
14
 choose
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
7
 unsupported_provider
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 check_fields
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
4
 check_capability
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
3
 get_missing_fields
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 describe
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
6
 get_capability
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 uncovered
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_success
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2/**
3 * Picks the handler of a report request and runs it.
4 *
5 * @package automattic/jetpack-woocommerce-stats
6 */
7
8namespace Automattic\Jetpack\WooCommerceStats\Report_Execution;
9
10use WP_Error;
11
12/**
13 * Resolves a route to its report and a provider's handler, runs it without falling back, and
14 * checks the answer against the report's contract.
15 *
16 * @since 0.3.3
17 */
18class Report_Executor {
19
20    /**
21     * `provider` value that follows the site's `Provider_Setting`.
22     */
23    private const AUTO = 'auto';
24
25    /**
26     * Response header naming the provider that served the report.
27     */
28    private const PROVIDER_HEADER = 'X-Jetpack-Report-Provider';
29
30    /**
31     * Response header naming the report's contract, as `id@version`.
32     */
33    private const CONTRACT_HEADER = 'X-Jetpack-Report-Contract';
34
35    /**
36     * Reports, handlers and providers.
37     *
38     * @var Report_Registry
39     */
40    private $registry;
41
42    /**
43     * Constructor.
44     *
45     * @param Report_Registry $registry Reports, handlers and providers.
46     */
47    public function __construct( Report_Registry $registry ) {
48        $this->registry = $registry;
49    }
50
51    /**
52     * Serve a report from the handler the request resolves to.
53     *
54     * @param string        $route         Route below `analytics/reports/`.
55     * @param array         $params        The report's query params, without the proxy's own.
56     * @param string|null   $provider      The validated `provider` param, `AUTO` for the site's setting, or null when the request names none.
57     * @param bool          $force_refresh Whether to skip caches.
58     * @param string[]|null $fields        Summary fields the caller reads, or null for the whole report.
59     * @return array|WP_Error The handler's payload with the report headers, or an error: `unknown_report` (404),
60     *                        `fields_not_described`, `unknown_field`, `unsupported_provider`, `unsupported_fields`,
61     *                        `unsupported_parameter` (422), `contract_violation` (502), the provider's or the handler's.
62     */
63    public function execute( $route, array $params, $provider = null, $force_refresh = false, $fields = null ) {
64        $definition = $this->registry->get_definition_for_route( $route );
65        if ( null === $definition ) {
66            return new WP_Error(
67                'unknown_report',
68                __( 'No report is defined for this route.', 'jetpack-woocommerce-stats-pkg' ),
69                array( 'status' => 404 )
70            );
71        }
72
73        if ( null !== $fields ) {
74            $error = self::check_fields( $definition, $fields );
75            if ( is_wp_error( $error ) ) {
76                return $error;
77            }
78        }
79
80        $request = new Report_Request( $definition, $route, $params, $force_refresh, $fields );
81
82        // A request naming no provider leaves readiness to the handler: the forward serves its cache before checking the connection.
83        if ( null === $provider ) {
84            $name    = Provider_Setting::DEFAULT_PROVIDER;
85            $handler = $this->registry->get_handler( $definition->id, $name );
86            if ( null === $handler ) {
87                return self::unsupported_provider( $name );
88            }
89        } else {
90            $chosen = $this->choose( self::AUTO === $provider ? Provider_Setting::get_providers() : array( $provider ), $request );
91            if ( is_wp_error( $chosen ) ) {
92                return $chosen;
93            }
94            list( $name, $handler ) = $chosen;
95
96            $ready = $this->registry->get_provider( $name )->check_ready();
97            if ( true === $ready && $handler instanceof Report_Readiness ) {
98                $ready = $handler->check_ready();
99            }
100            if ( is_wp_error( $ready ) ) {
101                return $ready;
102            }
103        }
104
105        $payload = $handler->run( $request );
106        if ( is_wp_error( $payload ) || ! self::is_success( $payload ) ) {
107            return $payload;
108        }
109
110        $missing = self::get_missing_fields( $payload, $request );
111        if ( $missing ) {
112            return new WP_Error(
113                'contract_violation',
114                /* translators: %s: comma-separated field names. */
115                sprintf( __( 'The report came back without: %s.', 'jetpack-woocommerce-stats-pkg' ), implode( ', ', $missing ) ),
116                array( 'status' => 502 )
117            );
118        }
119
120        return self::describe( $payload, $name, $handler, $definition );
121    }
122
123    /**
124     * The first provider whose handler covers and supports the request. Readiness is checked after
125     * the choice and never fallen back from, so a request's provider doesn't depend on the site's state.
126     *
127     * @param non-empty-array<string> $names   Provider names, in order of preference.
128     * @param Report_Request          $request The request.
129     * @return array{0: string, 1: Report_Handler}|WP_Error The provider name and its handler, or the first registered provider's refusal.
130     */
131    private function choose( array $names, Report_Request $request ) {
132        $refusals = array();
133        foreach ( $names as $name ) {
134            $handler = $this->registry->get_handler( $request->definition->id, $name );
135            if ( null === $handler ) {
136                // Skip a name nothing registered, but keep a registered provider's refusal.
137                if ( null !== $this->registry->get_provider( $name ) ) {
138                    $refusals[] = self::unsupported_provider( $name );
139                }
140                continue;
141            }
142
143            $covered = self::check_capability( $handler, $request );
144            if ( ! is_wp_error( $covered ) && $handler instanceof Report_Support ) {
145                $covered = $handler->supports( $request );
146            }
147            if ( ! is_wp_error( $covered ) ) {
148                return array( $name, $handler );
149            }
150            $refusals[] = $covered;
151        }
152
153        return $refusals[0] ?? self::unsupported_provider( $names[0] );
154    }
155
156    /**
157     * A 422 for a provider without a handler for the report.
158     *
159     * @param string $name Provider name.
160     * @return WP_Error
161     */
162    private static function unsupported_provider( $name ) {
163        return new WP_Error(
164            'unsupported_provider',
165            /* translators: %s: provider name, such as wpcom or local. */
166            sprintf( __( 'This report cannot be served by the %s provider.', 'jetpack-woocommerce-stats-pkg' ), $name ),
167            array( 'status' => 422 )
168        );
169    }
170
171    /**
172     * Refuse named fields the report's contract doesn't list.
173     *
174     * @param Report_Definition $definition The report.
175     * @param string[]          $fields     Field names the caller named.
176     * @return true|WP_Error A 422 when the report is undescribed, or a name is unknown or missing.
177     */
178    private static function check_fields( Report_Definition $definition, array $fields ) {
179        if ( null === $definition->fields ) {
180            return new WP_Error(
181                'fields_not_described',
182                __( 'This report has no field contract yet, so it can only be requested whole.', 'jetpack-woocommerce-stats-pkg' ),
183                array( 'status' => 422 )
184            );
185        }
186
187        if ( ! $fields ) {
188            return new WP_Error(
189                'unknown_field',
190                __( 'Name at least one field of the report.', 'jetpack-woocommerce-stats-pkg' ),
191                array( 'status' => 422 )
192            );
193        }
194
195        $unknown = array_values( array_diff( $fields, $definition->get_field_names() ) );
196        if ( $unknown ) {
197            return new WP_Error(
198                'unknown_field',
199                /* translators: %s: comma-separated field names. */
200                sprintf( __( 'This report has no such field: %s.', 'jetpack-woocommerce-stats-pkg' ), implode( ', ', $unknown ) ),
201                array( 'status' => 422 )
202            );
203        }
204
205        return true;
206    }
207
208    /**
209     * Whether a handler covers the request's params and fields, by what it declares.
210     *
211     * @param Report_Handler $handler The handler.
212     * @param Report_Request $request The request.
213     * @return true|WP_Error A 422 `unsupported_parameter` or `unsupported_fields`.
214     */
215    private static function check_capability( Report_Handler $handler, Report_Request $request ) {
216        $capability = self::get_capability( $handler );
217
218        $unsupported = self::uncovered( array_keys( $request->params ), $capability['params'] );
219        if ( $unsupported ) {
220            return new WP_Error(
221                'unsupported_parameter',
222                /* translators: %s: comma-separated query param names. */
223                sprintf( __( 'This provider cannot apply: %s.', 'jetpack-woocommerce-stats-pkg' ), implode( ', ', $unsupported ) ),
224                array( 'status' => 422 )
225            );
226        }
227
228        $unsupported = self::uncovered( $request->get_requested_fields(), $capability['fields'] );
229        if ( $unsupported ) {
230            return new WP_Error(
231                'unsupported_fields',
232                /* translators: %s: comma-separated field names. */
233                sprintf( __( 'This provider cannot produce: %s.', 'jetpack-woocommerce-stats-pkg' ), implode( ', ', $unsupported ) ),
234                array( 'status' => 422 )
235            );
236        }
237
238        return true;
239    }
240
241    /**
242     * Requested fields a successful answer lacks from its `summary`; checked only when the caller named fields.
243     *
244     * @param array          $payload The handler's payload.
245     * @param Report_Request $request The request.
246     * @return string[]
247     */
248    private static function get_missing_fields( array $payload, Report_Request $request ) {
249        if ( null === $request->fields ) {
250            return array();
251        }
252
253        $summary = ( (array) $payload['data'] )['summary'] ?? null;
254        $present = is_object( $summary ) || is_array( $summary ) ? array_keys( (array) $summary ) : array();
255
256        return array_values( array_diff( $request->fields, $present ) );
257    }
258
259    /**
260     * Name the provider and contract in headers, and list the contract fields the handler doesn't
261     * serve at the top of the body. The body is otherwise left as it came.
262     *
263     * @param array             $payload    The handler's payload.
264     * @param string            $provider   Provider name.
265     * @param Report_Handler    $handler    The handler that served it.
266     * @param Report_Definition $definition The report.
267     * @return array
268     */
269    private static function describe( array $payload, $provider, Report_Handler $handler, Report_Definition $definition ) {
270        $unsupported = self::uncovered( $definition->get_field_names(), self::get_capability( $handler )['fields'] );
271        if ( $unsupported && is_object( $payload['data'] ) ) {
272            $payload['data']                     = clone $payload['data'];
273            $payload['data']->unsupported_fields = $unsupported;
274        } elseif ( $unsupported && is_array( $payload['data'] ) && ! wp_is_numeric_array( $payload['data'] ) ) {
275            $payload['data']['unsupported_fields'] = $unsupported;
276        }
277
278        $payload['headers'] = array_merge(
279            (array) $payload['headers'],
280            array(
281                self::PROVIDER_HEADER => $provider,
282                self::CONTRACT_HEADER => $definition->get_contract(),
283            )
284        );
285
286        return $payload;
287    }
288
289    /**
290     * What a handler serves: everything unless it declares less.
291     *
292     * @param Report_Handler $handler The handler.
293     * @return array{fields: string[]|string, params: string[]|string}
294     */
295    private static function get_capability( Report_Handler $handler ) {
296        if ( $handler instanceof Report_Capability ) {
297            return $handler->get_capability();
298        }
299
300        return array(
301            'fields' => '*',
302            'params' => '*',
303        );
304    }
305
306    /**
307     * Names a capability list leaves out; none when it is `*`.
308     *
309     * @param string[]        $names    Names asked for.
310     * @param string[]|string $declared A capability list, or `*`.
311     * @return string[]
312     */
313    private static function uncovered( array $names, $declared ) {
314        return '*' === $declared ? array() : array_values( array_diff( $names, (array) $declared ) );
315    }
316
317    /**
318     * Whether a payload is a successful answer.
319     *
320     * @param array $payload The handler's payload.
321     * @return bool
322     */
323    private static function is_success( array $payload ) {
324        $status = (int) $payload['status'];
325
326        return $status >= 200 && $status < 300;
327    }
328}