Completed
Push — master ( 1f7ab5...0b80d4 )
by Denis
05:55
created

Security::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 5
cp 0.8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2.032
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
     * Домен тестового сервера API
34
     */
35
    const TEST_API_HOST = 'http://openapi.landev.ru';
36
37
    /**
38
     * Домен дев сервера API
39
     */
40
    const DEV_API_HOST = 'http://eop.local';
41
42
    /**
43
     * Домен продакшен сервера ЭБС
44
     */
45
    const PROD_EBS_HOST = 'https://e.lanbook.com';
46
47
    /**
48
     * Домен тестового сервера ЭБС
49
     */
50
    const TEST_EBS_HOST = 'http://ebs.landev.ru';
51
52
    /**
53
     * Домен дев сервера ЭБС
54
     */
55
    const DEV_EBS_HOST = 'http://ebs.local';
56
57
    /**
58
     * Инстанс клиента API
59
     *
60
     * @var Client
61
     */
62
    private $client;
63
64
    /**
65
     * Конструктор экземпляра класса Security
66
     *
67
     * Экземпляр класса Security нужен для получения публичных ресурсов по закрытому токену (Например url для автологина)
68
     *
69
     * @param Client $client Истанс клиента
70
     *
71
     * Пример:
72
     * ```php
73
     *      $token = '7c0c2193d27108a509abd8ea84a8750c82b3a520'; // токен для тестового подписчика
74
     *
75
     *      $client = new Client($token); // инициализация клиента
76
     *
77
     *      $security = new Security($client); // инициализация объекта SDK Security
78
     * ```
79
     *
80
     * @throws Exception
81
     */
82 1
    public function __construct(Client $client)
83
    {
84 1
        if (!$client) {
85
            throw new Exception('Клиент не инициализирован');
86
        }
87
88 1
        $this->client = $client;
89 1
    }
90
91
    /**
92
     * Получение хоста API-сервера
93
     *
94
     * Пример:
95
     * ```php
96
     *      $apiHost = \Lan\Ebs\Sdk\Security::getApiHost();
97
     * ```
98
     *
99
     * @return string Хост сервера API
100
     *
101
     * Пример:
102
     * ```
103
     *      https://openapi.e.lanbook.com
104
     * ```
105
     */
106 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...
107
    {
108 14
        return isset($_SERVER['USER']) && $_SERVER['USER'] == 'dp' ? Security::DEV_API_HOST : Security::PROD_API_HOST;
109
    }
110
111
    /**
112
     * Получение хоста сервера ЭБС
113
     *
114
     * @return string
115
     */
116
    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...
117
    {
118
        return isset($_SERVER['USER']) && $_SERVER['USER'] == 'dp' ? Security::DEV_EBS_HOST : Security::PROD_EBS_HOST;
119
    }
120
121
    /**
122
     * Получение url для автологина
123
     *
124
     * @param int|string $uid Уникальные идентификатора прользователя на стороне клиента
125
     * @param string $fio ФИО (необязательно)
126
     * @param string $email Электронный адрес (необязательно)
127
     * @param string $redirect Url для редиректа на сайте ЭБС
128
     *
129
     * @return mixed
130
     *
131
     * @throws Exception
132
     */
133 1
    public function getAutologinUrl($uid, $fio = null, $email = null, $redirect = null)
134
    {
135 1
        return $this->client->getResponse(
136 1
            $this->getUrl(__FUNCTION__),
137
            [
138 1
                'uid' => $uid,
139 1
                'time' => date('YmdHi'),
140 1
                'fio' => $fio,
141 1
                'email' => $email,
142 1
                'redirect' => $redirect
143
            ]
144 1
        )['data'];
145
    }
146
147
    /**
148
     * Получение данных для запроса через API
149
     *
150
     * @param string $method Http-метод запроса
151
     * @param array $params Параметры для формирования урла
152
     *
153
     * @return array
154
     *
155
     * @throws Exception
156
     */
157 1
    public function getUrl($method, array $params = [])
158
    {
159
        switch ($method) {
160 1
            case 'getAutologinUrl':
161
                return [
162 1
                    'url' => '/1.0/security/autologinUrl',
163
                    'method' => 'GET',
164
                    'code' => 200
165
                ];
166
            default:
167
                throw new Exception('Route for ' . $method . ' not found');
168
        }
169
    }
170
}