Completed
Pull Request — 2.0 (#7)
by Raphaël
11:08
created

ZohoDatabasePusher::updateDataZohoBean()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 7
Ratio 87.5 %

Importance

Changes 2
Bugs 1 Features 1
Metric Value
c 2
b 1
f 1
dl 7
loc 8
rs 9.2
cc 4
eloc 5
nc 3
nop 4
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
                $this->connection->beginTransaction();
120
                $this->connection->update($tableName, ['id' => $zohoBean->getZohoId()], ['uid' => $uid]);
121
                $this->connection->delete('local_insert', [ 'uid' => $uid ]);
122
                $this->connection->commit();
123
            }
124
        } else {
125
            $this->connection->executeUpdate('delete from local_update where uid in ( :rowsDeleted)',
126
                [
127
                'rowsDeleted' => $rowsDeleted,
128
                ],
129
                [
130
                'rowsDeleted' => Connection::PARAM_INT_ARRAY,
131
                ]
132
            );
133
        }
134
    }
135
136
    /**
137
     * Insert data to bean in order to insert zoho records.
138
     *
139
     * @param ZohoBeanInterface $zohoBean
140
     * @param array             $fieldsMatching
141
     * @param array             $row
142
     */
143 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...
144
    {
145
        foreach ($row as $columnName => $columnValue) {
146
            if ((!in_array($columnName, ['id', 'uid']) || isset($fieldsMatching[$columnName])) && !is_null($columnValue)) {
147
                $type = $fieldsMatching[$columnName]['type'];
148
                $value = $this->formatValueToBeans($type, $columnValue);
149
                $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
150
            }
151
        }
152
    }
153
154
    /**
155
     * Insert data to bean in order to update zoho records.
156
     *
157
     * @param ZohoBeanInterface $zohoBean
158
     * @param array             $fieldsMatching
159
     * @param type              $columnName
160
     * @param type              $valueDb
161
     */
162 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...
163
    {
164
        if (!in_array($columnName, ['id', 'uid']) || (isset($fieldsMatching[$columnName]))) {
165
            $type = $fieldsMatching[$columnName]['type'];
166
            $value = is_null($valueDb) ? $valueDb : $this->formatValueToBeans($type, $valueDb);
167
            $zohoBean->{$fieldsMatching[$columnName]['setter']}($value);
168
        }
169
    }
170
171
    /**
172
     * Change the value to the good format.
173
     *
174
     * @param string $type
175
     * @param mixed  $value
176
     *
177
     * @return mixed
178
     */
179
    private function formatValueToBeans($type, $value)
180
    {
181
        switch ($type) {
182
            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...
183
                $value = \DateTime::createFromFormat('Y-m-d', $value);
184
                break;
185
            case 'DateTime':
186
                $value = \DateTime::createFromFormat('Y-m-d H:i:s', $value);
187
                break;
188
        }
189
190
        return $value;
191
    }
192
193
    /**
194
     * Run deleted rows to Zoho : local_delete.
195
     *
196
     * @param AbstractZohoDao $zohoDao
197
     */
198
    public function pushDeletedRows(AbstractZohoDao $zohoDao)
199
    {
200
        $localTable = 'local_delete';
201
        $tableName = ZohoDatabaseHelper::getTableName($zohoDao, $this->prefix);
202
        $statement = $this->connection->createQueryBuilder();
203
        $statement->select('l.id')
204
        ->from($localTable, 'l')
205
        ->where('l.table_name=:table_name')
206
        ->setParameters([
207
            'table_name' => $tableName,
208
        ]);
209
        $results = $statement->execute();
210
        while ($row = $results->fetch()) {
211
            $zohoDao->delete($row['id']);
212
            $this->connection->delete($localTable, ['table_name' => $tableName, 'id' => $row['id']]);
213
        }
214
    }
215
216
    /**
217
     * Run inserted rows to Zoho : local_insert.
218
     *
219
     * @param AbstractZohoDao $zohoDao
220
     */
221
    public function pushInsertedRows(AbstractZohoDao $zohoDao)
222
    {
223
        return $this->pushDataToZoho($zohoDao);
224
    }
225
226
    /**
227
     * Run updated rows to Zoho : local_update.
228
     *
229
     * @param AbstractZohoDao $zohoDao
230
     */
231
    public function pushUpdatedRows(AbstractZohoDao $zohoDao)
232
    {
233
        $this->pushDataToZoho($zohoDao, true);
234
    }
235
236
    /**
237
     * Push data from db to Zoho.
238
     *
239
     * @param AbstractZohoDao $zohoDao
240
     */
241
    public function pushToZoho(AbstractZohoDao $zohoDao)
242
    {
243
        $this->logger->info(' > Insert new rows using {class_name}', ['class_name' => get_class($zohoDao)]);
244
        $this->pushInsertedRows($zohoDao);
245
        $this->logger->info(' > Update rows using {class_name}', ['class_name' => get_class($zohoDao)]);
246
        $this->pushUpdatedRows($zohoDao);
247
        $this->logger->info(' > Delete rows using  {class_name}', ['class_name' => get_class($zohoDao)]);
248
        $this->pushDeletedRows($zohoDao);
249
    }
250
    
251
}
252