Completed
Push — 2.0 ( 19a05a...780a67 )
by Raphaël
03:25 queued 01:42
created

ZohoDatabasePusher::pushInsertedRows()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Wabel\Zoho\CRM\Copy;
4
5
use Doctrine\DBAL\Connection;
6
use Psr\Log\LoggerInterface;
7
use Psr\Log\NullLogger;
8
use Wabel\Zoho\CRM\AbstractZohoDao;
9
use Wabel\Zoho\CRM\ZohoBeanInterface;
10
11
/**
12
 * Description of ZohoDatabasePusher.
13
 *
14
 * @author rbergina
15
 */
16
class ZohoDatabasePusher
17
{
18
    /**
19
     * @var Connection
20
     */
21
    private $connection;
22
23
    /**
24
     * @var LoggerInterface
25
     */
26
    private $logger;
27
28
    /**
29
     * @var string
30
     */
31
    private $prefix;
32
33
    /**
34
     * @param Connection $connection
35
     * @param int $apiLimitInsertUpdateDelete
36
     * @param string $prefix
37
     * @param LoggerInterface $logger
38
     */
39
    public function __construct(Connection $connection, $apiLimitInsertUpdateDelete = 100, $prefix = 'zoho_', LoggerInterface $logger = null)
40
    {
41
        $this->connection = $connection;
42
        $this->prefix = $prefix;
43
        if ($logger === null) {
44
            $this->logger = new NullLogger();
45
        } else {
46
            $this->logger = $logger;
47
        }
48
        $this->apiLimitInsertUpdateDelete = $apiLimitInsertUpdateDelete;
49
        if($apiLimitInsertUpdateDelete === null){
50
            $this->apiLimitInsertUpdateDelete = 100;
51
        }
52
    }
53
54
    /**
55
     * @var int
56
     */
57
    private $apiLimitInsertUpdateDelete;
58
59
    /**
60
     * @param AbstractZohoDao $zohoDao
61
     *
62
     * @return array
63
     */
64
    private function findMethodValues(AbstractZohoDao $zohoDao)
65
    {
66
        $fieldsMatching = array();
67
        foreach ($zohoDao->getFields() as $fieldsDescriptor) {
0 ignored issues
show
Bug introduced by
The method getFields() cannot be called from this context as it is declared protected in class Wabel\Zoho\CRM\AbstractZohoDao.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
68
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
69
                $fieldsMatching[$fieldDescriptor['name']] = [
70
                    'setter' => $fieldDescriptor['setter'],
71
                    'type' => $fieldDescriptor['type'],
72
                ];
73
            }
74
        }
75
76
        return $fieldsMatching;
77
    }
78
79
    /**
80
     * @param AbstractZohoDao $zohoDao
81
     * @param bool $update
82
     * @return int
83
     */
84
    private function countElementInTable(AbstractZohoDao $zohoDao, $update = false)
85
    {
86
        $localTable = $update ? 'local_update' : 'local_insert';
87
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
88
        return $this->connection->executeQuery('select uid from '.$localTable.' where table_name like :tableName',
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\DBAL\Driver\ResultStatement as the method rowCount() does only exist in the following implementations of said interface: Doctrine\DBAL\Cache\ResultCacheStatement, Doctrine\DBAL\Driver\IBMDB2\DB2Statement, Doctrine\DBAL\Driver\Mysqli\MysqliStatement, Doctrine\DBAL\Driver\OCI8\OCI8Statement, Doctrine\DBAL\Driver\PDOSqlsrv\Statement, Doctrine\DBAL\Driver\PDOStatement, Doctrine\DBAL\Driver\SQL...re\SQLAnywhereStatement, Doctrine\DBAL\Driver\SQLSrv\SQLSrvStatement, Doctrine\DBAL\Portability\Statement, Doctrine\DBAL\Statement.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
Security introduced by
If $localTable can contain user-input, it is usually preferable to use a parameter placeholder like :paramName and pass the dynamic input as second argument array('param' => $localTable).

Instead of embedding dynamic parameters in SQL, Doctrine also allows you to pass them separately and insert a placeholder instead:

function findUser(Doctrine\DBAL\Connection $con, $email) {
    // Unsafe
    $con->executeQuery("SELECT * FROM users WHERE email = '".$email."'");

    // Safe
    $con->executeQuery(
        "SELECT * FROM users WHERE email = :email",
        array('email' => $email)
    );
}
Loading history...
89
            ['tableName' => $tableName])->rowCount();
90
    }
91
92
    /**
93
     * Insert or Update rows.
94
     *
95
     * @param AbstractZohoDao $zohoDao
96
     */
97
    public function pushDataToZoho(AbstractZohoDao $zohoDao, $update = false)
98
    {
99
        $localTable = $update ? 'local_update' : 'local_insert';
100
        $fieldsMatching = $this->findMethodValues($zohoDao);
101
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
102
        do{
103
            $rowsDeleted = [];
104
            //@see https://www.zoho.com/crm/help/api/api-limits.html
105
            //To optimize your API usage, get maximum 200 records with each request and insert, update or delete maximum 100 records with each request.
106
            $statementLimiter = $this->connection->createQueryBuilder();
107
            $statementLimiter->select('DISTINCT table_name,uid')
108
                ->from($localTable)->setMaxResults($this->apiLimitInsertUpdateDelete);
109
            $statement = $this->connection->createQueryBuilder();
110
            $statement->select('zcrm.*');
111
            if ($update) {
112
                $statement->addSelect('l.field_name as updated_fieldname');
113
            }
114
            $statement->from($localTable, 'l')
115
                ->join('l','('.$statementLimiter->getSQL().')','ll','ll.table_name = l.table_name and  ll.uid = l.uid')
116
                ->join('l', $tableName, 'zcrm', 'zcrm.uid = l.uid')
117
                ->where('l.table_name=:table_name')
118
                ->setParameters([
119
                    'table_name' => $tableName,
120
                ])
121
            ;
122
            $results = $statement->execute();
123
            /* @var $zohoBeans ZohoBeanInterface[] */
124
            $zohoBeans = array();
125
            while ($row = $results->fetch()) {
126
                $beanClassName = $zohoDao->getBeanClassName();
0 ignored issues
show
Bug introduced by
The method getBeanClassName() cannot be called from this context as it is declared protected in class Wabel\Zoho\CRM\AbstractZohoDao.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
127
                /* @var $zohoBean ZohoBeanInterface */
128
                if (isset($zohoBeans[$row['uid']])) {
129
                    $zohoBean = $zohoBeans[$row['uid']];
130
                } else {
131
                    $zohoBean = new $beanClassName();
132
                }
133
134
                if (!$update) {
135
                    $this->insertDataZohoBean($zohoBean, $fieldsMatching, $row);
136
                    $zohoBeans[$row['uid']] = $zohoBean;
137
                    $rowsDeleted[] = $row['uid'];
138
                }
139
                if ($update && isset($row['updated_fieldname'])) {
140
                    $columnName = $row['updated_fieldname'];
141
                    $zohoBean->getZohoId() ?: $zohoBean->setZohoId($row['id']);
142
                    $this->updateDataZohoBean($zohoBean, $fieldsMatching, $columnName, $row[$columnName]);
143
                    $zohoBeans[$row['uid']] = $zohoBean;
144
                    $rowsDeleted[] = $row['uid'];
145
                }
146
            }
147
            $this->sendDataToZohoCleanLocal($zohoDao,$zohoBeans,$rowsDeleted,$update);
148
            $countToPush = $this->countElementInTable($zohoDao,$update);
149
        } while($countToPush > 0);
150
    }
151
152
    /**
153
     * @param AbstractZohoDao $zohoDao
154
     * @param ZohoBeanInterface[] $zohoBeans
155
     * @param string[] $rowsDeleted
156
     * @param bool $update
157
     */
158
    private function sendDataToZohoCleanLocal(AbstractZohoDao $zohoDao, array $zohoBeans,$rowsDeleted, $update = false)
159
    {
160
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
161
//        $zohoDao->save($zohoBeans);
162
        if (!$update) {
163
            foreach ($zohoBeans as $uid => $zohoBean) {
164
                $countResult = (int) $this->connection->fetchColumn('select count(id) from '.$tableName.' where id = :id', ['id'=>$zohoBean->getZohoId()]);
165
                //If the sent data were duplicates Zoho can merged so we need to check if the Zoho ID already exist.
166
                if ($countResult === 0) {
167
                    // ID not exist we can update the new row with the Zoho ID
168
                    $this->connection->beginTransaction();
169
                    $this->connection->update($tableName, ['id' => $zohoBean->getZohoId()], ['uid' => $uid]);
170
                    $this->connection->delete('local_insert', ['table_name'=>$tableName, 'uid' => $uid ]);
171
                    $this->connection->commit();
172
                } else {
173
                    //ID already exist we need to delete the duplicate row.
174
                    $this->connection->beginTransaction();
175
                    $this->connection->delete($tableName, ['uid' => $uid ]);
176
                    $this->connection->delete('local_insert', ['table_name'=>$tableName, 'uid' => $uid ]);
177
                    $this->connection->commit();
178
                }
179
            }
180
        } else {
181
            $this->connection->executeUpdate('delete from local_update where uid in ( :rowsDeleted)',
182
                [
183
                    'rowsDeleted' => $rowsDeleted,
184
                ],
185
                [
186
                    'rowsDeleted' => Connection::PARAM_INT_ARRAY,
187
                ]
188
            );
189
        }
190
    }
191
192
    /**
193
     * Insert data to bean in order to insert zoho records.
194
     *
195
     * @param ZohoBeanInterface $zohoBean
196
     * @param array             $fieldsMatching
197
     * @param array             $row
198
     */
199 View Code Duplication
    private function insertDataZohoBean(ZohoBeanInterface $zohoBean, array $fieldsMatching, array $row)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
200
    {
201
        foreach ($row as $columnName => $columnValue) {
202
            if ((!in_array($columnName, ['id', 'uid']) || isset($fieldsMatching[$columnName])) && !is_null($columnValue)) {
203
                $type = $fieldsMatching[$columnName]['type'];
204
                $value = $this->formatValueToBeans($type, $columnValue);
205
                $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
206
            }
207
        }
208
    }
209
210
    /**
211
     * Insert data to bean in order to update zoho records.
212
     *
213
     * @param ZohoBeanInterface $zohoBean
214
     * @param array             $fieldsMatching
215
     * @param type              $columnName
216
     * @param type              $valueDb
217
     */
218 View Code Duplication
    private function updateDataZohoBean(ZohoBeanInterface $zohoBean, array $fieldsMatching, $columnName, $valueDb)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
219
    {
220
        if (!in_array($columnName, ['id', 'uid']) || (isset($fieldsMatching[$columnName]))) {
221
            $type = $fieldsMatching[$columnName]['type'];
222
            $value = is_null($valueDb) ? $valueDb : $this->formatValueToBeans($type, $valueDb);
223
            $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
224
        }
225
    }
226
227
    /**
228
     * Change the value to the good format.
229
     *
230
     * @param string $type
231
     * @param mixed  $value
232
     *
233
     * @return mixed
234
     */
235
    private function formatValueToBeans($type, $value)
236
    {
237
        switch ($type) {
238
            case 'Date':
239
                $value = \DateTime::createFromFormat('Y-m-d', $value);
240
                break;
241
            case 'DateTime':
242
                $value = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
243
                break;
244
        }
245
246
        return $value;
247
    }
248
249
    /**
250
     * Run deleted rows to Zoho : local_delete.
251
     *
252
     * @param AbstractZohoDao $zohoDao
253
     */
254
    public function pushDeletedRows(AbstractZohoDao $zohoDao)
255
    {
256
        $localTable = 'local_delete';
257
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
258
        $statement = $this->connection->createQueryBuilder();
259
        $statement->select('l.id')
260
        ->from($localTable, 'l')
261
        ->where('l.table_name=:table_name')
262
        ->setParameters([
263
            'table_name' => $tableName,
264
        ]);
265
        $results = $statement->execute();
266
        while ($row = $results->fetch()) {
267
            $zohoDao->delete($row['id']);
268
            $this->connection->delete($localTable, ['table_name' => $tableName, 'id' => $row['id']]);
269
        }
270
    }
271
272
    /**
273
     * Run inserted rows to Zoho : local_insert.
274
     *
275
     * @param AbstractZohoDao $zohoDao
276
     */
277
    public function pushInsertedRows(AbstractZohoDao $zohoDao)
278
    {
279
        return $this->pushDataToZoho($zohoDao);
280
    }
281
282
    /**
283
     * Run updated rows to Zoho : local_update.
284
     *
285
     * @param AbstractZohoDao $zohoDao
286
     */
287
    public function pushUpdatedRows(AbstractZohoDao $zohoDao)
288
    {
289
        $this->pushDataToZoho($zohoDao, true);
290
    }
291
292
    /**
293
     * Push data from db to Zoho.
294
     *
295
     * @param AbstractZohoDao $zohoDao
296
     */
297
    public function pushToZoho(AbstractZohoDao $zohoDao)
298
    {
299
        $this->logger->info(' > Insert new rows using {class_name}', ['class_name' => get_class($zohoDao)]);
300
        $this->pushInsertedRows($zohoDao);
301
        $this->logger->info(' > Update rows using {class_name}', ['class_name' => get_class($zohoDao)]);
302
        $this->pushUpdatedRows($zohoDao);
303
        $this->logger->info(' > Delete rows using  {class_name}', ['class_name' => get_class($zohoDao)]);
304
        $this->pushDeletedRows($zohoDao);
305
    }
306
}
307