EntitiesGeneratorService::camelCase()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
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
     * @return array Array containing each fully qualified dao class name
35
     */
36
    public function generateAll($targetDirectory, $namespace)
37
    {
38
        $modules = $this->zohoClient->getModules();
39
        $zohoModules = [];
40
        foreach ($modules->getRecords() as $module) {
41
            try {
42
                $zohoModules[] = $this->generateModule($module['key'], $module['pl'], $module['sl'], $targetDirectory, $namespace);
43
            } catch (ZohoCRMException $e) {
44
                $this->logger->notice('Error thrown when retrieving fields for module {module}. Error message: {error}.',
45
                    [
46
                        'module' => $module['key'],
47
                        'error' => $e->getMessage(),
48
                        'exception' => $e,
49
                    ]);
50
            }
51
        }
52
53
        return $zohoModules;
54
    }
55
56
    /**
57
     * Generate a dao for a zoho module.
58
     *
59
     * @param string $moduleName
60
     * @param string $modulePlural
61
     * @param string $moduleSingular
62
     * @param string $targetDirectory
63
     * @param string $namespace
64
     *
65
     * @return string The fully qualified Dao class name
66
     */
67
    public function generateModule($moduleName, $modulePlural, $moduleSingular, $targetDirectory, $namespace)
68
    {
69
        $fields = $this->zohoClient->getFields($moduleName);
70
71
        if (!file_exists($targetDirectory)) {
72
            mkdir($targetDirectory, 0775, true);
73
        }
74
75
        $namespace = trim($namespace, '\\');
76
        $className = self::upperCamelCase($moduleSingular);
77
        $daoClassName = $className.'ZohoDao';
78
79
        $fieldRecords = $fields->getRecords();
80
81
        // Case is a reserved keyword. Let's rename it.
82
        if ($className === 'Case') {
83
            $className = 'ZohoCase';
84
        }
85
86
        $this->generateBean($fieldRecords, $namespace, $className, $moduleName, $targetDirectory, $moduleSingular);
87
        $this->generateDao($fieldRecords, $namespace, $className, $daoClassName, $moduleName, $targetDirectory, $moduleSingular, $modulePlural);
88
89
        return $namespace.'\\'.$daoClassName;
90
    }
91
92
    public function generateBean($fields, $namespace, $className, $moduleName, $targetDirectory, $moduleSingular)
93
    {
94
95
//        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...
96
//            $class = PhpClass::fromReflection(new \ReflectionClass($namespace."\\".$className));
97
//        } else {
98
            $class = PhpClass::create();
99
//        }
100
101
        $class->setName($className)
102
            ->setNamespace($namespace)
103
            ->addInterface('\\Wabel\\Zoho\\CRM\\ZohoBeanInterface')
104
            ->setMethod(PhpMethod::create('__construct'));
105
106
        // Let's add the ZohoID property
107
        self::registerProperty($class, 'zohoId', "The ID of this record in Zoho\nType: string\n", 'string');
108
109
        $usedIdentifiers = [];
110
111
        foreach ($fields as &$fieldCategory) {
112
            foreach ($fieldCategory as $name => &$field) {
113
                $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...
114
                $type = $field['type'];
115
                $isreadonly = $field['isreadonly'];
116
                $maxlength = $field['maxlength'];
117
                $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...
118
                $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...
119
                $customfield = $field['customfield'];
120
121 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...
122
                    case 'DateTime':
123
                    case 'Date':
124
                        $phpType = '\\DateTimeImmutable';
125
                        break;
126
                    case 'Boolean':
127
                        $phpType = 'bool';
128
                        break;
129
                    case 'Integer':
130
                        $phpType = 'int';
131
                        break;
132
                    default:
133
                        $phpType = 'string';
134
                        break;
135
                }
136
137
                $field['phpType'] = $phpType;
138
139
                $identifier = $this->getUniqueIdentifier($name, $usedIdentifiers);
140
                $usedIdentifiers[$identifier] = true;
141
142
                self::registerProperty($class, $identifier, 'Zoho field '.$name."\n".
143
                    'Type: '.$type."\n".
144
                    'Read only: '.($isreadonly ? 'true' : 'false')."\n".
145
                    'Max length: '.$maxlength."\n".
146
                    'Custom field: '.($customfield ? 'true' : 'false')."\n", $phpType);
147
148
                // Adds a ID field for lookups
149
                if ($type === 'Lookup') {
150
                    $generateId = false;
151
152
                    if ($customfield) {
153
                        $name .= '_ID';
154
                        $generateId = true;
155
                    } elseif ($name === $moduleSingular.' Owner') {
156
                        // Check if this is a "owner" field.
157
                        $name = 'SMOWNERID';
158
                        $generateId = true;
159
                    } else {
160
                        $mapping = [
161
                            'Account Name' => 'ACCOUNTID',
162
                            'Contact Name' => 'CONTACTID',
163
                            'Parent Account' => 'PARENTACCOUNTID',
164
                            'Campaign Source' => 'CAMPAIGNID',
165
                        ];
166
                        if (isset($mapping[$name])) {
167
                            $name = $mapping[$name];
168
                            $generateId = true;
169
                        } else {
170
                            $this->logger->warning('Unable to set a ID for the field {name} of the {module} module', [
171
                                    'name' => $name,
172
                                    'module' => $moduleName,
173
                            ]);
174
                        }
175
                    }
176
177
                    if ($generateId) {
178
                        $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...
179
                        $type = 'Lookup ID';
180
                        $isreadonly = true;
181
                        $maxlength = $field['maxlength'];
182
                        $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...
183
                        $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...
184
185
                        $field['phpType'] = $phpType;
186
187
                        self::registerProperty($class, ($customfield ? self::camelCase($name) : $name), 'Zoho field '.$name."\n".
188
                            'Type: '.$type."\n".
189
                            'Read only: '.($isreadonly ? 'true' : 'false')."\n".
190
                            'Max length: '.$maxlength."\n".
191
                            'Custom field: '.($customfield ? 'true' : 'false')."\n", 'string');
192
                    }
193
                }
194
            }
195
        }
196
197
        self::registerProperty($class, 'createdTime', "The time the record was created in Zoho\nType: DateTime\n", '\\DateTime');
198
        self::registerProperty($class, 'modifiedTime', "The last time the record was modified in Zoho\nType: DateTime\n", '\\DateTime');
199
200
        $method = PhpMethod::create('isDirty');
201
        $method->setDescription('Returns whether a property is changed or not.');
202
        $method->addParameter(PhpParameter::create('name'));
203
        $method->setBody("\$propertyName = 'dirty'.ucfirst(\$name);\nreturn \$this->\$propertyName;");
204
        $method->setType('bool');
205
        $class->setMethod($method);
206
207
        $generator = new CodeFileGenerator();
208
        $code = $generator->generate($class);
209
210 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...
211
            throw new ZohoCRMException("An error occurred while creating the class $className. Please verify the target directory or the rights of the file.");
212
        }
213
    }
214
215
    /**
216
     * Returns a unique identifier from the name.
217
     *
218
     * @param $name
219
     * @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...
220
     */
221
    private function getUniqueIdentifier($name, array $usedIdentifiers)
222
    {
223
        $id = self::camelCase($name);
224
        if (isset($usedIdentifiers[$id])) {
225
            $counter = 2;
226
            while (isset($usedIdentifiers[$id.'_'.$counter])) {
227
                ++$counter;
228
            }
229
230
            return $id.'_'.$counter;
231
        } else {
232
            return $id;
233
        }
234
    }
235
236
    public function generateDao($fields, $namespace, $className, $daoClassName, $moduleName, $targetDirectory, $moduleSingular, $modulePlural)
237
    {
238
        //        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...
239
//            $class = PhpClass::fromReflection(new \ReflectionClass($namespace."\\".$daoClassName));
240
//        } else {
241
            $class = PhpClass::create();
242
//        }
243
244
        $class->setName($daoClassName)
245
            ->setNamespace($namespace)
246
            ->setParentClassName('\\Wabel\\Zoho\\CRM\\AbstractZohoDao');
247
248
        $usedIdentifiers = [];
249
250
        foreach ($fields as $key => $fieldCategory) {
251
            foreach ($fieldCategory as $name => $field) {
252
                $type = $field['type'];
253
254 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...
255
                    case 'DateTime':
256
                    case 'Date':
257
                        $phpType = '\\DateTimeImmutable';
258
                        break;
259
                    case 'Boolean':
260
                        $phpType = 'bool';
261
                        break;
262
                    case 'Integer':
263
                        $phpType = 'int';
264
                        break;
265
                    default:
266
                        $phpType = 'string';
267
                        break;
268
                }
269
270
                $fields[$key][$name]['phpType'] = $phpType;
271
                $identifier = $this->getUniqueIdentifier($name, $usedIdentifiers);
272
                $usedIdentifiers[$identifier] = true;
273
                $fields[$key][$name]['getter'] = 'get'.ucfirst($identifier);
274
                $fields[$key][$name]['setter'] = 'set'.ucfirst($identifier);
275
                $fields[$key][$name]['name'] = $identifier;
276
277
                if ($type === 'Lookup') {
278
                    $generateId = false;
279
280
                    if ($field['customfield']) {
281
                        $name .= '_ID';
282
                        $generateId = true;
283
                    } elseif ($field['label'] === $moduleSingular.' Owner') {
284
                        // Check if this is a "owner" field.
285
                        $name = 'SMOWNERID';
286
                        $generateId = true;
287
                    } else {
288
                        $mapping = [
289
                            'Account Name' => 'ACCOUNTID',
290
                            'Contact Name' => 'CONTACTID',
291
                            'Parent Account' => 'PARENTACCOUNTID',
292
                            'Campaign Source' => 'CAMPAIGNID',
293
                        ];
294
                        if (isset($mapping[$field['label']])) {
295
                            $name = $mapping[$field['label']];
296
                            $generateId = true;
297
                        } 
298
                    }
299
                    if ($generateId) {
300
                        $fields[$key][$name]['req'] = false;
301
                        $fields[$key][$name]['type'] = 'Lookup ID';
302
                        $fields[$key][$name]['isreadonly'] = true;
303
                        $fields[$key][$name]['maxlength'] = 100;
304
                        $fields[$key][$name]['label'] = $name;
305
                        $fields[$key][$name]['dv'] = $name;
306
                        $fields[$key][$name]['customfield'] = true;
307
                        $fields[$key][$name]['phpType'] = $phpType;
308
                        $fields[$key][$name]['getter'] = 'get'.ucfirst(self::camelCase($name));
309
                        $fields[$key][$name]['setter'] = 'set'.ucfirst(self::camelCase($name));
310
                        $fields[$key][$name]['name'] = self::camelCase($name);
311
                    }
312
                }
313
            }
314
        }
315
316
        $class->setMethod(PhpMethod::create('getModule')->setBody('return '.var_export($moduleName, true).';'));
317
318
        $class->setMethod(PhpMethod::create('getSingularModuleName')->setBody('return '.var_export($moduleSingular, true).';'));
319
320
        $class->setMethod(PhpMethod::create('getPluralModuleName')->setBody('return '.var_export($modulePlural, true).';'));
321
322
        $class->setMethod(PhpMethod::create('getFields')->setBody('return '.var_export($fields, true).';'));
323
324
        $class->setMethod(PhpMethod::create('getBeanClassName')->setBody('return '.var_export($namespace.'\\'.$className, true).';'));
325
326
        $generator = new CodeFileGenerator();
327
        $code = $generator->generate($class);
328
329 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...
330
            throw new ZohoCRMException("An error occurred while creating the DAO $daoClassName. Please verify the target directory exists or the rights of the file.");
331
        }
332
    }
333
334
    private static function camelCase($str, array $noStrip = [])
335
    {
336
        $str = self::upperCamelCase($str, $noStrip);
337
        $str = lcfirst($str);
338
339
        return $str;
340
    }
341
342
    private static function upperCamelCase($str, array $noStrip = [])
343
    {
344
        // non-alpha and non-numeric characters become spaces
345
        $str = preg_replace('/[^a-z0-9'.implode('', $noStrip).']+/i', ' ', $str);
346
        $str = trim($str);
347
        // uppercase the first character of each word
348
        $str = ucwords($str);
349
        $str = str_replace(' ', '', $str);
350
351
        return $str;
352
    }
353
354
    private static function registerProperty(PhpClass $class, $name, $description, $type)
355
    {
356 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...
357
            $property = PhpProperty::create($name);
358
            $property->setDescription($description);
359
            $property->setType($type);
360
            $property->setVisibility('protected');
361
362
            $class->setProperty($property);
363
        }
364
365
        $isDirtyName = 'dirty'.ucfirst($name);
366 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...
367
            $dirtyProperty = PhpProperty::create($isDirtyName);
368
            $dirtyProperty->setDescription("Whether '$name' has been changed or not.");
369
            $dirtyProperty->setType('bool');
370
            $dirtyProperty->setVisibility('protected');
371
            $dirtyProperty->setDefaultValue(false);
0 ignored issues
show
Deprecated Code introduced by
The method gossi\codegen\model\part...Part::setDefaultValue() has been deprecated with message: use `setValue()` instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
372
373
            $class->setProperty($dirtyProperty);
374
        }
375
376
        $getterName = 'get'.ucfirst($name);
377
        $getterDescription = 'Get '.lcfirst($description);
378
        $setterName = 'set'.ucfirst($name);
379
        $setterDescription = 'Set '.lcfirst($description);
380
381
        if (!$class->hasMethod($getterName)) {
382
            $method = PhpMethod::create($getterName);
383
            $method->setDescription($getterDescription);
384
            $method->setBody("return \$this->{$name};");
385
            $class->setMethod($method);
386
        }
387
388
        if (!$class->hasMethod($setterName)) {
389
            $method = PhpMethod::create($setterName);
390
            $method->setDescription($setterDescription);
391
            $method->addParameter(PhpParameter::create($name)->setType($type));
392
            $method->setBody("\$this->{$name} = \${$name};\n".
393
                             '$this->dirty'.ucfirst($name)." = true;\n".
394
                             'return $this;');
395
            $class->setMethod($method);
396
        }
397
    }
398
}
399