-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathEndpoint.php
More file actions
1482 lines (1316 loc) · 43.9 KB
/
Endpoint.php
File metadata and controls
1482 lines (1316 loc) · 43.9 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
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Muffin\Webservice\Model;
use ArrayObject;
use BadMethodCallException;
use Cake\Core\App;
use Cake\Datasource\EntityInterface;
use Cake\Datasource\Exception\InvalidPrimaryKeyException;
use Cake\Datasource\RepositoryInterface;
use Cake\Datasource\RulesAwareTrait;
use Cake\Datasource\RulesChecker;
use Cake\Event\EventDispatcherInterface;
use Cake\Event\EventDispatcherTrait;
use Cake\Event\EventListenerInterface;
use Cake\Utility\Inflector;
use Cake\Validation\ValidatorAwareTrait;
use Muffin\Webservice\Exception\MissingResourceClassException;
use Muffin\Webservice\Exception\UnexpectedDriverException;
use Muffin\Webservice\Marshaller;
use Muffin\Webservice\Query;
use Muffin\Webservice\Schema;
/**
* The table equivalent of a webservice endpoint
*
* @package Muffin\Webservice\Model
*/
class Endpoint implements RepositoryInterface, EventListenerInterface, EventDispatcherInterface
{
use EventDispatcherTrait;
use RulesAwareTrait;
use ValidatorAwareTrait;
/**
* Name of default validation set.
*
* @var string
*/
const DEFAULT_VALIDATOR = 'default';
/**
* The alias this object is assigned to validators as.
*
* @var string
*/
const VALIDATOR_PROVIDER_NAME = 'endpoint';
/**
* Connection instance this endpoint uses
*
* @var \Muffin\Webservice\Connection|null $connection Connection instance
*/
protected $_connection;
/**
* The schema object containing a description of this endpoint fields
*
* @var \Muffin\Webservice\Schema
*/
protected $_schema;
/**
* The name of the class that represent a single resource for this endpoint
*
* @var string
*/
protected $_resourceClass;
/**
* Registry key used to create this endpoint object
*
* @var string
*/
protected $_registryAlias;
/**
* The name of the endpoint to contact
*
* @var string
*/
protected $_name;
/**
* The name of the field that represents the primary key in the endpoint
*
* @var string|array
*/
protected $_primaryKey;
/**
* The name of the field that represents a human readable representation of a row
*
* @var string
*/
protected $_displayField;
/**
* The webservice instance to call
*
* @var \Muffin\Webservice\Webservice\WebserviceInterface
*/
protected $_webservice;
/**
* The alias to use for the endpoint
*
* @var string
*/
protected $_alias;
/**
* The inflect method to use for endpoint routes
*
* @var string
*/
protected $_inflectionMethod = 'underscore';
/**
* Initializes a new instance
*
* The $config array understands the following keys:
*
* - alias: Alias to be assigned to this endpoint (default to endpoint name)
* - connection: The connection instance to use
* - name: Name of the endpoint to represent
* - endpoint: Deprecated, please pass name instead
* - resourceClass: The fully namespaced class name of the resource class that will
* represent rows in this endpoint.
* - schema: A \Muffin\Webservice\Schema object or an array that can be
* passed to it.
*
* @param array $config List of options for this endpoint
*/
public function __construct(array $config = [])
{
if (!empty($config['alias'])) {
$this->setAlias($config['alias']);
}
if (!empty($config['connection'])) {
$this->setConnection($config['connection']);
}
if (!empty($config['displayField'])) {
$this->setDisplayField($config['displayField']);
}
if (!empty($config['inflect'])) {
$this->setInflectionMethod($config['inflect']);
}
if (!empty($config['name'])) {
$this->setName($config['name']);
}
if (!empty($config['endpoint'])) {
$this->setName($config['endpoint']);
}
if (!empty($config['primaryKey'])) {
$this->setPrimaryKey($config['primaryKey']);
}
if (!empty($config['schema'])) {
$this->setSchema($config['schema']);
}
if (!empty($config['registryAlias'])) {
$this->setRegistryAlias($config['registryAlias']);
}
if (!empty($config['resourceClass'])) {
$this->setResourceClass($config['resourceClass']);
}
if (!empty($config['eventManager'])) {
$this->setEventManager($config['eventManager']);
}
$this->initialize($config);
$this->getEventManager()->on($this);
$this->dispatchEvent('Model.initialize');
}
/**
* Get the default connection name.
*
* This method is used to get the fallback connection name if an
* instance is created through the EndpointRegistry without a connection.
*
* @return string
*
* @see \Muffin\Webservice\Model\EndpointRegistry::get()
*/
public static function defaultConnectionName()
{
$namespaceParts = explode('\\', get_called_class());
$plugin = array_slice(array_reverse($namespaceParts), 3, 2);
return Inflector::underscore(current($plugin));
}
/**
* Initialize a endpoint instance. Called after the constructor.
*
* You can use this method to define validation and do any other initialization logic you need.
*
* ```
* public function initialize(array $config)
* {
* $this->primaryKey('something_else');
* }
* ```
*
* @param array $config Configuration options passed to the constructor
* @return void
*/
public function initialize(array $config)
{
}
/**
* Returns the endpoint name or sets a new one
*
* @param string|null $endpoint the new endpoint name
* @return string
* @deprecated 2.0.0 use setName() and getName() instead.
*/
public function endpoint($endpoint = null)
{
if ($endpoint !== null) {
$this->setName($endpoint);
}
return $this->getName();
}
/**
* Set the name of this endpoint
*
* @param string $name The name for this endpoint instance
* @return $this
*/
public function setName($name)
{
$inflectMethod = $this->getInflectionMethod();
$this->_name = Inflector::$inflectMethod($name);
return $this;
}
/**
* Get the name of this endpoint
*
* @return string
*/
public function getName()
{
if ($this->_name === null) {
$endpoint = namespaceSplit(get_class($this));
$endpoint = substr(end($endpoint), 0, -8);
$inflectMethod = $this->getInflectionMethod();
$this->_name = Inflector::$inflectMethod($endpoint);
}
return $this->_name;
}
/**
* Returns the endpoint alias or sets a new one
*
* @param string|null $alias the new endpoint alias
* @return string
* @deprecated 2.0.0 Use getAlias and setAlias instead
*/
public function alias($alias = null)
{
if ($alias !== null) {
$this->setAlias($alias);
}
return $this->getAlias();
}
/**
* Alias a field with the endpoint's current alias.
*
* @param string $field The field to alias.
* @return string The field prefixed with the endpoint alias.
*/
public function aliasField($field)
{
return $this->getAlias() . '.' . $field;
}
/**
* Returns the endpoint registry key used to create this endpoint instance
*
* @param string|null $registryAlias the key used to access this object
* @return string
* @deprecated 2.0.0 Use setRegistryAlias()/getRegistryAlias() instead.
*/
public function registryAlias($registryAlias = null)
{
if ($registryAlias !== null) {
$this->setRegistryAlias($registryAlias);
}
return $this->getRegistryAlias();
}
/**
* Sets the table registry key used to create this table instance.
*
* @param string $registryAlias The key used to access this object.
* @return $this
*/
public function setRegistryAlias($registryAlias)
{
$this->_registryAlias = $registryAlias;
return $this;
}
/**
* Returns the table registry key used to create this table instance.
*
* @return string
*/
public function getRegistryAlias()
{
if ($this->_registryAlias === null) {
$this->_registryAlias = $this->getAlias();
}
return $this->_registryAlias;
}
/**
* Set the driver to use
*
* @param \Muffin\Webservice\AbstractDriver|null $connection The driver to use
* @return \Muffin\Webservice\AbstractDriver|\Muffin\Webservice\Connection
* @deprecated 2.0.0 Use setConnection() and getConnection() instead.
*/
public function connection($connection = null)
{
if ($connection !== null) {
$this->setConnection($connection);
}
return $this->getConnection();
}
/**
* Sets the connection driver.
*
* @param \Muffin\Webservice\Connection $connection Connection instance
* @return $this
*/
public function setConnection($connection)
{
$this->_connection = $connection;
return $this;
}
/**
* Returns the connection driver.
*
* @return \Muffin\Webservice\Connection|null
*/
public function getConnection()
{
return $this->_connection;
}
/**
* Returns the schema endpoint object describing this endpoint's properties.
*
* If an \Muffin\Webservice\Schema is passed, it will be used for this endpoint
* instead of the default one.
*
* If an array is passed, a new \Muffin\Webservice\Schema will be constructed
* out of it and used as the schema for this endpoint.
*
* @param array|\Muffin\Webservice\Schema|null $schema New schema to be used for this endpoint
* @return \Muffin\Webservice\Schema
* @deprecated 2.0.0 Use setSchema() and getSchema() instead
*/
public function schema($schema = null)
{
if ($schema === null) {
return $this->getSchema();
}
$this->setSchema($schema);
return $this->getSchema();
}
/**
* Set the endpoints schema
*
* If a \Muffin\Webservice\Schema is passed, it will be used for this endpoint
* instead of the default one.
*
* If an array is passed, a new \Muffin\Webservice\Schema will be constructed
* out of it and used as the schema for this endpoint.
*
* @param \Muffin\Webservice\Schema|array $schema Either an array of fields and config, or a schema object
* @return $this
*/
public function setSchema($schema)
{
if (is_array($schema)) {
$schema = new Schema($this->getName(), $schema);
}
$this->_schema = $schema;
return $this;
}
/**
* Returns the schema endpoint object describing this endpoint's properties.
*
* @return \Muffin\Webservice\Schema
*/
public function getSchema()
{
if ($this->_schema === null) {
$this->_schema = $this->_initializeSchema($this->getWebservice()->describe($this->getName()));
}
return $this->_schema;
}
/**
* Override this function in order to alter the schema used by this endpoint.
* This function is only called after fetching the schema out of the webservice.
* If you wish to provide your own schema to this table without touching the
* database, you can override schema() or inject the definitions though that
* method.
*
* ### Example:
*
* ```
* protected function _initializeSchema(\Muffin\Webservice\Schema $schema) {
* $schema->addColumn('preferences', [
* 'type' => 'string'
* ]);
* return $schema;
* }
* ```
*
* @param \Muffin\Webservice\Schema $schema The schema definition fetched from webservice.
* @return \Muffin\Webservice\Schema the altered schema
* @api
*/
protected function _initializeSchema(Schema $schema)
{
return $schema;
}
/**
* Test to see if a Table has a specific field/column.
*
* Delegates to the schema object and checks for column presence
* using the Schema\Table instance.
*
* @param string $field The field to check for.
* @return bool True if the field exists, false if it does not.
*/
public function hasField($field)
{
$schema = $this->getSchema();
return $schema->column($field) !== null;
}
/**
* Returns the primary key field name or sets a new one
*
* @param string|array|null $key sets a new name to be used as primary key
* @return string|array
* @deprecated 2.0.0 Use getPrimaryKey() and setPrimaryKey() instead
*/
public function primaryKey($key = null)
{
if ($key !== null) {
$this->setPrimaryKey($key);
}
return $this->getPrimaryKey();
}
/**
* Returns the primary key field name
*
* @param string|array|null $key sets a new name to be used as primary key
* @return $this
*/
public function setPrimaryKey($key)
{
$this->_primaryKey = $key;
return $this;
}
/**
* Get the endpoints primary key, if one is not set, fetch it from the schema
*
* @return array|string
* @throws \Muffin\Webservice\Exception\UnexpectedDriverException When no schema exists to fetch the key from
*/
public function getPrimaryKey()
{
if ($this->_primaryKey === null) {
$schema = $this->getSchema();
if (!$schema) {
throw new UnexpectedDriverException(__('No schema has been defined for this endpoint'));
}
$key = (array)$schema->primaryKey();
if (count($key) === 1) {
$key = $key[0];
}
$this->_primaryKey = $key;
}
return $this->_primaryKey;
}
/**
* Returns the display field or sets a new one
*
* @param string|null $key sets a new name to be used as display field
* @return string
* @deprecated 2.0.0 Use setDisplayField and getDisplayField instead.
*/
public function displayField($key = null)
{
if ($key !== null) {
$this->setDisplayField($key);
}
return $this->getDisplayField();
}
/**
* Sets the endpoint display field
*
* @param string $field The new field to use as the display field
* @return $this
*/
public function setDisplayField($field)
{
$this->_displayField = $field;
return $this;
}
/**
* Get the endpoints current display field
*
* @return string
* @throws \Muffin\Webservice\Exception\UnexpectedDriverException When no schema exists to fetch the key from
*/
public function getDisplayField()
{
if ($this->_displayField === null) {
$primary = (array)$this->getPrimaryKey();
$this->_displayField = array_shift($primary);
$schema = $this->getSchema();
if (!$schema) {
throw new UnexpectedDriverException(__('No schema has been defined for this endpoint'));
}
if ($schema->column('title')) {
$this->_displayField = 'title';
}
if ($schema->column('name')) {
$this->_displayField = 'name';
}
}
return $this->_displayField;
}
/**
* Returns the class used to hydrate resources for this endpoint or sets a new one
*
* @param string|null $name the name of the class to use
* @throws \Muffin\Webservice\Exception\MissingResourceClassException when the entity class cannot be found
* @return string
* @deprecated 2.0.0 Use setResourceClassName() and getResourceClassName() instead.
*/
public function resourceClass($name = null)
{
if ($name !== null) {
$this->setResourceClass($name);
}
return $this->getResourceClass();
}
/**
* Set the resource class name used to hydrate resources for this endpoint
*
* @param string $name Name of the class to use
* @return $this
* @throws \Muffin\Webservice\Exception\MissingResourceClassException If the resource class specified does not exist
*/
public function setResourceClass($name)
{
$this->_resourceClass = App::className($name, 'Model/Resource');
if (!$this->_resourceClass) {
throw new MissingResourceClassException([$name]);
}
return $this;
}
/**
* Get the resource class name used to hydrate resources for this endpoint
*
* @return string
*/
public function getResourceClass()
{
if (!$this->_resourceClass) {
$default = \Muffin\Webservice\Model\Resource::class;
$self = get_called_class();
$parts = explode('\\', $self);
if ($self === __CLASS__ || count($parts) < 3) {
return $this->_resourceClass = $default;
}
$alias = Inflector::singularize(substr(array_pop($parts), 0, -8));
$name = implode('\\', array_slice($parts, 0, -1)) . '\Resource\\' . $alias;
if (!class_exists($name)) {
return $this->_resourceClass = $default;
} else {
return $this->_resourceClass = $name;
}
}
return $this->_resourceClass;
}
/**
* Returns the inflect method or sets a new one
*
* @param null|string $method The inflection method to use
* @return null|string
* @deprecated 2.0.0 Use setInflectionMethod() and getInflectionMethod() instead.
*/
public function inflectionMethod($method = null)
{
if ($method !== null) {
$this->setInflectionMethod($method);
}
return $this->getInflectionMethod();
}
/**
* Set a new inflection method
*
* @param string $method The name of the inflection method
* @return $this
*/
public function setInflectionMethod($method)
{
$this->_inflectionMethod = $method;
return $this;
}
/**
* Get the inflection method
*
* @return string|null
*/
public function getInflectionMethod()
{
return $this->_inflectionMethod;
}
/**
* Returns an instance of the Webservice used
*
* @param \Muffin\Webservice\Webservice\WebserviceInterface|string|null $webservice The webservice to use
* @return $this|\Muffin\Webservice\Webservice\WebserviceInterface
* @deprecated 2.0.0 Use setWebservice() and getWebservice() instead.
*/
public function webservice($webservice = null)
{
if ($webservice !== null) {
return $this->setWebservice($this->getName(), $webservice);
}
if ($webservice === null) {
return $this->getWebservice();
}
$this->_webservice = $webservice;
return $this;
}
/**
* Set the webservice instance to be used for this endpoint
*
* @param string $alias Alias for the webservice
* @param \Muffin\Webservice\Webservice\WebserviceInterface $webservice The webservice instance
* @return $this
* @throws \Muffin\Webservice\Exception\UnexpectedDriverException When no driver exists for the endpoint
*/
public function setWebservice($alias, $webservice)
{
$connection = $this->getConnection();
if (!$connection) {
throw new UnexpectedDriverException(__('No driver has been defined for this endpoint'));
}
$connection->setWebservice($alias, $webservice);
$this->_webservice = $connection->getWebservice($alias);
return $this;
}
/**
* Get this endpoints associated webservice
*
* @return \Muffin\Webservice\Webservice\WebserviceInterface
*/
public function getWebservice()
{
if ($this->_webservice === null) {
$this->_webservice = $this->getConnection()->getWebservice($this->getName());
}
return $this->_webservice;
}
/**
* Creates a new Query for this repository and applies some defaults based on the
* type of search that was selected.
*
* ### Model.beforeFind event
*
* Each find() will trigger a `Model.beforeFind` event for all attached
* listeners. Any listener can set a valid result set using $query
*
* @param string $type the type of query to perform
* @param array|\ArrayAccess $options An array that will be passed to Query::applyOptions()
* @return \Muffin\Webservice\Query
*/
public function find($type = 'all', $options = [])
{
$query = $this->query()->read();
return $this->callFinder($type, $query, $options);
}
/**
* Returns the query as passed.
*
* By default findAll() applies no conditions, you
* can override this method in subclasses to modify how `find('all')` works.
*
* @param \Muffin\Webservice\Query $query The query to find with
* @param array $options The options to use for the find
* @return \Muffin\Webservice\Query The query builder
*/
public function findAll(Query $query, array $options)
{
return $query;
}
/**
* Sets up a query object so results appear as an indexed array, useful for any
* place where you would want a list such as for populating input select boxes.
*
* When calling this finder, the fields passed are used to determine what should
* be used as the array key, value and optionally what to group the results by.
* By default the primary key for the model is used for the key, and the display
* field as value.
*
* The results of this finder will be in the following form:
*
* ```
* [
* 1 => 'value for id 1',
* 2 => 'value for id 2',
* 4 => 'value for id 4'
* ]
* ```
*
* You can specify which property will be used as the key and which as value
* by using the `$options` array, when not specified, it will use the results
* of calling `primaryKey` and `displayField` respectively in this endpoint:
*
* ```
* $endpoint->find('list', [
* 'keyField' => 'name',
* 'valueField' => 'age'
* ]);
* ```
*
* Results can be put together in bigger groups when they share a property, you
* can customize the property to use for grouping by setting `groupField`:
*
* ```
* $endpoint->find('list', [
* 'groupField' => 'category_id',
* ]);
* ```
*
* When using a `groupField` results will be returned in this format:
*
* ```
* [
* 'group_1' => [
* 1 => 'value for id 1',
* 2 => 'value for id 2',
* ]
* 'group_2' => [
* 4 => 'value for id 4'
* ]
* ]
* ```
*
* @param \Muffin\Webservice\Query $query The query to find with
* @param array $options The options for the find
* @return \Muffin\Webservice\Query The query builder
*/
public function findList(Query $query, array $options)
{
$options += [
'keyField' => $this->getPrimaryKey(),
'valueField' => $this->getDisplayField(),
'groupField' => null
];
$options = $this->_setFieldMatchers(
$options,
['keyField', 'valueField', 'groupField']
);
return $query->formatResults(function ($results) use ($options) {
return $results->combine(
$options['keyField'],
$options['valueField'],
$options['groupField']
);
});
}
/**
* Out of an options array, check if the keys described in `$keys` are arrays
* and change the values for closures that will concatenate the each of the
* properties in the value array when passed a row.
*
* This is an auxiliary function used for result formatters that can accept
* composite keys when comparing values.
*
* @param array $options the original options passed to a finder
* @param array $keys the keys to check in $options to build matchers from
* the associated value
* @return array
*/
protected function _setFieldMatchers($options, $keys)
{
foreach ($keys as $field) {
if (!is_array($options[$field])) {
continue;
}
if (count($options[$field]) === 1) {
$options[$field] = current($options[$field]);
continue;
}
$fields = $options[$field];
$options[$field] = function ($row) use ($fields) {
$matches = [];
foreach ($fields as $field) {
$matches[] = $row[$field];
}
return implode(';', $matches);
};
}
return $options;
}
/**
* Returns a single record after finding it by its primary key, if no record is
* found this method throws an exception.
*
* ### Example:
*
* ```
* $id = 10;
* $article = $articles->get($id);
*
* $article = $articles->get($id, ['contain' => ['Comments]]);
* ```
*
* @param mixed $primaryKey primary key value to find
* @param array|\ArrayAccess $options options accepted by `Endpoint::find()`
* @throws \Cake\Datasource\Exception\RecordNotFoundException if the record with such id could not be found
* @return \Cake\Datasource\EntityInterface
* @see \Cake\Datasource\RepositoryInterface::find()
*/
public function get($primaryKey, $options = [])
{
$key = (array)$this->getPrimaryKey();
$alias = $this->getAlias();
foreach ($key as $index => $keyname) {
$key[$index] = $keyname;
}
$primaryKey = (array)$primaryKey;
if (count($key) !== count($primaryKey)) {
$primaryKey = $primaryKey ?: [null];
$primaryKey = array_map(function ($key) {
return var_export($key, true);
}, $primaryKey);
throw new InvalidPrimaryKeyException(sprintf(
'Record not found in endpoint "%s" with primary key [%s]',
$this->getName(),
implode($primaryKey, ', ')
));
}
$conditions = array_combine($key, $primaryKey);
$cacheConfig = isset($options['cache']) ? $options['cache'] : false;
$cacheKey = isset($options['key']) ? $options['key'] : false;
$finder = isset($options['finder']) ? $options['finder'] : 'all';
unset($options['key'], $options['cache'], $options['finder']);
$query = $this->find($finder, $options)->where($conditions);
if ($cacheConfig) {
if (!$cacheKey) {
$cacheKey = sprintf(
"get:%s.%s%s",
$this->getConnection()->configName(),
$this->getName(),
json_encode($primaryKey)
);
}
$query->cache($cacheKey, $cacheConfig);
}
return $query->firstOrFail();
}
/**
* Finds an existing record or creates a new one.
*
* Using the attributes defined in $search a find() will be done to locate
* an existing record. If records matches the conditions, the first record
* will be returned.
*
* If no record can be found, a new entity will be created
* with the $search properties. If a callback is provided, it will be
* called allowing you to define additional default values. The new
* entity will be saved and returned.
*
* @param array $search The criteria to find existing records by.
* @param callable|null $callback A callback that will be invoked for newly
* created entities. This callback will be called *before* the entity
* is persisted.
* @return \Cake\Datasource\EntityInterface An entity.
*/
public function findOrCreate($search, callable $callback = null)
{
$query = $this->find()->where($search);
$row = $query->first();
if ($row) {
return $row;
}
$entity = $this->newEntity();
$entity->set($search, ['guard' => false]);
if ($callback) {
$callback($entity);
}
return $this->save($entity) ?: $entity;
}
/**
* Creates a new Query instance for this repository
*
* @return \Muffin\Webservice\Query
*/
public function query()
{
return new Query($this->getWebservice(), $this);