Completed
Push — 1.0 ( f5819f...ad6ea3 )
by David
09:59
created

ZohoDatabaseCopier::copyData()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 30
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 30
rs 8.439
cc 5
eloc 21
nc 8
nop 1
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
            switch ($field['type']) {
64
                case 'Lookup ID':
65
                case 'Lookup':
66
                    $type = "string";
67
                    $length = 100;
68
                    $index = true;
69
                    break;
70
                case 'OwnerLookup':
71
                    $type = "string";
72
                    $index = true;
73
                    $length = 25;
74
                    break;
75
                case 'DateTime':
76
                    $type = "datetime";
77
                    break;
78
                case 'Date':
79
                    $type = "date";
80
                    break;
81
                case 'DateTime':
82
                    $type = "datetime";
83
                    break;
84
                case 'Boolean':
85
                    $type = "boolean";
86
                    break;
87
                case 'TextArea':
88
                    $type = "text";
89
                    break;
90
                case 'Phone':
91
                case 'Text':
92
                case 'Email':
93
                case 'Pick List':
94
                    $type = "string";
95
                    $length = $field['maxlength'];
96
                    break;
97
                default:
98
                    throw new \RuntimeException('Unknown type "'.$field['type'].'"');
99
            }
100
101
            $options = [];
102
103
            if ($length) {
104
                $options['length'] = $length;
105
            }
106
107
            //$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...
108
            $options['notnull'] = false;
109
110
            $table->addColumn($columnName, $type, $options);
111
112
            if ($index) {
113
                $table->addIndex([ $columnName ]);
114
            }
115
        }
116
117
        $dbSchema = $this->connection->getSchemaManager()->createSchema();
118
        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...
119
            $dbTable = $dbSchema->getTable($tableName);
120
121
            $comparator = new \Doctrine\DBAL\Schema\Comparator();
122
            $tableDiff = $comparator->diffTable($dbTable, $table);
123
124 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...
125
                $diff = new SchemaDiff();
126
                $diff->fromSchema = $dbSchema;
127
                $diff->changedTables[$tableName] = $tableDiff;
128
                $statements = $diff->toSaveSql($this->connection->getDatabasePlatform());
129
                foreach ($statements as $sql) {
130
                    $this->connection->exec($sql);
131
                }
132
            }
133 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...
134
            $diff = new SchemaDiff();
135
            $diff->fromSchema = $dbSchema;
136
            $diff->newTables[$tableName] = $table;
137
            $statements = $diff->toSaveSql($this->connection->getDatabasePlatform());
138
            foreach ($statements as $sql) {
139
                $this->connection->exec($sql);
140
            }
141
        }
142
143
    }
144
145
    private function copyData(AbstractZohoDao $dao) {
146
        $records = $dao->getRecords();
147
        $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...
148
149
        $table = $this->connection->getSchemaManager()->createSchema()->getTable($tableName);
150
151
152
        $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...
153
        $fieldsByName = [];
154
        foreach ($flatFields as $field) {
155
            $fieldsByName[$field['name']] = $field;
156
        }
157
158
        foreach ($records as $record) {
159
            $data = [];
160
            $types = [];
161
            foreach ($table->getColumns() as $column) {
162
                if ($column->getName() === 'id') {
163
                    $data['id'] = $record->getZohoId();
164
                    $types['id'] = 'string';
165
                } else {
166
                    $field = $fieldsByName[$column->getName()];
167
                    $getterName = $field['getter'];
168
                    $data[$column->getName()] = $record->$getterName();
169
                    $types[$column->getName()] = $column->getType()->getName();
170
                }
171
            }
172
            $this->connection->insert($tableName, $data, $types);
173
        }
174
    }
175
176
    private function getFlatFields(array $fields)
177
    {
178
        $flatFields = [];
179
        foreach ($fields as $cat) {
180
            $flatFields = array_merge($flatFields, $cat);
181
        }
182
        return $flatFields;
183
    }
184
185
}
186