build: полная сборка в git — серверные PHP-зависимости lib/Vendor (438 файлов, из пиннированного релиза v22.0.12)
Type checking / changes (push) Has been cancelled
Type checking / test (push) Has been cancelled
Type checking / typescript-summary (push) Has been cancelled
Node tests / changes (push) Has been cancelled
Node tests / test (push) Has been cancelled
Node tests / test-summary (push) Has been cancelled

Теперь master f7_talk = ПОЛНЫЙ деплой-артефакт: built js (наша сборка) + lib/Vendor (серверные
PHP-deps) + патч Listener + version 22.0.12.1. Готов к брендингу dev-f7 и подписи dev-appstore.
Апстрим-подписи (appinfo/signature.json) в репо нет — переподпишет dev-appstore при публикации.
This commit is contained in:
2026-07-06 22:20:16 +00:00
parent 9dad445d11
commit 49dd055a58
439 changed files with 24952 additions and 0 deletions
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
/** @internal */
final class AttributeDefinition
{
public function __construct(
public readonly ClassDefinition $class,
/** @var list<mixed> */
public readonly array $arguments,
) {}
public function instantiate(): object
{
return new ($this->class->type->className())(...$this->arguments);
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use Countable;
use IteratorAggregate;
use Traversable;
use function array_filter;
use function count;
use function is_a;
/**
* @internal
*
* @implements IteratorAggregate<AttributeDefinition>
*/
final class Attributes implements IteratorAggregate, Countable
{
private static self $empty;
/** @var list<AttributeDefinition> */
private array $attributes;
/**
* @no-named-arguments
*/
public function __construct(AttributeDefinition ...$attributes)
{
$this->attributes = $attributes;
}
public static function empty(): self
{
return self::$empty ??= new self();
}
public function has(string $className): bool
{
foreach ($this->attributes as $attribute) {
if (is_a($attribute->class->type->className(), $className, true)) {
return true;
}
}
return false;
}
/**
* @param callable(AttributeDefinition): bool $callback
*/
public function filter(callable $callback): self
{
return new self(
...array_filter($this->attributes, $callback)
);
}
public function count(): int
{
return count($this->attributes);
}
/**
* @return list<AttributeDefinition>
*/
public function toArray(): array
{
return $this->attributes;
}
/**
* @return Traversable<AttributeDefinition>
*/
public function getIterator(): Traversable
{
yield from $this->attributes;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
/** @internal */
final class ClassDefinition
{
public function __construct(
/** @var class-string */
public readonly string $name,
public readonly ObjectType $type,
public readonly Attributes $attributes,
public readonly Properties $properties,
public readonly Methods $methods,
public readonly bool $isFinal,
public readonly bool $isAbstract,
) {}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use LogicException;
use function implode;
/** @internal */
final class ClassTypeAliasesDuplication extends LogicException
{
/**
* @param class-string $className
*/
public function __construct(string $className, string ...$names)
{
$names = implode('`, `', $names);
parent::__construct(
"The following type aliases already exist in class `$className`: `$names`.",
1638477604
);
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\InvalidType;
use ReflectionClass;
use RuntimeException;
/** @internal */
final class ExtendTagTypeError extends RuntimeException
{
/**
* @param ReflectionClass<object> $reflection
*/
public function __construct(ReflectionClass $reflection, InvalidType $previous)
{
parent::__construct(
"The `@extends` tag of the class `$reflection->name` is not valid: {$previous->getMessage()}",
1670193574,
$previous,
);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use ReflectionClass;
use RuntimeException;
/** @internal */
final class InvalidExtendTagClassName extends RuntimeException
{
/**
* @param ReflectionClass<object> $reflection
*/
public function __construct(ReflectionClass $reflection, Type $invalidExtendTag)
{
/** @var ReflectionClass<object> $parentClass */
$parentClass = $reflection->getParentClass();
parent::__construct(
"The `@extends` tag of the class `$reflection->name` has invalid class `{$invalidExtendTag->toString()}`, it should be `$parentClass->name`.",
1670183564,
);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use ReflectionClass;
use RuntimeException;
/** @internal */
final class InvalidExtendTagType extends RuntimeException
{
/**
* @param ReflectionClass<object> $reflection
*/
public function __construct(ReflectionClass $reflection, Type $invalidExtendTag)
{
/** @var ReflectionClass<object> $parentClass */
$parentClass = $reflection->getParentClass();
parent::__construct(
"The `@extends` tag of the class `$reflection->name` has invalid type `{$invalidExtendTag->toString()}`, it should be `{$parentClass->name}`.",
1670181134,
);
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use LogicException;
/** @internal */
final class InvalidTypeAliasImportClass extends LogicException
{
public function __construct(ObjectType $type, string $className)
{
parent::__construct(
"Cannot import a type alias from unknown class `$className` in class `{$type->className()}`.",
1638535486
);
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use LogicException;
/** @internal */
final class InvalidTypeAliasImportClassType extends LogicException
{
public function __construct(ObjectType $classType, Type $type)
{
parent::__construct(
"Importing a type alias can only be done with classes, `{$type->toString()}` was given in class `{$classType->className()}`.",
1638535608
);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use ReflectionClass;
use RuntimeException;
/** @internal */
final class SeveralExtendTagsFound extends RuntimeException
{
/**
* @param ReflectionClass<object> $reflection
*/
public function __construct(ReflectionClass $reflection)
{
parent::__construct(
"Only one `@extends` tag should be set for the class `$reflection->name`.",
1670195494,
);
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use LogicException;
/** @internal */
final class UnknownTypeAliasImport extends LogicException
{
/**
* @param class-string $importClassName
*/
public function __construct(ObjectType $type, string $importClassName, string $alias)
{
parent::__construct(
"Type alias `$alias` imported in `{$type->className()}` could not be found in `$importClassName`",
1638535757
);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
/** @internal */
final class FunctionDefinition
{
public function __construct(
/** @var non-empty-string */
public readonly string $name,
/** @var non-empty-string */
public readonly string $signature,
public readonly Attributes $attributes,
/** @var non-empty-string|null */
public readonly ?string $fileName,
/** @var class-string|null */
public readonly ?string $class,
public readonly bool $isStatic,
public readonly bool $isClosure,
public readonly Parameters $parameters,
public readonly Type $returnType
) {}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
/** @internal */
final class FunctionObject
{
public readonly FunctionDefinition $definition;
/** @var callable */
public readonly mixed $callback;
public function __construct(FunctionDefinition $definition, callable $callback)
{
$this->definition = $definition;
$this->callback = $callback;
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use Countable;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\FunctionDefinitionRepository;
use IteratorAggregate;
use Traversable;
use function array_keys;
use function count;
/**
* @internal
*
* @implements IteratorAggregate<string|int, FunctionObject>
*/
final class FunctionsContainer implements IteratorAggregate, Countable
{
/** @var array<FunctionObject> */
private array $functions = [];
public function __construct(
private FunctionDefinitionRepository $functionDefinitionRepository,
/** @var array<callable> */
private array $callables
) {}
public function has(string|int $key): bool
{
return isset($this->callables[$key]);
}
public function get(string|int $key): FunctionObject
{
return $this->function($key);
}
public function getIterator(): Traversable
{
foreach (array_keys($this->callables) as $key) {
yield $key => $this->function($key);
}
}
private function function(string|int $key): FunctionObject
{
return $this->functions[$key] ??= new FunctionObject(
$this->functionDefinitionRepository->for($this->callables[$key]),
$this->callables[$key]
);
}
public function count(): int
{
return count($this->callables);
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
/** @internal */
final class MethodDefinition
{
public function __construct(
/** @var non-empty-string */
public readonly string $name,
/** @var non-empty-string */
public readonly string $signature,
public readonly Attributes $attributes,
public readonly Parameters $parameters,
public readonly bool $isStatic,
public readonly bool $isPublic,
public readonly Type $returnType
) {}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* @internal
*
* @implements IteratorAggregate<string, MethodDefinition>
*/
final class Methods implements IteratorAggregate, Countable
{
/** @var MethodDefinition[] */
private array $methods = [];
public function __construct(MethodDefinition ...$methods)
{
foreach ($methods as $method) {
$this->methods[$method->name] = $method;
}
}
public function has(string $name): bool
{
return isset($this->methods[$name]);
}
public function get(string $name): MethodDefinition
{
return $this->methods[$name];
}
public function hasConstructor(): bool
{
return $this->has('__construct');
}
public function constructor(): MethodDefinition
{
return $this->get('__construct');
}
public function count(): int
{
return count($this->methods);
}
/**
* @return Traversable<string, MethodDefinition>
*/
public function getIterator(): Traversable
{
yield from $this->methods;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
/** @internal */
final class ParameterDefinition
{
public function __construct(
/** @var non-empty-string */
public readonly string $name,
/** @var non-empty-string */
public readonly string $signature,
public readonly Type $type,
public readonly Type $nativeType,
public readonly bool $isOptional,
public readonly bool $isVariadic,
public readonly mixed $defaultValue,
public readonly Attributes $attributes
) {}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use Countable;
use IteratorAggregate;
use Traversable;
use function array_values;
/**
* @internal
*
* @implements IteratorAggregate<string, ParameterDefinition>
*/
final class Parameters implements IteratorAggregate, Countable
{
/** @var ParameterDefinition[] */
private array $parameters = [];
public function __construct(ParameterDefinition ...$parameters)
{
foreach ($parameters as $parameter) {
$this->parameters[$parameter->name] = $parameter;
}
}
public function has(string $name): bool
{
return isset($this->parameters[$name]);
}
public function get(string $name): ParameterDefinition
{
return $this->parameters[$name];
}
/**
* @param int<0, max> $index
*/
public function at(int $index): ParameterDefinition
{
return array_values($this->parameters)[$index];
}
/**
* @return list<ParameterDefinition>
*/
public function toList(): array
{
return array_values($this->parameters);
}
public function count(): int
{
return count($this->parameters);
}
/**
* @return Traversable<string, ParameterDefinition>
*/
public function getIterator(): Traversable
{
yield from $this->parameters;
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* @internal
*
* @implements IteratorAggregate<string, PropertyDefinition>
*/
final class Properties implements IteratorAggregate, Countable
{
/** @var PropertyDefinition[] */
private array $properties = [];
public function __construct(PropertyDefinition ...$properties)
{
foreach ($properties as $property) {
$this->properties[$property->name] = $property;
}
}
public function has(string $name): bool
{
return isset($this->properties[$name]);
}
public function get(string $name): PropertyDefinition
{
return $this->properties[$name];
}
public function count(): int
{
return count($this->properties);
}
/**
* @return Traversable<string, PropertyDefinition>
*/
public function getIterator(): Traversable
{
yield from $this->properties;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
/** @internal */
final class PropertyDefinition
{
public function __construct(
/** @var non-empty-string */
public readonly string $name,
/** @var non-empty-string */
public readonly string $signature,
public readonly Type $type,
public readonly Type $nativeType,
public readonly bool $hasDefaultValue,
public readonly mixed $defaultValue,
public readonly bool $isPublic,
public readonly Attributes $attributes
) {}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\AttributeDefinition;
use ReflectionClass;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionParameter;
use ReflectionProperty;
use Reflector;
/** @internal */
interface AttributesRepository
{
/**
* @param ReflectionClass<object>|ReflectionProperty|ReflectionMethod|ReflectionFunction|ReflectionParameter $reflection
* @return list<AttributeDefinition>
*/
public function for(Reflector $reflection): array;
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ClassDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\ClassDefinitionRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\Psr\SimpleCache\CacheInterface;
/** @internal */
final class CacheClassDefinitionRepository implements ClassDefinitionRepository
{
public function __construct(
private ClassDefinitionRepository $delegate,
/** @var CacheInterface<ClassDefinition> */
private CacheInterface $cache
) {}
public function for(ObjectType $type): ClassDefinition
{
// @infection-ignore-all
$key = "class-definition-\0" . $type->toString();
$entry = $this->cache->get($key);
if ($entry) {
return $entry;
}
$class = $this->delegate->for($type);
$this->cache->set($key, $class);
return $class;
}
}
@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\FunctionDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\FunctionDefinitionRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use OCA\Talk\Vendor\Psr\SimpleCache\CacheInterface;
/** @internal */
final class CacheFunctionDefinitionRepository implements FunctionDefinitionRepository
{
public function __construct(
private FunctionDefinitionRepository $delegate,
/** @var CacheInterface<FunctionDefinition> */
private CacheInterface $cache
) {}
public function for(callable $function): FunctionDefinition
{
$reflection = Reflection::function($function);
// @infection-ignore-all
$key = "function-definition-\0" . $reflection->getFileName() . ':' . $reflection->getStartLine() . '-' . $reflection->getEndLine();
$entry = $this->cache->get($key);
if ($entry) {
return $entry;
}
$definition = $this->delegate->for($function);
$this->cache->set($key, $definition);
return $definition;
}
}
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use function array_map;
use function count;
use function implode;
use function is_array;
use function is_object;
use function var_export;
/** @internal */
final class AttributesCompiler
{
public function __construct(private ClassDefinitionCompiler $classDefinitionCompiler) {}
public function compile(Attributes $attributes): string
{
if (count($attributes) === 0) {
return Attributes::class . '::empty()';
}
$attributesListCode = $this->compileAttributes($attributes);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes($attributesListCode)
PHP;
}
private function compileAttributes(Attributes $attributes): string
{
$attributesListCode = [];
foreach ($attributes as $attribute) {
$class = $this->classDefinitionCompiler->compile($attribute->class);
if ($attribute->arguments === []) {
$arguments = '';
} else {
$arguments = implode(', ', array_map(
fn (mixed $argument) => $this->compileAttributeArguments($argument),
$attribute->arguments,
));
}
$attributesListCode[] = <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\AttributeDefinition(
$class,
[$arguments],
)
PHP;
}
return implode(', ', $attributesListCode);
}
private function compileAttributeArguments(mixed $value): string
{
if (is_object($value)) {
return 'unserialize(' . var_export(serialize($value), true) . ')';
}
if (is_array($value)) {
$parts = [];
foreach ($value as $key => $subValue) {
$parts[] = var_export($key, true) . ' => ' . $this->compileAttributeArguments($subValue);
}
return '[' . implode(', ', $parts) . ']';
}
return var_export($value, true);
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ClassDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\MethodDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\PropertyDefinition;
use function array_map;
use function assert;
use function implode;
use function iterator_to_array;
use function var_export;
/** @internal */
final class ClassDefinitionCompiler
{
private TypeCompiler $typeCompiler;
private AttributesCompiler $attributesCompiler;
private MethodDefinitionCompiler $methodCompiler;
private PropertyDefinitionCompiler $propertyCompiler;
public function __construct()
{
$this->typeCompiler = new TypeCompiler();
$this->attributesCompiler = new AttributesCompiler($this);
$this->methodCompiler = new MethodDefinitionCompiler($this->typeCompiler, $this->attributesCompiler);
$this->propertyCompiler = new PropertyDefinitionCompiler($this->typeCompiler, $this->attributesCompiler);
}
public function compile(mixed $value): string
{
assert($value instanceof ClassDefinition);
$name = var_export($value->name, true);
$type = $this->typeCompiler->compile($value->type);
$properties = array_map(
fn (PropertyDefinition $property) => $this->propertyCompiler->compile($property),
iterator_to_array($value->properties)
);
$properties = implode(', ', $properties);
$methods = array_map(
fn (MethodDefinition $method) => $this->methodCompiler->compile($method),
iterator_to_array($value->methods)
);
$methods = implode(', ', $methods);
$attributes = $this->attributesCompiler->compile($value->attributes);
$isFinal = var_export($value->isFinal, true);
$isAbstract = var_export($value->isAbstract, true);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\ClassDefinition(
$name,
$type,
$attributes,
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\Properties($properties),
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\Methods($methods),
$isFinal,
$isAbstract,
)
PHP;
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler\Exception;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use LogicException;
/** @internal */
final class TypeCannotBeCompiled extends LogicException
{
public function __construct(Type $type)
{
$class = $type::class;
parent::__construct(
"The type `$class` cannot be compiled.",
1616926126
);
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\FunctionDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ParameterDefinition;
use function var_export;
/** @internal */
final class FunctionDefinitionCompiler
{
private TypeCompiler $typeCompiler;
private AttributesCompiler $attributesCompiler;
private ParameterDefinitionCompiler $parameterCompiler;
public function __construct()
{
$this->typeCompiler = new TypeCompiler();
$this->attributesCompiler = new AttributesCompiler(new ClassDefinitionCompiler());
$this->parameterCompiler = new ParameterDefinitionCompiler($this->typeCompiler, $this->attributesCompiler);
}
public function compile(mixed $value): string
{
assert($value instanceof FunctionDefinition);
$parameters = array_map(
fn (ParameterDefinition $parameter) => $this->parameterCompiler->compile($parameter),
iterator_to_array($value->parameters)
);
$attributes = $this->attributesCompiler->compile($value->attributes);
$fileName = var_export($value->fileName, true);
$class = var_export($value->class, true);
$isStatic = var_export($value->isStatic, true);
$isClosure = var_export($value->isClosure, true);
$parameters = implode(', ', $parameters);
$returnType = $this->typeCompiler->compile($value->returnType);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\FunctionDefinition(
'{$value->name}',
'{$value->signature}',
$attributes,
$fileName,
$class,
$isStatic,
$isClosure,
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\Parameters($parameters),
$returnType
)
PHP;
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\MethodDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ParameterDefinition;
use function var_export;
/** @internal */
final class MethodDefinitionCompiler
{
private TypeCompiler $typeCompiler;
private AttributesCompiler $attributesCompiler;
private ParameterDefinitionCompiler $parameterCompiler;
public function __construct(TypeCompiler $typeCompiler, AttributesCompiler $attributesCompiler)
{
$this->typeCompiler = $typeCompiler;
$this->attributesCompiler = $attributesCompiler;
$this->parameterCompiler = new ParameterDefinitionCompiler($typeCompiler, $attributesCompiler);
}
public function compile(MethodDefinition $method): string
{
$attributes = $this->attributesCompiler->compile($method->attributes);
$parameters = array_map(
fn (ParameterDefinition $parameter) => $this->parameterCompiler->compile($parameter),
iterator_to_array($method->parameters)
);
$parameters = implode(', ', $parameters);
$isStatic = var_export($method->isStatic, true);
$isPublic = var_export($method->isPublic, true);
$returnType = $this->typeCompiler->compile($method->returnType);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\MethodDefinition(
'{$method->name}',
'{$method->signature}',
$attributes,
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\Parameters($parameters),
$isStatic,
$isPublic,
$returnType
)
PHP;
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ParameterDefinition;
/** @internal */
final class ParameterDefinitionCompiler
{
public function __construct(
private TypeCompiler $typeCompiler,
private AttributesCompiler $attributesCompiler
) {}
public function compile(ParameterDefinition $parameter): string
{
$isOptional = var_export($parameter->isOptional, true);
$isVariadic = var_export($parameter->isVariadic, true);
$defaultValue = $this->defaultValue($parameter);
$type = $this->typeCompiler->compile($parameter->type);
$nativeType = $this->typeCompiler->compile($parameter->nativeType);
$attributes = $this->attributesCompiler->compile($parameter->attributes);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\ParameterDefinition(
'{$parameter->name}',
'{$parameter->signature}',
$type,
$nativeType,
$isOptional,
$isVariadic,
$defaultValue,
$attributes
)
PHP;
}
private function defaultValue(ParameterDefinition $parameter): string
{
$defaultValue = $parameter->defaultValue;
return is_object($defaultValue)
? 'unserialize(' . var_export(serialize($defaultValue), true) . ')'
: var_export($defaultValue, true);
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\PropertyDefinition;
/** @internal */
final class PropertyDefinitionCompiler
{
public function __construct(
private TypeCompiler $typeCompiler,
private AttributesCompiler $attributesCompiler
) {}
public function compile(PropertyDefinition $property): string
{
$type = $this->typeCompiler->compile($property->type);
$nativeType = $this->typeCompiler->compile($property->nativeType);
$hasDefaultValue = var_export($property->hasDefaultValue, true);
$defaultValue = var_export($property->defaultValue, true);
$isPublic = var_export($property->isPublic, true);
$attributes = $this->attributesCompiler->compile($property->attributes);
return <<<PHP
new \OCA\Talk\Vendor\CuyZ\Valinor\Definition\PropertyDefinition(
'{$property->name}',
'{$property->signature}',
$type,
$nativeType,
$hasDefaultValue,
$defaultValue,
$isPublic,
$attributes
)
PHP;
}
}
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Cache\Compiler\Exception\TypeCannotBeCompiled;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ArrayKeyType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ArrayType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\BooleanValueType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\CallableType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ClassStringType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\EnumType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\FloatValueType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\IntegerRangeType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\IntegerValueType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\InterfaceType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\IntersectionType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\IterableType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ListType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\MixedType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeBooleanType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeClassType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeFloatType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeIntegerType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeStringType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NegativeIntegerType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NonEmptyArrayType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NonEmptyListType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NonEmptyStringType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NonNegativeIntegerType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NonPositiveIntegerType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NullType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NumericStringType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\PositiveIntegerType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ScalarConcreteType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ShapedArrayElement;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ShapedArrayType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\StringValueType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UndefinedObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnionType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use UnitEnum;
use function array_keys;
use function array_map;
use function implode;
use function var_export;
/** @internal */
final class TypeCompiler
{
public function compile(Type $type): string
{
$class = $type::class;
switch (true) {
case $type instanceof NullType:
case $type instanceof NativeBooleanType:
case $type instanceof NativeFloatType:
case $type instanceof NativeIntegerType:
case $type instanceof PositiveIntegerType:
case $type instanceof NegativeIntegerType:
case $type instanceof NonPositiveIntegerType:
case $type instanceof NonNegativeIntegerType:
case $type instanceof NativeStringType:
case $type instanceof NonEmptyStringType:
case $type instanceof NumericStringType:
case $type instanceof UndefinedObjectType:
case $type instanceof CallableType:
case $type instanceof MixedType:
case $type instanceof ScalarConcreteType:
return "$class::get()";
case $type instanceof BooleanValueType:
return $type->value() === true
? "$class::true()"
: "$class::false()";
case $type instanceof IntegerRangeType:
return "new $class({$type->min()}, {$type->max()})";
case $type instanceof StringValueType:
$value = var_export($type->toString(), true);
return "$class::from($value)";
case $type instanceof IntegerValueType:
case $type instanceof FloatValueType:
$value = var_export($type->value(), true);
return "new $class($value)";
case $type instanceof IntersectionType:
case $type instanceof UnionType:
$subTypes = array_map(
fn (Type $subType) => $this->compile($subType),
$type->types()
);
return "new $class(" . implode(', ', $subTypes) . ')';
case $type instanceof ArrayKeyType:
return match ($type->toString()) {
'string' => "$class::string()",
'int' => "$class::integer()",
default => "$class::default()",
};
case $type instanceof ShapedArrayType:
$elements = implode(', ', array_map(
fn (ShapedArrayElement $element) => $this->compileArrayShapeElement($element),
$type->elements()
));
if ($type->hasUnsealedType()) {
$unsealedType = $this->compile($type->unsealedType());
return "$class::unsealed($unsealedType, $elements)";
} elseif ($type->isUnsealed()) {
return "$class::unsealedWithoutType($elements)";
}
return "new $class($elements)";
case $type instanceof ArrayType:
case $type instanceof NonEmptyArrayType:
if ($type->toString() === 'array' || $type->toString() === 'non-empty-array') {
return "$class::native()";
}
$keyType = $this->compile($type->keyType());
$subType = $this->compile($type->subType());
return "new $class($keyType, $subType)";
case $type instanceof ListType:
case $type instanceof NonEmptyListType:
if ($type->toString() === 'list' || $type->toString() === 'non-empty-list') {
return "$class::native()";
}
$subType = $this->compile($type->subType());
return "new $class($subType)";
case $type instanceof IterableType:
$keyType = $this->compile($type->keyType());
$subType = $this->compile($type->subType());
return "new $class($keyType, $subType)";
case $type instanceof NativeClassType:
case $type instanceof InterfaceType:
$generics = [];
foreach ($type->generics() as $key => $generic) {
$generics[] = var_export($key, true) . ' => ' . $this->compile($generic);
}
$generics = implode(', ', $generics);
return "new $class('{$type->className()}', [$generics])";
case $type instanceof ClassStringType:
if (null === $type->subType()) {
return "new $class()";
}
$subType = $this->compile($type->subType());
return "new $class($subType)";
case $type instanceof EnumType:
$enumName = var_export($type->className(), true);
$pattern = var_export($type->pattern(), true);
$cases = array_map(
fn (string|int $key, UnitEnum $case) => var_export($key, true) . ' => ' . var_export($case, true),
array_keys($type->cases()),
$type->cases()
);
$cases = implode(', ', $cases);
return "new $class($enumName, $pattern, [$cases])";
case $type instanceof UnresolvableType:
$raw = var_export($type->toString(), true);
$message = var_export($type->message(), true);
return "new $class($raw, $message)";
default:
throw new TypeCannotBeCompiled($type);
}
}
private function compileArrayShapeElement(ShapedArrayElement $element): string
{
$class = ShapedArrayElement::class;
$key = $this->compile($element->key());
$type = $this->compile($element->type());
$optional = var_export($element->isOptional(), true);
return "new $class($key, $type, $optional)";
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ClassDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
/** @internal */
interface ClassDefinitionRepository
{
public function for(ObjectType $type): ClassDefinition;
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\FunctionDefinition;
/** @internal */
interface FunctionDefinitionRepository
{
public function for(callable $function): FunctionDefinition;
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\AttributeDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\ClassDefinitionRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Normalizer\AsTransformer;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeClassType;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use Error;
use ReflectionAttribute;
use Reflector;
use function array_map;
use function array_values;
/** @internal */
final class ReflectionAttributesRepository implements AttributesRepository
{
public function __construct(
private ClassDefinitionRepository $classDefinitionRepository,
/** @var list<class-string> */
private array $allowedAttributes,
) {}
public function for(Reflector $reflection): array
{
$attributes = array_filter(
$reflection->getAttributes(),
function (ReflectionAttribute $attribute) {
foreach ($this->allowedAttributes as $allowedAttribute) {
if (is_a($attribute->getName(), $allowedAttribute, true)) {
return $this->attributeCanBeInstantiated($attribute);
}
}
$parentAttributes = Reflection::class($attribute->getName())->getAttributes(AsTransformer::class);
return $parentAttributes !== [];
},
);
return array_values(array_map(
fn (ReflectionAttribute $attribute) => new AttributeDefinition(
$this->classDefinitionRepository->for(new NativeClassType($attribute->getName())),
array_values($attribute->getArguments()),
),
$attributes,
));
}
/**
* @param ReflectionAttribute<object> $attribute
*/
private function attributeCanBeInstantiated(ReflectionAttribute $attribute): bool
{
try {
$attribute->newInstance();
return true;
} catch (Error) {
// Race condition when the attribute is affected to a property/parameter
// that was PROMOTED, in this case the attribute will be applied to both
// ParameterReflection AND PropertyReflection, BUT the target arg inside the attribute
// class is configured to support only ONE of them (parameter OR property)
// https://wiki.php.net/rfc/constructor_promotion#attributes for more details.
// Ignore attribute if the instantiation failed.
return false;
}
}
}
@@ -0,0 +1,177 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ClassDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\ClassTypeAliasesDuplication;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\MethodDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Methods;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Properties;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\PropertyDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\ClassDefinitionRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ClassImportedTypeAliasResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ClassLocalTypeAliasResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ClassParentTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ReflectionTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\GenericType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Factory\TypeParserFactory;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use ReflectionClass;
use ReflectionMethod;
use ReflectionProperty;
use function array_filter;
use function array_keys;
use function array_map;
/** @internal */
final class ReflectionClassDefinitionRepository implements ClassDefinitionRepository
{
private TypeParserFactory $typeParserFactory;
private AttributesRepository $attributesRepository;
private ReflectionPropertyDefinitionBuilder $propertyBuilder;
private ReflectionMethodDefinitionBuilder $methodBuilder;
/** @var array<string, ReflectionTypeResolver> */
private array $typeResolver = [];
/**
* @param list<class-string> $allowedAttributes
*/
public function __construct(
TypeParserFactory $typeParserFactory,
array $allowedAttributes,
) {
$this->typeParserFactory = $typeParserFactory;
$this->attributesRepository = new ReflectionAttributesRepository($this, $allowedAttributes);
$this->propertyBuilder = new ReflectionPropertyDefinitionBuilder($this->attributesRepository);
$this->methodBuilder = new ReflectionMethodDefinitionBuilder($this->attributesRepository);
}
public function for(ObjectType $type): ClassDefinition
{
$reflection = Reflection::class($type->className());
return new ClassDefinition(
$reflection->name,
$type,
new Attributes(...$this->attributesRepository->for($reflection)),
new Properties(...$this->properties($type)),
new Methods(...$this->methods($type)),
$reflection->isFinal(),
$reflection->isAbstract(),
);
}
/**
* @return list<PropertyDefinition>
*/
private function properties(ObjectType $type): array
{
$reflection = Reflection::class($type->className());
$properties = [];
foreach ($reflection->getProperties() as $property) {
$typeResolver = $this->typeResolver($type, $property->getDeclaringClass());
$properties[$property->name] = $this->propertyBuilder->for($property, $typeResolver);
}
// Properties will be sorted by inheritance order, from parent to child.
$sortedProperties = [];
while ($reflection) {
$currentProperties = array_map(
fn (ReflectionProperty $property) => $properties[$property->name],
array_filter(
$reflection->getProperties(),
fn (ReflectionProperty $property) => isset($properties[$property->name]),
),
);
$sortedProperties = [...$currentProperties, ...$sortedProperties];
$reflection = $reflection->getParentClass();
}
return $sortedProperties;
}
/**
* @return list<MethodDefinition>
*/
private function methods(ObjectType $type): array
{
$reflection = Reflection::class($type->className());
$methods = $reflection->getMethods();
// Because `ReflectionMethod::getMethods()` wont list the constructor if
// it comes from a parent class AND is not public, we need to manually
// fetch it and add it to the list.
if ($reflection->hasMethod('__construct')) {
$methods[] = $reflection->getMethod('__construct');
}
return array_map(function (ReflectionMethod $method) use ($type) {
$typeResolver = $this->typeResolver($type, $method->getDeclaringClass());
return $this->methodBuilder->for($method, $typeResolver);
}, $methods);
}
/**
* @param ReflectionClass<object> $target
*/
private function typeResolver(ObjectType $type, ReflectionClass $target): ReflectionTypeResolver
{
$typeKey = $target->isInterface()
? "{$type->toString()}/{$type->className()}"
: "{$type->toString()}/$target->name";
if (isset($this->typeResolver[$typeKey])) {
return $this->typeResolver[$typeKey];
}
$parentTypeResolver = new ClassParentTypeResolver($this->typeParserFactory);
while ($type->className() !== $target->name) {
$type = $parentTypeResolver->resolveParentTypeFor($type);
}
$localTypeAliasResolver = new ClassLocalTypeAliasResolver($this->typeParserFactory);
$importedTypeAliasResolver = new ClassImportedTypeAliasResolver($this->typeParserFactory);
$generics = $type instanceof GenericType ? $type->generics() : [];
$localAliases = $localTypeAliasResolver->resolveLocalTypeAliases($type);
$importedAliases = $importedTypeAliasResolver->resolveImportedTypeAliases($type);
$duplicates = [];
$keys = [...array_keys($generics), ...array_keys($localAliases), ...array_keys($importedAliases)];
foreach ($keys as $key) {
$sameKeys = array_filter($keys, fn ($value) => $value === $key);
if (count($sameKeys) > 1) {
$duplicates[$key] = null;
}
}
if (count($duplicates) > 0) {
throw new ClassTypeAliasesDuplication($type->className(), ...array_keys($duplicates));
}
$advancedParser = $this->typeParserFactory->buildAdvancedTypeParserForClass($type, $generics + $localAliases + $importedAliases);
$nativeParser = $this->typeParserFactory->buildNativeTypeParserForClass($type->className());
return $this->typeResolver[$typeKey] = new ReflectionTypeResolver($nativeParser, $advancedParser);
}
}
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\FunctionDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Parameters;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\FunctionDefinitionRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\FunctionReturnTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ReflectionTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Factory\TypeParserFactory;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use ReflectionFunction;
use ReflectionParameter;
use function array_map;
use function str_ends_with;
use function str_starts_with;
/** @internal */
final class ReflectionFunctionDefinitionRepository implements FunctionDefinitionRepository
{
private TypeParserFactory $typeParserFactory;
private AttributesRepository $attributesRepository;
private ReflectionParameterDefinitionBuilder $parameterBuilder;
public function __construct(TypeParserFactory $typeParserFactory, AttributesRepository $attributesRepository)
{
$this->typeParserFactory = $typeParserFactory;
$this->attributesRepository = $attributesRepository;
$this->parameterBuilder = new ReflectionParameterDefinitionBuilder($attributesRepository);
}
public function for(callable $function): FunctionDefinition
{
$reflection = Reflection::function($function);
$nativeParser = $this->typeParserFactory->buildNativeTypeParserForFunction($reflection);
$advancedParser = $this->typeParserFactory->buildAdvancedTypeParserForFunction($reflection);
$typeResolver = new ReflectionTypeResolver($nativeParser, $advancedParser);
$returnTypeResolver = new FunctionReturnTypeResolver($typeResolver);
$parameters = array_map(
fn (ReflectionParameter $parameter) => $this->parameterBuilder->for($parameter, $typeResolver),
$reflection->getParameters(),
);
$name = $reflection->getName();
$signature = $this->signature($reflection);
$class = $reflection->getClosureScopeClass();
$returnType = $returnTypeResolver->resolveReturnTypeFor($reflection);
$nativeReturnType = $returnTypeResolver->resolveNativeReturnTypeFor($reflection);
// PHP8.2 use `ReflectionFunction::isAnonymous()`
$isClosure = $name === '{closure}' || str_ends_with($name, '\\{closure}') || str_starts_with($name, '{closure:');
if ($returnType instanceof UnresolvableType) {
$returnType = $returnType->forFunctionReturnType($signature);
} elseif (! $returnType->matches($nativeReturnType)) {
$returnType = UnresolvableType::forNonMatchingFunctionReturnTypes($name, $nativeReturnType, $returnType);
}
return new FunctionDefinition(
$name,
$signature,
new Attributes(...$this->attributesRepository->for($reflection)),
$reflection->getFileName() ?: null,
$class?->name,
$reflection->getClosureThis() === null,
$isClosure,
new Parameters(...$parameters),
$returnType,
);
}
/**
* @return non-empty-string
*/
private function signature(ReflectionFunction $reflection): string
{
// PHP8.2 use `ReflectionFunction::isAnonymous()`
if ($reflection->name === '{closure}' || str_ends_with($reflection->name, '\\{closure}') || str_starts_with($reflection->name, '{closure:')) {
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();
return $startLine === $endLine
? "Closure (line $startLine of {$reflection->getFileName()})"
: "Closure (lines $startLine to $endLine of {$reflection->getFileName()})";
}
return $reflection->getClosureScopeClass()
? $reflection->getClosureScopeClass()->name . '::' . $reflection->name . '()'
: $reflection->name . '()';
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\MethodDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Parameters;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\FunctionReturnTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ReflectionTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use ReflectionMethod;
use ReflectionParameter;
use function array_map;
/** @internal */
final class ReflectionMethodDefinitionBuilder
{
private AttributesRepository $attributesRepository;
private ReflectionParameterDefinitionBuilder $parameterBuilder;
public function __construct(AttributesRepository $attributesRepository)
{
$this->attributesRepository = $attributesRepository;
$this->parameterBuilder = new ReflectionParameterDefinitionBuilder($attributesRepository);
}
public function for(ReflectionMethod $reflection, ReflectionTypeResolver $typeResolver): MethodDefinition
{
$name = $reflection->name;
$signature = $reflection->getDeclaringClass()->name . '::' . $reflection->name . '()';
$parameters = array_map(
fn (ReflectionParameter $parameter) => $this->parameterBuilder->for($parameter, $typeResolver),
$reflection->getParameters()
);
$returnTypeResolver = new FunctionReturnTypeResolver($typeResolver);
$returnType = $returnTypeResolver->resolveReturnTypeFor($reflection);
$nativeReturnType = $returnTypeResolver->resolveNativeReturnTypeFor($reflection);
if ($returnType instanceof UnresolvableType) {
$returnType = $returnType->forMethodReturnType($signature);
} elseif (! $returnType->matches($nativeReturnType)) {
$returnType = UnresolvableType::forNonMatchingMethodReturnTypes($name, $nativeReturnType, $returnType);
}
return new MethodDefinition(
$name,
$signature,
new Attributes(...$this->attributesRepository->for($reflection)),
new Parameters(...$parameters),
$reflection->isStatic(),
$reflection->isPublic(),
$returnType
);
}
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\ParameterDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ParameterTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ReflectionTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use ReflectionParameter;
/** @internal */
final class ReflectionParameterDefinitionBuilder
{
public function __construct(private AttributesRepository $attributesRepository) {}
public function for(ReflectionParameter $reflection, ReflectionTypeResolver $typeResolver): ParameterDefinition
{
$parameterTypeResolver = new ParameterTypeResolver($typeResolver);
/** @var non-empty-string $name */
$name = $reflection->name;
$signature = $this->signature($reflection);
$type = $parameterTypeResolver->resolveTypeFor($reflection);
$nativeType = $parameterTypeResolver->resolveNativeTypeFor($reflection);
$isOptional = $reflection->isOptional();
$isVariadic = $reflection->isVariadic();
if ($reflection->isDefaultValueAvailable()) {
$defaultValue = $reflection->getDefaultValue();
} elseif ($reflection->isVariadic()) {
$defaultValue = [];
} else {
$defaultValue = null;
}
if ($type instanceof UnresolvableType) {
$type = $type->forParameter($signature);
} elseif (! $type->matches($nativeType)) {
$type = UnresolvableType::forNonMatchingParameterTypes($signature, $nativeType, $type);
} elseif ($isOptional && ! $type->accepts($defaultValue)) {
$type = UnresolvableType::forInvalidParameterDefaultValue($signature, $type, $defaultValue);
}
return new ParameterDefinition(
$name,
$signature,
$type,
$nativeType,
$isOptional,
$isVariadic,
$defaultValue,
new Attributes(...$this->attributesRepository->for($reflection)),
);
}
/**
* @return non-empty-string
*/
private function signature(ReflectionParameter $reflection): string
{
$signature = $reflection->getDeclaringFunction()->name . "(\$$reflection->name)";
$class = $reflection->getDeclaringClass();
if ($class) {
$signature = $class->name . '::' . $signature;
}
return $signature;
}
}
@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Attributes;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\PropertyDefinition;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\AttributesRepository;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\PropertyTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver\ReflectionTypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NullType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use ReflectionProperty;
/** @internal */
final class ReflectionPropertyDefinitionBuilder
{
public function __construct(private AttributesRepository $attributesRepository) {}
public function for(ReflectionProperty $reflection, ReflectionTypeResolver $typeResolver): PropertyDefinition
{
$propertyTypeResolver = new PropertyTypeResolver($typeResolver);
/** @var non-empty-string $name */
$name = $reflection->name;
$signature = $reflection->getDeclaringClass()->name . '::$' . $reflection->name;
$type = $propertyTypeResolver->resolveTypeFor($reflection);
$nativeType = $propertyTypeResolver->resolveNativeTypeFor($reflection);
$hasDefaultValue = $this->hasDefaultValue($reflection, $type);
$defaultValue = $reflection->getDefaultValue();
$isPublic = $reflection->isPublic();
if ($type instanceof UnresolvableType) {
$type = $type->forProperty($signature);
} elseif (! $type->matches($nativeType)) {
$type = UnresolvableType::forNonMatchingPropertyTypes($signature, $nativeType, $type);
} elseif ($hasDefaultValue && ! $type->accepts($defaultValue)) {
$type = UnresolvableType::forInvalidPropertyDefaultValue($signature, $type, $defaultValue);
}
return new PropertyDefinition(
$name,
$signature,
$type,
$nativeType,
$hasDefaultValue,
$defaultValue,
$isPublic,
new Attributes(...$this->attributesRepository->for($reflection)),
);
}
private function hasDefaultValue(ReflectionProperty $reflection, Type $type): bool
{
if ($reflection->hasType()) {
return $reflection->hasDefaultValue();
}
return $reflection->getDeclaringClass()->getDefaultProperties()[$reflection->name] !== null
|| NullType::get()->matches($type);
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\InvalidTypeAliasImportClass;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\InvalidTypeAliasImportClassType;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\UnknownTypeAliasImport;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\InvalidType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Factory\TypeParserFactory;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use function current;
use function key;
use function next;
/** @internal */
final class ClassImportedTypeAliasResolver
{
public function __construct(private TypeParserFactory $typeParserFactory) {}
/**
* @return array<string, Type>
*/
public function resolveImportedTypeAliases(ObjectType $type): array
{
$importedTypesRaw = $this->extractImportedAliasesFromDocBlock($type->className());
if ($importedTypesRaw === []) {
return [];
}
$typeParser = $this->typeParserFactory->buildAdvancedTypeParserForClass($type);
$importedTypes = [];
foreach ($importedTypesRaw as $class => $types) {
try {
$classType = $typeParser->parse($class);
} catch (InvalidType) {
throw new InvalidTypeAliasImportClass($type, $class);
}
if (! $classType instanceof ObjectType) {
throw new InvalidTypeAliasImportClassType($type, $classType);
}
$localTypes = (new ClassLocalTypeAliasResolver($this->typeParserFactory))->resolveLocalTypeAliases($classType);
foreach ($types as $importedType) {
if (! isset($localTypes[$importedType])) {
throw new UnknownTypeAliasImport($type, $classType->className(), $importedType);
}
$importedTypes[$importedType] = $localTypes[$importedType];
}
}
return $importedTypes;
}
/**
* @param class-string $className
* @return array<non-empty-string, list<non-empty-string>>
*/
private function extractImportedAliasesFromDocBlock(string $className): array
{
$docBlock = Reflection::class($className)->getDocComment();
if ($docBlock === false) {
return [];
}
$importedAliases = [];
$annotations = (new Annotations($docBlock))->filteredByPriority(
'@phpstan-import-type',
'@psalm-import-type',
);
foreach ($annotations as $annotation) {
$tokens = $annotation->filtered();
$name = current($tokens);
$from = next($tokens);
if ($from !== 'from') {
continue;
}
next($tokens);
$key = key($tokens);
// @phpstan-ignore identical.alwaysFalse (Somehow PHPStan does not properly infer the key)
if ($key === null) {
continue;
}
$class = $annotation->allAfter($key);
$importedAliases[$class][] = $name;
}
return $importedAliases;
}
}
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\InvalidType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Factory\TypeParserFactory;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use function current;
use function key;
use function next;
/** @internal */
final class ClassLocalTypeAliasResolver
{
public function __construct(private TypeParserFactory $typeParserFactory) {}
/**
* @return array<string, Type>
*/
public function resolveLocalTypeAliases(ObjectType $type): array
{
$localAliases = $this->extractLocalAliasesFromDocBlock($type->className());
if ($localAliases === []) {
return [];
}
$types = [];
foreach ($localAliases as $name => $raw) {
try {
$typeParser = $this->typeParserFactory->buildAdvancedTypeParserForClass($type, $types);
$types[$name] = $typeParser->parse($raw);
} catch (InvalidType $exception) {
$types[$name] = UnresolvableType::forLocalAlias($raw, $name, $type, $exception);
}
}
return $types;
}
/**
* @param class-string $className
* @return array<non-empty-string, non-empty-string>
*/
private function extractLocalAliasesFromDocBlock(string $className): array
{
$docBlock = Reflection::class($className)->getDocComment();
if ($docBlock === false) {
return [];
}
$aliases = [];
$annotations = (new Annotations($docBlock))->filteredInOrder(
'@phpstan-type',
'@psalm-type',
);
foreach ($annotations as $annotation) {
$tokens = $annotation->filtered();
$name = current($tokens);
$next = next($tokens);
if ($next === '=') {
next($tokens);
}
$key = key($tokens);
// @phpstan-ignore notIdentical.alwaysTrue (Somehow PHPStan does not properly infer the key)
if ($key !== null) {
$aliases[$name] = $annotation->allAfter($key);
}
}
return $aliases;
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\ExtendTagTypeError;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\InvalidExtendTagClassName;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\InvalidExtendTagType;
use OCA\Talk\Vendor\CuyZ\Valinor\Definition\Exception\SeveralExtendTagsFound;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\ObjectType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\InvalidType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Factory\TypeParserFactory;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\TokenizedAnnotation;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\NativeClassType;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use ReflectionClass;
use function array_map;
/** @internal */
final class ClassParentTypeResolver
{
public function __construct(private TypeParserFactory $typeParserFactory) {}
public function resolveParentTypeFor(ObjectType $type): NativeClassType
{
$reflection = Reflection::class($type->className());
/** @var ReflectionClass<object> $parentReflection */
$parentReflection = $reflection->getParentClass();
$extendedClass = $this->extractParentTypeFromDocBlock($reflection);
if (count($extendedClass) > 1) {
throw new SeveralExtendTagsFound($reflection);
} elseif (count($extendedClass) === 0) {
$extendedClass = $parentReflection->name;
} else {
$extendedClass = $extendedClass[0];
}
$typeParser = $this->typeParserFactory->buildAdvancedTypeParserForClass($type);
try {
$parentType = $typeParser->parse($extendedClass);
} catch (InvalidType $exception) {
throw new ExtendTagTypeError($reflection, $exception);
}
if (! $parentType instanceof NativeClassType) {
throw new InvalidExtendTagType($reflection, $parentType);
}
if ($parentType->className() !== $parentReflection->name) {
throw new InvalidExtendTagClassName($reflection, $parentType);
}
return $parentType;
}
/**
* @param ReflectionClass<object> $reflection
* @return list<non-empty-string>
*/
private function extractParentTypeFromDocBlock(ReflectionClass $reflection): array
{
$docBlock = $reflection->getDocComment();
if ($docBlock === false) {
return [];
}
$annotations = (new Annotations($docBlock))->filteredByPriority(
'@phpstan-extends',
'@psalm-extends',
'@extends',
);
return array_map(
fn (TokenizedAnnotation $annotation) => $annotation->raw(),
$annotations,
);
}
}
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\Template\DuplicatedTemplateName;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Utility\Reflection\Reflection;
use function array_key_exists;
use function array_keys;
use function current;
use function key;
/** @internal */
final class ClassTemplatesResolver
{
/**
* @param class-string $className
* @return list<non-empty-string>
*/
public function resolveTemplateNamesFrom(string $className): array
{
return array_keys($this->resolveTemplatesFrom($className));
}
/**
* @param class-string $className
* @return array<non-empty-string, non-empty-string|null>
*/
public function resolveTemplatesFrom(string $className): array
{
$docBlock = Reflection::class($className)->getDocComment();
if ($docBlock === false) {
return [];
}
$templates = [];
$annotations = (new Annotations($docBlock))->filteredByPriority(
'@phpstan-template',
'@psalm-template',
'@template',
);
foreach ($annotations as $annotation) {
$tokens = $annotation->filtered();
$name = current($tokens);
if (array_key_exists($name, $templates)) {
throw new DuplicatedTemplateName($className, $name);
}
$of = next($tokens);
if ($of !== 'of') {
// The keyword `of` was not found, the following tokens are
// considered as comments, and we ignore them.
$templates[$name] = null;
} else {
// The keyword `of` was found, the following tokens represent
// the template type.
next($tokens);
$key = key($tokens);
$templates[$name] = $key ? $annotation->allAfter($key) : null;
}
}
return $templates;
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use ReflectionFunctionAbstract;
/** @internal */
final class FunctionReturnTypeResolver
{
public function __construct(private ReflectionTypeResolver $typeResolver) {}
public function resolveReturnTypeFor(ReflectionFunctionAbstract $reflection): Type
{
$docBlockType = $this->extractReturnTypeFromDocBlock($reflection);
return $this->typeResolver->resolveType($reflection->getReturnType(), $docBlockType);
}
public function resolveNativeReturnTypeFor(ReflectionFunctionAbstract $reflection): Type
{
return $this->typeResolver->resolveNativeType($reflection->getReturnType());
}
private function extractReturnTypeFromDocBlock(ReflectionFunctionAbstract $reflection): ?string
{
$docBlock = $reflection->getDocComment();
if ($docBlock === false) {
return null;
}
return (new Annotations($docBlock))->firstOf(
'@phpstan-return',
'@psalm-return',
'@return',
)?->raw();
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ArrayKeyType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\ArrayType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use ReflectionParameter;
/** @internal */
final class ParameterTypeResolver
{
public function __construct(private ReflectionTypeResolver $typeResolver) {}
public function resolveTypeFor(ReflectionParameter $reflection): Type
{
$docBlockType = null;
if ($reflection->isPromoted()) {
// @phpstan-ignore-next-line / parameter is promoted so class exists for sure
$property = $reflection->getDeclaringClass()->getProperty($reflection->name);
$docBlockType = (new PropertyTypeResolver($this->typeResolver))->extractTypeFromDocBlock($property);
}
if ($docBlockType === null) {
$docBlockType = $this->extractTypeFromDocBlock($reflection);
}
$type = $this->typeResolver->resolveType($reflection->getType(), $docBlockType);
if ($reflection->isVariadic() && ! $type instanceof UnresolvableType) {
return new ArrayType(ArrayKeyType::default(), $type);
}
return $type;
}
public function resolveNativeTypeFor(ReflectionParameter $reflection): Type
{
$type = $this->typeResolver->resolveNativeType($reflection->getType());
if ($reflection->isVariadic()) {
return new ArrayType(ArrayKeyType::default(), $type);
}
return $type;
}
private function extractTypeFromDocBlock(ReflectionParameter $reflection): ?string
{
$docBlock = $reflection->getDeclaringFunction()->getDocComment();
if ($docBlock === false) {
return null;
}
$annotations = (new Annotations($docBlock))->filteredByPriority(
'@phpstan-param',
'@psalm-param',
'@param',
);
foreach ($annotations as $annotation) {
$tokens = $annotation->filtered();
$dollarSignKey = array_search('$', $tokens, true);
if ($dollarSignKey === false) {
continue;
}
$parameterName = $tokens[$dollarSignKey + 1] ?? null;
if ($parameterName === $reflection->name) {
return $annotation->splice($dollarSignKey);
}
}
return null;
}
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Lexer\Annotations;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use ReflectionProperty;
/** @internal */
final class PropertyTypeResolver
{
public function __construct(private ReflectionTypeResolver $typeResolver) {}
public function resolveTypeFor(ReflectionProperty $reflection): Type
{
$docBlockType = $this->extractTypeFromDocBlock($reflection);
return $this->typeResolver->resolveType($reflection->getType(), $docBlockType);
}
public function resolveNativeTypeFor(ReflectionProperty $reflection): Type
{
return $this->typeResolver->resolveNativeType($reflection->getType());
}
public function extractTypeFromDocBlock(ReflectionProperty $reflection): ?string
{
$docBlock = $reflection->getDocComment();
if ($docBlock === false) {
return null;
}
return (new Annotations($docBlock))->firstOf(
'@phpstan-var',
'@psalm-var',
'@var',
)?->raw();
}
}
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace OCA\Talk\Vendor\CuyZ\Valinor\Definition\Repository\Reflection\TypeResolver;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\Exception\InvalidType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Parser\TypeParser;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Type;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\MixedType;
use OCA\Talk\Vendor\CuyZ\Valinor\Type\Types\UnresolvableType;
use ReflectionIntersectionType;
use ReflectionNamedType;
use ReflectionType;
use ReflectionUnionType;
use function trim;
/** @internal */
final class ReflectionTypeResolver
{
public function __construct(
private TypeParser $nativeParser,
private TypeParser $advancedParser,
) {}
public function resolveType(?ReflectionType $native, ?string $docBlock): Type
{
if ($docBlock !== null) {
$docBlock = trim($docBlock);
return $this->parseType($docBlock, $this->advancedParser);
}
if ($native === null) {
return MixedType::get();
}
$type = $this->exportNativeType($native);
// When the type is a class, it may declare templates that must be
// filled with generics. PHP does not handle generics natively, so we
// need to make sure that no generics are left unassigned by parsing the
// type using the advanced parser.
return $this->parseType($type, $this->advancedParser);
}
public function resolveNativeType(?ReflectionType $reflection): Type
{
if ($reflection === null) {
return MixedType::get();
}
$type = $this->exportNativeType($reflection);
return $this->parseType($type, $this->nativeParser);
}
private function exportNativeType(ReflectionType $type): string
{
if ($type instanceof ReflectionUnionType) {
return implode('|', $type->getTypes());
}
if ($type instanceof ReflectionIntersectionType) {
return implode('&', $type->getTypes());
}
/** @var ReflectionNamedType $type */
$name = $type->getName();
if ($name !== 'null' && $type->allowsNull() && $name !== 'mixed') {
return $name . '|null';
}
return $name;
}
private function parseType(string $raw, TypeParser $parser): Type
{
try {
return $parser->parse($raw);
} catch (InvalidType $exception) {
return new UnresolvableType($raw, $exception->getMessage());
}
}
}