Completed
Push — master ( b7f9bf...48ba4b )
by Lars
02:40
created

AdapterFile::setExpired()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 14
cts 14
cp 1
rs 9.472
c 0
b 0
f 0
cc 4
nc 2
nop 3
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\cache;
6
7
/**
8
 * AdapterFile: File-adapter
9
 */
10
class AdapterFile extends AdapterFileAbstract
11
{
12
13
  /**
14
   * @inheritdoc
15
   */
16 7
  public function get(string $key)
17
  {
18 7
    $path = $this->getFileName($key);
19
20 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...
21 7
        \file_exists($path) === false
22
        ||
23 7
        \filesize($path) === 0
24
    ) {
25 1
      return null;
26
    }
27
28
    // init
29 7
    $string = '';
30
31
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
32 7
    $fp = @\fopen($path, 'rb');
33 7
    if ($fp && \flock($fp, LOCK_SH | LOCK_NB)) {
34 7
      while (!\feof($fp)) {
35 7
        $line = \fgets($fp);
36 7
        $string .= $line;
37
      }
38 7
      \flock($fp, LOCK_UN);
39
    }
40 7
    if ($fp) {
41 7
      \fclose($fp);
42
    }
43
44 7
    if (!$string) {
45
      return null;
46
    }
47
48 7
    $data = $this->serializer->unserialize($string);
49
50 7
    if (!$data || !$this->validateDataFromCache($data)) {
51
      return null;
52
    }
53
54 7
    if ($this->ttlHasExpired($data['ttl']) === true) {
55 2
      $this->remove($key);
56
57 2
      return null;
58
    }
59
60 6
    return $data['value'];
61
  }
62
63
  /**
64
   * @inheritdoc
65
   */
66 6
  public function setExpired(string $key, $value, int $ttl = 0): bool
67
  {
68 6
    $item = $this->serializer->serialize(
69
        array(
70 6
            'value' => $value,
71 6
            'ttl'   => $ttl ? $ttl + \time() : 0,
72
        )
73
    );
74
75
    // init
76 6
    $octetWritten = false;
77
78 6
    $cacheFile = $this->getFileName($key);
79
80
    // Open the file for writing only. If the file does not exist, it is created.
81
    // If it exists, it is neither truncated, nor the call to this function fails.
82
    /** @noinspection PhpUsageOfSilenceOperatorInspection */
83 6
    $fp = @\fopen($cacheFile, 'cb');
84 6
    if ($fp && \flock($fp, LOCK_EX | LOCK_NB)) {
85 6
      \ftruncate($fp, 0);
86 6
      $octetWritten = \fwrite($fp, $item);
87 6
      \fflush($fp);
88 6
      \flock($fp, LOCK_UN);
89
    }
90 6
    \fclose($fp);
91
92 6
    return $octetWritten !== false;
93
  }
94
}
95