forked from ddeboer/DdeboerSalesforceMapperBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Mapper.php
697 lines (613 loc) · 23.1 KB
/
Mapper.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
<?php
namespace Ddeboer\Salesforce\MapperBundle;
use Ddeboer\Salesforce\ClientBundle\ClientInterface;
use Ddeboer\Salesforce\MapperBundle\Annotation\AnnotationReader;
use Ddeboer\Salesforce\MapperBundle\Annotation;
use Ddeboer\Salesforce\MapperBundle\Response\MappedRecordIterator;
use Ddeboer\Salesforce\ClientBundle\Response;
use Ddeboer\Salesforce\MapperBundle\Query\Builder;
use Ddeboer\Salesforce\MapperBundle\Event\BeforeSaveEvent;
use Doctrine\Common\Cache\Cache;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* This mapper makes interaction with the Salesforce API using full objects
* much easier
*
* Working with the mapper requires you to annotate your objects. A set of
* standard objects is included in the Model directory. If you need access
* to custom properties on these objects, it is recommended to
* extend the standard objects, add the properties and annotate them
* (using @Salesforce\Field annotations). If you want this mapper to accept
* completely custom objects, you can extend from Model/AbstractModel, and add
* a @Salesforce\Object annotation.
*
* @author David de Boer <[email protected]>
*/
class Mapper
{
/**
* Salesforce client
*
* @var ClientInterface
*/
private $client;
/**
* Salesforce annotations reader
*
* @var AnnotationReader
*/
private $annotationReader;
/**
* Cache
*
* @var Cache
*/
private $cache;
/**
* Symfony event dispatcher
*
* @var EventDispatcherInterface
*/
private $eventDispatcher;
/**
* Construct mapper
*
* @param SoapClient $soapClient
* @param AnnotationReader $annotationReader
* @param Cache $cache
*/
public function __construct(ClientInterface $client, AnnotationReader $annotationReader, Cache $cache)
{
$this->client = $client;
$this->annotationReader = $annotationReader;
$this->cache = $cache;
}
/**
* Get event dispatcher
*
* @return type EventDispatcherInterface
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* Set event dispatcher
*
* @param EventDispatcherInterface $eventDispatcher
* @return Mapper
*/
public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
return $this;
}
/**
* Get object count
*
* @param string $modelClass Model class name
* @param boolean $includeDeleted
* @param array $criteria
* @return int
*/
public function count($modelClass, $includeDeleted = false, array $criteria = array())
{
$object = $this->annotationReader->getSalesforceObject($modelClass);
if (null === $object) {
throw new \UnexpectedValueException('Model has no Salesforce annotation');
}
$query = trim("select count() from {$object->name} "
. $this->getQueryWherePart($criteria, $modelClass));
if (true === $includeDeleted) {
$result = $this->client->queryAll($query);
} else {
$result = $this->client->query($query);
}
if ($result) {
return $result->count();
}
}
/**
* Delete one or more records from Salesforce
*
* @param array $models
* @return array
*/
public function delete(array $models)
{
$ids = array();
foreach ($models as $model) {
$ids[] = $model->getId();
}
return $this->client->delete($ids);
}
/**
* Find one object by id
*
* @param mixed $model Model object or class name
* @param string $id Object id
* @param int $related Number of levels of related records to include
* @return object Mapped domain object
*/
public function find($model, $id, $related = 1)
{
$query = $this->getQuerySelectPart($model, $related)
. sprintf(' where Id=\'%s\'', $id);
$result = $this->client->query($query);
$mappedRecordIterator = new MappedRecordIterator($result, $this, $model);
return $mappedRecordIterator->first();
}
/**
* Find multiple objects by criteria and return result as an iterator
*
* @param object $model Model object or class name
* @param array $criteria Criteria as key/value pairs
* @param array $order Order to sort by as key/value pairs
* @param int $related Number of levels of related records to include
* @param bool $deleted Whether to include deleted records
* @return MappedRecordIterator
*/
public function findBy($model, array $criteria, array $order = array(),
$related = 1, $deleted = false)
{
$query = $this->getQuerySelectPart($model, $related)
. $this->getQueryWherePart($criteria, $model)
. $this->getQueryOrderByPart($order, $model);
if (true === $deleted) {
$result = $this->client->queryAll($query);
} else {
$result = $this->client->query($query);
}
return new MappedRecordIterator($result, $this, $model);
}
/**
* Find one object by criteria
*
* @param object $model
* @param array $criteria
* @param array $order
* @param int $related
* @param bool $deleted
* @return object
*/
public function findOneBy($model, array $criteria, array $order = array(),
$related = 2, $deleted = false)
{
$iterator = $this->findBy($model, $criteria, $order, $related, $deleted);
return $iterator->first();
}
/**
* Fetch all objects of a certain type
*
* @param object $model Model object or class name
* @param array $order Order to sort by as key/value pairs
* @param boolean $related Number of levels of related records to include
* @param boolean $deleted Whether to include deleted records
* @return MappedRecordIterator
*/
public function findAll($model, array $order = array(), $related = 1,
$deleted = false)
{
return $this->findBy($model, array(), $order, $related, $deleted);
}
/**
* Get object description, if possible from cache
*
* @param object $model Model object or class name
* @return Response\DescribeSObjectResult
* @throws \InvalidArgumentException
*/
public function getObjectDescription($model)
{
$object = $this->annotationReader->getSalesforceObject($model);
return $this->doGetObjectDescription($object->name);
}
/**
* Save one or more domain models to Salesforce
*
* @param mixed $model One model or array of models
* @return Response\SaveResult[]
*/
public function save($model)
{
$models = is_array($model) ? $model : array($model);
if ($this->eventDispatcher) {
$event = new BeforeSaveEvent($models);
$this->eventDispatcher->dispatch(Events::beforeSave, $event);
}
$objectsToBeCreated = array();
$objectsToBeUpdated = array();
$modelsWithoutId = array();
foreach ($models as $model) {
$object = $this->annotationReader->getSalesforceObject($model);
$sObject = $this->mapToSalesforceObject($model);
if (isset($sObject->Id) && null !== $sObject->Id) {
$objectsToBeUpdated[$object->name][] = $sObject;
} else {
$objectsToBeCreated[$object->name][] = $sObject;
$modelsWithoutId[$object->name][] = $model;
}
}
$results = array();
foreach ($objectsToBeCreated as $objectName => $sObjects) {
$reflClass = new \ReflectionClass(current(
$modelsWithoutId[$objectName]
));
$reflProperty = $reflClass->getProperty('id');
$reflProperty->setAccessible(true);
$saveResults = $this->client->create($sObjects, $objectName);
for ($i = 0; $i < count($saveResults); $i++) {
$newId = $saveResults[$i]->id;
$model = $modelsWithoutId[$objectName][$i];
$reflProperty->setValue($model, $newId);
}
$results[] = $saveResults;
}
foreach ($objectsToBeUpdated as $objectName => $sObjects) {
$results[] = $this->client->update($sObjects, $objectName);
}
return $results;
}
/**
* Map a Salesforce object to a domain model object
*
* Uses reflection instead of setters because read-only properties on
* ojects should not need a setter.
*
* @param object $sObject
* @param string $modelClass Model class name
* @return object A mapped instantiation of the model class
*/
public function mapToDomainObject($sObject, $modelClass)
{
$model = new $modelClass();
$reflObject = new \ReflectionObject($model);
// Set Salesforce property values on domain object
$fields = $this->annotationReader->getSalesforceFields($modelClass);
foreach ($fields as $name => $field) {
if (isset($sObject->{$field->name})) {
// Use reflection to set the protected/private properties
$reflProperty = $reflObject->getProperty($name);
$reflProperty->setAccessible(true);
$reflProperty->setValue($model, $sObject->{$field->name});
}
}
// Set Salesforce relations on domain object
$relations = $this->annotationReader->getSalesforceRelations($modelClass);
foreach ($relations as $property => $relation) {
// Relation name must be set
if (isset($sObject->{$relation->name})) {
$value = $sObject->{$relation->name};
if ($value instanceof Response\RecordIterator) {
$value = new MappedRecordIterator(
$value, $this, $relation->class
);
} else {
$value = $this->mapToDomainObject(
$sObject->{$relation->name}, $relation->class
);
}
$reflProperty = $reflObject->getProperty($property);
$reflProperty->setAccessible(true);
$reflProperty->setValue($model, $value);
}
}
return $model;
}
/**
* Map a PHP model object to a Salesforce object
*
* The PHP object must be properly annoated
*
* @param mixed $model PHP model object
* @return \stdClass
*/
public function mapToSalesforceObject($model)
{
$sObject = new \stdClass;
$sObject->fieldsToNull = array();
$objectDescription = $this->getObjectDescription($model);
$reflClass = new \ReflectionClass($model);
$mappedProperties = $this->annotationReader->getSalesforceFields($model);
$mappedRelations = $this->annotationReader->getSalesforceRelations($model);
$allMappings = $mappedProperties->toArray() + $mappedRelations;
foreach ($allMappings as $property => $mapping) {
if ($mapping instanceof Annotation\Field) {
$fieldDescription = $objectDescription->getField($mapping->name);
$fieldName = $mapping->name;
} elseif ($mapping instanceof Annotation\Relation
&& $mapping->field) {
// Only one-to-one and one-to-many relations will be saved
$fieldDescription = $objectDescription->getField($mapping->field);
$fieldName = $mapping->field;
} else {
// Do not save many-to-many relations
continue;
}
if (!$fieldDescription) {
throw new \InvalidArgumentException(sprintf(
'Field %s (for property ‘%s’) does not exist on %s. '
. 'If you think it does, try emptying your cache.',
$fieldName, $property, $objectDescription->getName()
));
}
// If the object is created, only allow creatable fields.
// If the object is updated, only allow updatable.
if (($model->getId() && $fieldDescription->isUpdateable())
|| (!$model->getId() && $fieldDescription->isCreateable())
// for 'Id' field:
|| $fieldDescription->isIdLookup()) {
// Get value through reflection
$reflProperty = $reflClass->getProperty($property);
$reflProperty->setAccessible(true);
$value = $reflProperty->getValue($model);
if ($mapping instanceof Annotation\Relation) {
// @todo Implements recursive saving for new related
// records, too. This only works for already existing
// records.
if (method_exists($value, 'getId') && $value->getId()) {
$value = $value->getId();
$sObject->{$fieldDescription->getName()} = $value;
continue;
}
}
if (null === $value || (is_string($value) && $value === '')) {
// Do not set fieldsToNull on create
if ($model->getId()) {
$sObject->fieldsToNull[] = $fieldDescription->getName();
}
} else {
$sObject->{$fieldDescription->getName()} = $value;
}
}
}
// Strip all values from fields to null for which values have been
// set in the SObject
if (isset($sObject->fieldsToNull)) {
foreach ($sObject->fieldsToNull as $fieldToNull) {
if (isset($sObject->$fieldToNull)) {
unset($sObject->fieldsToNull);
}
}
}
return $sObject;
}
/**
* Get object description for Salesforce object
*
* @param string $objectName Name of the Salesforce object
* @return DescribeSObjectResult
* @throws \InvalidArgumentException
*/
private function doGetObjectDescription($objectName)
{
$cacheId = sprintf('ddeboer_salesforce_mapper.object_description.%s',
$objectName);
if ($this->cache->contains($cacheId)) {
return $this->cache->fetch($cacheId);
}
$descriptions = $this->client->describeSObjects(array($objectName));
if (count($descriptions) === 0) {
throw new \InvalidArgumentException('Salesforce object does not exist');
}
$description = /* @var $description DescribeSObjectResult */ $descriptions[0];
$this->cache->save($cacheId, $description);
return $description;
}
/**
* Get query basis
*
* @param string $modelClass Model class name
* @param int $related Number of levels of related records to include
* in query
* 0: do not include related records
* 1: include one level of related records, for
* instance owner on opportunity
* 2: include two levels, for instance owner and
* account owner on opportunity.
* @return string
*/
private function getQuerySelectPart($modelClass, $related)
{
$object = $this->annotationReader->getSalesforceObject($modelClass);
$fields = $this->getFields($modelClass, $related);
$oneToMany = $this->getOneToManySubqueries($modelClass, $related);
$select = $this->getSelect($object->name, $fields, $oneToMany);
return $select;
}
private function getSelect($object, $fields, $subqueries = array())
{
$select = 'select '
. implode(',', $fields);
if (count($subqueries) > 0) {
$select .= ', ' . implode(',', $subqueries);
}
$select .= ' from ' . $object;
return $select;
}
/**
* Get SOQL where query part based on criteria array
*
* @param array $criteria
* @return string
*/
private function getQueryWherePart(array $criteria, $model)
{
$whereParts = array();
$object = $this->annotationReader->getSalesforceObject($model);
$fields = $this->annotationReader->getSalesforceFields($model);
$objectDescription = $this->doGetObjectDescription($object->name);
foreach ($criteria as $key => $value) {
// Check if the criterion has an operator
$keyParts = explode(' ', $key);
// Criterion key has an operator part
if (isset($keyParts[1])) {
$operator = $keyParts[1];
} else {
// Criterion key has no operator, so add it ourselves
$operator = '=';
}
$name = $keyParts[0];
$field = $this->annotationReader->getSalesforceField($model, $name);
if (!$field) {
throw new \InvalidArgumentException('Invalid field ' . $name);
}
$whereParts[] = sprintf('%s %s %s',
$field->name,
$operator,
$this->getQuotedWhereValue($field, $value, $objectDescription)
);
}
if (!empty($whereParts)) {
return ' where ' . implode(' and ', $whereParts);
}
}
/**
* Get quoted where value
*
* @param Annotation\Field $field
* @param mixed $value
* @param DescribeSObjectResult $description
* @return string
* @throws \InvalidArgumentException
* @link http://www.salesforce.com/us/developer/docs/api/Content/field_types.htm#topic-title
*/
private function getQuotedWhereValue(Annotation\Field $field, $value,
Response\DescribeSObjectResult $description)
{
$fieldDescription = $description->getField($field->name);
if (!$fieldDescription) {
throw new \InvalidArgumentException(
sprintf('\'%s\' on object %s is not a valid field',
$field->name,
$description->getName()
)
);
}
switch ($fieldDescription->getType()) {
case 'date':
if ($value instanceof \DateTime) {
return $value->format('Y-m-d');
}
case 'datetime':
if ($value instanceof \DateTime) {
$value = $value->setTimeZone(new \DateTimeZone('UTC'));
return $value->format('Y-m-d\TH:i:sP');
} else {
// A text representation, such as ‘yesterday’: these should
// not be enclosed in quotes
return $value;
}
case 'boolean':
return $value ? 'true' : 'false';
case 'double':
case 'currency':
case 'percent':
case 'int':
return $value;
default:
return "'" . addslashes($value) . "'";
}
}
/**
* Get SOQL order by query part from order by array
*
* @param array $orderBy
* @return string
*/
private function getQueryOrderByPart(array $orderBy, $model)
{
$orderParts = array();
foreach ($orderBy as $field => $direction) {
$fieldAnnotation = $this->annotationReader->getSalesforceField($model, $field);
$orderParts[] = $fieldAnnotation->name . ' ' . $direction;
}
if (!empty($orderParts)) {
return ' order by ' . implode(',', $orderParts);
}
}
/**
* Get Salesforce fields and its relations from a Salesforce-annotated model
*
* @param string $modelClass
* @param int $includeRelatedLevels
* @param string $ignoreObject Salesforce object name of model for which
* fields should not be returned
* @return array
*/
private function getFields($modelClass, $includeRelatedLevels, $ignoreObject = null)
{
$fields = array();
foreach ($this->annotationReader->getSalesforceFields($modelClass) as $field) {
$fields[] = $field->name;
}
$description = $this->getObjectDescription($modelClass);
if ($includeRelatedLevels > 0) {
foreach($this->annotationReader->getSalesforceRelations($modelClass) as $relation) {
// Only process one-to-one and many-to-one relations here;
// one-to-many relations must be looked up as subquery.
if (!$relation->field) {
continue;
}
// Check whether we can find this relation
$relationshipField = $description->getRelationshipField($relation->field);
if (!$relationshipField) {
throw new \InvalidArgumentException(
'Field ' . $relation->field . ' does not exist on ' . $description->getName());
continue;
}
// If the referenced object should be ignored, don't fetch its
// fields
if ($ignoreObject && $relationshipField->references($ignoreObject)) {
continue;
}
$relatedFields = $this->getFields($relation->class, --$includeRelatedLevels);
foreach ($relatedFields as $relatedField) {
$fields[] = sprintf('%s.%s', $relationshipField->getRelationshipName(), $relatedField);
}
}
}
return $fields;
}
/**
* Gets subqueries (sub selects) for annoted one-to-many relations on the
* model
*
* @param object $model
* @param int $includeRelatedLevels
*/
public function getOneToManySubqueries($model, $includeRelatedLevels)
{
$relations = $this->annotationReader->getSalesforceRelations($model);
$object = $this->annotationReader->getSalesforceObject($model);
$subqueries = array();
if ($includeRelatedLevels > 0) {
foreach ($relations as $relation) {
// Only process one-to-many relations here
if ($relation->field) {
continue;
}
$fields = $this->getFields($relation->class, $includeRelatedLevels, $object->name);
$subqueries[] = sprintf('(%s)',
$this->getSelect($relation->name, $fields));
}
}
return $subqueries;
}
public function getClassMetadata($className)
{
$class;
}
public function merge($merge)
{
}
/**
* Create query builder
*
* @return Builder
*/
public function createQueryBuilder()
{
return new Builder($this, $this->client, $this->annotationReader);
}
}