ProviderWrapper::getErrorMethodCallMessage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api\Providers\Core;
4
5
use seregazhuk\PinterestBot\Exceptions\AuthRequired;
6
use seregazhuk\PinterestBot\Exceptions\InvalidRequest;
7
8
/**
9
 * Class ProviderWrapper is used to check for logged in status before any
10
 * provider method is being invoked.
11
 *
12
 * @package seregazhuk\PinterestBot\Api\Providers\Core
13
 */
14
class ProviderWrapper
15
{
16
    /**
17
     * @var Provider
18
     */
19
    protected $provider;
20
21
    /**
22
     * @param Provider|object $provider
23
     */
24
    public function __construct(Provider $provider)
25
    {
26
        $this->provider = $provider;
27
    }
28
29
    /**
30
     * Proxies a call to a provider with a login check
31
     * before every method if needed.
32
     *
33
     * @param $method
34
     * @param $arguments
35
     * @throws AuthRequired
36
     * @throws InvalidRequest
37
     * @return mixed|null
38
     */
39
    public function __call($method, $arguments)
40
    {
41
        if (method_exists($this->provider, $method)) {
42
            $this->checkMethodForLoginRequired($method);
43
44
            return call_user_func_array([$this->provider, $method], $arguments);
45
        }
46
47
        $errorMessage = $this->getErrorMethodCallMessage($method, "Method $method does'n exist.");
48
        throw new InvalidRequest($errorMessage);
49
    }
50
51
    /**
52
     * Checks if method requires login and if true,
53
     * checks logged in status.
54
     *
55
     * @param $method
56
     *
57
     * @throws AuthRequired if is not logged in
58
     */
59
    protected function checkMethodForLoginRequired($method)
60
    {
61
        $isLoggedIn = $this->provider->isLoggedIn();
62
        $methodRequiresLogin = $this->provider->checkMethodRequiresLogin($method);
63
64
        if ($methodRequiresLogin && !$isLoggedIn) {
65
            $errorMessage = $this->getErrorMethodCallMessage($method, 'You must log in before.');
66
            throw new AuthRequired($errorMessage);
67
        }
68
    }
69
70
    /**
71
     * @param string $method
72
     * @param string $message
73
     * @return string
74
     */
75
    protected function getErrorMethodCallMessage($method, $message)
76
    {
77
        $providerClass = get_class($this->provider);
78
79
        return "Error calling $providerClass::$method method. $message";
80
    }
81
}
82