Completed
Push — master ( 93e656...cbee39 )
by Denis
03:12
created

Security::getUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
dl 0
loc 13
ccs 3
cts 4
cp 0.75
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 9
nc 2
nop 2
crap 2.0625
1
<?php
2
/**
3
 * Class Security
4
 *
5
 * @author       Denis Shestakov <[email protected]>
6
 * @copyright    Copyright (c) 2017, Lan Publishing
7
 * @license      MIT
8
 */
9
10
namespace Lan\Ebs\Sdk;
11
12
use Exception;
13
14
/**
15
 * Класс для получения публичных ресурсов по закрытому токену
16
 *
17
 * @package      Lan\Ebs
18
 * @subpackage   Sdk
19
 */
20
final class Security implements Common
21
{
22
    /**
23
     * Токен для тестового доступа
24
     */
25
    const TEST_TOKEN = '7c0c2193d27108a509abd8ea84a8750c82b3a520';
26
27
    /**
28
     * Домен продакшен сервера API
29
     */
30
    const PROD_API_HOST = 'https://openapi.e.lanbook.com';
31
32
    /**
33
     * Домен продакшен сервера ЭБС
34
     */
35
    const PROD_EBS_HOST = 'https://e.lanbook.com';
36
37
    /**
38
     * Инстанс клиента API
39
     *
40
     * @var Client
41
     */
42
    private $client;
43
44
    /**
45
     * Конструктор экземпляра класса Security
46
     *
47
     * Экземпляр класса Security нужен для получения публичных ресурсов по закрытому токену (Например url для автологина)
48
     *
49
     * @param Client $client Истанс клиента
50
     *
51
     * Пример:
52
     * ```php
53
     *      $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
54
     *
55
     *      $client = new Client($token); // инициализация клиента
56
     *
57
     *      $security = new Security($client); // инициализация объекта SDK Security
58
     * ```
59
     *
60
     * @throws Exception
61
     */
62 1
    public function __construct(Client $client)
63
    {
64 1
        if (!$client) {
65
            throw new Exception('Клиент не инициализирован');
66
        }
67
68 1
        $this->client = $client;
69 1
    }
70
71
    /**
72
     * Получение хоста API-сервера
73
     *
74
     * Пример:
75
     * ```php
76
     *      $apiHost = \Lan\Ebs\Sdk\Security::getApiHost();
77
     * ```
78
     *
79
     * @return string Хост сервера API
80
     *
81
     * Пример:
82
     * ```
83
     *      https://openapi.e.lanbook.com
84
     * ```
85
     */
86 14
    public static function getApiHost()
0 ignored issues
show
Coding Style introduced by
getApiHost 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...
87
    {
88 14
        return isset($_SERVER['USER']) && $_SERVER['USER'] == 'dp' ? 'http://eop.local' : Security::PROD_API_HOST;
89
    }
90
91
    /**
92
     * Получение хоста сервера ЭБС
93
     *
94
     * @return string
95
     */
96
    public static function getEbsHost()
0 ignored issues
show
Coding Style introduced by
getEbsHost 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...
97
    {
98
        return isset($_SERVER['USER']) && $_SERVER['USER'] == 'dp' ? 'http://ebs.local' : Security::PROD_EBS_HOST;
99
    }
100
101
    /**
102
     * Получение url для автологина
103
     *
104
     * @param int|string $uid Уникальные идентификатора прользователя на стороне клиента
105
     * @param string $fio ФИО (необязательно)
106
     * @param string $email Электронный адрес (необязательно)
107
     * @param string $redirect Url для редиректа на сайте ЭБС
108
     *
109
     * @return mixed
110
     *
111
     * @throws Exception
112
     */
113 1
    public function getAutologinUrl($uid, $fio = null, $email = null, $redirect = null)
114
    {
115 1
        return $this->client->getResponse(
116 1
            $this->getUrl(__FUNCTION__),
117
            [
118 1
                'uid' => $uid,
119 1
                'time' => date('YmdHi'),
120 1
                'fio' => $fio,
121 1
                'email' => $email,
122 1
                'redirect' => $redirect
123
            ]
124 1
        )['data'];
125
    }
126
127
    /**
128
     * Получение данных для запроса через API
129
     *
130
     * @param string $method Http-метод запроса
131
     * @param array $params Параметры для формирования урла
132
     *
133
     * @return array
134
     *
135
     * @throws Exception
136
     */
137 1
    public function getUrl($method, array $params = [])
138
    {
139
        switch ($method) {
140 1
            case 'getAutologinUrl':
141
                return [
142 1
                    'url' => '/1.0/security/autologinUrl',
143
                    'method' => 'GET',
144
                    'code' => 200
145
                ];
146
            default:
147
                throw new Exception('Route for ' . $method . ' not found');
148
        }
149
    }
150
}