EmulatingStorage::encode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 9
ccs 0
cts 9
cp 0
crap 6
rs 9.9666
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of Railt package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
declare(strict_types=1);
9
10
namespace Railt\Storage\Drivers;
11
12
use Railt\Io\Readable;
13
use Railt\Storage\Storage;
14
15
/**
16
 * Class EmulatingStorage
17
 */
18
class EmulatingStorage implements Storage
19
{
20
    /**
21
     * @var array|string[]
22
     */
23
    private $storage = [];
24
25
    /**
26
     * @param Readable $readable
27
     * @param \Closure $then
28
     * @return object|mixed
29
     * @throws \BadMethodCallException
30
     */
31 View Code Duplication
    public function remember(Readable $readable, \Closure $then)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
32
    {
33
        $key = $readable->getHash();
34
35
        if (! \array_key_exists($key, $this->storage)) {
36
            $this->storage[$key] = $this->encode($then($readable));
37
        }
38
39
        return $this->decode($this->storage[$key]);
40
    }
41
42
    /**
43
     * @param $data
44
     * @return string
45
     * @throws \BadMethodCallException
46
     */
47
    private function encode($data): string
48
    {
49
        try {
50
            return \serialize($data);
51
        } catch (\Error $e) {
52
            $error = \sprintf('Error while entity serializing: %s', $e->getMessage());
53
            throw new \BadMethodCallException($error, $e->getCode(), $e);
54
        }
55
    }
56
57
    /**
58
     * @param string $data
59
     * @return mixed
60
     */
61
    private function decode(string $data)
62
    {
63
        return \unserialize($data, [
64
            'allowed_classes' => true,
65
        ]);
66
    }
67
}
68