Skip to content

Commit

Permalink
feat(generation): add ClassManipulator (#531)
Browse files Browse the repository at this point in the history
  • Loading branch information
innocenzi authored Oct 4, 2024
1 parent 41d9009 commit 92ccb7d
Show file tree
Hide file tree
Showing 26 changed files with 749 additions and 0 deletions.
6 changes: 6 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
"laminas/laminas-diactoros": "^3.3",
"masterminds/html5": "^2.9",
"monolog/monolog": "^3.7.0",
"nette/php-generator": "^4.1.6",
"nikic/php-parser": "^5.3",
"nunomaduro/collision": "^8.4",
"php": "^8.3",
"php-http/discovery": "^1.19.2",
Expand Down Expand Up @@ -46,6 +48,7 @@
"phpstan/phpstan": "^1.10.0",
"phpunit/phpunit": "^11.3.5",
"rector/rector": "^1.2",
"spatie/phpunit-snapshot-assertions": "^5.1.6",
"spaze/phpstan-disallowed-calls": "^3.1",
"symplify/monorepo-builder": "^11.2"
},
Expand All @@ -60,6 +63,7 @@
"tempest/database": "self.version",
"tempest/debug": "self.version",
"tempest/event-bus": "self.version",
"tempest/generation": "self.version",
"tempest/http": "self.version",
"tempest/http-client": "self.version",
"tempest/log": "self.version",
Expand All @@ -83,6 +87,7 @@
"Tempest\\Debug\\": "src/Tempest/Debug/src",
"Tempest\\EventBus\\": "src/Tempest/EventBus/src",
"Tempest\\Framework\\": "src/Tempest/Framework",
"Tempest\\Generation\\": "src/Tempest/Generation/src",
"Tempest\\HttpClient\\": "src/Tempest/HttpClient/src",
"Tempest\\Http\\": "src/Tempest/Http/src",
"Tempest\\Log\\": "src/Tempest/Log/src",
Expand Down Expand Up @@ -115,6 +120,7 @@
"Tempest\\Core\\Tests\\": "src/Tempest/Core/tests",
"Tempest\\Database\\Tests\\": "src/Tempest/Database/tests",
"Tempest\\EventBus\\Tests\\": "src/Tempest/EventBus/tests",
"Tempest\\Generation\\Tests\\": "src/Tempest/Generation/tests",
"Tempest\\HttpClient\\Tests\\": "src/Tempest/HttpClient/tests",
"Tempest\\Http\\Tests\\": "src/Tempest/Http/tests",
"Tempest\\Log\\Tests\\": "src/Tempest/Log/tests",
Expand Down
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ parameters:
-
message: '#.*[Rr]eadonly.*#'
path: src/Tempest/Core/src/Composer.php
-
message: '#.*final#'
path: src/Tempest/Generation/tests/TestCase.php
-
message: '#.*#'
path: src/Tempest/Http/Exceptions/HttpExceptionHandler.php
Expand Down
10 changes: 10 additions & 0 deletions src/Tempest/Generation/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Exclude build/test files from the release
.github/ export-ignore
tests/ export-ignore
.gitattributes export-ignore
.gitignore export-ignore
phpunit.xml export-ignore
README.md export-ignore

# Configure diff output for .php and .phar files.
*.php diff=php
9 changes: 9 additions & 0 deletions src/Tempest/Generation/LICENCE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
The MIT License (MIT)

Copyright (c) 2024 Brent Roose [email protected]

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:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

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.
24 changes: 24 additions & 0 deletions src/Tempest/Generation/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "tempest/generation",
"description": "A component for generating PHP.",
"license": "MIT",
"minimum-stability": "dev",
"require": {
"php": "^8.3",
"nette/php-generator": "^4.1.6",
"nikic/php-parser": "^5.3"
},
"autoload": {
"psr-4": {
"Tempest\\Generation\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Tempest\\Generation\\Tests\\": "tests"
}
},
"require-dev": {
"spatie/phpunit-snapshot-assertions": "^5.1.6"
}
}
13 changes: 13 additions & 0 deletions src/Tempest/Generation/phpunit.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<testsuites>
<testsuite name="Tempest Generation">
<directory>tests</directory>
</testsuite>
</testsuites>
<source restrictNotices="true" restrictWarnings="true" ignoreIndirectDeprecations="true">
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
175 changes: 175 additions & 0 deletions src/Tempest/Generation/src/ClassManipulator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
<?php

declare(strict_types=1);

namespace Tempest\Generation;

use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\PhpFile;
use Nette\PhpGenerator\PsrPrinter;
use ReflectionClass;

final class ClassManipulator
{
private ClassType $classType;

private PhpFile $file;

private string $namespace;

private bool $simplifyImplements = false;

private array $aliases = [];

public function __construct(string|ReflectionClass $className)
{
$reflection = is_string($className)
? new ReflectionClass($className)
: $className;

$this->file = new PhpFile();
$this->classType = ClassType::from($reflection->getName(), withBodies: true); // @phpstan-ignore-line
$this->namespace = $reflection->getNamespaceName();
}

public function removeClassAttribute(string $attributeName): self
{
$attributes = $this->classType->getAttributes();

foreach ($attributes as $key => $attribute) {
if ($attribute->getName() === $attributeName) {
unset($attributes[$key]);
}
}

$this->classType->setAttributes($attributes);

return $this;
}

public function setFinal(bool $final = true): self
{
$this->classType->setFinal($final);

return $this;
}

public function setReadOnly(bool $readonly = true): self
{
$this->classType->setReadOnly($readonly);

return $this;
}

public function setStrictTypes(bool $strictTypes = true): self
{
$this->file->setStrictTypes($strictTypes);

return $this;
}

public function updateNamespace(string $namespace): self
{
$this->namespace = $namespace;

return $this;
}

public function print(): string
{
$printer = new PsrPrinter();

$file = clone $this->file;
$namespace = $file->addNamespace($this->namespace);
$namespace->add($this->classType);

$this->simplifyClassNames($file);

return $printer->printFile($file);
}

public function simplifyImplements(): self
{
$this->simplifyImplements = true;

return $this;
}

public function setAlias(string $class, string $alias): self
{
if (isset($this->aliases[$class])) {
unset($this->aliases[$class]);
}

$this->aliases[$class] = $alias;

return $this;
}

private function simplifyClassNames(PhpFile $file): PhpFile
{
foreach ($file->getNamespaces() as $namespace) {
foreach ($namespace->getClasses() as $class) {
$types = [];

if ($this->simplifyImplements) {
foreach ($class->getImplements() as $implement) {
$types[] = $implement;
}
}

foreach ($class->getAttributes() as $attribute) {
$types[] = $attribute->getName();
}

foreach ($class->getMethods() as $method) {
$types[] = $method->getReturnType(true);

array_map(function ($param) use (&$types): void {
$types[] = $param->getType(true);
}, $method->getParameters());

$methodBody = $method->getBody();
$fqcnMatches = $this->extractFqcnFromBody($methodBody);

foreach (array_filter($fqcnMatches) as $fqcn) {
$namespace->addUse($fqcn);
}
}

array_map(function ($param) use (&$types): void {
$types[] = $param->getType(true);
}, $class->getProperties());

foreach ($this->aliases as $class => $alias) {
$namespace->addUse($class, $alias);
}

foreach (array_filter($types) as $type) {
if (is_string($type)) {
$namespace->addUse($type);

continue;
}

foreach ($type->getTypes() as $subtype) {
if ($subtype->isClass() && ! $subtype->isClassKeyword()) {
$namespace->addUse((string) $subtype);
}
}
}
}
}

return $file;
}

private function extractFqcnFromBody(string $body): array
{
preg_match_all('/(?:\\\\?[A-Za-z_][\w\d_]*\\\\)+[A-Za-z_][\w\d_]*/', $body, $matches);

return array_filter(array_unique(
array_map(fn (string $fqcn) => rtrim(ltrim($fqcn, '\\'), ':'), $matches[0])
));
}
}
Loading

0 comments on commit 92ccb7d

Please sign in to comment.