| Total Complexity | 145 |
| Total Lines | 879 |
| Duplicated Lines | 0 % |
| Changes | 14 | ||
| Bugs | 10 | Features | 1 |
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 | /** @var bool */ |
||
| 50 | protected $optimized = false; |
||
| 51 | |||
| 52 | /** @var bool */ |
||
| 53 | protected $ignore_missing = false; |
||
| 54 | |||
| 55 | /** |
||
| 56 | * Creates an Asset from a file path, an array of files path or an URL. |
||
| 57 | * |
||
| 58 | * @param Builder $builder |
||
| 59 | * @param string|array $paths |
||
| 60 | * @param array|null $options e.g.: ['fingerprint' => true, 'minify' => true, 'filename' => '', 'ignore_missing' => false] |
||
| 61 | * |
||
| 62 | * @throws RuntimeException |
||
| 63 | */ |
||
| 64 | public function __construct(Builder $builder, $paths, array $options = null) |
||
| 65 | { |
||
| 66 | $this->builder = $builder; |
||
| 67 | $this->config = $builder->getConfig(); |
||
| 68 | $paths = \is_array($paths) ? $paths : [$paths]; |
||
| 69 | array_walk($paths, function ($path) { |
||
| 70 | if (!\is_string($path)) { |
||
| 71 | throw new RuntimeException(sprintf('The path to an asset must be a string (%s given).', \gettype($path))); |
||
| 72 | } |
||
| 73 | if (empty($path)) { |
||
| 74 | throw new RuntimeException('The path to an asset can\'t be empty.'); |
||
| 75 | } |
||
| 76 | if (substr($path, 0, 2) == '..') { |
||
| 77 | 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)); |
||
| 78 | } |
||
| 79 | }); |
||
| 80 | $this->data = [ |
||
| 81 | 'file' => '', // absolute file path |
||
| 82 | 'files' => [], // array of files path (if bundle) |
||
| 83 | 'filename' => '', // filename |
||
| 84 | 'path_source' => '', // public path to the file, before transformations |
||
| 85 | 'path' => '', // public path to the file, after transformations |
||
| 86 | 'url' => null, // URL of a remote image |
||
| 87 | 'missing' => false, // if file not found, but missing ollowed 'missing' is true |
||
| 88 | 'ext' => '', // file extension |
||
| 89 | 'type' => '', // file type (e.g.: image, audio, video, etc.) |
||
| 90 | 'subtype' => '', // file media type (e.g.: image/png, audio/mp3, etc.) |
||
| 91 | 'size' => 0, // file size (in bytes) |
||
| 92 | 'content_source' => '', // file content, before transformations |
||
| 93 | 'content' => '', // file content, after transformations |
||
| 94 | 'width' => 0, // width (in pixels) in case of an image |
||
| 95 | 'height' => 0, // height (in pixels) in case of an image |
||
| 96 | 'exif' => [], // exif data |
||
| 97 | ]; |
||
| 98 | |||
| 99 | // handles options |
||
| 100 | $fingerprint = (bool) $this->config->get('assets.fingerprint.enabled'); |
||
| 101 | $minify = (bool) $this->config->get('assets.minify.enabled'); |
||
| 102 | $optimize = (bool) $this->config->get('assets.images.optimize.enabled'); |
||
| 103 | $filename = ''; |
||
| 104 | $ignore_missing = false; |
||
| 105 | $remote_fallback = null; |
||
| 106 | $force_slash = true; |
||
| 107 | extract(\is_array($options) ? $options : [], EXTR_IF_EXISTS); |
||
| 108 | $this->ignore_missing = $ignore_missing; |
||
| 109 | |||
| 110 | // fill data array with file(s) informations |
||
| 111 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 112 | $cacheKey = sprintf('%s__%s', implode('_', $paths), $this->builder->getVersion()); |
||
| 113 | if (!$cache->has($cacheKey)) { |
||
| 114 | $pathsCount = \count($paths); |
||
| 115 | $file = []; |
||
| 116 | for ($i = 0; $i < $pathsCount; $i++) { |
||
| 117 | // loads file(s) |
||
| 118 | $file[$i] = $this->loadFile($paths[$i], $ignore_missing, $remote_fallback, $force_slash); |
||
| 119 | // bundle: same type/ext only |
||
| 120 | if ($i > 0) { |
||
| 121 | if ($file[$i]['type'] != $file[$i - 1]['type']) { |
||
| 122 | throw new RuntimeException(sprintf('Asset bundle type error (%s != %s).', $file[$i]['type'], $file[$i - 1]['type'])); |
||
| 123 | } |
||
| 124 | if ($file[$i]['ext'] != $file[$i - 1]['ext']) { |
||
| 125 | throw new RuntimeException(sprintf('Asset bundle extension error (%s != %s).', $file[$i]['ext'], $file[$i - 1]['ext'])); |
||
| 126 | } |
||
| 127 | } |
||
| 128 | // missing allowed = empty path |
||
| 129 | if ($file[$i]['missing']) { |
||
| 130 | $this->data['missing'] = true; |
||
| 131 | $this->data['path'] = $file[$i]['path']; |
||
| 132 | |||
| 133 | continue; |
||
| 134 | } |
||
| 135 | // set data |
||
| 136 | $this->data['size'] += $file[$i]['size']; |
||
| 137 | $this->data['content_source'] .= $file[$i]['content']; |
||
| 138 | $this->data['content'] .= $file[$i]['content']; |
||
| 139 | if ($i == 0) { |
||
| 140 | $this->data['file'] = $file[$i]['filepath']; |
||
| 141 | $this->data['filename'] = $file[$i]['path']; |
||
| 142 | $this->data['path_source'] = $file[$i]['path']; |
||
| 143 | $this->data['path'] = $file[$i]['path']; |
||
| 144 | if (!empty($filename)) { /** @phpstan-ignore-line */ |
||
| 145 | $this->data['path'] = '/' . ltrim($filename, '/'); |
||
| 146 | } |
||
| 147 | $this->data['url'] = $file[$i]['url']; |
||
| 148 | $this->data['ext'] = $file[$i]['ext']; |
||
| 149 | $this->data['type'] = $file[$i]['type']; |
||
| 150 | $this->data['subtype'] = $file[$i]['subtype']; |
||
| 151 | if ($this->data['type'] == 'image') { |
||
| 152 | $this->data['width'] = $this->getWidth(); |
||
| 153 | $this->data['height'] = $this->getHeight(); |
||
| 154 | if ($this->data['subtype'] == 'jpeg') { |
||
| 155 | $this->data['exif'] = Util\File::readExif($file[$i]['filepath']); |
||
| 156 | } |
||
| 157 | } |
||
| 158 | } |
||
| 159 | // bundle files path |
||
| 160 | $this->data['files'][] = $file[$i]['filepath']; |
||
| 161 | } |
||
| 162 | // bundle: define path |
||
| 163 | if ($pathsCount > 1 && empty($filename)) { /** @phpstan-ignore-line */ |
||
| 164 | switch ($this->data['ext']) { |
||
| 165 | case 'scss': |
||
| 166 | case 'css': |
||
| 167 | $this->data['path'] = '/styles.' . $file[0]['ext']; |
||
| 168 | break; |
||
| 169 | case 'js': |
||
| 170 | $this->data['path'] = '/scripts.' . $file[0]['ext']; |
||
| 171 | break; |
||
| 172 | default: |
||
| 173 | throw new RuntimeException(sprintf('Asset bundle supports "%s" files only.', '.scss, .css and .js')); |
||
| 174 | } |
||
| 175 | } |
||
| 176 | $cache->set($cacheKey, $this->data); |
||
| 177 | } |
||
| 178 | $this->data = $cache->get($cacheKey); |
||
| 179 | |||
| 180 | // fingerprinting |
||
| 181 | if ($fingerprint) { |
||
| 182 | $this->fingerprint(); |
||
| 183 | } |
||
| 184 | // compiling (Sass files) |
||
| 185 | if ((bool) $this->config->get('assets.compile.enabled')) { |
||
| 186 | $this->compile(); |
||
| 187 | } |
||
| 188 | // minifying (CSS and JavScript files) |
||
| 189 | if ($minify) { |
||
| 190 | $this->minify(); |
||
| 191 | } |
||
| 192 | // optimizing (images files) |
||
| 193 | if ($optimize) { |
||
| 194 | $this->optimize = true; |
||
| 195 | } |
||
| 196 | } |
||
| 197 | |||
| 198 | /** |
||
| 199 | * Returns path. |
||
| 200 | * |
||
| 201 | * @throws RuntimeException |
||
| 202 | */ |
||
| 203 | public function __toString(): string |
||
| 204 | { |
||
| 205 | try { |
||
| 206 | $this->save(); |
||
| 207 | } catch (\Exception $e) { |
||
| 208 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 209 | } |
||
| 210 | |||
| 211 | if ($this->isImageInCdn()) { |
||
| 212 | return $this->buildImageCdnUrl(); |
||
| 213 | } |
||
| 214 | |||
| 215 | if ($this->builder->getConfig()->get('canonicalurl')) { |
||
| 216 | return (string) new Url($this->builder, $this->data['path'], ['canonical' => true]); |
||
| 217 | } |
||
| 218 | |||
| 219 | return $this->data['path']; |
||
| 220 | } |
||
| 221 | |||
| 222 | /** |
||
| 223 | * Fingerprints a file. |
||
| 224 | */ |
||
| 225 | public function fingerprint(): self |
||
| 226 | { |
||
| 227 | if ($this->fingerprinted) { |
||
| 228 | return $this; |
||
| 229 | } |
||
| 230 | |||
| 231 | $fingerprint = hash('md5', $this->data['content_source']); |
||
| 232 | $this->data['path'] = preg_replace( |
||
| 233 | '/\.' . $this->data['ext'] . '$/m', |
||
| 234 | ".$fingerprint." . $this->data['ext'], |
||
| 235 | $this->data['path'] |
||
| 236 | ); |
||
| 237 | |||
| 238 | $this->fingerprinted = true; |
||
| 239 | |||
| 240 | return $this; |
||
| 241 | } |
||
| 242 | |||
| 243 | /** |
||
| 244 | * Compiles a SCSS. |
||
| 245 | * |
||
| 246 | * @throws RuntimeException |
||
| 247 | */ |
||
| 248 | public function compile(): self |
||
| 249 | { |
||
| 250 | if ($this->compiled) { |
||
| 251 | return $this; |
||
| 252 | } |
||
| 253 | |||
| 254 | if ($this->data['ext'] != 'scss') { |
||
| 255 | return $this; |
||
| 256 | } |
||
| 257 | |||
| 258 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 259 | $cacheKey = $cache->createKeyFromAsset($this, ['compiled']); |
||
| 260 | if (!$cache->has($cacheKey)) { |
||
| 261 | $scssPhp = new Compiler(); |
||
| 262 | $importDir = []; |
||
| 263 | $importDir[] = Util::joinPath($this->config->getStaticPath()); |
||
| 264 | $importDir[] = Util::joinPath($this->config->getAssetsPath()); |
||
| 265 | $scssDir = $this->config->get('assets.compile.import') ?? []; |
||
| 266 | $themes = $this->config->getTheme() ?? []; |
||
| 267 | foreach ($scssDir as $dir) { |
||
| 268 | $importDir[] = Util::joinPath($this->config->getStaticPath(), $dir); |
||
| 269 | $importDir[] = Util::joinPath($this->config->getAssetsPath(), $dir); |
||
| 270 | $importDir[] = Util::joinPath(\dirname($this->data['file']), $dir); |
||
| 271 | foreach ($themes as $theme) { |
||
| 272 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "static/$dir")); |
||
| 273 | $importDir[] = Util::joinPath($this->config->getThemeDirPath($theme, "assets/$dir")); |
||
| 274 | } |
||
| 275 | } |
||
| 276 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 277 | // source map |
||
| 278 | if ($this->builder->isDebug() && (bool) $this->config->get('assets.compile.sourcemap')) { |
||
| 279 | $importDir = []; |
||
| 280 | $assetDir = (string) $this->config->get('assets.dir'); |
||
| 281 | $assetDirPos = strrpos($this->data['file'], DIRECTORY_SEPARATOR . $assetDir . DIRECTORY_SEPARATOR); |
||
| 282 | $fileRelPath = substr($this->data['file'], $assetDirPos + 8); |
||
| 283 | $filePath = Util::joinFile($this->config->getOutputPath(), $fileRelPath); |
||
| 284 | $importDir[] = \dirname($filePath); |
||
| 285 | foreach ($scssDir as $dir) { |
||
| 286 | $importDir[] = Util::joinFile($this->config->getOutputPath(), $dir); |
||
| 287 | } |
||
| 288 | $scssPhp->setImportPaths(array_unique($importDir)); |
||
| 289 | $scssPhp->setSourceMap(Compiler::SOURCE_MAP_INLINE); |
||
| 290 | $scssPhp->setSourceMapOptions([ |
||
| 291 | 'sourceMapBasepath' => Util::joinPath($this->config->getOutputPath()), |
||
| 292 | 'sourceRoot' => '/', |
||
| 293 | ]); |
||
| 294 | } |
||
| 295 | // output style |
||
| 296 | $outputStyles = ['expanded', 'compressed']; |
||
| 297 | $outputStyle = strtolower((string) $this->config->get('assets.compile.style')); |
||
| 298 | if (!\in_array($outputStyle, $outputStyles)) { |
||
| 299 | throw new RuntimeException(sprintf('Scss output style "%s" doesn\'t exists.', $outputStyle)); |
||
| 300 | } |
||
| 301 | $scssPhp->setOutputStyle($outputStyle); |
||
| 302 | // variables |
||
| 303 | $variables = $this->config->get('assets.compile.variables') ?? []; |
||
| 304 | if (!empty($variables)) { |
||
| 305 | $variables = array_map('ScssPhp\ScssPhp\ValueConverter::parseValue', $variables); |
||
| 306 | $scssPhp->replaceVariables($variables); |
||
| 307 | } |
||
| 308 | // update data |
||
| 309 | $this->data['path'] = preg_replace('/sass|scss/m', 'css', $this->data['path']); |
||
| 310 | $this->data['ext'] = 'css'; |
||
| 311 | $this->data['type'] = 'text'; |
||
| 312 | $this->data['subtype'] = 'text/css'; |
||
| 313 | $this->data['content'] = $scssPhp->compileString($this->data['content'])->getCss(); |
||
| 314 | $this->data['size'] = \strlen($this->data['content']); |
||
| 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->data['size'] = \strlen($this->data['content']); |
||
| 373 | $this->minified = true; |
||
| 374 | $cache->set($cacheKey, $this->data); |
||
| 375 | } |
||
| 376 | $this->data = $cache->get($cacheKey); |
||
| 377 | |||
| 378 | return $this; |
||
| 379 | } |
||
| 380 | |||
| 381 | /** |
||
| 382 | * Optimizing an image. |
||
| 383 | */ |
||
| 384 | public function optimize(string $filepath): self |
||
| 385 | { |
||
| 386 | if ($this->data['type'] != 'image') { |
||
| 387 | return $this; |
||
| 388 | } |
||
| 389 | |||
| 390 | $quality = $this->config->get('assets.images.quality') ?? 75; |
||
| 391 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 392 | $tags = ["q$quality", 'optimized']; |
||
| 393 | if ($this->data['width']) { |
||
| 394 | array_unshift($tags, "{$this->data['width']}x"); |
||
| 395 | } |
||
| 396 | $cacheKey = $cache->createKeyFromAsset($this, $tags); |
||
| 397 | if (!$cache->has($cacheKey)) { |
||
| 398 | $message = $this->data['path']; |
||
| 399 | $sizeBefore = filesize($filepath); |
||
| 400 | Optimizer::create($quality)->optimize($filepath); |
||
| 401 | $sizeAfter = filesize($filepath); |
||
| 402 | if ($sizeAfter < $sizeBefore) { |
||
| 403 | $message = sprintf( |
||
| 404 | '%s (%s Ko -> %s Ko)', |
||
| 405 | $message, |
||
| 406 | ceil($sizeBefore / 1000), |
||
| 407 | ceil($sizeAfter / 1000) |
||
| 408 | ); |
||
| 409 | } |
||
| 410 | $this->data['content'] = Util\File::fileGetContents($filepath); |
||
| 411 | $this->data['size'] = $sizeAfter; |
||
| 412 | $cache->set($cacheKey, $this->data); |
||
| 413 | $this->builder->getLogger()->debug(sprintf('Asset "%s" optimized', $message)); |
||
| 414 | } |
||
| 415 | $this->data = $cache->get($cacheKey); |
||
| 416 | $this->optimized = true; |
||
| 417 | |||
| 418 | return $this; |
||
| 419 | } |
||
| 420 | |||
| 421 | /** |
||
| 422 | * Resizes an image with a new $width. |
||
| 423 | * |
||
| 424 | * @throws RuntimeException |
||
| 425 | */ |
||
| 426 | public function resize(int $width): self |
||
| 427 | { |
||
| 428 | if ($this->data['missing']) { |
||
| 429 | throw new RuntimeException(sprintf('Not able to resize "%s": file not found', $this->data['path'])); |
||
| 430 | } |
||
| 431 | if ($this->data['type'] != 'image') { |
||
| 432 | throw new RuntimeException(sprintf('Not able to resize "%s": not an image', $this->data['path'])); |
||
| 433 | } |
||
| 434 | if ($width >= $this->data['width']) { |
||
| 435 | return $this; |
||
| 436 | } |
||
| 437 | |||
| 438 | $assetResized = clone $this; |
||
| 439 | $assetResized->data['width'] = $width; |
||
| 440 | |||
| 441 | if ($this->isImageInCdn()) { |
||
| 442 | return $assetResized; // returns the asset with the new width only: CDN do the rest of the job |
||
| 443 | } |
||
| 444 | |||
| 445 | $quality = $this->config->get('assets.images.quality'); |
||
| 446 | $cache = new Cache($this->builder, (string) $this->builder->getConfig()->get('cache.assets.dir')); |
||
| 447 | $cacheKey = $cache->createKeyFromAsset($assetResized, ["{$width}x", "q$quality"]); |
||
| 448 | if (!$cache->has($cacheKey)) { |
||
| 449 | if ($assetResized->data['type'] !== 'image') { |
||
| 450 | throw new RuntimeException(sprintf('Not able to resize "%s"', $assetResized->data['path'])); |
||
| 451 | } |
||
| 452 | if (!\extension_loaded('gd')) { |
||
| 453 | throw new RuntimeException('GD extension is required to use images resize.'); |
||
| 454 | } |
||
| 455 | |||
| 456 | try { |
||
| 457 | $img = ImageManager::make($assetResized->data['content_source'])->encode($assetResized->data['ext']); |
||
| 458 | $img->resize($width, null, function (\Intervention\Image\Constraint $constraint) { |
||
| 459 | $constraint->aspectRatio(); |
||
| 460 | $constraint->upsize(); |
||
| 461 | }); |
||
| 462 | } catch (\Exception $e) { |
||
| 463 | throw new RuntimeException(sprintf('Not able to resize image "%s": %s', $assetResized->data['path'], $e->getMessage())); |
||
| 464 | } |
||
| 465 | $assetResized->data['path'] = '/' . Util::joinPath( |
||
| 466 | (string) $this->config->get('assets.target'), |
||
| 467 | (string) $this->config->get('assets.images.resize.dir'), |
||
| 468 | (string) $width, |
||
| 469 | $assetResized->data['path'] |
||
| 470 | ); |
||
| 471 | |||
| 472 | try { |
||
| 473 | if ($assetResized->data['subtype'] == 'image/jpeg') { |
||
| 474 | $img->interlace(); |
||
| 475 | } |
||
| 476 | $assetResized->data['content'] = (string) $img->encode($assetResized->data['ext'], $quality); |
||
| 477 | $img->destroy(); |
||
| 478 | $assetResized->data['height'] = $assetResized->getHeight(); |
||
| 479 | $assetResized->data['size'] = \strlen($assetResized->data['content']); |
||
| 480 | } catch (\Exception $e) { |
||
| 481 | throw new RuntimeException(sprintf('Not able to encode image "%s": %s', $assetResized->data['path'], $e->getMessage())); |
||
| 482 | } |
||
| 483 | |||
| 484 | $cache->set($cacheKey, $assetResized->data); |
||
| 485 | } |
||
| 486 | $assetResized->data = $cache->get($cacheKey); |
||
| 487 | |||
| 488 | return $assetResized; |
||
| 489 | } |
||
| 490 | |||
| 491 | /** |
||
| 492 | * Converts an image asset to WebP format. |
||
| 493 | * |
||
| 494 | * @throws RuntimeException |
||
| 495 | */ |
||
| 496 | public function webp(?int $quality = null): self |
||
| 497 | { |
||
| 498 | if ($this->data['type'] !== 'image') { |
||
| 499 | throw new RuntimeException(sprintf('can\'t convert "%s" (%s) to WebP: it\'s not an image file.', $this->data['path'], $this->data['type'])); |
||
| 500 | } |
||
| 501 | |||
| 502 | if ($quality === null) { |
||
| 503 | $quality = (int) $this->config->get('assets.images.quality') ?? 75; |
||
| 504 | } |
||
| 505 | |||
| 506 | $assetWebp = clone $this; |
||
| 507 | $format = 'webp'; |
||
| 508 | $assetWebp['ext'] = $format; |
||
| 509 | |||
| 510 | if ($this->isImageInCdn()) { |
||
| 511 | return $assetWebp; // returns the asset with the new extension ('webp') only: CDN do the rest of the job |
||
| 512 | } |
||
| 513 | |||
| 514 | $img = ImageManager::make($assetWebp['content']); |
||
| 515 | $assetWebp['content'] = (string) $img->encode($format, $quality); |
||
| 516 | $img->destroy(); |
||
| 517 | $assetWebp['path'] = preg_replace('/\.' . $this->data['ext'] . '$/m', ".$format", $this->data['path']); |
||
| 518 | $assetWebp['subtype'] = "image/$format"; |
||
| 519 | $assetWebp['size'] = \strlen($assetWebp['content']); |
||
|
|
|||
| 520 | |||
| 521 | return $assetWebp; |
||
| 522 | } |
||
| 523 | |||
| 524 | /** |
||
| 525 | * Implements \ArrayAccess. |
||
| 526 | */ |
||
| 527 | #[\ReturnTypeWillChange] |
||
| 528 | public function offsetSet($offset, $value): void |
||
| 529 | { |
||
| 530 | if (!\is_null($offset)) { |
||
| 531 | $this->data[$offset] = $value; |
||
| 532 | } |
||
| 533 | } |
||
| 534 | |||
| 535 | /** |
||
| 536 | * Implements \ArrayAccess. |
||
| 537 | */ |
||
| 538 | #[\ReturnTypeWillChange] |
||
| 539 | public function offsetExists($offset): bool |
||
| 540 | { |
||
| 541 | return isset($this->data[$offset]); |
||
| 542 | } |
||
| 543 | |||
| 544 | /** |
||
| 545 | * Implements \ArrayAccess. |
||
| 546 | */ |
||
| 547 | #[\ReturnTypeWillChange] |
||
| 548 | public function offsetUnset($offset): void |
||
| 549 | { |
||
| 550 | unset($this->data[$offset]); |
||
| 551 | } |
||
| 552 | |||
| 553 | /** |
||
| 554 | * Implements \ArrayAccess. |
||
| 555 | */ |
||
| 556 | #[\ReturnTypeWillChange] |
||
| 557 | public function offsetGet($offset) |
||
| 558 | { |
||
| 559 | return isset($this->data[$offset]) ? $this->data[$offset] : null; |
||
| 560 | } |
||
| 561 | |||
| 562 | /** |
||
| 563 | * Hashing content of an asset with the specified algo, sha384 by default. |
||
| 564 | * Used for SRI (Subresource Integrity). |
||
| 565 | * |
||
| 566 | * @see https://developer.mozilla.org/fr/docs/Web/Security/Subresource_Integrity |
||
| 567 | */ |
||
| 568 | public function getIntegrity(string $algo = 'sha384'): string |
||
| 569 | { |
||
| 570 | return sprintf('%s-%s', $algo, base64_encode(hash($algo, $this->data['content'], true))); |
||
| 571 | } |
||
| 572 | |||
| 573 | /** |
||
| 574 | * Returns MP3 file infos. |
||
| 575 | * |
||
| 576 | * @see https://github.com/wapmorgan/Mp3Info |
||
| 577 | */ |
||
| 578 | public function getAudio(): Mp3Info |
||
| 585 | } |
||
| 586 | |||
| 587 | /** |
||
| 588 | * Returns MP4 file infos. |
||
| 589 | * |
||
| 590 | * @see https://github.com/clwu88/php-read-mp4info |
||
| 591 | */ |
||
| 592 | public function getVideo(): array |
||
| 593 | { |
||
| 594 | if ($this->data['type'] !== 'video') { |
||
| 595 | throw new RuntimeException(sprintf('Not able to get video infos of "%s"', $this->data['path'])); |
||
| 596 | } |
||
| 597 | |||
| 598 | return \Clwu\Mp4::getInfo($this->data['file']); |
||
| 599 | } |
||
| 600 | |||
| 601 | /** |
||
| 602 | * Returns the data URL (encoded in Base64). |
||
| 603 | * |
||
| 604 | * @throws RuntimeException |
||
| 605 | */ |
||
| 606 | public function dataurl(): string |
||
| 607 | { |
||
| 608 | if ($this->data['type'] == 'image' && !$this->isSVG()) { |
||
| 609 | return (string) ImageManager::make($this->data['content'])->encode('data-url', $this->config->get('assets.images.quality')); |
||
| 610 | } |
||
| 611 | |||
| 612 | return sprintf("data:%s;base64,%s", $this->data['subtype'], base64_encode($this->data['content'])); |
||
| 613 | } |
||
| 614 | |||
| 615 | /** |
||
| 616 | * Saves file. |
||
| 617 | * Note: a file from `static/` with the same name will NOT be overridden. |
||
| 618 | * |
||
| 619 | * @throws RuntimeException |
||
| 620 | */ |
||
| 621 | public function save(): void |
||
| 622 | { |
||
| 623 | $filepath = Util::joinFile($this->config->getOutputPath(), $this->data['path']); |
||
| 624 | if (!$this->builder->getBuildOptions()['dry-run'] && !Util\File::getFS()->exists($filepath)) { |
||
| 625 | try { |
||
| 626 | Util\File::getFS()->dumpFile($filepath, $this->data['content']); |
||
| 627 | $this->builder->getLogger()->debug(sprintf('Asset "%s" saved', $filepath)); |
||
| 628 | if ($this->optimize) { |
||
| 629 | $this->optimize($filepath); |
||
| 630 | } |
||
| 631 | } catch (\Symfony\Component\Filesystem\Exception\IOException $e) { |
||
| 632 | if (!$this->ignore_missing) { |
||
| 633 | throw new RuntimeException(sprintf('Can\'t save asset "%s"', $filepath)); |
||
| 634 | } |
||
| 635 | } |
||
| 636 | } |
||
| 637 | } |
||
| 638 | |||
| 639 | /** |
||
| 640 | * Is Asset is an image in CDN. |
||
| 641 | * |
||
| 642 | * @return boolean |
||
| 643 | */ |
||
| 644 | public function isImageInCdn() |
||
| 645 | { |
||
| 646 | if ($this->data['type'] != 'image' || (bool) $this->config->get('assets.images.cdn.enabled') !== true || ($this->isSVG() && (bool) $this->config->get('assets.images.cdn.svg') !== true)) { |
||
| 647 | return false; |
||
| 648 | } |
||
| 649 | // remote image? |
||
| 650 | if ($this->data['url'] !== null && (bool) $this->config->get('assets.images.cdn.remote') !== true) { |
||
| 651 | return false; |
||
| 652 | } |
||
| 653 | |||
| 654 | return true; |
||
| 655 | } |
||
| 656 | |||
| 657 | /** |
||
| 658 | * Load file data. |
||
| 659 | * |
||
| 660 | * @throws RuntimeException |
||
| 661 | */ |
||
| 662 | private function loadFile(string $path, bool $ignore_missing = false, ?string $remote_fallback = null, bool $force_slash = true): array |
||
| 702 | } |
||
| 703 | |||
| 704 | /** |
||
| 705 | * Try to find the file: |
||
| 706 | * 1. remote (if $path is a valid URL) |
||
| 707 | * 2. in static/ |
||
| 708 | * 3. in themes/<theme>/static/ |
||
| 709 | * Returns local file path or false if file don't exists. |
||
| 710 | * |
||
| 711 | * @throws RuntimeException |
||
| 712 | * |
||
| 713 | * @return string|false |
||
| 714 | */ |
||
| 715 | private function findFile(string $path, ?string $remote_fallback = null) |
||
| 716 | { |
||
| 717 | // in case of remote file: save it and returns cached file path |
||
| 718 | if (Util\Url::isUrl($path)) { |
||
| 719 | $url = $path; |
||
| 720 | $urlHost = parse_url($path, PHP_URL_HOST); |
||
| 721 | $urlPath = parse_url($path, PHP_URL_PATH); |
||
| 722 | $urlQuery = parse_url($path, PHP_URL_QUERY); |
||
| 723 | $extension = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION); |
||
| 724 | // Google Fonts hack |
||
| 725 | if (Util\Str::endsWith($urlPath, '/css') || Util\Str::endsWith($urlPath, '/css2')) { |
||
| 726 | $extension = 'css'; |
||
| 727 | } |
||
| 728 | $relativePath = Page::slugify(sprintf( |
||
| 729 | '%s%s%s%s', |
||
| 730 | $urlHost, |
||
| 731 | $this->sanitize($urlPath), |
||
| 732 | $urlQuery ? "-$urlQuery" : '', |
||
| 733 | $urlQuery && $extension ? ".$extension" : '' |
||
| 734 | )); |
||
| 735 | $filePath = Util::joinFile($this->config->getCacheAssetsRemotePath(), $relativePath); |
||
| 736 | if (!file_exists($filePath)) { |
||
| 737 | if (!Util\Url::isRemoteFileExists($url)) { |
||
| 738 | // is there a fallback in assets/ |
||
| 739 | if ($remote_fallback) { |
||
| 740 | $filePath = Util::joinFile($this->config->getAssetsPath(), $remote_fallback); |
||
| 741 | if (Util\File::getFS()->exists($filePath)) { |
||
| 742 | return $filePath; |
||
| 743 | } |
||
| 744 | } |
||
| 745 | |||
| 746 | return false; |
||
| 747 | } |
||
| 748 | if (false === $content = Util\File::fileGetContents($url, true)) { |
||
| 749 | return false; |
||
| 750 | } |
||
| 751 | if (\strlen($content) <= 1) { |
||
| 752 | throw new RuntimeException(sprintf('Asset at "%s" is empty', $url)); |
||
| 753 | } |
||
| 754 | Util\File::getFS()->dumpFile($filePath, $content); |
||
| 755 | } |
||
| 756 | |||
| 757 | return $filePath; |
||
| 758 | } |
||
| 759 | |||
| 760 | // checks in assets/ |
||
| 761 | $filePath = Util::joinFile($this->config->getAssetsPath(), $path); |
||
| 762 | if (Util\File::getFS()->exists($filePath)) { |
||
| 763 | return $filePath; |
||
| 764 | } |
||
| 765 | |||
| 766 | // checks in each themes/<theme>/assets/ |
||
| 767 | foreach ($this->config->getTheme() as $theme) { |
||
| 768 | $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'assets'), $path); |
||
| 769 | if (Util\File::getFS()->exists($filePath)) { |
||
| 770 | return $filePath; |
||
| 771 | } |
||
| 772 | } |
||
| 773 | |||
| 774 | // checks in static/ |
||
| 775 | $filePath = Util::joinFile($this->config->getStaticTargetPath(), $path); |
||
| 776 | if (Util\File::getFS()->exists($filePath)) { |
||
| 777 | return $filePath; |
||
| 778 | } |
||
| 779 | |||
| 780 | // checks in each themes/<theme>/static/ |
||
| 781 | foreach ($this->config->getTheme() as $theme) { |
||
| 782 | $filePath = Util::joinFile($this->config->getThemeDirPath($theme, 'static'), $path); |
||
| 783 | if (Util\File::getFS()->exists($filePath)) { |
||
| 784 | return $filePath; |
||
| 785 | } |
||
| 786 | } |
||
| 787 | |||
| 788 | return false; |
||
| 789 | } |
||
| 790 | |||
| 791 | /** |
||
| 792 | * Returns the width of an image/SVG. |
||
| 793 | * |
||
| 794 | * @throws RuntimeException |
||
| 795 | */ |
||
| 796 | private function getWidth(): int |
||
| 797 | { |
||
| 798 | if ($this->data['type'] != 'image') { |
||
| 799 | return 0; |
||
| 800 | } |
||
| 801 | if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) { |
||
| 802 | return (int) $svg->width; |
||
| 803 | } |
||
| 804 | if (false === $size = $this->getImageSize()) { |
||
| 805 | throw new RuntimeException(sprintf('Not able to get width of "%s"', $this->data['path'])); |
||
| 806 | } |
||
| 807 | |||
| 808 | return $size[0]; |
||
| 809 | } |
||
| 810 | |||
| 811 | /** |
||
| 812 | * Returns the height of an image/SVG. |
||
| 813 | * |
||
| 814 | * @throws RuntimeException |
||
| 815 | */ |
||
| 816 | private function getHeight(): int |
||
| 817 | { |
||
| 818 | if ($this->data['type'] != 'image') { |
||
| 819 | return 0; |
||
| 820 | } |
||
| 821 | if ($this->isSVG() && false !== $svg = $this->getSvgAttributes()) { |
||
| 822 | return (int) $svg->height; |
||
| 823 | } |
||
| 824 | if (false === $size = $this->getImageSize()) { |
||
| 825 | throw new RuntimeException(sprintf('Not able to get height of "%s"', $this->data['path'])); |
||
| 826 | } |
||
| 827 | |||
| 828 | return $size[1]; |
||
| 829 | } |
||
| 830 | |||
| 831 | /** |
||
| 832 | * Returns image size informations. |
||
| 833 | * |
||
| 834 | * @see https://www.php.net/manual/function.getimagesize.php |
||
| 835 | * |
||
| 836 | * @return array|false |
||
| 837 | */ |
||
| 838 | private function getImageSize() |
||
| 839 | { |
||
| 840 | if (!$this->data['type'] == 'image') { |
||
| 841 | return false; |
||
| 842 | } |
||
| 843 | |||
| 844 | try { |
||
| 845 | if (false === $size = getimagesizefromstring($this->data['content'])) { |
||
| 846 | return false; |
||
| 847 | } |
||
| 848 | } catch (\Exception $e) { |
||
| 849 | throw new RuntimeException(sprintf('Handling asset "%s" failed: "%s"', $this->data['path_source'], $e->getMessage())); |
||
| 850 | } |
||
| 851 | |||
| 852 | return $size; |
||
| 853 | } |
||
| 854 | |||
| 855 | /** |
||
| 856 | * Returns true if asset is a SVG. |
||
| 857 | */ |
||
| 858 | private function isSVG(): bool |
||
| 859 | { |
||
| 860 | return \in_array($this->data['subtype'], ['image/svg', 'image/svg+xml']) || $this->data['ext'] == 'svg'; |
||
| 861 | } |
||
| 862 | |||
| 863 | /** |
||
| 864 | * Returns SVG attributes. |
||
| 865 | * |
||
| 866 | * @return \SimpleXMLElement|false |
||
| 867 | */ |
||
| 868 | private function getSvgAttributes() |
||
| 869 | { |
||
| 870 | if (false === $xml = simplexml_load_string($this->data['content_source'])) { |
||
| 871 | return false; |
||
| 872 | } |
||
| 873 | |||
| 874 | return $xml->attributes(); |
||
| 875 | } |
||
| 876 | |||
| 877 | /** |
||
| 878 | * Replaces some characters by '_'. |
||
| 879 | */ |
||
| 880 | private function sanitize(string $string): string |
||
| 883 | } |
||
| 884 | |||
| 885 | /** |
||
| 886 | * Builds CDN image URL. |
||
| 887 | */ |
||
| 888 | private function buildImageCdnUrl(): string |
||
| 906 | ); |
||
| 907 | } |
||
| 908 | } |
||
| 909 |