Completed
Push — 3.0 ( 154001...3d6954 )
by Raphaël
08:06 queued 06:39
created

ZohoSyncDatabaseCommand::getListFieldName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace Wabel\Zoho\CRM\Copy;
4
5
use Mouf\Utils\Common\Lock;
6
use Mouf\Utils\Common\LockException;
7
use Symfony\Component\Console\Command\Command;
8
use Symfony\Component\Console\Input\InputInterface;
9
use Symfony\Component\Console\Logger\ConsoleLogger;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Console\Input\InputOption;
12
use Wabel\Zoho\CRM\AbstractZohoDao;
13
use Wabel\Zoho\CRM\Service\EntitiesGeneratorService;
14
use Wabel\Zoho\CRM\ZohoClient;
15
use Logger\Formatters\DateTimeFormatter;
16
use Mouf\Utils\Log\Psr\MultiLogger;
17
use Wabel\Zoho\CRM\Request\Response;
18
19
class ZohoSyncDatabaseCommand extends Command
20
{
21
    /**
22
     * The list of Zoho DAOs to copy.
23
     *
24
     * @var AbstractZohoDao[]
25
     */
26
    private $zohoDaos;
27
28
    /**
29
     * @var ZohoDatabaseModelSync
30
     */
31
    private $zohoDatabaseModelSync;
32
33
    /**
34
     * @var ZohoDatabaseCopier
35
     */
36
    private $zohoDatabaseCopier;
37
38
    /**
39
     * @var ZohoDatabasePusher
40
     */
41
    private $zohoDatabaseSync;
42
43
    /**
44
     *
45
     * @var MultiLogger
46
     */
47
    private $logger;
48
49
    /**
50
     * @var Lock
51
     */
52
    private $lock;
53
54
    /**
55
     * The Zoho Dao and Beans generator
56
     *
57
     * @var EntitiesGeneratorService
58
     */
59
    private $zohoEntitiesGenerator;
60
61
    /**
62
     *
63
     * @var ZohoClient
64
     */
65
    private $zohoClient;
66
67
    private $pathZohoDaos;
68
69
    private $namespaceZohoDaos;
70
71
    /**
72
     *
73
     * @var Response
74
     */
75
    private $usersResponse;
76
77
    /**
78
     * @var string[]
79
     */
80
    private $excludedZohoDao;
81
82
83
    /**
84
     * @param ZohoDatabaseModelSync    $zohoDatabaseModelSync
85
     * @param ZohoDatabaseCopier       $zohoDatabaseCopier
86
     * @param ZohoDatabasePusher       $zohoDatabaseSync
87
     * @param EntitiesGeneratorService $zohoEntitiesGenerator The Zoho Dao and Beans generator
88
     * @param ZohoClient               $zohoClient
89
     * @param string                   $pathZohoDaos          Tht path where we need to generate the Daos.
90
     * @param string                   $namespaceZohoDaos     Daos namespace
91
     * @param MultiLogger              $logger
92
     * @param Lock                     $lock                  A lock that can be used to avoid running the same command (copy) twice at the same time
93
     * @param string[]                 $excludedZohoDao       To exclude Dao and or solve Dao which can create ZohoResponse Error
94
     */
95
    public function __construct(ZohoDatabaseModelSync $zohoDatabaseModelSync, ZohoDatabaseCopier $zohoDatabaseCopier, ZohoDatabasePusher $zohoDatabaseSync,
96
        EntitiesGeneratorService $zohoEntitiesGenerator, ZohoClient $zohoClient,
97
        $pathZohoDaos, $namespaceZohoDaos, MultiLogger $logger, Lock $lock = null, $excludedZohoDao = []
98
    ) {
99
        parent::__construct();
100
        $this->zohoDatabaseModelSync = $zohoDatabaseModelSync;
101
        $this->zohoDatabaseCopier = $zohoDatabaseCopier;
102
        $this->zohoDatabaseSync = $zohoDatabaseSync;
103
        $this->zohoEntitiesGenerator =  $zohoEntitiesGenerator;
104
        $this->zohoClient = $zohoClient;
105
        $this->pathZohoDaos = $pathZohoDaos;
106
        $this->namespaceZohoDaos = $namespaceZohoDaos;
107
        $this->logger = $logger;
108
        $this->lock = $lock;
109
        $this->excludedZohoDao = $excludedZohoDao;
110
    }
111
112
    protected function configure()
113
    {
114
        $this
115
            ->setName('zoho:sync')
116
            ->setDescription('Synchronize the Zoho CRM data in a local database.')
117
            ->addOption('reset', 'r', InputOption::VALUE_NONE, 'Get a fresh copy of Zoho (rather than doing incremental copy)')
118
            ->addOption('skip-trigger', 's', InputOption::VALUE_NONE, 'Do not create or update the trigger')
119
            ->addOption('fetch-only', 'f', InputOption::VALUE_NONE, 'Fetch only the Zoho data in local database')
120
            ->addOption('push-only', 'p', InputOption::VALUE_NONE, 'Push only the local data to Zoho')
121
            ->addOption('limit', 'l', InputOption::VALUE_NONE, 'use defined memory limit or unlimited memory limit');
122
    }
123
124
    protected function execute(InputInterface $input, OutputInterface $output)
125
    {
126
        try {
127
            if ($this->lock) {
128
                $this->lock->acquireLock();
129
            }
130
131
            if(!$input->getOption('limit')) {
132
                ini_set('memory_limit', '-1');
133
            }
134
            
135
            $this->logger->addLogger(new DateTimeFormatter(new ConsoleLogger($output)));
136
            if ($input->getOption('fetch-only') && $input->getOption('push-only')) {
137
                $output->writeln('<error>Options fetch-only and push-only are mutually exclusive.</error>');
138
            }
139
140
            $this->syncUserModel($output);
141
142
            $this->regenerateZohoDao($output);
143
144
            $this->syncModel($input, $output);
145
146
            if (!$input->getOption('push-only')) {
147
                $this->fetchUserDb($input, $output);
148
                $this->fetchDb($input, $output);
149
            }
150
            if (!$input->getOption('fetch-only')) {
151
                $this->pushDb($output);
152
            }
153
            if ($this->lock) {
154
                $this->lock->releaseLock();
155
            }
156
        } catch (LockException $e) {
157
            $output->writeln('<error>Could not start zoho:copy-db copy command. Another zoho:copy-db copy command is already running.</error>');
158
        }
159
    }
160
161
    /**
162
     * Sychronizes the model of the database with Zoho records.
163
     *
164
     * @param OutputInterface $output
165
     */
166
    private function syncModel(InputInterface $input, OutputInterface $output)
167
    {
168
        $twoWaysSync = !$input->getOption('fetch-only');
169
        $skipCreateTrigger = $input->getOption('skip-trigger');
170
171
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
172
        foreach ($this->zohoDaos as $zohoDao) {
173
            $this->zohoDatabaseModelSync->synchronizeDbModel($zohoDao, $twoWaysSync, $skipCreateTrigger);
174
        }
175
        $output->writeln('Zoho data successfully synchronized.');
176
    }
177
178
    /**
179
     * Sychronizes the model of the database with Zoho Users records.
180
     *
181
     * @param OutputInterface $output
182
     */
183
    private function syncUserModel(OutputInterface $output)
184
    {
185
        $output->writeln('Starting synchronize Zoho users model.');
186
        $this->zohoDatabaseModelSync->synchronizeUserDbModel();
187
        $output->writeln('Zoho users model successfully synchronized.');
188
    }
189
190
    /**
191
     * Regerate Zoho Daos
192
     *
193
     * @param InputInterface  $input
0 ignored issues
show
Bug introduced by
There is no parameter named $input. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
194
     * @param OutputInterface $output
195
     */
196
    private function regenerateZohoDao(OutputInterface $output)
197
    {
198
        $output->writeln("Start to generate all the zoho daos.");
199
        $zohoModules = $this->zohoEntitiesGenerator->generateAll($this->pathZohoDaos, $this->namespaceZohoDaos);
200
        foreach ($zohoModules as $daoFullClassName) {
201
            /* @var $zohoDao AbstractZohoDao */
202
            $zohoDao = new $daoFullClassName($this->zohoClient);
203
            //To have more module which is use time of modification (createdTime or lastActivityTime).
204
            //use an array of Excluded Dao by full namespace
205
            if (($this->excludedZohoDao && in_array(get_class($zohoDao), $this->excludedZohoDao))) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->excludedZohoDao of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
206
                continue;
207
            }
208
            $this->zohoDaos [] = $zohoDao;
209
            $output->writeln(sprintf('<info>%s has created</info>', get_class($zohoDao)));
210
        }
211
        $output->writeln("Success to create all the zoho daos.");
212
    }
213
214
    /**
215
     * Run the fetch User Db command.
216
     *
217
     * @param InputInterface  $input
218
     * @param OutputInterface $output
219
     */
220
    private function fetchUserDb(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Unused Code introduced by
The parameter $input is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
221
    {
222
        $output->writeln('Starting copying Zoho users data into local database.');
223
        $this->zohoDatabaseCopier->fetchUserFromZoho();
224
        $output->writeln('Zoho users data successfully copied.');
225
    }
226
    
227
    
228
    /**
229
     * Run the fetch Db command.
230
     *
231
     * @param InputInterface  $input
232
     * @param OutputInterface $output
233
     */
234
    private function fetchDb(InputInterface $input, OutputInterface $output)
235
    {
236
        if ($input->getOption('reset')) {
237
            $incremental = false;
238
        } else {
239
            $incremental = true;
240
        }
241
242
        $twoWaysSync = !$input->getOption('fetch-only');
243
244
        $output->writeln('Starting copying Zoho data into local database.');
245
        foreach ($this->zohoDaos as $zohoDao) {
246
                $output->writeln(sprintf('Copying data using <info>%s</info>', get_class($zohoDao)));
247
                $this->zohoDatabaseCopier->fetchFromZoho($zohoDao, $incremental, $twoWaysSync);
248
        }
249
        $output->writeln('Zoho data successfully copied.');
250
    }
251
252
    /**
253
     * Run the push Db command.
254
     *
255
     * @param OutputInterface $output
256
     */
257
    private function pushDb(OutputInterface $output)
258
    {
259
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
260
        foreach ($this->zohoDaos as $zohoDao) {
261
            if($zohoDao->getFieldFromFieldName('createdTime')) {
262
                $this->zohoDatabaseSync->pushToZoho($zohoDao);
263
            }
264
        }
265
        $output->writeln('Zoho data successfully synchronized.');
266
    }
267
}
268