Completed
Push — 1.0 ( f2d05f...c3e315 )
by David
06:31
created

EntitiesGeneratorService::getUniqueIdentifier()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4286
cc 3
eloc 9
nc 3
nop 2
1
<?php
2
3
namespace Wabel\Zoho\CRM\Service;
4
5
use gossi\codegen\generator\CodeFileGenerator;
6
use gossi\codegen\model\PhpClass;
7
use gossi\codegen\model\PhpMethod;
8
use gossi\codegen\model\PhpParameter;
9
use gossi\codegen\model\PhpProperty;
10
use Psr\Log\LoggerInterface;
11
use Wabel\Zoho\CRM\ZohoClient;
12
use Wabel\Zoho\CRM\Exception\ZohoCRMException;
13
14
/**
15
 * This class is in charge of generating Zoho entities.
16
 */
17
class EntitiesGeneratorService
18
{
19
    private $zohoClient;
20
    private $logger;
21
22
    public function __construct(ZohoClient $zohoClient, LoggerInterface $logger)
23
    {
24
        $this->zohoClient = $zohoClient;
25
        $this->logger = $logger;
26
    }
27
28
    /**
29
     * Generate ALL entities for all Zoho modules.
30
     *
31
     * @param string $targetDirectory
32
     * @param string $namespace
33
     */
34
    public function generateAll($targetDirectory, $namespace)
35
    {
36
        $modules = $this->zohoClient->getModules();
37
        foreach ($modules->getRecords() as $module) {
38
            try {
39
                $this->generateModule($module['key'], $module['pl'], $module['sl'], $targetDirectory, $namespace);
40
            } catch (ZohoCRMException $e) {
41
                $this->logger->notice('Error thrown when retrieving fields for module {module}. Error message: {error}.',
42
                    [
43
                        'module' => $module['key'],
44
                        'error' => $e->getMessage(),
45
                        'exception' => $e,
46
                    ]);
47
            }
48
        }
49
    }
50
51
    public function generateModule($moduleName, $modulePlural, $moduleSingular, $targetDirectory, $namespace)
0 ignored issues
show
Unused Code introduced by
The parameter $modulePlural 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...
52
    {
53
        $fields = $this->zohoClient->getFields($moduleName);
54
55
        if (!file_exists($targetDirectory)) {
56
            mkdir($targetDirectory, 0775, true);
57
        }
58
59
        $namespace = trim($namespace, '\\');
60
        $className = self::upperCamelCase($moduleSingular);
61
        $daoClassName = $className.'ZohoDao';
62
63
        $fieldRecords = $fields->getRecords();
64
65
        $this->generateBean($fieldRecords, $namespace, $className, $moduleName, $targetDirectory);
66
        $this->generateDao($fieldRecords, $namespace, $className, $daoClassName, $moduleName, $targetDirectory);
67
    }
68
69
    public function generateBean($fields, $namespace, $className, $moduleName, $targetDirectory)
70
    {
71
72
//        if (class_exists($namespace."\\".$className)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
73
//            $class = PhpClass::fromReflection(new \ReflectionClass($namespace."\\".$className));
74
//        } else {
75
            $class = PhpClass::create();
76
//        }
77
78
        $class->setName($className)
79
            ->setNamespace($namespace)
80
            ->addInterface('\\Wabel\\Zoho\\CRM\\ZohoBeanInterface')
81
            ->setMethod(PhpMethod::create('__construct'));
82
83
        // Let's add the ZohoID property
84
        self::registerProperty($class, 'zohoId', "The ID of this record in Zoho\nType: string\n", 'string');
85
86
        foreach ($fields as &$fieldCategory) {
87
            foreach ($fieldCategory as $name => &$field) {
88
                $req = $field['req'];
0 ignored issues
show
Unused Code introduced by
$req is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
89
                $type = $field['type'];
90
                $isreadonly = $field['isreadonly'];
91
                $maxlength = $field['maxlength'];
92
                $label = $field['label'];
0 ignored issues
show
Unused Code introduced by
$label is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
93
                $dv = $field['dv'];
0 ignored issues
show
Unused Code introduced by
$dv is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
94
                $customfield = $field['customfield'];
95
96 View Code Duplication
                switch ($type) {
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...
97
                    case 'DateTime':
98
                    case 'Date':
99
                        $phpType = '\\DateTime';
100
                        break;
101
                    case 'Boolean':
102
                        $phpType = 'bool';
103
                        break;
104
                    case 'Integer':
105
                        $phpType = 'int';
106
                        break;
107
                    default:
108
                        $phpType = 'string';
109
                        break;
110
                }
111
112
                $field['phpType'] = $phpType;
113
114
                self::registerProperty($class, self::camelCase($name), 'Zoho field '.$name."\n".
115
                    'Type: '.$type."\n".
116
                    'Read only: '.($isreadonly ? 'true' : 'false')."\n".
117
                    'Max length: '.$maxlength."\n".
118
                    'Custom field: '.($customfield ? 'true' : 'false')."\n", $phpType);
119
120
                // Adds a ID field for lookups
121
                if ($type === 'Lookup') {
122
                    $generateId = false;
123
124
                    if ($customfield) {
125
                        $name .= '_ID';
126
                        $generateId = true;
127
                    } else {
128
                        switch ($name) {
129
                            //TODO : To be completed with known lookup fields that are not custom fields but default in Zoho
130
                            case 'Account Name' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
131
                                $name = 'ACCOUNTID';
132
                                $generateId = true;
133
                                break;
134
                            case 'Contact Name' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
135
                                $name = 'CONTACTID';
136
                                $generateId = true;
137
                                break;
138
                            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
139
                                $this->logger->warning('Unable to set a ID for the field {name} of the {module} module', [
140
                                    'name' => $name,
141
                                    'module' => $moduleName,
142
                                ]);
143
                        }
144
                    }
145
146
                    if ($generateId) {
147
                        $req = false;
0 ignored issues
show
Unused Code introduced by
$req is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
148
                        $type = 'Lookup ID';
149
                        $isreadonly = true;
150
                        $maxlength = $field['maxlength'];
151
                        $label = $field['label'];
0 ignored issues
show
Unused Code introduced by
$label is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
152
                        $dv = $field['dv'];
0 ignored issues
show
Unused Code introduced by
$dv is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
153
154
                        $field['phpType'] = $phpType;
155
156
                        self::registerProperty($class, ($customfield ? self::camelCase($name) : $name), 'Zoho field '.$name."\n".
157
                            'Type: '.$type."\n".
158
                            'Read only: '.($isreadonly ? 'true' : 'false')."\n".
159
                            'Max length: '.$maxlength."\n".
160
                            'Custom field: '.($customfield ? 'true' : 'false')."\n", 'string');
161
                    }
162
                }
163
            }
164
        }
165
166
        self::registerProperty($class, 'createdTime', "The time the record was created in Zoho\nType: DateTime\n", '\\DateTime');
167
        self::registerProperty($class, 'modifiedTime', "The last time the record was modified in Zoho\nType: DateTime\n", '\\DateTime');
168
169
        $method = PhpMethod::create('isDirty');
170
        $method->setDescription('Returns whether a property is changed or not.');
171
        $method->addParameter(PhpParameter::create('name'));
172
        $method->setBody("\$propertyName = 'dirty'.ucfirst(\$name);\nreturn \$this->\$propertyName;");
173
        $method->setType('bool');
174
        $class->setMethod($method);
175
176
        $generator = new CodeFileGenerator();
177
        $code = $generator->generate($class);
178
179 View Code Duplication
        if (!file_put_contents(rtrim($targetDirectory, '/').'/'.$className.'.php', $code)) {
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...
180
            throw new ZohoCRMException("An error occurred while creating the class $className. Please verify the target directory or the rights of the file.");
181
        }
182
    }
183
184
    /**
185
     * Returns a unique identifier from the name.
186
     *
187
     * @param $name
188
     * @param array $usedNames
0 ignored issues
show
Bug introduced by
There is no parameter named $usedNames. 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...
189
     */
190
    private function getUniqueIdentifier($name, array $usedIdentifiers) {
191
        $id = self::camelCase($name);
192
        if (isset($usedIdentifiers[$id])) {
193
            $counter = 2;
194
            while (isset($usedIdentifiers[$id.'_'.$counter])) {
195
                $counter++;
196
            }
197
            return $id.'_'.$counter;
198
        } else {
199
            return $id;
200
        }
201
    }
202
203
    public function generateDao($fields, $namespace, $className, $daoClassName, $moduleName, $targetDirectory)
204
    {
205
        //        if (class_exists($namespace."\\".$className)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% 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...
206
//            $class = PhpClass::fromReflection(new \ReflectionClass($namespace."\\".$daoClassName));
207
//        } else {
208
            $class = PhpClass::create();
209
//        }
210
211
        $class->setName($daoClassName)
212
            ->setNamespace($namespace)
213
            ->setParentClassName('\\Wabel\\Zoho\\CRM\\AbstractZohoDao');
214
215
        $usedIdentifiers = [];
216
217
        foreach ($fields as $key => $fieldCategory) {
218
            foreach ($fieldCategory as $name => $field) {
219
                $type = $field['type'];
220
221 View Code Duplication
                switch ($type) {
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...
222
                    case 'DateTime':
223
                    case 'Date':
224
                        $phpType = '\\DateTime';
225
                        break;
226
                    case 'Boolean':
227
                        $phpType = 'bool';
228
                        break;
229
                    case 'Integer':
230
                        $phpType = 'int';
231
                        break;
232
                    default:
233
                        $phpType = 'string';
234
                        break;
235
                }
236
237
                $fields[$key][$name]['phpType'] = $phpType;
238
                $identifier = $this->getUniqueIdentifier($name, $usedIdentifiers);
239
                $usedIdentifiers[$identifier] = true;
240
                $fields[$key][$name]['getter'] = 'get'.ucfirst($identifier);
241
                $fields[$key][$name]['setter'] = 'set'.ucfirst($identifier);
242
                $fields[$key][$name]['name'] = $identifier;
243
244
                if ($type === 'Lookup') {
245
                    $generateId = false;
246
247
                    if ($field['customfield']) {
248
                        $name .= '_ID';
249
                        $generateId = true;
250
                    } else {
251
                        switch ($field['label']) {
252
                            //TODO : To be completed with known lookup fields that are not custom fields but default in Zoho
253
                            case 'Account Name' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
254
                                $name = 'ACCOUNTID';
255
                                $generateId = true;
256
                                break;
257
                            case 'Contact Name' :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
258
                                $name = 'CONTACTID';
259
                                $generateId = true;
260
                                break;
261
                        }
262
                    }
263
                    if ($generateId) {
264
                        $fields[$key][$name]['req'] = false;
265
                        $fields[$key][$name]['type'] = 'Lookup ID';
266
                        $fields[$key][$name]['isreadonly'] = true;
267
                        $fields[$key][$name]['maxlength'] = 100;
268
                        $fields[$key][$name]['label'] = $name;
269
                        $fields[$key][$name]['dv'] = $name;
270
                        $fields[$key][$name]['customfield'] = true;
271
                        $fields[$key][$name]['phpType'] = $phpType;
272
                        $fields[$key][$name]['getter'] = 'get'.ucfirst(self::camelCase($name));
273
                        $fields[$key][$name]['setter'] = 'set'.ucfirst(self::camelCase($name));
274
                        $fields[$key][$name]['name'] = self::camelCase($name);
275
                    }
276
                }
277
            }
278
        }
279
280
        $class->setMethod(PhpMethod::create('getModule')->setBody('return '.var_export($moduleName, true).';'));
281
282
        $class->setMethod(PhpMethod::create('getFields')->setBody('return '.var_export($fields, true).';'));
283
284
        $class->setMethod(PhpMethod::create('getBeanClassName')->setBody('return '.var_export($namespace.'\\'.$className, true).';'));
285
286
        $generator = new CodeFileGenerator();
287
        $code = $generator->generate($class);
288
289 View Code Duplication
        if (!file_put_contents(rtrim($targetDirectory, '/').'/'.$daoClassName.'.php', $code)) {
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...
290
            throw new ZohoCRMException("An error occurred while creating the DAO $daoClassName. Please verify the target directory exists or the rights of the file.");
291
        }
292
    }
293
294
    private static function camelCase($str, array $noStrip = [])
295
    {
296
        $str = self::upperCamelCase($str, $noStrip);
297
        $str = lcfirst($str);
298
299
        return $str;
300
    }
301
302
    private static function upperCamelCase($str, array $noStrip = [])
303
    {
304
        // non-alpha and non-numeric characters become spaces
305
        $str = preg_replace('/[^a-z0-9'.implode('', $noStrip).']+/i', ' ', $str);
306
        $str = trim($str);
307
        // uppercase the first character of each word
308
        $str = ucwords($str);
309
        $str = str_replace(' ', '', $str);
310
311
        return $str;
312
    }
313
314
    private static function registerProperty(PhpClass $class, $name, $description, $type)
315
    {
316 View Code Duplication
        if (!$class->hasProperty($name)) {
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...
317
            $property = PhpProperty::create($name);
318
            $property->setDescription($description);
319
            $property->setType($type);
320
            $property->setVisibility('protected');
321
322
            $class->setProperty($property);
323
        }
324
325
        $isDirtyName = 'dirty'.ucfirst($name);
326 View Code Duplication
        if (!$class->hasProperty($isDirtyName)) {
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...
327
            $dirtyProperty = PhpProperty::create($isDirtyName);
328
            $dirtyProperty->setDescription("Whether '$name' has been changed or not.");
329
            $dirtyProperty->setType('bool');
330
            $dirtyProperty->setVisibility('protected');
331
            $dirtyProperty->setDefaultValue(false);
332
333
            $class->setProperty($dirtyProperty);
334
        }
335
336
        $getterName = 'get'.ucfirst($name);
337
        $getterDescription = 'Get '.lcfirst($description);
338
        $setterName = 'set'.ucfirst($name);
339
        $setterDescription = 'Set '.lcfirst($description);
340
341
        if (!$class->hasMethod($getterName)) {
342
            $method = PhpMethod::create($getterName);
343
            $method->setDescription($getterDescription);
344
            $method->setBody("return \$this->{$name};");
345
            $class->setMethod($method);
346
        }
347
348
        if (!$class->hasMethod($setterName)) {
349
            $method = PhpMethod::create($setterName);
350
            $method->setDescription($setterDescription);
351
            $method->addParameter(PhpParameter::create($name)->setType($type));
352
            $method->setBody("\$this->{$name} = \${$name};\n".
353
                             "\$this->dirty".ucfirst($name)." = true;\n".
354
                             "return \$this;");
355
            $class->setMethod($method);
356
        }
357
    }
358
}
359