RenderFactory.php$0 ➔ __construct()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Enjoys\AssetsCollector;
6
7
use Closure;
8
9
final class RenderFactory
10
{
11
12
13
    public static function getDefaultRenderer(AssetType $type): Renderer
14
    {
15
        return match ($type) {
16
            AssetType::CSS => self::createFromClosure(self::defaultCssRenderer()),
17
            AssetType::JS => self::createFromClosure(self::defaultJsRenderer())
18
        };
19
    }
20
21
    /**
22
     * @return Closure(Asset[]): string
23
     */
24
    private static function defaultCssRenderer(): Closure
25
    {
26
        /**
27
         * @param Asset[] $assets
28
         * @return string
29
         */
30
        return function (array $assets): string {
31
            $result = '';
32
            foreach ($assets as $asset) {
33
                $attributes = $asset->getAttributeCollection()
34
                    ->set('type', 'text/css')
35
                    ->set('rel', 'stylesheet')
36
                    ->getArray();
37
38
                krsort($attributes);
39
40
                $result .= sprintf(
41
                    "<link%s>\n",
42
                    (new AttributeCollection($attributes))->__toString()
43
                );
44
            }
45
            return $result;
46
        };
47
    }
48
49
    /**
50
     * @return Closure(Asset[]): string
51
     */
52
    private static function defaultJsRenderer(): Closure
53
    {
54
        /**
55
         * @param Asset[] $assets
56
         * @return string
57
         */
58
        return function (array $assets): string {
59
            $result = '';
60
            foreach ($assets as $asset) {
61
                $result .= sprintf(
62
                    "<script%s></script>\n",
63
                    $asset->getAttributeCollection()->__toString()
64
                );
65
            }
66
            return $result;
67
        };
68
    }
69
70
    /**
71
     * @param Closure(Asset[]): string $closure
72
     * @return Renderer
73
     */
74
    public static function createFromClosure(Closure $closure): Renderer
75
    {
76
        return new class($closure) implements Renderer {
77
78
            /**
79
             * @param Closure(Asset[]): string $renderer
80
             */
81
            public function __construct(private readonly Closure $renderer)
82
            {
83
            }
84
85
            public function render(array $assets): string
86
            {
87
                return call_user_func($this->renderer, $assets);
88
            }
89
        };
90
    }
91
}
92