Completed
Push — 1.0 ( 369bdd...256ad5 )
by David
05:23
created

ZohoDatabaseCopier   B

Complexity

Total Complexity 40

Size/Duplication

Total Lines 207
Duplicated Lines 8.7 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 40
c 5
b 0
f 0
lcom 1
cbo 9
dl 18
loc 207
rs 8.2608

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A copy() 0 5 1
F synchronizeDbModel() 18 117 30
B copyData() 0 44 6
A getFlatFields() 0 8 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ZohoDatabaseCopier often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ZohoDatabaseCopier, and based on these observations, apply Extract Interface, too.

1
<?php
2
namespace Wabel\Zoho\CRM\Copy;
3
4
use Doctrine\DBAL\Connection;
5
use Doctrine\DBAL\Schema\Schema;
6
use Doctrine\DBAL\Schema\SchemaDiff;
7
use Wabel\Zoho\CRM\AbstractZohoDao;
8
9
/**
10
 * This class is in charge of synchronizing one table of your database with Zoho records.
11
 */
12
class ZohoDatabaseCopier
13
{
14
15
    /**
16
     * @var Connection
17
     */
18
    private $connection;
19
20
    private $prefix;
21
22
    /**
23
     * ZohoDatabaseCopier constructor.
24
     * @param Connection $connection
25
     */
26
    public function __construct(Connection $connection, $prefix = "zoho_")
27
    {
28
        $this->connection = $connection;
29
        $this->prefix = $prefix;
30
    }
31
32
33
    public function copy(AbstractZohoDao $dao)
34
    {
35
        $this->synchronizeDbModel($dao);
36
        $this->copyData($dao);
37
    }
38
39
40
    /**
41
     * Synchronizes the DB model with Zoho.
42
     * @param AbstractZohoDao $dao
43
     * @throws \Doctrine\DBAL\DBALException
44
     * @throws \Doctrine\DBAL\Schema\SchemaException
45
     */
46
    private function synchronizeDbModel(AbstractZohoDao $dao) {
47
        $tableName = $this->prefix.$dao->getModule();
0 ignored issues
show
Bug introduced by
The method getModule() 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...
48
49
        $schema = new Schema();
50
        $table = $schema->createTable($tableName);
51
52
        $flatFields = $this->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...
53
54
        $table->addColumn("id", "string", ['length'=>100]);
55
        $table->setPrimaryKey(['id']);
56
57
        foreach ($flatFields as $field) {
58
            $columnName = $field['name'];
59
60
            $length = null;
61
            $index = false;
62
63
            // Note: full list of types available here: https://www.zoho.com/crm/help/customization/custom-fields.html
64
            switch ($field['type']) {
65
                case 'Lookup ID':
66
                case 'Lookup':
67
                    $type = "string";
68
                    $length = 100;
69
                    $index = true;
70
                    break;
71
                case 'OwnerLookup':
72
                    $type = "string";
73
                    $index = true;
74
                    $length = 25;
75
                    break;
76
                case 'DateTime':
77
                    $type = "datetime";
78
                    break;
79
                case 'Date':
80
                    $type = "date";
81
                    break;
82
                case 'DateTime':
83
                    $type = "datetime";
84
                    break;
85
                case 'Boolean':
86
                    $type = "boolean";
87
                    break;
88
                case 'TextArea':
89
                    $type = "text";
90
                    break;
91
                case 'BigInt':
92
                    $type = "bigint";
93
                    break;
94
                case 'Phone':
95
                case 'Auto Number':
96
                case 'Text':
97
                case 'URL':
98
                case 'Email':
99
                case 'Website':
100
                case 'Pick List':
101
                case 'Multiselect Pick List':
102
                    $type = "string";
103
                    $length = $field['maxlength'];
104
                    break;
105
                case 'Double':
106
                case 'Percent':
107
                    $type = "float";
108
                    break;
109
                case 'Integer':
110
                    $type = "integer";
111
                    break;
112
                case 'Currency':
113
                case 'Decimal':
114
                    $type = "decimal";
115
                    break;
116
                default:
117
                    throw new \RuntimeException('Unknown type "'.$field['type'].'"');
118
            }
119
120
            $options = [];
121
122
            if ($length) {
123
                $options['length'] = $length;
124
            }
125
126
            //$options['notnull'] = $field['req'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
127
            $options['notnull'] = false;
128
129
            $table->addColumn($columnName, $type, $options);
130
131
            if ($index) {
132
                $table->addIndex([ $columnName ]);
133
            }
134
        }
135
136
        $dbSchema = $this->connection->getSchemaManager()->createSchema();
137
        if ($this->connection->getSchemaManager()->tablesExist($tableName)) {
0 ignored issues
show
Documentation introduced by
$tableName is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
138
            $dbTable = $dbSchema->getTable($tableName);
139
140
            $comparator = new \Doctrine\DBAL\Schema\Comparator();
141
            $tableDiff = $comparator->diffTable($dbTable, $table);
142
143 View Code Duplication
            if ($tableDiff !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
144
                $diff = new SchemaDiff();
145
                $diff->fromSchema = $dbSchema;
146
                $diff->changedTables[$tableName] = $tableDiff;
147
                $statements = $diff->toSaveSql($this->connection->getDatabasePlatform());
148
                foreach ($statements as $sql) {
149
                    $this->connection->exec($sql);
150
                }
151
            }
152 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
153
            $diff = new SchemaDiff();
154
            $diff->fromSchema = $dbSchema;
155
            $diff->newTables[$tableName] = $table;
156
            $statements = $diff->toSaveSql($this->connection->getDatabasePlatform());
157
            foreach ($statements as $sql) {
158
                $this->connection->exec($sql);
159
            }
160
        }
161
162
    }
163
164
    private function copyData(AbstractZohoDao $dao) {
165
        $records = $dao->getRecords();
166
        $tableName = $this->prefix.$dao->getModule();
0 ignored issues
show
Bug introduced by
The method getModule() 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...
167
168
        $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
169
170
171
        $flatFields = $this->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...
172
        $fieldsByName = [];
173
        foreach ($flatFields as $field) {
174
            $fieldsByName[$field['name']] = $field;
175
        }
176
177
        $select = $this->connection->prepare('SELECT * FROM '.$tableName.' WHERE id = :id');
178
179
        foreach ($records as $record) {
180
            $data = [];
181
            $types = [];
182
            foreach ($table->getColumns() as $column) {
183
                if ($column->getName() === 'id') {
184
                    continue;
185
                } else {
186
                    $field = $fieldsByName[$column->getName()];
187
                    $getterName = $field['getter'];
188
                    $data[$column->getName()] = $record->$getterName();
189
                    $types[$column->getName()] = $column->getType()->getName();
190
                }
191
            }
192
193
            $select->execute([ 'id' => $record->getZohoId() ]);
194
            $result = $select->fetch(\PDO::FETCH_ASSOC);
195
            if ($result === false) {
196
                $data['id'] = $record->getZohoId();
197
                $types['id'] = 'string';
198
199
                $this->connection->insert($tableName, $data, $types);
200
            } else {
201
                $identifier = ['id' => $record->getZohoId() ];
202
                $types['id'] = 'string';
203
204
                $this->connection->update($tableName, $data, $identifier, $types);
205
            }
206
        }
207
    }
208
209
    private function getFlatFields(array $fields)
210
    {
211
        $flatFields = [];
212
        foreach ($fields as $cat) {
213
            $flatFields = array_merge($flatFields, $cat);
214
        }
215
        return $flatFields;
216
    }
217
218
}
219