Completed
Branch Gutenberg/master (c0e530)
by
unknown
91:03 queued 76:53
created
core/services/request/middleware/RecommendedVersions.php 2 patches
Indentation   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -19,182 +19,182 @@
 block discarded – undo
19 19
 class RecommendedVersions extends Middleware
20 20
 {
21 21
 
22
-    /**
23
-     * converts a Request to a Response
24
-     *
25
-     * @param RequestInterface  $request
26
-     * @param ResponseInterface $response
27
-     * @return ResponseInterface
28
-     * @throws InvalidDataTypeException
29
-     */
30
-    public function handleRequest(RequestInterface $request, ResponseInterface $response)
31
-    {
32
-        $this->request = $request;
33
-        $this->response = $response;
34
-        // check required WP version
35
-        if (! $this->minimumWordPressVersionRequired()) {
36
-            $this->request->unSetRequestParam('activate', true);
37
-            add_action('admin_notices', array($this, 'minimumWpVersionError'), 1);
38
-            $this->response->terminateRequest();
39
-            $this->response->deactivatePlugin();
40
-        }
41
-        // check recommended PHP version
42
-        if (! $this->minimumPhpVersionRecommended()) {
43
-            $this->displayMinimumRecommendedPhpVersionNotice();
44
-        }
45
-        // upcoming required version
46
-        if (! $this->upcomingRequiredPhpVersion()) {
47
-            $this->displayUpcomingRequiredVersion();
48
-        }
49
-        $this->response = $this->processRequestStack($this->request, $this->response);
50
-        return $this->response;
51
-    }
52
-
53
-
54
-    /**
55
-     * Helper method to assess installed wp version against given values.
56
-     * By default this compares the required minimum version of WP for EE against the installed version of WP
57
-     * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
58
-     * against) so consider that when sending in your values.
59
-     *
60
-     * @param string $version_to_check
61
-     * @param string $operator
62
-     * @return bool
63
-     */
64
-    public static function compareWordPressVersion($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
65
-    {
66
-        global $wp_version;
67
-        return version_compare(
68
-            // first account for wp_version being pre-release
69
-            // (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
70
-            strpos($wp_version, '-') > 0
71
-                ? substr($wp_version, 0, strpos($wp_version, '-'))
72
-                : $wp_version,
73
-            $version_to_check,
74
-            $operator
75
-        );
76
-    }
77
-
78
-
79
-    /**
80
-     * @return boolean
81
-     */
82
-    private function minimumWordPressVersionRequired()
83
-    {
84
-        return RecommendedVersions::compareWordPressVersion();
85
-    }
86
-
87
-
88
-    /**
89
-     * @param string $min_version
90
-     * @return boolean
91
-     */
92
-    private function checkPhpVersion($min_version = EE_MIN_PHP_VER_RECOMMENDED)
93
-    {
94
-        return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
95
-    }
96
-
97
-
98
-    /**
99
-     * @return boolean
100
-     */
101
-    private function minimumPhpVersionRecommended()
102
-    {
103
-        return $this->checkPhpVersion();
104
-    }
105
-
106
-
107
-    /**
108
-     * @return void
109
-     */
110
-    public function minimumWpVersionError()
111
-    {
112
-        global $wp_version;
113
-        ?>
22
+	/**
23
+	 * converts a Request to a Response
24
+	 *
25
+	 * @param RequestInterface  $request
26
+	 * @param ResponseInterface $response
27
+	 * @return ResponseInterface
28
+	 * @throws InvalidDataTypeException
29
+	 */
30
+	public function handleRequest(RequestInterface $request, ResponseInterface $response)
31
+	{
32
+		$this->request = $request;
33
+		$this->response = $response;
34
+		// check required WP version
35
+		if (! $this->minimumWordPressVersionRequired()) {
36
+			$this->request->unSetRequestParam('activate', true);
37
+			add_action('admin_notices', array($this, 'minimumWpVersionError'), 1);
38
+			$this->response->terminateRequest();
39
+			$this->response->deactivatePlugin();
40
+		}
41
+		// check recommended PHP version
42
+		if (! $this->minimumPhpVersionRecommended()) {
43
+			$this->displayMinimumRecommendedPhpVersionNotice();
44
+		}
45
+		// upcoming required version
46
+		if (! $this->upcomingRequiredPhpVersion()) {
47
+			$this->displayUpcomingRequiredVersion();
48
+		}
49
+		$this->response = $this->processRequestStack($this->request, $this->response);
50
+		return $this->response;
51
+	}
52
+
53
+
54
+	/**
55
+	 * Helper method to assess installed wp version against given values.
56
+	 * By default this compares the required minimum version of WP for EE against the installed version of WP
57
+	 * Note, $wp_version is the first parameter sent into the PHP version_compare function (what is being checked
58
+	 * against) so consider that when sending in your values.
59
+	 *
60
+	 * @param string $version_to_check
61
+	 * @param string $operator
62
+	 * @return bool
63
+	 */
64
+	public static function compareWordPressVersion($version_to_check = EE_MIN_WP_VER_REQUIRED, $operator = '>=')
65
+	{
66
+		global $wp_version;
67
+		return version_compare(
68
+			// first account for wp_version being pre-release
69
+			// (like RC, beta etc) which are usually in the format like 4.7-RC3-39519
70
+			strpos($wp_version, '-') > 0
71
+				? substr($wp_version, 0, strpos($wp_version, '-'))
72
+				: $wp_version,
73
+			$version_to_check,
74
+			$operator
75
+		);
76
+	}
77
+
78
+
79
+	/**
80
+	 * @return boolean
81
+	 */
82
+	private function minimumWordPressVersionRequired()
83
+	{
84
+		return RecommendedVersions::compareWordPressVersion();
85
+	}
86
+
87
+
88
+	/**
89
+	 * @param string $min_version
90
+	 * @return boolean
91
+	 */
92
+	private function checkPhpVersion($min_version = EE_MIN_PHP_VER_RECOMMENDED)
93
+	{
94
+		return version_compare(PHP_VERSION, $min_version, '>=') ? true : false;
95
+	}
96
+
97
+
98
+	/**
99
+	 * @return boolean
100
+	 */
101
+	private function minimumPhpVersionRecommended()
102
+	{
103
+		return $this->checkPhpVersion();
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return void
109
+	 */
110
+	public function minimumWpVersionError()
111
+	{
112
+		global $wp_version;
113
+		?>
114 114
         <div class="error">
115 115
             <p>
116 116
                 <?php
117
-                printf(
118
-                    __(
119
-                        'We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
120
-                        'event_espresso'
121
-                    ),
122
-                    EE_MIN_WP_VER_REQUIRED,
123
-                    $wp_version,
124
-                    '<br/>',
125
-                    '<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
126
-                );
127
-                ?>
117
+				printf(
118
+					__(
119
+						'We\'re sorry, but Event Espresso requires WordPress version %1$s or greater in order to operate. You are currently running version %2$s.%3$sFor information on how to update your version of WordPress, please go to %4$s.',
120
+						'event_espresso'
121
+					),
122
+					EE_MIN_WP_VER_REQUIRED,
123
+					$wp_version,
124
+					'<br/>',
125
+					'<a href="http://codex.wordpress.org/Updating_WordPress">http://codex.wordpress.org/Updating_WordPress</a>'
126
+				);
127
+				?>
128 128
             </p>
129 129
         </div>
130 130
         <?php
131
-    }
132
-
133
-
134
-    /**
135
-     *    _display_minimum_recommended_php_version_notice
136
-     *
137
-     * @access private
138
-     * @return void
139
-     * @throws InvalidDataTypeException
140
-     */
141
-    private function displayMinimumRecommendedPhpVersionNotice()
142
-    {
143
-        if ($this->request->isAdmin()) {
144
-            new PersistentAdminNotice(
145
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
146
-                sprintf(
147
-                    esc_html__(
148
-                        'Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
149
-                        'event_espresso'
150
-                    ),
151
-                    EE_MIN_PHP_VER_RECOMMENDED,
152
-                    PHP_VERSION,
153
-                    '<br/>',
154
-                    '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
155
-                )
156
-            );
157
-        }
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns whether the provided php version number is less than the current version of php installed on the server.
163
-     *
164
-     * @param string $version_required
165
-     * @return bool
166
-     */
167
-    private function upcomingRequiredPhpVersion($version_required = '5.5')
168
-    {
169
-        return true;
170
-        // return $this->checkPhpVersion($version_required);
171
-    }
172
-
173
-
174
-    /**
175
-     *  Sets a notice for an upcoming required version of PHP in the next update of EE core.
176
-     */
177
-    private function displayUpcomingRequiredVersion()
178
-    {
179
-        if ($this->request->isAdmin()
180
-            && apply_filters('FHEE__EE_Recommended_Versions__displayUpcomingRequiredVersion', true, $this->request)
181
-            && current_user_can('update_plugins')
182
-        ) {
183
-            add_action('admin_notices', function () {
184
-                echo '<div class="notice event-espresso-admin-notice notice-warning"><p>'
185
-                     . sprintf(
186
-                         esc_html__(
187
-                             'Please note: The next update of Event Espresso 4 will %1$srequire%2$s PHP 5.4.45 or greater.  Your web server\'s PHP version is %3$s.  You can contact your host and ask them to update your PHP version to at least PHP 5.6.  Please do not update to the new version of Event Espresso 4 until the PHP update is completed. Read about why keeping your server on the latest version of PHP is a good idea %4$shere%5$s',
188
-                             'event_espresso'
189
-                         ),
190
-                         '<strong>',
191
-                         '</strong>',
192
-                         PHP_VERSION,
193
-                         '<a href="https://wordpress.org/support/upgrade-php/">',
194
-                         '</a>'
195
-                     )
196
-                     . '</p></div>';
197
-            });
198
-        }
199
-    }
131
+	}
132
+
133
+
134
+	/**
135
+	 *    _display_minimum_recommended_php_version_notice
136
+	 *
137
+	 * @access private
138
+	 * @return void
139
+	 * @throws InvalidDataTypeException
140
+	 */
141
+	private function displayMinimumRecommendedPhpVersionNotice()
142
+	{
143
+		if ($this->request->isAdmin()) {
144
+			new PersistentAdminNotice(
145
+				'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
146
+				sprintf(
147
+					esc_html__(
148
+						'Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
149
+						'event_espresso'
150
+					),
151
+					EE_MIN_PHP_VER_RECOMMENDED,
152
+					PHP_VERSION,
153
+					'<br/>',
154
+					'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
155
+				)
156
+			);
157
+		}
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns whether the provided php version number is less than the current version of php installed on the server.
163
+	 *
164
+	 * @param string $version_required
165
+	 * @return bool
166
+	 */
167
+	private function upcomingRequiredPhpVersion($version_required = '5.5')
168
+	{
169
+		return true;
170
+		// return $this->checkPhpVersion($version_required);
171
+	}
172
+
173
+
174
+	/**
175
+	 *  Sets a notice for an upcoming required version of PHP in the next update of EE core.
176
+	 */
177
+	private function displayUpcomingRequiredVersion()
178
+	{
179
+		if ($this->request->isAdmin()
180
+			&& apply_filters('FHEE__EE_Recommended_Versions__displayUpcomingRequiredVersion', true, $this->request)
181
+			&& current_user_can('update_plugins')
182
+		) {
183
+			add_action('admin_notices', function () {
184
+				echo '<div class="notice event-espresso-admin-notice notice-warning"><p>'
185
+					 . sprintf(
186
+						 esc_html__(
187
+							 'Please note: The next update of Event Espresso 4 will %1$srequire%2$s PHP 5.4.45 or greater.  Your web server\'s PHP version is %3$s.  You can contact your host and ask them to update your PHP version to at least PHP 5.6.  Please do not update to the new version of Event Espresso 4 until the PHP update is completed. Read about why keeping your server on the latest version of PHP is a good idea %4$shere%5$s',
188
+							 'event_espresso'
189
+						 ),
190
+						 '<strong>',
191
+						 '</strong>',
192
+						 PHP_VERSION,
193
+						 '<a href="https://wordpress.org/support/upgrade-php/">',
194
+						 '</a>'
195
+					 )
196
+					 . '</p></div>';
197
+			});
198
+		}
199
+	}
200 200
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -32,18 +32,18 @@  discard block
 block discarded – undo
32 32
         $this->request = $request;
33 33
         $this->response = $response;
34 34
         // check required WP version
35
-        if (! $this->minimumWordPressVersionRequired()) {
35
+        if ( ! $this->minimumWordPressVersionRequired()) {
36 36
             $this->request->unSetRequestParam('activate', true);
37 37
             add_action('admin_notices', array($this, 'minimumWpVersionError'), 1);
38 38
             $this->response->terminateRequest();
39 39
             $this->response->deactivatePlugin();
40 40
         }
41 41
         // check recommended PHP version
42
-        if (! $this->minimumPhpVersionRecommended()) {
42
+        if ( ! $this->minimumPhpVersionRecommended()) {
43 43
             $this->displayMinimumRecommendedPhpVersionNotice();
44 44
         }
45 45
         // upcoming required version
46
-        if (! $this->upcomingRequiredPhpVersion()) {
46
+        if ( ! $this->upcomingRequiredPhpVersion()) {
47 47
             $this->displayUpcomingRequiredVersion();
48 48
         }
49 49
         $this->response = $this->processRequestStack($this->request, $this->response);
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
     {
143 143
         if ($this->request->isAdmin()) {
144 144
             new PersistentAdminNotice(
145
-                'php_version_' . str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED) . '_recommended',
145
+                'php_version_'.str_replace('.', '-', EE_MIN_PHP_VER_RECOMMENDED).'_recommended',
146 146
                 sprintf(
147 147
                     esc_html__(
148 148
                         'Event Espresso recommends PHP version %1$s or greater for optimal performance. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
             && apply_filters('FHEE__EE_Recommended_Versions__displayUpcomingRequiredVersion', true, $this->request)
181 181
             && current_user_can('update_plugins')
182 182
         ) {
183
-            add_action('admin_notices', function () {
183
+            add_action('admin_notices', function() {
184 184
                 echo '<div class="notice event-espresso-admin-notice notice-warning"><p>'
185 185
                      . sprintf(
186 186
                          esc_html__(
Please login to merge, or discard this patch.
core/services/assets/AssetCollection.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
             /** @var Asset $asset */
76 76
             $asset = $this->current();
77 77
             if ($asset->type() === $type) {
78
-                $files[ $asset->handle() ] = $asset;
78
+                $files[$asset->handle()] = $asset;
79 79
             }
80 80
             $this->next();
81 81
         }
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
             /** @var JavascriptAsset $asset */
97 97
             $asset = $this->current();
98 98
             if ($asset->type() === Asset::TYPE_JS && $asset->hasInlineData()) {
99
-                $files[ $asset->handle() ] = $asset;
99
+                $files[$asset->handle()] = $asset;
100 100
             }
101 101
             $this->next();
102 102
         }
Please login to merge, or discard this patch.
Indentation   +197 added lines, -197 removed lines patch added patch discarded remove patch
@@ -21,201 +21,201 @@
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * AssetCollection constructor
26
-     *
27
-     * @throws InvalidInterfaceException
28
-     */
29
-    public function __construct()
30
-    {
31
-        parent::__construct('EventEspresso\core\domain\values\assets\Asset');
32
-    }
33
-
34
-
35
-    /**
36
-     * @return StylesheetAsset[]
37
-     * @since 4.9.62.p
38
-     */
39
-    public function getStylesheetAssets()
40
-    {
41
-        return $this->getAssetsOfType(Asset::TYPE_CSS);
42
-    }
43
-
44
-
45
-    /**
46
-     * @return JavascriptAsset[]
47
-     * @since 4.9.62.p
48
-     */
49
-    public function getJavascriptAssets()
50
-    {
51
-        return $this->getAssetsOfType(Asset::TYPE_JS);
52
-    }
53
-
54
-
55
-    /**
56
-     * @return ManifestFile[]
57
-     * @since 4.9.62.p
58
-     */
59
-    public function getManifestFiles()
60
-    {
61
-        return $this->getAssetsOfType(Asset::TYPE_MANIFEST);
62
-    }
63
-
64
-
65
-    /**
66
-     * @param $type
67
-     * @return JavascriptAsset[]|StylesheetAsset[]|ManifestFile[]
68
-     * @since 4.9.62.p
69
-     */
70
-    protected function getAssetsOfType($type)
71
-    {
72
-        $files = array();
73
-        $this->rewind();
74
-        while ($this->valid()) {
75
-            /** @var Asset $asset */
76
-            $asset = $this->current();
77
-            if ($asset->type() === $type) {
78
-                $files[ $asset->handle() ] = $asset;
79
-            }
80
-            $this->next();
81
-        }
82
-        $this->rewind();
83
-        return $files;
84
-    }
85
-
86
-
87
-    /**
88
-     * @return JavascriptAsset[]
89
-     * @since 4.9.62.p
90
-     */
91
-    public function getJavascriptAssetsWithData()
92
-    {
93
-        $files = array();
94
-        $this->rewind();
95
-        while ($this->valid()) {
96
-            /** @var JavascriptAsset $asset */
97
-            $asset = $this->current();
98
-            if ($asset->type() === Asset::TYPE_JS && $asset->hasInlineData()) {
99
-                $files[ $asset->handle() ] = $asset;
100
-            }
101
-            $this->next();
102
-        }
103
-        $this->rewind();
104
-        return $files;
105
-    }
106
-
107
-
108
-    /**
109
-     * has
110
-     * returns TRUE or FALSE
111
-     * depending on whether the object is within the Collection
112
-     * based on the supplied $identifier and type
113
-     *
114
-     * @param  mixed $identifier
115
-     * @param string $type
116
-     * @return bool
117
-     * @since $VID:$
118
-     */
119
-    public function hasAssetOfType($identifier, $type = Asset::TYPE_JS)
120
-    {
121
-        $this->rewind();
122
-        while ($this->valid()) {
123
-            if ($this->getInfo() === $identifier && $this->current()->type() === $type) {
124
-                $this->rewind();
125
-                return true;
126
-            }
127
-            $this->next();
128
-        }
129
-        return false;
130
-    }
131
-
132
-
133
-    /**
134
-     * has
135
-     * returns TRUE or FALSE
136
-     * depending on whether the Stylesheet Asset is within the Collection
137
-     * based on the supplied $identifier
138
-     *
139
-     * @param  mixed $identifier
140
-     * @return bool
141
-     * @since $VID:$
142
-     */
143
-    public function hasStylesheetAsset($identifier)
144
-    {
145
-        return $this->hasAssetOfType($identifier, Asset::TYPE_CSS);
146
-    }
147
-
148
-
149
-    /**
150
-     * has
151
-     * returns TRUE or FALSE
152
-     * depending on whether the Javascript Asset is within the Collection
153
-     * based on the supplied $identifier
154
-     *
155
-     * @param  mixed $identifier
156
-     * @return bool
157
-     * @since $VID:$
158
-     */
159
-    public function hasJavascriptAsset($identifier)
160
-    {
161
-        return $this->hasAssetOfType($identifier, Asset::TYPE_JS);
162
-    }
163
-
164
-    /**
165
-     * has
166
-     * returns TRUE or FALSE
167
-     * depending on whether the object is within the Collection
168
-     * based on the supplied $identifier and type
169
-     *
170
-     * @param  mixed $identifier
171
-     * @param string $type
172
-     * @return JavascriptAsset|StylesheetAsset
173
-     * @since $VID:$
174
-     */
175
-    public function getAssetOfType($identifier, $type = Asset::TYPE_JS)
176
-    {
177
-        $this->rewind();
178
-        while ($this->valid()) {
179
-            if ($this->getInfo() === $identifier && $this->current()->type() === $type) {
180
-                /** @var JavascriptAsset|StylesheetAsset $object */
181
-                $object = $this->current();
182
-                $this->rewind();
183
-                return $object;
184
-            }
185
-            $this->next();
186
-        }
187
-        return null;
188
-    }
189
-
190
-
191
-    /**
192
-     * has
193
-     * returns TRUE or FALSE
194
-     * depending on whether the Stylesheet Asset is within the Collection
195
-     * based on the supplied $identifier
196
-     *
197
-     * @param  mixed $identifier
198
-     * @return StylesheetAsset
199
-     * @since $VID:$
200
-     */
201
-    public function getStylesheetAsset($identifier)
202
-    {
203
-        return $this->getAssetOfType($identifier, Asset::TYPE_CSS);
204
-    }
205
-
206
-
207
-    /**
208
-     * has
209
-     * returns TRUE or FALSE
210
-     * depending on whether the Javascript Asset is within the Collection
211
-     * based on the supplied $identifier
212
-     *
213
-     * @param  mixed $identifier
214
-     * @return JavascriptAsset
215
-     * @since $VID:$
216
-     */
217
-    public function getJavascriptAsset($identifier)
218
-    {
219
-        return $this->getAssetOfType($identifier, Asset::TYPE_JS);
220
-    }
24
+	/**
25
+	 * AssetCollection constructor
26
+	 *
27
+	 * @throws InvalidInterfaceException
28
+	 */
29
+	public function __construct()
30
+	{
31
+		parent::__construct('EventEspresso\core\domain\values\assets\Asset');
32
+	}
33
+
34
+
35
+	/**
36
+	 * @return StylesheetAsset[]
37
+	 * @since 4.9.62.p
38
+	 */
39
+	public function getStylesheetAssets()
40
+	{
41
+		return $this->getAssetsOfType(Asset::TYPE_CSS);
42
+	}
43
+
44
+
45
+	/**
46
+	 * @return JavascriptAsset[]
47
+	 * @since 4.9.62.p
48
+	 */
49
+	public function getJavascriptAssets()
50
+	{
51
+		return $this->getAssetsOfType(Asset::TYPE_JS);
52
+	}
53
+
54
+
55
+	/**
56
+	 * @return ManifestFile[]
57
+	 * @since 4.9.62.p
58
+	 */
59
+	public function getManifestFiles()
60
+	{
61
+		return $this->getAssetsOfType(Asset::TYPE_MANIFEST);
62
+	}
63
+
64
+
65
+	/**
66
+	 * @param $type
67
+	 * @return JavascriptAsset[]|StylesheetAsset[]|ManifestFile[]
68
+	 * @since 4.9.62.p
69
+	 */
70
+	protected function getAssetsOfType($type)
71
+	{
72
+		$files = array();
73
+		$this->rewind();
74
+		while ($this->valid()) {
75
+			/** @var Asset $asset */
76
+			$asset = $this->current();
77
+			if ($asset->type() === $type) {
78
+				$files[ $asset->handle() ] = $asset;
79
+			}
80
+			$this->next();
81
+		}
82
+		$this->rewind();
83
+		return $files;
84
+	}
85
+
86
+
87
+	/**
88
+	 * @return JavascriptAsset[]
89
+	 * @since 4.9.62.p
90
+	 */
91
+	public function getJavascriptAssetsWithData()
92
+	{
93
+		$files = array();
94
+		$this->rewind();
95
+		while ($this->valid()) {
96
+			/** @var JavascriptAsset $asset */
97
+			$asset = $this->current();
98
+			if ($asset->type() === Asset::TYPE_JS && $asset->hasInlineData()) {
99
+				$files[ $asset->handle() ] = $asset;
100
+			}
101
+			$this->next();
102
+		}
103
+		$this->rewind();
104
+		return $files;
105
+	}
106
+
107
+
108
+	/**
109
+	 * has
110
+	 * returns TRUE or FALSE
111
+	 * depending on whether the object is within the Collection
112
+	 * based on the supplied $identifier and type
113
+	 *
114
+	 * @param  mixed $identifier
115
+	 * @param string $type
116
+	 * @return bool
117
+	 * @since $VID:$
118
+	 */
119
+	public function hasAssetOfType($identifier, $type = Asset::TYPE_JS)
120
+	{
121
+		$this->rewind();
122
+		while ($this->valid()) {
123
+			if ($this->getInfo() === $identifier && $this->current()->type() === $type) {
124
+				$this->rewind();
125
+				return true;
126
+			}
127
+			$this->next();
128
+		}
129
+		return false;
130
+	}
131
+
132
+
133
+	/**
134
+	 * has
135
+	 * returns TRUE or FALSE
136
+	 * depending on whether the Stylesheet Asset is within the Collection
137
+	 * based on the supplied $identifier
138
+	 *
139
+	 * @param  mixed $identifier
140
+	 * @return bool
141
+	 * @since $VID:$
142
+	 */
143
+	public function hasStylesheetAsset($identifier)
144
+	{
145
+		return $this->hasAssetOfType($identifier, Asset::TYPE_CSS);
146
+	}
147
+
148
+
149
+	/**
150
+	 * has
151
+	 * returns TRUE or FALSE
152
+	 * depending on whether the Javascript Asset is within the Collection
153
+	 * based on the supplied $identifier
154
+	 *
155
+	 * @param  mixed $identifier
156
+	 * @return bool
157
+	 * @since $VID:$
158
+	 */
159
+	public function hasJavascriptAsset($identifier)
160
+	{
161
+		return $this->hasAssetOfType($identifier, Asset::TYPE_JS);
162
+	}
163
+
164
+	/**
165
+	 * has
166
+	 * returns TRUE or FALSE
167
+	 * depending on whether the object is within the Collection
168
+	 * based on the supplied $identifier and type
169
+	 *
170
+	 * @param  mixed $identifier
171
+	 * @param string $type
172
+	 * @return JavascriptAsset|StylesheetAsset
173
+	 * @since $VID:$
174
+	 */
175
+	public function getAssetOfType($identifier, $type = Asset::TYPE_JS)
176
+	{
177
+		$this->rewind();
178
+		while ($this->valid()) {
179
+			if ($this->getInfo() === $identifier && $this->current()->type() === $type) {
180
+				/** @var JavascriptAsset|StylesheetAsset $object */
181
+				$object = $this->current();
182
+				$this->rewind();
183
+				return $object;
184
+			}
185
+			$this->next();
186
+		}
187
+		return null;
188
+	}
189
+
190
+
191
+	/**
192
+	 * has
193
+	 * returns TRUE or FALSE
194
+	 * depending on whether the Stylesheet Asset is within the Collection
195
+	 * based on the supplied $identifier
196
+	 *
197
+	 * @param  mixed $identifier
198
+	 * @return StylesheetAsset
199
+	 * @since $VID:$
200
+	 */
201
+	public function getStylesheetAsset($identifier)
202
+	{
203
+		return $this->getAssetOfType($identifier, Asset::TYPE_CSS);
204
+	}
205
+
206
+
207
+	/**
208
+	 * has
209
+	 * returns TRUE or FALSE
210
+	 * depending on whether the Javascript Asset is within the Collection
211
+	 * based on the supplied $identifier
212
+	 *
213
+	 * @param  mixed $identifier
214
+	 * @return JavascriptAsset
215
+	 * @since $VID:$
216
+	 */
217
+	public function getJavascriptAsset($identifier)
218
+	{
219
+		return $this->getAssetOfType($identifier, Asset::TYPE_JS);
220
+	}
221 221
 }
Please login to merge, or discard this patch.
core/services/assets/Registry.php 1 patch
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -23,561 +23,561 @@
 block discarded – undo
23 23
 class Registry
24 24
 {
25 25
 
26
-    const FILE_NAME_BUILD_MANIFEST = 'build-manifest.json';
27
-
28
-    /**
29
-     * @var AssetCollection $assets
30
-     */
31
-    protected $assets;
32
-
33
-    /**
34
-     * @var I18nRegistry
35
-     */
36
-    private $i18n_registry;
37
-
38
-    /**
39
-     * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
40
-     *
41
-     * @var array
42
-     */
43
-    protected $jsdata = array();
44
-
45
-    /**
46
-     * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
47
-     * page source.
48
-     *
49
-     * @var array
50
-     */
51
-    private $script_handles_with_data = array();
52
-
53
-
54
-    /**
55
-     * Holds the manifest data obtained from registered manifest files.
56
-     * Manifests are maps of asset chunk name to actual built asset file names.
57
-     * Shape of this array is:
58
-     * array(
59
-     *  'some_namespace_slug' => array(
60
-     *      'some_chunk_name' => array(
61
-     *          'js' => 'filename.js'
62
-     *          'css' => 'filename.js'
63
-     *      ),
64
-     *      'url_base' => 'https://baseurl.com/to/assets
65
-     *  )
66
-     * )
67
-     *
68
-     * @var array
69
-     */
70
-    private $manifest_data = array();
71
-
72
-
73
-    /**
74
-     * Registry constructor.
75
-     * Hooking into WP actions for script registry.
76
-     *
77
-     * @param AssetCollection $assets
78
-     * @param I18nRegistry    $i18n_registry
79
-     */
80
-    public function __construct(AssetCollection $assets, I18nRegistry $i18n_registry)
81
-    {
82
-        $this->assets = $assets;
83
-        $this->i18n_registry = $i18n_registry;
84
-        add_action('wp_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
85
-        add_action('admin_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
86
-        add_action('wp_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
87
-        add_action('admin_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
88
-        add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 4);
89
-        add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 4);
90
-        add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
91
-        add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
92
-    }
93
-
94
-
95
-    /**
96
-     * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
97
-     * translation handling.
98
-     *
99
-     * @return I18nRegistry
100
-     */
101
-    public function getI18nRegistry()
102
-    {
103
-        return $this->i18n_registry;
104
-    }
105
-
106
-
107
-    /**
108
-     * Callback for the wp_enqueue_scripts actions used to register assets.
109
-     *
110
-     * @since 4.9.62.p
111
-     * @throws Exception
112
-     */
113
-    public function registerScriptsAndStyles()
114
-    {
115
-        try {
116
-            $this->registerScripts($this->assets->getJavascriptAssets());
117
-            $this->registerStyles($this->assets->getStylesheetAssets());
118
-        } catch (Exception $exception) {
119
-            new ExceptionStackTraceDisplay($exception);
120
-        }
121
-    }
122
-
123
-
124
-    /**
125
-     * Registers JS assets with WP core
126
-     *
127
-     * @since 4.9.62.p
128
-     * @param JavascriptAsset[] $scripts
129
-     * @throws AssetRegistrationException
130
-     * @throws InvalidDataTypeException
131
-     */
132
-    public function registerScripts(array $scripts)
133
-    {
134
-        foreach ($scripts as $script) {
135
-            // skip to next script if this has already been done
136
-            if ($script->isRegistered()) {
137
-                continue;
138
-            }
139
-            do_action(
140
-                'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
141
-                $script
142
-            );
143
-            $registered = wp_register_script(
144
-                $script->handle(),
145
-                $script->source(),
146
-                $script->dependencies(),
147
-                $script->version(),
148
-                $script->loadInFooter()
149
-            );
150
-            if (! $registered && defined('EE_DEBUG') && EE_DEBUG) {
151
-                throw new AssetRegistrationException($script->handle());
152
-            }
153
-            $script->setRegistered($registered);
154
-            if ($script->requiresTranslation()) {
155
-                $this->registerTranslation($script->handle());
156
-            }
157
-            do_action(
158
-                'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__after_script',
159
-                $script
160
-            );
161
-        }
162
-    }
163
-
164
-
165
-    /**
166
-     * Registers CSS assets with WP core
167
-     *
168
-     * @since 4.9.62.p
169
-     * @param StylesheetAsset[] $styles
170
-     * @throws InvalidDataTypeException
171
-     */
172
-    public function registerStyles(array $styles)
173
-    {
174
-        foreach ($styles as $style) {
175
-            // skip to next style if this has already been done
176
-            if ($style->isRegistered()) {
177
-                continue;
178
-            }
179
-            do_action(
180
-                'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__before_style',
181
-                $style
182
-            );
183
-            wp_register_style(
184
-                $style->handle(),
185
-                $style->source(),
186
-                $style->dependencies(),
187
-                $style->version(),
188
-                $style->media()
189
-            );
190
-            $style->setRegistered();
191
-            do_action(
192
-                'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__after_style',
193
-                $style
194
-            );
195
-        }
196
-    }
197
-
198
-
199
-    /**
200
-     * Call back for the script print in frontend and backend.
201
-     * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
202
-     *
203
-     * @since 4.9.31.rc.015
204
-     */
205
-    public function enqueueData()
206
-    {
207
-        $this->removeAlreadyRegisteredDataForScriptHandles();
208
-        wp_add_inline_script(
209
-            'eejs-core',
210
-            'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
211
-            'before'
212
-        );
213
-        $scripts = $this->assets->getJavascriptAssetsWithData();
214
-        foreach ($scripts as $script) {
215
-            $this->addRegisteredScriptHandlesWithData($script->handle());
216
-            if ($script->hasInlineDataCallback()) {
217
-                $localize = $script->inlineDataCallback();
218
-                $localize();
219
-            }
220
-        }
221
-    }
222
-
223
-
224
-    /**
225
-     * Used to add data to eejs.data object.
226
-     * Note:  Overriding existing data is not allowed.
227
-     * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
228
-     * If the data you add is something like this:
229
-     *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
230
-     * It will be exposed in the page source as:
231
-     *  eejs.data.my_plugin_data.foo == gar
232
-     *
233
-     * @param string       $key   Key used to access your data
234
-     * @param string|array $value Value to attach to key
235
-     * @throws InvalidArgumentException
236
-     */
237
-    public function addData($key, $value)
238
-    {
239
-        if ($this->verifyDataNotExisting($key)) {
240
-            $this->jsdata[ $key ] = $value;
241
-        }
242
-    }
243
-
244
-
245
-    /**
246
-     * Similar to addData except this allows for users to push values to an existing key where the values on key are
247
-     * elements in an array.
248
-     * When you use this method, the value you include will be appended to the end of an array on $key.
249
-     * So if the $key was 'test' and you added a value of 'my_data' then it would be represented in the javascript
250
-     * object like this, eejs.data.test = [ my_data,
251
-     * ]
252
-     * If there has already been a scalar value attached to the data object given key, then
253
-     * this will throw an exception.
254
-     *
255
-     * @param string       $key   Key to attach data to.
256
-     * @param string|array $value Value being registered.
257
-     * @throws InvalidArgumentException
258
-     */
259
-    public function pushData($key, $value)
260
-    {
261
-        if (isset($this->jsdata[ $key ])
262
-            && ! is_array($this->jsdata[ $key ])
263
-        ) {
264
-            throw new InvalidArgumentException(
265
-                sprintf(
266
-                    __(
267
-                        'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
26
+	const FILE_NAME_BUILD_MANIFEST = 'build-manifest.json';
27
+
28
+	/**
29
+	 * @var AssetCollection $assets
30
+	 */
31
+	protected $assets;
32
+
33
+	/**
34
+	 * @var I18nRegistry
35
+	 */
36
+	private $i18n_registry;
37
+
38
+	/**
39
+	 * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
40
+	 *
41
+	 * @var array
42
+	 */
43
+	protected $jsdata = array();
44
+
45
+	/**
46
+	 * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
47
+	 * page source.
48
+	 *
49
+	 * @var array
50
+	 */
51
+	private $script_handles_with_data = array();
52
+
53
+
54
+	/**
55
+	 * Holds the manifest data obtained from registered manifest files.
56
+	 * Manifests are maps of asset chunk name to actual built asset file names.
57
+	 * Shape of this array is:
58
+	 * array(
59
+	 *  'some_namespace_slug' => array(
60
+	 *      'some_chunk_name' => array(
61
+	 *          'js' => 'filename.js'
62
+	 *          'css' => 'filename.js'
63
+	 *      ),
64
+	 *      'url_base' => 'https://baseurl.com/to/assets
65
+	 *  )
66
+	 * )
67
+	 *
68
+	 * @var array
69
+	 */
70
+	private $manifest_data = array();
71
+
72
+
73
+	/**
74
+	 * Registry constructor.
75
+	 * Hooking into WP actions for script registry.
76
+	 *
77
+	 * @param AssetCollection $assets
78
+	 * @param I18nRegistry    $i18n_registry
79
+	 */
80
+	public function __construct(AssetCollection $assets, I18nRegistry $i18n_registry)
81
+	{
82
+		$this->assets = $assets;
83
+		$this->i18n_registry = $i18n_registry;
84
+		add_action('wp_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
85
+		add_action('admin_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
86
+		add_action('wp_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
87
+		add_action('admin_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
88
+		add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 4);
89
+		add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 4);
90
+		add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
91
+		add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
92
+	}
93
+
94
+
95
+	/**
96
+	 * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
97
+	 * translation handling.
98
+	 *
99
+	 * @return I18nRegistry
100
+	 */
101
+	public function getI18nRegistry()
102
+	{
103
+		return $this->i18n_registry;
104
+	}
105
+
106
+
107
+	/**
108
+	 * Callback for the wp_enqueue_scripts actions used to register assets.
109
+	 *
110
+	 * @since 4.9.62.p
111
+	 * @throws Exception
112
+	 */
113
+	public function registerScriptsAndStyles()
114
+	{
115
+		try {
116
+			$this->registerScripts($this->assets->getJavascriptAssets());
117
+			$this->registerStyles($this->assets->getStylesheetAssets());
118
+		} catch (Exception $exception) {
119
+			new ExceptionStackTraceDisplay($exception);
120
+		}
121
+	}
122
+
123
+
124
+	/**
125
+	 * Registers JS assets with WP core
126
+	 *
127
+	 * @since 4.9.62.p
128
+	 * @param JavascriptAsset[] $scripts
129
+	 * @throws AssetRegistrationException
130
+	 * @throws InvalidDataTypeException
131
+	 */
132
+	public function registerScripts(array $scripts)
133
+	{
134
+		foreach ($scripts as $script) {
135
+			// skip to next script if this has already been done
136
+			if ($script->isRegistered()) {
137
+				continue;
138
+			}
139
+			do_action(
140
+				'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
141
+				$script
142
+			);
143
+			$registered = wp_register_script(
144
+				$script->handle(),
145
+				$script->source(),
146
+				$script->dependencies(),
147
+				$script->version(),
148
+				$script->loadInFooter()
149
+			);
150
+			if (! $registered && defined('EE_DEBUG') && EE_DEBUG) {
151
+				throw new AssetRegistrationException($script->handle());
152
+			}
153
+			$script->setRegistered($registered);
154
+			if ($script->requiresTranslation()) {
155
+				$this->registerTranslation($script->handle());
156
+			}
157
+			do_action(
158
+				'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__after_script',
159
+				$script
160
+			);
161
+		}
162
+	}
163
+
164
+
165
+	/**
166
+	 * Registers CSS assets with WP core
167
+	 *
168
+	 * @since 4.9.62.p
169
+	 * @param StylesheetAsset[] $styles
170
+	 * @throws InvalidDataTypeException
171
+	 */
172
+	public function registerStyles(array $styles)
173
+	{
174
+		foreach ($styles as $style) {
175
+			// skip to next style if this has already been done
176
+			if ($style->isRegistered()) {
177
+				continue;
178
+			}
179
+			do_action(
180
+				'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__before_style',
181
+				$style
182
+			);
183
+			wp_register_style(
184
+				$style->handle(),
185
+				$style->source(),
186
+				$style->dependencies(),
187
+				$style->version(),
188
+				$style->media()
189
+			);
190
+			$style->setRegistered();
191
+			do_action(
192
+				'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__after_style',
193
+				$style
194
+			);
195
+		}
196
+	}
197
+
198
+
199
+	/**
200
+	 * Call back for the script print in frontend and backend.
201
+	 * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
202
+	 *
203
+	 * @since 4.9.31.rc.015
204
+	 */
205
+	public function enqueueData()
206
+	{
207
+		$this->removeAlreadyRegisteredDataForScriptHandles();
208
+		wp_add_inline_script(
209
+			'eejs-core',
210
+			'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
211
+			'before'
212
+		);
213
+		$scripts = $this->assets->getJavascriptAssetsWithData();
214
+		foreach ($scripts as $script) {
215
+			$this->addRegisteredScriptHandlesWithData($script->handle());
216
+			if ($script->hasInlineDataCallback()) {
217
+				$localize = $script->inlineDataCallback();
218
+				$localize();
219
+			}
220
+		}
221
+	}
222
+
223
+
224
+	/**
225
+	 * Used to add data to eejs.data object.
226
+	 * Note:  Overriding existing data is not allowed.
227
+	 * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
228
+	 * If the data you add is something like this:
229
+	 *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
230
+	 * It will be exposed in the page source as:
231
+	 *  eejs.data.my_plugin_data.foo == gar
232
+	 *
233
+	 * @param string       $key   Key used to access your data
234
+	 * @param string|array $value Value to attach to key
235
+	 * @throws InvalidArgumentException
236
+	 */
237
+	public function addData($key, $value)
238
+	{
239
+		if ($this->verifyDataNotExisting($key)) {
240
+			$this->jsdata[ $key ] = $value;
241
+		}
242
+	}
243
+
244
+
245
+	/**
246
+	 * Similar to addData except this allows for users to push values to an existing key where the values on key are
247
+	 * elements in an array.
248
+	 * When you use this method, the value you include will be appended to the end of an array on $key.
249
+	 * So if the $key was 'test' and you added a value of 'my_data' then it would be represented in the javascript
250
+	 * object like this, eejs.data.test = [ my_data,
251
+	 * ]
252
+	 * If there has already been a scalar value attached to the data object given key, then
253
+	 * this will throw an exception.
254
+	 *
255
+	 * @param string       $key   Key to attach data to.
256
+	 * @param string|array $value Value being registered.
257
+	 * @throws InvalidArgumentException
258
+	 */
259
+	public function pushData($key, $value)
260
+	{
261
+		if (isset($this->jsdata[ $key ])
262
+			&& ! is_array($this->jsdata[ $key ])
263
+		) {
264
+			throw new InvalidArgumentException(
265
+				sprintf(
266
+					__(
267
+						'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
268 268
                          push values to this data element when it is an array.',
269
-                        'event_espresso'
270
-                    ),
271
-                    $key,
272
-                    __METHOD__
273
-                )
274
-            );
275
-        }
276
-        $this->jsdata[ $key ][] = $value;
277
-    }
278
-
279
-
280
-    /**
281
-     * Used to set content used by javascript for a template.
282
-     * Note: Overrides of existing registered templates are not allowed.
283
-     *
284
-     * @param string $template_reference
285
-     * @param string $template_content
286
-     * @throws InvalidArgumentException
287
-     */
288
-    public function addTemplate($template_reference, $template_content)
289
-    {
290
-        if (! isset($this->jsdata['templates'])) {
291
-            $this->jsdata['templates'] = array();
292
-        }
293
-        //no overrides allowed.
294
-        if (isset($this->jsdata['templates'][ $template_reference ])) {
295
-            throw new InvalidArgumentException(
296
-                sprintf(
297
-                    __(
298
-                        'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
299
-                        'event_espresso'
300
-                    ),
301
-                    $template_reference
302
-                )
303
-            );
304
-        }
305
-        $this->jsdata['templates'][ $template_reference ] = $template_content;
306
-    }
307
-
308
-
309
-    /**
310
-     * Retrieve the template content already registered for the given reference.
311
-     *
312
-     * @param string $template_reference
313
-     * @return string
314
-     */
315
-    public function getTemplate($template_reference)
316
-    {
317
-        return isset($this->jsdata['templates'][ $template_reference ])
318
-            ? $this->jsdata['templates'][ $template_reference ]
319
-            : '';
320
-    }
321
-
322
-
323
-    /**
324
-     * Retrieve registered data.
325
-     *
326
-     * @param string $key Name of key to attach data to.
327
-     * @return mixed                If there is no for the given key, then false is returned.
328
-     */
329
-    public function getData($key)
330
-    {
331
-        return isset($this->jsdata[ $key ])
332
-            ? $this->jsdata[ $key ]
333
-            : false;
334
-    }
335
-
336
-
337
-    /**
338
-     * Verifies whether the given data exists already on the jsdata array.
339
-     * Overriding data is not allowed.
340
-     *
341
-     * @param string $key Index for data.
342
-     * @return bool        If valid then return true.
343
-     * @throws InvalidArgumentException if data already exists.
344
-     */
345
-    protected function verifyDataNotExisting($key)
346
-    {
347
-        if (isset($this->jsdata[ $key ])) {
348
-            if (is_array($this->jsdata[ $key ])) {
349
-                throw new InvalidArgumentException(
350
-                    sprintf(
351
-                        __(
352
-                            'The value for %1$s already exists in the Registry::eejs object.
269
+						'event_espresso'
270
+					),
271
+					$key,
272
+					__METHOD__
273
+				)
274
+			);
275
+		}
276
+		$this->jsdata[ $key ][] = $value;
277
+	}
278
+
279
+
280
+	/**
281
+	 * Used to set content used by javascript for a template.
282
+	 * Note: Overrides of existing registered templates are not allowed.
283
+	 *
284
+	 * @param string $template_reference
285
+	 * @param string $template_content
286
+	 * @throws InvalidArgumentException
287
+	 */
288
+	public function addTemplate($template_reference, $template_content)
289
+	{
290
+		if (! isset($this->jsdata['templates'])) {
291
+			$this->jsdata['templates'] = array();
292
+		}
293
+		//no overrides allowed.
294
+		if (isset($this->jsdata['templates'][ $template_reference ])) {
295
+			throw new InvalidArgumentException(
296
+				sprintf(
297
+					__(
298
+						'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
299
+						'event_espresso'
300
+					),
301
+					$template_reference
302
+				)
303
+			);
304
+		}
305
+		$this->jsdata['templates'][ $template_reference ] = $template_content;
306
+	}
307
+
308
+
309
+	/**
310
+	 * Retrieve the template content already registered for the given reference.
311
+	 *
312
+	 * @param string $template_reference
313
+	 * @return string
314
+	 */
315
+	public function getTemplate($template_reference)
316
+	{
317
+		return isset($this->jsdata['templates'][ $template_reference ])
318
+			? $this->jsdata['templates'][ $template_reference ]
319
+			: '';
320
+	}
321
+
322
+
323
+	/**
324
+	 * Retrieve registered data.
325
+	 *
326
+	 * @param string $key Name of key to attach data to.
327
+	 * @return mixed                If there is no for the given key, then false is returned.
328
+	 */
329
+	public function getData($key)
330
+	{
331
+		return isset($this->jsdata[ $key ])
332
+			? $this->jsdata[ $key ]
333
+			: false;
334
+	}
335
+
336
+
337
+	/**
338
+	 * Verifies whether the given data exists already on the jsdata array.
339
+	 * Overriding data is not allowed.
340
+	 *
341
+	 * @param string $key Index for data.
342
+	 * @return bool        If valid then return true.
343
+	 * @throws InvalidArgumentException if data already exists.
344
+	 */
345
+	protected function verifyDataNotExisting($key)
346
+	{
347
+		if (isset($this->jsdata[ $key ])) {
348
+			if (is_array($this->jsdata[ $key ])) {
349
+				throw new InvalidArgumentException(
350
+					sprintf(
351
+						__(
352
+							'The value for %1$s already exists in the Registry::eejs object.
353 353
                             Overrides are not allowed. Since the value of this data is an array, you may want to use the
354 354
                             %2$s method to push your value to the array.',
355
-                            'event_espresso'
356
-                        ),
357
-                        $key,
358
-                        'pushData()'
359
-                    )
360
-                );
361
-            }
362
-            throw new InvalidArgumentException(
363
-                sprintf(
364
-                    __(
365
-                        'The value for %1$s already exists in the Registry::eejs object. Overrides are not
355
+							'event_espresso'
356
+						),
357
+						$key,
358
+						'pushData()'
359
+					)
360
+				);
361
+			}
362
+			throw new InvalidArgumentException(
363
+				sprintf(
364
+					__(
365
+						'The value for %1$s already exists in the Registry::eejs object. Overrides are not
366 366
                         allowed.  Consider attaching your value to a different key',
367
-                        'event_espresso'
368
-                    ),
369
-                    $key
370
-                )
371
-            );
372
-        }
373
-        return true;
374
-    }
375
-
376
-
377
-    /**
378
-     * Get the actual asset path for asset manifests.
379
-     * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
380
-     *
381
-     * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
382
-     *                           asset file location.
383
-     * @param string $chunk_name
384
-     * @param string $asset_type
385
-     * @return string
386
-     * @since 4.9.59.p
387
-     */
388
-    public function getAssetUrl($namespace, $chunk_name, $asset_type)
389
-    {
390
-        $url = isset(
391
-            $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ],
392
-            $this->manifest_data[ $namespace ]['url_base']
393
-        )
394
-            ? $this->manifest_data[ $namespace ]['url_base']
395
-              . $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ]
396
-            : $chunk_name;
397
-        return apply_filters(
398
-            'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
399
-            $url,
400
-            $namespace,
401
-            $chunk_name,
402
-            $asset_type
403
-        );
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * Return the url to a js file for the given namespace and chunk name.
410
-     *
411
-     * @param string $namespace
412
-     * @param string $chunk_name
413
-     * @return string
414
-     */
415
-    public function getJsUrl($namespace, $chunk_name)
416
-    {
417
-        return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_JS);
418
-    }
419
-
420
-
421
-    /**
422
-     * Return the url to a css file for the given namespace and chunk name.
423
-     *
424
-     * @param string $namespace
425
-     * @param string $chunk_name
426
-     * @return string
427
-     */
428
-    public function getCssUrl($namespace, $chunk_name)
429
-    {
430
-        return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_CSS);
431
-    }
432
-
433
-
434
-    /**
435
-     * @since 4.9.62.p
436
-     * @throws InvalidArgumentException
437
-     * @throws InvalidFilePathException
438
-     */
439
-    public function registerManifestFiles()
440
-    {
441
-        $manifest_files = $this->assets->getManifestFiles();
442
-        foreach ($manifest_files as $manifest_file) {
443
-            $this->registerManifestFile(
444
-                $manifest_file->assetNamespace(),
445
-                $manifest_file->urlBase(),
446
-                $manifest_file->filepath() . Registry::FILE_NAME_BUILD_MANIFEST
447
-            );
448
-        }
449
-    }
450
-
451
-
452
-    /**
453
-     * Used to register a js/css manifest file with the registered_manifest_files property.
454
-     *
455
-     * @param string $namespace     Provided to associate the manifest file with a specific namespace.
456
-     * @param string $url_base      The url base for the manifest file location.
457
-     * @param string $manifest_file The absolute path to the manifest file.
458
-     * @throws InvalidArgumentException
459
-     * @throws InvalidFilePathException
460
-     * @since 4.9.59.p
461
-     */
462
-    public function registerManifestFile($namespace, $url_base, $manifest_file)
463
-    {
464
-        if (isset($this->manifest_data[ $namespace ])) {
465
-            throw new InvalidArgumentException(
466
-                sprintf(
467
-                    esc_html__(
468
-                        'The namespace for this manifest file has already been registered, choose a namespace other than %s',
469
-                        'event_espresso'
470
-                    ),
471
-                    $namespace
472
-                )
473
-            );
474
-        }
475
-        if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
476
-            if (is_admin()) {
477
-                EE_Error::add_error(
478
-                    sprintf(
479
-                        esc_html__(
480
-                            'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
481
-                            'event_espresso'
482
-                        ),
483
-                        'Event Espresso',
484
-                        $url_base,
485
-                        'plugins_url',
486
-                        'WP_PLUGIN_URL'
487
-                    ),
488
-                    __FILE__,
489
-                    __FUNCTION__,
490
-                    __LINE__
491
-                );
492
-            }
493
-            return;
494
-        }
495
-        $this->manifest_data[ $namespace ] = $this->decodeManifestFile($manifest_file);
496
-        if (! isset($this->manifest_data[ $namespace ]['url_base'])) {
497
-            $this->manifest_data[ $namespace ]['url_base'] = trailingslashit($url_base);
498
-        }
499
-    }
500
-
501
-
502
-    /**
503
-     * Decodes json from the provided manifest file.
504
-     *
505
-     * @since 4.9.59.p
506
-     * @param string $manifest_file Path to manifest file.
507
-     * @return array
508
-     * @throws InvalidFilePathException
509
-     */
510
-    private function decodeManifestFile($manifest_file)
511
-    {
512
-        if (! file_exists($manifest_file)) {
513
-            throw new InvalidFilePathException($manifest_file);
514
-        }
515
-        return json_decode(file_get_contents($manifest_file), true);
516
-    }
517
-
518
-
519
-    /**
520
-     * This is used to set registered script handles that have data.
521
-     *
522
-     * @param string $script_handle
523
-     */
524
-    private function addRegisteredScriptHandlesWithData($script_handle)
525
-    {
526
-        $this->script_handles_with_data[ $script_handle ] = $script_handle;
527
-    }
528
-
529
-
530
-    /**i
367
+						'event_espresso'
368
+					),
369
+					$key
370
+				)
371
+			);
372
+		}
373
+		return true;
374
+	}
375
+
376
+
377
+	/**
378
+	 * Get the actual asset path for asset manifests.
379
+	 * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
380
+	 *
381
+	 * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
382
+	 *                           asset file location.
383
+	 * @param string $chunk_name
384
+	 * @param string $asset_type
385
+	 * @return string
386
+	 * @since 4.9.59.p
387
+	 */
388
+	public function getAssetUrl($namespace, $chunk_name, $asset_type)
389
+	{
390
+		$url = isset(
391
+			$this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ],
392
+			$this->manifest_data[ $namespace ]['url_base']
393
+		)
394
+			? $this->manifest_data[ $namespace ]['url_base']
395
+			  . $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ]
396
+			: $chunk_name;
397
+		return apply_filters(
398
+			'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
399
+			$url,
400
+			$namespace,
401
+			$chunk_name,
402
+			$asset_type
403
+		);
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * Return the url to a js file for the given namespace and chunk name.
410
+	 *
411
+	 * @param string $namespace
412
+	 * @param string $chunk_name
413
+	 * @return string
414
+	 */
415
+	public function getJsUrl($namespace, $chunk_name)
416
+	{
417
+		return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_JS);
418
+	}
419
+
420
+
421
+	/**
422
+	 * Return the url to a css file for the given namespace and chunk name.
423
+	 *
424
+	 * @param string $namespace
425
+	 * @param string $chunk_name
426
+	 * @return string
427
+	 */
428
+	public function getCssUrl($namespace, $chunk_name)
429
+	{
430
+		return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_CSS);
431
+	}
432
+
433
+
434
+	/**
435
+	 * @since 4.9.62.p
436
+	 * @throws InvalidArgumentException
437
+	 * @throws InvalidFilePathException
438
+	 */
439
+	public function registerManifestFiles()
440
+	{
441
+		$manifest_files = $this->assets->getManifestFiles();
442
+		foreach ($manifest_files as $manifest_file) {
443
+			$this->registerManifestFile(
444
+				$manifest_file->assetNamespace(),
445
+				$manifest_file->urlBase(),
446
+				$manifest_file->filepath() . Registry::FILE_NAME_BUILD_MANIFEST
447
+			);
448
+		}
449
+	}
450
+
451
+
452
+	/**
453
+	 * Used to register a js/css manifest file with the registered_manifest_files property.
454
+	 *
455
+	 * @param string $namespace     Provided to associate the manifest file with a specific namespace.
456
+	 * @param string $url_base      The url base for the manifest file location.
457
+	 * @param string $manifest_file The absolute path to the manifest file.
458
+	 * @throws InvalidArgumentException
459
+	 * @throws InvalidFilePathException
460
+	 * @since 4.9.59.p
461
+	 */
462
+	public function registerManifestFile($namespace, $url_base, $manifest_file)
463
+	{
464
+		if (isset($this->manifest_data[ $namespace ])) {
465
+			throw new InvalidArgumentException(
466
+				sprintf(
467
+					esc_html__(
468
+						'The namespace for this manifest file has already been registered, choose a namespace other than %s',
469
+						'event_espresso'
470
+					),
471
+					$namespace
472
+				)
473
+			);
474
+		}
475
+		if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
476
+			if (is_admin()) {
477
+				EE_Error::add_error(
478
+					sprintf(
479
+						esc_html__(
480
+							'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
481
+							'event_espresso'
482
+						),
483
+						'Event Espresso',
484
+						$url_base,
485
+						'plugins_url',
486
+						'WP_PLUGIN_URL'
487
+					),
488
+					__FILE__,
489
+					__FUNCTION__,
490
+					__LINE__
491
+				);
492
+			}
493
+			return;
494
+		}
495
+		$this->manifest_data[ $namespace ] = $this->decodeManifestFile($manifest_file);
496
+		if (! isset($this->manifest_data[ $namespace ]['url_base'])) {
497
+			$this->manifest_data[ $namespace ]['url_base'] = trailingslashit($url_base);
498
+		}
499
+	}
500
+
501
+
502
+	/**
503
+	 * Decodes json from the provided manifest file.
504
+	 *
505
+	 * @since 4.9.59.p
506
+	 * @param string $manifest_file Path to manifest file.
507
+	 * @return array
508
+	 * @throws InvalidFilePathException
509
+	 */
510
+	private function decodeManifestFile($manifest_file)
511
+	{
512
+		if (! file_exists($manifest_file)) {
513
+			throw new InvalidFilePathException($manifest_file);
514
+		}
515
+		return json_decode(file_get_contents($manifest_file), true);
516
+	}
517
+
518
+
519
+	/**
520
+	 * This is used to set registered script handles that have data.
521
+	 *
522
+	 * @param string $script_handle
523
+	 */
524
+	private function addRegisteredScriptHandlesWithData($script_handle)
525
+	{
526
+		$this->script_handles_with_data[ $script_handle ] = $script_handle;
527
+	}
528
+
529
+
530
+	/**i
531 531
      * Checks WP_Scripts for all of each script handle registered internally as having data and unsets from the
532 532
      * Dependency stored in WP_Scripts if its set.
533 533
      */
534
-    private function removeAlreadyRegisteredDataForScriptHandles()
535
-    {
536
-        if (empty($this->script_handles_with_data)) {
537
-            return;
538
-        }
539
-        foreach ($this->script_handles_with_data as $script_handle) {
540
-            $this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
541
-        }
542
-    }
543
-
544
-
545
-    /**
546
-     * Removes any data dependency registered in WP_Scripts if its set.
547
-     *
548
-     * @param string $script_handle
549
-     */
550
-    private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
551
-    {
552
-        if (isset($this->script_handles_with_data[ $script_handle ])) {
553
-            global $wp_scripts;
554
-            $unset_handle = false;
555
-            if ($wp_scripts->get_data($script_handle, 'data')) {
556
-                unset($wp_scripts->registered[ $script_handle ]->extra['data']);
557
-                $unset_handle = true;
558
-            }
559
-            //deal with inline_scripts
560
-            if ($wp_scripts->get_data($script_handle, 'before')) {
561
-                unset($wp_scripts->registered[ $script_handle ]->extra['before']);
562
-                $unset_handle = true;
563
-            }
564
-            if ($wp_scripts->get_data($script_handle, 'after')) {
565
-                unset($wp_scripts->registered[ $script_handle ]->extra['after']);
566
-            }
567
-            if ($unset_handle) {
568
-                unset($this->script_handles_with_data[ $script_handle ]);
569
-            }
570
-        }
571
-    }
572
-
573
-
574
-    /**
575
-     * register translations for a registered script
576
-     *
577
-     * @param string $handle
578
-     */
579
-    public function registerTranslation($handle)
580
-    {
581
-        $this->i18n_registry->registerScriptI18n($handle);
582
-    }
534
+	private function removeAlreadyRegisteredDataForScriptHandles()
535
+	{
536
+		if (empty($this->script_handles_with_data)) {
537
+			return;
538
+		}
539
+		foreach ($this->script_handles_with_data as $script_handle) {
540
+			$this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
541
+		}
542
+	}
543
+
544
+
545
+	/**
546
+	 * Removes any data dependency registered in WP_Scripts if its set.
547
+	 *
548
+	 * @param string $script_handle
549
+	 */
550
+	private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
551
+	{
552
+		if (isset($this->script_handles_with_data[ $script_handle ])) {
553
+			global $wp_scripts;
554
+			$unset_handle = false;
555
+			if ($wp_scripts->get_data($script_handle, 'data')) {
556
+				unset($wp_scripts->registered[ $script_handle ]->extra['data']);
557
+				$unset_handle = true;
558
+			}
559
+			//deal with inline_scripts
560
+			if ($wp_scripts->get_data($script_handle, 'before')) {
561
+				unset($wp_scripts->registered[ $script_handle ]->extra['before']);
562
+				$unset_handle = true;
563
+			}
564
+			if ($wp_scripts->get_data($script_handle, 'after')) {
565
+				unset($wp_scripts->registered[ $script_handle ]->extra['after']);
566
+			}
567
+			if ($unset_handle) {
568
+				unset($this->script_handles_with_data[ $script_handle ]);
569
+			}
570
+		}
571
+	}
572
+
573
+
574
+	/**
575
+	 * register translations for a registered script
576
+	 *
577
+	 * @param string $handle
578
+	 */
579
+	public function registerTranslation($handle)
580
+	{
581
+		$this->i18n_registry->registerScriptI18n($handle);
582
+	}
583 583
 }
Please login to merge, or discard this patch.
core/services/assets/I18nRegistry.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -14,238 +14,238 @@
 block discarded – undo
14 14
  */
15 15
 class I18nRegistry
16 16
 {
17
-    /**
18
-     * @var DomainInterface
19
-     */
20
-    private $domain;
21
-
22
-    /**
23
-     * Will hold all registered i18n scripts.  Prevents script handles from being registered more than once.
24
-     *
25
-     * @var array
26
-     */
27
-    private $registered_i18n = array();
28
-
29
-
30
-    /**
31
-     * Used to hold queued translations for the chunks loading in a view.
32
-     *
33
-     * @var array
34
-     */
35
-    private $queued_handle_translations = array();
36
-
37
-    /**
38
-     * Used to track script handles queued for adding translation strings as inline data in the dom.
39
-     *
40
-     * @var array
41
-     */
42
-    private $queued_scripts = array();
43
-
44
-
45
-    /**
46
-     * Obtained from the generated json file from the all javascript using wp.i18n with a map of script handle names to
47
-     * translation strings.
48
-     *
49
-     * @var array
50
-     */
51
-    private $i18n_map;
52
-
53
-
54
-    /**
55
-     * I18nRegistry constructor.
56
-     *
57
-     * @param array() $i18n_map  An array of script handle names and the strings translated for those handles.  If not
58
-     *                            provided, the class will look for map in root of plugin with filename of
59
-     *                            'translation-map.json'.
60
-     * @param DomainInterface $domain
61
-     */
62
-    public function __construct(array $i18n_map = array(), DomainInterface $domain)
63
-    {
64
-        $this->domain = $domain;
65
-        $this->setI18nMap($i18n_map);
66
-        add_filter('print_scripts_array', array($this, 'queueI18n'));
67
-    }
68
-
69
-
70
-    /**
71
-     * Used to register a script that has i18n strings for its $handle
72
-     *
73
-     * @param string $handle The script handle reference.
74
-     * @param string $domain The i18n domain for the strings.
75
-     */
76
-    public function registerScriptI18n($handle, $domain = 'event_espresso')
77
-    {
78
-        if(! isset($this->registered_i18n[$handle])) {
79
-            $this->registered_i18n[ $handle ] = 1;
80
-            $this->queued_scripts[ $handle ] = $domain;
81
-        }
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Callback on print_scripts_array to listen for scripts enqueued and handle setting up the localized data.
88
-     *
89
-     * @param array $handles Array of registered script handles.
90
-     * @return array
91
-     */
92
-    public function queueI18n(array $handles)
93
-    {
94
-        if (empty($this->queued_scripts)) {
95
-            return $handles;
96
-        }
97
-        foreach ($handles as $handle) {
98
-            $this->queueI18nTranslationsForHandle($handle);
99
-        }
100
-        if ($this->queued_handle_translations) {
101
-            foreach ($this->queued_handle_translations as $handle => $translations_for_domain) {
102
-                $this->registerInlineScript(
103
-                    $handle,
104
-                    $translations_for_domain['translations'],
105
-                    $translations_for_domain['domain']
106
-                );
107
-            }
108
-        }
109
-        return $handles;
110
-    }
111
-
112
-
113
-    /**
114
-     * Registers inline script with translations for given handle and domain.
115
-     *
116
-     * @param string $handle       Handle used to register javascript file containing translations.
117
-     * @param array  $translations Array of string translations.
118
-     * @param string $domain       Domain for translations.  If left empty then strings are registered with the default
119
-     *                             domain for the javascript.
120
-     */
121
-    protected function registerInlineScript($handle, array $translations, $domain)
122
-    {
123
-        $script = $domain ?
124
-            'eejs.i18n.setLocaleData( ' . wp_json_encode($translations) . ', "' . $domain . '" );' :
125
-            'eejs.i18n.setLocaleData( ' . wp_json_encode($translations) . ' );';
126
-        wp_add_inline_script($handle, $script, 'before');
127
-    }
128
-
129
-
130
-    /**
131
-     * Queues up the translation strings for the given handle.
132
-     *
133
-     * @param string $handle The script handle being queued up.
134
-     */
135
-    private function queueI18nTranslationsForHandle($handle)
136
-    {
137
-        if (isset($this->queued_scripts[$handle])) {
138
-            $domain = $this->queued_scripts[$handle];
139
-            $translations = $this->getJedLocaleDataForDomainAndChunk($handle, $domain);
140
-            if (count($translations) > 0) {
141
-                $this->queued_handle_translations[$handle] = array(
142
-                    'domain'       => $domain,
143
-                    'translations' => $translations,
144
-                );
145
-            }
146
-            unset($this->queued_scripts[$handle]);
147
-        }
148
-    }
149
-
150
-
151
-    /**
152
-     * Sets the internal i18n_map property.
153
-     * If $chunk_map is empty or not an array, will attempt to load a chunk map from a default named map.
154
-     *
155
-     * @param array $i18n_map  If provided, an array of translation strings indexed by script handle names they
156
-     *                         correspond to.
157
-     */
158
-    private function setI18nMap(array $i18n_map)
159
-    {
160
-        if (empty($i18n_map)) {
161
-            $i18n_map = file_exists($this->domain->pluginPath() . 'translation-map.json')
162
-                ? json_decode(
163
-                        file_get_contents($this->domain->pluginPath() . 'translation-map.json'),
164
-                        true
165
-                    )
166
-                : array();
167
-        }
168
-        $this->i18n_map = $i18n_map;
169
-    }
170
-
171
-
172
-    /**
173
-     * Get the jed locale data for a given $handle and domain
174
-     *
175
-     * @param string $handle The name for the script handle we want strings returned for.
176
-     * @param string $domain The i18n domain.
177
-     * @return array
178
-     */
179
-    protected function getJedLocaleDataForDomainAndChunk($handle, $domain)
180
-    {
181
-        $translations = $this->getJedLocaleData($domain);
182
-        // get index for adding back after extracting strings for this $chunk.
183
-        $index = $translations[''];
184
-        $translations = $this->getLocaleDataMatchingMap(
185
-            $this->getOriginalStringsForHandleFromMap($handle),
186
-            $translations
187
-        );
188
-        $translations[''] = $index;
189
-        return $translations;
190
-    }
191
-
192
-
193
-    /**
194
-     * Get locale data for given strings from given translations
195
-     *
196
-     * @param array $string_set   This is the subset of strings (msgIds) we want to extract from the translations array.
197
-     * @param array $translations Translation data to extra strings from.
198
-     * @return array
199
-     */
200
-    protected function getLocaleDataMatchingMap(array $string_set, array $translations)
201
-    {
202
-        if (empty($string_set)) {
203
-            return array();
204
-        }
205
-        // some strings with quotes in them will break on the array_flip, so making sure quotes in the string are
206
-        // slashed also filter falsey values.
207
-        $string_set = array_unique(array_filter(wp_slash($string_set)));
208
-        return array_intersect_key($translations, array_flip($string_set));
209
-    }
210
-
211
-
212
-    /**
213
-     * Get original strings to translate for the given chunk from the map
214
-     *
215
-     * @param string $handle The script handle name to get strings from the map for.
216
-     * @return array
217
-     */
218
-    protected function getOriginalStringsForHandleFromMap($handle)
219
-    {
220
-        return isset($this->i18n_map[$handle]) ? $this->i18n_map[$handle] : array();
221
-    }
222
-
223
-
224
-    /**
225
-     * Returns Jed-formatted localization data.
226
-     *
227
-     * @param  string $domain Translation domain.
228
-     * @return array
229
-     */
230
-    private function getJedLocaleData($domain)
231
-    {
232
-        $translations = get_translations_for_domain($domain);
233
-
234
-        $locale = array(
235
-            '' => array(
236
-                'domain' => $domain,
237
-                'lang'   => is_admin() ? get_user_locale() : get_locale(),
238
-            ),
239
-        );
240
-
241
-        if (! empty($translations->headers['Plural-Forms'])) {
242
-            $locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
243
-        }
244
-
245
-        foreach ($translations->entries as $msgid => $entry) {
246
-            $locale[$msgid] = $entry->translations;
247
-        }
248
-
249
-        return $locale;
250
-    }
17
+	/**
18
+	 * @var DomainInterface
19
+	 */
20
+	private $domain;
21
+
22
+	/**
23
+	 * Will hold all registered i18n scripts.  Prevents script handles from being registered more than once.
24
+	 *
25
+	 * @var array
26
+	 */
27
+	private $registered_i18n = array();
28
+
29
+
30
+	/**
31
+	 * Used to hold queued translations for the chunks loading in a view.
32
+	 *
33
+	 * @var array
34
+	 */
35
+	private $queued_handle_translations = array();
36
+
37
+	/**
38
+	 * Used to track script handles queued for adding translation strings as inline data in the dom.
39
+	 *
40
+	 * @var array
41
+	 */
42
+	private $queued_scripts = array();
43
+
44
+
45
+	/**
46
+	 * Obtained from the generated json file from the all javascript using wp.i18n with a map of script handle names to
47
+	 * translation strings.
48
+	 *
49
+	 * @var array
50
+	 */
51
+	private $i18n_map;
52
+
53
+
54
+	/**
55
+	 * I18nRegistry constructor.
56
+	 *
57
+	 * @param array() $i18n_map  An array of script handle names and the strings translated for those handles.  If not
58
+	 *                            provided, the class will look for map in root of plugin with filename of
59
+	 *                            'translation-map.json'.
60
+	 * @param DomainInterface $domain
61
+	 */
62
+	public function __construct(array $i18n_map = array(), DomainInterface $domain)
63
+	{
64
+		$this->domain = $domain;
65
+		$this->setI18nMap($i18n_map);
66
+		add_filter('print_scripts_array', array($this, 'queueI18n'));
67
+	}
68
+
69
+
70
+	/**
71
+	 * Used to register a script that has i18n strings for its $handle
72
+	 *
73
+	 * @param string $handle The script handle reference.
74
+	 * @param string $domain The i18n domain for the strings.
75
+	 */
76
+	public function registerScriptI18n($handle, $domain = 'event_espresso')
77
+	{
78
+		if(! isset($this->registered_i18n[$handle])) {
79
+			$this->registered_i18n[ $handle ] = 1;
80
+			$this->queued_scripts[ $handle ] = $domain;
81
+		}
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Callback on print_scripts_array to listen for scripts enqueued and handle setting up the localized data.
88
+	 *
89
+	 * @param array $handles Array of registered script handles.
90
+	 * @return array
91
+	 */
92
+	public function queueI18n(array $handles)
93
+	{
94
+		if (empty($this->queued_scripts)) {
95
+			return $handles;
96
+		}
97
+		foreach ($handles as $handle) {
98
+			$this->queueI18nTranslationsForHandle($handle);
99
+		}
100
+		if ($this->queued_handle_translations) {
101
+			foreach ($this->queued_handle_translations as $handle => $translations_for_domain) {
102
+				$this->registerInlineScript(
103
+					$handle,
104
+					$translations_for_domain['translations'],
105
+					$translations_for_domain['domain']
106
+				);
107
+			}
108
+		}
109
+		return $handles;
110
+	}
111
+
112
+
113
+	/**
114
+	 * Registers inline script with translations for given handle and domain.
115
+	 *
116
+	 * @param string $handle       Handle used to register javascript file containing translations.
117
+	 * @param array  $translations Array of string translations.
118
+	 * @param string $domain       Domain for translations.  If left empty then strings are registered with the default
119
+	 *                             domain for the javascript.
120
+	 */
121
+	protected function registerInlineScript($handle, array $translations, $domain)
122
+	{
123
+		$script = $domain ?
124
+			'eejs.i18n.setLocaleData( ' . wp_json_encode($translations) . ', "' . $domain . '" );' :
125
+			'eejs.i18n.setLocaleData( ' . wp_json_encode($translations) . ' );';
126
+		wp_add_inline_script($handle, $script, 'before');
127
+	}
128
+
129
+
130
+	/**
131
+	 * Queues up the translation strings for the given handle.
132
+	 *
133
+	 * @param string $handle The script handle being queued up.
134
+	 */
135
+	private function queueI18nTranslationsForHandle($handle)
136
+	{
137
+		if (isset($this->queued_scripts[$handle])) {
138
+			$domain = $this->queued_scripts[$handle];
139
+			$translations = $this->getJedLocaleDataForDomainAndChunk($handle, $domain);
140
+			if (count($translations) > 0) {
141
+				$this->queued_handle_translations[$handle] = array(
142
+					'domain'       => $domain,
143
+					'translations' => $translations,
144
+				);
145
+			}
146
+			unset($this->queued_scripts[$handle]);
147
+		}
148
+	}
149
+
150
+
151
+	/**
152
+	 * Sets the internal i18n_map property.
153
+	 * If $chunk_map is empty or not an array, will attempt to load a chunk map from a default named map.
154
+	 *
155
+	 * @param array $i18n_map  If provided, an array of translation strings indexed by script handle names they
156
+	 *                         correspond to.
157
+	 */
158
+	private function setI18nMap(array $i18n_map)
159
+	{
160
+		if (empty($i18n_map)) {
161
+			$i18n_map = file_exists($this->domain->pluginPath() . 'translation-map.json')
162
+				? json_decode(
163
+						file_get_contents($this->domain->pluginPath() . 'translation-map.json'),
164
+						true
165
+					)
166
+				: array();
167
+		}
168
+		$this->i18n_map = $i18n_map;
169
+	}
170
+
171
+
172
+	/**
173
+	 * Get the jed locale data for a given $handle and domain
174
+	 *
175
+	 * @param string $handle The name for the script handle we want strings returned for.
176
+	 * @param string $domain The i18n domain.
177
+	 * @return array
178
+	 */
179
+	protected function getJedLocaleDataForDomainAndChunk($handle, $domain)
180
+	{
181
+		$translations = $this->getJedLocaleData($domain);
182
+		// get index for adding back after extracting strings for this $chunk.
183
+		$index = $translations[''];
184
+		$translations = $this->getLocaleDataMatchingMap(
185
+			$this->getOriginalStringsForHandleFromMap($handle),
186
+			$translations
187
+		);
188
+		$translations[''] = $index;
189
+		return $translations;
190
+	}
191
+
192
+
193
+	/**
194
+	 * Get locale data for given strings from given translations
195
+	 *
196
+	 * @param array $string_set   This is the subset of strings (msgIds) we want to extract from the translations array.
197
+	 * @param array $translations Translation data to extra strings from.
198
+	 * @return array
199
+	 */
200
+	protected function getLocaleDataMatchingMap(array $string_set, array $translations)
201
+	{
202
+		if (empty($string_set)) {
203
+			return array();
204
+		}
205
+		// some strings with quotes in them will break on the array_flip, so making sure quotes in the string are
206
+		// slashed also filter falsey values.
207
+		$string_set = array_unique(array_filter(wp_slash($string_set)));
208
+		return array_intersect_key($translations, array_flip($string_set));
209
+	}
210
+
211
+
212
+	/**
213
+	 * Get original strings to translate for the given chunk from the map
214
+	 *
215
+	 * @param string $handle The script handle name to get strings from the map for.
216
+	 * @return array
217
+	 */
218
+	protected function getOriginalStringsForHandleFromMap($handle)
219
+	{
220
+		return isset($this->i18n_map[$handle]) ? $this->i18n_map[$handle] : array();
221
+	}
222
+
223
+
224
+	/**
225
+	 * Returns Jed-formatted localization data.
226
+	 *
227
+	 * @param  string $domain Translation domain.
228
+	 * @return array
229
+	 */
230
+	private function getJedLocaleData($domain)
231
+	{
232
+		$translations = get_translations_for_domain($domain);
233
+
234
+		$locale = array(
235
+			'' => array(
236
+				'domain' => $domain,
237
+				'lang'   => is_admin() ? get_user_locale() : get_locale(),
238
+			),
239
+		);
240
+
241
+		if (! empty($translations->headers['Plural-Forms'])) {
242
+			$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
243
+		}
244
+
245
+		foreach ($translations->entries as $msgid => $entry) {
246
+			$locale[$msgid] = $entry->translations;
247
+		}
248
+
249
+		return $locale;
250
+	}
251 251
 }
252 252
\ No newline at end of file
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.4.0');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.63.rc.014');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.63.rc.014');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.