Cancelled
Push — 2.0 ( c33a68...ef9d4b )
by David
346:33 queued 346:33
created

ZohoDatabasePusher::insertDataZohoBean()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

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