Completed
Pull Request — master (#6)
by Hector
03:06
created

Resource::toArray()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 14
rs 9.4285
cc 3
eloc 8
nc 3
nop 0
1
<?php
2
3
namespace Hborras\TwitterAdsSDK\TwitterAds;
4
5
use Hborras\TwitterAdsSDK\ServerError;
6
use Hborras\TwitterAdsSDK\TwitterAdsException;
7
use Hborras\TwitterAdsSDK\Arrayable;
8
9
/**
10
 * Created by PhpStorm.
11
 * User: hborras
12
 * Date: 2/04/16
13
 * Time: 12:17.
14
 */
15
abstract class Resource implements Arrayable
16
{
17
    use \Hborras\TwitterAdsSDK\DateTime\DateTimeFormatter;
18
19
    const RESOURCE            = '';
20
    const RESOURCE_COLLECTION = '';
21
    const RESOURCE_ID_REPLACE = '{id}';
22
    const RESOURCE_REPLACE    = '{account_id}';
23
24
    /** @var  Account $account */
25
    private $account;
26
    private $properties = [];
27
28
    abstract public function getId();
29
30
    /**
31
     * Automatically set the account if this class is not an account
32
     * Resource constructor.
33
     * @param Account|null $account
34
     */
35
    public function __construct(Account $account = null)
36
    {
37
        if (get_class($this) != Account::class) {
38
            $this->setAccount($account);
39
        }
40
    }
41
42
    /**
43
     * Returns a Cursor instance for a given resource.
44
     *
45
     * @param $params
46
     *
47
     * @return Cursor
48
     */
49
    public function all($params = [])
50
    {
51
        $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE_COLLECTION);
52
        $request = $this->account->getTwitterAds()->get($resource, $params);
53
54
        return new Cursor($this, $this->account, $request, $params);
55
    }
56
57
    /**
58
     * Returns an object instance for a given resource.
59
     *
60
     * @param string $id
61
     * @param $params
62
     *
63
     * @return Resource
64
     */
65
    public function load($id, $params = [])
66
    {
67
        $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE);
68
        $resource = str_replace(static::RESOURCE_ID_REPLACE, $id, $resource);
69
        $request = $this->account->getTwitterAds()->get($resource, $params);
70
71
        return $this->fromResponse($request->data);
72
    }
73
74
    /**
75
     * Reloads all attributes for the current object instance from the API.
76
     *
77
     * @param $params
78
     *
79
     * @return Resource
80
     *
81
     * @throws TwitterAdsException
82
     */
83
    public function reload($params)
84
    {
85
        if (!$this->getId()) {
86
            throw new ServerError(TwitterAdsException::SERVER_ERROR, "Error loading entity", null, null);
87
        }
88
89
        $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE);
90
        $resource = str_replace(static::RESOURCE_ID_REPLACE, $this->getId(), $resource);
91
        $request = $this->account->getTwitterAds()->get($resource, $params);
92
93
        return $this->fromResponse($request->data);
94
    }
95
96
    /**
97
     * Populates a given objects attributes from a parsed JSON API response.
98
     * This helper handles all necessary type coercions as it assigns attribute values.
99
     *
100
     * @param $response
101
     *
102
     * @return $this
103
     */
104
    public function fromResponse($response)
105
    {
106
        foreach (get_object_vars($response) as $key => $value) {
107
            if (($key == 'created_at' || $key == 'updated_at' || $key == 'start_time' || $key == 'end_time' || $key == 'timezone_switch_at') && !is_null($value)) {
108
                $this->$key = $this->toDateTimeImmutable($value);
109
            } else {
110
                $this->$key = $value;
111
            }
112
        }
113
114
        return $this;
115
    }
116
117
    /**
118
     * Generates a Hash of property values for the current object. This helper
119
     * handles all necessary type coercions as it generates its output.
120
     */
121
    public function toParams()
122
    {
123
        $params = [];
124
        foreach ($this->getProperties() as $property) {
125
            if (is_null($this->$property)) {
126
                continue;
127
            }
128
            if ($this->$property instanceof DateTime) {
0 ignored issues
show
Bug introduced by
The class Hborras\TwitterAdsSDK\TwitterAds\DateTime does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
129
                $params[$property] = $this->$property->format('c');
130
            } elseif (is_array($this->$property)) {
131
                $params[$property] = implode(',', $this->$property);
132
            } elseif (is_bool($this->$property)) {
133
                $params[$property] = $this->$property ? 'true' : 'false';
134
            } else {
135
                $params[$property] = strval($this->$property);
136
            }
137
        }
138
139
        return $params;
140
    }
141
142
    public function validateLoaded()
143
    {
144
        if (!$this->getId()) {
145
            throw new ServerError(TwitterAdsException::SERVER_ERROR, "Error loading entity", null, null);
146
        }
147
    }
148
149
    public function toArray()
150
    {
151
        $data = [];
152
        $vars = get_object_vars($this);
153
154
        foreach ($vars as $key => $var) {
155
            if ($var instanceof $this) {
156
                continue;
157
            }
158
            $data[$key] = $var;
159
        }
160
161
        return $data;
162
    }
163
164
    public function loadResource(Account $account, $id = '', $params = [])
165
    {
166
        $this->setAccount($account);
167
        $account->validateLoaded();
168
        if ($id != '') {
169
            return $this->load($id, $params);
170
        } else {
171
            return $this->all($params);
172
        }
173
    }
174
175
    /**
176
     * Saves or updates the current object instance depending on the
177
     * presence of `object->getId()`.
178
     */
179
    public function save()
180
    {
181
        if ($this->getId()) {
182
            $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE);
183
            $resource = str_replace(static::RESOURCE_ID_REPLACE, $this->getId(), $resource);
184
            $request = $this->account->getTwitterAds()->put($resource, $this->toParams());
185
        } else {
186
            $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE_COLLECTION);
187
            $request = $this->account->getTwitterAds()->post($resource, $this->toParams());
188
        }
189
190
        return $this->fromResponse($request->data);
191
    }
192
193
    /**
194
     * Deletes the current object instance depending on the
195
     * presence of `object->getId()`.
196
     */
197
    public function delete()
198
    {
199
        $resource = str_replace(static::RESOURCE_REPLACE, $this->account->getId(), static::RESOURCE);
200
        $resource = str_replace(static::RESOURCE_ID_REPLACE, $this->getId(), $resource);
201
        $request = $this->account->getTwitterAds()->put($resource, $this->toParams());
202
        $this->fromResponse($request->data);
203
    }
204
205
    /**
206
     * @return Account
207
     */
208
    public function getAccount()
209
    {
210
        return $this->account;
211
    }
212
213
    /**
214
     * @param Account $account
215
     */
216
    public function setAccount($account = null)
217
    {
218
        $this->account = $account;
219
    }
220
221
    /**
222
     * @return array
223
     */
224
    public function getProperties()
225
    {
226
        return $this->properties;
227
    }
228
}
229