-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathAbstractResource.php
More file actions
647 lines (561 loc) · 18.3 KB
/
AbstractResource.php
File metadata and controls
647 lines (561 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
<?php
/**
* @package Zammad API Client
* @author Jens Pfeifer <jens.pfeifer@znuny.com>
*/
namespace ZammadAPIClient\Resource;
use ZammadAPIClient\Exception\AlreadyFetchedObjectException;
abstract class AbstractResource
{
// API client used for requests to Zammad.
private $client;
// Data returned by response from Zammad.
private $remote_data = [];
// Values that were set by the API client to be saved in Zammad later by a call to save().
private $values = [];
// Error message of last response from Zammad.
private $error = null;
/**
* @param object $client ZammadAPIClient object
*/
public function __construct( \ZammadAPIClient\Client $client )
{
$this->client = $client;
}
/**
* Returns the ZammadAPIClient object.
*
* @return object ZammadAPIClient object
*/
protected function getClient()
{
return $this->client;
}
/**
* Sets remote data that was returned from Zammad.
*
* @param array $remote_data Data to set.
*
* @return object
*/
protected function setRemoteData( array $remote_data = [] )
{
$this->remote_data = $remote_data;
return $this;
}
/**
* Clears remote data that was returned by Zammad.
*
* @return object This object
*/
protected function clearRemoteData()
{
$this->remote_data = [];
return $this;
}
/**
* Fetches remote data that was returned by Zammad.
*
* @return array Array with the object's data. Might be empty.
*/
protected function getRemoteData()
{
return $this->remote_data;
}
/**
* Sets local values that will be saved later in Zammad by a call to save().
*
* Already set values will be merged with the ones given.
* If you want to completely discard the existing values,
* call clearValues() before setValues().
*
* @param array $values Values to set (key-value-pairs).
*
* @return object This object
*/
public function setValues( array $values )
{
$this->values = array_merge( $this->values, $values );
return $this;
}
/**
* Sets a single local value that will be saved later in Zammad by a call to save().
*
* @param string $key Key of value to set.
* @param mixed $value Value to set.
*
* @return object This object
*/
public function setValue( $key, $value )
{
$this->values[$key] = $value;
return $this;
}
/**
* Gets value of object.
*
* First, it's been checked if the key exists in the local values that will be saved later in Zammad
* by a call to save().
*
* If not found, additionally the remote data will be searched for the key. This
* ensures that a value is being returned that hasn't been changed locally.
*
* @param string $key Key to fetch value for.
*
* @return mixed Value or null if not found. Null could also be the set value.
*/
public function getValue($key)
{
if ( array_key_exists( $key, $this->values ) ) {
return $this->values[$key];
}
$remote_data = $this->getRemoteData();
if ( array_key_exists( $key, $remote_data ) ) {
return $remote_data[$key];
}
return null;
}
/**
* Gets all values of object.
*
* Local values will be merged with remote data, where local values overwrite remote data.
* This ensures that values can be returned that haven't been changed locally.
*
* @return mixed Array with values of object.
*/
public function getValues()
{
$values = array_merge( $this->getRemoteData(), $this->values );
return $values;
}
/**
* Gets all unsaved values of object.
*
* @return mixed Array with unsaved values of object.
*/
public function getUnsavedValues()
{
return $this->values;
}
/**
* Clears local values, which means that the local changes will be discarded and
* a call to save() does not update the remote data.
*
* @return object This object
*/
public function clearUnsavedValues()
{
$this->values = [];
return $this;
}
/**
* Gets the ID of the object.
* This is a convenience method for getValue('id')
*
* @return string ID of this object, if available.
*/
public function getID()
{
return $this->getValue('id');
}
/**
* Checks if there are unsaved local values.
*
* @return boolean True: dirty, false: not dirty.
*/
public function isDirty()
{
return !empty( $this->getUnsavedValues() );
}
/**
* Sets error message from last action.
*
* @param string $error Error
*
* @return object This object
*/
protected function setError( $error )
{
$this->error = $error;
return $this;
}
/**
* Gets error message from last action.
*
* @return string Error from last action
*/
public function getError()
{
return $this->error;
}
/**
* Checks if last action resulted in an error.
*
* @return boolean
*/
public function hasError()
{
return !empty( $this->getError() );
}
/**
* Clears error message from last action.
*
* @return object This object
*/
protected function clearError()
{
$this->error = null;
return $this;
}
/**
* Fetches object data for given object ID.
*
* @param mixed $object_id ID of object to fetch, false value or omit to fetch all objects.
*
* @return object This object.
*/
public function get($object_id)
{
if ( !empty( $this->getValues() ) ) {
throw new AlreadyFetchedObjectException('Object already contains values, get() not possible, use a new object');
}
if ( empty($object_id) ) {
throw new \RuntimeException('Missing object ID');
}
$url = $this->getURL(
'get',
[
'object_id' => $object_id,
]
);
$response = $this->getClient()->get(
$url,
[
'expand' => true,
]
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
}
else {
$this->clearError();
$this->setRemoteData( $response->getData() );
}
return $this;
}
/**
* Fetches object data for all objects of this type.
* Pagination available.
*
* @param integer $page Page of objects, optional, if given, $objects_per_page must also be given.
* @param integer $objects_per_page Number of objects per page, optional, if given, $page must also be given.
*
* @return mixed Returns array of ZammadAPIClient\Resource\... objects
* or this object on failure.
*/
public function all( $page = null, $objects_per_page = null )
{
if ( !empty( $this->getValues() ) ) {
throw new AlreadyFetchedObjectException('Object already contains values, all() not possible, use a new object');
}
if ( isset($page) && $page <= 0 ) {
throw new \RuntimeException('Parameter page must be > 0');
}
if ( isset($objects_per_page) && $objects_per_page <= 0 ) {
throw new \RuntimeException('Parameter objects_per_page must be > 0');
}
if (
( isset($page) && !isset($objects_per_page) )
|| ( !isset($page) && isset($objects_per_page) )
) {
throw new \RuntimeException('Parameters page and objects_per_page must both be given');
}
if ( !isset($page) || !isset($objects_per_page) ) {
return $this->allWithoutPagination();
}
$url_parameters = [
'expand' => true,
];
if ( isset($page) && isset($objects_per_page) ) {
$url_parameters['page'] = $page;
$url_parameters['per_page'] = $objects_per_page;
}
$url = $this->getURL('all');
$response = $this->getClient()->get(
$url,
$url_parameters
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
return $this;
}
$this->clearError();
// Return array of resource objects if no $object_id was given.
// Note: the resource object (this object) used to execute get() will be left empty in this case.
$objects = [];
foreach ( $response->getData() as $object_data ) {
$object = $this->getClient()->resource( get_class($this) );
$object->setRemoteData($object_data);
$objects[] = $object;
}
return $objects;
}
/**
* Fetches object data for all objects of this type.
* This method will be used internally and automatically by all() to automate pagination
* to retrieve all available objects, ignoring the server side limit of fetchable objects.
*
* @return mixed Returns array of ZammadAPIClient\Resource\... objects
* or this object on failure.
*/
private function allWithoutPagination()
{
$page = 1;
$objects_per_page = 100;
$objects = [];
$objects_of_page = [];
do {
$objects_of_page = $this->all( $page, $objects_per_page );
if ( !is_array($objects_of_page) ) {
return $this;
}
$objects = array_merge( $objects, $objects_of_page );
$is_last_page = count($objects_of_page) < $objects_per_page
|| !count($objects_of_page);
$page++;
} while ( !$is_last_page );
return $objects;
}
/**
* Fetches object data for given search term.
* Pagination available.
*
* @param string $search_term Search term.
* @param integer $page Page of objects, optional, if given, $objects_per_page must also be given.
* @param integer $objects_per_page Number of objects per page, optional, if given, $page must also be given.
*
* @return mixed Returns array of ZammadAPIClient\Resource\... objects
* or this object on failure.
*/
public function search( $search_term, $page = null, $objects_per_page = null, $sort_by = null, $order_by = null )
{
if ( !empty( $this->getValues() ) ) {
throw new AlreadyFetchedObjectException('Object already contains values, search() not possible, use a new object');
}
if ( isset($page) && $page <= 0 ) {
throw new \RuntimeException('Parameter page must be a > 0');
}
if ( isset($objects_per_page) && $objects_per_page <= 0 ) {
throw new \RuntimeException('Parameter objects_per_page must be a > 0');
}
if (
( isset($page) && !isset($objects_per_page) )
|| ( !isset($page) && isset($objects_per_page) )
) {
throw new \RuntimeException('Parameters page and objects_per_page must both be given');
}
if ( !isset($page) || !isset($objects_per_page) ) {
return $this->searchWithoutPagination($search_term, $sort_by, $order_by);
}
$url_parameters = [
'expand' => true,
'query' => $search_term,
];
if ( isset($page) && isset($objects_per_page) ) {
$url_parameters['page'] = $page;
$url_parameters['per_page'] = $objects_per_page;
}
if ( isset($sort_by) ) {
$url_parameters['sort_by'] = $sort_by;
}
if ( isset($order_by) ) {
$url_parameters['order_by'] = $order_by;
}
$url = $this->getURL('search');
$response = $this->getClient()->get(
$url,
$url_parameters
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
return $this;
}
$this->clearError();
// Return array of resource objects if no $object_id was given.
// Note: the resource object (this object) used to execute get() will be left empty in this case.
$objects = [];
foreach ( $response->getData() as $object_data ) {
$object = $this->getClient()->resource( get_class($this) );
$object->setRemoteData($object_data);
$objects[] = $object;
}
return $objects;
}
/**
* Fetches object data for searched objects of this type.
* This method will be used internally and automatically by search() to automate pagination
* to retrieve all available objects, ignoring the server side limit of fetchable objects.
*
* @return mixed Returns array of ZammadAPIClient\Resource\... objects
* or this object on failure.
*/
private function searchWithoutPagination($search_term, $sort_by = null, $order_by = null)
{
$page = 1;
$objects_per_page = 100;
$objects = [];
$objects_of_page = [];
do {
$objects_of_page = $this->search( $search_term, $page, $objects_per_page, $sort_by, $order_by );
if ( !is_array($objects_of_page) ) {
return $this;
}
$objects = array_merge( $objects, $objects_of_page );
$is_last_page = count($objects_of_page) < $objects_per_page
|| !count($objects_of_page);
$page++;
} while ( !$is_last_page );
return $objects;
}
/**
* Saves object data. Works for objects that are new or will be updated.
*
* @return mixed Save successful (object reference, $this) or not (false).
*/
public function save()
{
if ( empty( $this->getID() ) ) {
return $this->create();
}
return $this->update();
}
/**
* Creates a new object with the current data.
*
* @return object This object
*/
protected function create()
{
if ( !empty( $this->getID() ) ) {
throw new \Exception('Object already has an ID, create() not possible');
}
if ( !$this->isDirty() ) {
return $this;
}
$url = $this->getURL('create');
$response = $this->getClient()->post(
$url,
$this->getUnsavedValues(),
[
'expand' => true,
]
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
return $this;
}
$this->clearError();
$this->setRemoteData( $response->getData() );
$this->clearUnsavedValues();
return $this;
}
/**
* Updates an existing object with the current data.
*
* @return object This object
*/
protected function update()
{
$object_id = $this->getID();
if ( empty($object_id) ) {
throw new \Exception('Object has no ID, update() not possible');
}
if ( !$this->isDirty() ) {
return $this;
}
$url = $this->getURL(
'update',
[
'object_id' => $object_id,
]
);
$response = $this->getClient()->put(
$url,
$this->getUnsavedValues(),
[
'expand' => true,
]
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
return $this;
}
$this->clearError();
$this->setRemoteData( $response->getData() );
$this->clearUnsavedValues();
return $this;
}
/**
* Deletes the data of this object.
* If data contains an ID, the object will also be deleted in Zammad.
*
* @return object This object
*/
public function delete()
{
// Delete object in Zammad.
$object_id = $this->getID();
if ( !empty($object_id) ) {
$url = $this->getURL(
'delete',
[
'object_id' => $object_id,
]
);
$response = $this->getClient()->delete(
$url,
[
'expand' => true,
]
);
if ( $response->hasError() ) {
$this->setError( $response->getError() );
return $this;
}
}
// Clear data of this (local) object.
$this->clearError();
$this->clearRemoteData();
$this->clearUnsavedValues();
return $this;
}
/**
* Returns the URL for the given method name, including its replaced placeholders.
*
* @param string $method_name E. g. 'get', 'all', etc.
* @param array $placeholder_values Array of placeholder => value pairs,
* e. g. [ 'object_id' => 2 ] will replace
* {object_id} in URL with 2.
*
* @return string URL, e. g. 'tickets/10'.
*/
protected function getURL( $method_name, array $placeholder_values = [] )
{
if ( !array_key_exists( $method_name, $this::URLS ) ) {
throw new \RuntimeException(
"Method '$method_name' is not supported for "
. get_class($this)
. ' resource'
);
}
$url = $this::URLS[$method_name];
foreach ( $placeholder_values as $placeholder => $value ) {
$url = preg_replace( "/\{$placeholder\}/", "$value", $url );
}
return $url;
}
public function can( $method_name )
{
return array_key_exists( $method_name, $this::URLS );
}
}