Skip to content

Commit 92ccb7d

Browse files
authored
feat(generation): add ClassManipulator (#531)
1 parent 41d9009 commit 92ccb7d

26 files changed

+749
-0
lines changed

composer.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@
1818
"laminas/laminas-diactoros": "^3.3",
1919
"masterminds/html5": "^2.9",
2020
"monolog/monolog": "^3.7.0",
21+
"nette/php-generator": "^4.1.6",
22+
"nikic/php-parser": "^5.3",
2123
"nunomaduro/collision": "^8.4",
2224
"php": "^8.3",
2325
"php-http/discovery": "^1.19.2",
@@ -46,6 +48,7 @@
4648
"phpstan/phpstan": "^1.10.0",
4749
"phpunit/phpunit": "^11.3.5",
4850
"rector/rector": "^1.2",
51+
"spatie/phpunit-snapshot-assertions": "^5.1.6",
4952
"spaze/phpstan-disallowed-calls": "^3.1",
5053
"symplify/monorepo-builder": "^11.2"
5154
},
@@ -60,6 +63,7 @@
6063
"tempest/database": "self.version",
6164
"tempest/debug": "self.version",
6265
"tempest/event-bus": "self.version",
66+
"tempest/generation": "self.version",
6367
"tempest/http": "self.version",
6468
"tempest/http-client": "self.version",
6569
"tempest/log": "self.version",
@@ -83,6 +87,7 @@
8387
"Tempest\\Debug\\": "src/Tempest/Debug/src",
8488
"Tempest\\EventBus\\": "src/Tempest/EventBus/src",
8589
"Tempest\\Framework\\": "src/Tempest/Framework",
90+
"Tempest\\Generation\\": "src/Tempest/Generation/src",
8691
"Tempest\\HttpClient\\": "src/Tempest/HttpClient/src",
8792
"Tempest\\Http\\": "src/Tempest/Http/src",
8893
"Tempest\\Log\\": "src/Tempest/Log/src",
@@ -115,6 +120,7 @@
115120
"Tempest\\Core\\Tests\\": "src/Tempest/Core/tests",
116121
"Tempest\\Database\\Tests\\": "src/Tempest/Database/tests",
117122
"Tempest\\EventBus\\Tests\\": "src/Tempest/EventBus/tests",
123+
"Tempest\\Generation\\Tests\\": "src/Tempest/Generation/tests",
118124
"Tempest\\HttpClient\\Tests\\": "src/Tempest/HttpClient/tests",
119125
"Tempest\\Http\\Tests\\": "src/Tempest/Http/tests",
120126
"Tempest\\Log\\Tests\\": "src/Tempest/Log/tests",

phpstan.neon.dist

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ parameters:
2121
-
2222
message: '#.*[Rr]eadonly.*#'
2323
path: src/Tempest/Core/src/Composer.php
24+
-
25+
message: '#.*final#'
26+
path: src/Tempest/Generation/tests/TestCase.php
2427
-
2528
message: '#.*#'
2629
path: src/Tempest/Http/Exceptions/HttpExceptionHandler.php
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Exclude build/test files from the release
2+
.github/ export-ignore
3+
tests/ export-ignore
4+
.gitattributes export-ignore
5+
.gitignore export-ignore
6+
phpunit.xml export-ignore
7+
README.md export-ignore
8+
9+
# Configure diff output for .php and .phar files.
10+
*.php diff=php

src/Tempest/Generation/LICENCE.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) 2024 Brent Roose [email protected]
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "tempest/generation",
3+
"description": "A component for generating PHP.",
4+
"license": "MIT",
5+
"minimum-stability": "dev",
6+
"require": {
7+
"php": "^8.3",
8+
"nette/php-generator": "^4.1.6",
9+
"nikic/php-parser": "^5.3"
10+
},
11+
"autoload": {
12+
"psr-4": {
13+
"Tempest\\Generation\\": "src"
14+
}
15+
},
16+
"autoload-dev": {
17+
"psr-4": {
18+
"Tempest\\Generation\\Tests\\": "tests"
19+
}
20+
},
21+
"require-dev": {
22+
"spatie/phpunit-snapshot-assertions": "^5.1.6"
23+
}
24+
}

src/Tempest/Generation/phpunit.xml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.4/phpunit.xsd" bootstrap="vendor/autoload.php" executionOrder="depends,defects" beStrictAboutOutputDuringTests="true" displayDetailsOnPhpunitDeprecations="true" failOnPhpunitDeprecation="false" failOnRisky="true" failOnWarning="true">
3+
<testsuites>
4+
<testsuite name="Tempest Generation">
5+
<directory>tests</directory>
6+
</testsuite>
7+
</testsuites>
8+
<source restrictNotices="true" restrictWarnings="true" ignoreIndirectDeprecations="true">
9+
<include>
10+
<directory>src</directory>
11+
</include>
12+
</source>
13+
</phpunit>
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace Tempest\Generation;
6+
7+
use Nette\PhpGenerator\ClassType;
8+
use Nette\PhpGenerator\PhpFile;
9+
use Nette\PhpGenerator\PsrPrinter;
10+
use ReflectionClass;
11+
12+
final class ClassManipulator
13+
{
14+
private ClassType $classType;
15+
16+
private PhpFile $file;
17+
18+
private string $namespace;
19+
20+
private bool $simplifyImplements = false;
21+
22+
private array $aliases = [];
23+
24+
public function __construct(string|ReflectionClass $className)
25+
{
26+
$reflection = is_string($className)
27+
? new ReflectionClass($className)
28+
: $className;
29+
30+
$this->file = new PhpFile();
31+
$this->classType = ClassType::from($reflection->getName(), withBodies: true); // @phpstan-ignore-line
32+
$this->namespace = $reflection->getNamespaceName();
33+
}
34+
35+
public function removeClassAttribute(string $attributeName): self
36+
{
37+
$attributes = $this->classType->getAttributes();
38+
39+
foreach ($attributes as $key => $attribute) {
40+
if ($attribute->getName() === $attributeName) {
41+
unset($attributes[$key]);
42+
}
43+
}
44+
45+
$this->classType->setAttributes($attributes);
46+
47+
return $this;
48+
}
49+
50+
public function setFinal(bool $final = true): self
51+
{
52+
$this->classType->setFinal($final);
53+
54+
return $this;
55+
}
56+
57+
public function setReadOnly(bool $readonly = true): self
58+
{
59+
$this->classType->setReadOnly($readonly);
60+
61+
return $this;
62+
}
63+
64+
public function setStrictTypes(bool $strictTypes = true): self
65+
{
66+
$this->file->setStrictTypes($strictTypes);
67+
68+
return $this;
69+
}
70+
71+
public function updateNamespace(string $namespace): self
72+
{
73+
$this->namespace = $namespace;
74+
75+
return $this;
76+
}
77+
78+
public function print(): string
79+
{
80+
$printer = new PsrPrinter();
81+
82+
$file = clone $this->file;
83+
$namespace = $file->addNamespace($this->namespace);
84+
$namespace->add($this->classType);
85+
86+
$this->simplifyClassNames($file);
87+
88+
return $printer->printFile($file);
89+
}
90+
91+
public function simplifyImplements(): self
92+
{
93+
$this->simplifyImplements = true;
94+
95+
return $this;
96+
}
97+
98+
public function setAlias(string $class, string $alias): self
99+
{
100+
if (isset($this->aliases[$class])) {
101+
unset($this->aliases[$class]);
102+
}
103+
104+
$this->aliases[$class] = $alias;
105+
106+
return $this;
107+
}
108+
109+
private function simplifyClassNames(PhpFile $file): PhpFile
110+
{
111+
foreach ($file->getNamespaces() as $namespace) {
112+
foreach ($namespace->getClasses() as $class) {
113+
$types = [];
114+
115+
if ($this->simplifyImplements) {
116+
foreach ($class->getImplements() as $implement) {
117+
$types[] = $implement;
118+
}
119+
}
120+
121+
foreach ($class->getAttributes() as $attribute) {
122+
$types[] = $attribute->getName();
123+
}
124+
125+
foreach ($class->getMethods() as $method) {
126+
$types[] = $method->getReturnType(true);
127+
128+
array_map(function ($param) use (&$types): void {
129+
$types[] = $param->getType(true);
130+
}, $method->getParameters());
131+
132+
$methodBody = $method->getBody();
133+
$fqcnMatches = $this->extractFqcnFromBody($methodBody);
134+
135+
foreach (array_filter($fqcnMatches) as $fqcn) {
136+
$namespace->addUse($fqcn);
137+
}
138+
}
139+
140+
array_map(function ($param) use (&$types): void {
141+
$types[] = $param->getType(true);
142+
}, $class->getProperties());
143+
144+
foreach ($this->aliases as $class => $alias) {
145+
$namespace->addUse($class, $alias);
146+
}
147+
148+
foreach (array_filter($types) as $type) {
149+
if (is_string($type)) {
150+
$namespace->addUse($type);
151+
152+
continue;
153+
}
154+
155+
foreach ($type->getTypes() as $subtype) {
156+
if ($subtype->isClass() && ! $subtype->isClassKeyword()) {
157+
$namespace->addUse((string) $subtype);
158+
}
159+
}
160+
}
161+
}
162+
}
163+
164+
return $file;
165+
}
166+
167+
private function extractFqcnFromBody(string $body): array
168+
{
169+
preg_match_all('/(?:\\\\?[A-Za-z_][\w\d_]*\\\\)+[A-Za-z_][\w\d_]*/', $body, $matches);
170+
171+
return array_filter(array_unique(
172+
array_map(fn (string $fqcn) => rtrim(ltrim($fqcn, '\\'), ':'), $matches[0])
173+
));
174+
}
175+
}

0 commit comments

Comments
 (0)