Passed
Pull Request — master (#857)
by Georges
04:15 queued 02:15
created

DriverBaseTrait::getDriverName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 *
5
 * This file is part of Phpfastcache.
6
 *
7
 * @license MIT License (MIT)
8
 *
9
 * For full copyright and license information, please see the docs/CREDITS.txt and LICENCE files.
10
 *
11
 * @author Georges.L (Geolim4)  <[email protected]>
12
 * @author Contributors  https://github.com/PHPSocialNetwork/phpfastcache/graphs/contributors
13
 */
14
15
declare(strict_types=1);
16
17
namespace Phpfastcache\Core\Pool;
18
19
use DateTime;
20
use DateTimeInterface;
21
use Phpfastcache\Config\ConfigurationOptionInterface;
22
use Phpfastcache\Event\EventManagerDispatcherTrait;
23
use Phpfastcache\Event\EventManagerInterface;
24
use Phpfastcache\Exceptions\PhpfastcacheInvalidArgumentException;
25
use Phpfastcache\Util\ClassNamespaceResolverTrait;
26
use Throwable;
27
use Phpfastcache\Config\ConfigurationOption;
28
use Phpfastcache\Core\Item\ExtendedCacheItemInterface;
29
use Phpfastcache\Entities\DriverIO;
30
use Phpfastcache\Exceptions\PhpfastcacheCoreException;
31
use Phpfastcache\Exceptions\PhpfastcacheDriverCheckException;
32
use Phpfastcache\Exceptions\PhpfastcacheDriverConnectException;
33
use Phpfastcache\Exceptions\PhpfastcacheIOException;
34
use Phpfastcache\Exceptions\PhpfastcacheLogicException;
35
use ReflectionObject;
36
37
trait DriverBaseTrait
38
{
39
    use DriverPoolAbstractTrait;
40
    use ClassNamespaceResolverTrait;
41
    use EventManagerDispatcherTrait;
42
43
    protected static array $cacheItemClasses = [];
44
45
    protected ConfigurationOptionInterface $config;
46
47
    protected object|array|null $instance;
48
49
    protected string $driverName;
50
51
    protected string $instanceId;
52
53
    /**
54
     * Driver constructor.
55
     * @param ConfigurationOptionInterface $config
56
     * @param string $instanceId
57
     * @param EventManagerInterface $em
58
     * @throws PhpfastcacheCoreException
59
     * @throws PhpfastcacheDriverCheckException
60
     * @throws PhpfastcacheDriverConnectException
61
     * @throws PhpfastcacheIOException
62
     * @throws PhpfastcacheInvalidArgumentException
63
     */
64
    public function __construct(ConfigurationOptionInterface $config, string $instanceId, EventManagerInterface $em)
65
    {
66
        $this->setEventManager($em);
67
        $this->setConfig($config);
68
        $this->instanceId = $instanceId;
69
        $this->IO = new DriverIO();
0 ignored issues
show
Bug Best Practice introduced by
The property IO does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
70
71
        if (!$this->driverCheck()) {
72
            throw new PhpfastcacheDriverCheckException(\sprintf(self::DRIVER_CHECK_FAILURE, $this->getDriverName()));
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...t::DRIVER_CHECK_FAILURE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
73
        }
74
75
        try {
76
            $this->driverConnect();
77
            $config->lock($this);
0 ignored issues
show
Bug introduced by
$this of type Phpfastcache\Core\Pool\DriverBaseTrait is incompatible with the type Phpfastcache\Core\Pool\E...dCacheItemPoolInterface expected by parameter $poolInstance of Phpfastcache\Config\Lock...rationInterface::lock(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

77
            $config->lock(/** @scrutinizer ignore-type */ $this);
Loading history...
78
        } catch (Throwable $e) {
79
            throw new PhpfastcacheDriverConnectException(
80
                sprintf(
81
                    self::DRIVER_CONNECT_FAILURE,
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...:DRIVER_CONNECT_FAILURE was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
82
                    $e::class,
83
                    $this->getDriverName(),
84
                    $e->getMessage(),
85
                    $e->getLine() ?: 'unknown line',
86
                    $e->getFile() ?: 'unknown file'
87
                ),
88
                0,
89
                $e
90
            );
91
        }
92
    }
93
94
    /**
95
     * @return string
96
     */
97
    public function getDriverName(): string
98
    {
99
        if (!isset($this->driverName)) {
100
            $this->driverName = \ucfirst(\substr(\strrchr((new ReflectionObject($this))->getNamespaceName(), '\\'), 1));
101
        }
102
        return $this->driverName;
103
    }
104
105
    /**
106
     * @return ConfigurationOptionInterface
107
     */
108
    public function getDefaultConfig(): ConfigurationOptionInterface
109
    {
110
        $className = $this::getConfigClass();
111
112
        return new $className();
113
    }
114
115
    /**
116
     * @return string
117
     */
118
    public static function getConfigClass(): string
119
    {
120
        $localConfigClass = \substr(static::class, 0, \strrpos(static::class, '\\')) . '\Config';
121
        if (\class_exists($localConfigClass) && \is_a($localConfigClass, ConfigurationOption::class, true)) {
122
            return $localConfigClass;
123
        }
124
        return ConfigurationOption::class;
125
    }
126
127
    public static function getItemClass(): string
128
    {
129
        if (!isset(self::$cacheItemClasses[static::class])) {
130
            self::$cacheItemClasses[static::class] = self::getClassNamespace() . '\\' . 'Item';
131
        }
132
133
        return self::$cacheItemClasses[static::class];
134
    }
135
136
137
    /**
138
     * @param ExtendedCacheItemInterface $item
139
     * @param bool $stringifyDate
140
     * @return array
141
     * @throws PhpfastcacheLogicException
142
     */
143
    public function driverPreWrap(ExtendedCacheItemInterface $item, bool $stringifyDate = false): array
144
    {
145
        $wrap = [
146
            ExtendedCacheItemPoolInterface::DRIVER_KEY_WRAPPER_INDEX => $item->getKey(), // Stored but not really used, allow you to quickly identify the cache key
147
            ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX => $item->getRawValue(),
148
            TaggableCacheItemPoolInterface::DRIVER_TAGS_WRAPPER_INDEX => $item->getTags(),
149
            self::DRIVER_EDATE_WRAPPER_INDEX => $item->getExpirationDate(),
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...VER_EDATE_WRAPPER_INDEX was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
150
        ];
151
152
        if ($this->getConfig()->isItemDetailedDate()) {
153
            $wrap[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = new DateTime();// Always on the latest date
154
            /**
155
             * If the creation date exists
156
             * reuse it else set a new Date
157
             */
158
            $wrap[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = $item->getCreationDate();
159
        } else {
160
            $wrap[ExtendedCacheItemPoolInterface::DRIVER_MDATE_WRAPPER_INDEX] = null;
161
            $wrap[ExtendedCacheItemPoolInterface::DRIVER_CDATE_WRAPPER_INDEX] = null;
162
        }
163
164
        if ($stringifyDate) {
165
            \array_walk($wrap, static function (mixed &$value, string $key): void {
166
                if ($value instanceof DateTimeInterface && $key !== ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX) {
167
                    $value = $value->format(DateTimeInterface::W3C);
168
                }
169
            });
170
        }
171
172
        return $wrap;
173
    }
174
175
    /**
176
     * @return ConfigurationOptionInterface
177
     */
178
    public function getConfig(): ConfigurationOptionInterface
179
    {
180
        return $this->config;
181
    }
182
183
    /**
184
     * @param ConfigurationOptionInterface $config
185
     * @return static
186
     */
187
    public function setConfig(ConfigurationOptionInterface $config): static
188
    {
189
        $this->config = $config;
190
191
        return $this;
192
    }
193
194
    /**
195
     * @param array $wrapper
196
     * @return mixed
197
     * @throws \Exception
198
     */
199
    public function driverUnwrapData(array $wrapper): mixed
200
    {
201
        return $wrapper[ExtendedCacheItemPoolInterface::DRIVER_DATA_WRAPPER_INDEX];
202
    }
203
204
    /**
205
     * @param array $wrapper
206
     * @return DateTime
207
     */
208
    public function driverUnwrapEdate(array $wrapper): \DateTime
209
    {
210
        if ($wrapper[self::DRIVER_EDATE_WRAPPER_INDEX] instanceof \DateTime) {
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...VER_EDATE_WRAPPER_INDEX was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
211
            return $wrapper[self::DRIVER_EDATE_WRAPPER_INDEX];
212
        }
213
214
        return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[self::DRIVER_EDATE_WRAPPER_INDEX]);
215
    }
216
217
    /**
218
     * @param array $wrapper
219
     * @return DateTime|null
220
     */
221
    public function driverUnwrapCdate(array $wrapper): ?\DateTime
222
    {
223
        if ($wrapper[self::DRIVER_CDATE_WRAPPER_INDEX] instanceof \DateTime) {
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...VER_CDATE_WRAPPER_INDEX was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
224
            return $wrapper[self::DRIVER_CDATE_WRAPPER_INDEX];
225
        }
226
227
        return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[self::DRIVER_CDATE_WRAPPER_INDEX]);
228
    }
229
230
    /**
231
     * @param array $wrapper
232
     * @return DateTime|null
233
     */
234
    public function driverUnwrapMdate(array $wrapper): ?\DateTime
235
    {
236
        if ($wrapper[self::DRIVER_MDATE_WRAPPER_INDEX] instanceof \DateTime) {
0 ignored issues
show
Bug introduced by
The constant Phpfastcache\Core\Pool\D...VER_MDATE_WRAPPER_INDEX was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
237
            return $wrapper[self::DRIVER_MDATE_WRAPPER_INDEX];
238
        }
239
240
        return DateTime::createFromFormat(\DateTimeInterface::W3C, $wrapper[self::DRIVER_MDATE_WRAPPER_INDEX]);
241
    }
242
243
    /**
244
     * @return string
245
     */
246
    public function getInstanceId(): string
247
    {
248
        return $this->instanceId;
249
    }
250
251
    /**
252
     * Encode data types such as object/array
253
     * for driver that does not support
254
     * non-scalar value
255
     * @param $data
256
     * @return string
257
     */
258
    protected function encode($data): string
259
    {
260
        return \serialize($data);
261
    }
262
263
    /**
264
     * Decode data types such as object/array
265
     * for driver that does not support
266
     * non-scalar value
267
     * @param string|null $value
268
     * @return mixed
269
     */
270
    protected function decode(?string $value): mixed
271
    {
272
        return \unserialize((string) $value, ['allowed_classes' => true]);
273
    }
274
}
275