Completed
Pull Request — 1.1 (#26)
by Raphaël
04:50
created

EntitiesGeneratorService::generateDao()   F

Complexity

Conditions 23
Paths 12424

Size

Total Lines 136
Code Lines 97

Duplication

Lines 18
Ratio 13.24 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 18
loc 136
rs 2
cc 23
eloc 97
nc 12424
nop 8

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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
                $nullable = false;
121
122 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...
123
                    case 'DateTime':
124
                    case 'Date':
125
                        $phpType = '\\DateTimeInterface';
126
                        $nullable = true;
127
                        break;
128
                    case 'Boolean':
129
                        $phpType = 'bool';
130
                        break;
131
                    case 'Integer':
132
                        $phpType = 'int';
133
                        break;
134
                    default:
135
                        $phpType = 'string';
136
                        break;
137
                }
138
139
                $field['phpType'] = $phpType;
140
141
                $identifier = $this->getUniqueIdentifier($name, $usedIdentifiers);
142
                $usedIdentifiers[$identifier] = true;
143
144
                self::registerProperty($class, $identifier, 'Zoho field '.$name."\n".
145
                    'Type: '.$type."\n".
146
                    'Read only: '.($isreadonly ? 'true' : 'false')."\n".
147
                    'Max length: '.$maxlength."\n".
148
                    'Custom field: '.($customfield ? 'true' : 'false')."\n", $phpType, $nullable);
149
150
                // Adds a ID field for lookups
151
                if ($type === 'Lookup') {
152
                    $generateId = false;
153
154
                    if ($customfield) {
155
                        $name .= '_ID';
156
                        $generateId = true;
157
                    } elseif ($name === $moduleSingular.' Owner') {
158
                        // Check if this is a "owner" field.
159
                        $name = 'SMOWNERID';
160
                        $generateId = true;
161
                    } else {
162
                        $mapping = [
163
                            'Account Name' => 'ACCOUNTID',
164
                            'Contact Name' => 'CONTACTID',
165
                            'Parent Account' => 'PARENTACCOUNTID',
166
                            'Campaign Source' => 'CAMPAIGNID',
167
                        ];
168
                        if (isset($mapping[$name])) {
169
                            $name = $mapping[$name];
170
                            $generateId = true;
171
                        } else {
172
                            $this->logger->warning('Unable to set a ID for the field {name} of the {module} module', [
173
                                    'name' => $name,
174
                                    'module' => $moduleName,
175
                            ]);
176
                        }
177
                    }
178
179
                    if ($generateId) {
180
                        $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...
181
                        $type = 'Lookup ID';
182
                        $isreadonly = true;
183
                        $maxlength = $field['maxlength'];
184
                        $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...
185
                        $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...
186
187
                        $field['phpType'] = $phpType;
188
189
                        self::registerProperty($class, ($customfield ? self::camelCase($name) : $name), 'Zoho field '.$name."\n".
190
                            'Type: '.$type."\n".
191
                            'Read only: '.($isreadonly ? 'true' : 'false')."\n".
192
                            'Max length: '.$maxlength."\n".
193
                            'Custom field: '.($customfield ? 'true' : 'false')."\n", 'string');
194
                    }
195
                }
196
            }
197
        }
198
199
        self::registerProperty($class, 'createdTime', "The time the record was created in Zoho\nType: DateTime\n", '\\DateTime');
200
        self::registerProperty($class, 'modifiedTime', "The last time the record was modified in Zoho\nType: DateTime\n", '\\DateTime');
201
202
        $method = PhpMethod::create('isDirty');
203
        $method->setDescription('Returns whether a property is changed or not.');
204
        $method->addParameter(PhpParameter::create('name'));
205
        $method->setBody("\$propertyName = 'dirty'.ucfirst(\$name);\nreturn \$this->\$propertyName;");
206
        $method->setType('bool');
207
        $class->setMethod($method);
208
209
        $generator = new CodeFileGenerator();
210
        $code = $generator->generate($class);
211
212 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...
213
            throw new ZohoCRMException("An error occurred while creating the class $className. Please verify the target directory or the rights of the file.");
214
        }
215
    }
216
217
    /**
218
     * Returns a unique identifier from the name.
219
     *
220
     * @param $name
221
     * @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...
222
     */
223
    private function getUniqueIdentifier($name, array $usedIdentifiers)
224
    {
225
        $id = self::camelCase($name);
226
        if (isset($usedIdentifiers[$id])) {
227
            $counter = 2;
228
            while (isset($usedIdentifiers[$id.'_'.$counter])) {
229
                ++$counter;
230
            }
231
232
            return $id.'_'.$counter;
233
        } else {
234
            return $id;
235
        }
236
    }
237
238
    public function generateDao($fields, $namespace, $className, $daoClassName, $moduleName, $targetDirectory, $moduleSingular, $modulePlural)
239
    {
240
        //        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...
241
//            $class = PhpClass::fromReflection(new \ReflectionClass($namespace."\\".$daoClassName));
242
//        } else {
243
            $class = PhpClass::create();
244
//        }
245
246
        $class->setName($daoClassName)
247
            ->setNamespace($namespace)
248
            ->setParentClassName('\\Wabel\\Zoho\\CRM\\AbstractZohoDao');
249
250
        $usedIdentifiers = [];
251
252
        foreach ($fields as $key => $fieldCategory) {
253
            foreach ($fieldCategory as $name => $field) {
254
                $type = $field['type'];
255
256 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...
257
                    case 'DateTime':
258
                    case 'Date':
259
                        $phpType = '\\DateTime';
260
                        break;
261
                    case 'Boolean':
262
                        $phpType = 'bool';
263
                        break;
264
                    case 'Integer':
265
                        $phpType = 'int';
266
                        break;
267
                    default:
268
                        $phpType = 'string';
269
                        break;
270
                }
271
272
                $fields[$key][$name]['phpType'] = $phpType;
273
                $identifier = $this->getUniqueIdentifier($name, $usedIdentifiers);
274
                $usedIdentifiers[$identifier] = true;
275
                $fields[$key][$name]['getter'] = 'get'.ucfirst($identifier);
276
                $fields[$key][$name]['setter'] = 'set'.ucfirst($identifier);
277
                $fields[$key][$name]['name'] = $identifier;
278
279
                $specialOwnerFieldsMapping = [
280
                    'Created By' => 'SMCREATORID',
281
                    'Modified By' =>'MODIFIEDBY',
282
                ];
283
284
                $specialDateFieldsMapping = [
285
                    'Created Time' => 'createdTime',
286
                    'Modified Time' =>'modifiedTime'
287
                ];
288
                //Detect Special Fields from Zoho - Using API, you cannot create or update these system-generated fields:
289
                $systemGenerated = false;
290
                if (isset($specialOwnerFieldsMapping[$field['label']]) || isset($specialDateFieldsMapping[$field['label']])){
291
                   $systemGenerated = true;
292
                }
293
                if($systemGenerated){
294
                    $dateSpecialField = false;
295
                    if (isset($specialOwnerFieldsMapping[$field['label']])) {
296
                        $name = $specialOwnerFieldsMapping[$field['label']];
297
                        $generateId = true;
298
                    }
299
                    if (isset($specialDateFieldsMapping[$field['label']])) {
300
                        $name = $specialDateFieldsMapping[$field['label']];
301
                        $generateId = true;
302
                        $dateSpecialField = true;
303
                    }
304
                    if ($generateId) {
0 ignored issues
show
Bug introduced by
The variable $generateId does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
305
                        $fields[$key][$name]['req'] = false;
306
                        $fields[$key][$name]['type'] = !$dateSpecialField?'Lookup ID':'Date';
307
                        $fields[$key][$name]['isreadonly'] = !$dateSpecialField?true:false;
308
                        $fields[$key][$name]['maxlength'] = !$dateSpecialField?100:20;
309
                        $fields[$key][$name]['label'] = $name;
310
                        $fields[$key][$name]['dv'] = $name;
311
                        $fields[$key][$name]['customfield'] = true;
312
                        $fields[$key][$name]['phpType'] = !$dateSpecialField?$phpType:'\\DateTime';
313
                        $fields[$key][$name]['getter'] = 'get'.ucfirst(self::camelCase($name));
314
                        $fields[$key][$name]['setter'] = 'set'.ucfirst(self::camelCase($name));
315
                        $fields[$key][$name]['name'] = self::camelCase($name);
316
                    }
317
                }
318
                if ($type === 'Lookup') {
319
                    $generateId = false;
320
321
                    if ($field['customfield']) {
322
                        $name .= '_ID';
323
                        $generateId = true;
324
                    } elseif ($field['label'] === $moduleSingular.' Owner') {
325
                        // Check if this is a "owner" field.
326
                        $name = 'SMOWNERID';
327
                        $generateId = true;
328
                    } else {
329
                        $mapping = [
330
                            'Account Name' => 'ACCOUNTID',
331
                            'Contact Name' => 'CONTACTID',
332
                            'Parent Account' => 'PARENTACCOUNTID',
333
                            'Campaign Source' => 'CAMPAIGNID',
334
                        ];
335
                        if (isset($mapping[$field['label']])) {
336
                            $name = $mapping[$field['label']];
337
                            $generateId = true;
338
                        }
339
                    }
340
                    if ($generateId) {
341
                        $fields[$key][$name]['req'] = false;
342
                        $fields[$key][$name]['type'] = 'Lookup ID';
343
                        $fields[$key][$name]['isreadonly'] = true;
344
                        $fields[$key][$name]['maxlength'] = 100;
345
                        $fields[$key][$name]['label'] = $name;
346
                        $fields[$key][$name]['dv'] = $name;
347
                        $fields[$key][$name]['customfield'] = true;
348
                        $fields[$key][$name]['phpType'] = $phpType;
349
                        $fields[$key][$name]['getter'] = 'get'.ucfirst(self::camelCase($name));
350
                        $fields[$key][$name]['setter'] = 'set'.ucfirst(self::camelCase($name));
351
                        $fields[$key][$name]['name'] = self::camelCase($name);
352
                    }
353
                }
354
            }
355
        }
356
357
        $class->setMethod(PhpMethod::create('getModule')->setBody('return '.var_export($moduleName, true).';'));
358
359
        $class->setMethod(PhpMethod::create('getSingularModuleName')->setBody('return '.var_export($moduleSingular, true).';'));
360
361
        $class->setMethod(PhpMethod::create('getPluralModuleName')->setBody('return '.var_export($modulePlural, true).';'));
362
363
        $class->setMethod(PhpMethod::create('getFields')->setBody('return '.var_export($fields, true).';'));
364
365
        $class->setMethod(PhpMethod::create('getBeanClassName')->setBody('return '.var_export($namespace.'\\'.$className, true).';'));
366
367
        $generator = new CodeFileGenerator();
368
        $code = $generator->generate($class);
369
370 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...
371
            throw new ZohoCRMException("An error occurred while creating the DAO $daoClassName. Please verify the target directory exists or the rights of the file.");
372
        }
373
    }
374
375
    private static function camelCase($str, array $noStrip = [])
376
    {
377
        $str = self::upperCamelCase($str, $noStrip);
378
        $str = lcfirst($str);
379
380
        return $str;
381
    }
382
383
    private static function upperCamelCase($str, array $noStrip = [])
384
    {
385
        // non-alpha and non-numeric characters become spaces
386
        $str = preg_replace('/[^a-z0-9'.implode('', $noStrip).']+/i', ' ', $str);
387
        $str = trim($str);
388
        // uppercase the first character of each word
389
        $str = ucwords($str);
390
        $str = str_replace(' ', '', $str);
391
392
        return $str;
393
    }
394
395
    private static function registerProperty(PhpClass $class, $name, $description, $type, $nullable = false)
396
    {
397 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...
398
            $property = PhpProperty::create($name);
399
            $property->setDescription($description);
400
            $property->setType($type);
401
            $property->setVisibility('protected');
402
403
            $class->setProperty($property);
404
        }
405
406
        $isDirtyName = 'dirty'.ucfirst($name);
407 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...
408
            $dirtyProperty = PhpProperty::create($isDirtyName);
409
            $dirtyProperty->setDescription("Whether '$name' has been changed or not.");
410
            $dirtyProperty->setType('bool');
411
            $dirtyProperty->setVisibility('protected');
412
            $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...
413
414
            $class->setProperty($dirtyProperty);
415
        }
416
417
        $getterName = 'get'.ucfirst($name);
418
        $getterDescription = 'Get '.lcfirst($description);
419
        $setterName = 'set'.ucfirst($name);
420
        $setterDescription = 'Set '.lcfirst($description);
421
422
        if (!$class->hasMethod($getterName)) {
423
            $method = PhpMethod::create($getterName);
424
            $method->setDescription($getterDescription);
425
            $method->setBody("return \$this->{$name};");
426
            $class->setMethod($method);
427
        }
428
429
        if (!$class->hasMethod($setterName)) {
430
            $method = PhpMethod::create($setterName);
431
            $method->setDescription($setterDescription);
432
            $parameter = PhpParameter::create($name)->setType($type);
433
            if ($nullable) {
434
                $parameter->setValue(null);
435
            }
436
            $method->addParameter($parameter);
437
            $method->setBody("\$this->{$name} = \${$name};\n".
438
                             '$this->dirty'.ucfirst($name)." = true;\n".
439
                             'return $this;');
440
            $class->setMethod($method);
441
        }
442
    }
443
}
444