Skip to content

Commit a2e6a0c

Browse files
committed
refactoring & fixes
1 parent 1170323 commit a2e6a0c

File tree

9 files changed

+97
-107
lines changed

9 files changed

+97
-107
lines changed

src/PhpGenerator/ClassType.php

Lines changed: 19 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,8 @@ public static function enum(string $name): self
101101
*/
102102
public static function from($class, bool $withBodies = false, bool $materializeTraits = true): self
103103
{
104-
return (new Factory)->fromClassReflection(new \ReflectionClass($class), $withBodies, $materializeTraits);
104+
return (new Factory)
105+
->fromClassReflection(new \ReflectionClass($class), $withBodies, $materializeTraits);
105106
}
106107

107108

@@ -110,13 +111,15 @@ public static function from($class, bool $withBodies = false, bool $materializeT
110111
*/
111112
public static function withBodiesFrom($class): self
112113
{
113-
return (new Factory)->fromClassReflection(new \ReflectionClass($class), true);
114+
return (new Factory)
115+
->fromClassReflection(new \ReflectionClass($class), true);
114116
}
115117

116118

117119
public static function fromCode(string $code): self
118120
{
119-
return (new Factory)->fromClassCode($code);
121+
return (new Factory)
122+
->fromClassCode($code);
120123
}
121124

122125

@@ -321,10 +324,7 @@ public function addImplement(string $name): self
321324
/** @return static */
322325
public function removeImplement(string $name): self
323326
{
324-
$key = array_search($name, $this->implements, true);
325-
if ($key !== false) {
326-
unset($this->implements[$key]);
327-
}
327+
$this->implements = array_diff($this->implements, [$name]);
328328
return $this;
329329
}
330330

@@ -424,10 +424,10 @@ public function addMember($member): self
424424
public function setConstants(array $consts): self
425425
{
426426
$this->consts = [];
427-
foreach ($consts as $k => $v) {
428-
$const = $v instanceof Constant
429-
? $v
430-
: (new Constant($k))->setValue($v);
427+
foreach ($consts as $k => $const) {
428+
if (!$const instanceof Constant) {
429+
$const = (new Constant($k))->setValue($const)->setPublic();
430+
}
431431
$this->consts[$const->getName()] = $const;
432432
}
433433
return $this;
@@ -443,7 +443,9 @@ public function getConstants(): array
443443

444444
public function addConstant(string $name, $value): Constant
445445
{
446-
return $this->consts[$name] = (new Constant($name))->setValue($value)->setPublic();
446+
return $this->consts[$name] = (new Constant($name))
447+
->setValue($value)
448+
->setPublic();
447449
}
448450

449451

@@ -457,7 +459,7 @@ public function removeConstant(string $name): self
457459

458460
/**
459461
* Sets cases to enum
460-
* @param EnumCase[] $consts
462+
* @param EnumCase[] $cases
461463
* @return static
462464
*/
463465
public function setCases(array $cases): self
@@ -481,7 +483,8 @@ public function getCases(): array
481483
/** Adds case to enum */
482484
public function addCase(string $name, $value = null): EnumCase
483485
{
484-
return $this->cases[$name] = (new EnumCase($name))->setValue($value);
486+
return $this->cases[$name] = (new EnumCase($name))
487+
->setValue($value);
485488
}
486489

487490

@@ -499,11 +502,9 @@ public function removeCase(string $name): self
499502
*/
500503
public function setProperties(array $props): self
501504
{
505+
(function (Property ...$props) {})(...$props);
502506
$this->properties = [];
503507
foreach ($props as $v) {
504-
if (!$v instanceof Property) {
505-
throw new Nette\InvalidArgumentException('Argument must be Nette\PhpGenerator\Property[].');
506-
}
507508
$this->properties[$v->getName()] = $v;
508509
}
509510
return $this;
@@ -560,11 +561,9 @@ public function hasProperty(string $name): bool
560561
*/
561562
public function setMethods(array $methods): self
562563
{
564+
(function (Method ...$methods) {})(...$methods);
563565
$this->methods = [];
564566
foreach ($methods as $v) {
565-
if (!$v instanceof Method) {
566-
throw new Nette\InvalidArgumentException('Argument must be Nette\PhpGenerator\Method[].');
567-
}
568567
$this->methods[$v->getName()] = $v;
569568
}
570569
return $this;

src/PhpGenerator/Dumper.php

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ private function dumpArray(array &$var, array $parents, int $level, int $column)
121121
}
122122

123123

124-
private function dumpObject(&$var, array $parents, int $level): string
124+
private function dumpObject($var, array $parents, int $level): string
125125
{
126126
if ($var instanceof \Serializable) {
127127
return 'unserialize(' . $this->dumpString(serialize($var)) . ')';
@@ -244,10 +244,9 @@ private function dumpArguments(array &$var, int $column, bool $named): string
244244

245245

246246
/**
247-
* @return object
248247
* @internal
249248
*/
250-
public static function createObject(string $class, array $props)
249+
public static function createObject(string $class, array $props): object
251250
{
252251
return unserialize('O' . substr(serialize($class), 1, -1) . substr(serialize($props), 1));
253252
}

src/PhpGenerator/EnumCase.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ final class EnumCase
2222
use Traits\CommentAware;
2323
use Traits\AttributeAware;
2424

25-
/** @var mixed */
25+
/** @var string|int|null */
2626
private $value;
2727

2828

src/PhpGenerator/Extractor.php

Lines changed: 37 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ public function extractMethodBodies(string $className): array
7676

7777
public function extractFunctionBody(string $name): ?string
7878
{
79+
/** @var Node\Stmt\Function_ $functionNode */
7980
$functionNode = (new NodeFinder)->findFirst($this->statements, function (Node $node) use ($name) {
8081
return $node instanceof Node\Stmt\Function_ && $node->namespacedName->toString() === $name;
8182
});
@@ -87,9 +88,8 @@ public function extractFunctionBody(string $name): ?string
8788
/** @param Node[] $statements */
8889
private function getReformattedBody(array $statements, int $level): string
8990
{
90-
$replacements = $this->prepareReplacements($statements);
9191
$body = $this->getNodeContents(...$statements);
92-
$body = $this->performReplacements($body, $replacements);
92+
$body = $this->performReplacements($body, $this->prepareReplacements($statements));
9393
return Helpers::unindent($body, $level);
9494
}
9595

@@ -98,55 +98,44 @@ private function prepareReplacements(array $statements): array
9898
{
9999
$start = $statements[0]->getStartFilePos();
100100
$replacements = [];
101-
$nodeFinder = new NodeFinder;
102-
103-
// name-nodes => resolved fully-qualified name
104-
foreach ($nodeFinder->findInstanceOf($statements, Node\Name\FullyQualified::class) as $node) {
105-
if ($node->hasAttribute('originalName')
106-
&& $node->getAttribute('originalName') instanceof Node\Name
107-
) {
108-
$replacements[] = [
109-
$node->getStartFilePos() - $start,
110-
$node->getEndFilePos() - $start,
111-
$node->toCodeString(),
112-
];
113-
}
114-
}
101+
(new NodeFinder)->find($statements, function (Node $node) use (&$replacements, $start) {
102+
if ($node instanceof Node\Name\FullyQualified) {
103+
if ($node->getAttribute('originalName') instanceof Node\Name) {
104+
$replacements[] = [
105+
$node->getStartFilePos() - $start,
106+
$node->getEndFilePos() - $start,
107+
$node->toCodeString(),
108+
];
109+
}
115110

116-
// multi-line strings => singleline
117-
foreach (array_merge(
118-
$nodeFinder->findInstanceOf($statements, Node\Scalar\String_::class),
119-
$nodeFinder->findInstanceOf($statements, Node\Scalar\EncapsedStringPart::class)
120-
) as $node) {
121-
/** @var Node\Scalar\String_|Node\Scalar\EncapsedStringPart $node */
122-
$token = $this->getNodeContents($node);
123-
if (strpos($token, "\n") !== false) {
124-
$quote = $node instanceof Node\Scalar\String_ ? '"' : '';
125-
$replacements[] = [
126-
$node->getStartFilePos() - $start,
127-
$node->getEndFilePos() - $start,
128-
$quote . addcslashes($node->value, "\x00..\x1F") . $quote,
129-
];
130-
}
131-
}
111+
} elseif ($node instanceof Node\Scalar\String_ || $node instanceof Node\Scalar\EncapsedStringPart) {
112+
// multi-line strings => singleline
113+
$token = $this->getNodeContents($node);
114+
if (strpos($token, "\n") !== false) {
115+
$quote = $node instanceof Node\Scalar\String_ ? '"' : '';
116+
$replacements[] = [
117+
$node->getStartFilePos() - $start,
118+
$node->getEndFilePos() - $start,
119+
$quote . addcslashes($node->value, "\x00..\x1F") . $quote,
120+
];
121+
}
132122

133-
// HEREDOC => "string"
134-
foreach ($nodeFinder->findInstanceOf($statements, Node\Scalar\Encapsed::class) as $node) {
135-
/** @var Node\Scalar\Encapsed $node */
136-
if ($node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC) {
137-
$replacements[] = [
138-
$node->getStartFilePos() - $start,
139-
$node->parts[0]->getStartFilePos() - $start - 1,
140-
'"',
141-
];
142-
$replacements[] = [
143-
end($node->parts)->getEndFilePos() - $start + 1,
144-
$node->getEndFilePos() - $start,
145-
'"',
146-
];
123+
} elseif ($node instanceof Node\Scalar\Encapsed) {
124+
// HEREDOC => "string"
125+
if ($node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC) {
126+
$replacements[] = [
127+
$node->getStartFilePos() - $start,
128+
$node->parts[0]->getStartFilePos() - $start - 1,
129+
'"',
130+
];
131+
$replacements[] = [
132+
end($node->parts)->getEndFilePos() - $start + 1,
133+
$node->getEndFilePos() - $start,
134+
'"',
135+
];
136+
}
147137
}
148-
}
149-
138+
});
150139
return $replacements;
151140
}
152141

src/PhpGenerator/Helpers.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public static function unformatDocComment(string $comment): string
9292
public static function unindent(string $s, int $level = 1): string
9393
{
9494
return $level
95-
? preg_replace('#^(\t|\ \ \ \ ){1,' . $level . '}#m', '', $s)
95+
? preg_replace('#^(\t| {4}){1,' . $level . '}#m', '', $s)
9696
: $s;
9797
}
9898

@@ -131,7 +131,7 @@ public static function tabsToSpaces(string $s, int $count = 4): string
131131

132132

133133
/** @internal */
134-
public static function createObject(string $class, array $props)
134+
public static function createObject(string $class, array $props): object
135135
{
136136
return Dumper::createObject($class, $props);
137137
}

src/PhpGenerator/PhpNamespace.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ public function addUse(string $name, string $alias = null, string &$aliasOut = n
114114

115115
} elseif (isset($this->uses[$alias]) && $this->uses[$alias] !== $name) {
116116
throw new InvalidStateException(
117-
"Alias '$alias' used already for '{$this->uses[$alias]}', cannot use for '{$name}'."
117+
"Alias '$alias' used already for '{$this->uses[$alias]}', cannot use for '$name'."
118118
);
119119
}
120120

src/PhpGenerator/Printer.php

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,12 @@ public function printMethod(Method $method, PhpNamespace $namespace = null): str
116116
. ($method->getReturnReference() ? '&' : '')
117117
. $method->getName();
118118
$returnType = $this->printReturnType($method);
119+
$params = $this->printParameters($method, strlen($line) + strlen($returnType) + strlen($this->indentation) + 2);
119120

120121
return Helpers::formatDocComment($method->getComment() . "\n")
121122
. self::printAttributes($method->getAttributes())
122123
. $line
123-
. ($params = $this->printParameters($method, strlen($line) + strlen($returnType) + strlen($this->indentation) + 2)) // 2 = parentheses
124+
. $params
124125
. $returnType
125126
. ($method->isAbstract() || $method->getBody() === null
126127
? ";\n"
@@ -144,7 +145,9 @@ public function printClass(ClassType $class, PhpNamespace $namespace = null): st
144145
$resolutions = $trait->getResolutions();
145146
$traits[] = Helpers::formatDocComment((string) $trait->getComment())
146147
. 'use ' . $resolver($trait->getName())
147-
. ($resolutions ? " {\n" . $this->indentation . implode(";\n" . $this->indentation, $resolutions) . ";\n}\n" : ";\n");
148+
. ($resolutions
149+
? " {\n" . $this->indentation . implode(";\n" . $this->indentation, $resolutions) . ";\n}\n"
150+
: ";\n");
148151
}
149152

150153
$cases = [];
@@ -185,7 +188,9 @@ public function printClass(ClassType $class, PhpNamespace $namespace = null): st
185188
$properties[] = Helpers::formatDocComment((string) $property->getComment())
186189
. self::printAttributes($property->getAttributes())
187190
. $def
188-
. ($property->getValue() === null && !$property->isInitialized() ? '' : ' = ' . $this->dump($property->getValue(), strlen($def) + 3)) // 3 = ' = '
191+
. ($property->getValue() === null && !$property->isInitialized()
192+
? ''
193+
: ' = ' . $this->dump($property->getValue(), strlen($def) + 3)) // 3 = ' = '
189194
. ";\n";
190195
}
191196

@@ -264,28 +269,6 @@ public function printFile(PhpFile $file): string
264269
}
265270

266271

267-
/** @return static */
268-
public function setTypeResolving(bool $state = true): self
269-
{
270-
$this->resolveTypes = $state;
271-
return $this;
272-
}
273-
274-
275-
protected function indent(string $s): string
276-
{
277-
$s = str_replace("\t", $this->indentation, $s);
278-
return Strings::indent($s, 1, $this->indentation);
279-
}
280-
281-
282-
protected function dump($var, int $column = 0): string
283-
{
284-
$this->dumper->indentation = $this->indentation;
285-
return $this->dumper->dump($var, $column);
286-
}
287-
288-
289272
protected function printUses(PhpNamespace $namespace): string
290273
{
291274
$name = $namespace->getName();
@@ -304,7 +287,7 @@ protected function printUses(PhpNamespace $namespace): string
304287
/**
305288
* @param Closure|GlobalFunction|Method $function
306289
*/
307-
public function printParameters($function, int $column = 0): string
290+
protected function printParameters($function, int $column = 0): string
308291
{
309292
$params = [];
310293
$list = $function->getParameters();
@@ -339,7 +322,7 @@ public function printParameters($function, int $column = 0): string
339322
}
340323

341324

342-
public function printType(?string $type, bool $nullable): string
325+
protected function printType(?string $type, bool $nullable): string
343326
{
344327
if ($type === null) {
345328
return '';
@@ -384,7 +367,29 @@ private function printAttributes(array $attrs, bool $inline = false): string
384367
}
385368

386369

387-
private function joinProperties(array $props)
370+
/** @return static */
371+
public function setTypeResolving(bool $state = true): self
372+
{
373+
$this->resolveTypes = $state;
374+
return $this;
375+
}
376+
377+
378+
protected function indent(string $s): string
379+
{
380+
$s = str_replace("\t", $this->indentation, $s);
381+
return Strings::indent($s, 1, $this->indentation);
382+
}
383+
384+
385+
protected function dump($var, int $column = 0): string
386+
{
387+
$this->dumper->indentation = $this->indentation;
388+
return $this->dumper->dump($var, $column);
389+
}
390+
391+
392+
private function joinProperties(array $props): string
388393
{
389394
return $this->linesBetweenProperties
390395
? implode(str_repeat("\n", $this->linesBetweenProperties), $props)

0 commit comments

Comments
 (0)