| Total Complexity | 131 |
| Total Lines | 783 |
| Duplicated Lines | 0 % |
| Changes | 19 | ||
| Bugs | 11 | Features | 0 |
Complex classes like Asset often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Asset, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 27 | class Asset implements \ArrayAccess |
||
| 28 | { |
||
| 29 | /** @var Builder */ |
||
| 30 | protected $builder; |
||
| 31 | |||
| 32 | /** @var Config */ |
||
| 33 | protected $config; |
||
| 34 | |||
| 35 | /** @var array */ |
||
| 36 | protected $data = []; |
||
| 37 | |||
| 38 | /** @var bool */ |
||
| 39 | protected $fingerprinted = false; |
||
| 40 | |||
| 41 | /** @var bool */ |
||
| 42 | protected $compiled = false; |
||
| 43 | |||
| 44 | /** @var bool */ |
||
| 45 | protected $minified = false; |
||
| 46 | |||
| 47 | /** @var bool */ |
||
| 48 | protected $optimize = false; |
||
| 49 | protected $optimized = false; |
||
| 50 | |||
| 51 | protected $resized = false; |
||
| 52 | |||
| 53 | /** @var bool */ |
||
| 54 | protected $ignore_missing = false; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * Creates an Asset from a file path or an array of files path. |
||
| 58 | * |
||
| 59 | * @param Builder $builder |
||
| 60 | * @param string|array $paths |
||
| 61 | * @param array|null $options e.g.: ['fingerprint' => true, 'minify' => true, 'filename' => '', 'ignore_missing' => false] |
||
| 62 | * |
||
| 63 | * @throws RuntimeException |
||
| 64 | */ |
||
| 65 | public function __construct(Builder $builder, $paths, array $options = null) |
||
| 66 | { |
||
| 67 | $this->builder = $builder; |
||
| 68 | $this->config = $builder->getConfig(); |
||
| 69 | $paths = is_array($paths) ? $paths : [$paths]; |
||
| 70 | array_walk($paths, function ($path) { |
||
| 71 | if (empty($path)) { |
||
| 72 | throw new RuntimeException('The path to an asset can\'t be empty.'); |
||
| 73 | } |
||
| 74 | if (substr($path, 0, 2) == '..') { |
||
| 75 | throw new RuntimeException(\sprintf('The path to asset "%s" is wrong: it must be directly relative to "assets" or "static" directory, or a remote URL.', $path)); |
||
| 76 | } |
||
| 77 | }); |
||
| 78 | $this->data = [ |
||
| 79 | 'file' => '', // absolute file path |
||
| 80 | 'files' => [], // bundle: files path |
||
| 81 | 'filename' => '', // filename |
||
| 82 | 'path_source' => '', // public path to the file, before transformations |
||
| 83 | 'path' => '', // public path to the file, after transformations |
||
| 84 | 'missing' => false, // if file not found, but missing ollowed 'missing' is true |
||
| 85 | 'ext' => '', // file extension |
||
| 86 | 'type' => '', // file type (e.g.: image, audio, video, etc.) |
||
| 87 | 'subtype' => '', // file media type (e.g.: image/png, audio/mp3, etc.) |
||
| 88 | 'size' => 0, // file size (in bytes) |
||
| 89 | 'content_source' => '', // file content, before transformations |
||
| 90 | 'content' => '', // file content, after transformations |
||
| 91 | 'width' => 0, // width (in pixels) in case of an image |
||
| 92 | 'height' => 0, // height (in pixels) in case of an image |
||
| 93 | ]; |
||
| 94 | |||
| 95 | // handles options |
||
| 96 | $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled'); |
||
| 97 | $minify = (bool) $this->config->get('assets.minify.enabled'); |
||
| 98 | $optimize = (bool) $this->config->get('assets.images.optimize.enabled'); |
||
| 99 | $filename = ''; |
||
| 100 | $ignore_missing = false; |
||
| 101 | $remote_fallback = null; |
||
| 102 | $force_slash = true; |
||
| 103 | extract(is_array($options) ? $options : [], EXTR_IF_EXISTS); |
||
| 104 | $this->ignore_missing = $ignore_missing; |
||
| 105 | |||
| 106 | // fill data array with file(s) informations |
||
| 107 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 108 | $cacheKey = \sprintf('%s__%s', implode('_', $paths), $this->builder->getVersion()); |
||
| 109 | if (!$cache->has($cacheKey)) { |
||
| 110 | $pathsCount = count($paths); |
||
| 111 | $file = []; |
||
| 112 | for ($i = 0; $i < $pathsCount; $i++) { |
||
| 113 | // loads file(s) |
||
| 114 | $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash); |
||
| 115 | // bundle: same type/ext only |
||
| 116 | if ($i > 0) { |
||
| 117 | if ($file[$i]['type'] != $file[$i - 1]['type']) { |
||
| 118 | throw new RuntimeException(\sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type'])); |
||
| 119 | } |
||
| 120 | if ($file[$i]['ext'] != $file[$i - 1]['ext']) { |
||
| 121 | throw new RuntimeException(\sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext'])); |
||
| 122 | } |
||
| 123 | } |
||
| 124 | // missing allowed = empty path |
||
| 125 | if ($file[$i]['missing']) { |
||
| 126 | $this->data['missing'] = true; |
||
| 127 | $this->data['path'] = $file[$i]['path']; |
||
| 128 | |||
| 129 | continue; |
||
| 130 | } |
||
| 131 | // set data |
||
| 132 | $this->data['size'] += $file[$i]['size']; |
||
| 133 | $this->data['content_source'] .= $file[$i]['content']; |
||
| 134 | $this->data['content'] .= $file[$i]['content']; |
||
| 135 | if ($i == 0) { |
||
| 136 | $this->data['file'] = $file[$i]['filepath']; |
||
| 137 | $this->data['filename'] = $file[$i]['path']; |
||
| 138 | $this->data['path_source'] = $file[$i]['path']; |
||
| 139 | $this->data['path'] = $file[$i]['path']; |
||
| 140 | if (!empty($filename)) { /** @phpstan-ignore-line */ |
||
| 141 | $this->data['path'] = '/'.ltrim($filename, '/'); |
||
| 142 | } |
||
| 143 | $this->data['ext'] = $file[$i]['ext']; |
||
| 144 | $this->data['type'] = $file[$i]['type']; |
||
| 145 | $this->data['subtype'] = $file[$i]['subtype']; |
||
| 146 | if ($this->data['type'] == 'image') { |
||
| 147 | $this->data['width'] = $this->getWidth(); |
||
| 148 | $this->data['height'] = $this->getHeight(); |
||
| 149 | } |
||
| 150 | $this->data['url'] = $file[$i]['url']; |
||
| 151 | } |
||
| 152 | // bundle files path |
||
| 153 | $this->data['files'][] = $file[$i]['filepath']; |
||
| 154 | } |
||
| 155 | // bundle: define path |
||
| 156 | if ($pathsCount > 1 && empty($filename)) { /** @phpstan-ignore-line */ |
||
| 157 | switch ($this->data['ext']) { |
||
| 158 | case 'scss': |
||
| 159 | case 'css': |
||
| 160 | $this->data['path'] = '/styles.'.$file[0]['ext']; |
||
| 161 | break; |
||
| 162 | case 'js': |
||
| 163 | $this->data['path'] = '/scripts.'.$file[0]['ext']; |
||
| 164 | break; |
||
| 165 | default: |
||
| 166 | throw new RuntimeException(\sprintf('Asset bundle supports "%s" files only.', '.scss, .css and .js')); |
||
| 167 | } |
||
| 168 | } |
||
| 169 | $cache->set($cacheKey, $this->data); |
||
| 170 | } |
||
| 171 | $this->data = $cache->get($cacheKey); |
||
| 172 | |||
| 173 | $cdn = 1; |
||
| 174 | if ($this->data['type'] == 'image' && $cdn == 1) { |
||
| 175 | return; |
||
| 176 | } |
||
| 177 | |||
| 178 | // fingerprinting |
||
| 179 | if ($fingerprint) { |
||
| 180 | $this->fingerprint(); |
||
| 181 | } |
||
| 182 | // compiling |
||
| 183 | if ((bool) $this->config->get('assets.compile.enabled')) { |
||
| 184 | $this->compile(); |
||
| 185 | } |
||
| 186 | // minifying |
||
| 187 | if ($minify) { |
||
| 188 | $this->minify(); |
||
| 189 | } |
||
| 190 | // optimizing |
||
| 191 | if ($optimize) { |
||
| 192 | $this->optimize = true; |
||
| 193 | } |
||
| 194 | } |
||
| 195 | |||
| 196 | /** |
||
| 197 | * Returns path. |
||
| 198 | * |
||
| 199 | * @throws RuntimeException |
||
| 200 | */ |
||
| 201 | public function __toString(): string |
||
| 202 | { |
||
| 203 | $cdn = 1; |
||
| 204 | if ($this->data['type'] == 'image' && !empty($this->data['url']) && $cdn == 1) { |
||
| 205 | if ($this->resized) { |
||
| 206 | return $this->data['url']; |
||
| 207 | } |
||
| 208 | |||
| 209 | return \sprintf('https://res.cloudinary.com/aligny/image/fetch/q_auto,f_auto/%s', $this->data['url']); |
||
| 210 | } |
||
| 211 | |||
| 212 | try { |
||
| 213 | $this->save(); |
||
| 214 | } catch (\Exception $e) { |
||
| 215 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 216 | } |
||
| 217 | |||
| 218 | if ($this->builder->getConfig()->get('canonicalurl')) { |
||
| 219 | return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]); |
||
| 220 | } |
||
| 221 | |||
| 222 | return $this->data['path']; |
||
| 223 | } |
||
| 224 | |||
| 225 | /** |
||
| 226 | * Fingerprints a file. |
||
| 227 | */ |
||
| 228 | public function fingerprint(): self |
||
| 229 | { |
||
| 230 | if ($this->fingerprinted) { |
||
| 231 | return $this; |
||
| 232 | } |
||
| 233 | |||
| 234 | $fingerprint = hash('md5', $this->data['content_source']); |
||
| 235 | $this->data['path'] = preg_replace( |
||
| 236 | '/\.'.$this->data['ext'].'$/m', |
||
| 237 | ".$fingerprint.".$this->data['ext'], |
||
| 238 | $this->data['path'] |
||
| 239 | ); |
||
| 240 | |||
| 241 | $this->fingerprinted = true; |
||
| 242 | |||
| 243 | return $this; |
||
| 244 | } |
||
| 245 | |||
| 246 | /** |
||
| 247 | * Compiles a SCSS. |
||
| 248 | * |
||
| 249 | * @throws RuntimeException |
||
| 250 | */ |
||
| 251 | public function compile(): self |
||
| 252 | { |
||
| 253 | if ($this->compiled) { |
||
| 254 | return $this; |
||
| 255 | } |
||
| 256 | |||
| 257 | if ($this->data['ext'] != 'scss') { |
||
| 258 | return $this; |
||
| 259 | } |
||
| 260 | |||
| 261 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 262 | $cacheKey = $cache->createKeyFromAsset($this, ['compiled']); |
||
| 263 | if (!$cache->has($cacheKey)) { |
||
| 264 | $scssPhp = new Compiler(); |
||
| 265 | $importDir = []; |
||
| 266 | $importDir[] = Util::joinPath($this->config->getStaticPath()); |
||
| 267 | $importDir[] = Util::joinPath($this->config->getAssetsPath()); |
||
| 268 | $scssDir = $this->config->get('assets.compile.import') ?? []; |
||
| 269 | $themes = $this->config->getTheme() ?? []; |
||
| 270 | foreach ($scssDir as $dir) { |
||
| 271 | $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir); |
||
| 272 | $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir); |
||
| 273 | $importDir[] = Util::joinPath(dirname($this->data['file']), $dir); |
||
| 274 | foreach ($themes as $theme) { |
||
| 275 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")); |
||
| 276 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir")); |
||
| 277 | } |
||
| 278 | } |
||
| 279 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 280 | // source map |
||
| 281 | if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) { |
||
| 282 | $importDir = []; |
||
| 283 | $assetDir = (string) $this->config->get('assets.dir'); |
||
| 284 | $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR.$assetDir.DIRECTORY_SEPARATOR); |
||
| 285 | $fileRelPath = substr($this->data['file'], $assetDirPos + 8); |
||
| 286 | $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath); |
||
| 287 | $importDir[] = dirname($filePath); |
||
| 288 | foreach ($scssDir as $dir) { |
||
| 289 | $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir); |
||
| 290 | } |
||
| 291 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 292 | $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE); |
||
| 293 | $scssPhp->setSourceMapOptions([ |
||
| 294 | 'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()), |
||
| 295 | 'sourceRoot' => '/', |
||
| 296 | ]); |
||
| 297 | } |
||
| 298 | // output style |
||
| 299 | $outputStyles = ['expanded', 'compressed']; |
||
| 300 | $outputStyle = strtolower((string) $this->config->get('assets.compile.style')); |
||
| 301 | if (!in_array($outputStyle, $outputStyles)) { |
||
| 302 | throw new RuntimeException(\sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle)); |
||
| 303 | } |
||
| 304 | $scssPhp->setOutputStyle($outputStyle); |
||
| 305 | // variables |
||
| 306 | $variables = $this->config->get('assets.compile.variables') ?? []; |
||
| 307 | if (!empty($variables)) { |
||
| 308 | $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables); |
||
| 309 | $scssPhp->replaceVariables($variables); |
||
| 310 | } |
||
| 311 | // update data |
||
| 312 | $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']); |
||
| 313 | $this->data['ext'] = 'css'; |
||
| 314 | $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss(); |
||
| 315 | $this->compiled = true; |
||
| 316 | $cache->set($cacheKey, $this->data); |
||
| 317 | } |
||
| 318 | $this->data = $cache->get($cacheKey); |
||
| 319 | |||
| 320 | return $this; |
||
| 321 | } |
||
| 322 | |||
| 323 | /** |
||
| 324 | * Minifying a CSS or a JS. |
||
| 325 | * |
||
| 326 | * @throws RuntimeException |
||
| 327 | */ |
||
| 328 | public function minify(): self |
||
| 329 | { |
||
| 330 | // disable minify to preserve inline source map |
||
| 331 | if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) { |
||
| 332 | return $this; |
||
| 333 | } |
||
| 334 | |||
| 335 | if ($this->minified) { |
||
| 336 | return $this; |
||
| 337 | } |
||
| 338 | |||
| 339 | if ($this->data['ext'] == 'scss') { |
||
| 340 | $this->compile(); |
||
| 341 | } |
||
| 342 | |||
| 343 | if ($this->data['ext'] != 'css' && $this->data['ext'] != 'js') { |
||
| 344 | return $this; |
||
| 345 | } |
||
| 346 | |||
| 347 | if (substr($this->data['path'], -8) == '.min.css' || substr($this->data['path'], -7) == '.min.js') { |
||
| 348 | $this->minified; |
||
| 349 | |||
| 350 | return $this; |
||
| 351 | } |
||
| 352 | |||
| 353 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 354 | $cacheKey = $cache->createKeyFromAsset($this, ['minified']); |
||
| 355 | if (!$cache->has($cacheKey)) { |
||
| 356 | switch ($this->data['ext']) { |
||
| 357 | case 'css': |
||
| 358 | $minifier = new Minify\CSS($this->data['content']); |
||
| 359 | break; |
||
| 360 | case 'js': |
||
| 361 | $minifier = new Minify\JS($this->data['content']); |
||
| 362 | break; |
||
| 363 | default: |
||
| 364 | throw new RuntimeException(\sprintf('Not able to minify "%s"', $this->data['path'])); |
||
| 365 | } |
||
| 366 | $this->data['path'] = preg_replace( |
||
| 367 | '/\.'.$this->data['ext'].'$/m', |
||
| 368 | '.min.'.$this->data['ext'], |
||
| 369 | $this->data['path'] |
||
| 370 | ); |
||
| 371 | $this->data['content'] = $minifier->minify(); |
||
| 372 | $this->minified = true; |
||
| 373 | $cache->set($cacheKey, $this->data); |
||
| 374 | } |
||
| 375 | $this->data = $cache->get($cacheKey); |
||
| 376 | |||
| 377 | return $this; |
||
| 378 | } |
||
| 379 | |||
| 380 | /** |
||
| 381 | * Optimizing an image. |
||
| 382 | */ |
||
| 383 | public function optimize(string $filepath): self |
||
| 384 | { |
||
| 385 | if ($this->data['type'] != 'image') { |
||
| 386 | return $this; |
||
| 387 | } |
||
| 388 | |||
| 389 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 390 | $tags = ['optimized']; |
||
| 391 | if ($this->data['width']) { |
||
| 392 | array_unshift($tags, "{$this->data['width']}x"); |
||
| 393 | } |
||
| 394 | $cacheKey = $cache->createKeyFromAsset($this, $tags); |
||
| 395 | if (!$cache->has($cacheKey)) { |
||
| 396 | $message = $this->data['path']; |
||
| 397 | $sizeBefore = filesize($filepath); |
||
| 398 | Optimizer::create($this->config->get('assets.images.quality') ?? 75)->optimize($filepath); |
||
| 399 | $sizeAfter = filesize($filepath); |
||
| 400 | if ($sizeAfter < $sizeBefore) { |
||
| 401 | $message = \sprintf( |
||
| 402 | '%s (%s Ko -> %s Ko)', |
||
| 403 | $message, |
||
| 404 | ceil($sizeBefore / 1000), |
||
| 405 | ceil($sizeAfter / 1000) |
||
| 406 | ); |
||
| 407 | } |
||
| 408 | $this->data['content'] = Util\File::fileGetContents($filepath); |
||
| 409 | $cache->set($cacheKey, $this->data); |
||
| 410 | $this->builder->getLogger()->debug(\sprintf('Asset "%s" optimized', $message)); |
||
| 411 | } |
||
| 412 | $this->data = $cache->get($cacheKey); |
||
| 413 | $this->optimized = true; |
||
| 414 | |||
| 415 | return $this; |
||
| 416 | } |
||
| 417 | |||
| 418 | /** |
||
| 419 | * Resizes an image with a new $width. |
||
| 420 | * |
||
| 421 | * @throws RuntimeException |
||
| 422 | */ |
||
| 423 | public function resize(int $width): self |
||
| 424 | { |
||
| 425 | if ($this->data['missing']) { |
||
| 426 | throw new RuntimeException(\sprintf('Not able to resize "%s": file not found', $this->data['path'])); |
||
| 427 | } |
||
| 428 | if ($this->data['type'] != 'image') { |
||
| 429 | throw new RuntimeException(\sprintf('Not able to resize "%s": not an image', $this->data['path'])); |
||
| 430 | } |
||
| 431 | |||
| 432 | $this->resized = true; |
||
| 433 | |||
| 434 | if ($width >= $this->getWidth()) { |
||
| 435 | return $this; |
||
| 436 | } |
||
| 437 | |||
| 438 | $assetResized = clone $this; |
||
| 439 | $assetResized->data['width'] = $width; |
||
| 440 | |||
| 441 | $cdn = 1; |
||
| 442 | if ($this->data['type'] == 'image' && !empty($this->data['url']) && $cdn == 1) { |
||
| 443 | $assetResized->data['url'] = \sprintf('https://res.cloudinary.com/aligny/image/fetch/c_limit,w_%s,q_auto,f_auto/%s', $width, $this->data['url']); |
||
| 444 | |||
| 445 | return $assetResized; |
||
| 446 | } |
||
| 447 | |||
| 448 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 449 | $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x"]); |
||
| 450 | if (!$cache->has($cacheKey)) { |
||
| 451 | if ($assetResized->data['type'] !== 'image') { |
||
| 452 | throw new RuntimeException(\sprintf('Not able to resize "%s"', $assetResized->data['path'])); |
||
| 453 | } |
||
| 454 | if (!extension_loaded('gd')) { |
||
| 455 | throw new RuntimeException('GD extension is required to use images resize.'); |
||
| 456 | } |
||
| 457 | |||
| 458 | try { |
||
| 459 | $img = ImageManager::make($assetResized->data['content_source']); |
||
| 460 | $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) { |
||
| 461 | $constraint->aspectRatio(); |
||
| 462 | $constraint->upsize(); |
||
| 463 | }); |
||
| 464 | } catch (\Exception $e) { |
||
| 465 | throw new RuntimeException(\sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage())); |
||
| 466 | } |
||
| 467 | $assetResized->data['path'] = '/'.Util::joinPath( |
||
| 468 | (string) $this->config->get('assets.target'), |
||
| 469 | (string) $this->config->get('assets.images.resize.dir'), |
||
| 470 | (string) $width, |
||
| 471 | $assetResized->data['path'] |
||
| 472 | ); |
||
| 473 | |||
| 474 | try { |
||
| 475 | $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $this->config->get('assets.images.quality')); |
||
| 476 | $assetResized->data['height'] = $assetResized->getHeight(); |
||
| 477 | } catch (\Exception $e) { |
||
| 478 | throw new RuntimeException(\sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage())); |
||
| 479 | } |
||
| 480 | |||
| 481 | $cache->set($cacheKey, $assetResized->data); |
||
| 482 | } |
||
| 483 | $assetResized->data = $cache->get($cacheKey); |
||
| 484 | |||
| 485 | return $assetResized; |
||
| 486 | } |
||
| 487 | |||
| 488 | /** |
||
| 489 | * Returns the data URL of an image. |
||
| 490 | * |
||
| 491 | * @throws RuntimeException |
||
| 492 | */ |
||
| 493 | public function dataurl(): string |
||
| 494 | { |
||
| 495 | if ($this->data['type'] !== 'image') { |
||
| 496 | throw new RuntimeException(\sprintf('Can\'t get data URL of "%s"', $this->data['path'])); |
||
| 497 | } |
||
| 498 | |||
| 499 | return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality')); |
||
| 500 | } |
||
| 501 | |||
| 502 | /** |
||
| 503 | * Implements \ArrayAccess. |
||
| 504 | */ |
||
| 505 | #[\ReturnTypeWillChange] |
||
| 506 | public function offsetSet($offset, $value): void |
||
| 507 | { |
||
| 508 | if (!is_null($offset)) { |
||
| 509 | $this->data[$offset] = $value; |
||
| 510 | } |
||
| 511 | } |
||
| 512 | |||
| 513 | /** |
||
| 514 | * Implements \ArrayAccess. |
||
| 515 | */ |
||
| 516 | #[\ReturnTypeWillChange] |
||
| 517 | public function offsetExists($offset): bool |
||
| 518 | { |
||
| 519 | return isset($this->data[$offset]); |
||
| 520 | } |
||
| 521 | |||
| 522 | /** |
||
| 523 | * Implements \ArrayAccess. |
||
| 524 | */ |
||
| 525 | #[\ReturnTypeWillChange] |
||
| 526 | public function offsetUnset($offset): void |
||
| 527 | { |
||
| 528 | unset($this->data[$offset]); |
||
| 529 | } |
||
| 530 | |||
| 531 | /** |
||
| 532 | * Implements \ArrayAccess. |
||
| 533 | */ |
||
| 534 | #[\ReturnTypeWillChange] |
||
| 535 | public function offsetGet($offset) |
||
| 536 | { |
||
| 537 | return isset($this->data[$offset]) ? $this->data[$offset] : null; |
||
| 538 | } |
||
| 539 | |||
| 540 | /** |
||
| 541 | * Hashing content of an asset with the specified algo, sha384 by default. |
||
| 542 | * Used for SRI (Subresource Integrity). |
||
| 543 | * |
||
| 544 | * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity |
||
| 545 | */ |
||
| 546 | public function getIntegrity(string $algo = 'sha384'): string |
||
| 547 | { |
||
| 548 | return \sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true))); |
||
| 549 | } |
||
| 550 | |||
| 551 | /** |
||
| 552 | * Returns the width of an image/SVG. |
||
| 553 | * |
||
| 554 | * @throws RuntimeException |
||
| 555 | */ |
||
| 556 | public function getWidth(): int |
||
| 557 | { |
||
| 558 | if ($this->data['type'] != 'image') { |
||
| 559 | return 0; |
||
| 560 | } |
||
| 561 | if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) { |
||
| 562 | return (int) $svg->width; |
||
| 563 | } |
||
| 564 | if (false === $size = $this->getImageSize()) { |
||
| 565 | throw new RuntimeException(\sprintf('Not able to get width of "%s"', $this->data['path'])); |
||
| 566 | } |
||
| 567 | |||
| 568 | return $size[0]; |
||
| 569 | } |
||
| 570 | |||
| 571 | /** |
||
| 572 | * Returns the height of an image/SVG. |
||
| 573 | * |
||
| 574 | * @throws RuntimeException |
||
| 575 | */ |
||
| 576 | public function getHeight(): int |
||
| 577 | { |
||
| 578 | if ($this->data['type'] != 'image') { |
||
| 579 | return 0; |
||
| 580 | } |
||
| 581 | if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) { |
||
| 582 | return (int) $svg->height; |
||
| 583 | } |
||
| 584 | if (false === $size = $this->getImageSize()) { |
||
| 585 | throw new RuntimeException(\sprintf('Not able to get height of "%s"', $this->data['path'])); |
||
| 586 | } |
||
| 587 | |||
| 588 | return $size[1]; |
||
| 589 | } |
||
| 590 | |||
| 591 | /** |
||
| 592 | * Returns MP3 file infos. |
||
| 593 | * |
||
| 594 | * @see https://github.com/wapmorgan/Mp3Info |
||
| 595 | */ |
||
| 596 | public function getAudio(): Mp3Info |
||
| 597 | { |
||
| 598 | if ($this->data['type'] !== 'audio') { |
||
| 599 | throw new RuntimeException(\sprintf('Not able to get audio infos of "%s"', $this->data['path'])); |
||
| 600 | } |
||
| 601 | |||
| 602 | return new Mp3Info($this->data['file']); |
||
| 603 | } |
||
| 604 | |||
| 605 | /** |
||
| 606 | * Saves file. |
||
| 607 | * Note: a file from `static/` with the same name will NOT be overridden. |
||
| 608 | * |
||
| 609 | * @throws RuntimeException |
||
| 610 | */ |
||
| 611 | public function save(): void |
||
| 612 | { |
||
| 613 | $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']); |
||
| 614 | if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) { |
||
| 615 | try { |
||
| 616 | Util\File::getFS()->dumpFile($filepath, $this->data['content']); |
||
| 617 | $this->builder->getLogger()->debug(\sprintf('Asset "%s" saved', $this->data['path'])); |
||
| 618 | if ($this->optimize) { |
||
| 619 | $this->optimize($filepath); |
||
| 620 | } |
||
| 621 | } catch (\Symfony\Component\Filesystem\Exception\IOException $e) { |
||
| 622 | if (!$this->ignore_missing) { |
||
| 623 | throw new RuntimeException(\sprintf('Can\'t save asset "%s".', $filepath)); |
||
| 624 | } |
||
| 625 | } |
||
| 626 | } |
||
| 627 | } |
||
| 628 | |||
| 629 | /** |
||
| 630 | * Load file data. |
||
| 631 | * |
||
| 632 | * @throws RuntimeException |
||
| 633 | */ |
||
| 634 | private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array |
||
| 683 | } |
||
| 684 | |||
| 685 | /** |
||
| 686 | * Try to find the file: |
||
| 687 | * 1. remote (if $path is a valid URL) |
||
| 688 | * 2. in static/ |
||
| 689 | * 3. in themes/<theme>/static/ |
||
| 690 | * Returns local file path or false if file don't exists. |
||
| 691 | * |
||
| 692 | * @throws RuntimeException |
||
| 693 | * |
||
| 694 | * @return string|false |
||
| 695 | */ |
||
| 696 | private function findFile(string $path, ?string $remote_fallback = null) |
||
| 697 | { |
||
| 698 | // in case of remote file: save it and returns cached file path |
||
| 699 | if (Util\Url::isUrl($path)) { |
||
| 700 | $url = $path; |
||
| 701 | $relativePath = Page::slugify(\sprintf('%s%s-%s', parse_url($url, PHP_URL_HOST), parse_url($url, PHP_URL_PATH), parse_url($url, PHP_URL_QUERY))); |
||
| 702 | $filePath = Util::joinFile($this->config->getCacheAssetsRemotePath(), $relativePath); |
||
| 703 | if (!file_exists($filePath)) { |
||
| 704 | if (!Util\Url::isRemoteFileExists($url)) { |
||
| 705 | // is there a fallback in assets/ |
||
| 706 | if ($remote_fallback) { |
||
| 707 | $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback); |
||
| 708 | if (Util\File::getFS()->exists($filePath)) { |
||
| 709 | return $filePath; |
||
| 710 | } |
||
| 711 | } |
||
| 712 | |||
| 713 | return false; |
||
| 714 | } |
||
| 715 | if (false === $content = Util\File::fileGetContents($url, true)) { |
||
| 716 | return false; |
||
| 717 | } |
||
| 718 | if (strlen($content) <= 1) { |
||
| 719 | throw new RuntimeException(\sprintf('Asset at "%s" is empty.', $url)); |
||
| 720 | } |
||
| 721 | Util\File::getFS()->dumpFile($filePath, $content); |
||
| 722 | } |
||
| 723 | |||
| 724 | return $filePath; |
||
| 725 | } |
||
| 726 | |||
| 727 | // checks in assets/ |
||
| 728 | $filePath = Util::joinFile($this->config->getAssetsPath(), $path); |
||
| 729 | if (Util\File::getFS()->exists($filePath)) { |
||
| 730 | return $filePath; |
||
| 731 | } |
||
| 732 | |||
| 733 | // checks in each themes/<theme>/assets/ |
||
| 734 | foreach ($this->config->getTheme() as $theme) { |
||
| 735 | $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path); |
||
| 736 | if (Util\File::getFS()->exists($filePath)) { |
||
| 737 | return $filePath; |
||
| 738 | } |
||
| 739 | } |
||
| 740 | |||
| 741 | // checks in static/ |
||
| 742 | $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path); |
||
| 743 | if (Util\File::getFS()->exists($filePath)) { |
||
| 744 | return $filePath; |
||
| 745 | } |
||
| 746 | |||
| 747 | // checks in each themes/<theme>/static/ |
||
| 748 | foreach ($this->config->getTheme() as $theme) { |
||
| 749 | $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path); |
||
| 750 | if (Util\File::getFS()->exists($filePath)) { |
||
| 751 | return $filePath; |
||
| 752 | } |
||
| 753 | } |
||
| 754 | |||
| 755 | return false; |
||
| 756 | } |
||
| 757 | |||
| 758 | /** |
||
| 759 | * Returns image size informations. |
||
| 760 | * |
||
| 761 | * @see https://www.php.net/manual/function.getimagesize.php |
||
| 762 | * |
||
| 763 | * @return array|false |
||
| 764 | */ |
||
| 765 | private function getImageSize() |
||
| 766 | { |
||
| 767 | if (!$this->data['type'] == 'image') { |
||
| 768 | return false; |
||
| 769 | } |
||
| 770 | |||
| 771 | try { |
||
| 772 | if (false === $size = getimagesizefromstring($this->data['content'])) { |
||
| 773 | return false; |
||
| 774 | } |
||
| 775 | } catch (\Exception $e) { |
||
| 776 | throw new RuntimeException(\sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage())); |
||
| 777 | } |
||
| 778 | |||
| 779 | return $size; |
||
| 780 | } |
||
| 781 | |||
| 782 | /** |
||
| 783 | * Returns true if asset is a SVG. |
||
| 784 | */ |
||
| 785 | private function isSVG(): bool |
||
| 786 | { |
||
| 787 | return in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg'; |
||
| 788 | } |
||
| 789 | |||
| 790 | /** |
||
| 791 | * Returns SVG attributes. |
||
| 792 | * |
||
| 793 | * @return \SimpleXMLElement|false |
||
| 794 | */ |
||
| 795 | private function getSvgAttributes() |
||
| 796 | { |
||
| 797 | if (false === $xml = simplexml_load_string($this->data['content_source'])) { |
||
| 798 | return false; |
||
| 799 | } |
||
| 800 | |||
| 801 | return $xml->attributes(); |
||
| 802 | } |
||
| 803 | |||
| 804 | /** |
||
| 805 | * Replaces some characters by '_'. |
||
| 806 | */ |
||
| 807 | private function sanitize(string $string): string |
||
| 810 | } |
||
| 811 | } |
||
| 812 |