Completed
Push — master ( e8b212...5db87b )
by Stephen
03:28
created

StarCitizens::getCallParams()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 15
ccs 10
cts 10
cp 1
rs 9.4285
cc 2
eloc 11
nc 2
nop 4
crap 2
1
<?php
2
3
namespace StarCitizen;
4
5
use StarCitizen\Models\Model;
6
use StarCitizen\Client\StarCitizensClient;
7
8
/**
9
 * Class StarCitizens
10
 * @package StarCitizen
11
 *
12
 * @method accounts($id, $profileType = false, $cache = false, $raw = false) Get accounts system results
13
 * @method organizations($id, $profileType = false, $cache = false, $raw = false) Get org system results
14
 */
15
final class StarCitizens
16
{
17
    /**
18
     * @var bool|StarCitizensClient The client object
19
     */
20
    private static $client = false;
21
22
    /**
23
     * @var array  The config for the StarCitizens todo move this to a separate file
24
     */
25
    private $systems = [
26
        "accounts" => [
27
            "base_action" => "full_profile",
28
            "actions" => [
29
                "full_profile" => '\Profile',
30
                "threads" => ['\Thread', '', 'thread_id'],
31
                "posts" => ['\Post', 'post', 'post_id'],
32
            ]
33
        ],
34
        "organizations" => [
35
            "base_action" => "single_organization",
36
            "actions" => [
37
                "single_organization" => '\Organisation',
38
                "organization_members" => ['\OrgMember', '', 'handle']
39
            ]
40
        ],
41
    ];
42
43
    /**
44
     * StarCitizens constructor.
45
     */
46 20
    public function __construct()
47 1
    {
48 20
        self::setupClient();
49 20
    }
50
51
    /**
52
     * Find an entity based on id and return the correct model or raw json output
53
     *
54
     * @param $id
55
     * @param $system
56
     * @param $profileType
57
     * @param bool $raw
58
     * @param bool $cache
59
     * @return bool|mixed
60
     */
61 19
    private function get($id, $system, $profileType, $raw = false, $cache = false)
62
    {
63 19
        $response = json_decode(
64
            self::$client
65 19
                ->getResult(
66 19
                    $this->getCallParams($id, $system, $profileType, $cache)
67 19
                )
68 19
                ->getBody()
69 19
                ->getContents(),
70
            true
71 19
        );
72
73 19
        return $this->checkResponse($response, $this->systems[$system]['actions'][$profileType], $raw);
74
    }
75
76
    /**
77
     * Returns the params needed for an API call
78
     *
79
     * @param $id
80
     * @param $system
81
     * @param $profileType
82
     * @param $cache
83
     * @return array
84
     */
85 19
    private function getCallParams($id, $system, $profileType, $cache)
86
    {
87 19
        $cache = ($cache === true) ? "cache" : "live";
88
89
        return [
90 19
            'api_source' => $cache,
91 19
            'system' => $system,
92 19
            'action' => $profileType,
93 19
            'target_id' => $id,
94 19
            'expedite' => '0',
95 19
            'format' => 'json',
96 19
            'start_page' => '1',
97
            'end_page' => '5'
98 19
        ];
99
    }
100
101
    /**
102
     * Checks the response for success messages and returns the raw response or model
103
     *
104
     * @param $response
105
     * @param $profileType
106
     * @param $raw
107
     *
108
     * @return bool|mixed
109
     */
110 19
    private function checkResponse($response, $profileType, $raw)
111
    {
112 19
        if ($response['request_stats']['query_status'] == "success") {
113 19
            if ($raw === true) {
114 1
                return $response;
115
            } else {
116 19
                return $this->fillModel($profileType, $response['data']);
117
            }
118
        }
119
120 3
        return false;
121
    }
122
123
    /**
124
     * Setup the client
125
     */
126 20
    private static function setupClient()
127
    {
128 20
        if (self::$client === false) {
129 1
            self::$client = new StarCitizensClient();
130 1
        }
131 20
    }
132
133
    /**
134
     * Fills our model in with the provided data or sends the data to a store
135
     *
136
     * @param $model
137
     * @param $fillData
138
     *
139
     * @return Model
140
     */
141 19
    private function fillModel($model, $fillData)
142
    {
143 19
        if (is_array($model)) {
144 15
            list($className, $dataRoot, $idName) =$model;
145 15
            $object = new \ReflectionClass('StarCitizen\Models\Store');
146 15
            return $object->newInstance($fillData, $className, $dataRoot, $idName);
147
        } else {
148 8
            $object = new \ReflectionClass('StarCitizen\Models' . $model);
149 8
            return $object->newInstance($fillData);
150
        }
151
    }
152
153
    /**
154
     * Magic call function based on the config information
155
     *
156
     * @param $name
157
     * @param $arguments
158
     * @return bool|mixed
159
     * @throws \Exception
160
     */
161 20
    public function __call($name, $arguments)
162
    {
163 20
        if (array_key_exists($name, $this->systems)) {
164 19
            return $this->doCall($name, $arguments);
165
        }
166
167 1
        throw new \Exception("Method {$name} not found");
168
    }
169
170
    /**
171
     * This is the real call function
172
     *
173
     * @param $system
174
     * @param array $arguments
175
     * @return bool|mixed
176
     */
177 19
    private function doCall($system, array $arguments = [])
178
    {
179 19
        $id = '';
180 19
        $cache = false;
181 19
        $raw = false;
182 19
        $action = "";
183
184 19
        $fixedArguments = $this->standardGetArguments($arguments);
185 19
        extract($fixedArguments, EXTR_OVERWRITE);
186 19
        $action = ($action == "") ? $this->systems[$system]['base_action'] : $action;
187 19
        return $this->get($id, $system, $action, $raw, $cache);
188
    }
189
190
    /**
191
     * Get the standard arguments for a find call and checks that we
192
     * have the correct arguments passed to the magic function
193
     *
194
     * @param array $arguments
195
     * @return array
196
     */
197 19
    private function standardGetArguments(array $arguments)
198
    {
199
200
        $defaults = [
201 19
            'id' => '',
202 19
            'action' => '',
203 19
            'raw' => false,
204 19
            'cache' => false,
205 19
        ];
206
207 19
        $varNames = array_keys($defaults);
208
209 19
        for ($argumentCount = 0; $argumentCount < 4; $argumentCount++) {
210 19
            if (array_key_exists($argumentCount, $arguments)) {
211 19
                $defaults[$varNames[$argumentCount]] = $arguments[$argumentCount];
212 19
            }
213 19
        }
214
        
215 19
        return $defaults;
216
    }
217
218
    /**
219
     * Allows our functions to be called statically, this is a bit hacky tbh.
220
     * 
221
     * @param $name
222
     * @param $arguments
223
     * @return bool|mixed
224
     * @throws \Exception
225
     */
226 1
    public static function __callStatic($name, $arguments)
227
    {
228 1
        $starCitizens = new StarCitizens();
229 1
        return $starCitizens->__call($name, $arguments);
230
    }
231
}