Completed
Push — master ( 98cd2e...56265b )
by Thomas
09:01
created

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 1
Metric Value
c 1
b 0
f 1
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\serializer\base;
3
4
use gossi\codegen\model\PhpMethod;
5
use gossi\codegen\model\PhpParameter;
6
use gossi\codegen\model\PhpTrait;
7
use keeko\framework\utils\NameUtils;
8
use keeko\tools\generator\serializer\AbstractSerializerGenerator;
9
use Propel\Generator\Model\Table;
10
11
class ModelSerializerTraitGenerator extends AbstractSerializerGenerator {
12
	
13
	/**
14
	 * 
15
	 * @param Table $model
16
	 * @return PhpTrait
17
	 */
18
	public function generate(Table $model) {
19
		$ns = $this->packageService->getNamespace();
20
		$fqcn = sprintf('%s\\serializer\\base\\%sSerializerTrait', $ns, $model->getPhpName());
21
		$class = new PhpTrait($fqcn);
22
// 		$class->setParentClassName('AbstractSerializer');
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% 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...
23
// 		$class->addUseStatement('keeko\\framework\\model\\AbstractSerializer');
24
		
25
		$this->generateIdentifyingMethods($class, $model);
26
		$this->generateAttributeMethods($class, $model);
27
		$this->generateHydrateMethod($class, $model);
28
		$this->generateRelationshipMethods($class, $model);
29
		
30
		return $class;
31
	}
32
	
33
	protected function generateIdentifyingMethods(PhpTrait $class, Table $model) {
34
		$package = $this->packageService->getPackage();
35
		$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...
36
		
37
		$class->setMethod(PhpMethod::create('getId')
38
			->addParameter(PhpParameter::create('model'))
39
			->setBody($this->twig->render('getId.twig'))
40
		);
41
		
42
		$class->setMethod(PhpMethod::create('getType')
43
			->addParameter(PhpParameter::create('model'))
44
			->setBody($this->twig->render('getType.twig', [
45
				'type' => $type
46
			]))
47
		);
48
	}
49
	
50
	protected function generateAttributeMethods(PhpTrait $class, Table $model) {
51
		$writeFields = $this->codegenService->getWriteFields($model->getOriginCommonName());
52
		$attrs = '';
53
		
54
		foreach ($writeFields as $field) {
55
			$col = $model->getColumn($field);
56
			$param = $col->isTemporalType() ? '\DateTime::ISO8601' : '';
57
			$attrs .= sprintf("\t'%s' => \$model->%s(%s),\n", $field, $col->getPhpName(), $param);
58
		}
59
		
60
		if (count($field) > 0) {
0 ignored issues
show
Bug introduced by
The variable $field seems to be defined by a foreach iteration on line 54. 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...
61
			$attrs = substr($attrs, 0, -1);
62
		}
63
		
64
		$class->setMethod(PhpMethod::create('getAttributes')
65
			->addParameter(PhpParameter::create('model'))
66
			->addParameter(PhpParameter::create('fields')->setType('array')->setDefaultValue(null))
67
			->setBody($this->twig->render('getAttributes.twig', [
68
				'attrs' => $attrs
69
			]))
70
		);
71
		
72
		$class->setMethod(PhpMethod::create('getSortFields')
73
			->setBody($this->twig->render('getFields.twig', [
74
				'fields' => $this->codegenService->arrayToCode($writeFields)
75
			]))
76
		);
77
		
78
		$readFields = $this->codegenService->getReadFields($model->getOriginCommonName());
79
		$class->setMethod(PhpMethod::create('getFields')
80
			->setBody($this->twig->render('getFields.twig', [
81
				'fields' => $this->codegenService->arrayToCode($readFields)
82
			]))
83
		);
84
	}
85
	
86
	protected function generateHydrateMethod(PhpTrait $class, Table $model) {
87
		if ($model->isReadOnly()) {
88
			$body = $this->twig->render('hydrate-readonly.twig');
89
		} else {
90
			$class->addUseStatement('keeko\\framework\\utils\\HydrateUtils');
91
			$modelName = $model->getOriginCommonName();
92
			$conversions = $this->codegenService->getCodegen()->getWriteConversion($modelName);
93
			$fields = $this->codegenService->getWriteFields($modelName);
94
			$code = '';
95
			
96
			foreach ($fields as $field) {
97
				$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...
98
				if (isset($conversions[$field])) {
99
					$code .= ' => function($v) {'."\n\t".'return ' . $conversions[$field] . ';'."\n".'}';
100
				}
101
		
102
				$code .= ', ';
103
			}
104
			
105
			if (strlen($code) > 0) {
106
				$code = substr($code, 0, -2);
107
			}
108
			
109
			$code = sprintf('[%s]', $code);
110
			$body = $this->twig->render('hydrate.twig', [
111
				'code' => $code
112
			]);
113
		}
114
		
115
		$class->setMethod(PhpMethod::create('hydrate')
116
			->addParameter(PhpParameter::create('model'))
117
			->addParameter(PhpParameter::create('data'))
118
			->setBody($body)
119
		);
120
	}
121
	
122
	protected function generateRelationshipMethods(PhpTrait $class, Table $model) {
123
		if ($model->isReadOnly()) {
124
			return;
125
		}
126
		
127
		$rels = [];
128
		$relationships = $this->modelService->getRelationships($model);
129
		
130
		if ($relationships['count'] > 0) {
131
			$class->addUseStatement('Tobscure\\JsonApi\\Relationship');
132
		}
133
		
134
		foreach ($relationships['all'] as $rel) {
135
			if ($rel['type'] == 'one') {
136
				$fk = $rel['fk'];
137
				$foreignModel = $fk->getForeignTable();
138
				
139
				$refPhpName = $fk->getPhpName();
140
				if ($refPhpName === null) {
141
					$refPhpName = $foreignModel->getPhpName();
142
				}
143
				
144
				$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...
145
				$method = NameUtils::toCamelCase($refPhpName);
146
				$crudMethod = $refPhpName;
147
				$rels[$name] = $foreignModel->getPhpName() . '::getSerializer()->getType(null)';
148
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName());
149
				$class->addUseStatement('Tobscure\\JsonApi\\Resource');
150
				
151
				// read
152
				$body = $this->twig->render('to-one-read.twig', [
153
					'ref' => $refPhpName,
154
					'class' => $foreignModel->getPhpName()
155
				]);
156
				
157
				// set
158
				$class->setMethod(PhpMethod::create('set'.$crudMethod)
159
					->addParameter(PhpParameter::create('model'))
160
					->addParameter(PhpParameter::create('data'))
161
					->setBody($this->twig->render('to-one-set.twig', [
162
						'ref' => $refPhpName
163
					]))
164
				);
165
			}
166
			
167
			if ($rel['type'] == 'many') {
168
				$fk = $rel['fk'];
169
				$foreignModel = $fk->getForeignTable();
170
				
171
				$refPhpName = $rel['lk']->getRefPhpName();
172
				if ($refPhpName === null) {
173
					$refPhpName = $foreignModel->getPhpName();
174
				}
175
				
176
				$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...
177
				$method = NameUtils::toCamelCase($refPhpName);
178
				$crudMethod = NameUtils::pluralize($refPhpName);
179
				$rels[$name] = $foreignModel->getPhpName() . '::getSerializer()->getType(null)';
180
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName());
181
				$class->addUseStatement($foreignModel->getNamespace() . '\\' . $foreignModel->getPhpName() . 'Query');
182
				$class->addUseStatement('Tobscure\\JsonApi\\Collection');
183
				
184
				// read
185
				$body = $this->twig->render('to-many-read.twig', [
186
					'getter' => NameUtils::pluralize($refPhpName),
187
					'class' => $refPhpName
188
				]);
189
				
190
				// set
191
				$class->addUseStatement($rel['cfk']->getMiddleTable()->getNamespace() . '\\' .$rel['cfk']->getMiddleTable()->getPhpName() . 'Query');
192
				$class->setMethod(PhpMethod::create('set'.$crudMethod)
193
					->addParameter(PhpParameter::create('model'))
194
					->addParameter(PhpParameter::create('data'))
195
					->setBody($this->twig->render('to-many-set.twig', [
196
						'query_class' => $rel['cfk']->getMiddleTable()->getPhpName(),
197
						'class' => $refPhpName,
198
						'adder' => $crudMethod
199
					]))
200
				);
201
202
				// add
203
				$class->setMethod(PhpMethod::create('add'.$crudMethod)
204
					->addParameter(PhpParameter::create('model'))
205
					->addParameter(PhpParameter::create('data'))
206
					->setBody($this->twig->render('to-many-add.twig', [
207
						'ref' => $refPhpName,
208
						'ref_var' => $method
209
					]))
210
				);
211
				
212
				// remove
213
				$class->setMethod(PhpMethod::create('remove'.$crudMethod)
214
					->addParameter(PhpParameter::create('model'))
215
					->addParameter(PhpParameter::create('data'))
216
					->setBody($this->twig->render('to-many-remove.twig', [
217
						'ref' => $refPhpName,
218
						'ref_var' => $method
219
					]))
220
				);
221
			}
222
			
223
			// needs to go down
224
			$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...
225
				->addParameter(PhpParameter::create('model'))
226
				->addParameter(PhpParameter::create('related'))
227
				->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...
228
			);
229
		}
230
		
231
		$class->setMethod(PhpMethod::create('getRelationships')
232
			->setBody($this->twig->render('getRelationships.twig', [
233
				'fields' => $rels
234
			]))
235
		);
236
	}
237
}