Passed
Push — master ( 213665...3da0c8 )
by Mehmet
01:44
created

MemcachedCache::set()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 9
Ratio 100 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 9
loc 9
ccs 4
cts 5
cp 0.8
rs 9.6666
cc 2
eloc 5
nc 2
nop 3
crap 2.032
1
<?php
2
3
namespace Soupmix\Cache;
4
5
use Soupmix\Cache\Exceptions\InvalidArgumentException;
6
use Psr\SimpleCache\CacheInterface;
7
use Memcached;
8
9
class MemcachedCache implements CacheInterface
10
{
11
12
    const PSR16_RESERVED_CHARACTERS = ['{','}','(',')','/','@',':'];
13
14
    public $handler;
15
16
    /**
17
     * Connect to Memcached service
18
     *
19
     * @param Memcached $handler Memcached handler object
20
     *
21
     */
22 5
    public function __construct(Memcached $handler)
23
    {
24 5
        $this->handler = $handler;
25 5
        if (defined('Memcached::HAVE_IGBINARY') && extension_loaded('igbinary')) {
26
            ini_set('memcached.serializer', 'igbinary');
27
        }
28 5
    }
29
30
    /**
31
     * {@inheritDoc}
32
     */
33 1
    public function get($key, $default = null)
34
    {
35
36 1
        $this->checkReservedCharacters($key);
37 1
        $value = $this->handler->get($key);
38 1
        return $value ?: $default;
39
    }
40
41
    /**
42
     * {@inheritDoc}
43
     */
44 3 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...
45
    {
46
47 3
        $this->checkReservedCharacters($key);
48 3
        if ($ttl instanceof DateInterval) {
0 ignored issues
show
Bug introduced by
The class Soupmix\Cache\DateInterval does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
49
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
50
        }
51 3
        return $this->handler->set($key, $value, (int) $ttl);
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57 1
    public function delete($key)
58
    {
59
60 1
        $this->checkReservedCharacters($key);
61 1
        return (bool) $this->handler->delete($key);
62
    }
63
64
    /**
65
     * {@inheritDoc}
66
     */
67 5
    public function clear()
68
    {
69 5
        return $this->handler->flush();
70
    }
71
72
    /**
73
     * {@inheritDoc}
74
     */
75 1
    public function getMultiple($keys, $default = null)
76
    {
77 1
        $defaults = array_fill(0, count($keys), $default);
78 1
        foreach ($keys as $key) {
79 1
            $this->checkReservedCharacters($key);
80
        }
81 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...
82
    }
83
84
    /**
85
     * {@inheritDoc}
86
     */
87 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...
88
    {
89 1
        foreach ($values as $key => $value) {
90 1
            $this->checkReservedCharacters($key);
91
        }
92 1
        if ($ttl instanceof DateInterval) {
0 ignored issues
show
Bug introduced by
The class Soupmix\Cache\DateInterval does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
93
            $ttl = (new DateTime('now'))->add($ttl)->getTimeStamp() - time();
94
        }
95 1
        return $this->handler->setMulti($values, (int) $ttl);
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     */
101 1
    public function deleteMultiple($keys)
102
    {
103 1
        foreach ($keys as $key) {
104 1
            $this->checkReservedCharacters($key);
105
        }
106 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...
107
    }
108
109
    /**
110
     * {@inheritDoc}
111
     */
112 1
    public function increment($key, $step = 1)
113
    {
114 1
        return $this->handler->increment($key, $step);
115
    }
116
117
    /**
118
     * {@inheritDoc}
119
     */
120 1
    public function decrement($key, $step = 1)
121
    {
122 1
        return $this->handler->decrement($key, $step);
123
    }
124
125
    /**
126
     * {@inheritDoc}
127
     */
128 1
    public function has($key)
129
    {
130 1
        $this->checkReservedCharacters($key);
131 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...
132 1
        return Memcached::RES_NOTFOUND !== $this->handler->getResultCode();
133
    }
134
135 4
    private function checkReservedCharacters($key)
136
    {
137 4
        if (!is_string($key)) {
138
            $message = sprintf('key %s is not a string.', $key);
139
            throw new InvalidArgumentException($message);
140
        }
141 4
        foreach (self::PSR16_RESERVED_CHARACTERS as $needle) {
142 4
            if (strpos($key, $needle) !== false) {
143
                $message = sprintf('%s string is not a legal value.', $key);
144
                throw new InvalidArgumentException($message);
145
            }
146
        }
147 4
    }
148
}
149