Completed
Push — master ( 097ee4...b7f9bf )
by Lars
02:18
created

AdapterFileSimple::get()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 37

Duplication

Lines 7
Ratio 18.92 %

Importance

Changes 0
Metric Value
dl 7
loc 37
rs 8.3946
c 0
b 0
f 0
cc 7
nc 5
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\cache;
6
7
/**
8
 * AdapterFileSimple: File-adapter (simple)
9
 */
10
class AdapterFileSimple extends AdapterFileAbstract
11
{
12
  const CACHE_FILE_PREFIX = '__simple_';
13
14
  protected function getContext()
15
  {
16
    static $CONTEXT_CACHE = null;
17
18
    if ($CONTEXT_CACHE === null) {
19
      $CONTEXT_CACHE = \stream_context_create(
20
          [
21
              'http' =>
22
                  [
23
                      'timeout' => 2,
24
                  ],
25
          ]
26
      );
27
    }
28
29
    return $CONTEXT_CACHE;
30
  }
31
32
  /**
33
   * @inheritdoc
34
   */
35
  public function get(string $key)
36
  {
37
    $path = $this->getFileName($key);
38
39 View Code Duplication
    if (
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
40
        \file_exists($path) === false
41
        ||
42
        \filesize($path) === 0
43
    ) {
44
      return null;
45
    }
46
47
    // init
48
    $string = \file_get_contents(
49
        $path,
50
        false,
51
        $this->getContext()
52
    );
53
54
    if (!$string) {
55
      return null;
56
    }
57
58
    $data = $this->serializer->unserialize($string);
59
60
    if (!$data || !$this->validateDataFromCache($data)) {
61
      return null;
62
    }
63
64
    if ($this->ttlHasExpired($data['ttl']) === true) {
65
      $this->remove($key);
66
67
      return null;
68
    }
69
70
    return $data['value'];
71
  }
72
73
  /**
74
   * @inheritdoc
75
   */
76
  public function setExpired(string $key, $value, int $ttl = 0): bool
77
  {
78
    return (bool)\file_put_contents(
79
        $this->getFileName($key),
80
        $this->serializer->serialize(
81
            [
82
                'value' => $value,
83
                'ttl'   => $ttl ? $ttl + \time() : 0,
84
            ]
85
        ),
86
        0,
87
        $this->getContext()
88
    );
89
  }
90
91
}
92