Completed
Pull Request — 2.0 (#51)
by
unknown
01:13
created

AbstractZohoDao::isLogResponses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
namespace Wabel\Zoho\CRM;
4
5
use Wabel\Zoho\CRM\BeanComponents\Field;
6
use Wabel\Zoho\CRM\Exceptions\ExceptionZohoClient;
7
use Wabel\Zoho\CRM\Exceptions\ZohoCRMORMException;
8
use Wabel\Zoho\CRM\Helpers\BeanHelper;
9
use Wabel\Zoho\CRM\Helpers\ComponentHelper;
10
use Wabel\Zoho\CRM\Helpers\ZCRMModuleHelper;
11
12
/**
13
 * Base class that provides access to Zoho through Zoho beans.
14
 */
15
abstract class AbstractZohoDao
16
{
17
18
    /**
19
     * The class implementing API methods not directly related to a specific module.
20
     *
21
     * @var ZohoClient
22
     */
23
    protected $zohoClient;
24
25
    /**
26
     * Wether or not to log Zoho Api Reponses
27
     *
28
     * @var bool
29
     */
30
    protected $logResponses = false;
31
32
    public function __construct(ZohoClient $zohoClient)
33
    {
34
        $this->zohoClient = $zohoClient;
35
    }
36
37
    abstract protected function getModule();
38
    abstract protected function getSingularModuleName();
39
    abstract protected function getPluralModuleName();
40
    abstract protected function getBeanClassName();
41
    abstract protected function getFieldsDetails();
42
43
    /**
44
     * @return bool
45
     */
46
    public function isLogResponses(): bool {
47
        return $this->logResponses;
48
    }
49
50
    /**
51
     * @param bool $logResponses
52
     */
53
    public function setLogResponses( bool $logResponses ): void {
54
        $this->logResponses = $logResponses;
55
    }
56
57
    /**
58
     * @return ZohoClient
59
     */
60
    public function getZohoClient(): ZohoClient
61
    {
62
        return $this->zohoClient;
63
    }
64
65
66
    /**
67
     * @return Field[]
68
     */
69
    public function getFields()
70
    {
71
        return array_map(
72
            function (array $fieldDetails) {
73
                return ComponentHelper::createFieldFromArray($fieldDetails);
74
            }, $this->getFieldsDetails()
75
        );
76
    }
77
78
79
    /**
80
     * Returns a module from Zoho.
81
     *
82
     * @return \ZCRMModule
83
     */
84
    public function getZCRMModule()
85
    {
86
        return $this->zohoClient->getModule($this->getModule());
87
    }
88
89
    /**
90
     * Parse a Zoho Response in order to retrieve one or several ZohoBeans from it.
91
     *
92
     * @param  \ZCRMRecord[] $ZCRMRecords
93
     * @return ZohoBeanInterface[] The array of Zoho Beans parsed from the response
94
     * @throws ZohoCRMORMException
95
     */
96
    protected function getBeansFromZCRMRecords(array $ZCRMRecords)
97
    {
98
        $beanClass = $this->getBeanClassName();
99
        $beanArray = array();
100
101
        foreach ($ZCRMRecords as $record) {
102
103
            /**
104
 * @var ZohoBeanInterface $bean 
105
*/
106
            $bean = new $beanClass();
107
            BeanHelper::updateZCRMRecordToBean($this, $bean, $record);
108
            $beanArray[] = $bean;
109
        }
110
111
        return $beanArray;
112
    }
113
114
    /**
115
     * Implements deleteRecords API method.
116
     *
117
     * @param  string $id
118
     * @return ZohoBeanInterface[]
119
     * @throws ZohoCRMORMException
120
     */
121
    public function delete($id): array
122
    {
123
        /***
124
         * @var $ZCRMRecordDeleted \EntityResponse[]
125
         */
126
        $ZCRMRecordsDeleted = $this->zohoClient->deleteRecords($this->getModule(), $id);
127
128
        $recordsToDeleted = array_map(
129
            function (\EntityResponse $ZCRMRecordDeleted) {
130
                return $ZCRMRecordDeleted->getData();
131
            }, $ZCRMRecordsDeleted
132
        );
133
134
        return $this->getBeansFromZCRMRecords($recordsToDeleted);
135
    }
136
137
    /**
138
     * Implements getRecordById API method.
139
     *
140
     * @param string $id Zoho Id of the record to retrieve OR an array of IDs
141
     *
142
     * @return ZohoBeanInterface The array of Zoho Beans parsed from the response
143
     * @throws ZohoCRMORMException
144
     */
145
    public function getById($id): ZohoBeanInterface
146
    {
147
            $module = $this->getModule();
148
            $ZCRMRecord = $this->zohoClient->getRecordById($module, $id);
149
            $beans =  $this->getBeansFromZCRMRecords([$ZCRMRecord]);
0 ignored issues
show
Documentation introduced by
array($ZCRMRecord) is of type array<integer,object<ZCR...ect<ZCRMRecord>|null"}>, but the function expects a array<integer,object<ZCRMRecord>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
150
151
            return $beans[0];
152
    }
153
154
    /**
155
     * Implements getRecords API method.
156
     *
157
     * @param  string|null    $cvId
158
     * @param  string|null    $sortColumnString
159
     * @param  string|null    $sortOrderString
160
     * @param  \DateTime|null $lastModifiedTime
161
     * @param  int            $page
162
     * @param  int            $perPage
163
     * @return ZohoBeanInterface[]
164
     * @throws ZohoCRMORMException
165
     * @throws \ZCRMException
166
     */
167
    public function getRecords($cvId = null, $sortColumnString = null, $sortOrderString = null, \DateTime $lastModifiedTime = null, $page = 1, $perPage = 200): array
168
    {
169
        try{
170
            $ZCRMRecords =  ZCRMModuleHelper::getAllZCRMRecordsFromPagination($this->zohoClient, $this->getModule(),
171
                $cvId, $sortColumnString, $sortOrderString, $page, $perPage, $lastModifiedTime);
172
        } catch(\ZCRMException $exception){
173
            if(ExceptionZohoClient::exceptionCodeFormat($exception->getExceptionCode()) === ExceptionZohoClient::EXCEPTION_CODE_NO__CONTENT) {
174
                $ZCRMRecords = [];
175
            } else{
176
                $this->zohoClient->logException($exception);
177
                throw $exception;
178
            }
179
        }
180
        return $this->getBeansFromZCRMRecords($ZCRMRecords);
181
    }
182
183
    /**
184
     * Returns the list of deleted records.
185
     *
186
     * @param  \DateTimeInterface|null $lastModifiedTime
187
     * @param  int                     $page
188
     * @param  int                     $perPage
189
     * @return \ZCRMTrashRecord[]
190
     * @throws \ZCRMException
191
     */
192
    public function getDeletedRecordIds(\DateTimeInterface $lastModifiedTime = null, $page = 1, $perPage = 200)
193
    {
194
        return ZCRMModuleHelper::getAllZCRMTrashRecordsFromPagination($this->zohoClient, $this->getModule(), 'all', $lastModifiedTime, $page, $perPage);
195
    }
196
197
    /**
198
     * @Todo
199
     */
200
    // public function getRelatedRecords
201
    // public function searchRecords
202
    // public function uploadFile
203
    // public function downloadFile
204
205
    /**
206
     * Implements insertRecords or updateRecords or upsertRecords API method.
207
     *
208
     * @param  ZohoBeanInterface[] $beans
209
     * @param  bool                $wfTrigger Whether or not the call should trigger the workflows related to a "created" event
210
     * @throws ZohoCRMORMException
211
     */
212
    public function createOrUpdate( array $beans, bool $wfTrigger = false, $action = 'upsert'): void
213
    {
214
        /**
215
         * @var $records \ZCRMRecord[]
216
         */
217
        $records = [];
218
219
        $dao = $this;
220
        $processAction = ($action === 'update')?'updating':$action.'ing';
221
222
        foreach (array_chunk($beans, 100) as $beansPool) {
223
            /**
224
             * @var $beansPool ZohoBeanInterface[]
225
             */
226
            $recordsToMerge = array_map(
227
                function ($beanPool) use ($dao) {
228
                    /**
229
                     * @var $beanPool ZohoBeanInterface
230
                     */
231
                    BeanHelper::createOrUpdateBeanToZCRMRecord($dao, $beanPool);
232
                    return $beanPool->getZCRMRecord();
233
                }, $beansPool
234
            );
235
            $records = array_merge($records, $recordsToMerge);
236
            switch ($action){
237
            case 'insert':
238
                 $this->zohoClient->insertRecords($this->getModule(), $records, $wfTrigger);
239
                break;
240
            case 'update':
241
                $this->zohoClient->updateRecords($this->getModule(), $records, $wfTrigger);
242
                break;
243
            case 'upsert':
244
            default:
245
                $this->zohoClient->upsertRecords($this->getModule(), $records);
246
            }
247
        }
248
        if ($this->isLogResponses()) {
249
          foreach ( $responses as $response ) {
0 ignored issues
show
Bug introduced by
The variable $responses does not exist. Did you mean $response?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
250
            $this->getZohoClient()->getLogger()->debug( json_encode( $response->getResponseJSON(), JSON_PRETTY_PRINT ) );
0 ignored issues
show
Bug introduced by
The method getLogger() does not seem to exist on object<Wabel\Zoho\CRM\ZohoClient>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
251
          }
252
        }
253
        if (count($records) != count($beans)) {
254
            throw new ZohoCRMORMException('Error while '.$processAction.' beans in Zoho. '.count($beans).' passed in parameter, but '.count($records).' returned.');
255
        }
256
257
        foreach ($beans as $key => $bean) {
258
            BeanHelper::updateZCRMRecordToBean($dao, $bean, $records[$key]);
259
        }
260
    }
261
262
    /**
263
     * Implements insertRecords API method.
264
     *
265
     * @param  ZohoBeanInterface[] $beans
266
     * @param  bool                $wfTrigger Whether or not the call should trigger the workflows related to a "created" event
267
     * @throws ZohoCRMORMException
268
     */
269
    public function insertRecords( array $beans, bool $wfTrigger = false): void
270
    {
271
        $this->createOrUpdate($beans, $wfTrigger, 'insert');
272
    }
273
274
    /**
275
     * Implements updateRecords API method.
276
     *
277
     * @param  ZohoBeanInterface[] $beans
278
     * @param  bool                $wfTrigger
279
     * @throws ZohoCRMORMException
280
     */
281
    public function updateRecords(array $beans, bool $wfTrigger = false): void
282
    {
283
        $this->createOrUpdate($beans, $wfTrigger, 'update');
284
    }
285
286
    /**
287
     * Saves the bean or array of beans passed in Zoho.
288
     * It will perform an insert if the bean has no ZohoID or an update if the bean has a ZohoID.
289
     * wfTrigger only usable for a single record update/insert.
290
     *
291
     * @param ZohoBeanInterface|ZohoBeanInterface[] $beans     A bean or an array of beans.
292
     * @param bool                                  $wfTrigger
293
     */
294
    public function save($beans, $wfTrigger = false): void
295
    {
296
297
        if (!is_array($beans)) {
298
            $beans = [$beans];
299
        }
300
301
        $toInsert = [];
302
        $toUpdate = [];
303
304
        foreach ($beans as $bean) {
305
            if ($bean->getZohoId()) {
306
                $toUpdate[] = $bean;
307
            } else {
308
                $toInsert[] = $bean;
309
            }
310
        }
311
312
        if ($toInsert) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $toInsert of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
313
            $this->insertRecords($toInsert, $wfTrigger);
314
        }
315
        if ($toUpdate) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $toUpdate of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
316
            $this->updateRecords($toUpdate, $wfTrigger);
317
        }
318
    }
319
320
    /**
321
     * @return ZohoBeanInterface
322
     * @throws ZohoCRMORMException
323
     */
324
    public function create()
325
    {
326
        $record = \ZCRMRecord::getInstance($this->getModule(), null);
327
        $beanClassName = $this->getBeanClassName();
328
        $bean = new $beanClassName();
329
        BeanHelper::updateZCRMRecordToBean($this, $bean, $record);
330
        return $bean;
331
    }
332
333
    /**
334
     * @param  $fieldName
335
     * @return null|Field
336
     */
337
    public function getFieldFromFieldName($fieldName)
338
    {
339
        $fields = $this->getFields();
340
        /**
341
         * @var Field[] $field
342
         */
343
        $field = array_values(
344
            array_filter(
345
                $fields, function (Field $fiedObj) use ($fieldName) {
346
                    return $fiedObj->getName() === $fieldName;
347
                }
348
            )
349
        );
350
351
        return count($field) === 1?$field[0] :null;
352
    }
353
}
354