Completed
Pull Request — 1.1 (#3)
by Raphaël
02:24
created

ZohoDatabaseSyncZoho::deleteDataToZoho()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 15
rs 9.4285
cc 2
eloc 12
nc 2
nop 2
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
use Wabel\Zoho\CRM\Exception\ZohoCRMException;
11
use Wabel\Zoho\CRM\Exception\ZohoCRMResponseException;
12
use function Stringy\create as s;
13
14
/**
15
 * Description of ZohoDatabaseSyncZoho
16
 *
17
 * @author rbergina
18
 */
19
class ZohoDatabaseSyncZoho
20
{
21
22
    /**
23
     * @var Connection
24
     */
25
    private $connection;
26
27
    /**
28
     * @var LoggerInterface
29
     */
30
    private $logger;
31
32
    /**
33
     *
34
     * @var string
35
     */
36
    private $prefix;
37
38
    /**
39
     * @param Connection $connection
40
     * @param string $prefix
41
     * @param LoggerInterface $logger
42
     */
43
    public function __construct(Connection $connection, $prefix = 'zoho_', LoggerInterface $logger = null)
44
    {
45
        $this->connection = $connection;
46
        $this->prefix = $prefix;
47
        if ($logger === null) {
48
            $this->logger = new NullLogger();
49
        } else {
50
            $this->logger = $logger;
51
        }
52
    }
53
54
    /**
55
     *
56
     * @param AbstractZohoDao $zohoDao
57
     * @return array
58
     */
59
    private function findMethodValues(AbstractZohoDao $zohoDao){
60
        $fieldsMatching = array();
61
        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...
62
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
63
                $fieldsMatching[$fieldDescriptor['name']] = [
64
                    'setter' => $fieldDescriptor['setter']
65
                ];
66
            }
67
68
        }
69
        return $fieldsMatching;
70
    }
71
72
    /**
73
     * Insert or Update rows.
74
     * @param AbstractZohoDao $zohoDao
75
     * @param string $localTable
76
     */
77
    public function pushDataToZoho(AbstractZohoDao $zohoDao, $localTable, $update = false){
78
79
            $fieldsMatching = $this->findMethodValues($zohoDao);
80
            $tableName = $this->getTableName($zohoDao);
81
            $rowsDeleted = [];
82
            $statement = $this->connection->createQueryBuilder();
83
            $statement->select('zcrm.*');
84
            if($update){
85
                $statement->addSelect('l.field_name as updated_fieldname');
86
            }
87
            $statement->from($localTable, 'l')
88
            ->join('l', $tableName, 'zcrm', 'zcrm.uid = l.uid')
89
            ->where('l.table_name=:table_name')
90
            ->setParameters([
91
                'table_name' => $tableName
92
            ]);
93
            $results = $statement->execute();
94
            /* @var $zohoBeans ZohoBeanInterface[] */
95
            $zohoBeans = array();
96
            while ($row = $results->fetch()) {
97
                $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...
98
                /* @var $zohoBean ZohoBeanInterface */
99
                $zohoBean = new $beanClassName();
100
                if(!$update){
101
                    foreach ($row as $columnName => $columnValue) {
102
                        if (in_array($columnName,['id','uid'])) {
103
                            continue;
104
                        }else{
105
                           if($columnValue){
106
                               $zohoBean->{$fieldsMatching[$columnName]['setter']}($columnValue);
107
                           }
108
                        }
109
110
                    }
111
                    $zohoBeans[$row['uid']] =  $zohoBean;
112
                    $rowsDeleted[] = $row['uid'];
113
                } else{
114
                    $columnName = $row['updated_fieldname'];
115
                    $zohoBean->setZohoId($row['id']);
116
                    if (in_array($columnName,['uid'])) {
117
                        continue;
118
                    }else{
119
                        $zohoBean->{$fieldsMatching[$columnName]['setter']}($row[$columnName]);
120
                        $zohoBeans[] = $zohoBean;
121
                        $rowsDeleted[] = $row['uid'];
122
                    }
123
                }
124
            }
125
            $zohoDao->save($zohoBeans);
126
            if(!$update){
127
                foreach ($zohoBeans as $uid => $zohoBean) {
128
                    $this->connection->update($tableName, [ 'id'=>$zohoBean->getZohoId(),'lastActivityTime'=> date("Y-m-d H:i:s") ], ['uid'=>$uid ]);
129
                }
130
            }
131
            $statementDelete = $this->connection->prepare('delete from '.$localTable.' where uid in ( :rowsDeleted)');
132
            $statementDelete->execute([
133
                'rowsDeleted' => implode(',', $rowsDeleted)
134
            ]);
135
    }
136
137
    /**
138
     * Find the row to delete and remove to Zoho.
139
     * @param AbstractZohoDao $zohoDao
140
     * @param string $localTable
141
     */
142
    public function deleteDataToZoho(AbstractZohoDao $zohoDao, $localTable){
143
        $tableName = $this->getTableName($zohoDao);
144
        $statement = $this->connection->createQueryBuilder();
145
        $statement->select('l.id')
146
        ->from($localTable, 'l')
147
        ->where('l.table_name=:table_name')
148
        ->setParameters([
149
            'table_name' => $tableName
150
        ]);
151
        $results = $statement->execute();
152
        while ($row = $results->fetch()) {
153
            $zohoDao->delete($row['id']);
154
            $this->connection->delete($localTable, ['table_name' => $tableName,'id' => $row['id']]);
155
        }
156
}
157
    
158
    /**
159
     * Run inserted rows to Zoho : local_insert.
160
     * @param AbstractZohoDao $zohoDao
161
     */
162
    public function pushInsertedRows(AbstractZohoDao $zohoDao){
163
        return $this->pushDataToZoho($zohoDao, 'local_insert');
164
    }
165
166
    /**
167
     * Run updated rows to Zoho : local_update.
168
     * @param AbstractZohoDao $zohoDao
169
     */
170
    public function pushUpdatedRows(AbstractZohoDao $zohoDao){
171
        $this->pushDataToZoho($zohoDao, 'local_update', true);
172
    }
173
174
    /**
175
     * Run deleted rows to Zoho : local_delete.
176
     * @param AbstractZohoDao $zohoDao
177
     */
178
    public function pushDeletedRows(AbstractZohoDao $zohoDao){
179
        $this->deleteDataToZoho($zohoDao, 'local_delete');
180
    }
181
182
    /**
183
     * Computes the name of the table based on the DAO plural module name.
184
     *
185
     * @param AbstractZohoDao $dao
186
     *
187
     * @return string
188
     */
189 View Code Duplication
    private function getTableName(AbstractZohoDao $dao)
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...
190
    {
191
        $tableName = $this->prefix.$dao->getPluralModuleName();
0 ignored issues
show
Bug introduced by
The method getPluralModuleName() 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...
192
        $tableName = s($tableName)->upperCamelize()->underscored();
193
194
        return (string) $tableName;
195
    }
196
197
198
    /**
199
     * @param LoggerInterface $logger
200
     */
201
    public function setLogger(LoggerInterface $logger)
202
    {
203
        $this->logger = $logger;
204
    }
205
206
207
}