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

ZohoDatabaseSyncZoho::findMethodValues()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 7
nc 3
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\ZohoBeanInterface;
10
use Wabel\Zoho\CRM\Exception\ZohoCRMException;
11
use Wabel\Zoho\CRM\Exception\ZohoCRMResponseException;
12
use function Stringy\create as s;
13
14
/**
15
 * Description of ZohoDatabaseSyncZoho
16
 *
17
 * @author rbergina
18
 */
19
class ZohoDatabaseSyncZoho
20
{
21
22
    /**
23
     * @var Connection
24
     */
25
    private $connection;
26
27
    /**
28
     * @var LoggerInterface
29
     */
30
    private $logger;
31
32
    /**
33
     * @param \Wabel\Zoho\CRM\AbstractZohoDao[] $zohoDaos           The list of Zoho DAOs to copy
0 ignored issues
show
Bug introduced by
There is no parameter named $zohoDaos. 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...
34
     * @param Connection $connection
35
     *
36
     */
37
    public function __construct(Connection $connection, $prefix = 'zoho_', LoggerInterface $logger = null)
38
    {
39
        $this->connection = $connection;
40
        $this->prefix = $prefix;
0 ignored issues
show
Bug introduced by
The property prefix does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
41
        if ($logger === null) {
42
            $this->logger = new NullLogger();
43
        } else {
44
            $this->logger = $logger;
45
        }
46
    }
47
48
/**
49
     *
50
     * @param AbstractZohoDao $zohoDao
51
     * @return array
52
     */
53
    private function findMethodValues(AbstractZohoDao $zohoDao){
54
        $fieldsMatching = array();
55
        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...
56
            foreach (array_values($fieldsDescriptor) as $fieldDescriptor) {
57
                $fieldsMatching[$fieldDescriptor['name']] = [
58
                    'setter' => $fieldDescriptor['setter']
59
                ];
60
            }
61
62
        }
63
        return $fieldsMatching;
64
    }
65
66
    /**
67
     * Insert or Update rows.
68
     * @param AbstractZohoDao $zohoDao
69
     * @param string $localTable
70
     */
71
    public function pushDataToZoho(AbstractZohoDao $zohoDao, $localTable, $update = false){
72
73
            $fieldsMatching = $this->findMethodValues($zohoDao);
74
            $tableName = $this->getTableName($zohoDao);
75
            $rowsDeleted = [];
76
            $statement = $this->connection->createQueryBuilder();
77
            $statement->select('zcrm.*');
78
            if($update){
79
                $statement->addSelect('l.field_name as updated_fieldname');
80
            }
81
            $statement->from($localTable, 'l')
82
            ->join('l', $tableName, 'zcrm', 'zcrm.uid = l.uid')
83
            ->where('l.table_name=:table_name')
84
            ->setParameters([
85
                'table_name' => $tableName
86
            ]);
87
            $results = $statement->execute();
88
            /* @var $zohoBeans ZohoBeanInterface[] */
89
            $zohoBeans = array();
90
            while ($row = $results->fetch()) {
91
                $beanClassName = $zohoDao->getBeanClassName();
0 ignored issues
show
Bug introduced by
The method getBeanClassName() 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...
92
                /* @var $zohoBean ZohoBeanInterface */
93
                $zohoBean = new $beanClassName();
94
                if(!$update){
95
                    foreach ($row as $columnName => $columnValue) {
96
                        if (in_array($columnName,['id','uid'])) {
97
                            continue;
98
                        }else{
99
                           if($columnValue){
100
                               $zohoBean->{$fieldsMatching[$columnName]['setter']}($columnValue);
101
                           }
102
                        }
103
104
                    }
105
                    $zohoBeans[$row['uid']] =  $zohoBean;
106
                    $rowsDeleted[] = $row['uid'];
107
                } else{
108
                    $columnName = $row['updated_fieldname'];
109
                    $zohoBean->setZohoId($row['id']);
110
                    if (in_array($columnName,['uid'])) {
111
                        continue;
112
                    }else{
113
                        $zohoBean->{$fieldsMatching[$columnName]['setter']}($row[$columnName]);
114
                        $zohoBeans[] = $zohoBean;
115
                        $rowsDeleted[] = $row['uid'];
116
                    }
117
                }
118
            }
119
            $zohoDao->save($zohoBeans);
120
            if(!$update){
121
                foreach ($zohoBeans as $uid => $zohoBean) {
122
                    $this->connection->update($tableName, [ 'id'=>$zohoBean->getZohoId(),'lastActivityTime'=> date("Y-m-d H:i:s") ], ['uid'=>$uid ]);
123
                }
124
            }
125
            $statementDelete = $this->connection->prepare('delete from '.$localTable.' where uid in ( :rowsDeleted)');
126
            $statementDelete->execute([
127
                'rowsDeleted' => implode(',', $rowsDeleted)
128
            ]);
129
    }
130
131
    /**
132
     * Find the row to delete and remove to Zoho.
133
     * @param AbstractZohoDao $zohoDao
134
     * @param string $localTable
135
     */
136
    public function deleteDataToZoho(AbstractZohoDao $zohoDao, $localTable){
137
        $tableName = $this->getTableName($zohoDao);
138
        $statement = $this->connection->createQueryBuilder();
139
        $statement->select('l.id')
140
        ->from($localTable, 'l')
141
        ->where('l.table_name=:table_name')
142
        ->setParameters([
143
            'table_name' => $tableName
144
        ]);
145
        $results = $statement->execute();
146
        while ($row = $results->fetch()) {
147
            $zohoDao->delete($row['id']);
148
            $this->connection->delete($localTable, ['table_name' => $tableName,'id' => $row['id']]);
149
        }
150
}
151
    
152
    /**
153
     * Run inserted rows to Zoho : local_insert.
154
     * @param AbstractZohoDao $zohoDao
155
     */
156
    public function pushInsertedRows(AbstractZohoDao $zohoDao){
157
        return $this->pushDataToZoho($zohoDao, 'local_insert');
158
    }
159
160
    /**
161
     * Run updated rows to Zoho : local_update.
162
     * @param AbstractZohoDao $zohoDao
163
     */
164
    public function pushUpdatedRows(AbstractZohoDao $zohoDao){
165
        $this->pushDataToZoho($zohoDao, 'local_update', true);
166
    }
167
168
    /**
169
     * Run deleted rows to Zoho : local_delete.
170
     * @param AbstractZohoDao $zohoDao
171
     */
172
    public function pushDeletedRows(AbstractZohoDao $zohoDao){
173
        $this->deleteDataToZoho($zohoDao, 'local_delete');
174
    }
175
176
    /**
177
     * Computes the name of the table based on the DAO plural module name.
178
     *
179
     * @param AbstractZohoDao $dao
180
     *
181
     * @return string
182
     */
183 View Code Duplication
    private function getTableName(AbstractZohoDao $dao)
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...
184
    {
185
        $tableName = $this->prefix.$dao->getPluralModuleName();
0 ignored issues
show
Bug introduced by
The method getPluralModuleName() 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...
186
        $tableName = s($tableName)->upperCamelize()->underscored();
187
188
        return (string) $tableName;
189
    }
190
191
192
    /**
193
     * @param LoggerInterface $logger
194
     */
195
    public function setLogger(LoggerInterface $logger)
196
    {
197
        $this->logger = $logger;
198
    }
199
200
201
}