-
Notifications
You must be signed in to change notification settings - Fork 125
/
PropertyGenerator.php
84 lines (68 loc) · 2.07 KB
/
PropertyGenerator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace Jane\JsonSchema\Generator\Model;
use Jane\JsonSchema\Generator\Naming;
use Jane\JsonSchema\Guesser\Guess\Property;
use Jane\JsonSchema\Guesser\Guess\Type;
use PhpParser\Comment\Doc;
use PhpParser\Node\Stmt;
use PhpParser\Parser;
trait PropertyGenerator
{
/**
* The naming service.
*
* @return Naming
*/
abstract protected function getNaming();
/**
* The PHP Parser.
*
* @return Parser
*/
abstract protected function getParser();
protected function createProperty(Property $property, $namespace, $default = null, bool $required = false): Stmt
{
$propertyName = $this->getNaming()->getPropertyName($property->getPhpName());
$propertyStmt = new Stmt\PropertyProperty($propertyName);
if (null === $default) {
$default = $property->getDefault();
}
if ((null !== $default && is_scalar($default)) || (Type::TYPE_ARRAY === $property->getType()->getTypeHint($namespace) && \is_array($default))) {
$propertyStmt->default = $this->getDefaultAsExpr($default)->expr;
}
return new Stmt\Property(Stmt\Class_::MODIFIER_PROTECTED, [
$propertyStmt,
], [
'comments' => [$this->createPropertyDoc($property, $namespace, $required)],
]);
}
protected function createPropertyDoc(Property $property, $namespace, bool $required): Doc
{
$docTypeHint = $property->getType()->getDocTypeHint($namespace);
if (!$required && strpos($docTypeHint, 'null') === false) {
$docTypeHint .= '|null';
}
$description = sprintf(<<<EOD
/**
* %s
*
EOD
, $property->getDescription());
if ($property->isDeprecated()) {
$description .= <<<EOD
* @deprecated
*
EOD;
}
$description .= sprintf(<<<EOD
* @var %s
*/
EOD
, $docTypeHint);
return new Doc($description);
}
private function getDefaultAsExpr($value): Stmt\Expression
{
return $this->parser->parse('<?php ' . var_export($value, true) . ';')[0];
}
}