1
|
|
|
<?php |
2
|
|
|
namespace gossi\codegen\generator; |
3
|
|
|
|
4
|
|
|
use gossi\codegen\config\CodeFileGeneratorConfig; |
5
|
|
|
use gossi\codegen\model\GenerateableInterface; |
6
|
|
|
use gossi\docblock\Docblock; |
7
|
|
|
use phootwork\lang\Text; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Code file generator. |
11
|
|
|
* |
12
|
|
|
* Generates code for a model and puts it into a file with `<?php` statements. Can also |
13
|
|
|
* generate header comments. |
14
|
|
|
* |
15
|
|
|
* @author Thomas Gossmann |
16
|
|
|
*/ |
17
|
|
|
class CodeFileGenerator extends CodeGenerator { |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Creates a new CodeFileGenerator |
21
|
|
|
* |
22
|
|
|
* @see https://php-code-generator.readthedocs.org/en/latest/generator.html |
23
|
|
|
* @param CodeFileGeneratorConfig|array $config |
24
|
|
|
*/ |
25
|
6 |
|
public function __construct($config = null) { |
26
|
6 |
|
parent::__construct($config); |
27
|
6 |
|
} |
28
|
|
|
|
29
|
6 |
|
protected function configure($config = null) { |
30
|
6 |
|
if (is_array($config)) { |
31
|
5 |
|
$this->config = new CodeFileGeneratorConfig($config); |
32
|
1 |
|
} else if ($config instanceof CodeFileGeneratorConfig) { |
33
|
1 |
|
$this->config = $config; |
34
|
|
|
} else { |
35
|
1 |
|
$this->config = new CodeFileGeneratorConfig(); |
36
|
|
|
} |
37
|
6 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* {@inheritDoc} |
41
|
|
|
* |
42
|
|
|
* @return CodeFileGeneratorConfig |
43
|
|
|
*/ |
44
|
1 |
|
public function getConfig() { |
45
|
1 |
|
return $this->config; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* {@inheritDoc} |
50
|
|
|
*/ |
51
|
5 |
|
public function generate(GenerateableInterface $model) { |
52
|
5 |
|
$content = "<?php\n"; |
53
|
|
|
|
54
|
5 |
|
$comment = $this->config->getHeaderComment(); |
55
|
5 |
|
if ($comment !== null && !$comment->isEmpty()) { |
56
|
1 |
|
$content .= str_replace('/**', '/*', $comment->toString()) . "\n"; |
57
|
|
|
} |
58
|
|
|
|
59
|
5 |
|
$docblock = $this->config->getHeaderDocblock(); |
60
|
5 |
|
if ($docblock !== null && !$docblock->isEmpty()) { |
61
|
1 |
|
$content .= $docblock->toString() . "\n"; |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
if ($this->config->getDeclareStrictTypes()) { |
65
|
1 |
|
$content .= "declare(strict_types=1);\n\n"; |
66
|
|
|
} |
67
|
|
|
|
68
|
5 |
|
$content .= parent::generate($model); |
69
|
|
|
|
70
|
5 |
|
if ($this->config->getBlankLineAtEnd() && !Text::create($content)->endsWith("\n")) { |
|
|
|
|
71
|
4 |
|
$content .= "\n"; |
72
|
|
|
} |
73
|
|
|
|
74
|
5 |
|
return $content; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the parent class: