Completed
Pull Request — 2.0 (#18)
by David
02:15
created

ZohoSyncDatabaseCommand::execute()   C

Complexity

Conditions 8
Paths 95

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 1
Metric Value
dl 0
loc 32
rs 5.3846
c 6
b 1
f 1
cc 8
eloc 19
nc 95
nop 2
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
     * @var EntitiesGeneratorService
57
     */
58
    private $zohoEntitiesGenerator;
59
60
    /**
61
     *
62
     * @var ZohoClient
63
     */
64
    private $zohoClient;
65
66
    private $pathZohoDaos;
67
68
    private $namespaceZohoDaos;
69
70
    /**
71
     *
72
     * @var Response
73
     */
74
    private $usersResponse;
0 ignored issues
show
Unused Code introduced by
The property $usersResponse is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
75
76
77
    /**
78
     * @param ZohoDatabaseModelSync $zohoDatabaseModelSync
79
     * @param ZohoDatabaseCopier    $zohoDatabaseCopier
80
     * @param ZohoDatabasePusher    $zohoDatabaseSync
81
     * @param EntitiesGeneratorService $zohoEntitiesGenerator The Zoho Dao and Beans generator
82
     * @param ZohoClient $zohoClient
83
     * @param string $pathZohoDaos Tht path where we need to generate the Daos.
84
     * @param string $namespaceZohoDaos Daos namespace
85
     * @param MultiLogger $logger
86
     * @param Lock                  $lock                  A lock that can be used to avoid running the same command (copy) twice at the same time
87
     */
88
    public function __construct(ZohoDatabaseModelSync $zohoDatabaseModelSync, ZohoDatabaseCopier $zohoDatabaseCopier, ZohoDatabasePusher $zohoDatabaseSync,
89
        EntitiesGeneratorService $zohoEntitiesGenerator, ZohoClient $zohoClient,
90
        $pathZohoDaos, $namespaceZohoDaos, MultiLogger $logger, Lock $lock = null)
91
    {
92
        parent::__construct();
93
        $this->zohoDatabaseModelSync = $zohoDatabaseModelSync;
94
        $this->zohoDatabaseCopier = $zohoDatabaseCopier;
95
        $this->zohoDatabaseSync = $zohoDatabaseSync;
96
        $this->zohoEntitiesGenerator =  $zohoEntitiesGenerator;
97
        $this->zohoClient = $zohoClient;
98
        $this->pathZohoDaos = $pathZohoDaos;
99
        $this->namespaceZohoDaos = $namespaceZohoDaos;
100
        $this->logger = $logger;
101
        $this->lock = $lock;
102
    }
103
104
    protected function configure()
105
    {
106
        $this
107
            ->setName('zoho:sync')
108
            ->setDescription('Synchronize the Zoho CRM data in a local database.')
109
            ->addOption('reset', 'r', InputOption::VALUE_NONE, 'Get a fresh copy of Zoho (rather than doing incremental copy)')
110
            ->addOption('skip-trigger', 's', InputOption::VALUE_NONE, 'Do not create or update the trigger')
111
            ->addOption('fetch-only', 'f', InputOption::VALUE_NONE, 'Fetch only the Zoho data in local database')
112
            ->addOption('push-only', 'p', InputOption::VALUE_NONE, 'Push only the local data to Zoho');
113
    }
114
115
    protected function execute(InputInterface $input, OutputInterface $output)
116
    {
117
        try {
118
            if ($this->lock) {
119
                $this->lock->acquireLock();
120
            }
121
            
122
            $this->logger->addLogger(new DateTimeFormatter(new ConsoleLogger($output)));
123
            if ($input->getOption('fetch-only') && $input->getOption('push-only')) {
124
                $output->writeln('<error>Options fetch-only and push-only are mutually exclusive.</error>');
125
            }
126
127
            $this->syncUserModel($output);
128
129
            $this->regenerateZohoDao($output);
130
131
            $this->syncModel($input, $output);
132
133
            if (!$input->getOption('push-only')) {
134
                $this->fetchUserDb($input, $output);
135
                $this->fetchDb($input, $output);
136
            }
137
            if (!$input->getOption('fetch-only')) {
138
                $this->pushDb($output);
139
            }
140
            if ($this->lock) {
141
                $this->lock->releaseLock();
142
            }
143
        } catch (LockException $e) {
144
            $output->writeln('<error>Could not start zoho:copy-db copy command. Another zoho:copy-db copy command is already running.</error>');
145
        }
146
    }
147
148
    /**
149
     * Sychronizes the model of the database with Zoho records.
150
     *
151
     * @param OutputInterface $output
152
     */
153
    private function syncModel(InputInterface $input, OutputInterface $output)
154
    {
155
        $twoWaysSync = !$input->getOption('fetch-only');
156
        $skipCreateTrigger = $input->getOption('skip-trigger');
157
158
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
159
        foreach ($this->zohoDaos as $zohoDao) {
160
            $this->zohoDatabaseModelSync->synchronizeDbModel($zohoDao, $twoWaysSync, $skipCreateTrigger);
161
        }
162
        $output->writeln('Zoho data successfully synchronized.');
163
    }
164
165
    /**
166
     * Sychronizes the model of the database with Zoho Users records.
167
     *
168
     * @param OutputInterface $output
169
     */
170
    private function syncUserModel(OutputInterface $output)
171
    {
172
        $output->writeln('Starting synchronize Zoho users model.');
173
        $this->zohoDatabaseModelSync->synchronizeUserDbModel();
174
        $output->writeln('Zoho users model successfully synchronized.');
175
    }
176
177
178
    /**
179
     * @param AbstractZohoDao $zohoDao
180
     *
181
     * @return array
182
     */
183
    private function getListFieldName(AbstractZohoDao $zohoDao)
184
    {
185
        $fieldNames= array();
186
        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...
187
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
188
                $fieldNames[] = $fieldDescriptor['name'];
189
            }
190
        }
191
192
        return $fieldNames;
193
    }
194
    
195
    /**
196
     * Regerate Zoho Daos
197
     * @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...
198
     * @param OutputInterface $output
199
     */
200
    private function regenerateZohoDao(OutputInterface $output)
201
    {
202
        $output->writeln("Start to generate all the zoho daos.");
203
        $zohoModules = $this->zohoEntitiesGenerator->generateAll($this->pathZohoDaos, $this->namespaceZohoDaos);
204
        foreach ($zohoModules as $daoFullClassName) {
205
            /* @var $zohoDao AbstractZohoDao */
206
            $zohoDao = new $daoFullClassName($this->zohoClient);
207
            if (!in_array('lastActivityTime', $this->getListFieldName($zohoDao))) {
208
                continue;
209
            }
210
            $this->zohoDaos [] = $zohoDao;
211
            $output->writeln(sprintf('<info>%s has created</info>', get_class($zohoDao)));
212
        }
213
        $output->writeln("Success to create all the zoho daos.");
214
    }
215
216
    /**
217
     * Run the fetch User Db command.
218
     *
219
     * @param InputInterface  $input
220
     * @param OutputInterface $output
221
     */
222
    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...
223
    {
224
        $output->writeln('Starting copying Zoho users data into local database.');
225
        $this->zohoDatabaseCopier->fetchUserFromZoho();
226
        $output->writeln('Zoho users data successfully copied.');
227
    }
228
    
229
    
230
    /**
231
     * Run the fetch Db command.
232
     *
233
     * @param InputInterface  $input
234
     * @param OutputInterface $output
235
     */
236
    private function fetchDb(InputInterface $input, OutputInterface $output)
237
    {
238
        if ($input->getOption('reset')) {
239
            $incremental = false;
240
        } else {
241
            $incremental = true;
242
        }
243
244
        $twoWaysSync = !$input->getOption('fetch-only');
245
246
        $output->writeln('Starting copying Zoho data into local database.');
247
        foreach ($this->zohoDaos as $zohoDao) {
248
            $output->writeln(sprintf('Copying data using <info>%s</info>', get_class($zohoDao)));
249
            $this->zohoDatabaseCopier->fetchFromZoho($zohoDao, $incremental, $twoWaysSync);
250
        }
251
        $output->writeln('Zoho data successfully copied.');
252
    }
253
254
    /**
255
     * Run the push Db command.
256
     *
257
     * @param OutputInterface $output
258
     */
259
    private function pushDb(OutputInterface $output)
260
    {
261
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
262
        foreach ($this->zohoDaos as $zohoDao) {
263
            $this->zohoDatabaseSync->pushToZoho($zohoDao);
264
        }
265
        $output->writeln('Zoho data successfully synchronized.');
266
    }
267
}
268