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

ZohoDatabaseCopier::setLogger()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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