Application   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 159
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 9

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 2 Features 0
Metric Value
wmc 20
c 3
b 2
f 0
lcom 2
cbo 9
dl 0
loc 159
ccs 0
cts 80
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
C init() 0 48 8
B handleRequest() 0 31 5
A loadController() 0 9 1
A setLayoutVariables() 0 15 2
A shouldSkipAuth() 0 19 4
1
<?php
2
/**
3
* PHPCI - Continuous Integration for PHP.
4
*
5
* @copyright    Copyright 2014, Block 8 Limited.
6
* @license      https://github.com/Block8/PHPCI/blob/master/LICENSE.md
7
*
8
* @link         https://www.phptesting.org/
9
*/
10
11
namespace PHPCI;
12
13
use b8;
14
use b8\Exception\HttpException;
15
use b8\Http\Response;
16
use b8\Http\Response\RedirectResponse;
17
use b8\View;
18
19
/**
20
 * PHPCI Front Controller.
21
 *
22
 * @author   Dan Cryer <[email protected]>
23
 */
24
class Application extends b8\Application
25
{
26
    /**
27
     * @var \PHPCI\Controller
28
     */
29
    protected $controller;
30
31
    /**
32
     * Initialise PHPCI - Handles session verification, routing, etc.
33
     */
34
    public function init()
0 ignored issues
show
Coding Style introduced by
init uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
35
    {
36
        $request = &$this->request;
37
        $route = '/:controller/:action';
38
        $opts = array('controller' => 'Home', 'action' => 'index');
39
40
        // Inlined as a closure to fix "using $this when not in object context" on 5.3
41
        $validateSession = function () {
42
            if (!empty($_SESSION['phpci_user_id'])) {
43
                $user = b8\Store\Factory::getStore('User')->getByPrimaryKey($_SESSION['phpci_user_id']);
44
45
                if ($user) {
46
                    $_SESSION['phpci_user'] = $user;
47
48
                    return true;
49
                }
50
51
                unset($_SESSION['phpci_user_id']);
52
            }
53
54
            return false;
55
        };
56
57
        $skipAuth = array($this, 'shouldSkipAuth');
58
59
        // Handler for the route we're about to register, checks for a valid session where necessary:
60
        $routeHandler = function (&$route, Response &$response) use (&$request, $validateSession, $skipAuth) {
61
            $skipValidation = in_array($route['controller'], array('session', 'webhook', 'build-status'));
62
63
            if (!$skipValidation && !$validateSession() && (!is_callable($skipAuth) || !$skipAuth())) {
64
                if ($request->isAjax()) {
65
                    $response->setResponseCode(401);
66
                    $response->setContent('');
67
                } else {
68
                    $_SESSION['phpci_login_redirect'] = substr($request->getPath(), 1);
69
                    $response = new RedirectResponse($response);
70
                    $response->setHeader('Location', PHPCI_URL.'session/login');
71
                }
72
73
                return false;
74
            }
75
76
            return true;
77
        };
78
79
        $this->router->clearRoutes();
0 ignored issues
show
Bug introduced by
The property router does not seem to exist. Did you mean route?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
80
        $this->router->register($route, $opts, $routeHandler);
0 ignored issues
show
Bug introduced by
The property router does not seem to exist. Did you mean route?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
81
    }
82
83
    /**
84
     * Handle an incoming web request.
85
     *
86
     * @return b8\b8\Http\Response|Response
87
     */
88
    public function handleRequest()
89
    {
90
        try {
91
            $this->response = parent::handleRequest();
92
        } catch (HttpException $ex) {
93
            $this->config->set('page_title', 'Error');
94
95
            $view = new View('exception');
96
            $view->exception = $ex;
97
98
            $this->response->setResponseCode($ex->getErrorCode());
99
            $this->response->setContent($view->render());
100
        } catch (\Exception $ex) {
101
            $this->config->set('page_title', 'Error');
102
103
            $view = new View('exception');
104
            $view->exception = $ex;
105
106
            $this->response->setResponseCode(500);
107
            $this->response->setContent($view->render());
108
        }
109
110
        if ($this->response->hasLayout() && $this->controller->layout) {
111
            $this->setLayoutVariables($this->controller->layout);
112
113
            $this->controller->layout->content = $this->response->getContent();
114
            $this->response->setContent($this->controller->layout->render());
115
        }
116
117
        return $this->response;
118
    }
119
120
    /**
121
     * Loads a particular controller, and injects our layout view into it.
122
     *
123
     * @param $class
124
     *
125
     * @return mixed
126
     */
127
    protected function loadController($class)
128
    {
129
        $controller = parent::loadController($class);
130
        $controller->layout = new View('layout');
131
        $controller->layout->title = 'PHPCI';
132
        $controller->layout->breadcrumb = array();
133
134
        return $controller;
135
    }
136
137
    /**
138
     * Injects variables into the layout before rendering it.
139
     *
140
     * @param View $layout
141
     */
142
    protected function setLayoutVariables(View &$layout)
143
    {
144
        $groups = array();
145
        $groupStore = b8\Store\Factory::getStore('ProjectGroup');
146
        $groupList = $groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
147
148
        foreach ($groupList['items'] as $group) {
149
            $thisGroup = array('title' => $group->getTitle());
150
            $projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId());
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class b8\Store as the method getByGroupId() does only exist in the following sub-classes of b8\Store: PHPCI\Store\Base\ProjectStoreBase, PHPCI\Store\ProjectStore. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
151
            $thisGroup['projects'] = $projects['items'];
152
            $groups[] = $thisGroup;
153
        }
154
155
        $layout->groups = $groups;
156
    }
157
158
    /**
159
     * Check whether we should skip auth (because it is disabled).
160
     *
161
     * @return bool
162
     */
163
    protected function shouldSkipAuth()
0 ignored issues
show
Coding Style introduced by
shouldSkipAuth uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
164
    {
165
        $config = b8\Config::getInstance();
166
        $state = (bool) $config->get('phpci.authentication_settings.state', false);
167
        $userId = $config->get('phpci.authentication_settings.user_id', 0);
168
169
        if (false !== $state && 0 != (int) $userId) {
170
            $user = b8\Store\Factory::getStore('User')
171
                ->getByPrimaryKey($userId);
172
173
            if ($user) {
174
                $_SESSION['phpci_user'] = $user;
175
176
                return true;
177
            }
178
        }
179
180
        return false;
181
    }
182
}
183