Completed
Push — master ( 389cfb...bc3e86 )
by Michal
07:54
created
src/Webrouse/AssetMacro/AssetMacro.php 2 patches
Indentation   +183 added lines, -183 removed lines patch added patch discarded remove patch
@@ -55,175 +55,175 @@  discard block
 block discarded – undo
55 55
 			'%node.word, %node.array, $basePath, $template->global->' . self::CONFIG_PROVIDER . '))');
56 56
 	}
57 57
 
58
-    /**
59
-     * @param string $asset     Asset relative path
60
-     * @param array $args       Other macro arguments
61
-     * @param string $basePath  Base path
62
-     * @param array $config     Macro configuration
63
-     * @return string
64
-     */
58
+	/**
59
+	 * @param string $asset     Asset relative path
60
+	 * @param array $args       Other macro arguments
61
+	 * @param string $basePath  Base path
62
+	 * @param array $config     Macro configuration
63
+	 * @return string
64
+	 */
65 65
 	public static function resolveAssetPath($asset, array $args, $basePath, array $config) {
66
-        list($path, $format, $need) = self::processArguments($asset, $args);
67
-	    $wwwDir = self::normalizePath($config['wwwDir']);
68
-        $manifest = self::resolveManifest($path, $need, $wwwDir, $config);
69
-        $revision = $manifest === NULL ? NULL : self::resolveRevision($manifest, $path, $need, $config);
70
-
71
-        // Is revision only version (query parameter) or full path to asset?
72
-        $isVersion = $revision === NULL || strspn($revision,"./") === 0;
73
-
74
-        // Check if asset exists
75
-        if ($config['existCheck'] === TRUE) {
76
-            $ds = DIRECTORY_SEPARATOR;
77
-            $filePath = $isVersion ? ($wwwDir . $ds . $path) : ($wwwDir . $ds . self::normalizePath($revision));
78
-            if (! file_exists($filePath)) {
79
-                $msg = sprintf("Asset '%s' not found.", $filePath);
80
-                self::throwError(new AssetNotFoundException($msg), $config['missingAsset'], $need);
81
-                return '';
82
-            }
83
-        }
84
-
85
-        // Format output
86
-        return self::formatOutput($format, $basePath, $path, $revision, $isVersion);
87
-    }
88
-
89
-    /**
90
-     * @param string $format         Output format
91
-     * @param string $basePath       Base path
92
-     * @param string $path           Asset relative path
93
-     * @param string|null $revision  Asset revision (version or path to file)
94
-     * @param bool   $isVersion      Is revision only version or full path?
95
-     * @return string
96
-     */
97
-    private static function formatOutput($format, $basePath, $path, $revision, $isVersion)
98
-    {
99
-        $revision = $revision ?: 'unknown';
100
-        $path = $isVersion ?
101
-            sprintf("%s?v=%s", $path, $revision) :
102
-            $revision;
103
-
104
-        return Strings::replace($format,
105
-            '/%([^%]+)%/',
106
-            function ($matches) use ($basePath, $format, $path, $revision) {
107
-                switch ($matches[1]) {
108
-                    case 'raw':
109
-                        return $revision;
110
-                    case 'basePath':
111
-                        return $basePath;
112
-                    case 'path':
113
-                        return $path;
114
-                    case 'url':
115
-                        return sprintf("%s/%s", $basePath, $path);
116
-                    default:
117
-                        $msg = sprintf(
118
-                            "Asset macro: Invalid variable '%s' in format '%s'. " .
119
-                            "Use one of allowed variables: %%raw%%, %%basePath%%, %%path%%, %%url%%.",
120
-                            $matches[1],
121
-                            $format
122
-                        );
123
-                        throw new InvalidVariableException($msg);
124
-                }
125
-            });
126
-    }
127
-
128
-    /**
129
-     * @param string $asset  Asset path specified in macro
130
-     * @param array $args    Macro arguments
131
-     * @return array
132
-     */
133
-    private static function processArguments($asset, array $args)
134
-    {
135
-        $format = isset($args['format']) ? $args['format'] : (isset($args[0]) ? $args[0] : '%url%');
136
-        $need = isset($args['need']) ? $args['need'] : (isset($args[1]) ? $args[1] : TRUE);
137
-
138
-        Validators::assert($asset, 'string', 'path');
139
-        Validators::assert($format, 'string', 'format');
140
-        Validators::assert($need, 'bool', 'need');
141
-
142
-        $path = self::normalizePath($asset);
143
-
144
-        return [$path, $format, $need];
145
-    }
146
-
147
-    /**
148
-     * @param string $asset   Asset path specified in macro
149
-     * @param bool $need      Fail if manifest doesn't exist?
150
-     * @param string $wwwDir  Public www dir
151
-     * @param array $config   Macro configuration
152
-     * @return null|array
153
-     */
154
-    private static function resolveManifest($asset, $need, $wwwDir, array $config) {
155
-        $manifest = $config['manifest'];
156
-
157
-	    // Asset revisions specified directly in configuration
158
-        if (is_array($manifest)) {
159
-            return $manifest;
160
-        }
161
-
162
-        // Path to JSON manifest
163
-        if (is_string($manifest)) {
164
-            if ( ! file_exists($manifest)) {
165
-                $msg = sprintf("Manifest file not found: '%s'.", $manifest);
166
-                self::throwError(new ManifestNotFoundException($msg), $config['missingManifest'], $need);
167
-                return NULL;
168
-            }
169
-            return Json::decode(file_get_contents($manifest), Json::FORCE_ARRAY);
170
-        }
171
-
172
-        // Autodetect manifest path
173
-        return self::autodetectManifest($asset, $wwwDir, $need, $config);
174
-    }
175
-
176
-    /**
177
-     * @param string $asset   Asset path specified in macro
178
-     * @param string $wwwDir  Public www dir
179
-     * @param bool $need      Fail if asset/manifest doesn't exist?
180
-     * @param array $config   Macro configuration
181
-     * @return null|array
182
-     */
183
-    private static function autodetectManifest($asset, $wwwDir, $need, array $config) {
184
-        // Get asset dir, there begins search manifest
185
-        $dir = realpath($wwwDir . DIRECTORY_SEPARATOR . dirname($asset));
186
-        if ($dir === FALSE) {
187
-            $msg = sprintf("Parent dir of asset '%s' not found.", $asset);
188
-            self::throwError(new DirNotFoundException($msg), $config['missingAsset'], $need);
189
-            return NULL;
190
-        }
191
-
192
-        // Autodetect manifest
193
-        $autodetectPaths = $config['autodetect'];
194
-        while (Strings::startsWith($dir, $wwwDir)) {
195
-            foreach ($autodetectPaths as $path) {
196
-                $path = $dir . DIRECTORY_SEPARATOR . $path;
197
-                if (file_exists($path)) {
198
-                    return Json::decode(file_get_contents($path), Json::FORCE_ARRAY);
199
-                }
200
-            }
201
-
202
-            $dir = dirname($dir); // go up
203
-        }
204
-
205
-        $msg = sprintf("Manifest not found in: %s.", implode(', ', $autodetectPaths));
206
-        self::throwError(new ManifestNotFoundException($msg), $config['missingManifest'], $need);
207
-        return NULL;
208
-    }
209
-
210
-    /**
211
-     * @param null|array $manifest  Array of revisions
212
-     * @param string $path          Asset path
213
-     * @param bool $need            Fail if revision doesn't exist?
214
-     * @param array $config         Macro configuration
215
-     * @return null|string
216
-     */
217
-    private static function resolveRevision($manifest, $path, $need, array $config) {
218
-        $revision = isset($manifest[$path]) ? $manifest[$path] : NULL;
66
+		list($path, $format, $need) = self::processArguments($asset, $args);
67
+		$wwwDir = self::normalizePath($config['wwwDir']);
68
+		$manifest = self::resolveManifest($path, $need, $wwwDir, $config);
69
+		$revision = $manifest === NULL ? NULL : self::resolveRevision($manifest, $path, $need, $config);
70
+
71
+		// Is revision only version (query parameter) or full path to asset?
72
+		$isVersion = $revision === NULL || strspn($revision,"./") === 0;
73
+
74
+		// Check if asset exists
75
+		if ($config['existCheck'] === TRUE) {
76
+			$ds = DIRECTORY_SEPARATOR;
77
+			$filePath = $isVersion ? ($wwwDir . $ds . $path) : ($wwwDir . $ds . self::normalizePath($revision));
78
+			if (! file_exists($filePath)) {
79
+				$msg = sprintf("Asset '%s' not found.", $filePath);
80
+				self::throwError(new AssetNotFoundException($msg), $config['missingAsset'], $need);
81
+				return '';
82
+			}
83
+		}
84
+
85
+		// Format output
86
+		return self::formatOutput($format, $basePath, $path, $revision, $isVersion);
87
+	}
88
+
89
+	/**
90
+	 * @param string $format         Output format
91
+	 * @param string $basePath       Base path
92
+	 * @param string $path           Asset relative path
93
+	 * @param string|null $revision  Asset revision (version or path to file)
94
+	 * @param bool   $isVersion      Is revision only version or full path?
95
+	 * @return string
96
+	 */
97
+	private static function formatOutput($format, $basePath, $path, $revision, $isVersion)
98
+	{
99
+		$revision = $revision ?: 'unknown';
100
+		$path = $isVersion ?
101
+			sprintf("%s?v=%s", $path, $revision) :
102
+			$revision;
103
+
104
+		return Strings::replace($format,
105
+			'/%([^%]+)%/',
106
+			function ($matches) use ($basePath, $format, $path, $revision) {
107
+				switch ($matches[1]) {
108
+					case 'raw':
109
+						return $revision;
110
+					case 'basePath':
111
+						return $basePath;
112
+					case 'path':
113
+						return $path;
114
+					case 'url':
115
+						return sprintf("%s/%s", $basePath, $path);
116
+					default:
117
+						$msg = sprintf(
118
+							"Asset macro: Invalid variable '%s' in format '%s'. " .
119
+							"Use one of allowed variables: %%raw%%, %%basePath%%, %%path%%, %%url%%.",
120
+							$matches[1],
121
+							$format
122
+						);
123
+						throw new InvalidVariableException($msg);
124
+				}
125
+			});
126
+	}
127
+
128
+	/**
129
+	 * @param string $asset  Asset path specified in macro
130
+	 * @param array $args    Macro arguments
131
+	 * @return array
132
+	 */
133
+	private static function processArguments($asset, array $args)
134
+	{
135
+		$format = isset($args['format']) ? $args['format'] : (isset($args[0]) ? $args[0] : '%url%');
136
+		$need = isset($args['need']) ? $args['need'] : (isset($args[1]) ? $args[1] : TRUE);
137
+
138
+		Validators::assert($asset, 'string', 'path');
139
+		Validators::assert($format, 'string', 'format');
140
+		Validators::assert($need, 'bool', 'need');
141
+
142
+		$path = self::normalizePath($asset);
143
+
144
+		return [$path, $format, $need];
145
+	}
146
+
147
+	/**
148
+	 * @param string $asset   Asset path specified in macro
149
+	 * @param bool $need      Fail if manifest doesn't exist?
150
+	 * @param string $wwwDir  Public www dir
151
+	 * @param array $config   Macro configuration
152
+	 * @return null|array
153
+	 */
154
+	private static function resolveManifest($asset, $need, $wwwDir, array $config) {
155
+		$manifest = $config['manifest'];
156
+
157
+		// Asset revisions specified directly in configuration
158
+		if (is_array($manifest)) {
159
+			return $manifest;
160
+		}
161
+
162
+		// Path to JSON manifest
163
+		if (is_string($manifest)) {
164
+			if ( ! file_exists($manifest)) {
165
+				$msg = sprintf("Manifest file not found: '%s'.", $manifest);
166
+				self::throwError(new ManifestNotFoundException($msg), $config['missingManifest'], $need);
167
+				return NULL;
168
+			}
169
+			return Json::decode(file_get_contents($manifest), Json::FORCE_ARRAY);
170
+		}
171
+
172
+		// Autodetect manifest path
173
+		return self::autodetectManifest($asset, $wwwDir, $need, $config);
174
+	}
175
+
176
+	/**
177
+	 * @param string $asset   Asset path specified in macro
178
+	 * @param string $wwwDir  Public www dir
179
+	 * @param bool $need      Fail if asset/manifest doesn't exist?
180
+	 * @param array $config   Macro configuration
181
+	 * @return null|array
182
+	 */
183
+	private static function autodetectManifest($asset, $wwwDir, $need, array $config) {
184
+		// Get asset dir, there begins search manifest
185
+		$dir = realpath($wwwDir . DIRECTORY_SEPARATOR . dirname($asset));
186
+		if ($dir === FALSE) {
187
+			$msg = sprintf("Parent dir of asset '%s' not found.", $asset);
188
+			self::throwError(new DirNotFoundException($msg), $config['missingAsset'], $need);
189
+			return NULL;
190
+		}
191
+
192
+		// Autodetect manifest
193
+		$autodetectPaths = $config['autodetect'];
194
+		while (Strings::startsWith($dir, $wwwDir)) {
195
+			foreach ($autodetectPaths as $path) {
196
+				$path = $dir . DIRECTORY_SEPARATOR . $path;
197
+				if (file_exists($path)) {
198
+					return Json::decode(file_get_contents($path), Json::FORCE_ARRAY);
199
+				}
200
+			}
201
+
202
+			$dir = dirname($dir); // go up
203
+		}
204
+
205
+		$msg = sprintf("Manifest not found in: %s.", implode(', ', $autodetectPaths));
206
+		self::throwError(new ManifestNotFoundException($msg), $config['missingManifest'], $need);
207
+		return NULL;
208
+	}
209
+
210
+	/**
211
+	 * @param null|array $manifest  Array of revisions
212
+	 * @param string $path          Asset path
213
+	 * @param bool $need            Fail if revision doesn't exist?
214
+	 * @param array $config         Macro configuration
215
+	 * @return null|string
216
+	 */
217
+	private static function resolveRevision($manifest, $path, $need, array $config) {
218
+		$revision = isset($manifest[$path]) ? $manifest[$path] : NULL;
219 219
         
220
-        if ($revision === NULL) {
221
-            $msg = sprintf("Revision for asset '%s' not found in manifest.", $path);
222
-            self::throwError(new AssetVersionNotFound($msg), $config['missingRevision'], $need);
223
-        }
220
+		if ($revision === NULL) {
221
+			$msg = sprintf("Revision for asset '%s' not found in manifest.", $path);
222
+			self::throwError(new AssetVersionNotFound($msg), $config['missingRevision'], $need);
223
+		}
224 224
         
225
-        return $revision;
226
-    }
225
+		return $revision;
226
+	}
227 227
 
228 228
 
229 229
 	/**
@@ -245,27 +245,27 @@  discard block
 block discarded – undo
245 245
 	}
246 246
 
247 247
 	private static function normalizePath($path, $separator = '\\/')
248
-    {
249
-        // Remove any kind of unicode whitespace
250
-        $normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
248
+	{
249
+		// Remove any kind of unicode whitespace
250
+		$normalized = preg_replace('#\p{C}+|^\./#u', '', $path);
251 251
 
252
-        // Path remove self referring paths ("/./").
253
-        $normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
252
+		// Path remove self referring paths ("/./").
253
+		$normalized = preg_replace('#/\.(?=/)|^\./|\./$#', '', $normalized);
254 254
 
255
-        // Regex for resolving relative paths
256
-        $regex = '#\/*[^/\.]+/\.\.#Uu';
255
+		// Regex for resolving relative paths
256
+		$regex = '#\/*[^/\.]+/\.\.#Uu';
257 257
 
258
-        while (preg_match($regex, $normalized)) {
259
-            $normalized = preg_replace($regex, '', $normalized);
260
-        }
258
+		while (preg_match($regex, $normalized)) {
259
+			$normalized = preg_replace($regex, '', $normalized);
260
+		}
261 261
 
262
-        if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
263
-            throw new InvalidPathException(
264
-                sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized)
265
-            );
266
-        }
262
+		if (preg_match('#/\.{2}|\.{2}/#', $normalized)) {
263
+			throw new InvalidPathException(
264
+				sprintf("Path is outside of the defined root, path: '%s', resolved: '%s'.", $path, $normalized)
265
+			);
266
+		}
267 267
 
268
-        return rtrim($normalized, $separator);
269
-    }
268
+		return rtrim($normalized, $separator);
269
+	}
270 270
 
271 271
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -6 removed lines patch added patch discarded remove patch
@@ -69,13 +69,13 @@  discard block
 block discarded – undo
69 69
         $revision = $manifest === NULL ? NULL : self::resolveRevision($manifest, $path, $need, $config);
70 70
 
71 71
         // Is revision only version (query parameter) or full path to asset?
72
-        $isVersion = $revision === NULL || strspn($revision,"./") === 0;
72
+        $isVersion = $revision === NULL || strspn($revision, "./") === 0;
73 73
 
74 74
         // Check if asset exists
75 75
         if ($config['existCheck'] === TRUE) {
76 76
             $ds = DIRECTORY_SEPARATOR;
77 77
             $filePath = $isVersion ? ($wwwDir . $ds . $path) : ($wwwDir . $ds . self::normalizePath($revision));
78
-            if (! file_exists($filePath)) {
78
+            if (!file_exists($filePath)) {
79 79
                 $msg = sprintf("Asset '%s' not found.", $filePath);
80 80
                 self::throwError(new AssetNotFoundException($msg), $config['missingAsset'], $need);
81 81
                 return '';
@@ -98,12 +98,11 @@  discard block
 block discarded – undo
98 98
     {
99 99
         $revision = $revision ?: 'unknown';
100 100
         $path = $isVersion ?
101
-            sprintf("%s?v=%s", $path, $revision) :
102
-            $revision;
101
+            sprintf("%s?v=%s", $path, $revision) : $revision;
103 102
 
104 103
         return Strings::replace($format,
105 104
             '/%([^%]+)%/',
106
-            function ($matches) use ($basePath, $format, $path, $revision) {
105
+            function($matches) use ($basePath, $format, $path, $revision) {
107 106
                 switch ($matches[1]) {
108 107
                     case 'raw':
109 108
                         return $revision;
@@ -161,7 +160,7 @@  discard block
 block discarded – undo
161 160
 
162 161
         // Path to JSON manifest
163 162
         if (is_string($manifest)) {
164
-            if ( ! file_exists($manifest)) {
163
+            if (!file_exists($manifest)) {
165 164
                 $msg = sprintf("Manifest file not found: '%s'.", $manifest);
166 165
                 self::throwError(new ManifestNotFoundException($msg), $config['missingManifest'], $need);
167 166
                 return NULL;
Please login to merge, or discard this patch.
src/Webrouse/AssetMacro/DI/Extension.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -16,21 +16,21 @@  discard block
 block discarded – undo
16 16
 	 * @var array
17 17
 	 */
18 18
 	public $defaults = [
19
-	    // Public www dir
19
+		// Public www dir
20 20
 		'wwwDir' => '%wwwDir%',
21
-        // Assets revision manifest
21
+		// Assets revision manifest
22 22
 		'manifest' => NULL,
23
-        // Paths for manifest autodetection
23
+		// Paths for manifest autodetection
24 24
 		'autodetect' => [
25
-            'assets.json',
26
-		    'busters.json',
25
+			'assets.json',
26
+			'busters.json',
27 27
 			'versions.json',
28
-            'manifest.json',
28
+			'manifest.json',
29 29
 			'rev-manifest.json',
30 30
 		],
31
-        // Check the existence of asset file
32
-        'existCheck' => TRUE,
33
-        // Error handling
31
+		// Check the existence of asset file
32
+		'existCheck' => TRUE,
33
+		// Error handling
34 34
 		'missingAsset' => 'notice',    // exception, notice, or ignore
35 35
 		'missingManifest' => 'notice', // exception, notice, or ignore
36 36
 		'missingRevision' => 'ignore',  // exception, notice, or ignore
@@ -42,16 +42,16 @@  discard block
 block discarded – undo
42 42
 		$config = $this->getContainerBuilder()->expand($this->validateConfig($this->defaults));
43 43
 
44 44
 		// Validate configuration
45
-        Validators::assertField($config, 'wwwDir', 'string');
46
-        Validators::assertField($config, 'manifest', 'null|string|array');
47
-        Validators::assertField($config, 'autodetect', 'array');
48
-        Validators::assertField($config, 'existCheck', 'bool');
45
+		Validators::assertField($config, 'wwwDir', 'string');
46
+		Validators::assertField($config, 'manifest', 'null|string|array');
47
+		Validators::assertField($config, 'autodetect', 'array');
48
+		Validators::assertField($config, 'existCheck', 'bool');
49 49
 		$choices = ['exception', 'notice', 'ignore'];
50 50
 		$this->validateChoices('missingAsset', $choices);
51 51
 		$this->validateChoices('missingManifest', $choices);
52 52
 		$this->validateChoices('missingRevision', $choices);
53 53
 
54
-        // Setup macro
54
+		// Setup macro
55 55
 		$builder = $this->getContainerBuilder();
56 56
 		$builder->getDefinition('latte.latteFactory')
57 57
 			->addSetup("?->addProvider(?, ?)", ['@self', AssetMacro::CONFIG_PROVIDER, $config])
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -31,9 +31,9 @@  discard block
 block discarded – undo
31 31
         // Check the existence of asset file
32 32
         'existCheck' => TRUE,
33 33
         // Error handling
34
-		'missingAsset' => 'notice',    // exception, notice, or ignore
34
+		'missingAsset' => 'notice', // exception, notice, or ignore
35 35
 		'missingManifest' => 'notice', // exception, notice, or ignore
36
-		'missingRevision' => 'ignore',  // exception, notice, or ignore
36
+		'missingRevision' => 'ignore', // exception, notice, or ignore
37 37
 	];
38 38
 
39 39
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	 */
69 69
 	private function validateChoices($key, array $choices)
70 70
 	{
71
-		if ( ! in_array($this->config[$key], $choices)) {
71
+		if (!in_array($this->config[$key], $choices)) {
72 72
 			throw new UnexpectedValueException(sprintf(
73 73
 				"Unexpected value '%s' of '%s' configuration key. Allowed values: %s.",
74 74
 				$this->config[$key],
Please login to merge, or discard this patch.