Completed
Push — 2.0 ( 94a944...924b75 )
by Raphaël
08:39
created

ZohoSyncDatabaseCommand::fetchUserDb()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
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;
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
            }
138
            if (!$input->getOption('fetch-only')) {
139
                $this->pushDb($output);
140
            }
141
            if ($this->lock) {
142
                $this->lock->releaseLock();
143
            }
144
        } catch (LockException $e) {
145
            $output->writeln('<error>Could not start zoho:copy-db copy command. Another zoho:copy-db copy command is already running.</error>');
146
        }
147
    }
148
149
    /**
150
     * Sychronizes the model of the database with Zoho records.
151
     *
152
     * @param OutputInterface $output
153
     */
154
    private function syncModel(InputInterface $input, OutputInterface $output)
155
    {
156
        $twoWaysSync = !$input->getOption('fetch-only');
157
        $skipCreateTrigger = $input->getOption('skip-trigger');
158
159
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
160
        foreach ($this->zohoDaos as $zohoDao) {
161
            $this->zohoDatabaseModelSync->synchronizeDbModel($zohoDao, $twoWaysSync, $skipCreateTrigger);
162
        }
163
        $output->writeln('Zoho data successfully synchronized.');
164
    }
165
166
167
168
    /**
169
     * Generate the User Response from Zoho
170
     * @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...
171
     * @param OutputInterface $output
172
     */
173
    private function getUsersReponse(OutputInterface $output)
174
    {
175
        $output->writeln("Start to request users data from zoho.");
176
        $this->usersResponse =$this->zohoClient->getUsers();
177
        $output->writeln("Finish to requuest users data from zoho.");
178
    }
179
180
    /**
181
     * Sychronizes the model of the database with Zoho Users records.
182
     *
183
     * @param OutputInterface $output
184
     */
185
    private function syncUserModel(OutputInterface $output)
186
    {
187
        $this->getUsersReponse($output);
188
        $output->writeln('Starting synchronize Zoho users model.');
189
        $this->zohoDatabaseModelSync->synchronizeUserDbModel($this->usersResponse);
190
        $output->writeln('Zoho users model successfully synchronized.');
191
    }
192
193
194
    /**
195
     * @param AbstractZohoDao $zohoDao
196
     *
197
     * @return array
198
     */
199
    private function getListFieldName(AbstractZohoDao $zohoDao)
200
    {
201
        $fieldNames= array();
202
        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...
203
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
204
                $fieldNames[] = $fieldDescriptor['name'];
205
            }
206
        }
207
208
        return $fieldNames;
209
    }
210
    
211
    /**
212
     * Regerate Zoho Daos
213
     * @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...
214
     * @param OutputInterface $output
215
     */
216
    private function regenerateZohoDao(OutputInterface $output)
217
    {
218
        $output->writeln("Start to generate all the zoho daos.");
219
        $zohoModules = $this->zohoEntitiesGenerator->generateAll($this->pathZohoDaos,$this->namespaceZohoDaos);
220
        foreach ($zohoModules as $daoFullClassName) {
221
            /* @var $zohoDao AbstractZohoDao */
222
            $zohoDao = new $daoFullClassName($this->zohoClient);
223
            if(!in_array('lastActivityTime', $this->getListFieldName($zohoDao))){
224
                continue;
225
            }
226
            $this->zohoDaos [] = $zohoDao;
227
            $output->writeln(sprintf('<info>%s has created</info>', get_class($zohoDao)));
228
        }
229
        $output->writeln("Success to create all the zoho daos.");
230
    }
231
232
    /**
233
     * Run the fetch User Db command.
234
     *
235
     * @param InputInterface  $input
236
     * @param OutputInterface $output
237
     */
238
    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...
239
    {
240
        $output->writeln('Starting copying Zoho users data into local database.');
241
        $this->zohoDatabaseCopier->fetchUserFromZoho($this->usersResponse);
242
        $output->writeln('Zoho users data successfully copied.');
243
    }
244
    
245
    
246
    /**
247
     * Run the fetch Db command.
248
     *
249
     * @param InputInterface  $input
250
     * @param OutputInterface $output
251
     */
252
    private function fetchDb(InputInterface $input, OutputInterface $output)
253
    {
254
        if ($input->getOption('reset')) {
255
            $incremental = false;
256
        } else {
257
            $incremental = true;
258
        }
259
260
        $twoWaysSync = !$input->getOption('fetch-only');
261
262
        $output->writeln('Starting copying Zoho data into local database.');
263
        foreach ($this->zohoDaos as $zohoDao) {
264
            $output->writeln(sprintf('Copying data using <info>%s</info>', get_class($zohoDao)));
265
            $this->zohoDatabaseCopier->fetchFromZoho($zohoDao, $incremental, $twoWaysSync);
266
        }
267
        $output->writeln('Zoho data successfully copied.');
268
    }
269
270
    /**
271
     * Run the push Db command.
272
     *
273
     * @param OutputInterface $output
274
     */
275
    private function pushDb(OutputInterface $output)
276
    {
277
278
        $output->writeln('Starting synchronize Zoho data into Zoho CRM.');
279
        foreach ($this->zohoDaos as $zohoDao) {
280
            $this->zohoDatabaseSync->pushToZoho($zohoDao);
281
        }
282
        $output->writeln('Zoho data successfully synchronized.');
283
    }
284
}
285