CacheableWidget   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 38
c 1
b 1
f 0
dl 0
loc 77
ccs 35
cts 35
cp 1
rs 10
wmc 7

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A render() 0 12 1
A resolveContentToCache() 0 10 2
A configureOptions() 0 20 1
A createKey() 0 7 1
A getName() 0 3 1
1
<?php
2
/**
3
 * This file is part of the sauls/widget package.
4
 *
5
 * @author    Saulius Vaičeliūnas <[email protected]>
6
 * @link      http://saulius.vaiceliunas.lt
7
 * @copyright 2020
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
13
declare(strict_types=1);
14
15
namespace Sauls\Component\Widget\Widgets;
16
17
use Psr\Cache\InvalidArgumentException;
18
use Sauls\Component\Widget\Exception\WidgetFactoryIsNullException;
19
use Sauls\Component\Widget\Factory\Traits\WidgetFactoryAwareTrait;
20
use Sauls\Component\Widget\Named;
21
use Sauls\Component\Widget\Widget;
22
use Symfony\Component\OptionsResolver\OptionsResolver;
23
use Symfony\Contracts\Cache\CacheInterface;
24
use Symfony\Contracts\Cache\ItemInterface;
25
26
use function json_encode;
27
use function sprintf;
28
29
class CacheableWidget extends Widget implements Named
30
{
31
    use WidgetFactoryAwareTrait;
32
33
    public static $prefix = 'cw';
34
    public static $total = 0;
35
    private CacheInterface $cache;
36
37 4
    public function __construct(CacheInterface $cache)
38
    {
39 4
        $this->cache = $cache;
40 4
    }
41
42
    /**
43
     * @throws InvalidArgumentException
44
     */
45 3
    public function render(): string
46
    {
47 3
        $self = $this;
48
49 3
        return $this->cache->get(
50 3
                $this->createKey(),
51 3
                function (ItemInterface $item) use ($self) {
52 2
                    $item->expiresAfter($self->getOption('ttl'));
53
54 2
                    return $self->resolveContentToCache();
55 3
                }
56 2
            ) ?? '';
57
    }
58
59 3
    private function createKey(): string
60
    {
61 3
        return sprintf(
62 3
            '__%1$s%2$s__%3$s__',
63 3
            $this->getOption('namespace') . self::$prefix,
64 3
            md5($this->getOption('widget.id') . json_encode($this->getOptions())),
65 3
            $this->getId()
66
        );
67
    }
68
69 2
    private function resolveContentToCache(): string
70
    {
71 2
        if (null === $this->widgetFactory) {
72 1
            throw new WidgetFactoryIsNullException('Widget factory is needed for this widget to work properly');
73
        }
74
75 1
        return (string)$this->widgetFactory->create(
76 1
                $this->getOption('widget.id') ?? '',
77 1
                $this->getOption('widget.options') ?? []
78 1
            ) ?? '';
79
    }
80
81 1
    public function getName(): string
82
    {
83 1
        return 'cacheable_widget';
84
    }
85
86 3
    protected function configureOptions(OptionsResolver $resolver): void
87
    {
88
        $resolver
89 3
            ->setDefined(
90
                [
91 3
                    'widget',
92
                    'namespace',
93
                    'ttl',
94
                ]
95
            )
96 3
            ->addAllowedTypes('widget', ['array'])
97 3
            ->addAllowedTypes('namespace', ['string'])
98 3
            ->addAllowedTypes('ttl', ['int'])
99 3
            ->setDefaults(
100
                [
101 3
                    'namespace' => '__widget__',
102
                    'ttl' => 3600,
103
                    'widget' => [
104
                        'id' => '',
105
                        'options' => [],
106
                    ],
107
                ]
108
            );
109 3
    }
110
}
111