Completed
Push — 2.0 ( 5143f7...50f362 )
by Raphaël
02:25
created

ZohoDatabasePusher   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 248
Duplicated Lines 6.85 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 8
Bugs 3 Features 1
Metric Value
wmc 34
c 8
b 3
f 1
lcom 1
cbo 6
dl 17
loc 248
rs 9.2

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A findMethodValues() 0 14 3
D pushDataToZoho() 0 73 12
B insertDataZohoBean() 10 10 5
A updateDataZohoBean() 7 8 4
A formatValueToBeans() 0 13 3
A pushDeletedRows() 0 17 2
A pushInsertedRows() 0 4 1
A pushUpdatedRows() 0 4 1
A pushToZoho() 0 9 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 string          $prefix
36
     * @param LoggerInterface $logger
37
     */
38
    public function __construct(Connection $connection, $prefix = 'zoho_', LoggerInterface $logger = null)
39
    {
40
        $this->connection = $connection;
41
        $this->prefix = $prefix;
42
        if ($logger === null) {
43
            $this->logger = new NullLogger();
44
        } else {
45
            $this->logger = $logger;
46
        }
47
    }
48
49
    /**
50
     * @param AbstractZohoDao $zohoDao
51
     *
52
     * @return array
53
     */
54
    private function findMethodValues(AbstractZohoDao $zohoDao)
55
    {
56
        $fieldsMatching = array();
57
        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...
58
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
59
                $fieldsMatching[$fieldDescriptor['name']] = [
60
                    'setter' => $fieldDescriptor['setter'],
61
                    'type' => $fieldDescriptor['type'],
62
                ];
63
            }
64
        }
65
66
        return $fieldsMatching;
67
    }
68
69
    /**
70
     * Insert or Update rows.
71
     *
72
     * @param AbstractZohoDao $zohoDao
73
     */
74
    public function pushDataToZoho(AbstractZohoDao $zohoDao, $update = false)
75
    {
76
        $localTable = $update ? 'local_update' : 'local_insert';
77
        $fieldsMatching = $this->findMethodValues($zohoDao);
78
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
79
        $rowsDeleted = [];
80
        $statement = $this->connection->createQueryBuilder();
81
        $statement->select('zcrm.*');
82
        if ($update) {
83
            $statement->addSelect('l.field_name as updated_fieldname');
84
        }
85
        $statement->from($localTable, 'l')
86
        ->join('l', $tableName, 'zcrm', 'zcrm.uid = l.uid')
87
        ->where('l.table_name=:table_name')
88
        ->setParameters([
89
            'table_name' => $tableName,
90
        ]);
91
        $results = $statement->execute();
92
        /* @var $zohoBeans ZohoBeanInterface[] */
93
        $zohoBeans = array();
94
        while ($row = $results->fetch()) {
95
            $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...
96
            /* @var $zohoBean ZohoBeanInterface */
97
            if (isset($zohoBeans[$row['uid']])) {
98
                $zohoBean = $zohoBeans[$row['uid']];
99
            } else {
100
                $zohoBean = new $beanClassName();
101
            }
102
103
            if (!$update) {
104
                $this->insertDataZohoBean($zohoBean, $fieldsMatching, $row);
105
                $zohoBeans[$row['uid']] = $zohoBean;
106
                $rowsDeleted[] = $row['uid'];
107
            }
108
            if ($update && isset($row['updated_fieldname'])) {
109
                $columnName = $row['updated_fieldname'];
110
                $zohoBean->getZohoId() ?: $zohoBean->setZohoId($row['id']);
111
                $this->updateDataZohoBean($zohoBean, $fieldsMatching, $columnName, $row[$columnName]);
112
                $zohoBeans[$row['uid']] = $zohoBean;
113
                $rowsDeleted[] = $row['uid'];
114
            }
115
        }
116
        $zohoDao->save($zohoBeans);
117
        if (!$update) {
118
            foreach ($zohoBeans as $uid => $zohoBean) {
119
                $countResult = $this->connection->fetchColumn('select count(id) from '.$tableName.' where id = :id',['id'=>$zohoBean->getZohoId()]);
120
                //If the sent data were duplicates Zoho can merged so we need to check if the Zoho ID already exist.
121
                if($countResult === 0) {
122
                    // ID not exist we can update the new row with the Zoho ID
123
                    $this->connection->beginTransaction();
124
                    $this->connection->update($tableName, ['id' => $zohoBean->getZohoId()], ['uid' => $uid]);
125
                    $this->connection->delete('local_insert', ['table_name'=>$tableName, 'uid' => $uid ]);
126
                    $this->connection->commit();
127
                } else {
128
                    //ID already exist we need to delete the duplicate row.
129
                    $this->connection->beginTransaction();
130
                    $this->connection->delete($tableName, ['uid' => $uid ]);
131
                    $this->connection->delete('local_insert', ['table_name'=>$tableName, 'uid' => $uid ]);
132
                    $this->connection->commit();
133
                    
134
                }
135
            }
136
        } else {
137
            $this->connection->executeUpdate('delete from local_update where uid in ( :rowsDeleted)',
138
                [
139
                'rowsDeleted' => $rowsDeleted,
140
                ],
141
                [
142
                'rowsDeleted' => Connection::PARAM_INT_ARRAY,
143
                ]
144
            );
145
        }
146
    }
147
148
    /**
149
     * Insert data to bean in order to insert zoho records.
150
     *
151
     * @param ZohoBeanInterface $zohoBean
152
     * @param array             $fieldsMatching
153
     * @param array             $row
154
     */
155 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...
156
    {
157
        foreach ($row as $columnName => $columnValue) {
158
            if ((!in_array($columnName, ['id', 'uid']) || isset($fieldsMatching[$columnName])) && !is_null($columnValue)) {
159
                $type = $fieldsMatching[$columnName]['type'];
160
                $value = $this->formatValueToBeans($type, $columnValue);
161
                $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
162
            }
163
        }
164
    }
165
166
    /**
167
     * Insert data to bean in order to update zoho records.
168
     *
169
     * @param ZohoBeanInterface $zohoBean
170
     * @param array             $fieldsMatching
171
     * @param type              $columnName
172
     * @param type              $valueDb
173
     */
174 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...
175
    {
176
        if (!in_array($columnName, ['id', 'uid']) || (isset($fieldsMatching[$columnName]))) {
177
            $type = $fieldsMatching[$columnName]['type'];
178
            $value = is_null($valueDb) ? $valueDb : $this->formatValueToBeans($type, $valueDb);
179
            $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
180
        }
181
    }
182
183
    /**
184
     * Change the value to the good format.
185
     *
186
     * @param string $type
187
     * @param mixed  $value
188
     *
189
     * @return mixed
190
     */
191
    private function formatValueToBeans($type, $value)
192
    {
193
        switch ($type) {
194
            case 'Date' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
195
                $value = \DateTime::createFromFormat('Y-m-d', $value);
196
                break;
197
            case 'DateTime':
198
                $value = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
199
                break;
200
        }
201
202
        return $value;
203
    }
204
205
    /**
206
     * Run deleted rows to Zoho : local_delete.
207
     *
208
     * @param AbstractZohoDao $zohoDao
209
     */
210
    public function pushDeletedRows(AbstractZohoDao $zohoDao)
211
    {
212
        $localTable = 'local_delete';
213
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
214
        $statement = $this->connection->createQueryBuilder();
215
        $statement->select('l.id')
216
        ->from($localTable, 'l')
217
        ->where('l.table_name=:table_name')
218
        ->setParameters([
219
            'table_name' => $tableName,
220
        ]);
221
        $results = $statement->execute();
222
        while ($row = $results->fetch()) {
223
            $zohoDao->delete($row['id']);
224
            $this->connection->delete($localTable, ['table_name' => $tableName, 'id' => $row['id']]);
225
        }
226
    }
227
228
    /**
229
     * Run inserted rows to Zoho : local_insert.
230
     *
231
     * @param AbstractZohoDao $zohoDao
232
     */
233
    public function pushInsertedRows(AbstractZohoDao $zohoDao)
234
    {
235
        return $this->pushDataToZoho($zohoDao);
236
    }
237
238
    /**
239
     * Run updated rows to Zoho : local_update.
240
     *
241
     * @param AbstractZohoDao $zohoDao
242
     */
243
    public function pushUpdatedRows(AbstractZohoDao $zohoDao)
244
    {
245
        $this->pushDataToZoho($zohoDao, true);
246
    }
247
248
    /**
249
     * Push data from db to Zoho.
250
     *
251
     * @param AbstractZohoDao $zohoDao
252
     */
253
    public function pushToZoho(AbstractZohoDao $zohoDao)
254
    {
255
        $this->logger->info(' > Insert new rows using {class_name}', ['class_name' => get_class($zohoDao)]);
256
        $this->pushInsertedRows($zohoDao);
257
        $this->logger->info(' > Update rows using {class_name}', ['class_name' => get_class($zohoDao)]);
258
        $this->pushUpdatedRows($zohoDao);
259
        $this->logger->info(' > Delete rows using  {class_name}', ['class_name' => get_class($zohoDao)]);
260
        $this->pushDeletedRows($zohoDao);
261
    }
262
    
263
}
264