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

Attribute #70

Open
wants to merge 5 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
3 changes: 3 additions & 0 deletions artisan
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
<?php

use Illuminate\Foundation\PackageManifest;
use LaraStrict\Testing\Actions\GetDevBasePathForAssertsAction;
use LaraStrict\Testing\Actions\GetDevBasePathForStubs;
use LaraStrict\Testing\Actions\GetDevNamespaceForStubsAction;
use LaraStrict\Testing\Contracts\GetBasePathForAssertsActionContract;
use LaraStrict\Testing\Contracts\GetBasePathForStubsActionContract;
use LaraStrict\Testing\Contracts\GetNamespaceForStubsActionContract;

Expand Down Expand Up @@ -52,6 +54,7 @@ foreach ($packageManifest->providers() as $provider) {
$app->register(\LaraStrict\Core\LaraStrictServiceProvider::class);

$app->bind(GetBasePathForStubsActionContract::class, GetDevBasePathForStubs::class);
$app->bind(GetBasePathForAssertsActionContract::class, GetDevBasePathForAssertsAction::class);
$app->bind(GetNamespaceForStubsActionContract::class, GetDevNamespaceForStubsAction::class);

$status = $kernel->handle(
Expand Down
78 changes: 78 additions & 0 deletions src/Testing/Actions/ComposerAutoloadAbsoluteAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

declare(strict_types=1);

namespace LaraStrict\Testing\Actions;

use Exception;
use Illuminate\Filesystem\Filesystem;
use LaraStrict\Testing\Constants\ComposerConstants;
use LaraStrict\Testing\Contracts\GetBasePathForStubsActionContract;
use LaraStrict\Testing\Services\ComposerJsonDataService;

final class ComposerAutoloadAbsoluteAction
{
/**
* @var array<string, string>
*/
private array $dirs = [];

public function __construct(
private readonly ComposerJsonDataService $getComposerJsonDataAction,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

$getComposerJsonDataAction -> $composerJsonDataService

private readonly Filesystem $filesystem,
GetBasePathForStubsActionContract $getBasePathForStubsAction,
) {
$this->dirs = $this->prepareSourceDirs($getBasePathForStubsAction->execute());
}

/**
* @return array<string, string>
*/
public function execute(?string $path = null): array
{
if ($path !== null) {
$this->dirs += $this->loadNewComposer($path);
}

return $this->dirs;
}

/**
* @return array<string, string>
*/
private function prepareSourceDirs(string $basePath): array
{
$data = $this->getComposerJsonDataAction->data($basePath);
$dirs = [];

foreach ([ComposerConstants::AutoLoad, ComposerConstants::AutoLoadDev] as $section) {
if (isset($data[$section][ComposerConstants::Psr4]) === false || is_array($data[$section][ComposerConstants::Psr4]) === false) {
continue;
}

foreach ($data[$section][ComposerConstants::Psr4] as $ns => $path) {
$dirs[$ns] = $basePath . DIRECTORY_SEPARATOR . trim((string) $path, '\\/');
}
}

return $dirs;
}

/**
* @return array<string>
*/
private function loadNewComposer(string $path): array
{
if ($this->filesystem->isFile($path)) {
$path = $this->filesystem->dirname($path);
} elseif ($this->filesystem->isDirectory($path) === false) {
throw new Exception(sprintf('The path is not dir "%s".', $path));
}

while ($this->getComposerJsonDataAction->isExist($path) === false) {
$path = $this->filesystem->dirname($path);
}

return $this->prepareSourceDirs($path);
}
}
183 changes: 183 additions & 0 deletions src/Testing/Actions/ExpectationFileContentAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
<?php declare(strict_types=1);

namespace LaraStrict\Testing\Actions;

use LaraStrict\Testing\Constants\StubConstants;
use LaraStrict\Testing\Entities\PhpDocEntity;
use LaraStrict\Testing\Enums\PhpType;
use Nette\PhpGenerator\Literal;
use Nette\PhpGenerator\PhpFile;
use Nette\PhpGenerator\PromotedParameter;
use Nette\PhpGenerator\PsrPrinter;
use ReflectionIntersectionType;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionType;
use ReflectionUnionType;

final class ExpectationFileContentAction
{
public const HookProperty = '_hook';


public function execute(
PsrPrinter $printer,
string $namespace,
string $className,
ReflectionMethod $method,
PhpDocEntity $phpDoc,
): string
{
$parameters = $method->getParameters();

$file = new PhpFile();
$file->setStrictTypes();

$class = $file
->addNamespace($namespace)
->addClass($className);

$constructor = $class
->setFinal()
->addMethod('__construct');

$returnType = $method->getReturnType();
if ($returnType !== null &&
($returnType instanceof ReflectionNamedType === false || self::canReturnExpectation($returnType)) ||
$phpDoc->returnType === PhpType::Mixed) {
$constructorParameter = $constructor
->addPromotedParameter('return')
->setReadOnly();

$this->setParameterType($returnType, $constructorParameter);
}

$parameterTypes = [];
foreach ($parameters as $parameter) {
$constructorParameter = $constructor
->addPromotedParameter($parameter->name)
->setReadOnly();

$parameterTypes[] = $this->setParameterType($parameter->getType(), $constructorParameter);
$this->setParameterDefaultValue($parameter, $constructorParameter);
}
$parameterTypes[] = 'self';

$constructor
->addPromotedParameter(self::HookProperty)
->setReadOnly()
->setType('\Closure')
->setNullable()
->setDefaultValue(null);

$constructor->addComment(
sprintf('@param \Closure(%s):void|null $%s', implode(',', $parameterTypes), self::HookProperty)
);

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


private static function canReturnExpectation(ReflectionNamedType $returnType): bool
{
return $returnType->getName() !== PhpType::Void->value
&& $returnType->getName() !== PhpType::Self->value
&& $returnType->getName() !== PhpType::Static ->value;
}


private function setParameterType(
ReflectionType|ReflectionNamedType|ReflectionUnionType|ReflectionIntersectionType|null $type,
PromotedParameter $constructorParameter
): string
{
$proposedType = '';

$allowNull = false;
$mapToName = static function (ReflectionType $type) use (&$allowNull): ?string {
if ($type instanceof ReflectionNamedType) {
$name = $type->getName();
if ($name === 'null') {
$allowNull = false;
}

// Fix global namespace
if (class_exists($name)) {
return '\\' . $name;
}

return $name;
}

return null;
};

// TODO move to separate action and test with unit test
if ($type instanceof ReflectionNamedType) {
$allowNull = $type->allowsNull();
$proposedType = $type->getName();

if (class_exists($proposedType)) {
// Fix global namespace
$proposedType = '\\' . $proposedType;
}

$constructorParameter->setNullable($type->allowsNull());
} elseif ($type instanceof ReflectionUnionType) {
$allowNull = $type->allowsNull();
$proposedType = implode('|', array_filter(array_map($mapToName, $type->getTypes())));
} elseif ($type instanceof ReflectionIntersectionType) {
$allowNull = $type->allowsNull();
$proposedType = implode('&', array_filter(array_map($mapToName, $type->getTypes())));
}

if ($proposedType === '') {
$proposedType = 'mixed';
}

if ($allowNull) {
$constructorParameter->setNullable($allowNull);
}

// Callable not supported in property
if ($proposedType === 'callable') {
$proposedType = '\Closure';
}

$constructorParameter->setType($proposedType);

return $proposedType;
}


private function setParameterDefaultValue(
ReflectionParameter $parameter,
PromotedParameter $constructorParameter
): void
{
if ($parameter->isDefaultValueAvailable() === false) {
return;
}

if ($parameter->isDefaultValueConstant()) {
$constant = $parameter->getDefaultValueConstantName();
// Ensure that constants are from global scope
$constantLiteral = new Literal(StubConstants::NameSpaceSeparator . $constant);
$constructorParameter->setDefaultValue($constantLiteral);

return;
}

$defaultValue = $parameter->getDefaultValue();

if (is_object($defaultValue)) {
$objectLiteral = new Literal(
'new ' . StubConstants::NameSpaceSeparator . $defaultValue::class . '(/* unknown */)'
);
$constructorParameter->setDefaultValue($objectLiteral);
} else {
$constructorParameter->setDefaultValue($defaultValue);
}
}
}
86 changes: 86 additions & 0 deletions src/Testing/Actions/ExpectationMethodAssertAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php declare(strict_types=1);

namespace LaraStrict\Testing\Actions;

use LaraStrict\Testing\Entities\PhpDocEntity;
use LaraStrict\Testing\Enums\PhpType;
use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\Factory;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionUnionType;

final class ExpectationMethodAssertAction
{
/**
* Generates a method assert in assert class. Generates __construct if $expectationClassName is passed (requires
* extending AbstractExpectationCallsMap).
*/
public function execute(
ClassType $assertClass,
ReflectionMethod $method,
string $expectationClassName,
PhpDocEntity $phpDoc,
): void
{
$parameters = $method->getParameters();

$assertMethod = (new Factory())->fromMethodReflection($method);
$assertClass->addMember($assertMethod);

$assertMethod->addBody(sprintf(
'$_expectation = $this->getExpectation(%s);',
$expectationClassName . '::class'
));

$hookParameters = [];

if ($parameters !== []) {
$assertMethod->addBody('$_message = $this->getDebugMessage();');
$assertMethod->addBody('');

foreach ($parameters as $parameter) {
$hookParameters[] = sprintf('$%s', $parameter->name);
$assertMethod->addBody(sprintf(
'Assert::assertEquals($_expectation->%s, $%s, $_message);',
$parameter->name,
$parameter->name
));
}
}

$hookParameters[] = '$_expectation';

$assertMethod->addBody('');

$assertMethod->addBody(sprintf('if (is_callable($_expectation->%s)) {', ExpectationFileContentAction::HookProperty));
$assertMethod->addBody(sprintf(
' call_user_func($_expectation->%s, %s);',
ExpectationFileContentAction::HookProperty,
implode(', ', $hookParameters),
));
$assertMethod->addBody('}');

$returnType = $method->getReturnType();

if ($returnType instanceof ReflectionNamedType) {
$enumReturnType = PhpType::tryFrom($returnType->getName()) ?? PhpType::Mixed;
} elseif ($returnType instanceof ReflectionUnionType) {
$enumReturnType = PhpType::Mixed;
} else {
$enumReturnType = $phpDoc->returnType;
}

switch ($enumReturnType) {
case PhpType::Mixed:
$assertMethod->addBody('');
$assertMethod->addBody('return $_expectation->return;');
break;
case PhpType::Self:
case PhpType::Static:
$assertMethod->addBody('');
$assertMethod->addBody('return $this;');
break;
}
}
}
Loading
Loading