ModelSerializerTraitGenerator::generate()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 1
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 keeko\tools\model\Relationship;
10
use Propel\Generator\Model\Table;
11
use gossi\codegen\model\PhpProperty;
12
13
class ModelSerializerTraitGenerator extends AbstractSerializerGenerator {
14
15
	/**
16
	 *
17
	 * @param Table $model
18
	 * @return PhpTrait
19
	 */
20
	public function generate(Table $model) {
21
		$ns = $this->packageService->getNamespace();
22
		$fqcn = sprintf('%s\\serializer\\base\\%sSerializerTrait', $ns, $model->getPhpName());
23
		$trait = new PhpTrait($fqcn);
24
25
		$this->generateIdentifyingMethods($trait, $model);
26
		$this->generateAttributeMethods($trait, $model);
27
		$this->generateRelationshipMethods($trait, $model);
28
		$this->generateTypeInferencerAccess($trait);
29
30
		return $trait;
31
	}
32
33
	protected function generateIdentifyingMethods(PhpTrait $trait, Table $model) {
34
		$package = $this->packageService->getPackage();
35
		$type = sprintf('%s/%s', $package->getKeeko()->getModule()->getSlug(), NameUtils::dasherize($model->getOriginCommonName()));
36
37
		$trait->setMethod(PhpMethod::create('getId')
38
			->addParameter(PhpParameter::create('model'))
39
			->setBody($this->twig->render('getId.twig'))
40
			->setType('string')
41
		);
42
43
		$trait->setMethod(PhpMethod::create('getType')
44
			->addParameter(PhpParameter::create('model'))
45
			->setBody($this->twig->render('getType.twig', [
46
				'type' => $type
47
			]))
48
			->setType('string')
49
		);
50
	}
51
52
	protected function generateAttributeMethods(PhpTrait $trait, Table $model) {
53
		$readFields = $this->generatorDefinitionService->getReadFields($model->getOriginCommonName());
54
		$attrs = '';
55
56
		foreach ($readFields as $field) {
57
			$col = $model->getColumn($field);
58
			$param = $col->isTemporalType() ? '\DateTime::ISO8601' : '';
59
			$attrs .= sprintf("\t'%s' => \$model->get%s(%s),\n",
60
				NameUtils::dasherize($field), $col->getPhpName(), $param
61
			);
62
		}
63
64
		if (count($field) > 0) {
0 ignored issues
show
Bug introduced by
The variable $field seems to be defined by a foreach iteration on line 56. 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...
65
			$attrs = substr($attrs, 0, -2);
66
		}
67
68
		$trait->setMethod(PhpMethod::create('getAttributes')
69
			->addParameter(PhpParameter::create('model'))
70
			->addParameter(PhpParameter::create('fields')->setType('array')->setDefaultValue(null))
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...
71
			->setBody($this->twig->render('getAttributes.twig', [
72
				'attrs' => $attrs
73
			]))
74
		);
75
76
		$trait->setMethod(PhpMethod::create('getSortFields')
77
			->setBody($this->twig->render('getFields.twig', [
78
				'fields' => $this->codeService->arrayToCode(array_map(function ($field) {
79
					return NameUtils::dasherize($field);
80
				}, $readFields))
81
			]))
82
		);
83
84
		$readFields = $this->generatorDefinitionService->getReadFields($model->getOriginCommonName());
85
		$trait->setMethod(PhpMethod::create('getFields')
86
			->setBody($this->twig->render('getFields.twig', [
87
				'fields' => $this->codeService->arrayToCode(array_map(function ($field) {
88
					return NameUtils::dasherize($field);
89
				}, $readFields))
90
			]))
91
		);
92
	}
93
94
	protected function generateRelationshipMethods(PhpTrait $trait, Table $model) {
95
// 		if ($model->isReadOnly()) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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
// 			return;
97
// 		}
98
99
		$fields = [];
100
		$methods = [];
101
		$plural = [];
102
		$relationships = $this->modelService->getRelationships($model);
103
		$methodNameGenerator = $this->factory->getRelationshipMethodNameGenerator();
104
105
		// add self link for relationships if there are any
106
		if ($relationships->size() > 0) {
107
			$trait->addUseStatement('Tobscure\\JsonApi\\Relationship');
108
			$trait->setMethod(PhpMethod::create('addRelationshipSelfLink')
109
				->addParameter(PhpParameter::create('relationship')
110
					->setType('Relationship')
111
				)
112
				->addParameter(PhpParameter::create('model')
113
					->setType('mixed')
114
				)
115
				->addParameter(PhpParameter::create('related')
116
					->setType('string')
117
				)
118
				->setAbstract(true)
119
				->setVisibility(PhpMethod::VISIBILITY_PROTECTED)
120
				->setType('Relationship')
121
			);
122
		}
123
124
		// iterate all relationships
125
		foreach ($relationships->getAll() as $rel) {
126
			// one-to-one
127
			if ($rel->getType() == Relationship::ONE_TO_ONE) {
128
				$foreign = $rel->getForeign();
129
				$relatedName = $rel->getRelatedName();
130
				$typeName = $rel->getRelatedTypeName();
131
				$method = NameUtils::toCamelCase($relatedName);
132
				$fields[$typeName] = $foreign->getPhpName() . '::getSerializer()->getType(null)';
133
				$trait->addUseStatement($foreign->getNamespace() . '\\' . $foreign->getPhpName());
134
				$trait->addUseStatement('Tobscure\\JsonApi\\Resource');
135
136
				// read
137
				$body = $this->twig->render('to-one-read.twig', [
138
					'class' => $foreign->getPhpName(),
139
					'related' => $relatedName,
140
					'related_type' => $typeName
141
				]);
142
			}
143
144
			// ?-to-many
145
			else {
146
				$foreign = $rel->getForeign();
147
				$typeName = $rel->getRelatedPluralTypeName();
148
				$method = NameUtils::toCamelCase($rel->getRelatedPluralName());
149
				$fields[$typeName] = $foreign->getPhpName() . '::getSerializer()->getType(null)';
150
				$trait->addUseStatement($foreign->getNamespace() . '\\' . $foreign->getPhpName());
151
				$trait->addUseStatement('Tobscure\\JsonApi\\Collection');
152
153
				// read
154
				$body = $this->twig->render('to-many-read.twig', [
155
					'class' => $foreign->getPhpName(),
156
					'related' => $typeName,
157
					'related_type' => $rel->getRelatedTypeName()
158
				]);
159
160
				// method name for collection
161
				$methods[$typeName] = $methodNameGenerator->generateMethodName($rel);
162
				$plural[$typeName] = $methodNameGenerator->generatePluralMethodName($rel);
163
// 				if ($rel->getType() == Relationship::MANY_TO_MANY
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...
164
// 						&& $rel->getForeign() == $rel->getModel()) {
165
// 					$lk = $rel->getLocalKey();
166
// 					$methods[$typeName] = $foreign->getPhpName() . 'RelatedBy' . $lk->getLocalColumn()->getPhpName();
167
// 					$plural[$typeName] = NameUtils::pluralize($foreign->getPhpName()) . 'RelatedBy' . $lk->getLocalColumn()->getPhpName();
168
// 				}
169
			}
170
171
			// set read method on class
172
			$trait->setMethod(PhpMethod::create($method)
173
				->addParameter(PhpParameter::create('model'))
174
				->setBody($body)
175
				->setType('Relationship')
176
			);
177
178
			// add reverse many-to-many
179
			if ($rel->getType() == Relationship::MANY_TO_MANY && $rel->isReflexive()) {
180
				$foreign = $rel->getForeign();
181
				$typeName = $rel->getReverseRelatedPluralTypeName();
182
				$method = NameUtils::toCamelCase($rel->getReverseRelatedPluralName());
183
				$fields[$typeName] = $foreign->getPhpName() . '::getSerializer()->getType(null)';
184
				$trait->addUseStatement($foreign->getNamespace() . '\\' . $foreign->getPhpName());
185
				$trait->addUseStatement('Tobscure\\JsonApi\\Collection');
186
187
				// read
188
				$body = $this->twig->render('to-many-read.twig', [
189
					'class' => $foreign->getPhpName(),
190
					'related' => $typeName,
191
					'related_type' => $rel->getReverseRelatedTypeName()
192
				]);
193
194
				$methods[$typeName] = $methodNameGenerator->generateReverseMethodName($rel);
195
				$plural[$typeName] = $methodNameGenerator->generateReversePluralMethodName($rel);
196
197
				// set read method on class
198
				$trait->setMethod(PhpMethod::create($method)
199
					->addParameter(PhpParameter::create('model'))
200
					->setBody($body)
201
					->setType('Relationship')
202
				);
203
			}
204
		}
205
206
		// method: getRelationships() : array
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
207
		$trait->setMethod(PhpMethod::create('getRelationships')
208
			->setBody($this->twig->render('getRelationships.twig', [
209
				'fields' => $fields
210
			]))
211
		);
212
213
		// method: getCollectionMethodName($relatedName) : string
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
214
		$trait->setProperty(PhpProperty::create('methodNames')
215
			->setExpression($this->codeService->mapToCode($methods))
216
			->setVisibility(PhpProperty::VISIBILITY_PRIVATE)
217
		);
218
		$trait->setMethod(PhpMethod::create('getCollectionMethodName')
219
			->addParameter(PhpParameter::create('relatedName'))
220
			->setBody($this->twig->render('getCollectionMethodName.twig'))
221
			->setVisibility(PhpMethod::VISIBILITY_PROTECTED)
222
		);
223
224
		// method: getCollectionMethodPluralName($relatedName) : string
0 ignored issues
show
Unused Code Comprehensibility introduced by
37% 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...
225
		$trait->setProperty(PhpProperty::create('methodPluralNames')
226
			->setExpression($this->codeService->mapToCode($plural))
227
			->setVisibility(PhpProperty::VISIBILITY_PRIVATE)
228
		);
229
		$trait->setMethod(PhpMethod::create('getCollectionMethodPluralName')
230
			->addParameter(PhpParameter::create('relatedName'))
231
			->setBody($this->twig->render('getCollectionMethodPluralName.twig'))
232
			->setVisibility(PhpMethod::VISIBILITY_PROTECTED)
233
		);
234
	}
235
236
	protected function generateTypeInferencerAccess(PhpTrait $trait) {
237
		$namespace = $this->factory->getNamespaceGenerator()->getSerializerNamespace();
238
		$trait->addUseStatement($namespace . '\\TypeInferencer');
239
		$trait->setMethod(PhpMethod::create('getTypeInferencer')
240
			->setVisibility(PhpMethod::VISIBILITY_PROTECTED)
241
			->setBody($this->twig->render('getTypeInferencer.twig'))
242
		);
243
	}
244
}
245