| Total Complexity | 154 |
| Total Lines | 1052 |
| Duplicated Lines | 0 % |
| Changes | 16 | ||
| Bugs | 3 | Features | 1 |
Complex classes like Core 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 Core, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 47 | class Core extends SlugifyExtension |
||
| 48 | { |
||
| 49 | /** @var Builder */ |
||
| 50 | protected $builder; |
||
| 51 | |||
| 52 | /** @var Config */ |
||
| 53 | protected $config; |
||
| 54 | |||
| 55 | /** @var Slugify */ |
||
| 56 | private static $slugifier; |
||
| 57 | |||
| 58 | public function __construct(Builder $builder) |
||
| 68 | } |
||
| 69 | |||
| 70 | /** |
||
| 71 | * {@inheritdoc} |
||
| 72 | */ |
||
| 73 | public function getName(): string |
||
| 74 | { |
||
| 75 | return 'CoreExtension'; |
||
| 76 | } |
||
| 77 | |||
| 78 | /** |
||
| 79 | * {@inheritdoc} |
||
| 80 | */ |
||
| 81 | public function getFunctions() |
||
| 82 | { |
||
| 83 | return [ |
||
| 84 | new \Twig\TwigFunction('url', [$this, 'url'], ['needs_context' => true]), |
||
| 85 | // assets |
||
| 86 | new \Twig\TwigFunction('asset', [$this, 'asset']), |
||
| 87 | new \Twig\TwigFunction('html', [$this, 'html'], ['needs_context' => true]), |
||
| 88 | new \Twig\TwigFunction('integrity', [$this, 'integrity']), |
||
| 89 | new \Twig\TwigFunction('image_srcset', [$this, 'imageSrcset']), |
||
| 90 | new \Twig\TwigFunction('image_sizes', [$this, 'imageSizes']), |
||
| 91 | // content |
||
| 92 | new \Twig\TwigFunction('readtime', [$this, 'readtime']), |
||
| 93 | new \Twig\TwigFunction('hash', [$this, 'hash']), |
||
| 94 | // others |
||
| 95 | new \Twig\TwigFunction('getenv', [$this, 'getEnv']), |
||
| 96 | new \Twig\TwigFunction('d', [$this, 'varDump'], ['needs_context' => true, 'needs_environment' => true]), |
||
| 97 | // deprecated |
||
| 98 | new \Twig\TwigFunction( |
||
| 99 | 'minify', |
||
| 100 | [$this, 'minify'], |
||
| 101 | ['deprecation_info' => new DeprecatedCallableInfo('', '', 'minify filter')] |
||
| 102 | ), |
||
| 103 | new \Twig\TwigFunction( |
||
| 104 | 'toCSS', |
||
| 105 | [$this, 'toCss'], |
||
| 106 | ['deprecation_info' => new DeprecatedCallableInfo('', '', 'to_css filter')] |
||
| 107 | ), |
||
| 108 | ]; |
||
| 109 | } |
||
| 110 | |||
| 111 | /** |
||
| 112 | * {@inheritdoc} |
||
| 113 | */ |
||
| 114 | public function getFilters(): array |
||
| 164 | ] |
||
| 165 | ), |
||
| 166 | ]; |
||
| 167 | } |
||
| 168 | |||
| 169 | /** |
||
| 170 | * {@inheritdoc} |
||
| 171 | */ |
||
| 172 | public function getTests() |
||
| 173 | { |
||
| 174 | return [ |
||
| 175 | new \Twig\TwigTest('asset', [$this, 'isAsset']), |
||
| 176 | new \Twig\TwigTest('image_large', [$this, 'isImageLarge']), |
||
| 177 | new \Twig\TwigTest('image_square', [$this, 'isImageSquare']), |
||
| 178 | ]; |
||
| 179 | } |
||
| 180 | |||
| 181 | /** |
||
| 182 | * Filters by Section. |
||
| 183 | */ |
||
| 184 | public function filterBySection(PagesCollection $pages, string $section): CollectionInterface |
||
| 187 | } |
||
| 188 | |||
| 189 | /** |
||
| 190 | * Filters a pages collection by variable's name/value. |
||
| 191 | */ |
||
| 192 | public function filterBy(PagesCollection $pages, string $variable, string $value): CollectionInterface |
||
| 193 | { |
||
| 194 | $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) { |
||
| 195 | // is a dedicated getter exists? |
||
| 196 | $method = 'get' . ucfirst($variable); |
||
| 197 | if (method_exists($page, $method) && $page->$method() == $value) { |
||
| 198 | return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true; |
||
| 199 | } |
||
| 200 | // or a classic variable |
||
| 201 | if ($page->getVariable($variable) == $value) { |
||
| 202 | return $page->getType() == Type::PAGE->value && !$page->isVirtual() && true; |
||
| 203 | } |
||
| 204 | }); |
||
| 205 | |||
| 206 | return $filteredPages; |
||
| 207 | } |
||
| 208 | |||
| 209 | /** |
||
| 210 | * Sorts a collection by title. |
||
| 211 | */ |
||
| 212 | public function sortByTitle(\Traversable $collection): array |
||
| 213 | { |
||
| 214 | $sort = \SORT_ASC; |
||
| 215 | |||
| 216 | $collection = iterator_to_array($collection); |
||
| 217 | array_multisort(array_keys(/** @scrutinizer ignore-type */ $collection), $sort, \SORT_NATURAL | \SORT_FLAG_CASE, $collection); |
||
| 218 | |||
| 219 | return $collection; |
||
| 220 | } |
||
| 221 | |||
| 222 | /** |
||
| 223 | * Sorts a collection by weight. |
||
| 224 | * |
||
| 225 | * @param \Traversable|array $collection |
||
| 226 | */ |
||
| 227 | public function sortByWeight($collection): array |
||
| 228 | { |
||
| 229 | $callback = function ($a, $b) { |
||
| 230 | if (!isset($a['weight'])) { |
||
| 231 | $a['weight'] = 0; |
||
| 232 | } |
||
| 233 | if (!isset($b['weight'])) { |
||
| 234 | $a['weight'] = 0; |
||
| 235 | } |
||
| 236 | if ($a['weight'] == $b['weight']) { |
||
| 237 | return 0; |
||
| 238 | } |
||
| 239 | |||
| 240 | return $a['weight'] < $b['weight'] ? -1 : 1; |
||
| 241 | }; |
||
| 242 | |||
| 243 | if (!\is_array($collection)) { |
||
| 244 | $collection = iterator_to_array($collection); |
||
| 245 | } |
||
| 246 | usort(/** @scrutinizer ignore-type */ $collection, $callback); |
||
| 247 | |||
| 248 | return $collection; |
||
| 249 | } |
||
| 250 | |||
| 251 | /** |
||
| 252 | * Sorts by creation date (or 'updated' date): the most recent first. |
||
| 253 | */ |
||
| 254 | public function sortByDate(\Traversable $collection, string $variable = 'date', bool $descTitle = false): array |
||
| 273 | } |
||
| 274 | |||
| 275 | /** |
||
| 276 | * Creates an URL. |
||
| 277 | * |
||
| 278 | * $options[ |
||
| 279 | * 'canonical' => false, |
||
| 280 | * 'format' => 'html', |
||
| 281 | * 'language' => null, |
||
| 282 | * ]; |
||
| 283 | * |
||
| 284 | * @param array $context |
||
| 285 | * @param Page|Asset|string|null $value |
||
| 286 | * @param array|null $options |
||
| 287 | */ |
||
| 288 | public function url(array $context, $value = null, ?array $options = null): string |
||
| 289 | { |
||
| 290 | $optionsLang = []; |
||
| 291 | $optionsLang['language'] = (string) $context['site']['language']; |
||
| 292 | $options = array_merge($optionsLang, $options ?? []); |
||
| 293 | |||
| 294 | return (new Url($this->builder, $value, $options))->getUrl(); |
||
| 295 | } |
||
| 296 | |||
| 297 | /** |
||
| 298 | * Creates an Asset (CSS, JS, images, etc.) from a path or an array of paths. |
||
| 299 | * |
||
| 300 | * @param string|array $path File path or array of files path (relative from `assets/` or `static/` dir). |
||
| 301 | * @param array|null $options |
||
| 302 | * |
||
| 303 | * @return Asset |
||
| 304 | */ |
||
| 305 | public function asset($path, array|null $options = null): Asset |
||
| 306 | { |
||
| 307 | if (!\is_string($path) && !\is_array($path)) { |
||
| 308 | throw new RuntimeException(\sprintf('Argument of "%s()" must a string or an array.', \Cecil\Util::formatMethodName(__METHOD__))); |
||
| 309 | } |
||
| 310 | |||
| 311 | return new Asset($this->builder, $path, $options); |
||
| 312 | } |
||
| 313 | |||
| 314 | /** |
||
| 315 | * Compiles a SCSS asset. |
||
| 316 | * |
||
| 317 | * @param string|Asset $asset |
||
| 318 | * |
||
| 319 | * @return Asset |
||
| 320 | */ |
||
| 321 | public function toCss($asset): Asset |
||
| 322 | { |
||
| 323 | if (!$asset instanceof Asset) { |
||
| 324 | $asset = new Asset($this->builder, $asset); |
||
| 325 | } |
||
| 326 | |||
| 327 | return $asset->compile(); |
||
| 328 | } |
||
| 329 | |||
| 330 | /** |
||
| 331 | * Minifying an asset (CSS or JS). |
||
| 332 | * |
||
| 333 | * @param string|Asset $asset |
||
| 334 | * |
||
| 335 | * @return Asset |
||
| 336 | */ |
||
| 337 | public function minify($asset): Asset |
||
| 338 | { |
||
| 339 | if (!$asset instanceof Asset) { |
||
| 340 | $asset = new Asset($this->builder, $asset); |
||
| 341 | } |
||
| 342 | |||
| 343 | return $asset->minify(); |
||
| 344 | } |
||
| 345 | |||
| 346 | /** |
||
| 347 | * Fingerprinting an asset. |
||
| 348 | * |
||
| 349 | * @param string|Asset $asset |
||
| 350 | * |
||
| 351 | * @return Asset |
||
| 352 | */ |
||
| 353 | public function fingerprint($asset): Asset |
||
| 354 | { |
||
| 355 | if (!$asset instanceof Asset) { |
||
| 356 | $asset = new Asset($this->builder, $asset); |
||
| 357 | } |
||
| 358 | |||
| 359 | return $asset->fingerprint(); |
||
| 360 | } |
||
| 361 | |||
| 362 | /** |
||
| 363 | * Resizes an image. |
||
| 364 | * |
||
| 365 | * @param string|Asset $asset |
||
| 366 | * |
||
| 367 | * @return Asset |
||
| 368 | */ |
||
| 369 | public function resize($asset, int $size): Asset |
||
| 370 | { |
||
| 371 | if (!$asset instanceof Asset) { |
||
| 372 | $asset = new Asset($this->builder, $asset); |
||
| 373 | } |
||
| 374 | |||
| 375 | return $asset->resize($size); |
||
| 376 | } |
||
| 377 | |||
| 378 | /** |
||
| 379 | * Crops an image Asset to the given width and height, keeping the aspect ratio. |
||
| 380 | * |
||
| 381 | * @param string|Asset $asset |
||
| 382 | * |
||
| 383 | * @return Asset |
||
| 384 | */ |
||
| 385 | public function cover($asset, int $width, int $height): Asset |
||
| 386 | { |
||
| 387 | if (!$asset instanceof Asset) { |
||
| 388 | $asset = new Asset($this->builder, $asset); |
||
| 389 | } |
||
| 390 | |||
| 391 | return $asset->cover($width, $height); |
||
| 392 | } |
||
| 393 | |||
| 394 | /** |
||
| 395 | * Creates a maskable icon from an image asset. |
||
| 396 | * The maskable icon is used for Progressive Web Apps (PWAs). |
||
| 397 | * |
||
| 398 | * @param string|Asset $asset |
||
| 399 | * |
||
| 400 | * @return Asset |
||
| 401 | */ |
||
| 402 | public function maskable($asset, ?int $padding = null): Asset |
||
| 403 | { |
||
| 404 | if (!$asset instanceof Asset) { |
||
| 405 | $asset = new Asset($this->builder, $asset); |
||
| 406 | } |
||
| 407 | |||
| 408 | return $asset->maskable($padding); |
||
| 409 | } |
||
| 410 | |||
| 411 | /** |
||
| 412 | * Returns the data URL of an image. |
||
| 413 | * |
||
| 414 | * @param string|Asset $asset |
||
| 415 | * |
||
| 416 | * @return string |
||
| 417 | */ |
||
| 418 | public function dataurl($asset): string |
||
| 425 | } |
||
| 426 | |||
| 427 | /** |
||
| 428 | * Hashing an asset with algo (sha384 by default). |
||
| 429 | * |
||
| 430 | * @param string|Asset $asset |
||
| 431 | * @param string $algo |
||
| 432 | * |
||
| 433 | * @return string |
||
| 434 | */ |
||
| 435 | public function integrity($asset, string $algo = 'sha384'): string |
||
| 442 | } |
||
| 443 | |||
| 444 | /** |
||
| 445 | * Minifying a CSS string. |
||
| 446 | */ |
||
| 447 | public function minifyCss(?string $value): string |
||
| 464 | } |
||
| 465 | |||
| 466 | /** |
||
| 467 | * Minifying a JavaScript string. |
||
| 468 | */ |
||
| 469 | public function minifyJs(?string $value): string |
||
| 470 | { |
||
| 471 | $value = $value ?? ''; |
||
| 472 | |||
| 473 | if ($this->builder->isDebug()) { |
||
| 474 | return $value; |
||
| 475 | } |
||
| 476 | |||
| 477 | $cache = new Cache($this->builder, 'assets'); |
||
| 478 | $cacheKey = $cache->createKeyFromValue(null, $value); |
||
| 479 | if (!$cache->has($cacheKey)) { |
||
| 480 | $minifier = new Minify\JS($value); |
||
| 481 | $value = $minifier->minify(); |
||
| 482 | $cache->set($cacheKey, $value, $this->config->get('cache.assets.ttl')); |
||
| 483 | } |
||
| 484 | |||
| 485 | return $cache->get($cacheKey, $value); |
||
| 486 | } |
||
| 487 | |||
| 488 | /** |
||
| 489 | * Compiles a SCSS string. |
||
| 490 | * |
||
| 491 | * @throws RuntimeException |
||
| 492 | */ |
||
| 493 | public function scssToCss(?string $value): string |
||
| 517 | } |
||
| 518 | |||
| 519 | /** |
||
| 520 | * Creates the HTML element of an asset. |
||
| 521 | * |
||
| 522 | * @param array $context Twig context |
||
| 523 | * @param Asset|array<Asset,string> $assets Asset or array of assets and associated media query |
||
| 524 | * @param array $attributes HTML attributes |
||
| 525 | * @param array $options Options: |
||
| 526 | * [ |
||
| 527 | * 'preload' => false, |
||
| 528 | * 'responsive' => false, |
||
| 529 | * 'formats' => [], |
||
| 530 | * ]; |
||
| 531 | * |
||
| 532 | * @return string HTML element |
||
| 533 | * |
||
| 534 | * @throws RuntimeException |
||
| 535 | */ |
||
| 536 | public function html(array $context, Asset|array $assets, array $attributes = [], array $options = []): string |
||
| 537 | { |
||
| 538 | $htmlAttributes = ''; |
||
| 539 | $preload = false; |
||
| 540 | $responsive = $this->config->isEnabled('layouts.images.responsive'); |
||
| 541 | $formats = (array) $this->config->get('layouts.images.formats'); |
||
| 542 | extract($options, EXTR_IF_EXISTS); |
||
| 543 | |||
| 544 | // prepare HTML attributes |
||
| 545 | foreach ($attributes as $name => $value) { |
||
| 546 | $attribute = \sprintf(' %s="%s"', $name, $value); |
||
| 547 | if (!isset($value)) { |
||
| 548 | $attribute = \sprintf(' %s', $name); |
||
| 549 | } |
||
| 550 | $htmlAttributes .= $attribute; |
||
| 551 | } |
||
| 552 | |||
| 553 | if (!\is_array($assets)) { |
||
| 554 | $assets = [$assets => null]; |
||
| 555 | } |
||
| 556 | foreach ($assets as $asset => $media) { |
||
| 557 | if (!$asset instanceof Asset) { |
||
| 558 | $asset = new Asset($this->builder, $asset); |
||
| 559 | } |
||
| 560 | |||
| 561 | // media attribute |
||
| 562 | $htmlAttributes .= $media ? \sprintf(' media="%s"', $media) : ''; |
||
| 563 | |||
| 564 | // be sure Asset file is saved |
||
| 565 | $asset->save(); |
||
| 566 | |||
| 567 | // CSS or JavaScript |
||
| 568 | switch ($asset['ext']) { |
||
| 569 | case 'css': |
||
| 570 | if ($preload) { |
||
| 571 | return \sprintf( |
||
| 572 | '<link href="%s" rel="preload" as="style" onload="this.onload=null;this.rel=\'stylesheet\'"%s><noscript><link rel="stylesheet" href="%1$s"%2$s></noscript>', |
||
| 573 | $this->url($context, $asset, $options), |
||
| 574 | $htmlAttributes |
||
| 575 | ); |
||
| 576 | } |
||
| 577 | |||
| 578 | return \sprintf('<link rel="stylesheet" href="%s"%s>', $this->url($context, $asset, $options), $htmlAttributes); |
||
| 579 | case 'js': |
||
| 580 | return \sprintf('<script src="%s"%s></script>', $this->url($context, $asset, $options), $htmlAttributes); |
||
| 581 | } |
||
| 582 | } |
||
| 583 | |||
| 584 | |||
| 585 | |||
| 586 | |||
| 587 | // image |
||
| 588 | if ($asset['type'] == 'image') { |
||
| 589 | // if responsive is enabled |
||
| 590 | $sizes = ''; |
||
| 591 | if ( |
||
| 592 | $responsive && $srcset = Image::buildHtmlSrcset( |
||
| 593 | $asset, |
||
| 594 | $this->config->getAssetsImagesWidths() |
||
| 595 | ) |
||
| 596 | ) { |
||
| 597 | $htmlAttributes .= \sprintf(' srcset="%s"', $srcset); |
||
| 598 | $sizes = Image::getHtmlSizes($attributes['class'] ?? '', $this->config->getAssetsImagesSizes()); |
||
| 599 | $htmlAttributes .= \sprintf(' sizes="%s"', $sizes); |
||
| 600 | if ($asset['width'] > max($this->config->getAssetsImagesWidths())) { |
||
| 601 | $asset = $asset->resize(max($this->config->getAssetsImagesWidths())); |
||
| 602 | } |
||
| 603 | } |
||
| 604 | |||
| 605 | // `<img>` element |
||
| 606 | $img = \sprintf( |
||
| 607 | '<img src="%s" width="' . ($asset['width'] ?: '') . '" height="' . ($asset['height'] ?: '') . '"%s>', |
||
| 608 | $this->url($context, $asset, $options), |
||
| 609 | $htmlAttributes |
||
| 610 | ); |
||
| 611 | |||
| 612 | // multiple formats (`<source>`)? |
||
| 613 | if (\count($formats) > 0) { |
||
| 614 | $source = ''; |
||
| 615 | foreach ($formats as $format) { |
||
| 616 | try { |
||
| 617 | $assetConverted = $asset->convert($format); |
||
| 618 | // if responsive is enabled |
||
| 619 | if ($responsive && $srcset = Image::buildHtmlSrcset($assetConverted, $this->config->getAssetsImagesWidths())) { |
||
| 620 | // `<source>` element |
||
| 621 | $source .= \sprintf( |
||
| 622 | "\n <source type=\"image/$format\" srcset=\"%s\" sizes=\"%s\">", |
||
| 623 | $srcset, |
||
| 624 | $sizes |
||
| 625 | ); |
||
| 626 | continue; |
||
| 627 | } |
||
| 628 | // `<source>` element |
||
| 629 | $source .= \sprintf("\n <source type=\"image/$format\" srcset=\"%s\">", $assetConverted); |
||
| 630 | } catch (\Exception $e) { |
||
| 631 | $this->builder->getLogger()->error($e->getMessage()); |
||
| 632 | continue; |
||
| 633 | } |
||
| 634 | } |
||
| 635 | // put `<source>` in `<picture>` |
||
| 636 | if (!empty($source)) { |
||
| 637 | return \sprintf("<picture>%s\n %s\n</picture>", $source, $img); |
||
| 638 | } |
||
| 639 | } |
||
| 640 | |||
| 641 | return $img; |
||
| 642 | } |
||
| 643 | |||
| 644 | throw new RuntimeException(\sprintf('%s is available for CSS, JavaScript and image files only.', '"html" filter')); |
||
| 645 | } |
||
| 646 | |||
| 647 | /** |
||
| 648 | * Builds the HTML img `srcset` (responsive) attribute of an image Asset. |
||
| 649 | * |
||
| 650 | * @throws RuntimeException |
||
| 651 | */ |
||
| 652 | public function imageSrcset(Asset $asset): string |
||
| 653 | { |
||
| 654 | return Image::buildHtmlSrcset($asset, $this->config->getAssetsImagesWidths(), true); |
||
| 655 | } |
||
| 656 | |||
| 657 | /** |
||
| 658 | * Returns the HTML img `sizes` attribute based on a CSS class name. |
||
| 659 | */ |
||
| 660 | public function imageSizes(string $class): string |
||
| 661 | { |
||
| 662 | return Image::getHtmlSizes($class, $this->config->getAssetsImagesSizes()); |
||
| 663 | } |
||
| 664 | |||
| 665 | /** |
||
| 666 | * Converts an image Asset to WebP format. |
||
| 667 | */ |
||
| 668 | public function webp(Asset $asset, ?int $quality = null): Asset |
||
| 669 | { |
||
| 670 | return $this->convert($asset, 'webp', $quality); |
||
| 671 | } |
||
| 672 | |||
| 673 | /** |
||
| 674 | * Converts an image Asset to AVIF format. |
||
| 675 | */ |
||
| 676 | public function avif(Asset $asset, ?int $quality = null): Asset |
||
| 677 | { |
||
| 678 | return $this->convert($asset, 'avif', $quality); |
||
| 679 | } |
||
| 680 | |||
| 681 | /** |
||
| 682 | * Converts an image Asset to the given format. |
||
| 683 | * |
||
| 684 | * @throws RuntimeException |
||
| 685 | */ |
||
| 686 | private function convert(Asset $asset, string $format, ?int $quality = null): Asset |
||
| 699 | } |
||
| 700 | } |
||
| 701 | |||
| 702 | /** |
||
| 703 | * Returns the content of an asset. |
||
| 704 | */ |
||
| 705 | public function inline(Asset $asset): string |
||
| 706 | { |
||
| 707 | return $asset['content']; |
||
| 708 | } |
||
| 709 | |||
| 710 | /** |
||
| 711 | * Reads $length first characters of a string and adds a suffix. |
||
| 712 | */ |
||
| 713 | public function excerpt(?string $string, int $length = 450, string $suffix = ' …'): string |
||
| 714 | { |
||
| 715 | $string = $string ?? ''; |
||
| 716 | |||
| 717 | $string = str_replace('</p>', '<br><br>', $string); |
||
| 718 | $string = trim(strip_tags($string, '<br>')); |
||
| 719 | if (mb_strlen($string) > $length) { |
||
| 720 | $string = mb_substr($string, 0, $length); |
||
| 721 | $string .= $suffix; |
||
| 722 | } |
||
| 723 | |||
| 724 | return $string; |
||
| 725 | } |
||
| 726 | |||
| 727 | /** |
||
| 728 | * Reads characters before or after '<!-- separator -->'. |
||
| 729 | * Options: |
||
| 730 | * - separator: string to use as separator (`excerpt|break` by default) |
||
| 731 | * - capture: part to capture, `before` or `after` the separator (`before` by default). |
||
| 732 | */ |
||
| 733 | public function excerptHtml(?string $string, array $options = []): string |
||
| 734 | { |
||
| 735 | $string = $string ?? ''; |
||
| 736 | |||
| 737 | $separator = (string) $this->config->get('pages.body.excerpt.separator'); |
||
| 738 | $capture = (string) $this->config->get('pages.body.excerpt.capture'); |
||
| 739 | extract($options, EXTR_IF_EXISTS); |
||
| 740 | |||
| 741 | // https://regex101.com/r/n9TWHF/1 |
||
| 742 | $pattern = '(.*)<!--[[:blank:]]?(' . $separator . ')[[:blank:]]?-->(.*)'; |
||
| 743 | preg_match('/' . $pattern . '/is', $string, $matches); |
||
| 744 | |||
| 745 | if (empty($matches)) { |
||
| 746 | return $string; |
||
| 747 | } |
||
| 748 | $result = trim($matches[1]); |
||
| 749 | if ($capture == 'after') { |
||
| 750 | $result = trim($matches[3]); |
||
| 751 | } |
||
| 752 | // removes footnotes and returns result |
||
| 753 | return preg_replace('/<sup[^>]*>[^u]*<\/sup>/', '', $result); |
||
| 754 | } |
||
| 755 | |||
| 756 | /** |
||
| 757 | * Converts a Markdown string to HTML. |
||
| 758 | * |
||
| 759 | * @throws RuntimeException |
||
| 760 | */ |
||
| 761 | public function markdownToHtml(?string $markdown): ?string |
||
| 762 | { |
||
| 763 | $markdown = $markdown ?? ''; |
||
| 764 | |||
| 765 | try { |
||
| 766 | $parsedown = new Parsedown($this->builder); |
||
| 767 | $html = $parsedown->text($markdown); |
||
| 768 | } catch (\Exception $e) { |
||
| 769 | throw new RuntimeException( |
||
| 770 | '"markdown_to_html" filter can not convert supplied Markdown.', |
||
| 771 | previous: $e |
||
| 772 | ); |
||
| 773 | } |
||
| 774 | |||
| 775 | return $html; |
||
| 776 | } |
||
| 777 | |||
| 778 | /** |
||
| 779 | * Extract table of content of a Markdown string, |
||
| 780 | * in the given format ("html" or "json", "html" by default). |
||
| 781 | * |
||
| 782 | * @throws RuntimeException |
||
| 783 | */ |
||
| 784 | public function markdownToToc(?string $markdown, $format = 'html', ?array $selectors = null, string $url = ''): ?string |
||
| 785 | { |
||
| 786 | $markdown = $markdown ?? ''; |
||
| 787 | $selectors = $selectors ?? (array) $this->config->get('pages.body.toc'); |
||
| 788 | |||
| 789 | try { |
||
| 790 | $parsedown = new Parsedown($this->builder, ['selectors' => $selectors, 'url' => $url]); |
||
| 791 | $parsedown->body($markdown); |
||
| 792 | $return = $parsedown->contentsList($format); |
||
| 793 | } catch (\Exception) { |
||
| 794 | throw new RuntimeException('"toc" filter can not convert supplied Markdown.'); |
||
| 795 | } |
||
| 796 | |||
| 797 | return $return; |
||
| 798 | } |
||
| 799 | |||
| 800 | /** |
||
| 801 | * Converts a JSON string to an array. |
||
| 802 | * |
||
| 803 | * @throws RuntimeException |
||
| 804 | */ |
||
| 805 | public function jsonDecode(?string $json): ?array |
||
| 806 | { |
||
| 807 | $json = $json ?? ''; |
||
| 808 | |||
| 809 | try { |
||
| 810 | $array = json_decode($json, true); |
||
| 811 | if ($array === null && json_last_error() !== JSON_ERROR_NONE) { |
||
| 812 | throw new \Exception('JSON error.'); |
||
| 813 | } |
||
| 814 | } catch (\Exception) { |
||
| 815 | throw new RuntimeException('"json_decode" filter can not parse supplied JSON.'); |
||
| 816 | } |
||
| 817 | |||
| 818 | return $array; |
||
| 819 | } |
||
| 820 | |||
| 821 | /** |
||
| 822 | * Converts a YAML string to an array. |
||
| 823 | * |
||
| 824 | * @throws RuntimeException |
||
| 825 | */ |
||
| 826 | public function yamlParse(?string $yaml): ?array |
||
| 827 | { |
||
| 828 | $yaml = $yaml ?? ''; |
||
| 829 | |||
| 830 | try { |
||
| 831 | $array = Yaml::parse($yaml, Yaml::PARSE_DATETIME); |
||
| 832 | if (!\is_array($array)) { |
||
| 833 | throw new ParseException('YAML error.'); |
||
| 834 | } |
||
| 835 | } catch (ParseException $e) { |
||
| 836 | throw new RuntimeException(\sprintf('"yaml_parse" filter can not parse supplied YAML: %s', $e->getMessage())); |
||
| 837 | } |
||
| 838 | |||
| 839 | return $array; |
||
| 840 | } |
||
| 841 | |||
| 842 | /** |
||
| 843 | * Split a string into an array using a regular expression. |
||
| 844 | * |
||
| 845 | * @throws RuntimeException |
||
| 846 | */ |
||
| 847 | public function pregSplit(?string $value, string $pattern, int $limit = 0): ?array |
||
| 848 | { |
||
| 849 | $value = $value ?? ''; |
||
| 850 | |||
| 851 | try { |
||
| 852 | $array = preg_split($pattern, $value, $limit); |
||
| 853 | if ($array === false) { |
||
| 854 | throw new RuntimeException('PREG split error.'); |
||
| 855 | } |
||
| 856 | } catch (\Exception) { |
||
| 857 | throw new RuntimeException('"preg_split" filter can not split supplied string.'); |
||
| 858 | } |
||
| 859 | |||
| 860 | return $array; |
||
| 861 | } |
||
| 862 | |||
| 863 | /** |
||
| 864 | * Perform a regular expression match and return the group for all matches. |
||
| 865 | * |
||
| 866 | * @throws RuntimeException |
||
| 867 | */ |
||
| 868 | public function pregMatchAll(?string $value, string $pattern, int $group = 0): ?array |
||
| 869 | { |
||
| 870 | $value = $value ?? ''; |
||
| 871 | |||
| 872 | try { |
||
| 873 | $array = preg_match_all($pattern, $value, $matches, PREG_PATTERN_ORDER); |
||
| 874 | if ($array === false) { |
||
| 875 | throw new RuntimeException('PREG match all error.'); |
||
| 876 | } |
||
| 877 | } catch (\Exception) { |
||
| 878 | throw new RuntimeException('"preg_match_all" filter can not match in supplied string.'); |
||
| 879 | } |
||
| 880 | |||
| 881 | return $matches[$group]; |
||
| 882 | } |
||
| 883 | |||
| 884 | /** |
||
| 885 | * Calculates estimated time to read a text. |
||
| 886 | */ |
||
| 887 | public function readtime(?string $text): string |
||
| 888 | { |
||
| 889 | $text = $text ?? ''; |
||
| 890 | |||
| 891 | $words = str_word_count(strip_tags($text)); |
||
| 892 | $min = floor($words / 200); |
||
| 893 | if ($min === 0) { |
||
| 894 | return '1'; |
||
| 895 | } |
||
| 896 | |||
| 897 | return (string) $min; |
||
| 898 | } |
||
| 899 | |||
| 900 | /** |
||
| 901 | * Gets the value of an environment variable. |
||
| 902 | */ |
||
| 903 | public function getEnv(?string $var): ?string |
||
| 904 | { |
||
| 905 | $var = $var ?? ''; |
||
| 906 | |||
| 907 | return getenv($var) ?: null; |
||
| 908 | } |
||
| 909 | |||
| 910 | /** |
||
| 911 | * Dump variable (or Twig context). |
||
| 912 | */ |
||
| 913 | public function varDump(\Twig\Environment $env, array $context, $var = null, ?array $options = null): void |
||
| 914 | { |
||
| 915 | if (!$env->isDebug()) { |
||
| 916 | return; |
||
| 917 | } |
||
| 918 | |||
| 919 | if ($var === null) { |
||
| 920 | $var = array(); |
||
| 921 | foreach ($context as $key => $value) { |
||
| 922 | if (!$value instanceof \Twig\Template && !$value instanceof \Twig\TemplateWrapper) { |
||
| 923 | $var[$key] = $value; |
||
| 924 | } |
||
| 925 | } |
||
| 926 | } |
||
| 927 | |||
| 928 | $cloner = new VarCloner(); |
||
| 929 | $cloner->setMinDepth(3); |
||
| 930 | $dumper = new HtmlDumper(); |
||
| 931 | $dumper->setTheme($options['theme'] ?? 'light'); |
||
| 932 | |||
| 933 | $data = $cloner->cloneVar($var)->withMaxDepth(3); |
||
| 934 | $dumper->dump($data, null, ['maxDepth' => 3]); |
||
| 935 | } |
||
| 936 | |||
| 937 | /** |
||
| 938 | * Tests if a variable is an Asset. |
||
| 939 | */ |
||
| 940 | public function isAsset($variable): bool |
||
| 941 | { |
||
| 942 | return $variable instanceof Asset; |
||
| 943 | } |
||
| 944 | |||
| 945 | /** |
||
| 946 | * Tests if an image Asset is large enough to be used as a cover image. |
||
| 947 | * A large image is defined as having a width >= 600px and height >= 315px. |
||
| 948 | */ |
||
| 949 | public function isImageLarge(Asset $asset): bool |
||
| 950 | { |
||
| 951 | return $asset['type'] == 'image' && $asset['width'] > $asset['height'] && $asset['width'] >= 600 && $asset['height'] >= 315; |
||
| 952 | } |
||
| 953 | |||
| 954 | /** |
||
| 955 | * Tests if an image Asset is square. |
||
| 956 | * A square image is defined as having the same width and height. |
||
| 957 | */ |
||
| 958 | public function isImageSquare(Asset $asset): bool |
||
| 959 | { |
||
| 960 | return $asset['type'] == 'image' && $asset['width'] == $asset['height']; |
||
| 961 | } |
||
| 962 | |||
| 963 | /** |
||
| 964 | * Returns the dominant hex color of an image asset. |
||
| 965 | * |
||
| 966 | * @param string|Asset $asset |
||
| 967 | * |
||
| 968 | * @return string |
||
| 969 | */ |
||
| 970 | public function dominantColor($asset): string |
||
| 971 | { |
||
| 972 | if (!$asset instanceof Asset) { |
||
| 973 | $asset = new Asset($this->builder, $asset); |
||
| 974 | } |
||
| 975 | |||
| 976 | return Image::getDominantColor($asset); |
||
| 977 | } |
||
| 978 | |||
| 979 | /** |
||
| 980 | * Returns a Low Quality Image Placeholder (LQIP) as data URL. |
||
| 981 | * |
||
| 982 | * @param string|Asset $asset |
||
| 983 | * |
||
| 984 | * @return string |
||
| 985 | */ |
||
| 986 | public function lqip($asset): string |
||
| 987 | { |
||
| 988 | if (!$asset instanceof Asset) { |
||
| 989 | $asset = new Asset($this->builder, $asset); |
||
| 990 | } |
||
| 991 | |||
| 992 | return Image::getLqip($asset); |
||
| 993 | } |
||
| 994 | |||
| 995 | /** |
||
| 996 | * Converts an hexadecimal color to RGB. |
||
| 997 | * |
||
| 998 | * @throws RuntimeException |
||
| 999 | */ |
||
| 1000 | public function hexToRgb(?string $variable): array |
||
| 1001 | { |
||
| 1002 | $variable = $variable ?? ''; |
||
| 1003 | |||
| 1004 | if (!self::isHex($variable)) { |
||
| 1005 | throw new RuntimeException(\sprintf('"%s" is not a valid hexadecimal value.', $variable)); |
||
| 1006 | } |
||
| 1007 | $hex = ltrim($variable, '#'); |
||
| 1008 | if (\strlen($hex) == 3) { |
||
| 1009 | $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2]; |
||
| 1010 | } |
||
| 1011 | $c = hexdec($hex); |
||
| 1012 | |||
| 1013 | return [ |
||
| 1014 | 'red' => $c >> 16 & 0xFF, |
||
| 1015 | 'green' => $c >> 8 & 0xFF, |
||
| 1016 | 'blue' => $c & 0xFF, |
||
| 1017 | ]; |
||
| 1018 | } |
||
| 1019 | |||
| 1020 | /** |
||
| 1021 | * Split a string in multiple lines. |
||
| 1022 | */ |
||
| 1023 | public function splitLine(?string $variable, int $max = 18): array |
||
| 1024 | { |
||
| 1025 | $variable = $variable ?? ''; |
||
| 1026 | |||
| 1027 | return preg_split("/.{0,{$max}}\K(\s+|$)/", $variable, 0, PREG_SPLIT_NO_EMPTY); |
||
| 1028 | } |
||
| 1029 | |||
| 1030 | /** |
||
| 1031 | * Hashing an object, an array or a string (with algo, md5 by default). |
||
| 1032 | */ |
||
| 1033 | public function hash(object|array|string $data, $algo = 'md5'): string |
||
| 1034 | { |
||
| 1035 | switch (\gettype($data)) { |
||
| 1036 | case 'object': |
||
| 1037 | return spl_object_hash($data); |
||
| 1038 | case 'array': |
||
| 1039 | return hash($algo, serialize($data)); |
||
| 1040 | } |
||
| 1041 | |||
| 1042 | return hash($algo, $data); |
||
| 1043 | } |
||
| 1044 | |||
| 1045 | /** |
||
| 1046 | * Converts a variable to an iterable (array). |
||
| 1047 | */ |
||
| 1048 | public function iterable($value): array |
||
| 1049 | { |
||
| 1050 | if (\is_array($value)) { |
||
| 1051 | return $value; |
||
| 1052 | } |
||
| 1053 | if (\is_string($value)) { |
||
| 1054 | return [$value]; |
||
| 1055 | } |
||
| 1056 | if ($value instanceof \Traversable) { |
||
| 1057 | return iterator_to_array($value); |
||
| 1058 | } |
||
| 1059 | if ($value instanceof \stdClass) { |
||
| 1060 | return (array) $value; |
||
| 1061 | } |
||
| 1062 | if (\is_object($value)) { |
||
| 1063 | return [$value]; |
||
| 1064 | } |
||
| 1065 | if (\is_int($value) || \is_float($value)) { |
||
| 1066 | return [$value]; |
||
| 1067 | } |
||
| 1068 | return [$value]; |
||
| 1069 | } |
||
| 1070 | |||
| 1071 | /** |
||
| 1072 | * Highlights a code snippet. |
||
| 1073 | */ |
||
| 1074 | public function highlight(string $code, string $language): string |
||
| 1077 | } |
||
| 1078 | |||
| 1079 | /** |
||
| 1080 | * Returns an array with unique values. |
||
| 1081 | */ |
||
| 1082 | public function unique(array $array): array |
||
| 1083 | { |
||
| 1084 | return array_intersect_key($array, array_unique(array_map('strtolower', $array), SORT_STRING)); |
||
| 1085 | } |
||
| 1086 | |||
| 1087 | /** |
||
| 1088 | * Is a hexadecimal color is valid? |
||
| 1089 | */ |
||
| 1090 | private static function isHex(string $hex): bool |
||
| 1091 | { |
||
| 1092 | $valid = \is_string($hex); |
||
| 1093 | $hex = ltrim($hex, '#'); |
||
| 1094 | $length = \strlen($hex); |
||
| 1095 | $valid = $valid && ($length === 3 || $length === 6); |
||
| 1099 | } |
||
| 1100 | } |
||
| 1101 |