AuthBasic::by()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 15
cts 15
cp 1
rs 9.52
c 0
b 0
f 0
cc 4
nc 6
nop 2
crap 4
1
<?php
2
/*
3
 * This file is part of the Respect\Rest package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
9
namespace Respect\Rest\Routines;
10
11
use Respect\Rest\Request;
12
13
class AuthBasic extends AbstractRoutine implements ProxyableBy
14
{
15
    public $realm;
16
17 7
    public function __construct($realm, $callback)
18
    {
19 7
        $this->realm = $realm;
20 7
        parent::__construct($callback);
21 7
    }
22
23 7
    public function by(Request $request, $params)
0 ignored issues
show
Coding Style introduced by
by uses the super-global variable $_SERVER 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...
24
    {
25 7
        $callbackResponse = false;
26
27 7
        if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
28 3
            $callbackResponse = call_user_func_array(
29 3
                $this->callback,
30 3
                array_merge(explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))), $params)
31
            );
32 5
        } elseif (isset($_SERVER['PHP_AUTH_USER'])) {
33 3
            $callbackResponse = call_user_func_array(
34 3
                $this->callback,
35 3
                array_merge(array($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']), $params)
36
            );
37
        }
38
39 7
        if ($callbackResponse === false) {
40 3
            header('HTTP/1.1 401');
41 3
            header("WWW-Authenticate: Basic realm=\"{$this->realm}\"");
42
43 3
            return call_user_func($this->callback, null, null);
44
        }
45
46 4
        return $callbackResponse;
47
    }
48
}
49