forked from modxcms/revolution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodRestController.php
916 lines (829 loc) · 28 KB
/
modRestController.php
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
<?php
/*
* This file is part of the MODX Revolution package.
*
* Copyright (c) MODX, LLC
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace MODX\Revolution\Rest;
use MODX\Revolution\modX;
use xPDO\Om\xPDOObject;
use xPDO\Om\xPDOQuery;
/**
* Abstract controller class for modRestService; all REST controllers must extend this class to be properly
* implemented.
*
* @package MODX\Revolution\Rest
*/
abstract class modRestController
{
/** @var modX $modx The modX instance */
public $modx;
/** @var array $config An array of configuration properties, passed from modRestService */
public $config = [];
/** @var array $properties An array of request parameters passed */
public $properties = [];
/** @var array $headers An array of HTTP headers passed */
public $headers = [];
/** @var string $primaryKeyField The primary key field for this controller; useful when automating REST calls */
public $primaryKeyField = 'id';
/** @var array $errors An array of errors that may have occurred for this controller */
public $errors = [];
/** @var string $errorMessage A generic error message for this response */
public $errorMessage = '';
/** @var boolean $protected Whether or not this controller is "protected" - meaning whether or not verifyAuthentication will be called */
protected $protected = true;
/** @var modRestServiceRequest $request The request object passed to this controller */
protected $request;
/** @var string $response The response being sent by this controller */
protected $response;
/** @var string $responseStatus The response status being sent by this controller */
protected $responseStatus;
/**
* The following options are used if the default get/put/post/delete methods are not overridden. They automate
* the display and manipulation of data based on the classKey that is specified on the controller class, allowing
* for quick and easy controller creation based on standard CRUD concepts.
*/
/** @var string $classKey The xPDO class to use */
public $classKey;
/** @var string $classAlias The alias of the class when used in the getList method */
public $classAlias;
/** @var string $defaultSortField The default field to sort by in the getList method */
public $defaultSortField = 'name';
/** @var string $defaultSortDirection The default direction to sort in the getList method */
public $defaultSortDirection = 'ASC';
/** @var int $defaultLimit The default number of records to return in the getList method */
public $defaultLimit = 20;
/** @var int $defaultOffset The default offset in the getList method */
public $defaultOffset = 0;
/** @var xPDOObject $object */
public $object;
/** @var array $searchFields Optional. An array of fields to use when the search parameter is passed */
public $searchFields = [];
/** @var array $postRequiredFields An array of required field keys that must be passed for POST requests */
public $postRequiredFields = [];
/** @var array $postRequiredRelatedObjects An array of classKey/field pairings for checking related objects on POST */
public $postRequiredRelatedObjects = [];
/** @var string $postMethod The method on the object to call for POST requests */
public $postMethod = 'save';
/** @var array $putRequiredFields An array of required field keys that must be passed for PUT requests */
public $putRequiredFields = [];
/** @var array $postRequiredRelatedObjects An array of classKey/field pairings for checking related objects on PUT */
public $putRequiredRelatedObjects = [];
/** @var string $putMethod The method on the object to call for PUT requests */
public $putMethod = 'save';
/** @var array $deleteRequiredFields An array of required field keys that must be passed for DELETE requests */
public $deleteRequiredFields = [];
/** @var string $deleteMethod The method on the object to call for DELETE requests */
public $deleteMethod = 'remove';
/** @var array $allowedMethods An array of allowed request methods */
public $allowedMethods = ['GET', 'POST', 'PUT', 'DELETE'];
/** @var array $allowedMethods An array of allowed request methods */
public $allowedHeaders = ['Content-Type'];
/**
* @param modX $modx The modX instance
* @param modRestServiceRequest $request The rest service request class instance
* @param array $config An array of configuration properties, passed through from modRestService
*/
public function __construct(modX $modx, modRestServiceRequest $request, array $config = [])
{
$this->modx =& $modx;
$this->request =& $request;
$this->config = array_merge($this->config, $config);
}
/**
* Get a configuration option for this controller
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getOption($key, $default = null)
{
return array_key_exists($key, $this->config) ? $this->config[$key] : $default;
}
/**
* Initialize the controller
*/
public function initialize()
{
}
/**
* Override to verify authentication on this specific controller. Useful for managing permissions.
*
* @return boolean
*/
public function verifyAuthentication()
{
return true;
}
/**
* Return whether or not this controller is set to be protected
*
* @final
* @return bool
*/
final public function isProtected()
{
return $this->protected;
}
/**
* Check for any empty fields
*
* @param array $fields
* @param boolean $setFieldError
*
* @return bool|string
*/
public function checkRequiredFields(array $fields = [], $setFieldError = true)
{
$missing = [];
foreach ($fields as $field) {
$value = $this->getProperty($field);
if (empty($value)) {
$missing[] = $field;
if ($setFieldError) {
$this->addFieldError($field, $this->modx->lexicon('rest.err_field_required'));
}
}
}
if (!empty($missing)) {
return $this->modx->lexicon('rest.err_fields_required', [
'fields' => implode(', ', $missing),
]);
}
return true;
}
/**
* Check to ensure the existence of required related objects on the passed request
*
* @param array $pairs An array of arrays in the format: 'field' => 'classKey'
*
* @return boolean
*/
public function checkRequiredRelatedObjects(array $pairs = [])
{
$passed = true;
foreach ($pairs as $field => $classKey) {
if (!empty($classKey) && !empty($field)) {
$relatedObject = $this->modx->getObject($classKey, $this->getProperty($field));
if (empty($relatedObject)) {
$objectName = substr($classKey, 2);
$this->addFieldError($field, $this->modx->lexicon('err.obj_nf', ['name' => $objectName]));
$passed = false;
}
}
}
return $passed;
}
/**
* Get a REQUEST property for the controller
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getProperty($key, $default = null)
{
$value = $default;
if (array_key_exists($key, $this->properties)) {
$value = $this->properties[$key];
}
return $value;
}
/**
* Set a request property for the controller
*
* @param string $key
* @param string $value
*/
public function setProperty($key, $value)
{
$this->properties[$key] = $value;
}
/**
* Unset a request property for the controller
*
* @param string $key
*/
public function unsetProperty($key)
{
unset($this->properties[$key]);
}
/**
* Get the request properties for the controller
*
* @return array
*/
public function getProperties()
{
return $this->properties;
}
/**
* Set a collection of properties for the controller
*
* @param array $properties An array of properties
* @param bool $merge Optionally, only merge properties in if this is true
*/
public function setProperties(array $properties = [], $merge = false)
{
$this->properties = $merge ? array_merge($this->properties, $properties) : $properties;
}
/**
* Set the HTTP request headers for this controller
*
* @param array $headers An array of headers
* @param bool $merge Optionally, only merge headers in if this is true
*/
public function setHeaders(array $headers = [], $merge = false)
{
$this->headers = $merge ? array_merge($this->headers, $headers) : $headers;
}
/**
* Get the request headers for this controller
*
* @return array
*/
final public function getHeaders()
{
return $this->headers;
}
/**
* Return a success message for this controller, with an optional return object
*
* @param string $message Optional. The success response message.
* @param array|xPDOObject $object Optional. An xPDOObject or array to send as the return object.
* @param int $status Optional. The status code to send.
*/
public function success($message = '', $object = [], $status = null)
{
if (empty($status)) {
$status = $this->getOption('defaultSuccessStatusCode', 200);
}
$this->process(true, $message, $object, $status);
}
/**
* Return a failure message for this controller, with an optional return object. Will also automatically
* send errors in an errors root node if any are found.
*
* @param string $message Optional. The failure response message.
* @param array|xPDOObject $object Optional. An xPDOObject or array to send as the return object.
* @param int $status Optional. The status code to send.
*/
public function failure($message = '', $object = [], $status = null)
{
if (empty($status)) {
$status = $this->getOption('defaultFailureStatusCode', 200);
}
$this->process(false, $message, $object, $status);
}
/**
* Process the response and format in the proper response format.
*
* @param bool $success Whether or not this response is successful.
* @param string $message Optional. The response message.
* @param array|xPDOObject $object Optional. The response return object.
* @param int $status Optional. The response code.
*/
protected function process($success = true, $message = '', $object = [], $status = 200)
{
$response = [
$this->getOption('responseSuccessKey', 'success') => $success,
$this->getOption('responseMessageKey', 'message') => $message,
$this->getOption('responseObjectKey', 'object') => is_object($object) ? $object->toArray() : $object,
'code' => $status,
];
if (empty($success) && !empty($this->errors)) {
$response[$this->getOption('responseErrorsKey', 'errors')] = $this->errors;
}
$this->modx->log(modX::LOG_LEVEL_DEBUG, '[REST] Sending REST response: ' . print_r($response, true));
$this->response = $response;
$this->responseStatus = empty($status) ? (empty($success) ? $this->getOption('defaultFailureStatusCode',
200) : $this->getOption('defaultSuccessStatusCode', 200)) : $status;
}
/**
* Return the response status code
*
* @return string
*/
final public function getResponseStatus()
{
return $this->responseStatus;
}
/**
* Return the response payload
*
* @return string
*/
final public function getResponse()
{
return $this->response;
}
/**
* Get any errors that may have been set on this controller
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* See if any errors have been set during the request on this controller
*
* @return bool
*/
public function hasErrors()
{
return !empty($this->errors) || !empty($this->errorMessage);
}
/**
* Set an error for a specific field
*
* @param string $k The key of the field to set
* @param string $v The error message to set
* @param boolean $append Whether or not to append the error message or overwrite it
*/
public function addFieldError($k, $v, $append = true)
{
if ($append && !empty($this->errors[$k])) {
$separator = $this->getOption('errorMessageSeparator', ' ');
$this->errors[$k] .= $separator . $v;
} else {
$this->errors[$k] = $v;
}
}
/**
* Remove an error from a field
*
* @param string $k
*/
public function removeFieldError($k)
{
unset($this->errors[$k]);
}
/**
* Set the general error message
*
* @param string $message
*/
public function setErrorMessage($message)
{
$this->errorMessage = $message;
}
/**
* Clear the general error message
*/
public function clearErrorMessage()
{
$this->errorMessage = '';
}
/**
* Set a default value for a property on this controller request.
*
* @param string $k The key of the field
* @param mixed $v The default value to set
* @param bool $useNotEmpty Whether or not to use empty() for checking set status
*
* @return boolean True if the default was used
*/
public function setDefault($k, $v, $useNotEmpty = false)
{
$isSet = false;
if ($useNotEmpty) {
if (!empty($this->properties[$k])) {
$isSet = true;
}
} else {
if (array_key_exists($k, $this->properties)) {
$isSet = true;
}
}
if (!$isSet) {
$this->properties[$k] = $v;
}
return !$isSet;
}
/**
* Set an array of default values for properties on this controller request
*
* @param array $array
* @param bool $useNotEmpty
*/
public function setDefaults(array $array, $useNotEmpty = false)
{
foreach ($array as $k => $v) {
$this->setDefault($k, $v, $useNotEmpty);
}
}
/**
* Output a collection of objects as a list.
*
* @param array $list
* @param int|boolean $total
* @param int $status
*/
public function collection($list = [], $total = false, $status = null)
{
if (empty($status)) {
$status = $this->getOption('defaultSuccessStatusCode', 200);
}
if ($total === false) {
$total = count($list);
}
$this->response = [
$this->getOption('collectionResultsKey', 'results') => $list,
$this->getOption('collectionTotalKey', 'total') => $total,
];
$this->responseStatus = $status;
}
/**
* Route GET requests
*
* @return array
*/
public function get()
{
$pk = $this->getProperty($this->primaryKeyField);
if (empty($pk)) {
return $this->getList();
}
return $this->read($pk);
}
/**
* Abstract method for routing GET requests without a primary key passed. Must be defined in your derivative
* controller. Handles fetching of collections of objects.
*
* @abstract
* @return array
*/
public function getList()
{
$this->getProperties();
$c = $this->modx->newQuery($this->classKey);
$c = $this->addSearchQuery($c);
$c = $this->prepareListQueryBeforeCount($c);
$total = $this->modx->getCount($this->classKey, $c);
$alias = !empty($this->classAlias) ? $this->classAlias : $this->modx->getAlias($this->classKey);
$c->select($this->modx->getSelectColumns($this->classKey, $alias));
$c = $this->prepareListQueryAfterCount($c);
$c->sortby($this->getProperty($this->getOption('propertySort', 'sort'), $this->defaultSortField),
$this->getProperty($this->getOption('propertySortDir', 'dir'), $this->defaultSortDirection));
$limit = $this->getProperty($this->getOption('propertyLimit', 'limit'), $this->defaultLimit);
if (empty($limit)) {
$limit = $this->defaultLimit;
}
$c->limit($limit, $this->getProperty($this->getOption('propertyOffset', 'start'), $this->defaultOffset));
$objects = $this->modx->getCollection($this->classKey, $c);
if (empty($objects)) {
$objects = [];
}
$list = [];
/** @var xPDOObject $object */
foreach ($objects as $object) {
$list[] = $this->prepareListObject($object);
}
return $this->collection($list, $total);
}
/**
* Add a search query to listing calls
*
* @param xPDOQuery $c
*
* @return xPDOQuery
*/
protected function addSearchQuery(xPDOQuery $c)
{
$search = $this->getProperty($this->getOption('propertySearch', 'search'), false);
if (!empty($search) && !empty($this->searchFields)) {
$searchQuery = [];
$i = 0;
foreach ($this->searchFields as $searchField) {
$or = $i > 0 ? 'OR:' : '';
$searchQuery[$or . $searchField . ':LIKE'] = '%' . $search . '%';
$i++;
}
if (!empty($searchQuery)) {
$c->where($searchQuery);
}
}
return $c;
}
/**
* Allows manipulation of the query object before the COUNT statement is called on listing calls. Override to
* provide custom functionality.
*
* @param xPDOQuery $c
*
* @return xPDOQuery
*/
protected function prepareListQueryBeforeCount(xPDOQuery $c)
{
return $c;
}
/**
* Allows manipulation of the query object after the COUNT statement is called on listing calls. Override to
* provide custom functionality.
*
* @param xPDOQuery $c
*
* @return xPDOQuery
*/
protected function prepareListQueryAfterCount(xPDOQuery $c)
{
return $c;
}
/**
* Returns an array of field-value pairs for the object when listing. Override to provide custom functionality.
*
* @param xPDOObject $object The current iterated object
*
* @return array An array of field-value pairs of data
*/
protected function prepareListObject(xPDOObject $object)
{
return $object->toArray();
}
/**
* Get the criteria for the getObject call for GET/PUT/DELETE requests
*
* @param mixed $id
*
* @return array
*/
public function getPrimaryKeyCriteria($id)
{
return [$this->primaryKeyField => $id];
}
/**
* Abstract method for routing GET requests with a primary key passed. Must be defined in your derivative
* controller.
*
* @abstract
*
* @param $id
*/
public function read($id)
{
if (empty($id)) {
return $this->failure($this->modx->lexicon('rest.err_field_ns', [
'field' => $this->primaryKeyField,
]));
}
/** @var xPDOObject $object */
$c = $this->getPrimaryKeyCriteria($id);
$this->object = $this->modx->getObject($this->classKey, $c);
if (empty($this->object)) {
return $this->failure($this->modx->lexicon('rest.err_obj_nf', [
'class_key' => $this->classKey,
]));
}
$objectArray = $this->object->toArray();
$afterRead = $this->afterRead($objectArray);
if ($afterRead !== true && $afterRead !== null) {
return $this->failure($afterRead === false ? $this->errorMessage : $afterRead);
}
return $this->success('', $objectArray);
}
/**
* Fires after reading the object. Override to provide custom functionality.
*
* @param array $objectArray A reference to the outputting array
*
* @return boolean|string Either return true/false or a string message
*/
public function afterRead(array &$objectArray)
{
return !$this->hasErrors();
}
/**
* Method for routing POST requests. Can be overridden; default behavior automates xPDOObject, class-based requests.
*
* @abstract
*/
public function post()
{
$properties = $this->getProperties();
if (!empty($this->postRequiredFields)) {
$result = $this->checkRequiredFields($this->postRequiredFields);
if ($result !== true) {
return $this->failure($result);
}
}
if (!empty($this->postRequiredRelatedObjects)) {
if (!$this->checkRequiredRelatedObjects($this->postRequiredRelatedObjects)) {
return $this->failure();
}
}
/** @var xPDOObject $object */
$this->object = $this->modx->newObject($this->classKey);
$this->object->fromArray($properties);
$beforePost = $this->beforePost();
if ($beforePost !== true && $beforePost !== null) {
return $this->failure($beforePost === false ? $this->errorMessage : $beforePost);
}
if (!$this->object->{$this->postMethod}()) {
$this->setObjectErrors();
if ($this->hasErrors()) {
return $this->failure();
} else {
return $this->failure($this->modx->lexicon('rest.err_class_save', [
'class_key' => $this->classKey,
]));
}
}
$objectArray = $this->object->toArray();
$this->afterPost($objectArray);
return $this->success('', $objectArray);
}
/**
* Fires before saving the new object. Override to provide custom functionality.
*
* @return boolean
*/
public function beforePost()
{
return !$this->hasErrors();
}
/**
* Fires after saving the new object. Override to provide custom functionality.
*
* @param array $objectArray A reference to the outputting array
*/
public function afterPost(array &$objectArray)
{
}
/**
* Handles updating of objects
*
* @return array
*/
public function put()
{
$id = $this->getProperty($this->primaryKeyField, false);
if (empty($id)) {
return $this->failure($this->modx->lexicon('rest.err_field_ns', [
'field' => $this->primaryKeyField,
]));
}
$c = $this->getPrimaryKeyCriteria($id);
$this->object = $this->modx->getObject($this->classKey, $c);
if (empty($this->object)) {
return $this->failure($this->modx->lexicon('rest.err_obj_nf', [
'class_key' => $this->classKey,
]));
}
if (!empty($this->putRequiredFields)) {
$result = $this->checkRequiredFields($this->putRequiredFields);
if ($result !== true) {
return $this->failure($result);
}
}
if (!empty($this->putRequiredRelatedObjects)) {
if (!$this->checkRequiredRelatedObjects($this->putRequiredRelatedObjects)) {
return $this->failure();
}
}
$this->object->fromArray($this->getProperties());
$beforePut = $this->beforePut();
if ($beforePut !== true && $beforePut !== null) {
return $this->failure($beforePut === false ? $this->errorMessage : $beforePut);
}
if (!$this->object->{$this->putMethod}()) {
$this->setObjectErrors();
if ($this->hasErrors()) {
return $this->failure();
} else {
return $this->failure($this->modx->lexicon('rest.err_class_save', [
'class_key' => $this->classKey,
]));
}
}
$objectArray = $this->object->toArray();
$this->afterPut($objectArray);
return $this->success('', $objectArray);
}
/**
* Fires before saving an existing object. Override to provide custom functionality.
*
* @return boolean
*/
public function beforePut()
{
return !$this->hasErrors();
}
/**
* Fires after saving an existing object. Override to provide custom functionality.
*
* @param array $objectArray A reference to the outputting array
*/
public function afterPut(array &$objectArray)
{
}
/**
* Handle DELETE requests
*
* @return array
*/
public function delete()
{
$id = $this->getProperty($this->primaryKeyField, false);
if (empty($id)) {
return $this->failure($this->modx->lexicon('rest.err_field_ns', [
'field' => $this->primaryKeyField,
]));
}
$c = $this->getPrimaryKeyCriteria($id);
$this->object = $this->modx->getObject($this->classKey, $c);
if (empty($this->object)) {
return $this->failure($this->modx->lexicon('rest.err_obj_nf', [
'class_key' => $this->classKey,
]));
}
if (!empty($this->deleteRequiredFields)) {
$result = $this->checkRequiredFields($this->deleteRequiredFields);
if ($result !== true) {
return $this->failure($result);
}
}
$this->object->fromArray($this->getProperties());
$beforeDelete = $this->beforeDelete();
if ($beforeDelete !== true) {
return $this->failure($beforeDelete === false ? $this->errorMessage : $beforeDelete);
}
if (!$this->object->{$this->deleteMethod}()) {
$this->setObjectErrors();
return $this->failure($this->modx->lexicon('rest.err_class_remove', [
'class_key' => $this->classKey,
]));
}
$objectArray = $this->object->toArray();
$this->afterDelete($objectArray);
return $this->success('', $objectArray);
}
/**
* Fires before deleting an existing object. Override to provide custom functionality.
*
* @return boolean
*/
public function beforeDelete()
{
return !$this->hasErrors();
}
/**
* Fires after deleting an existing object. Override to provide custom functionality.
*
* @param array $objectArray
*/
public function afterDelete(array &$objectArray)
{
}
/**
* Handle OPTIONS requests
*
* @return array
*/
public function options()
{
header('Access-Control-Allow-Methods: ' . implode(', ', $this->allowedMethods));
header('Access-Control-Allow-Headers: ' . implode(', ', $this->allowedHeaders));
$this->responseStatus = 200;
}
/**
* Set object-specific model-layer errors for classes that implement the getErrors/addFieldError methods
*/
public function setObjectErrors()
{
if (method_exists($this->object, 'getErrors')) {
$errors = $this->object->getErrors();
foreach ($errors as $k => $msg) {
$this->addFieldError($k, $msg);
}
}
}
/**
* If an object is set, set the object fields with the passed values
*
* @param object $object
* @param array $values
*
* @return mixed
*/
public function setObjectFields(&$object, array $values = [])
{
foreach ($values as $key => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$object->{$key[$k]} = $v;
}
} else {
$object->{$key} = $value;
}
}
return $object;
}
}