Completed
Push — master ( e6cd79...15515b )
by Mike
02:12
created

SugarAPI::setInstance()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 9
nc 8
nop 1
1
<?php
2
3
namespace SugarAPI\SDK;
4
5
use SugarAPI\SDK\Exception\InitializationFailure;
6
use SugarAPI\SDK\Exception\InvalidEntryPoint;
7
use SugarAPI\SDK\Exception\AuthenticationException;
8
use SugarAPI\SDK\Exception\SDKException;
9
10
class SugarAPI {
11
12
    const API_URL = '/rest/v10/';
13
14
    protected static $_DEFAULTS = array();
15
16
    protected $instance;
17
    protected $url;
18
19
    protected $authOptions = array(
20
        'grant_type' => 'password',
21
        'username' => '',
22
        'password' => '',
23
        'client_id' => '',
24
        'client_secret' => '',
25
        'platform' => ''
26
    );
27
    protected $authToken;
28
29
    private $entryPoints = array();
30
31
    public function __construct($instance='',array $authOptions = array()){
32
        $this->loadDefaults();
33
        if (!empty($instance)){
34
            $this->setInstance($instance);
35
        }
36
        if (!empty($authOptions)){
37
            $this->setAuthOptions($authOptions);
38
        }
39
        $this->registerSDKEntryPoints();
40
    }
41
42
    protected function loadDefaults(){
43
        include __DIR__ .DIRECTORY_SEPARATOR.'defaults.php';
44
        if (isset($defaults)) {
0 ignored issues
show
Bug introduced by
The variable $defaults seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
45
            static::$_DEFAULTS = $defaults;
46
            if (isset($defaults['instance'])){
47
                $this->setInstance($defaults['instance']);
48
            }
49
            if (isset($defaults['auth']) && is_array($defaults['auth'])){
50
                $this->setAuthOptions($defaults['auth']);
51
            }
52
        }
53
    }
54
55
    public function setAuthOptions(array $options){
56
        foreach($this->authOptions as $key => $value){
57
            if (isset($options[$key])){
58
                $this->authOptions[$key] = $options[$key];
59
            }
60
        }
61
    }
62
63
    protected function registerSDKEntryPoints(){
64
        require __DIR__ .DIRECTORY_SEPARATOR.'EntryPoint' .DIRECTORY_SEPARATOR.'registry.php';
65
        foreach($entryPoints as $funcName => $className){
0 ignored issues
show
Bug introduced by
The variable $entryPoints does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
66
            $className = "SugarAPI\\SDK\\EntryPoint\\".$className;
67
            $this->registerEntryPoint($funcName,$className);
68
        }
69
    }
70
71
    public function registerEntryPoint($funcName,$className){
72
        if (isset($this->entryPoints[$funcName])){
73
            throw new SDKException('SDK method already defined. Method '.$funcName.' references Class '.$className);
74
        }
75
        $this->entryPoints[$funcName] = $className;
76
    }
77
78
    public function __call($name,$params){
79
        if (array_key_exists($name,$this->entryPoints)){
80
            $Class = $this->entryPoints[$name];
81
            $EntryPoint = new $Class($this->url,$params);
82
83
            if ($EntryPoint->authRequired()){
84
                if (isset($this->authToken)) {
85
                    $EntryPoint->getRequest()->addHeader('OAuth-Token', $this->authToken->access_token);
86
                }else{
87
                    throw new AuthenticationException('no_auth');
88
                }
89
            }
90
            return $EntryPoint;
91
        }else{
92
            throw new SDKException('Method '.$name.', is not a registered method of the SugarAPI SDK');
93
        }
94
    }
95
    public function login(){
96
        if (empty($this->authOptions['username']) || empty($this->authOptions['password'])){
97
            throw new AuthenticationException("Username or Password was not provided.");
98
        }
99
        $EP = $this->accessToken();
0 ignored issues
show
Documentation Bug introduced by
The method accessToken does not exist on object<SugarAPI\SDK\SugarAPI>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
100
        $response = $EP->data($this->authOptions)->execute()->getResponse();
101
        if ($response->getStatus()=='200'){
102
            $this->authToken = $response->getBody();
103
        }else{
104
            throw new AuthenticationException($response->getBody());
105
        }
106
    }
107
    public function setInstance($instance){
108
        if (strpos("https",$instance)!==FALSE){
109
            $this->secure = TRUE;
0 ignored issues
show
Bug introduced by
The property secure does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
110
        }
111
        if (strpos("http",$instance)===FALSE){
112
            $instance = "http://".$instance;
113
        }
114
        if (strpos("rest/v10",$instance)!==FALSE){
115
            $instance = str_replace("rest/v10","",$instance);
116
        }
117
        $this->instance = $instance;
118
        $this->url = rtrim($this->instance,"/").self::API_URL;
119
    }
120
    public function getURL(){
121
        return $this->url;
122
    }
123
    public function getToken(){
124
        return $this->authToken;
125
    }
126
    public function getAuthOptions(){
127
        return $this->authOptions;
128
    }
129
}