Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow architectures to be created from expressions #399

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 48 additions & 33 deletions .php-cs-fixer.dist.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,55 @@
->exclude('vendor/')
->notPath('tests/E2E/_fixtures/parse_error/Services/CartService.php');

$rules = [
'@Symfony' => true,
'@Symfony:risky' => true,
'@PHP71Migration:risky' => true,
'@PSR2' => true,
'@DoctrineAnnotation' => true,
'array_syntax' => ['syntax' => 'short'],
'fully_qualified_strict_types' => true, // Transforms imported FQCN parameters and return types in function arguments to short version.
'dir_constant' => true, // Replaces dirname(__FILE__) expression with equivalent __DIR__ constant.
'heredoc_to_nowdoc' => true,
'linebreak_after_opening_tag' => true, // Ensure there is no code on the same line as the PHP open tag.
'blank_line_after_opening_tag' => false,
'modernize_types_casting' => true, // Replaces intval, floatval, doubleval, strval and boolval function calls with according type casting operator.
'multiline_whitespace_before_semicolons' => true, // Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.
'no_unreachable_default_argument_value' => true, // In function arguments there must not be arguments with default values before non-default ones.
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],// To avoid problems of compatibility with the old php-cs-fixer version used on PHP 7.3
'no_useless_else' => true,
'no_useless_return' => true,
'ordered_class_elements' => true, // Orders the elements of classes/interfaces/traits.
'ordered_imports' => true,
'phpdoc_add_missing_param_annotation' => ['only_untyped' => false], // PHPDoc should contain @param for all params (for untyped parameters only).
'phpdoc_order' => true, // Annotations in PHPDoc should be ordered so that @param annotations come first, then @throws annotations, then @return annotations.
'declare_strict_types' => true,
'psr_autoloading' => true, // Class names should match the file name.
'no_php4_constructor' => true, // Convert PHP4-style constructors to __construct.
'semicolon_after_instruction' => true,
'align_multiline_comment' => true,
'general_phpdoc_annotation_remove' => ['annotations' => ['author', 'package']],
'list_syntax' => ['syntax' => 'short'],
'phpdoc_to_comment' => false,
'php_unit_method_casing' => ['case' => 'snake_case'],
'function_to_constant' => false,
'native_constant_invocation' =>[
'fix_built_in' => false,
'include' => [
'DIRECTORY_SEPARATOR',
'PHP_INT_SIZE',
'PHP_SAPI',
'PHP_VERSION_ID'
],
'scope' => 'namespaced',
'strict' => false
]
];
if (phpversion()[0] == '8') {
$rules['get_class_to_class_keyword'] = false; // if enabled, either if fails on PHP8, or it fails on PHP7
}

return (new PhpCsFixer\Config())
->setFinder($finder)
->setRiskyAllowed(true)
->setRules([
'@Symfony' => true,
'@Symfony:risky' => true,
'@PHP71Migration:risky' => true,
'@PSR2' => true,
'@DoctrineAnnotation' => true,
'array_syntax' => ['syntax' => 'short'],
'fully_qualified_strict_types' => true, // Transforms imported FQCN parameters and return types in function arguments to short version.
'dir_constant' => true, // Replaces dirname(__FILE__) expression with equivalent __DIR__ constant.
'heredoc_to_nowdoc' => true,
'linebreak_after_opening_tag' => true, // Ensure there is no code on the same line as the PHP open tag.
'blank_line_after_opening_tag' => false,
'modernize_types_casting' => true, // Replaces intval, floatval, doubleval, strval and boolval function calls with according type casting operator.
'multiline_whitespace_before_semicolons' => true, // Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.
'no_unreachable_default_argument_value' => true, // In function arguments there must not be arguments with default values before non-default ones.
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],// To avoid problems of compatibility with the old php-cs-fixer version used on PHP 7.3
'no_useless_else' => true,
'no_useless_return' => true,
'ordered_class_elements' => true, // Orders the elements of classes/interfaces/traits.
'ordered_imports' => true,
'phpdoc_add_missing_param_annotation' => ['only_untyped' => false], // PHPDoc should contain @param for all params (for untyped parameters only).
'phpdoc_order' => true, // Annotations in PHPDoc should be ordered so that @param annotations come first, then @throws annotations, then @return annotations.
'declare_strict_types' => true,
'psr_autoloading' => true, // Class names should match the file name.
'no_php4_constructor' => true, // Convert PHP4-style constructors to __construct.
'semicolon_after_instruction' => true,
'align_multiline_comment' => true,
'general_phpdoc_annotation_remove' => ['annotations' => ['author', 'package']],
'list_syntax' => ['syntax' => 'short'],
'phpdoc_to_comment' => false,
'php_unit_method_casing' => ['case' => 'snake_case'],
'function_to_constant' => false
]);
->setRules($rules);
56 changes: 56 additions & 0 deletions src/Expression/Boolean/Andx.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Arkitect\Expression\Boolean;

use Arkitect\Analyzer\ClassDescription;
use Arkitect\Expression\Description;
use Arkitect\Expression\Expression;
use Arkitect\Rules\Violation;
use Arkitect\Rules\ViolationMessage;
use Arkitect\Rules\Violations;

final class Andx implements Expression
{
/** @var Expression[] */
private $expressions;

public function __construct(Expression ...$expressions)
{
$this->expressions = $expressions;
}

public function describe(ClassDescription $theClass, string $because): Description
{
$expressionsDescriptions = [];
foreach ($this->expressions as $expression) {
$expressionsDescriptions[] = $expression->describe($theClass, '')->toString();
}

return new Description(
'all expressions must be true ('.implode(', ', $expressionsDescriptions).')',
$because
);
}

public function evaluate(ClassDescription $theClass, Violations $violations, string $because): void
{
foreach ($this->expressions as $expression) {
$newViolations = new Violations();
$expression->evaluate($theClass, $newViolations, $because);
if (0 !== $newViolations->count()) {
$violations->add(Violation::create(
$theClass->getFQCN(),
ViolationMessage::withDescription(
$this->describe($theClass, $because),
"The class '".$theClass->getFQCN()."' violated the expression "
.$expression->describe($theClass, '')->toString()
)
));

return;
}
}
}
}
42 changes: 42 additions & 0 deletions src/Expression/Boolean/Not.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace Arkitect\Expression\Boolean;

use Arkitect\Analyzer\ClassDescription;
use Arkitect\Expression\Description;
use Arkitect\Expression\Expression;
use Arkitect\Rules\Violation;
use Arkitect\Rules\ViolationMessage;
use Arkitect\Rules\Violations;

final class Not implements Expression
{
/** @var Expression */
private $expression;

public function __construct(Expression $expression)
{
$this->expression = $expression;
}

public function describe(ClassDescription $theClass, string $because): Description
{
return new Description('must NOT ('.$this->expression->describe($theClass, '')->toString().')', $because);
}

public function evaluate(ClassDescription $theClass, Violations $violations, string $because): void
{
$newViolations = new Violations();
$this->expression->evaluate($theClass, $newViolations, $because);
if (0 !== $newViolations->count()) {
return;
}

$violations->add(Violation::create(
$theClass->getFQCN(),
ViolationMessage::selfExplanatory($this->describe($theClass, $because))
));
}
}
155 changes: 155 additions & 0 deletions src/Expression/ForClasses/DependsOnlyOnTheseExpressions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
<?php

declare(strict_types=1);

namespace Arkitect\Expression\ForClasses;

use Arkitect\Analyzer\ClassDependency;
use Arkitect\Analyzer\ClassDescription;
use Arkitect\Analyzer\FileParser;
use Arkitect\Analyzer\FileParserFactory;
use Arkitect\Expression\Description;
use Arkitect\Expression\Expression;
use Arkitect\Expression\MergeableExpression;
use Arkitect\Rules\Violation;
use Arkitect\Rules\ViolationMessage;
use Arkitect\Rules\Violations;

class DependsOnlyOnTheseExpressions implements Expression
{
/** @var FileParser */
private $fileParser;

/** @var Expression[] */
private $expressions = [];

public function __construct(Expression ...$expressions)
{
$this->fileParser = FileParserFactory::createFileParser();
foreach ($expressions as $newExpression) {
$this->addExpression($newExpression);
}
}

public function describe(ClassDescription $theClass, string $because): Description
{
$expressionsDescriptions = '';
foreach ($this->expressions as $expression) {
$expressionsDescriptions .= $expression->describe($theClass, '')->toString()."\n";
}

return new Description(
"should depend only on classes in one of the given expressions: \n"
.$expressionsDescriptions,
$because
);
}

public function evaluate(ClassDescription $theClass, Violations $violations, string $because): void
{
$dependencies = $this->removeDuplicateDependencies($theClass->getDependencies());

foreach ($dependencies as $dependency) {
if (
'' === $dependency->getFQCN()->namespace()
|| $theClass->namespaceMatches($dependency->getFQCN()->namespace())
) {
continue;
}

$dependencyClassDescription = $this->getDependencyClassDescription($dependency);
if (null === $dependencyClassDescription) {
return;
}

if (!$this->matchesAnyOfTheExpressions($dependencyClassDescription)) {
$violations->add(
Violation::create(
$theClass->getFQCN(),
ViolationMessage::withDescription(
$this->describe($theClass, $because),
"The dependency '".$dependencyClassDescription->getFQCN()."' violated the expression: \n"
.$this->describeDependencyRequirement($dependencyClassDescription)."\n"
)
)
);
}
}
}

private function describeDependencyRequirement(ClassDescription $theDependency): string
{
$expressionsDescriptions = [];
foreach ($this->expressions as $expression) {
$expressionsDescriptions[] = $expression->describe($theDependency, '')->toString();
}

return implode("\nOR\n", array_unique($expressionsDescriptions));
}

private function matchesAnyOfTheExpressions(ClassDescription $dependencyClassDescription): bool
{
foreach ($this->expressions as $expression) {
$newViolations = new Violations();
$expression->evaluate($dependencyClassDescription, $newViolations, '');
if (0 === $newViolations->count()) {
return true;
}
}

return false;
}

/**
* @param ClassDependency $dependency
*/
private function getDependencyClassDescription($dependency): ?ClassDescription
{
/** @var class-string $dependencyFqcn */
$dependencyFqcn = $dependency->getFQCN()->toString();
$reflector = new \ReflectionClass($dependencyFqcn);
$filename = $reflector->getFileName();
if (false === $filename) {
return null;
}
$this->fileParser->parse(file_get_contents($filename), $filename);
$classDescriptionList = $this->fileParser->getClassDescriptions();

return array_pop($classDescriptionList);
}

/**
* @param ClassDependency[] $dependenciesList
*
* @return ClassDependency[]
*/
private function removeDuplicateDependencies(array $dependenciesList): array
{
$filteredList = [];
foreach ($dependenciesList as $classDependency) {
$dependencyFqcn = $classDependency->getFQCN()->toString();
if (\array_key_exists($dependencyFqcn, $filteredList)) {
continue;
}
$filteredList[$dependencyFqcn] = $classDependency;
}

return $filteredList;
}

private function addExpression(Expression $newExpression): void
{
foreach ($this->expressions as $index => $existingExpression) {
if (
$newExpression instanceof $existingExpression
&& $newExpression instanceof MergeableExpression
&& $existingExpression instanceof MergeableExpression
) {
$this->expressions[$index] = $existingExpression->mergeWith($newExpression);

return;
}
}
$this->expressions[] = $newExpression;
}
}
14 changes: 12 additions & 2 deletions src/Expression/ForClasses/ResideInOneOfTheseNamespaces.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@
use Arkitect\Analyzer\ClassDescription;
use Arkitect\Expression\Description;
use Arkitect\Expression\Expression;
use Arkitect\Expression\MergeableExpression;
use Arkitect\Rules\Violation;
use Arkitect\Rules\ViolationMessage;
use Arkitect\Rules\Violations;

class ResideInOneOfTheseNamespaces implements Expression
class ResideInOneOfTheseNamespaces implements Expression, MergeableExpression
{
/** @var string[] */
private $namespaces;

public function __construct(string ...$namespaces)
{
$this->namespaces = $namespaces;
$this->namespaces = array_unique($namespaces);
}

public function describe(ClassDescription $theClass, string $because): Description
Expand All @@ -45,4 +46,13 @@ public function evaluate(ClassDescription $theClass, Violations $violations, str
$violations->add($violation);
}
}

public function mergeWith(Expression $expression): Expression
{
if (!$expression instanceof self) {
throw new \InvalidArgumentException('Can not merge expressions. The given expression should be of type '.\get_class($this).' but is of type '.\get_class($expression));
}

return new self(...array_merge($this->namespaces, $expression->namespaces));
}
}
13 changes: 13 additions & 0 deletions src/Expression/MergeableExpression.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

declare(strict_types=1);

namespace Arkitect\Expression;

interface MergeableExpression
{
/**
* @throws \InvalidArgumentException when the given expression is not of the same type
*/
public function mergeWith(Expression $expression): Expression;
}
Loading