Client   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 85
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 7
c 4
b 0
f 0
lcom 1
cbo 1
dl 0
loc 85
ccs 27
cts 27
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __call() 0 14 3
A getAuthorizationUrl() 0 11 1
A createResourceInstance() 0 13 2
1
<?php
2
3
namespace Habrahabr\Api;
4
5
use Habrahabr\Api\Exception\ResourceNotExistsException;
6
use Habrahabr\Api\HttpAdapter\HttpAdapterInterface;
7
use Habrahabr\Api\Resources\ResourceInterface;
8
9
/**
10
 * Class Client
11
 *
12
 * Основной класс для получения доступа к классам Habrahabr Api ресурсов
13
 *
14
 * @package Habrahabr\Api
15
 * @version 0.1.5
16
 * @author thematicmedia <[email protected]>
17
 * @link https://tmtm.ru/
18
 * @link https://habrahabr.ru/
19
 * @link https://github.com/thematicmedia/habrahabr_api
20
 * @method Resources\UserResource getUserResource()
21
 * @method Resources\SearchResource getSearchResource()
22
 * @method Resources\PollResource getPollResource()
23
 * @method Resources\PostResource getPostResource()
24
 * @method Resources\HubResource getHubResource()
25
 * @method Resources\FeedResource getFeedResource()
26
 * @method Resources\FlowResource getFlowResource()
27
 * @method Resources\CompanyResource getCompanyResource()
28
 * @method Resources\CommentsResource getCommentsResource()
29
 * @method Resources\TrackerResource getTrackerResource()
30
 * @method Resources\SettingsResource getSettingsResource()
31
 *
32
 * For the full copyright and license information, please view the LICENSE
33
 * file that was distributed with this source code.
34
 */
35
class Client
36
{
37
    /**
38
     * @type HttpAdapterInterface|null Экземпляр Habrahabr Api HTTP адаптера
39
     */
40
    protected $adapter = null;
41
42
    /**
43
     * @type array Контейнер для хранения экземпляров классов ресурсов
44
     */
45
    protected $resources = [];
46
47
    /**
48
     * Client constructor.
49
     *
50
     * @param HttpAdapterInterface $adapter Экземпляр Habrahabr Api HTTP адаптера
51
     */
52 12
    public function __construct(HttpAdapterInterface $adapter)
53
    {
54 12
        $this->adapter = $adapter;
55 12
    }
56
57
    /**
58
     * Возращает экземпляр ресурса для работы с Habrahabr Api
59
     *
60
     * @param string $name Название метода по шаблону get[Ресурс]Resource
61
     * @param array $arguments Список передаваемых экземпляру аргументов
62
     * @return ResourceInterface
63
     * @throws ResourceNotExistsException
64
     */
65 11
    public function __call($name, $arguments)
66
    {
67 11
        if (preg_match('#^get([\w]+)Resource$#i', $name, $m)) {
68 10
            $name = ucfirst($m[1]) . 'Resource';
69
70 10
            if (!isset($this->resources[$name])) {
71 10
                $this->resources[$name] = $this->createResourceInstance($name);
72 9
            }
73
74 9
            return $this->resources[$name];
75
        }
76
77 1
        throw new ResourceNotExistsException('Method ' . $name . ' not implemented');
78
    }
79
80
    /**
81
     * Возращает URL для OAuth авторизации Habrahabr Api
82
     *
83
     * @param string $redirect_uri OAuth Redirect URL
84
     * @param string $response_type OAuth Response type
85
     * @return string
86
     */
87 1
    public function getAuthorizationUrl($redirect_uri, $response_type = 'code')
88
    {
89 1
        return sprintf('https://%s/auth/o/login/?%s',
90 1
            str_replace('api.', '', parse_url($this->adapter->getEndpoint(), PHP_URL_HOST)),
91 1
            http_build_query([
92 1
                'response_type' => $response_type,
93 1
                'client_id' => $this->adapter->getClient(),
94 1
                'redirect_uri' => $redirect_uri,
95 1
            ])
96 1
        );
97
    }
98
99
    /**
100
     * Создания экземпляра ресурса для работы с Habrahabr Api
101
     *
102
     * @param string $name Название класса для инициализации
103
     * @return ResourceInterface
104
     * @throws ResourceNotExistsException
105
     */
106 10
    protected function createResourceInstance($name)
107
    {
108 10
        $classname = '\\Habrahabr\\Api\\Resources\\' . $name;
109
110 10
        if (!class_exists($classname)) {
111 1
            throw new ResourceNotExistsException($name);
112
        }
113
114 9
        $resource = new $classname();
115 9
        $resource->setAdapter($this->adapter);
116
117 9
        return $resource;
118
    }
119
}
120