Completed
Push — master ( 66405f...98cd2e )
by Thomas
06:52
created

SerializerGenerator::generateRelationshipMethods()   C

Complexity

Conditions 8
Paths 21

Size

Total Lines 115
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 115
rs 5.2676
cc 8
eloc 71
nc 21
nop 2

How to fix   Long Method   

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:

1
<?php
2
namespace keeko\tools\generator;
3
4
use gossi\codegen\model\PhpClass;
5
use gossi\codegen\model\PhpMethod;
6
use gossi\codegen\model\PhpParameter;
7
use keeko\framework\utils\NameUtils;
8
use keeko\tools\generator\AbstractCodeGenerator;
9
use Propel\Generator\Model\Table;
10
use phootwork\file\File;
11
12
class SerializerGenerator extends AbstractCodeGenerator {
13
14
	protected function getTemplateFolder() {
15
		return 'serializer';
16
	}
17
	
18
	public function generate(Table $model) {
19
		$fqcn = sprintf('%s\\serializer\\%sSerializer', $model->getNamespace(), $model->getPhpName());
20
		$class = new PhpClass($fqcn);
21
// 		$file = new File($this->codegenService->getFilename($class));
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
22
// 		if ($file->exists()) {
23
// 			$class = PhpClass::fromFile($file->getPathname());
24
// 		}
25
		$class->setParentClassName('AbstractSerializer');
26
		$class->addUseStatement('keeko\\framework\\model\\AbstractSerializer');
27
		
28
		$this->generateIdentifyingMethods($class, $model);
29
		$this->generateAttributeMethods($class, $model);
30
		$this->generateHydrateMethod($class, $model);
31
		$this->generateRelationshipMethods($class, $model);
32
		
33
		return $class;
34
	}
35
	
36
	protected function generateIdentifyingMethods(PhpClass $class, Table $model) {
37
		$package = $this->packageService->getPackage();
38
		$type = sprintf('%s/%s', $package->getCleanName(), NameUtils::dasherize($model->getOriginCommonName()));
1 ignored issue
show
Bug introduced by
The method dasherize() cannot be called from this context as it is declared private in class keeko\framework\utils\NameUtils.

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...
Bug introduced by
The method getCleanName() does not seem to exist on object<keeko\framework\schema\PackageSchema>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
39
		
40
		$class->setMethod(PhpMethod::create('getId')
41
			->addParameter(PhpParameter::create('model'))
42
			->setBody($this->twig->render('getId.twig'))
43
		);
44
		
45
		$class->setMethod(PhpMethod::create('getType')
46
			->addParameter(PhpParameter::create('model'))
47
			->setBody($this->twig->render('getType.twig', [
48
				'type' => $type
49
			]))
50
		);
51
	}
52
	
53
	protected function generateAttributeMethods(PhpClass $class, Table $model) {
54
		$writeFields = $this->codegenService->getWriteFields($model->getOriginCommonName());
55
		$attrs = '';
56
		
57
		foreach ($writeFields as $field) {
58
			$col = $model->getColumn($field);
59
			$param = $col->isTemporalType() ? '\DateTime::ISO8601' : '';
60
			$attrs .= sprintf("\t'%s' => \$model->%s(%s),\n", $field, $col->getPhpName(), $param);
61
		}
62
		
63
		if (count($field) > 0) {
0 ignored issues
show
Bug introduced by
The variable $field seems to be defined by a foreach iteration on line 57. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
64
			$attrs = substr($attrs, 0, -1);
65
		}
66
		
67
		$class->setMethod(PhpMethod::create('getAttributes')
68
			->addParameter(PhpParameter::create('model'))
69
			->addParameter(PhpParameter::create('fields')->setType('array')->setDefaultValue(null))
70
			->setBody($this->twig->render('getAttributes.twig', [
71
				'attrs' => $attrs
72
			]))
73
		);
74
		
75
		$class->setMethod(PhpMethod::create('getSortFields')
76
			->setBody($this->twig->render('getFields.twig', [
77
				'fields' => $this->codegenService->arrayToCode($writeFields)
78
			]))
79
		);
80
		
81
		$readFields = $this->codegenService->getReadFields($model->getOriginCommonName());
82
		$class->setMethod(PhpMethod::create('getFields')
83
			->setBody($this->twig->render('getFields.twig', [
84
				'fields' => $this->codegenService->arrayToCode($readFields)
85
			]))
86
		);
87
	}
88
	
89
	protected function generateHydrateMethod(PhpClass $class, Table $model) {
90
		if ($model->isReadOnly()) {
91
			$body = $this->twig->render('hydrate-readonly.twig');
92
		} else {
93
			$class->addUseStatement('keeko\\framework\\utils\\HydrateUtils');
94
			$modelName = $model->getOriginCommonName();
95
			$conversions = $this->codegenService->getCodegen()->getWriteConversion($modelName);
96
			$fields = $this->codegenService->getWriteFields($modelName);
97
			$code = '';
98
			
99
			foreach ($fields as $field) {
100
				$code .= "'$field'";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $field instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
101
				if (isset($conversions[$field])) {
102
					$code .= ' => function($v) {'."\n\t".'return ' . $conversions[$field] . ';'."\n".'}';
103
				}
104
		
105
				$code .= ', ';
106
			}
107
			
108
			if (strlen($code) > 0) {
109
				$code = substr($code, 0, -2);
110
			}
111
			
112
			$code = sprintf('[%s]', $code);
113
			$body = $this->twig->render('hydrate.twig', [
114
				'code' => $code
115
			]);
116
		}
117
		
118
		$class->setMethod(PhpMethod::create('hydrate')
119
			->addParameter(PhpParameter::create('model'))
120
			->addParameter(PhpParameter::create('data'))
121
			->setBody($body)
122
		);
123
	}
124
	
125
	protected function generateRelationshipMethods(PhpClass $class, Table $model) {
126
		if ($model->isReadOnly()) {
127
			return;
128
		}
129
		
130
		$rels = [];
131
		$relationships = $this->modelService->getRelationships($model);
132
		
133
		if ($relationships['count'] > 0) {
134
			$class->addUseStatement('Tobscure\\JsonApi\\Relationship');
135
		}
136
		
137
		foreach ($relationships['all'] as $rel) {
138
			if ($rel['type'] == 'one') {
139
				$fk = $rel['fk'];
140
				$foreignModel = $fk->getForeignTable();
141
				
142
				$refPhpName = $fk->getPhpName();
143
				if ($refPhpName === null) {
144
					$refPhpName = $foreignModel->getPhpName();
145
				}
146
				
147
				$name = NameUtils::dasherize($refPhpName);
1 ignored issue
show
Bug introduced by
The method dasherize() cannot be called from this context as it is declared private in class keeko\framework\utils\NameUtils.

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
				$method = NameUtils::toCamelCase($refPhpName);
149
				$crudMethod = $refPhpName;
150
				$rels[$name] = $foreignModel->getPhpName() . '::getSerializer()->getType(null)';
151
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName());
152
				$class->addUseStatement('Tobscure\\JsonApi\\Resource');
153
				
154
				// read
155
				$body = $this->twig->render('to-one-read.twig', [
156
					'ref' => $refPhpName,
157
					'class' => $foreignModel->getPhpName()
158
				]);
159
				
160
				// set
161
				$class->setMethod(PhpMethod::create('set'.$crudMethod)
162
					->addParameter(PhpParameter::create('model'))
163
					->addParameter(PhpParameter::create('data'))
164
					->setBody($this->twig->render('to-one-set.twig', [
165
						'ref' => $refPhpName
166
					]))
167
				);
168
			}
169
			
170
			if ($rel['type'] == 'many') {
171
				$fk = $rel['fk'];
172
				$foreignModel = $fk->getForeignTable();
173
				
174
				$refPhpName = $rel['lk']->getRefPhpName();
175
				if ($refPhpName === null) {
176
					$refPhpName = $foreignModel->getPhpName();
177
				}
178
				
179
				$name = NameUtils::dasherize($refPhpName);
1 ignored issue
show
Bug introduced by
The method dasherize() cannot be called from this context as it is declared private in class keeko\framework\utils\NameUtils.

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...
180
				$method = NameUtils::toCamelCase($refPhpName);
181
				$crudMethod = NameUtils::pluralize($refPhpName);
182
				$rels[$name] = $foreignModel->getPhpName() . '::getSerializer()->getType(null)';
183
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName());
184
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName() . 'Query');
185
				$class->addUseStatement('Tobscure\\JsonApi\\Collection');
186
				
187
				// read
188
				$body = $this->twig->render('to-many-read.twig', [
189
					'getter' => NameUtils::pluralize($refPhpName),
190
					'class' => $refPhpName
191
				]);
192
				
193
				// set
194
				$class->addUseStatement($rel['cfk']->getMiddleTable()->getNamespace() . '\\' .$rel['cfk']->getMiddleTable()->getPhpName() . 'Query');
195
				$class->setMethod(PhpMethod::create('set'.$crudMethod)
196
					->addParameter(PhpParameter::create('model'))
197
					->addParameter(PhpParameter::create('data'))
198
					->setBody($this->twig->render('to-many-set.twig', [
199
						'query_class' => $rel['cfk']->getMiddleTable()->getPhpName(),
200
						'class' => $refPhpName,
201
						'adder' => $crudMethod
202
					]))
203
				);
204
205
				// add
206
				$class->setMethod(PhpMethod::create('add'.$crudMethod)
207
					->addParameter(PhpParameter::create('model'))
208
					->addParameter(PhpParameter::create('data'))
209
					->setBody($this->twig->render('to-many-add.twig', [
210
						'ref' => $refPhpName,
211
						'ref_var' => $method
212
					]))
213
				);
214
				
215
				// remove
216
				$class->setMethod(PhpMethod::create('remove'.$crudMethod)
217
					->addParameter(PhpParameter::create('model'))
218
					->addParameter(PhpParameter::create('data'))
219
					->setBody($this->twig->render('to-many-remove.twig', [
220
						'ref' => $refPhpName,
221
						'ref_var' => $method
222
					]))
223
				);
224
			}
225
			
226
			// needs to go down
227
			$class->setMethod(PhpMethod::create($method)
0 ignored issues
show
Bug introduced by
The variable $method 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...
228
				->addParameter(PhpParameter::create('model'))
229
				->addParameter(PhpParameter::create('related'))
230
				->setBody($body)
0 ignored issues
show
Bug introduced by
The variable $body 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...
231
			);
232
		}
233
		
234
		$class->setMethod(PhpMethod::create('getRelationships')
235
			->setBody($this->twig->render('getRelationships.twig', [
236
				'fields' => $rels
237
			]))
238
		);
239
	}
240
}