Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.77% covered (warning)
80.77%
21 / 26
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Set_Provider_CSS
80.77% covered (warning)
80.77%
21 / 26
50.00% covered (danger)
50.00%
1 / 2
7.35
0.00% covered (danger)
0.00%
0 / 1
 handle
80.00% covered (warning)
80.00%
20 / 25
0.00% covered (danger)
0.00%
0 / 1
6.29
 unmask_content
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace Automattic\Jetpack_Boost\Lib\Critical_CSS\Data_Sync_Actions;
4
5use Automattic\Jetpack\WP_JS_Data_Sync\Contracts\Data_Sync_Action;
6use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_State;
7use Automattic\Jetpack_Boost\Lib\Critical_CSS\Critical_CSS_Storage;
8use Automattic\Jetpack_Boost\Lib\Critical_CSS\Display_Critical_CSS;
9
10/**
11 * Critical CSS Action: Set CSS for a provider.
12 */
13class Set_Provider_CSS implements Data_Sync_Action {
14
15    /**
16     * Handles the action logic.
17     *
18     * @param mixed            $data     JSON Data passed to the action.
19     * @param \WP_REST_Request $_request The request object.
20     */
21    public function handle( $data, $_request ) {
22        $state = new Critical_CSS_State();
23
24        if ( empty( $data['key'] ) || empty( $data['css'] ) ) {
25            return array(
26                'success' => false,
27                'state'   => $state->get(),
28                'error'   => 'Invalid data',
29            );
30        }
31
32        $provider_key = sanitize_key( $data['key'] );
33        $css          = $this->unmask_content( $data['css'] );
34        $storage      = new Critical_CSS_Storage();
35        $success      = strlen( $css ) <= Display_Critical_CSS::MAX_CSS_BYTES;
36        $error        = null;
37        if ( ! $success ) {
38            $storage->delete_css( $provider_key );
39            $error = $state->set_provider_payload_too_large( $provider_key );
40            if ( is_wp_error( $error ) ) {
41                $state->set_error( $error->get_error_message() );
42            }
43        } else {
44            $storage->store_css( $provider_key, $css );
45            $state->set_provider_success( $provider_key );
46        }
47        $state->save();
48
49        return array(
50            'success' => $success,
51            'state'   => $state->get(),
52            'error'   => is_wp_error( $error ) ? $error->get_error_message() : '',
53        );
54    }
55
56    /**
57     * Unmasks the content.
58     *
59     * @param string $content The content to unmask.
60     * @return string The unmasked content.
61     */
62    private function unmask_content( $content ) {
63        return str_replace( '__JB_XMLNS__', 'xmlns', $content );
64    }
65}