Completed
Push — master ( a18851...eb3437 )
by Lars
02:11
created

CachePsr16::deleteMultiple()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 3
Ratio 23.08 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 3
loc 13
ccs 0
cts 9
cp 0
rs 9.2
c 1
b 0
f 1
cc 4
eloc 7
nc 3
nop 1
crap 20
1
<?php
2
3
declare(strict_types=1);
4
5
namespace voku\cache;
6
7
use Psr\SimpleCache\CacheInterface;
8
use voku\cache\Exception\InvalidArgumentException;
9
10
class CachePsr16 extends Cache implements CacheInterface
11
{
12
  /**
13
   * Wipes clean the entire cache's keys.
14
   *
15
   * @return bool True on success and false on failure.
16
   */
17
  public function clear(): bool
18
  {
19
    return $this->removeAll();
20
  }
21
22
  /**
23
   * Delete an item from the cache by its unique key.
24
   *
25
   * @param string $key The unique cache key of the item to delete.
26
   *
27
   * @return bool True if the item was successfully removed. False if there was an error.
28
   *
29 1
   * @throws InvalidArgumentException
30
   */
31 1
  public function delete($key): bool
32
  {
33
    if (!\is_string($key)) {
34
      throw new InvalidArgumentException('$key is not a string:' . print_r($key, true));
35 1
    }
36
37
    return $this->removeItem($key);
38
  }
39
40
  /**
41
   * Deletes multiple cache items in a single operation.
42
   *
43
   * @param \iterable $keys A list of string-based keys to be deleted.
44
   *
45
   * @return bool True if the items were successfully removed. False if there was an error.
46
   *
47
   * @throws InvalidArgumentException
48
   */
49
  public function deleteMultiple($keys): bool
50
  {
51 View Code Duplication
    if (!\is_array($keys) && !($keys instanceof \Traversable)) {
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...
52
      throw new InvalidArgumentException('$keys is not iterable:' . print_r($keys, true));
53
    }
54
55
    $results = array();
56
    foreach ((array)$keys as $key) {
57
      $results = $this->delete($key);
58
    }
59
60
    return \in_array(false, $results, true) === false;
61
  }
62
63
  /**
64
   * Fetches a value from the cache.
65
   *
66
   * @param string $key     The unique key of this item in the cache.
67
   * @param mixed  $default Default value to return if the key does not exist.
68
   *
69
   * @return mixed The value of the item from the cache, or $default in case of cache miss.
70
   *
71
   * @throws InvalidArgumentException
72
   */
73
  public function get($key, $default = null)
74 3
  {
75
    if ($this->has($key) === true) {
76 3
      return $this->getItem($key);
77 1
    }
78
79
    return $default;
80 2
  }
81
82
  /**
83
   * Obtains multiple cache items by their unique keys.
84
   *
85
   * @param \iterable $keys    A list of keys that can obtained in a single operation.
86
   * @param mixed     $default Default value to return for keys that do not exist.
87
   *
88
   * @return \iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as
89
   *                   value.
90
   *
91
   * @throws InvalidArgumentException
92
   */
93
  public function getMultiple($keys, $default = null)
94
  {
95 View Code Duplication
    if (!\is_array($keys) && !($keys instanceof \Traversable)) {
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...
96
      throw new InvalidArgumentException('$keys is not iterable:' . print_r($keys, true));
97
    }
98
99
    $result = array();
100
    foreach ((array)$keys as $key) {
101
      $result[$key] = $this->has($key) ? $this->get($key) : $default;
102
    }
103
104
    return $result;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $result; (array) is incompatible with the return type declared by the interface Psr\SimpleCache\CacheInterface::getMultiple of type Psr\SimpleCache\iterable.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
105
  }
106
107
  /**
108
   * Determines whether an item is present in the cache.
109
   *
110
   * NOTE: It is recommended that has() is only to be used for cache warming type purposes
111
   * and not to be used within your live applications operations for get/set, as this method
112
   * is subject to a race condition where your has() will return true and immediately after,
113
   * another script can remove it making the state of your app out of date.
114
   *
115
   * @param string $key The cache item key.
116
   *
117
   * @return bool
118
   *
119
   * @throws InvalidArgumentException
120
   */
121
  public function has($key): bool
122 4
  {
123
    if (!\is_string($key)) {
124 4
      throw new InvalidArgumentException('$key is not a string:' . print_r($key, true));
125
    }
126
127
    return $this->existsItem($key);
128 4
  }
129
130
  /**
131
   * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
132
   *
133
   * @param string                 $key   The key of the item to store.
134
   * @param mixed                  $value The value of the item to store, must be serializable.
135
   * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
136
   *                                      the driver supports TTL then the library may set a default value
137
   *                                      for it or let the driver take care of that.
138
   *
139
   * @return bool True on success and false on failure.
140
   *
141
   * @throws InvalidArgumentException
142
   */
143
  public function set($key, $value, $ttl = null): bool
144 3
  {
145
    if (!\is_string($key)) {
146 3
      throw new InvalidArgumentException('$key is not a string:' . print_r($key, true));
147
    }
148
149
    return $this->setItem($key, $value, $ttl);
0 ignored issues
show
Bug introduced by
It seems like $ttl defined by parameter $ttl on line 143 can also be of type null or object<DateInterval>; however, voku\cache\Cache::setItem() does only seem to accept integer, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
150 3
  }
151
152
  /**
153
   * Persists a set of key => value pairs in the cache, with an optional TTL.
154
   *
155
   * @param \iterable              $values A list of key => value pairs for a multiple-set operation.
156
   * @param null|int|\DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
157
   *                                       the driver supports TTL then the library may set a default value
158
   *                                       for it or let the driver take care of that.
159
   *
160
   * @return bool True on success and false on failure.
161
   *
162
   * @throws InvalidArgumentException
163
   */
164
  public function setMultiple($values, $ttl = null): bool
165
  {
166 View Code Duplication
    if (!\is_array($values) && !($values instanceof \Traversable)) {
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...
167
      throw new InvalidArgumentException('$values is not iterable:' . print_r($values, true));
168
    }
169
170
    $results = array();
171
    foreach ((array)$values as $key => $value) {
172
      $results = $this->set($key, $value, $ttl);
173
    }
174
175
    return \in_array(false, $results, true) === false;
176
  }
177
}
178