Completed
Pull Request — 2.0 (#15)
by Raphaël
08:24
created

ZohoDatabaseCopier::fetchUserFromZoho()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 44
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 8.439
c 0
b 0
f 0
cc 5
eloc 30
nc 7
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\Request\Response;
10
11
/**
12
 * This class is in charge of synchronizing one table of your database with Zoho records.
13
 */
14
class ZohoDatabaseCopier
15
{
16
    /**
17
     * @var Connection
18
     */
19
    private $connection;
20
21
    private $prefix;
22
23
    /**
24
     * @var ZohoChangeListener[]
25
     */
26
    private $listeners;
27
28
    /**
29
     * @var LoggerInterface
30
     */
31
    private $logger;
32
33
    /**
34
     * @var LocalChangesTracker
35
     */
36
    private $localChangesTracker;
37
38
    /**
39
     * ZohoDatabaseCopier constructor.
40
     *
41
     * @param Connection           $connection
42
     * @param string               $prefix     Prefix for the table name in DB
43
     * @param ZohoChangeListener[] $listeners  The list of listeners called when a record is inserted or updated.
44
     */
45 View Code Duplication
    public function __construct(Connection $connection, $prefix = 'zoho_', array $listeners = [], LoggerInterface $logger = null)
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...
46
    {
47
        $this->connection = $connection;
48
        $this->prefix = $prefix;
49
        $this->listeners = $listeners;
50
        if ($logger === null) {
51
            $this->logger = new NullLogger();
52
        } else {
53
            $this->logger = $logger;
54
        }
55
        $this->localChangesTracker = new LocalChangesTracker($connection, $this->logger);
56
    }
57
58
    /**
59
     * @param Response $userResponse
60
     * 
61
     * @throws \Doctrine\DBAL\DBALException
62
     * @throws \Doctrine\DBAL\Schema\SchemaException
63
     * @throws \Wabel\Zoho\CRM\Exception\ZohoCRMResponseException
64
     */
65
    public function fetchUserFromZoho(Response $userResponse)
66
    {
67
        $tableName = 'users';
68
        $this->logger->notice("Copying FULL data users for '$tableName'");
69
        $records = $userResponse->getRecords();
70
        $this->logger->info('Fetched '.count($records).' records');
71
72
        $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
73
        
74
        $select = $this->connection->prepare('SELECT * FROM '.$tableName.' WHERE id = :id');
75
76
        $this->connection->beginTransaction();
77
        foreach ($records as $record) {
78
            $data = [];
79
            $types = [];
80
            foreach ($table->getColumns() as $column) {
81
                if (in_array($column->getName(), ['id', 'uid'])) {
82
                    continue;
83
                } else {
84
                    $data[$column->getName()] = $record[$column->getName()];
85
                    $types[$column->getName()] = $column->getType()->getName();
86
                }
87
            }
88
89
            $select->execute(['id' => $record['id']]);
90
            $result = $select->fetch(\PDO::FETCH_ASSOC);
91
            if ($result === false) {
92
                $this->logger->debug("Inserting record with ID '".$record['id']."'.");
93
94
                $data['id'] = $record['id'];
95
                $types['id'] = 'string';
96
97
                $this->connection->insert($tableName, $data, $types);
98
99
            } else {
100
                $this->logger->debug("Updating record with ID '".$record['id']."'.");
101
                $identifier = ['id' => $record['id']];
102
                $types['id'] = 'string';
103
104
                $this->connection->update($tableName, $data, $identifier, $types);
105
            }
106
        }
107
        $this->connection->commit();
108
    }
109
    
110
    /**
111
     * @param AbstractZohoDao $dao
112
     * @param bool            $incrementalSync Whether we synchronize only the modified files or everything.
113
     * @param bool            $twoWaysSync
114
     *
115
     * @throws \Doctrine\DBAL\DBALException
116
     * @throws \Doctrine\DBAL\Schema\SchemaException
117
     * @throws \Wabel\Zoho\CRM\Exception\ZohoCRMResponseException
118
     */
119
    public function fetchFromZoho(AbstractZohoDao $dao, $incrementalSync = true, $twoWaysSync = true)
120
    {
121
        $tableName = ZohoDatabaseHelper::getTableName($dao, $this->prefix);
122
123
        if ($incrementalSync) {
124
            $this->logger->info("Copying incremental data for '$tableName'");
125
            /////'SHOW COLUMNS FROM '.$tableName.' LIKE `lastActivityTime`');
126
            // Let's get the last modification date:
127
            $lastActivityTime = $this->connection->fetchColumn('SELECT MAX(lastActivityTime) FROM '.$tableName);
128
            if ($lastActivityTime !== null) {
129
                $lastActivityTime = new \DateTime($lastActivityTime);
130
                $this->logger->info('Last activity time: '.$lastActivityTime->format('c'));
131
                // Let's add one second to the last activity time (otherwise, we are fetching again the last record in DB).
132
                $lastActivityTime->add(new \DateInterval('PT1S'));
133
            }
134
135
            $records = $dao->getRecords(null, null, $lastActivityTime);
136
            $deletedRecordIds = $dao->getDeletedRecordIds($lastActivityTime);
137
        } else {
138
            $this->logger->notice("Copying FULL data for '$tableName'");
139
            $records = $dao->getRecords();
140
            $deletedRecordIds = [];
141
        }
142
        $this->logger->info('Fetched '.count($records).' records');
143
144
        $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
145
146
        $flatFields = ZohoDatabaseHelper::getFlatFields($dao->getFields());
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...
147
        $fieldsByName = [];
148
        foreach ($flatFields as $field) {
149
            $fieldsByName[$field['name']] = $field;
150
        }
151
152
        $select = $this->connection->prepare('SELECT * FROM '.$tableName.' WHERE id = :id');
153
154
        $this->connection->beginTransaction();
155
156
        foreach ($records as $record) {
157
            $data = [];
158
            $types = [];
159
            foreach ($table->getColumns() as $column) {
160
                if (in_array($column->getName(), ['id', 'uid'])) {
161
                    continue;
162
                } else {
163
                    $field = $fieldsByName[$column->getName()];
164
                    $getterName = $field['getter'];
165
                    $data[$column->getName()] = $record->$getterName();
166
                    $types[$column->getName()] = $column->getType()->getName();
167
                }
168
            }
169
170
            $select->execute(['id' => $record->getZohoId()]);
171
            $result = $select->fetch(\PDO::FETCH_ASSOC);
172
            if ($result === false) {
173
                $this->logger->debug("Inserting record with ID '".$record->getZohoId()."'.");
174
175
                $data['id'] = $record->getZohoId();
176
                $types['id'] = 'string';
177
178
                $this->connection->insert($tableName, $data, $types);
179
180
                foreach ($this->listeners as $listener) {
181
                    $listener->onInsert($data, $dao);
182
                }
183
            } else {
184
                $this->logger->debug("Updating record with ID '".$record->getZohoId()."'.");
185
                $identifier = ['id' => $record->getZohoId()];
186
                $types['id'] = 'string';
187
188
                $this->connection->update($tableName, $data, $identifier, $types);
189
190
                // Let's add the id for the update trigger
191
                $data['id'] = $record->getZohoId();
192
                foreach ($this->listeners as $listener) {
193
                    $listener->onUpdate($data, $result, $dao);
194
                }
195
            }
196
        }
197
        $sqlStatementUid = 'select uid from '.$this->connection->quoteIdentifier($tableName).' where id = :id';
198
        foreach ($deletedRecordIds as $id) {
199
            $uid = $this->connection->fetchColumn($sqlStatementUid, ['id' => $id]);
200
            $this->connection->delete($tableName, ['id' => $id]);
201
            if ($twoWaysSync) {
202
                // TODO: we could detect if there are changes to be updated to the server and try to warn with a log message
203
                // Also, let's remove the newly created field (because of the trigger) to avoid looping back to Zoho
204
                $this->connection->delete('local_delete', ['table_name' => $tableName, 'id' => $id]);
205
                $this->connection->delete('local_update', ['table_name' => $tableName, 'uid' => $uid]);
206
            }
207
        }
208
209
        $this->connection->commit();
210
    }
211
}
212