/
Base.php
941 lines (832 loc) · 26.1 KB
/
Base.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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
<?php
/*
* This file is part of the php-ActiveResource.
* (c) 2010 Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ActiveResource;
use ActiveResource\Connections\Connection;
use ActiveResource\Schemas\Schema;
use ActiveResource\Schemas\AttrSchema;
use ActiveResource\Responses\Response;
use ActiveResource\Ext\Inflector;
/**
* Base implements base REST model abstraction class.
*
* @package ActiveResource
* @subpackage base
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @version 1.0.0
*/
abstract class Base
{
protected $id;
protected $attrs = array();
protected $connection;
protected $schema;
protected $prefix_options = array();
/**
* Constructs new object
*
* @param array $attrs object attributes
* @param ActiveResource\Connections\Connection $connection connection instance
*/
public function __construct(array $attrs, Connection $connection)
{
$this->setConnection($connection);
$this->setSchema($this->initSchema());
$this->load($attrs);
}
/**
* Sets current resource connection manager
*
* @param ActiveResource\Connections\Connection $connection conneciton instance
*/
public function setConnection(Connection $connection)
{
$this->connection = $connection;
}
/**
* Returns current resource connection manager
*
* @return ActiveResource\Connections\Connection
*/
public function getConnection()
{
return $this->connection;
}
/**
* Sets current resource attribute schema
*
* @param ActiveResource\Schemas\Schema $schema schema instance
*/
public function setSchema(Schema $schema)
{
$this->schema = $schema;
}
/**
* Returns current resource schema
*
* @return ActiveResource\Schemas\Schema
*/
public function getSchema()
{
return $this->schema;
}
/**
* Returns new scheme for resource (override this method to set your custom schema for resource)
*
* @return ActiveResource\Schemas\Schema
*/
protected function initSchema()
{
return new AttrSchema(
$this->schemaDefinition()
);
}
/**
* Returns schema definition, used to create new schema for resource (override for custom def.)
*
* @return array
*/
protected function schemaDefinition()
{
return array();
}
/**
* Constructs & returns newly created object (*new* method in Ruby AR)
*
* @param array $attrs object attributes
* @param ActiveResource\Connections\Connection $connection connection instance
*
* @return ActiveResource\Base
*/
public static function init(array $attrs, Connection $connection)
{
return self::instantiateRecord($attrs, array(), $connection);
}
/**
* Sets default prefix options for object
*
* @param array $options prefix options
*/
public function setPrefixOptions(array $options)
{
$this->prefix_options = $options;
}
/**
* Return default object prefix options
*
* @return array prefix options
*/
public function getPrefixOptions()
{
return $this->prefix_options;
}
/**
* Populate object values with specified attributes
*
* @param array $attrs object attributes
*/
public function load(array $attrs)
{
if (isset($attrs['id']))
{
$this->id = $attrs['id'];
unset($attrs['id']);
}
$this->attrs = $attrs;
}
/**
* Reloads object values from remote remote service
*
*/
public function reload()
{
if ($this->isPersisted())
{
$this->load(
$this->connection->get(self::getElementPath($this->getId()))
);
}
}
/**
* Returns object id
*
* @return integer id of the object
*/
public function getId()
{
return $this->id;
}
/**
* Returns object attribute
*
* @param string $name attribute name
*
* @return mixed attribute value
*/
public function __get($name)
{
return isset($this->attrs[$name]) ? $this->attrs[$name] : null;
}
/**
* Sets object attribute
*
* @param string $name attribute name
* @param string $value attribute value
*/
public function __set($name, $value)
{
$this->attrs[$name] = $value;
}
/**
* Returns object element name (override it if you need)
*
* @return string element name
*/
public static function getElementName()
{
return Inflector::underscoreClassName(get_called_class());
}
/**
* Returns object collection name (override it if you need)
*
* @return string collection name
*/
public static function getCollectionName()
{
return Inflector::pluralize(self::getElementName());
}
/**
* Checks whether object exists on remote service
*
* @param integer $id object id
* @param ActiveResource\Connections\Connection $connection remote service connection
*
* @return boolean true if exists, false otherwise
*/
public static function isExists($id, array $prefix_options,
array $query_options,
Connection $connection)
{
try
{
try
{
$response = $connection->head(self::getElementPath($id, $prefix_options, $query_options));
return 200 == $response->getCode();
}
catch (\ActiveResource\Exceptions\ResourceGone $e)
{
return false;
}
}
catch (\ActiveResource\Exceptions\ResourceNotFound $e)
{
return false;
}
}
/**
* Sends new request to remote service & create new object with fictive data
*
* @param ActiveResource\Connections\Connection $connection remote service connection
*
* @return ActiveResource\Base new object
*/
public static function build(array $prefix_options, array $query_options, Connection $connection)
{
$body = $connection->
get(self::getNewElementPath($prefix_options, $query_options))->
getDecodedBody();
$attrs = $body[self::getElementName()];
$class = get_called_class();
return new $class($attrs, $connection);
}
/**
* Checks if object is new (not saved to remote service)
*
* @return boolean true if new, false otherways
*/
public function isNew()
{
return null === $this->getId();
}
/**
* Checks if object is saved to remote service
*
* @return boolean true if saved, false otherways
*/
public function isPersisted()
{
return !$this->isNew();
}
/**
* Saves current object to remote service (create if object is new & update otherways)
*
* @return boolean true if saved, false otherways
*/
public function save()
{
return $this->isNew() ? $this->create() : $this->update();
}
/**
* Removes current object from remote service
*
* @return boolean true if succesfully destroyed, false otherways
*/
public function destroy()
{
$response = $this->connection->delete(self::getElementPath($this->getId()));
return 200 == $response->getCode();
}
/**
* Core method for finding resources.
*
* ==== 1st argument:
*
* integer - Returns resource with specified id
* string - One of the specified scopes ('all', 'first', 'last', 'one')
* array - First element must be is integer or scope, others - options
*
* ==== Options:
*
* 'from' - string, which specifies resource name or path
* 'params' - prefix & query parameters
*
* ==== Examples:
*
* Person::find(1, $connection)
* // => GET /people/1.xml
*
* Person::find('all', $connection)
* // => GET /people.xml
*
* Person::find(array('all', 'params' => array('title' => 'CEO')), $connection)
* // => GET /people.xml?title=CEO
*
* Person::find(array('first', 'from' => 'managers'), $connection)
* // => GET /people/managers.xml
*
* Person::find(array('last', 'from' => 'managers'), $connection)
* // => GET /people/managers.xml
*
* Person::find(array('all', 'from' => '/companies/1/people.xml'), $connection)
* // => GET /companies/1/people.xml
*
* Person::find(array('one', 'from' => 'leader'), $connection)
* // => GET /people/leader.xml
*
* Person::find(array('all', 'from' => 'developers', params => array('lang' => 'php')), $connection)
* // => GET /people/developers.xml?lang=php
*
* Person::find(array('one', 'from' => '/companies/1/manager.xml'), $connection)
* // => GET /companies/1/manager.xml
*
* StreetAddress::find(array(1, 'params' => array('person_id' => 2)))
* // => GET /people/2/street_addresses/1.xml
*
* ==== Failure or missing data
*
* A failure to find the requested object raises a ResourceNotFound
* exception if the find was called with an id.
* With any other scope, find returns nil when no data is returned.
*
* @param integer|string|array $criteria criteria of the query
* @param ActiveResource\Connections\Connection $connection remote resource connection
*
* @return array|ActiveResource\Base single object or array of objects
*/
public static function find($criteria, Connection $connection)
{
if (!is_array($criteria))
{
$criteria = array($criteria);
}
switch ($scope = array_shift($criteria))
{
case 'one': return self::findOne($criteria, $connection);
case 'first': return array_shift(self::findEvery($criteria, $connection));
case 'last': return array_pop(self::findEvery($criteria, $connection));
case 'all': return self::findEvery($criteria, $connection);
default: return self::findSingle($scope, $criteria, $connection);
}
}
public function elementGet($method_name, array $params = array())
{
list($prefix_options, $query_options) = self::splitParams($params);
if ($this->isNew())
{
$response = $this->connection->get(
self::getCustomMethodNewElementPath($method_name, $prefix_options, $query_options)
);
}
else
{
$response = $this->connection->get(
self::getCustomMethodElementPath(
$method_name, $this->getId(), $prefix_options, $query_options
)
);
}
$attrs = $response->getDecodedBody();
return $attrs[end(array_keys($attrs))];
}
public static function collectionGet($method_name, array $params = array(),
Connection $connection)
{
list($prefix_options, $query_options) = self::splitParams($params);
$response = $connection->get(
self::getCustomMethodCollectionPath($method_name, $prefix_options, $query_options)
);
$attrs = $response->getDecodedBody();
return $attrs[end(array_keys($attrs))];
}
public function elementPost($method_name, array $params = array(), array $body = array())
{
list($prefix_options, $query_options) = self::splitParams($params);
$body = array('request' => $body);
if ($this->isNew())
{
$response = $this->connection->post(
self::getCustomMethodNewElementPath($method_name, $prefix_options, $query_options), $body
);
}
else
{
$response = $this->connection->post(
self::getCustomMethodElementPath(
$method_name, $this->getId(), $prefix_options, $query_options
), $body
);
}
return 201 === $response->getCode();
}
public static function collectionPost($method_name, array $params = array(),
array $body = array(), Connection $connection)
{
list($prefix_options, $query_options) = self::splitParams($params);
$body = array('request' => $body);
$response = $connection->post(
self::getCustomMethodCollectionPath($method_name, $prefix_options, $query_options), $body
);
return 201 === $response->getCode();
}
public function elementPut($method_name, array $params = array(), array $body = array())
{
list($prefix_options, $query_options) = self::splitParams($params);
$body = array('request' => $body);
$response = $this->connection->put(
self::getCustomMethodElementPath(
$method_name, $this->getId(), $prefix_options, $query_options
), $body
);
return 204 === $response->getCode() || 200 === $response->getCode();
}
public static function collectionPut($method_name, array $params = array(),
array $body = array(), Connection $connection)
{
list($prefix_options, $query_options) = self::splitParams($params);
$body = array('request' => $body);
$response = $connection->put(
self::getCustomMethodCollectionPath($method_name, $prefix_options, $query_options), $body
);
return 204 === $response->getCode() || 200 === $response->getCode();
}
public function elementDelete($method_name, array $params = array())
{
list($prefix_options, $query_options) = self::splitParams($params);
$response = $this->connection->delete(
self::getCustomMethodElementPath(
$method_name, $this->getId(), $prefix_options, $query_options
)
);
return 200 === $response->getCode();
}
public static function collectionDelete($method_name, array $params = array(),
Connection $connection)
{
list($prefix_options, $query_options) = self::splitParams($params);
$response = $connection->delete(
self::getCustomMethodCollectionPath($method_name, $prefix_options, $query_options)
);
return 200 === $response->getCode();
}
public function elementHead($method_name, array $params = array())
{
list($prefix_options, $query_options) = self::splitParams($params);
$response = $this->connection->head(
self::getCustomMethodElementPath(
$method_name, $this->getId(), $prefix_options, $query_options
)
);
return 200 === $response->getCode();
}
public static function collectionHead($method_name, array $params = array(),
Connection $connection)
{
list($prefix_options, $query_options) = self::splitParams($params);
$response = $connection->head(
self::getCustomMethodCollectionPath($method_name, $prefix_options, $query_options)
);
return 200 === $response->getCode();
}
/**
* Returns collection url path to objects
*
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string collection path
*/
protected static function getCollectionPath(array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
self::getQueryString($query_options)
);
}
/**
* Returns collection url path to objects
*
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string collection path
*/
protected static function getCustomMethodCollectionPath($method_name,
array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s/%s.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
$method_name,
self::getQueryString($query_options)
);
}
/**
* Returns url path to object with specified id
*
* @param integer $id id of the object
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string element path
*/
protected static function getElementPath($id, array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s/%d.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
$id,
self::getQueryString($query_options)
);
}
/**
* Returns url path to object with specified id
*
* @param integer $id id of the object
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string element path
*/
protected static function getCustomMethodElementPath($method_name, $id,
array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s/%d/%s.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
$id,
$method_name,
self::getQueryString($query_options)
);
}
/**
* Returns url path to new object
*
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string new element path
*/
protected static function getNewElementPath(array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s/new.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
self::getQueryString($query_options)
);
}
/**
* Returns url path to new object
*
* @param array $prefix_options prefix options
* @param array $query_options query options
*
* @return string new element path
*/
protected static function getCustomMethodNewElementPath($method_name,
array $prefix_options = array(),
array $query_options = array())
{
return sprintf('%s%s/new/%s.:extension:%s',
self::getPrefix($prefix_options),
self::getCollectionName(),
$method_name,
self::getQueryString($query_options)
);
}
protected static function findEvery(array $args = array(), Connection $connection)
{
try
{
list($from, $prefix_options, $query_options) = self::extractOptions($args);
if (null === $from)
{
$response = $connection->get(self::getCollectionPath($prefix_options, $query_options));
$decoded = $response->getDecodedBody();
$attrs = $decoded[self::getCollectionName()];
}
elseif (false !== strpos($from, '/'))
{
$path = sprintf('%s%s', $from, self::getQueryString($query_options));
$response = $connection->get($path);
$decoded = $response->getDecodedBody();
$attrs = $decoded[self::getCollectionName()];
}
else
{
$attrs = self::collectionGet(
$from, array_merge($prefix_options, $query_options), $connection
);
}
return self::instantiateCollection($attrs, $prefix_options, $connection);
}
catch (\ActiveResource\Exceptions\ResourceNotFound $e)
{
return null;
}
}
protected static function findOne(array $args = array(), Connection $connection)
{
try
{
list($from, $prefix_options, $query_options) = self::extractOptions($args);
if (false !== strpos($from, '/'))
{
$path = sprintf('%s%s', $from, self::getQueryString($query_options));
$response = $connection->get($path);
$decoded = $response->getDecodedBody();
$attrs = $decoded[self::getElementName()];
}
else
{
$attrs = self::collectionGet(
$from, array_merge($prefix_options, $query_options), $connection
);
}
return self::instantiateRecord($attrs, $prefix_options, $connection);
}
catch (\ActiveResource\Exceptions\ResourceNotFound $e)
{
return null;
}
}
protected static function findSingle($id, array $args = array(), Connection $connection)
{
try
{
list($from, $prefix_options, $query_options) = self::extractOptions($args);
$response = $connection->get(self::getElementPath($id, $prefix_options, $query_options));
$decoded = $response->getDecodedBody();
$attrs = $decoded[self::getElementName()];
return self::instantiateRecord($attrs, $prefix_options, $connection);
}
catch (\ActiveResource\Exceptions\ResourceNotFound $e)
{
return null;
}
}
/**
* Create current resource on remote service.
*
* @return boolean true if created, false otherways
*/
protected function create()
{
$prepared_attrs = array();
$prepared_attrs[$this->getElementName()] = $this->attrs;
$response = $this->connection->post($this->getCollectionPath(), $prepared_attrs);
if (201 == $response->getCode())
{
$this->id = $this->getIdFromResponse($response);
$this->loadAttributesFromResponse($response);
return null !== $this->id;
}
return false;
}
/**
* Updates current resource on remote service
*
* @return boolean true if updated, false otherways
*/
protected function update()
{
$prepared_attrs = array();
$prepared_attrs[$this->getElementName()] = $this->attrs;
$response = $this->connection->put($this->getElementPath($this->getId()), $prepared_attrs);
$this->loadAttributesFromResponse($response);
return 204 == $response->getCode() || 200 == $response->getCode();
}
/**
* Returns url prefix, generated from the prefix options
*
* @param array $options prefix options
*
* @return string generated prefix
*/
protected static function getPrefix(array $options)
{
$prefix = '/';
foreach ($options as $name => $value)
{
$collection = Inflector::pluralize(strtr($name, array('_id' => '')));
$prefix .= sprintf('%s/%d/', $collection, $value);
}
return $prefix;
}
/**
* Returns url query string, generated from query options
*
* @param array $options query options
*
* @return string generated query string
*/
protected static function getQueryString(array $options)
{
$query_options = array();
foreach ($options as $name => $value)
{
$query_options[] = sprintf('%s=%s', $name, $value);
}
return !empty($query_options) ? '?' . implode('&', $query_options) : '';
}
/**
* Returns new object, populated with array data
*
* @param array $attrs attributes
* @param array $prefix_options prefix options for object
* @param ActiveResource\Connections\Connection $connection remote service connection
*
* @return ActiveResource\Base new resource instance
*/
protected static function instantiateRecord(array $attrs,
array $prefix_options = array(),
Connection $connection)
{
$class = get_called_class();
$record = new $class($attrs, $connection);
return $record;
}
/**
* Returns new objects list, populated with array data
*
* @param array $attrs_list array of objects attrbiutes
* @param array $prefix_options prefix options for objects
* @param ActiveResource\Connections\Connection $connection remote service connection
*
* @return array array of Base objects
*/
protected static function instantiateCollection(array $attrs_list,
array $prefix_options = array(),
Connection $connection)
{
$list = array();
foreach ($attrs_list as $attrs)
{
$list[] = self::instantiateRecord($attrs, $prefix_options, $connection);
}
return $list;
}
/**
* Extracts from & splitted params optoins from find arguments
*
* @param array $args options array
*
* @return array array of [0]=from, [1]=prefix_options & [2]=query_options
*/
private static function extractOptions(array $args)
{
$options = array();
$options[0] = null;
$options[1] = $options[2] = array();
if (isset($args['from']))
{
$options[0] = $args['from'];
}
if (isset($args['params']))
{
list($options[1], $options[2]) = self::splitParams($args['params']);
}
return $options;
}
/**
* Split params array into prefix_options & query_options
*
* @param array $params params array
*
* @return array array of [0]=prefix_options, [1]=query_options
*/
private static function splitParams(array $params)
{
$prefix_options = array();
$query_options = array();
foreach ($params as $name => $value)
{
if (false !== strpos($name, '_id'))
{
$prefix_options[$name] = $value;
}
else
{
$query_options[$name] = $value;
}
}
return array($prefix_options, $query_options);
}
/**
* Takes a response from a typical create post and pulls the ID out
*
* @param ActiveResource\Responses\Response $response response object
*
* @return integer id of the newly created resource
*/
private function getIdFromResponse(Response $response)
{
preg_match('/\/([^\/]*?)(\.\w+)?$/', $response->getHeader('Location'), $matches);
return isset($matches[1]) ? intval($matches[1]) : null;
}
/**
* Loads resource attributes from response
*
* @param ActiveResource\Responses\Response $response response object
*/
private function loadAttributesFromResponse(Response $response)
{
if ('0' != $response->getHeader('Content-Length') && 0 < strlen(trim($response->getBody())))
{
$this->load(
$this->connection->getFormat()->decode($response->getBody())
);
}
}
}