desarrolla2 /
Cache
| 1 | <?php |
||
| 2 | /** |
||
| 3 | * This file is part of the Cache package. |
||
| 4 | * |
||
| 5 | * Copyright (c) Daniel González |
||
| 6 | * |
||
| 7 | * For the full copyright and license information, please view the LICENSE |
||
| 8 | * file that was distributed with this source code. |
||
| 9 | * |
||
| 10 | * @author Daniel González <[email protected]> |
||
| 11 | * @author Arnold Daniels <[email protected]> |
||
| 12 | */ |
||
| 13 | |||
| 14 | declare(strict_types=1); |
||
| 15 | |||
| 16 | namespace Desarrolla2\Cache\Packer; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * Support packing for Caching adapter |
||
| 20 | */ |
||
| 21 | trait PackingTrait |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * @var PackerInterface |
||
| 25 | */ |
||
| 26 | protected $packer; |
||
| 27 | |||
| 28 | |||
| 29 | /** |
||
| 30 | * Create the default packer for this cache implementation |
||
| 31 | * |
||
| 32 | * @return PackerInterface |
||
| 33 | */ |
||
| 34 | abstract protected static function createDefaultPacker(): PackerInterface; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Set a packer to pack (serialialize) and unpack (unserialize) the data. |
||
| 38 | * |
||
| 39 | * @param PackerInterface $packer |
||
| 40 | * @return static |
||
| 41 | */ |
||
| 42 | public function withPacker(PackerInterface $packer) |
||
| 43 | { |
||
| 44 | $cache = $this->cloneSelf(); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 45 | $cache->packer = $packer; |
||
| 46 | |||
| 47 | return $cache; |
||
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Get the packer |
||
| 52 | * |
||
| 53 | * @return PackerInterface |
||
| 54 | */ |
||
| 55 | 1069 | protected function getPacker(): PackerInterface |
|
| 56 | { |
||
| 57 | 1069 | if (!isset($this->packer)) { |
|
| 58 | 1069 | $this->packer = static::createDefaultPacker(); |
|
| 59 | } |
||
| 60 | |||
| 61 | 1069 | return $this->packer; |
|
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * Pack the value |
||
| 66 | * |
||
| 67 | * @param mixed $value |
||
| 68 | * @return string|mixed |
||
| 69 | */ |
||
| 70 | 835 | protected function pack($value) |
|
| 71 | { |
||
| 72 | 835 | return $this->getPacker()->pack($value); |
|
| 73 | } |
||
| 74 | |||
| 75 | /** |
||
| 76 | * Unpack the data to retrieve the value |
||
| 77 | * |
||
| 78 | * @param string|mixed $packed |
||
| 79 | * @return mixed |
||
| 80 | * @throws \UnexpectedValueException |
||
| 81 | */ |
||
| 82 | 402 | protected function unpack($packed) |
|
| 83 | { |
||
| 84 | 402 | return $this->getPacker()->unpack($packed); |
|
| 85 | } |
||
| 86 | } |
||
| 87 |