Completed
Push — develop ( 515643...e2e58e )
by
unknown
08:08
created

PaginationParams::getParams()   D

Complexity

Conditions 12
Paths 176

Size

Total Lines 41
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 41
rs 4.8484
c 0
b 0
f 0
cc 12
eloc 28
nc 176
nop 3

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * YAWIK
4
 *
5
 * @filesource
6
 * @copyright (c) 2013 - 2016 Cross Solution (http://cross-solution.de)
7
 * @license   MIT
8
 */
9
10
/** SessionParams.php */
11
namespace Core\Controller\Plugin;
12
13
use Zend\Mvc\Controller\Plugin\AbstractPlugin;
14
use Zend\Session\Container;
15
use Core\Repository\RepositoryInterface;
16
17
/**
18
 * Manages pagination parameters in a session container.
19
 *
20
 * @author Mathias Gelhausen <[email protected]>
21
 */
22
class PaginationParams extends AbstractPlugin
23
{
24
    
25
    /**
26
     * Invoke object as function.
27
     *
28
     * if <i>$namespace</i> is given, proxies to {@link getParams}, if <i>$defaults</i>
29
     * is an array and not callable or proxises to {@link getList} in the other case.
30
     *
31
     * if called without arguments, returns itself.
32
     *
33
     * @param string|null $namespace
34
     * @param array|RepositoryInterface $defaults
35
     * @return \Core\Controller\Plugin\PaginationParams|Parameters|PaginationList
36
     */
37
    public function __invoke($namespace = null, $defaults = array('page' => 1), $params = null)
38
    {
39
        if (null === $namespace) {
40
            return $this;
41
        }
42
        
43
        if (is_array($defaults) && !is_callable($defaults)) {
44
            return $this->getParams($namespace, $defaults, $params);
45
        }
46
        
47
        if ($defaults instanceof RepositoryInterface || is_callable($defaults)) {
48
            return $this->getList($namespace, $defaults);
49
        }
50
    }
51
    
52
    /**
53
     * Sets pagination params and stores them in the session.
54
     *
55
     * @param String $namespace
56
     * @param array|Parameters $params
57
     * @return \Core\Controller\Plugin\PaginationParams fluent interface
58
     */
59
    public function setParams($namespace, $params)
60
    {
61
        $session = new Container($namespace);
62
        $session->params = $params;
63
        unset($session->list);
64
        return $this;
65
    }
66
    
67
    /**
68
     * Retrieves pagination params.
69
     *
70
     * Automatically merges parameters stored in the session according to specs
71
     * provided.
72
     *
73
     * @param string $namespace Session namespace
74
     * @param array $defaults
75
     *      1. [paramName] => [defaultValue],
76
     *         Set default value if paramName is not present in params
77
     *      2. [paramName]
78
     *         Store paramName if it is present, do nothing if not.
79
     *
80
     * @return Parameters
81
     */
82
    public function getParams($namespace, $defaults, $params = null)
83
    {
84
        $session        = new Container($namespace);
85
        $sessionParams  = $session->params ?: array();
86
        $params         = $params ?: $this->getController()->getRequest()->getQuery();
87
        
88
        if ($params->get('clear')) {
89
            $sessionParams = array();
90
            unset($params['clear']);
91
        }
92
        
93
        $changed = false;
94
        foreach ($defaults as $key => $default) {
95
            if (is_numeric($key)) {
96
                $key = $default;
97
                $default = null;
98
            }
99
            $value = $params->get($key);
100
            if (null === $value) {
101
                if (isset($sessionParams[$key])) {
102
                    $params->set($key, $sessionParams[$key]);
103
                } elseif (null !== $default) {
104
                    $params->set($key, $default);
105
                    $sessionParams[$key] = $default;
106
                    $changed = true;
107
                }
108
            } else {
109
                if (!isset($sessionParams[$key]) || $sessionParams[$key] != $value) {
110
                    $changed = true;
111
                    $sessionParams[$key] = $value;
112
                }
113
            }
114
        }
115
        
116
        if ($changed) {
117
            unset($session->list);
118
            $session->params = $sessionParams;
119
        }
120
        
121
        return $params;
122
    }
123
    
124
    /**
125
     * Gets the list of ids.
126
     *
127
     * If no list is stored in the session, it will try to create one
128
     * using the given callback, which is either a RepositoryInterface or a
129
     * callable. In the first case, a method called "getPaginationList" will get called.
130
     * The stored parameters (or an empty array, if nothing is stored) will be passed.
131
     *
132
     * @param string $namespace
133
     * @param RepositoryInterface|callable $callback
134
     */
135
    public function getList($namespace, $callback)
136
    {
137
        $session = new Container($namespace);
138
        $params  = $session->params?:array();
0 ignored issues
show
Unused Code introduced by
$params 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...
139
        if (!$session->list) {
140
            $session->list = is_array($callback)
141
            ? call_user_func($callback, $session->params)
142
            : $callback->getPaginationList($session->params);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Core\Repository\RepositoryInterface as the method getPaginationList() does only exist in the following implementations of said interface: Applications\Repository\Application.

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...
143
        }
144
        return $session->list;
145
    }
146
        
147
    /**
148
     * Get previous and next id from the list.
149
     *
150
     * @param string $namespace
151
     * @param RepositoryInterface|callable $callback
152
     * @param string $id Current application id
153
     * @return array
154
     *          first entry: previous id or null
155
     *          second entry: next id or null
156
     */
157
    public function getNeighbours($namespace, $callback, $id)
158
    {
159
        $list = $this->getList($namespace, $callback);
160
        $list->setCurrent($id);
161
        return array(
162
            $list->getPrevious(),
163
            $list->getNext()
164
        );
165
    }
166
}
167