MemcachedCache::increment()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Soupmix\Cache;
4
5
use Soupmix\Cache\Exceptions\InvalidArgumentException;
6
use Psr\SimpleCache\CacheInterface;
7
use Memcached;
8
use DateInterval;
9
use DateTime;
10
11
class MemcachedCache implements CacheInterface
12
{
13
14
    const PSR16_RESERVED_CHARACTERS = ['{','}','(',')','/','@',':'];
15
16
    public $handler;
17
18
    /**
19
     * Connect to Memcached service
20
     *
21
     * @param Memcached $handler Memcached handler object
22
     *
23
     */
24 7
    public function __construct(Memcached $handler)
25
    {
26 7
        $this->handler = $handler;
27 7
        if (defined('Memcached::HAVE_IGBINARY') && extension_loaded('igbinary')) {
28 7
            ini_set('memcached.serializer', 'igbinary');
29
        }
30 7
    }
31
32
    /**
33
     * {@inheritDoc}
34
     */
35 1
    public function get($key, $default = null)
36
    {
37
38 1
        $this->checkReservedCharacters($key);
39 1
        $value = $this->handler->get($key);
40 1
        return $value ?: $default;
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     */
46 5 View Code Duplication
    public function set($key, $value, $ttl = null)
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...
47
    {
48
49 5
        $this->checkReservedCharacters($key);
50 3
        if ($ttl instanceof DateInterval) {
51 1
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
52
        }
53 3
        return $this->handler->set($key, $value, (int) $ttl);
54
    }
55
56
    /**
57
     * {@inheritDoc}
58
     */
59 1
    public function delete($key)
60
    {
61
62 1
        $this->checkReservedCharacters($key);
63 1
        return (bool) $this->handler->delete($key);
64
    }
65
66
    /**
67
     * {@inheritDoc}
68
     */
69 7
    public function clear()
70
    {
71 7
        return $this->handler->flush();
72
    }
73
74
    /**
75
     * {@inheritDoc}
76
     */
77 1
    public function getMultiple($keys, $default = null)
78
    {
79 1
        $defaults = array_fill(0, count($keys), $default);
80 1
        foreach ($keys as $key) {
81 1
            $this->checkReservedCharacters($key);
82
        }
83 1
        return array_merge($this->handler->getMulti($keys), $defaults);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return array_merge($this...lti($keys), $defaults); (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...
84
    }
85
86
    /**
87
     * {@inheritDoc}
88
     */
89 1 View Code Duplication
    public function setMultiple($values, $ttl = null)
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...
90
    {
91 1
        foreach ($values as $key => $value) {
92 1
            $this->checkReservedCharacters($key);
93
        }
94 1
        if ($ttl instanceof DateInterval) {
95 1
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
96
        }
97 1
        return $this->handler->setMulti($values, (int) $ttl);
98
    }
99
100
    /**
101
     * {@inheritDoc}
102
     */
103 1
    public function deleteMultiple($keys)
104
    {
105 1
        foreach ($keys as $key) {
106 1
            $this->checkReservedCharacters($key);
107
        }
108 1
        return $this->handler->deleteMulti($keys);
0 ignored issues
show
Bug introduced by
The method deleteMulti() does not exist on Memcached. Did you maybe mean delete()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
109
    }
110
111
    /**
112
     * {@inheritDoc}
113
     */
114 1
    public function increment($key, $step = 1)
115
    {
116 1
        return $this->handler->increment($key, $step);
117
    }
118
119
    /**
120
     * {@inheritDoc}
121
     */
122 1
    public function decrement($key, $step = 1)
123
    {
124 1
        return $this->handler->decrement($key, $step);
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130 1
    public function has($key)
131
    {
132 1
        $this->checkReservedCharacters($key);
133 1
        $value = $this->handler->get($key);
0 ignored issues
show
Unused Code introduced by
$value is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
134 1
        return Memcached::RES_NOTFOUND !== $this->handler->getResultCode();
135
    }
136
137 6
    private function checkReservedCharacters($key)
138
    {
139 6
        if (!is_string($key)) {
140 1
            $message = sprintf('key %s is not a string.', $key);
141 1
            throw new InvalidArgumentException($message);
142
        }
143 5
        foreach (self::PSR16_RESERVED_CHARACTERS as $needle) {
144 5
            if (strpos($key, $needle) !== false) {
145 1
                $message = sprintf('%s string is not a legal value.', $key);
146 1
                throw new InvalidArgumentException($message);
147
            }
148
        }
149 4
    }
150
}
151