Completed
Branch FET/11450/reserved-instance-in... (0b2d22)
by
unknown
32:10 queued 12:45
created

Stats   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 215
Duplicated Lines 3.26 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 7
loc 215
rs 10
c 0
b 0
f 0
wmc 21
lcom 1
cbo 5

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A setUxipNotices() 0 10 2
A statsCallback() 0 11 2
A canDisplayNotices() 0 5 2
A optinNotice() 0 16 1
B optinText() 0 40 3
A enqueueScripts() 7 19 1
A ajaxHandler() 0 11 3
A sendStats() 0 6 3
A statSendTimestampExpired() 0 14 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace EventEspresso\core\domain\services\pue;
3
4
use Closure;
5
use EE_Admin_Page;
6
use EE_Error;
7
use EE_Maintenance_Mode;
8
use EEH_Template;
9
use EEM_Payment_Method;
10
use Exception;
11
12
/**
13
 * Stats
14
 * This service exposes various stat collection logic retrieval and storage. Used for prepping the stats package sent
15
 * through PUE as a part of the UXIP stats collection.
16
 *
17
 * @package EventEspresso\core\domain\services\pue
18
 * @author  Darren Ethier
19
 * @since   4.9.59.p
20
 */
21
class Stats
22
{
23
24
    const OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS = 'ee_uxip_stats_expiry';
25
26
    /**
27
     * @var Config
28
     */
29
    private $config;
30
31
32
    /**
33
     * @var StatsGatherer
34
     */
35
    private $stats_gatherer;
36
37
38
    /**
39
     * @var EE_Maintenance_Mode
40
     */
41
    private $maintenance_mode;
42
43
    public function __construct(
44
        Config $config,
45
        EE_Maintenance_Mode $maintenance_mode,
46
        StatsGatherer $stats_gatherer
47
    ) {
48
        $this->config = $config;
49
        $this->maintenance_mode = $maintenance_mode;
50
        $this->stats_gatherer = $stats_gatherer;
51
        $this->setUxipNotices();
52
    }
53
54
55
    /**
56
     * Displays uxip opt-in notice if necessary.
57
     */
58
    private function setUxipNotices()
59
    {
60
        if ($this->canDisplayNotices()) {
61
            add_action('admin_notices', array($this, 'optinNotice'));
62
            add_action('admin_enqueue_scripts', array($this, 'enqueueScripts'));
63
            add_action('wp_ajax_espresso_data_optin', array($this, 'ajaxHandler'));
64
            //makes sure optin defaults to yes even if its currently empty.
65
            $this->config->setHasOptedInForUxip();
66
        }
67
    }
68
69
70
    /**
71
     * This returns the callback that PluginUpdateEngineChecker will use for getting any extra stats to send.
72
     * @return Closure
73
     */
74
    public function statsCallback()
75
    {
76
        //returns a callback that can is used to retrieve the stats to send along to the pue server.
77
        return function () {
78
            //we only send stats one a week, so let's see if our stat timestamp has expired.
79
            if (! $this->sendStats()) {
80
                return array();
81
            }
82
            return $this->stats_gatherer->stats();
83
        };
84
    }
85
86
87
    /**
88
     * Return whether notices can be displayed or not
89
     * @return bool
90
     */
91
    private function canDisplayNotices()
92
    {
93
        return ! $this->config->hasNotifiedForUxip()
94
               && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance;
95
    }
96
97
98
    /**
99
     * Callback for the admin_notices hook that outputs the UXIP optin-in notice.
100
     */
101
    public function optinNotice()
102
    {
103
        ?>
104
        <div class="updated data-collect-optin" id="espresso-data-collect-optin-container">
105
            <div id="data-collect-optin-options-container">
106
                <span class="dashicons dashicons-admin-site"></span>
107
                <span class="data-optin-text"><?php echo self::optinText(); ?></span>
108
                <span style="display: none" id="data-optin-nonce"><?php echo wp_create_nonce('ee-data-optin'); ?></span>
109
                <button class="button-secondary data-optin-button" value="no">
110
                    <?php _e('Dismiss', 'event_espresso'); ?>
111
                </button>
112
                <div style="clear:both"></div>
113
            </div>
114
        </div>
115
        <?php
116
    }
117
118
119
    /**
120
     * Retrieves the optin text (static so it can be used in multiple places as necessary).
121
     * @param bool $extra
122
     */
123
    public static function optinText($extra = true)
124
    {
125
        if (! $extra) {
126
            echo '<h2 class="ee-admin-settings-hdr" '
127
                 . (! $extra ? 'id="UXIP_settings"' : '')
128
                 . '>'
129
                 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
130
                 . EEH_Template::get_help_tab_link('organization_logo_info')
131
                 . '</h2>';
132
            printf(
133
                esc_html__(
134
                    '%sPlease help us make Event Espresso better and vote for your favorite features.%s The %sUser eXperience Improvement Program (UXIP)%s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary but it is enabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %sPlease see our %sPrivacy Policy%s for more information.',
135
                    'event_espresso'
136
                ),
137
                '<p><em>',
138
                '</em></p>',
139
                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
140
                '</a>',
141
                '<br><br>',
142
                '<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
143
                '</a>'
144
            );
145
        } else {
146
            $settings_url = EE_Admin_Page::add_query_args_and_nonce(
147
                array('action' => 'default'),
148
                admin_url('admin.php?page=espresso_general_settings')
149
            );
150
            $settings_url .= '#UXIP_settings';
151
            printf(
152
                esc_html__(
153
                    'The Event Espresso UXIP feature is active on your site. For %smore info%s and to opt-out %sclick here%s.',
154
                    'event_espresso'
155
                ),
156
                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
157
                '</a>',
158
                '<a href="' . $settings_url . '" target="_blank">',
159
                '</a>'
160
            );
161
        }
162
    }
163
164
165
    /**
166
     * Callback for admin_enqueue_scripts that sets up the scripts and styles for the uxip notice
167
     */
168 View Code Duplication
    public function enqueueScripts()
169
    {
170
        wp_register_script(
171
            'ee-data-optin-js',
172
            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
173
            array('jquery'),
174
            EVENT_ESPRESSO_VERSION,
175
            true
176
        );
177
        wp_register_style(
178
            'ee-data-optin-css',
179
            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
180
            array(),
181
            EVENT_ESPRESSO_VERSION
182
        );
183
184
        wp_enqueue_script('ee-data-optin-js');
185
        wp_enqueue_style('ee-data-optin-css');
186
    }
187
188
189
    /**
190
     * Callback for wp_ajax_espresso_data_optin that handles the ajax request
191
     */
192
    public function ajaxHandler()
193
    {
194
        //verify nonce
195
        if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
196
            exit();
197
        }
198
199
        //update has notified option
200
        $this->config->setHasNotifiedAboutUxip();
201
        exit();
202
    }
203
204
205
    /**
206
     * Used to determine whether additional stats are sent.
207
     */
208
    private function sendStats()
209
    {
210
        return $this->config->isOptedInForUxip()
211
            && $this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance
212
            && $this->statSendTimestampExpired();
213
    }
214
215
216
    /**
217
     * Returns true when the timestamp used to track whether stats get sent (currently a weekly interval) is expired.
218
     * Returns false otherwise.
219
     * @return bool
220
     */
221
    private function statSendTimestampExpired()
222
    {
223
        $current_expiry = get_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, null);
224
        if ($current_expiry === null) {
225
            add_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS, '', 'no');
226
            return true;
227
        }
228
229
        if (time() > (int) $current_expiry) {
230
            update_option(self::OPTIONS_KEY_EXPIRY_TIMESTAMP_FOR_SENDING_STATS, time() + WEEK_IN_SECONDS);
231
            return true;
232
        }
233
        return false;
234
    }
235
}