Cache   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 127
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 127
ccs 0
cts 56
cp 0
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B update() 0 53 4
A flushAnnotatedTags() 0 13 3
A getTimeInterval() 0 4 2
A getTags() 0 9 1
1
<?php
2
3
/**
4
 *
5
 * This file is part of the Apix Project.
6
 *
7
 * (c) Franck Cassedanne <franck at ouarz.net>
8
 *
9
 * @license     http://opensource.org/licenses/BSD-3-Clause  New BSD License
10
 *
11
 */
12
13
namespace Apix\Plugin;
14
15
use Apix\Service;
16
17
/**
18
 * Caching plugin for APIx.
19
 *
20
 * @author Franck Cassedanne <[email protected]>
21
 * @see https://github.com/frqnck/apix-cache
22
 */
23
class Cache extends PluginAbstractEntity
24
{
25
26
    public static $hook = array(
27
        'entity',
28
        'early',
29
        'interface' => 'Apix\Cache\Adapter' // 'frqnck\Cachette'
30
    );
31
32
    protected $annotation = 'api_cache';
33
34
    protected $options = array(
35
        'enable'        => true,              // wether to enable or not
36
        'adapter'       => 'Apix\Cache\Apc',  // instantiate by default
37
        'default_ttl'   => '10mins',          // lifetime, null stands forever
38
        'runtime_flush' => true,              // flush tags at runtime (cronjob)
39
        'append_tags'   => array(),           // default tags to append (v1, dev)
40
    );
41
42
    /**
43
     * @{@inheritdoc}
44
     */
45
    public function update(\SplSubject $entity)
46
    {
47
        $this->setEntity($entity);
0 ignored issues
show
Compatibility introduced by
$entity of type object<SplSubject> is not a sub-type of object<Apix\Entity>. It seems like you assume a concrete implementation of the interface SplSubject to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
48
49
        // skip this plugin if it is disable.
50
        if ( !$this->getSubTagBool('enable', $this->options['enable']) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getSubTagBool('en...his->options['enable']) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
51
            return false;
52
        }
53
        $logger = Service::get('logger');
54
55
        try {
56
            $this->flushAnnotatedTags($this->options['runtime_flush']);
57
58
            // the cache id is simply the entity route name for now!
59
            $id = Service::get('request')->getRequestedUri();
60
61
            // 1.) use the cache if present
62
            if ($data = $this->adapter->loadKey($id)) {
63
                $entity->setResults((array) $data);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SplSubject as the method setResults() does only exist in the following implementations of said interface: Apix\Entity, Apix\Entity\EntityClass, Apix\Entity\EntityClosure.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
64
65
                $logger->debug('Cache: loading resource "{id}"', array('id'=>$id));
66
67
            } else {
68
69
                // 2.) otherwise call and retrieve the method's output
70
                $data = call_user_func_array(array($entity, 'call'), array(true));
71
72
                $ttl = $this->getSubTagString('ttl', $this->options['default_ttl']);
73
74
                $seconds = $this->getTimeInterval($ttl);
75
76
                $tags = $this->getTags();
77
78
                // 3.) cache it for later usage
79
                $this->adapter->save($data, $id, $tags, $seconds);
80
81
                $logger->debug(
82
                    'Cache: saving resource "{id}" for {sec}s [tags: {tags}]',
83
                    array('id' => $id, 'sec' => $seconds, 'tags' => $tags)
84
                );
85
            }
86
87
        } catch (\Exception $e) {
88
            $logger->error(
89
                'Cache: Exception "{msg}"',
90
                array('msg' => $e->getMessage(), 'exception' => $e)
91
            );
92
93
            throw $e; // rethrow!
94
        }
95
96
        return $data;
97
    }
98
99
    /**
100
     * Flush the tags explicitly
101
     *
102
     * @param  boolean      $enable Wether to flush or not
103
     * @return boolean|null
104
     */
105
    public function flushAnnotatedTags($enable, array $default = null)
106
    {
107
        if ( $enable
108
            && $tags = $this->getSubTagValues('flush', $default)
109
        ) {
110
            $success = $this->adapter->clean($tags);
111
112
            $logger = Service::get('logger');
113
            $logger->debug('Cache: tags purged [{tags}]', array('tags' => $tags));
114
115
            return $success;
116
        }
117
    }
118
119
    /**
120
     * Returns the time interval in seconds.
121
     *
122
     * Inputs strings are date/time strtotime formatted.
123
     * @see http://php.net/strtotime
124
     *
125
     * @param  string  $end   The end time.
126
     * @param  string  $start The start time, default to 'now'.
127
     * @return integer The interval in seconds.
128
     */
129
    protected function getTimeInterval($end=null, $start='now')
130
    {
131
        return 0 == $end ? null : strtotime($end)-strtotime($start);
132
    }
133
134
    /**
135
     * Returns all the tags for this cache.
136
     *
137
     * @return array
138
     */
139
    protected function getTags()
140
    {
141
        $tags = array_merge(
142
            $this->options['append_tags'],
143
            $this->getSubTagValues('tags', array())
144
        );
145
146
        return array_unique($tags);
147
    }
148
149
}