Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

View file

@ -0,0 +1,54 @@
{
"name": "nette/php-generator",
"description": "🐘 Nette PHP Generator: generates neat PHP code for you. Supports new PHP 8.5 features.",
"keywords": ["nette", "php", "code", "scaffolding"],
"homepage": "https://nette.org",
"license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"require": {
"php": "8.1 - 8.5",
"nette/utils": "^4.0.6"
},
"require-dev": {
"nette/tester": "^2.6",
"nikic/php-parser": "^5.0",
"tracy/tracy": "^2.8",
"phpstan/phpstan": "^2.1.40@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0",
"jetbrains/phpstorm-attributes": "^1.2"
},
"suggest": {
"nikic/php-parser": "to use ClassType::from(withBodies: true) & ClassType::fromCode()"
},
"autoload": {
"classmap": ["src/"],
"psr-4": {
"Nette\\": "src"
}
},
"minimum-stability": "dev",
"scripts": {
"phpstan": "phpstan analyse",
"tester": "tester tests -s"
},
"extra": {
"branch-alias": {
"dev-master": "4.2-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}

60
vendor/nette/php-generator/license.md vendored Normal file
View file

@ -0,0 +1,60 @@
Licenses
========
Good news! You may use Nette Framework under the terms of either
the New BSD License or the GNU General Public License (GPL) version 2 or 3.
The BSD License is recommended for most projects. It is easy to understand and it
places almost no restrictions on what you can do with the framework. If the GPL
fits better to your project, you can use the framework under this license.
You don't have to notify anyone which license you are using. You can freely
use Nette Framework in commercial projects as long as the copyright header
remains intact.
Please be advised that the name "Nette Framework" is a protected trademark and its
usage has some limitations. So please do not use word "Nette" in the name of your
project or top-level domain, and choose a name that stands on its own merits.
If your stuff is good, it will not take long to establish a reputation for yourselves.
New BSD License
---------------
Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of "Nette Framework" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright owner or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
GNU General Public License
--------------------------
GPL licenses are very very long, so instead of including them here we offer
you URLs with full text:
- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html)
- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)

1008
vendor/nette/php-generator/readme.md vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,40 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of a PHP attribute.
*/
final class Attribute
{
public function __construct(
private readonly string $name,
/** @var mixed[] */
private readonly array $args,
) {
if (!Helpers::isNamespaceIdentifier($name)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid attribute name.");
}
}
public function getName(): string
{
return $this->name;
}
/** @return mixed[] */
public function getArguments(): array
{
return $this->args;
}
}

View file

@ -0,0 +1,167 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function array_map, func_num_args, is_object, str_contains, strtolower;
/**
* Base definition of class, interface, trait or enum type.
*/
abstract class ClassLike
{
use Traits\CommentAware;
use Traits\AttributeAware;
#[\Deprecated('Use Visibility::Public')]
public const VisibilityPublic = Visibility::Public,
VISIBILITY_PUBLIC = Visibility::Public;
#[\Deprecated('Use Visibility::Protected')]
public const VisibilityProtected = Visibility::Protected,
VISIBILITY_PROTECTED = Visibility::Protected;
#[\Deprecated('Use Visibility::Private')]
public const VisibilityPrivate = Visibility::Private,
VISIBILITY_PRIVATE = Visibility::Private;
private ?PhpNamespace $namespace;
private ?string $name;
/** @param class-string|object $class */
public static function from(string|object $class, bool $withBodies = false): static
{
$instance = (new Factory)
->fromClassReflection(new \ReflectionClass($class), $withBodies);
if (!$instance instanceof static) {
$class = is_object($class) ? $class::class : $class;
throw new Nette\InvalidArgumentException("$class cannot be represented with " . static::class . '. Call ' . $instance::class . '::' . __FUNCTION__ . '() or ' . __METHOD__ . '() instead.');
}
return $instance;
}
public static function fromCode(string $code): static
{
$instance = (new Factory)
->fromClassCode($code);
if (!$instance instanceof static) {
throw new Nette\InvalidArgumentException('Provided code cannot be represented with ' . static::class . '. Call ' . $instance::class . '::' . __FUNCTION__ . '() or ' . __METHOD__ . '() instead.');
}
return $instance;
}
public function __construct(string $name)
{
if (str_contains($name, '\\')) {
$this->namespace = new PhpNamespace(Helpers::extractNamespace($name));
$this->setName(Helpers::extractShortName($name));
} else {
$this->namespace = func_num_args() > 1 ? func_get_arg(1) : null; // backward compatibility
$this->setName($name);
}
}
public function __toString(): string
{
return (new Printer)->printClass($this, $this->namespace);
}
/** @internal */
public function setNamespace(?PhpNamespace $namespace): static
{
$this->namespace = $namespace;
return $this;
}
public function getNamespace(): ?PhpNamespace
{
return $this->namespace;
}
public function setName(?string $name): static
{
if ($name !== null && (!Helpers::isIdentifier($name) || isset(Helpers::Keywords[strtolower($name)]))) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid class name.");
}
$this->name = $name;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function getFullName(): ?string
{
return $this->name && ($namespace = $this->namespace?->getName())
? $namespace . '\\' . $this->name
: $this->name;
}
public function isClass(): bool
{
return $this instanceof ClassType;
}
public function isInterface(): bool
{
return $this instanceof InterfaceType;
}
public function isTrait(): bool
{
return $this instanceof TraitType;
}
public function isEnum(): bool
{
return $this instanceof EnumType;
}
/** @param list<string> $names */
protected function validateNames(array $names): void
{
foreach ($names as $name) {
if (!Helpers::isNamespaceIdentifier($name, allowLeadingSlash: true)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid class name.");
}
}
}
public function validate(): void
{
}
public function __clone(): void
{
$this->attributes = array_map(fn($attr) => clone $attr, $this->attributes);
}
}

View file

@ -0,0 +1,124 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use const PHP_VERSION_ID;
final class ClassManipulator
{
public function __construct(
private readonly ClassType $class,
) {
}
/**
* Inherits property from parent class.
*/
public function inheritProperty(string $name, bool $returnIfExists = false): Property
{
if ($this->class->hasProperty($name)) {
return $returnIfExists
? $this->class->getProperty($name)
: throw new Nette\InvalidStateException("Cannot inherit property '$name', because it already exists.");
}
$parents = [...(array) $this->class->getExtends(), ...$this->class->getImplements()]
?: throw new Nette\InvalidStateException("Class '{$this->class->getName()}' has neither setExtends() nor setImplements() set.");
foreach ($parents as $parent) {
/** @var class-string $parent */
try {
$rp = new \ReflectionProperty($parent, $name);
} catch (\ReflectionException) {
continue;
}
return $this->implementProperty($rp);
}
throw new Nette\InvalidStateException("Property '$name' has not been found in any ancestor: " . implode(', ', $parents));
}
/**
* Inherits method from parent class or interface.
*/
public function inheritMethod(string $name, bool $returnIfExists = false): Method
{
if ($this->class->hasMethod($name)) {
return $returnIfExists
? $this->class->getMethod($name)
: throw new Nette\InvalidStateException("Cannot inherit method '$name', because it already exists.");
}
$parents = [...(array) $this->class->getExtends(), ...$this->class->getImplements()]
?: throw new Nette\InvalidStateException("Class '{$this->class->getName()}' has neither setExtends() nor setImplements() set.");
foreach ($parents as $parent) {
try {
$rm = new \ReflectionMethod($parent, $name);
} catch (\ReflectionException) {
continue;
}
return $this->implementMethod($rm);
}
throw new Nette\InvalidStateException("Method '$name' has not been found in any ancestor: " . implode(', ', $parents));
}
/**
* Implements all methods from the given interface or abstract class.
* @param class-string $name
*/
public function implement(string $name): void
{
$definition = new \ReflectionClass($name);
if ($definition->isInterface()) {
$this->class->addImplement($name);
} elseif ($definition->isAbstract()) {
$this->class->setExtends($name);
} else {
throw new Nette\InvalidArgumentException("'$name' is not an interface or abstract class.");
}
foreach ($definition->getMethods() as $method) {
if (!$this->class->hasMethod($method->getName()) && $method->isAbstract()) {
$this->implementMethod($method);
}
}
if (PHP_VERSION_ID >= 80400) {
foreach ($definition->getProperties() as $property) {
if (!$this->class->hasProperty($property->getName()) && $property->isAbstract()) {
$this->implementProperty($property);
}
}
}
}
private function implementMethod(\ReflectionMethod $rm): Method
{
$method = (new Factory)->fromMethodReflection($rm);
$method->setAbstract(false);
$this->class->addMember($method);
return $method;
}
private function implementProperty(\ReflectionProperty $rp): Property
{
$property = (new Factory)->fromPropertyReflection($rp);
$property->setHooks([])->setAbstract(false);
$this->class->addMember($property);
return $property;
}
}

View file

@ -0,0 +1,191 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function array_diff, array_map, func_num_args, strtolower;
/**
* Definition of a class with properties, methods, constants, traits and PHP attributes.
*/
final class ClassType extends ClassLike
{
use Traits\ConstantsAware;
use Traits\MethodsAware;
use Traits\PropertiesAware;
use Traits\TraitsAware;
#[\Deprecated]
public const
TYPE_CLASS = 'class',
TYPE_INTERFACE = 'interface',
TYPE_TRAIT = 'trait',
TYPE_ENUM = 'enum';
private bool $final = false;
private bool $abstract = false;
private ?string $extends = null;
private bool $readOnly = false;
/** @var list<string> */
private array $implements = [];
public function __construct(?string $name = null)
{
parent::__construct($name ?? 'foo', func_num_args() > 1 ? func_get_arg(1) : null); // backward compatibility
if ($name === null) {
$this->setName(null);
}
}
public function setFinal(bool $state = true): static
{
$this->final = $state;
return $this;
}
public function isFinal(): bool
{
return $this->final;
}
public function setAbstract(bool $state = true): static
{
$this->abstract = $state;
return $this;
}
public function isAbstract(): bool
{
return $this->abstract;
}
public function setReadOnly(bool $state = true): static
{
$this->readOnly = $state;
return $this;
}
public function isReadOnly(): bool
{
return $this->readOnly;
}
public function setExtends(?string $name): static
{
if ($name) {
$this->validateNames([$name]);
}
$this->extends = $name;
return $this;
}
public function getExtends(): ?string
{
return $this->extends;
}
/** @param list<string> $names */
public function setImplements(array $names): static
{
$this->validateNames($names);
$this->implements = $names;
return $this;
}
/** @return list<string> */
public function getImplements(): array
{
return $this->implements;
}
public function addImplement(string $name): static
{
$this->validateNames([$name]);
$this->implements[] = $name;
return $this;
}
public function removeImplement(string $name): static
{
$this->implements = array_values(array_diff($this->implements, [$name]));
return $this;
}
public function addMember(Method|Property|Constant|TraitUse $member, bool $overwrite = false): static
{
$name = $member->getName();
[$type, $n] = match (true) {
$member instanceof Constant => ['consts', $name],
$member instanceof Method => ['methods', strtolower($name)],
$member instanceof Property => ['properties', $name],
$member instanceof TraitUse => ['traits', $name],
};
if (!$overwrite && isset($this->$type[$n])) {
throw new Nette\InvalidStateException("Cannot add member '$name', because it already exists.");
}
$this->$type[$n] = $member;
return $this;
}
/**
* @deprecated use ClassManipulator::inheritProperty()
*/
public function inheritProperty(string $name, bool $returnIfExists = false): Property
{
return (new ClassManipulator($this))->inheritProperty($name, $returnIfExists);
}
/**
* @deprecated use ClassManipulator::inheritMethod()
*/
public function inheritMethod(string $name, bool $returnIfExists = false): Method
{
return (new ClassManipulator($this))->inheritMethod($name, $returnIfExists);
}
/** @throws Nette\InvalidStateException */
public function validate(): void
{
$name = $this->getName();
if ($name === null && ($this->abstract || $this->final)) {
throw new Nette\InvalidStateException('Anonymous class cannot be abstract or final.');
} elseif ($this->abstract && $this->final) {
throw new Nette\InvalidStateException("Class '$name' cannot be abstract and final at the same time.");
}
}
public function __clone(): void
{
parent::__clone();
$this->consts = array_map(fn(Constant $c) => clone $c, $this->consts);
$this->methods = array_map(fn(Method $m) => clone $m, $this->methods);
$this->properties = array_map(fn(Property $p) => clone $p, $this->properties);
$this->traits = array_map(fn(TraitUse $t) => clone $t, $this->traits);
}
}

View file

@ -0,0 +1,65 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Definition of a closure.
*/
final class Closure
{
use Traits\FunctionLike;
use Traits\AttributeAware;
/** @var list<Parameter> */
private array $uses = [];
/** @param \Closure(): mixed $closure */
public static function from(\Closure $closure): self
{
return (new Factory)->fromFunctionReflection(new \ReflectionFunction($closure));
}
public function __toString(): string
{
return (new Printer)->printClosure($this);
}
/**
* Replaces all uses.
* @param list<Parameter> $uses
*/
public function setUses(array $uses): static
{
(function (Parameter ...$uses) {})(...$uses);
$this->uses = $uses;
return $this;
}
/** @return list<Parameter> */
public function getUses(): array
{
return $this->uses;
}
public function addUse(string $name): Parameter
{
return $this->uses[] = new Parameter($name);
}
public function __clone(): void
{
$this->parameters = array_map(fn($param) => clone $param, $this->parameters);
}
}

View file

@ -0,0 +1,64 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Definition of a class constant.
*/
final class Constant
{
use Traits\NameAware;
use Traits\VisibilityAware;
use Traits\CommentAware;
use Traits\AttributeAware;
private mixed $value;
private bool $final = false;
private ?string $type = null;
public function setValue(mixed $val): static
{
$this->value = $val;
return $this;
}
public function getValue(): mixed
{
return $this->value;
}
public function setFinal(bool $state = true): static
{
$this->final = $state;
return $this;
}
public function isFinal(): bool
{
return $this->final;
}
public function setType(?string $type): static
{
Helpers::validateType($type);
$this->type = $type;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
}

View file

@ -0,0 +1,288 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function addcslashes, array_keys, array_shift, count, dechex, get_mangled_object_vars, implode, in_array, is_array, is_int, is_object, is_resource, is_string, ltrim, method_exists, ord, preg_match, preg_replace, preg_replace_callback, preg_split, range, serialize, str_contains, str_pad, str_repeat, str_replace, strlen, strrpos, strtoupper, substr, trim, unserialize, var_export;
use const PREG_SPLIT_DELIM_CAPTURE, STR_PAD_LEFT;
/**
* Generates a PHP representation of a variable.
*/
final class Dumper
{
private const IndentLength = 4;
public int $maxDepth = 50;
public int $wrapLength = 120;
public string $indentation = "\t";
public bool $customObjects = true;
/**
* Returns a PHP representation of a variable.
*/
public function dump(mixed $var, int $column = 0): string
{
return $this->dumpVar($var, [], 0, $column);
}
/** @param array<mixed[]|object> $parents */
private function dumpVar(mixed $var, array $parents = [], int $level = 0, int $column = 0): string
{
if ($var === null) {
return 'null';
} elseif (is_string($var)) {
return $this->dumpString($var);
} elseif (is_array($var)) {
return $this->dumpArray($var, $parents, $level, $column);
} elseif ($var instanceof Literal) {
return $this->dumpLiteral($var, $level);
} elseif (is_object($var)) {
return $this->dumpObject($var, $parents, $level, $column);
} elseif (is_resource($var)) {
throw new Nette\InvalidStateException('Cannot dump value of type resource.');
} else {
return var_export($var, return: true);
}
}
private function dumpString(string $s): string
{
$special = [
"\r" => '\r',
"\n" => '\n',
"\t" => '\t',
"\e" => '\e',
'\\' => '\\\\',
];
$utf8 = preg_match('##u', $s);
$escaped = preg_replace_callback(
$utf8 ? '#[\p{C}\\\]#u' : '#[\x00-\x1F\x7F-\xFF\\\]#',
fn($m) => $special[$m[0]] ?? (strlen($m[0]) === 1
? '\x' . str_pad(strtoupper(dechex(ord($m[0]))), 2, '0', STR_PAD_LEFT)
: '\u{' . strtoupper(ltrim(dechex(self::utf8Ord($m[0])), '0')) . '}'),
$s,
);
return $s === str_replace('\\\\', '\\', $escaped)
? "'" . preg_replace('#\'|\\\(?=[\'\\\]|$)#D', '\\\$0', $s) . "'"
: '"' . addcslashes($escaped, '"$') . '"';
}
private static function utf8Ord(string $c): int
{
$ord0 = ord($c[0]);
return match (true) {
$ord0 < 0x80 => $ord0,
$ord0 < 0xE0 => ($ord0 << 6) + ord($c[1]) - 0x3080,
$ord0 < 0xF0 => ($ord0 << 12) + (ord($c[1]) << 6) + ord($c[2]) - 0xE2080,
default => ($ord0 << 18) + (ord($c[1]) << 12) + (ord($c[2]) << 6) + ord($c[3]) - 0x3C82080,
};
}
/**
* @param mixed[] $var
* @param array<mixed[]|object> $parents
*/
private function dumpArray(array $var, array $parents, int $level, int $column): string
{
if (empty($var)) {
return '[]';
} elseif ($level > $this->maxDepth || in_array($var, $parents, strict: true)) {
throw new Nette\InvalidStateException('Nesting level too deep or recursive dependency.');
}
$parents[] = $var;
$hideKeys = is_int(($keys = array_keys($var))[0]) && $keys === range($keys[0], $keys[0] + count($var) - 1);
$pairs = [];
foreach ($var as $k => $v) {
$keyPart = $hideKeys && ($k !== $keys[0] || $k === 0)
? ''
: $this->dumpVar($k) . ' => ';
$pairs[] = $keyPart . $this->dumpVar($v, $parents, $level + 1, strlen($keyPart) + 1); // 1 = comma after item
}
$line = '[' . implode(', ', $pairs) . ']';
$space = str_repeat($this->indentation, $level);
return !str_contains($line, "\n") && $level * self::IndentLength + $column + strlen($line) <= $this->wrapLength
? $line
: "[\n$space" . $this->indentation . implode(",\n$space" . $this->indentation, $pairs) . ",\n$space]";
}
/** @param array<mixed[]|object> $parents */
private function dumpObject(object $var, array $parents, int $level, int $column): string
{
if ($level > $this->maxDepth || in_array($var, $parents, strict: true)) {
throw new Nette\InvalidStateException('Nesting level too deep or recursive dependency.');
} elseif ((new \ReflectionObject($var))->isAnonymous()) {
throw new Nette\InvalidStateException('Cannot dump an instance of an anonymous class.');
}
$class = $var::class;
$parents[] = $var;
if ($class === \stdClass::class) {
$var = (array) $var;
return '(object) ' . $this->dumpArray($var, $parents, $level, $column + 10);
} elseif ($class === \DateTime::class || $class === \DateTimeImmutable::class) {
assert($var instanceof \DateTimeInterface);
return $this->format(
"new \\$class(?, new \\DateTimeZone(?))",
$var->format('Y-m-d H:i:s.u'),
$var->getTimezone()->getName(),
);
} elseif ($var instanceof \UnitEnum) {
return '\\' . $var::class . '::' . $var->name;
} elseif ($var instanceof \Closure) {
$inner = Nette\Utils\Callback::unwrap($var);
if (is_callable($inner) && Nette\Utils\Callback::isStatic($inner)) {
return implode('::', (array) $inner) . '(...)';
}
throw new Nette\InvalidStateException('Cannot dump object of type Closure.');
} elseif ($this->customObjects) {
return $this->dumpCustomObject($var, $parents, $level);
} else {
throw new Nette\InvalidStateException("Cannot dump object of type $class.");
}
}
/** @param array<mixed[]|object> $parents */
private function dumpCustomObject(object $var, array $parents, int $level): string
{
$class = $var::class;
$space = str_repeat($this->indentation, $level);
$out = "\n";
if (method_exists($var, '__serialize')) {
$arr = $var->__serialize();
} else {
$arr = (array) $var;
if (method_exists($var, '__sleep')) {
foreach ($var->__sleep() as $v) {
$props[$v] = $props["\x00*\x00$v"] = $props["\x00$class\x00$v"] = true;
}
}
}
foreach ($arr as $k => $v) {
if (!isset($props) || isset($props[$k])) {
$out .= $space . $this->indentation
. ($keyPart = $this->dumpVar($k) . ' => ')
. $this->dumpVar($v, $parents, $level + 1, strlen($keyPart))
. ",\n";
}
}
return '\\' . self::class . "::createObject(\\$class::class, [$out$space])";
}
private function dumpLiteral(Literal $var, int $level): string
{
$s = $var->formatWith($this);
$s = Nette\Utils\Strings::unixNewLines($s);
$s = Nette\Utils\Strings::indent(trim($s), $level, $this->indentation);
return ltrim($s, $this->indentation);
}
/**
* Generates PHP statement. Supports placeholders: ? \? $? ->? ::? ...? ...?: ?*
*/
public function format(string $statement, mixed ...$args): string
{
$tokens = preg_split('#(\.\.\.\?:?|\$\?|->\?|::\?|\\\\\?|\?\*|\?(?!\w))#', $statement, -1, PREG_SPLIT_DELIM_CAPTURE);
$res = '';
foreach ($tokens as $n => $token) {
if ($n % 2 === 0) {
$res .= $token;
} elseif ($token === '\?') {
$res .= '?';
} elseif (!$args) {
throw new Nette\InvalidArgumentException('Insufficient number of arguments.');
} elseif ($token === '?') {
$res .= $this->dump(array_shift($args), strlen($res) - strrpos($res, "\n"));
} elseif ($token === '...?' || $token === '...?:' || $token === '?*') {
$arg = array_shift($args);
if (!is_array($arg)) {
throw new Nette\InvalidArgumentException('Argument must be an array.');
}
$res .= $this->dumpArguments($arg, strlen($res) - strrpos($res, "\n"), $token === '...?:');
} else { // $ -> ::
$arg = array_shift($args);
if ($arg instanceof Literal || !Helpers::isIdentifier($arg)) {
$arg = '{' . $this->dumpVar($arg) . '}';
}
$res .= substr($token, 0, -1) . $arg;
}
}
if ($args) {
throw new Nette\InvalidArgumentException('Insufficient number of placeholders.');
}
return $res;
}
/** @param mixed[] $args */
private function dumpArguments(array $args, int $column, bool $named): string
{
$pairs = [];
foreach ($args as $k => $v) {
$name = $named && !is_int($k) ? $k . ': ' : '';
$pairs[] = $name . $this->dumpVar($v, [$args], 0, $column + strlen($name) + 1); // 1 = ) after args
}
$line = implode(', ', $pairs);
return count($args) < 2 || (!str_contains($line, "\n") && $column + strlen($line) <= $this->wrapLength)
? $line
: "\n" . $this->indentation . implode(",\n" . $this->indentation, $pairs) . ",\n";
}
/**
* @param class-string $class
* @param mixed[] $props
* @internal
*/
public static function createObject(string $class, array $props): object
{
if (method_exists($class, '__unserialize')) {
$obj = (new \ReflectionClass($class))->newInstanceWithoutConstructor();
$obj->__unserialize($props);
return $obj;
}
return unserialize('O' . substr(serialize($class), 1, -1) . substr(serialize($props), 1));
}
}

View file

@ -0,0 +1,34 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Definition of an enum case.
*/
final class EnumCase
{
use Traits\NameAware;
use Traits\CommentAware;
use Traits\AttributeAware;
private string|int|Literal|null $value = null;
public function setValue(string|int|Literal|null $val): static
{
$this->value = $val;
return $this;
}
public function getValue(): string|int|Literal|null
{
return $this->value;
}
}

View file

@ -0,0 +1,143 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of an enum with cases, methods, constants and traits.
*/
final class EnumType extends ClassLike
{
use Traits\ConstantsAware;
use Traits\MethodsAware;
use Traits\TraitsAware;
/** @var list<string> */
private array $implements = [];
/** @var array<string, EnumCase> */
private array $cases = [];
private ?string $type = null;
public function setType(?string $type): static
{
$this->type = $type;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
/** @param list<string> $names */
public function setImplements(array $names): static
{
$this->validateNames($names);
$this->implements = $names;
return $this;
}
/** @return list<string> */
public function getImplements(): array
{
return $this->implements;
}
public function addImplement(string $name): static
{
$this->validateNames([$name]);
$this->implements[] = $name;
return $this;
}
public function removeImplement(string $name): static
{
$this->implements = array_values(array_diff($this->implements, [$name]));
return $this;
}
/**
* Sets cases to enum
* @param list<EnumCase> $cases
*/
public function setCases(array $cases): static
{
(function (EnumCase ...$cases) {})(...$cases);
$this->cases = [];
foreach ($cases as $case) {
$this->cases[$case->getName()] = $case;
}
return $this;
}
/** @return array<string, EnumCase> */
public function getCases(): array
{
return $this->cases;
}
/** Adds case to enum */
public function addCase(string $name, string|int|Literal|null $value = null, bool $overwrite = false): EnumCase
{
if (!$overwrite && isset($this->cases[$name])) {
throw new Nette\InvalidStateException("Cannot add cases '$name', because it already exists.");
}
return $this->cases[$name] = (new EnumCase($name))
->setValue($value);
}
public function removeCase(string $name): static
{
unset($this->cases[$name]);
return $this;
}
/**
* Adds a member. If it already exists, throws an exception or overwrites it if $overwrite is true.
*/
public function addMember(Method|Constant|EnumCase|TraitUse $member, bool $overwrite = false): static
{
$name = $member->getName();
[$type, $n] = match (true) {
$member instanceof Constant => ['consts', $name],
$member instanceof Method => ['methods', strtolower($name)],
$member instanceof TraitUse => ['traits', $name],
$member instanceof EnumCase => ['cases', $name],
};
if (!$overwrite && isset($this->$type[$n])) {
throw new Nette\InvalidStateException("Cannot add member '$name', because it already exists.");
}
$this->$type[$n] = $member;
return $this;
}
public function __clone(): void
{
parent::__clone();
$this->consts = array_map(fn(Constant $c) => clone $c, $this->consts);
$this->methods = array_map(fn(Method $m) => clone $m, $this->methods);
$this->traits = array_map(fn(TraitUse $t) => clone $t, $this->traits);
$this->cases = array_map(fn(EnumCase $c) => clone $c, $this->cases);
}
}

View file

@ -0,0 +1,615 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use PhpParser;
use PhpParser\Modifiers;
use PhpParser\Node;
use PhpParser\NodeFinder;
use PhpParser\ParserFactory;
use function addcslashes, array_map, assert, class_exists, end, in_array, is_array, is_string, rtrim, str_contains, str_repeat, str_replace, str_starts_with, strlen, substr, substr_replace, usort;
/**
* Extracts information from PHP code.
* @internal
*/
final class Extractor
{
private string $code;
/** @var array<Node> */
private array $statements;
private PhpParser\PrettyPrinterAbstract $printer;
public function __construct(string $code)
{
if (!class_exists(ParserFactory::class)) {
throw new Nette\NotSupportedException("PHP-Parser is required to load method bodies, install package 'nikic/php-parser' 4.7 or newer.");
}
$this->printer = new PhpParser\PrettyPrinter\Standard;
$this->parseCode($code);
}
private function parseCode(string $code): void
{
if (!str_starts_with($code, '<?php')) {
throw new Nette\InvalidStateException('The input string is not a PHP code.');
}
$this->code = Nette\Utils\Strings::unixNewLines($code);
$parser = (new ParserFactory)->createForNewestSupportedVersion();
$stmts = $parser->parse($this->code);
assert($stmts !== null);
$traverser = new PhpParser\NodeTraverser;
$traverser->addVisitor(new PhpParser\NodeVisitor\ParentConnectingVisitor);
$traverser->addVisitor(new PhpParser\NodeVisitor\NameResolver(null, ['preserveOriginalNames' => true]));
$this->statements = $traverser->traverse($stmts);
}
/** @return array<string, string> */
public function extractMethodBodies(string $className): array
{
$nodeFinder = new NodeFinder;
$classNode = $nodeFinder->findFirst(
$this->statements,
fn(Node $node) => $node instanceof Node\Stmt\ClassLike && $node->namespacedName !== null && $node->namespacedName->toString() === $className,
);
if (!$classNode) {
return [];
}
$res = [];
foreach ($nodeFinder->findInstanceOf($classNode, Node\Stmt\ClassMethod::class) as $methodNode) {
if ($methodNode->stmts) {
$res[$methodNode->name->toString()] = $this->getReformattedContents($methodNode->stmts, 2);
}
}
return $res;
}
/** @return array<string, array<string, array{string, bool}>> */
public function extractPropertyHookBodies(string $className): array
{
if (!class_exists(Node\PropertyHook::class)) {
return [];
}
$nodeFinder = new NodeFinder;
$classNode = $nodeFinder->findFirst(
$this->statements,
fn(Node $node) => $node instanceof Node\Stmt\ClassLike && $node->namespacedName !== null && $node->namespacedName->toString() === $className,
);
if (!$classNode) {
return [];
}
$res = [];
foreach ($nodeFinder->findInstanceOf($classNode, Node\Stmt\Property::class) as $propertyNode) {
foreach ($propertyNode->props as $propNode) {
$propName = $propNode->name->toString();
foreach ($propertyNode->hooks as $hookNode) {
$body = $hookNode->body;
if ($body !== null) {
$contents = $this->getReformattedContents(is_array($body) ? $body : [$body], 3);
$res[$propName][$hookNode->name->toString()] = [$contents, !is_array($body)];
}
}
}
}
return $res;
}
public function extractFunctionBody(string $name): string
{
$functionNode = (new NodeFinder)->findFirst(
$this->statements,
fn(Node $node) => $node instanceof Node\Stmt\Function_ && $node->namespacedName !== null && $node->namespacedName->toString() === $name,
);
assert($functionNode instanceof Node\Stmt\Function_);
return $this->getReformattedContents($functionNode->stmts, 1);
}
/** @param Node[] $nodes */
private function getReformattedContents(array $nodes, int $level): string
{
if (!$nodes) {
return '';
}
$body = $this->getNodeContents(...$nodes);
$body = $this->performReplacements($body, $this->prepareReplacements($nodes, $level));
return Helpers::unindent($body, $level);
}
/**
* @param Node[] $nodes
* @return array<array{int, int, string}>
*/
private function prepareReplacements(array $nodes, int $level): array
{
$start = $this->getNodeStartPos($nodes[0]);
$replacements = [];
$indent = "\n" . str_repeat("\t", $level);
(new NodeFinder)->find($nodes, function (Node $node) use (&$replacements, $start, $level, $indent) {
if ($node instanceof Node\Name\FullyQualified) {
if ($node->getAttribute('originalName') instanceof Node\Name) {
$of = match (true) {
$node->getAttribute('parent') instanceof Node\Expr\ConstFetch => PhpNamespace::NameConstant,
$node->getAttribute('parent') instanceof Node\Expr\FuncCall => PhpNamespace::NameFunction,
default => PhpNamespace::NameNormal,
};
$replacements[] = [
$node->getStartFilePos() - $start,
$node->getEndFilePos() - $start,
Helpers::tagName($node->toCodeString(), $of),
];
}
} elseif (
$node instanceof Node\Scalar\String_
&& in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_SINGLE_QUOTED, Node\Scalar\String_::KIND_DOUBLE_QUOTED], strict: true)
&& str_contains($node->getAttribute('rawValue'), "\n")
) { // multi-line strings -> single line
$replacements[] = [
$node->getStartFilePos() - $start,
$node->getEndFilePos() - $start,
'"' . addcslashes($node->value, "\x00..\x1F\"") . '"',
];
} elseif (
$node instanceof Node\Scalar\String_
&& in_array($node->getAttribute('kind'), [Node\Scalar\String_::KIND_NOWDOC, Node\Scalar\String_::KIND_HEREDOC], strict: true)
&& Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
) { // fix indentation of NOWDOW/HEREDOC
$replacements[] = [
$node->getStartFilePos() - $start,
$node->getEndFilePos() - $start,
str_replace("\n", $indent, $this->getNodeContents($node)),
];
} elseif (
$node instanceof Node\Scalar\Encapsed
&& $node->getAttribute('kind') === Node\Scalar\String_::KIND_DOUBLE_QUOTED
) { // multi-line strings -> single line
foreach ($node->parts as $part) {
if ($part instanceof Node\Scalar\EncapsedStringPart) {
$replacements[] = [
$part->getStartFilePos() - $start,
$part->getEndFilePos() - $start,
addcslashes($part->value, "\x00..\x1F\""),
];
}
}
} elseif (
$node instanceof Node\Scalar\Encapsed && $node->getAttribute('kind') === Node\Scalar\String_::KIND_HEREDOC
&& Helpers::unindent($node->getAttribute('docIndentation'), $level) === $node->getAttribute('docIndentation')
) { // fix indentation of HEREDOC
$replacements[] = [
$tmp = $node->getStartFilePos() - $start + strlen($node->getAttribute('docLabel')) + 3, // <<<
$tmp,
$indent,
];
$replacements[] = [
$tmp = $node->getEndFilePos() - $start - strlen($node->getAttribute('docLabel')),
$tmp,
$indent,
];
foreach ($node->parts as $part) {
if ($part instanceof Node\Scalar\EncapsedStringPart) {
$replacements[] = [
$part->getStartFilePos() - $start,
$part->getEndFilePos() - $start,
str_replace("\n", $indent, $this->getNodeContents($part)),
];
}
}
}
});
return $replacements;
}
/** @param array<array{int, int, string}> $replacements */
private function performReplacements(string $s, array $replacements): string
{
usort($replacements, fn($a, $b) => $b[0] <=> $a[0]);
foreach ($replacements as [$start, $end, $replacement]) {
$s = substr_replace($s, $replacement, $start, $end - $start + 1);
}
return $s;
}
public function extractAll(): PhpFile
{
$phpFile = new PhpFile;
if (
($firstStmt = $this->statements[0] ?? null)
&& ($firstStmt = $firstStmt instanceof Node\Stmt\Declare_ ? $this->statements[1] ?? null : $firstStmt)
&& !$firstStmt instanceof Node\Stmt\ClassLike
&& !$firstStmt instanceof Node\Stmt\Function_
) {
$comments = $firstStmt->getComments();
foreach ($comments as $i => $comment) {
if ($comment instanceof PhpParser\Comment\Doc) {
$phpFile->setComment(Helpers::unformatDocComment($comment->getReformattedText()));
break;
}
}
}
$namespaces = ['' => $this->statements];
foreach ($this->statements as $node) {
if ($node instanceof Node\Stmt\Declare_
&& $node->declares[0]->key->name === 'strict_types'
&& $node->declares[0]->value instanceof Node\Scalar\LNumber
) {
$phpFile->setStrictTypes((bool) $node->declares[0]->value->value);
} elseif ($node instanceof Node\Stmt\Namespace_) {
$namespaces[$node->name?->toString() ?? ''] = $node->stmts;
}
}
foreach ($namespaces as $name => $nodes) {
foreach ($nodes as $node) {
match (true) {
$node instanceof Node\Stmt\Use_ => $this->addUseToNamespace($phpFile->addNamespace($name), $node),
$node instanceof Node\Stmt\ClassLike => $this->addClassLikeToFile($phpFile, $node),
$node instanceof Node\Stmt\Function_ => $this->addFunctionToFile($phpFile, $node),
default => null,
};
}
}
return $phpFile;
}
private function addUseToNamespace(PhpNamespace $namespace, Node\Stmt\Use_ $node): void
{
$of = [
$node::TYPE_NORMAL => PhpNamespace::NameNormal,
$node::TYPE_FUNCTION => PhpNamespace::NameFunction,
$node::TYPE_CONSTANT => PhpNamespace::NameConstant,
][$node->type];
foreach ($node->uses as $use) {
$namespace->addUse($use->name->toString(), $use->alias?->toString(), $of);
}
}
private function addClassLikeToFile(PhpFile $phpFile, Node\Stmt\ClassLike $node): ClassLike
{
assert($node->namespacedName !== null);
if ($node instanceof Node\Stmt\Class_) {
$class = $phpFile->addClass($node->namespacedName->toString());
$class->setFinal($node->isFinal());
$class->setAbstract($node->isAbstract());
$class->setReadOnly($node->isReadonly());
if ($node->extends) {
$class->setExtends($node->extends->toString());
}
foreach ($node->implements as $item) {
$class->addImplement($item->toString());
}
} elseif ($node instanceof Node\Stmt\Interface_) {
$class = $phpFile->addInterface($node->namespacedName->toString());
foreach ($node->extends as $item) {
$class->addExtend($item->toString());
}
} elseif ($node instanceof Node\Stmt\Trait_) {
$class = $phpFile->addTrait($node->namespacedName->toString());
} elseif ($node instanceof Node\Stmt\Enum_) {
$class = $phpFile->addEnum($node->namespacedName->toString());
$class->setType($node->scalarType?->toString());
foreach ($node->implements as $item) {
$class->addImplement($item->toString());
}
} else {
throw new Nette\ShouldNotHappenException;
}
$this->addCommentAndAttributes($class, $node);
$this->addClassMembers($class, $node);
return $class;
}
private function addClassMembers(ClassLike $class, Node\Stmt\ClassLike $node): void
{
foreach ($node->stmts as $stmt) {
match (true) {
$stmt instanceof Node\Stmt\TraitUse => $this->addTraitToClass($class, $stmt),
$stmt instanceof Node\Stmt\Property => $this->addPropertyToClass($class, $stmt),
$stmt instanceof Node\Stmt\ClassMethod => $this->addMethodToClass($class, $stmt),
$stmt instanceof Node\Stmt\ClassConst => $this->addConstantToClass($class, $stmt),
$stmt instanceof Node\Stmt\EnumCase => $this->addEnumCaseToClass($class, $stmt),
default => null,
};
}
}
private function addTraitToClass(ClassLike $class, Node\Stmt\TraitUse $node): void
{
foreach ($node->traits as $item) {
$trait = $class->addTrait($item->toString());
}
assert($trait instanceof TraitUse);
foreach ($node->adaptations as $item) {
$trait->addResolution(rtrim($this->getReformattedContents([$item], 0), ';'));
}
$this->addCommentAndAttributes($trait, $node);
}
private function addPropertyToClass(ClassLike $class, Node\Stmt\Property $node): void
{
foreach ($node->props as $item) {
$prop = $class->addProperty($item->name->toString());
$prop->setStatic($node->isStatic());
$prop->setVisibility($this->toVisibility($node->flags), $this->toSetterVisibility($node->flags));
$prop->setType($node->type ? $this->toPhp($node->type) : null);
if ($item->default) {
$prop->setValue($this->toValue($item->default));
}
$prop->setReadOnly($node->isReadonly() || ($class instanceof ClassType && $class->isReadOnly()));
$this->addCommentAndAttributes($prop, $node);
$prop->setAbstract((bool) ($node->flags & Modifiers::ABSTRACT));
$prop->setFinal((bool) ($node->flags & Modifiers::FINAL));
$this->addHooksToProperty($prop, $node);
}
}
private function addHooksToProperty(Property|PromotedParameter $prop, Node\Stmt\Property|Node\Param $node): void
{
if (!class_exists(Node\PropertyHook::class)) {
return;
}
foreach ($node->hooks as $hookNode) {
/** @var 'set'|'get' $hookType */
$hookType = $hookNode->name->toString();
$hook = $prop->addHook($hookType);
$hook->setFinal((bool) ($hookNode->flags & Modifiers::FINAL));
$this->setupFunction($hook, $hookNode);
if ($hookNode->body === null) {
$hook->setAbstract();
} elseif (!is_array($hookNode->body)) {
$hook->setBody($this->getReformattedContents([$hookNode->body], 1), short: true);
}
}
}
private function addMethodToClass(ClassLike $class, Node\Stmt\ClassMethod $node): void
{
$method = $class->addMethod($node->name->toString());
$method->setAbstract($node->isAbstract());
$method->setFinal($node->isFinal());
$method->setStatic($node->isStatic());
$method->setVisibility($this->toVisibility($node->flags));
$this->setupFunction($method, $node);
if ($method->getName() === Method::Constructor && $class instanceof ClassType && $class->isReadOnly()) {
array_map(fn($param) => $param instanceof PromotedParameter ? $param->setReadOnly() : $param, $method->getParameters());
}
}
private function addConstantToClass(ClassLike $class, Node\Stmt\ClassConst $node): void
{
foreach ($node->consts as $item) {
$const = $class->addConstant($item->name->toString(), $this->toValue($item->value));
$const->setVisibility($this->toVisibility($node->flags));
$const->setFinal($node->isFinal());
$this->addCommentAndAttributes($const, $node);
}
}
private function addEnumCaseToClass(EnumType $class, Node\Stmt\EnumCase $node): void
{
$value = match (true) {
$node->expr === null => null,
$node->expr instanceof Node\Scalar\LNumber, $node->expr instanceof Node\Scalar\String_ => $node->expr->value,
default => $this->toValue($node->expr),
};
$case = $class->addCase($node->name->toString(), $value);
$this->addCommentAndAttributes($case, $node);
}
private function addFunctionToFile(PhpFile $phpFile, Node\Stmt\Function_ $node): void
{
assert($node->namespacedName !== null);
$function = $phpFile->addFunction($node->namespacedName->toString());
$this->setupFunction($function, $node);
}
private function addCommentAndAttributes(
ClassLike|Constant|Property|GlobalFunction|Method|Parameter|EnumCase|TraitUse|PropertyHook $element,
Node $node,
): void
{
if ($node->getDocComment()) {
$comment = $node->getDocComment()->getReformattedText();
$comment = Helpers::unformatDocComment($comment);
$element->setComment($comment);
$node->setDocComment(new PhpParser\Comment\Doc(''));
}
foreach ($node->attrGroups ?? [] as $group) {
foreach ($group->attrs as $attribute) {
$args = [];
foreach ($attribute->args as $arg) {
if ($arg->name) {
$args[$arg->name->toString()] = $this->toValue($arg->value);
} else {
$args[] = $this->toValue($arg->value);
}
}
$element->addAttribute($attribute->name->toString(), $args);
}
}
}
private function setupFunction(GlobalFunction|Method|PropertyHook $function, Node\FunctionLike $node): void
{
$function->setReturnReference($node->returnsByRef());
if (!$function instanceof PropertyHook) {
$function->setReturnType($node->getReturnType() ? $this->toPhp($node->getReturnType()) : null);
}
foreach ($node->getParams() as $item) {
assert($item->var instanceof Node\Expr\Variable && is_string($item->var->name));
$getVisibility = $this->toVisibility($item->flags);
$setVisibility = $this->toSetterVisibility($item->flags);
$final = (bool) ($item->flags & Modifiers::FINAL);
if ($getVisibility || $setVisibility || $final) {
assert($function instanceof Method);
$param = $function->addPromotedParameter($item->var->name)
->setVisibility($getVisibility, $setVisibility)
->setReadOnly($item->isReadonly())
->setFinal($final);
$this->addHooksToProperty($param, $item);
} else {
$param = $function->addParameter($item->var->name);
}
$param->setType($item->type ? $this->toPhp($item->type) : null);
$param->setReference($item->byRef);
if (!$function instanceof PropertyHook) {
$function->setVariadic($item->variadic);
}
if ($item->default) {
$param->setDefaultValue($this->toValue($item->default));
}
$this->addCommentAndAttributes($param, $item);
}
$this->addCommentAndAttributes($function, $node);
if ($node->getStmts()) {
$indent = $function instanceof GlobalFunction ? 1 : 2;
$function->setBody($this->getReformattedContents($node->getStmts(), $indent));
}
}
private function toValue(Node\Expr $node): mixed
{
if ($node instanceof Node\Expr\ConstFetch) {
return match ($node->name->toLowerString()) {
'null' => null,
'true' => true,
'false' => false,
default => new Literal($this->getReformattedContents([$node], 0)),
};
} elseif ($node instanceof Node\Scalar\LNumber
|| $node instanceof Node\Scalar\DNumber
|| $node instanceof Node\Scalar\String_
) {
return $node->value;
} elseif ($node instanceof Node\Expr\Array_) {
$res = [];
foreach ($node->items as $item) {
if ($item->unpack) {
return new Literal($this->getReformattedContents([$node], 0));
} elseif ($item->key) {
$key = $this->toValue($item->key);
if ($key instanceof Literal) {
return new Literal($this->getReformattedContents([$node], 0));
}
$res[$key] = $this->toValue($item->value);
} else {
$res[] = $this->toValue($item->value);
}
}
return $res;
} else {
return new Literal($this->getReformattedContents([$node], 0));
}
}
private function toVisibility(int $flags): ?Visibility
{
return match (true) {
(bool) ($flags & Modifiers::PUBLIC) => Visibility::Public,
(bool) ($flags & Modifiers::PROTECTED) => Visibility::Protected,
(bool) ($flags & Modifiers::PRIVATE) => Visibility::Private,
default => null,
};
}
private function toSetterVisibility(int $flags): ?Visibility
{
return match (true) {
!class_exists(Node\PropertyHook::class) => null,
(bool) ($flags & Modifiers::PUBLIC_SET) => Visibility::Public,
(bool) ($flags & Modifiers::PROTECTED_SET) => Visibility::Protected,
(bool) ($flags & Modifiers::PRIVATE_SET) => Visibility::Private,
default => null,
};
}
private function toPhp(Node $value): string
{
$dolly = clone $value;
$dolly->setAttribute('comments', []);
return $this->printer->prettyPrint([$dolly]);
}
private function getNodeContents(Node ...$nodes): string
{
$start = $this->getNodeStartPos($nodes[0]);
$last = end($nodes);
assert($last !== false);
return substr($this->code, $start, $last->getEndFilePos() - $start + 1);
}
private function getNodeStartPos(Node $node): int
{
return ($comments = $node->getComments())
? $comments[0]->getStartFilePos()
: $node->getStartFilePos();
}
}

View file

@ -0,0 +1,418 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use Nette\Utils\Reflection;
use function array_diff, array_filter, array_key_exists, array_map, count, explode, file_get_contents, implode, is_object, is_subclass_of, method_exists, reset;
use const PHP_VERSION_ID;
/**
* Creates a representations based on reflection or source code.
*/
final class Factory
{
/** @var array<string, array<string, string>> */
private array $bodyCache = [];
/** @var array<string, Extractor> */
private array $extractorCache = [];
/** @param \ReflectionClass<object> $from */
public function fromClassReflection(
\ReflectionClass $from,
bool $withBodies = false,
): ClassLike
{
if ($withBodies && ($from->isAnonymous() || $from->isInternal() || $from->isInterface())) {
throw new Nette\NotSupportedException('The $withBodies parameter cannot be used for anonymous or internal classes or interfaces.');
}
$class = $this->createClassObject($from);
$this->setupInheritance($class, $from);
$this->populateMembers($class, $from, $withBodies);
return $class;
}
/** @param \ReflectionClass<object> $from */
private function createClassObject(\ReflectionClass &$from): ClassLike
{
if ($from->isAnonymous()) {
return new ClassType;
} elseif ($from->isEnum()) {
$name = $from->getName();
/** @var class-string<\UnitEnum> $name */
$from = new \ReflectionEnum($name);
$class = new EnumType($from->getName());
} elseif ($from->isInterface()) {
$class = new InterfaceType($from->getName());
} elseif ($from->isTrait()) {
$class = new TraitType($from->getName());
} else {
$class = new ClassType($from->getShortName());
$class->setFinal($from->isFinal() && $class->isClass());
$class->setAbstract($from->isAbstract() && $class->isClass());
$class->setReadOnly(PHP_VERSION_ID >= 80200 && $from->isReadOnly());
}
(new PhpNamespace($from->getNamespaceName()))->add($class);
return $class;
}
/** @param \ReflectionClass<object> $from */
private function setupInheritance(ClassLike $class, \ReflectionClass $from): void
{
$ifaces = $from->getInterfaceNames();
foreach ($ifaces as $iface) {
$ifaces = array_filter($ifaces, fn(string $item): bool => !is_subclass_of($iface, $item));
}
if ($from->isInterface()) {
assert($class instanceof InterfaceType);
$class->setExtends(array_values($ifaces));
} elseif ($ifaces) {
assert($class instanceof ClassType || $class instanceof EnumType);
$ifaces = array_diff($ifaces, [\BackedEnum::class, \UnitEnum::class]);
$class->setImplements(array_values($ifaces));
}
$class->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$class->setAttributes($this->formatAttributes($from->getAttributes()));
if ($from->getParentClass()) {
assert($class instanceof ClassType);
$class->setExtends($from->getParentClass()->name);
$class->setImplements(array_values(array_diff($class->getImplements(), $from->getParentClass()->getInterfaceNames())));
}
}
/** @param \ReflectionClass<object> $from */
private function populateMembers(ClassLike $class, \ReflectionClass $from, bool $withBodies): void
{
// Properties
$props = [];
foreach ($from->getProperties() as $prop) {
$declaringClass = Reflection::getPropertyDeclaringClass($prop);
if ($prop->isDefault()
&& $declaringClass->name === $from->name
&& !$prop->isPromoted()
&& !$class->isEnum()
) {
$props[] = $p = $this->fromPropertyReflection($prop);
if ($withBodies && ($file = $declaringClass->getFileName())) {
$hookBodies ??= $this->getExtractor($file)->extractPropertyHookBodies($declaringClass->name);
/** @var array<'set'|'get', array{string, bool}> $propHookBodies */
$propHookBodies = $hookBodies[$prop->getName()] ?? [];
foreach ($propHookBodies as $hookType => [$body, $short]) {
$p->getHook($hookType)?->setBody($body, short: $short);
}
}
}
}
if ($props) {
assert($class instanceof ClassType || $class instanceof InterfaceType || $class instanceof TraitType);
$class->setProperties($props);
}
// Methods and trait resolutions
$methods = $resolutions = [];
foreach ($from->getMethods() as $method) {
$declaringMethod = Reflection::getMethodDeclaringMethod($method);
$declaringClass = $declaringMethod->getDeclaringClass();
if (
$declaringClass->name === $from->name
&& (!$from instanceof \ReflectionEnum || !method_exists($from->isBacked() ? \BackedEnum::class : \UnitEnum::class, $method->name))
) {
$methods[] = $m = $this->fromMethodReflection($method);
if ($withBodies && ($file = $declaringClass->getFileName())) {
$bodies = &$this->bodyCache[$declaringClass->name];
$bodies ??= $this->getExtractor($file)->extractMethodBodies($declaringClass->name);
if (isset($bodies[$declaringMethod->name])) {
$m->setBody($bodies[$declaringMethod->name]);
}
}
}
$modifier = $declaringMethod->getModifiers() !== $method->getModifiers()
? ' ' . $this->getVisibility($method)->value
: null;
$alias = $declaringMethod->name !== $method->name ? ' ' . $method->name : '';
if ($modifier || $alias) {
$resolutions[] = $declaringMethod->name . ' as' . $modifier . $alias;
}
}
assert($class instanceof ClassType || $class instanceof InterfaceType || $class instanceof TraitType || $class instanceof EnumType);
$class->setMethods($methods);
// Traits
foreach ($from->getTraitNames() as $trait) {
assert($class instanceof ClassType || $class instanceof TraitType || $class instanceof EnumType);
$trait = $class->addTrait($trait);
foreach ($resolutions as $resolution) {
$trait->addResolution($resolution);
}
$resolutions = [];
}
// Constants and enum cases
$consts = $cases = [];
foreach ($from->getReflectionConstants() as $const) {
if ($from instanceof \ReflectionEnum && $from->hasCase($const->name)) {
$cases[] = $this->fromCaseReflection($const);
} elseif ($const->getDeclaringClass()->name === $from->name) {
$consts[] = $this->fromConstantReflection($const);
}
}
if ($consts) {
$class->setConstants($consts);
}
if ($cases) {
assert($class instanceof EnumType);
$class->setCases($cases);
}
}
public function fromMethodReflection(\ReflectionMethod $from): Method
{
$method = new Method($from->name);
$method->setParameters(array_map($this->fromParameterReflection(...), $from->getParameters()));
$method->setStatic($from->isStatic());
$isInterface = $from->getDeclaringClass()->isInterface();
$method->setVisibility($isInterface ? null : $this->getVisibility($from));
$method->setFinal($from->isFinal());
$method->setAbstract($from->isAbstract() && !$isInterface);
$method->setReturnReference($from->returnsReference());
$method->setVariadic($from->isVariadic());
$method->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$method->setAttributes($this->formatAttributes($from->getAttributes()));
$method->setReturnType((string) $from->getReturnType());
return $method;
}
public function fromFunctionReflection(\ReflectionFunction $from, bool $withBody = false): GlobalFunction|Closure
{
$function = $from->isClosure() ? new Closure : new GlobalFunction($from->name);
$function->setParameters(array_map($this->fromParameterReflection(...), $from->getParameters()));
$function->setReturnReference($from->returnsReference());
$function->setVariadic($from->isVariadic());
if (!$from->isClosure()) {
assert($function instanceof GlobalFunction);
$function->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
}
$function->setAttributes($this->formatAttributes($from->getAttributes()));
$function->setReturnType((string) $from->getReturnType());
if ($withBody) {
if ($from->isClosure() || $from->isInternal() || !($file = $from->getFileName())) {
throw new Nette\NotSupportedException('The $withBody parameter cannot be used for closures or internal functions.');
}
$function->setBody($this->getExtractor($file)->extractFunctionBody($from->name));
}
return $function;
}
/** @param callable(): mixed $from */
public function fromCallable(callable $from): Method|GlobalFunction|Closure
{
$ref = Nette\Utils\Callback::toReflection($from);
return $ref instanceof \ReflectionMethod
? $this->fromMethodReflection($ref)
: $this->fromFunctionReflection($ref);
}
public function fromParameterReflection(\ReflectionParameter $from): Parameter
{
if ($from->isPromoted()) {
$property = $from->getDeclaringClass()?->getProperty($from->name);
\assert($property instanceof \ReflectionProperty);
$param = (new PromotedParameter($from->name))
->setVisibility($this->getVisibility($property))
->setReadOnly($property->isReadOnly())
->setFinal(PHP_VERSION_ID >= 80500 && $property->isFinal() && !$property->isPrivateSet());
$this->addHooks($property, $param);
} else {
$param = new Parameter($from->name);
}
$param->setReference($from->isPassedByReference());
$param->setType((string) $from->getType());
if ($from->isDefaultValueAvailable()) {
if ($from->isDefaultValueConstant()) {
$parts = explode('::', $from->getDefaultValueConstantName() ?? '');
if (count($parts) > 1) {
$parts[0] = Helpers::tagName($parts[0]);
}
$param->setDefaultValue(new Literal(implode('::', $parts)));
} elseif (is_object($from->getDefaultValue())) {
$param->setDefaultValue($this->fromObject($from->getDefaultValue()));
} else {
$param->setDefaultValue($from->getDefaultValue());
}
}
$param->setAttributes($this->formatAttributes($from->getAttributes()));
return $param;
}
public function fromConstantReflection(\ReflectionClassConstant $from): Constant
{
$const = new Constant($from->name);
$const->setValue($from->getValue());
$const->setVisibility($this->getVisibility($from));
$const->setFinal($from->isFinal());
$const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$const->setAttributes($this->formatAttributes($from->getAttributes()));
return $const;
}
public function fromCaseReflection(\ReflectionClassConstant $from): EnumCase
{
$const = new EnumCase($from->name);
$const->setValue($from->getValue()->value ?? null);
$const->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$const->setAttributes($this->formatAttributes($from->getAttributes()));
return $const;
}
public function fromPropertyReflection(\ReflectionProperty $from): Property
{
$defaults = $from->getDeclaringClass()->getDefaultProperties();
$prop = new Property($from->name);
$prop->setValue($defaults[$prop->getName()] ?? null);
$prop->setStatic($from->isStatic());
$prop->setVisibility($this->getVisibility($from));
$prop->setType((string) $from->getType());
$prop->setInitialized($from->hasType() && array_key_exists($prop->getName(), $defaults));
$prop->setReadOnly($from->isReadOnly());
$prop->setComment(Helpers::unformatDocComment((string) $from->getDocComment()));
$prop->setAttributes($this->formatAttributes($from->getAttributes()));
if (PHP_VERSION_ID >= 80400) {
$this->addHooks($from, $prop);
$isInterface = $from->getDeclaringClass()->isInterface();
$prop->setFinal($from->isFinal() && !$prop->isPrivate(PropertyAccessMode::Set));
$prop->setAbstract($from->isAbstract() && !$isInterface);
}
return $prop;
}
private function addHooks(\ReflectionProperty $from, Property|PromotedParameter $prop): void
{
if (PHP_VERSION_ID < 80400) {
return;
}
$getV = $this->getVisibility($from);
$setV = $from->isPrivateSet()
? Visibility::Private
: ($from->isProtectedSet() ? Visibility::Protected : $getV);
$defaultSetV = $from->isReadOnly() && $getV !== Visibility::Private
? Visibility::Protected
: $getV;
if ($setV !== $defaultSetV) {
$prop->setVisibility($getV === Visibility::Public ? null : $getV, $setV);
}
/** @var 'set'|'get' $type */
foreach ($from->getHooks() as $type => $hook) {
$params = $hook->getParameters();
if (
count($params) === 1
&& $params[0]->getName() === 'value'
&& $params[0]->getType() == $from->getType() // intentionally ==
) {
$params = [];
}
$prop->addHook($type)
->setParameters(array_map($this->fromParameterReflection(...), $params))
->setAbstract($hook->isAbstract())
->setFinal($hook->isFinal())
->setReturnReference($hook->returnsReference())
->setComment(Helpers::unformatDocComment((string) $hook->getDocComment()))
->setAttributes($this->formatAttributes($hook->getAttributes()));
}
}
public function fromObject(object $obj): Literal
{
return new Literal('new \\' . $obj::class . '(/* unknown */)');
}
public function fromClassCode(string $code): ClassLike
{
$classes = $this->fromCode($code)->getClasses();
return reset($classes) ?: throw new Nette\InvalidStateException('The code does not contain any class.');
}
public function fromCode(string $code): PhpFile
{
$reader = new Extractor($code);
return $reader->extractAll();
}
/**
* @param list<\ReflectionAttribute<object>> $attrs
* @return list<Attribute>
*/
private function formatAttributes(array $attrs): array
{
$res = [];
foreach ($attrs as $attr) {
$args = $attr->getArguments();
foreach ($args as &$arg) {
if (is_object($arg)) {
$arg = $this->fromObject($arg);
}
}
$res[] = new Attribute($attr->getName(), $args);
}
return $res;
}
private function getVisibility(\ReflectionProperty|\ReflectionMethod|\ReflectionClassConstant $from): Visibility
{
return $from->isPrivate()
? Visibility::Private
: ($from->isProtected() ? Visibility::Protected : Visibility::Public);
}
private function getExtractor(string $file): Extractor
{
$cache = &$this->extractorCache[$file];
$cache ??= new Extractor(file_get_contents($file) ?: throw new Nette\InvalidStateException("Unable to read file '$file'."));
return $cache;
}
}

View file

@ -0,0 +1,40 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of a global function.
*/
final class GlobalFunction
{
use Traits\FunctionLike;
use Traits\NameAware;
use Traits\CommentAware;
use Traits\AttributeAware;
/** @param string|(\Closure(): mixed) $function */
public static function from(string|\Closure $function, bool $withBody = false): self
{
return (new Factory)->fromFunctionReflection(Nette\Utils\Callback::toReflection($function), $withBody);
}
public function __toString(): string
{
return (new Printer)->printFunction($this);
}
public function __clone(): void
{
$this->parameters = array_map(fn($param) => clone $param, $this->parameters);
}
}

View file

@ -0,0 +1,156 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function is_string, preg_match, preg_replace, preg_replace_callback, str_contains, str_repeat, str_replace, strrpos, strtolower, substr, trim;
/**
* @internal
*/
final class Helpers
{
use Nette\StaticClass;
public const ReIdentifier = '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*';
public const Keywords = [
// class keywords
'bool' => 1, 'false' => 1, 'float' => 1, 'int' => 1, 'iterable' => 1, 'mixed' => 1, 'never' => 1, 'null' => 1,
'object' => 1, 'parent' => 1, 'self' => 1, 'string' => 1, 'true' => 1, 'void' => 1,
// PHP keywords
'__halt_compiler' => 1, 'abstract' => 1, 'and' => 1, 'array' => 1, 'as' => 1, 'break' => 1, 'callable' => 1,
'case' => 1, 'catch' => 1, 'class' => 1, 'clone' => 1, 'const' => 1, 'continue' => 1, 'declare' => 1, 'default' => 1,
'die' => 1, 'do' => 1, 'echo' => 1, 'else' => 1, 'elseif' => 1, 'empty' => 1, 'enddeclare' => 1, 'endfor' => 1,
'endforeach' => 1, 'endif' => 1, 'endswitch' => 1, 'endwhile' => 1, 'eval' => 1, 'exit' => 1, 'extends' => 1,
'final' => 1, 'finally' => 1, 'fn' => 1, 'for' => 1, 'foreach' => 1, 'function' => 1, 'global' => 1, 'goto' => 1,
'if' => 1, 'implements' => 1, 'include' => 1, 'include_once' => 1, 'instanceof' => 1, 'insteadof' => 1,
'interface' => 1, 'isset' => 1, 'list' => 1, 'match' => 1, 'namespace' => 1, 'new' => 1, 'or' => 1, 'print' => 1,
'private' => 1, 'protected' => 1, 'public' => 1, 'readonly' => 1, 'require' => 1, 'require_once' => 1, 'return' => 1,
'static' => 1, 'switch' => 1, 'throw' => 1, 'trait' => 1, 'try' => 1, 'unset' => 1, 'use' => 1, 'var' => 1,
'while' => 1, 'xor' => 1, 'yield' => 1, '__CLASS__' => 1, '__DIR__' => 1, '__FILE__' => 1, '__FUNCTION__' => 1,
'__LINE__' => 1, '__METHOD__' => 1, '__NAMESPACE__' => 1, '__PROPERTY__' => 1, '__TRAIT__' => 1,
];
#[\Deprecated]
public const
PHP_IDENT = self::ReIdentifier,
KEYWORDS = self::Keywords;
public static function formatDocComment(string $content, bool $forceMultiLine = false): string
{
$s = trim($content);
$s = str_replace('*/', '* /', $s);
if ($s === '') {
return '';
} elseif ($forceMultiLine || str_contains($content, "\n")) {
$s = str_replace("\n", "\n * ", "/**\n$s") . "\n */";
return Nette\Utils\Strings::normalize($s) . "\n";
} else {
return "/** $s */\n";
}
}
/** @param PhpNamespace::Name* $of */
public static function tagName(string $name, string $of = PhpNamespace::NameNormal): string
{
return isset(self::Keywords[strtolower($name)])
? $name
: "/*($of*/$name";
}
public static function simplifyTaggedNames(string $code, ?PhpNamespace $namespace): string
{
return preg_replace_callback('~/\*\(([ncf])\*/([\w\x7f-\xff\\\]++)~', function ($m) use ($namespace) {
[, $of, $name] = $m;
return $namespace
? $namespace->simplifyType($name, $of)
: $name;
}, $code);
}
public static function unformatDocComment(string $comment): string
{
return preg_replace('#^\s*\* ?#m', '', trim(trim(trim($comment), '/*')));
}
public static function unindent(string $s, int $level = 1): string
{
return $level
? preg_replace('#^(\t| {4}){1,' . $level . '}#m', '', $s)
: $s;
}
public static function isIdentifier(mixed $value): bool
{
return is_string($value) && preg_match('#^' . self::ReIdentifier . '$#D', $value);
}
public static function isNamespaceIdentifier(mixed $value, bool $allowLeadingSlash = false): bool
{
$re = '#^' . ($allowLeadingSlash ? '\\\?' : '') . self::ReIdentifier . '(\\\\' . self::ReIdentifier . ')*$#D';
return is_string($value) && preg_match($re, $value);
}
public static function extractNamespace(string $name): string
{
return ($pos = strrpos($name, '\\')) ? substr($name, 0, $pos) : '';
}
public static function extractShortName(string $name): string
{
return ($pos = strrpos($name, '\\')) === false
? $name
: substr($name, $pos + 1);
}
public static function tabsToSpaces(string $s, int $count = 4): string
{
return str_replace("\t", str_repeat(' ', $count), $s);
}
/**
* @param class-string $class
* @param mixed[] $props
* @internal
*/
public static function createObject(string $class, array $props): object
{
return Dumper::createObject($class, $props);
}
public static function validateType(?string $type, bool &$nullable = false): ?string
{
if ($type === '' || $type === null) {
return null;
} elseif (!Nette\Utils\Validators::isTypeDeclaration($type)) {
throw new Nette\InvalidArgumentException("Value '$type' is not valid type.");
}
if ($type[0] === '?') {
$nullable = true;
return substr($type, 1);
}
return $type;
}
}

View file

@ -0,0 +1,90 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of an interface with properties, methods and constants.
*/
final class InterfaceType extends ClassLike
{
use Traits\ConstantsAware;
use Traits\MethodsAware;
use Traits\PropertiesAware;
/** @var list<string> */
private array $extends = [];
/** @param string|list<string> $names */
public function setExtends(string|array $names): static
{
$names = (array) $names;
$this->validateNames($names);
$this->extends = $names;
return $this;
}
/** @return list<string> */
public function getExtends(): array
{
return $this->extends;
}
public function addExtend(string $name): static
{
$this->validateNames([$name]);
$this->extends[] = $name;
return $this;
}
/**
* Adds a member. If it already exists, throws an exception or overwrites it if $overwrite is true.
*/
public function addMember(Method|Constant|Property $member, bool $overwrite = false): static
{
$name = $member->getName();
[$type, $n] = match (true) {
$member instanceof Constant => ['consts', $name],
$member instanceof Method => ['methods', strtolower($name)],
$member instanceof Property => ['properties', $name],
};
if (!$overwrite && isset($this->$type[$n])) {
throw new Nette\InvalidStateException("Cannot add member '$name', because it already exists.");
}
$this->$type[$n] = $member;
return $this;
}
/** @throws Nette\InvalidStateException */
public function validate(): void
{
foreach ($this->getProperties() as $property) {
if ($property->isInitialized()) {
throw new Nette\InvalidStateException("Property {$this->getName()}::\${$property->getName()}: Interface cannot have initialized properties.");
} elseif (!$property->getHooks()) {
throw new Nette\InvalidStateException("Property {$this->getName()}::\${$property->getName()}: Interface cannot have properties without hooks.");
}
}
}
public function __clone(): void
{
parent::__clone();
$this->consts = array_map(fn(Constant $c) => clone $c, $this->consts);
$this->methods = array_map(fn(Method $m) => clone $m, $this->methods);
$this->properties = array_map(fn(Property $p) => clone $p, $this->properties);
}
}

View file

@ -0,0 +1,47 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* PHP literal value.
*/
class Literal
{
/**
* Creates a literal representing the creation of an object using the new operator.
* @param mixed[] $args
*/
public static function new(string $class, array $args = []): self
{
return new self('new ' . $class . '(...?:)', [$args]);
}
public function __construct(
private readonly string $value,
/** @var ?mixed[] */
private readonly ?array $args = null,
) {
}
public function __toString(): string
{
return $this->formatWith(new Dumper);
}
/** @internal */
public function formatWith(Dumper $dumper): string
{
return $this->args === null
? $this->value
: $dumper->format($this->value, ...$this->args);
}
}

View file

@ -0,0 +1,111 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function func_num_args;
/**
* Definition of a class method.
*/
final class Method
{
use Traits\FunctionLike;
use Traits\NameAware;
use Traits\VisibilityAware;
use Traits\CommentAware;
use Traits\AttributeAware;
public const Constructor = '__construct';
private bool $static = false;
private bool $final = false;
private bool $abstract = false;
/** @param string|array{object|string, string}|(\Closure(): mixed) $method */
public static function from(string|array|\Closure $method): static
{
return (new Factory)->fromMethodReflection(Nette\Utils\Callback::toReflection($method));
}
public function __toString(): string
{
return (new Printer)->printMethod($this);
}
public function setStatic(bool $state = true): static
{
$this->static = $state;
return $this;
}
public function isStatic(): bool
{
return $this->static;
}
public function setFinal(bool $state = true): static
{
$this->final = $state;
return $this;
}
public function isFinal(): bool
{
return $this->final;
}
public function setAbstract(bool $state = true): static
{
$this->abstract = $state;
return $this;
}
public function isAbstract(): bool
{
return $this->abstract;
}
/**
* @param string $name without $
*/
public function addPromotedParameter(string $name, mixed $defaultValue = null): PromotedParameter
{
$param = new PromotedParameter($name);
if (func_num_args() > 1) {
$param->setDefaultValue($defaultValue);
}
return $this->parameters[$name] = $param;
}
/** @throws Nette\InvalidStateException */
public function validate(): void
{
if ($this->abstract && ($this->final || $this->visibility === Visibility::Private)) {
throw new Nette\InvalidStateException("Method $this->name() cannot be abstract and final or private at the same time.");
}
}
public function __clone(): void
{
$this->parameters = array_map(fn($param) => clone $param, $this->parameters);
}
}

View file

@ -0,0 +1,94 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette\Utils\Type;
/**
* Definition of a function/method parameter.
*/
class Parameter
{
use Traits\NameAware;
use Traits\AttributeAware;
use Traits\CommentAware;
private bool $reference = false;
private ?string $type = null;
private bool $nullable = false;
private bool $hasDefaultValue = false;
private mixed $defaultValue = null;
public function setReference(bool $state = true): static
{
$this->reference = $state;
return $this;
}
public function isReference(): bool
{
return $this->reference;
}
public function setType(?string $type): static
{
$this->type = Helpers::validateType($type, $this->nullable);
return $this;
}
/** @return ($asObject is true ? ?Type : ?string) */
public function getType(bool $asObject = false): Type|string|null
{
return $asObject && $this->type
? Type::fromString($this->type)
: $this->type;
}
public function setNullable(bool $state = true): static
{
$this->nullable = $state;
return $this;
}
public function isNullable(): bool
{
return $this->nullable || ($this->hasDefaultValue && $this->defaultValue === null);
}
public function setDefaultValue(mixed $val): static
{
$this->defaultValue = $val;
$this->hasDefaultValue = true;
return $this;
}
public function getDefaultValue(): mixed
{
return $this->defaultValue;
}
public function hasDefaultValue(): bool
{
return $this->hasDefaultValue;
}
public function validate(): void
{
}
}

View file

@ -0,0 +1,222 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function count;
/**
* Definition of a PHP file.
*
* Generates:
* - opening tag (<?php)
* - doc comments
* - one or more namespaces
*/
final class PhpFile
{
use Traits\CommentAware;
/** @var array<string, PhpNamespace> */
private array $namespaces = [];
private bool $strictTypes = false;
public static function fromCode(string $code): self
{
return (new Factory)->fromCode($code);
}
/**
* Adds a namespace, class-like type, or function to the file. If the item has a namespace,
* it will be added to that namespace (creating it if needed).
*/
public function add(ClassType|InterfaceType|TraitType|EnumType|GlobalFunction|PhpNamespace $item): static
{
if ($item instanceof PhpNamespace) {
if (isset($this->namespaces[$name = $item->getName()])) {
throw new Nette\InvalidStateException("Namespace '$name' already exists in the file.");
}
$this->namespaces[$name] = $item;
$this->refreshBracketedSyntax();
} elseif ($item instanceof GlobalFunction) {
$this->addNamespace('')->add($item);
} else {
$this->addNamespace($item->getNamespace()?->getName() ?? '')->add($item);
}
return $this;
}
/**
* Adds a class to the file. If it already exists, throws an exception.
* As a parameter, pass the full name with namespace.
*/
public function addClass(string $name): ClassType
{
return $this
->addNamespace(Helpers::extractNamespace($name))
->addClass(Helpers::extractShortName($name));
}
/**
* Adds an interface to the file. If it already exists, throws an exception.
* As a parameter, pass the full name with namespace.
*/
public function addInterface(string $name): InterfaceType
{
return $this
->addNamespace(Helpers::extractNamespace($name))
->addInterface(Helpers::extractShortName($name));
}
/**
* Adds a trait to the file. If it already exists, throws an exception.
* As a parameter, pass the full name with namespace.
*/
public function addTrait(string $name): TraitType
{
return $this
->addNamespace(Helpers::extractNamespace($name))
->addTrait(Helpers::extractShortName($name));
}
/**
* Adds an enum to the file. If it already exists, throws an exception.
* As a parameter, pass the full name with namespace.
*/
public function addEnum(string $name): EnumType
{
return $this
->addNamespace(Helpers::extractNamespace($name))
->addEnum(Helpers::extractShortName($name));
}
/**
* Adds a function to the file. If it already exists, throws an exception.
* As a parameter, pass the full name with namespace.
*/
public function addFunction(string $name): GlobalFunction
{
return $this
->addNamespace(Helpers::extractNamespace($name))
->addFunction(Helpers::extractShortName($name));
}
/**
* Adds a namespace to the file. If it already exists, it returns the existing one.
*/
public function addNamespace(string|PhpNamespace $namespace): PhpNamespace
{
$res = $namespace instanceof PhpNamespace
? ($this->namespaces[$namespace->getName()] = $namespace)
: ($this->namespaces[$namespace] ??= new PhpNamespace($namespace));
$this->refreshBracketedSyntax();
return $res;
}
/**
* Removes the namespace from the file.
*/
public function removeNamespace(string|PhpNamespace $namespace): static
{
$name = $namespace instanceof PhpNamespace ? $namespace->getName() : $namespace;
unset($this->namespaces[$name]);
return $this;
}
/** @return array<string, PhpNamespace> */
public function getNamespaces(): array
{
return $this->namespaces;
}
/** @return array<string, ClassType|InterfaceType|TraitType|EnumType> */
public function getClasses(): array
{
$classes = [];
foreach ($this->namespaces as $n => $namespace) {
$n .= $n ? '\\' : '';
foreach ($namespace->getClasses() as $c => $class) {
$classes[$n . $c] = $class;
}
}
return $classes;
}
/** @return array<string, GlobalFunction> */
public function getFunctions(): array
{
$functions = [];
foreach ($this->namespaces as $n => $namespace) {
$n .= $n ? '\\' : '';
foreach ($namespace->getFunctions() as $f => $function) {
$functions[$n . $f] = $function;
}
}
return $functions;
}
/**
* Adds a use statement to the file, to the global namespace.
* @param PhpNamespace::Name* $of
*/
public function addUse(string $name, ?string $alias = null, string $of = PhpNamespace::NameNormal): static
{
$this->addNamespace('')->addUse($name, $alias, $of);
return $this;
}
/**
* Adds declare(strict_types=1) to output.
*/
public function setStrictTypes(bool $state = true): static
{
$this->strictTypes = $state;
return $this;
}
public function hasStrictTypes(): bool
{
return $this->strictTypes;
}
public function __toString(): string
{
return (new Printer)->printFile($this);
}
private function refreshBracketedSyntax(): void
{
foreach ($this->namespaces as $namespace) {
$namespace->setBracketedSyntax(count($this->namespaces) > 1 && isset($this->namespaces['']));
}
}
}

View file

@ -0,0 +1,14 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/** @deprecated use Nette\PhpGenerator\Literal */
class PhpLiteral extends Literal
{
}

View file

@ -0,0 +1,417 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use Nette\InvalidStateException;
use function strlen;
use const ARRAY_FILTER_USE_BOTH;
/**
* Definition of a PHP namespace.
*
* Generates:
* - namespace statement
* - variable amount of use statements
* - one or more class declarations
*/
final class PhpNamespace
{
public const
NameNormal = 'n',
NameFunction = 'f',
NameConstant = 'c';
#[\Deprecated('use PhpNamespace::NameNormal')]
public const NAME_NORMAL = self::NameNormal;
#[\Deprecated('use PhpNamespace::NameFunction')]
public const NAME_FUNCTION = self::NameFunction;
#[\Deprecated('use PhpNamespace::NameConstant')]
public const NAME_CONSTANT = self::NameConstant;
private string $name;
private bool $bracketedSyntax = false;
/** @var array<string, array<string, string>> */
private array $aliases = [
self::NameNormal => [],
self::NameFunction => [],
self::NameConstant => [],
];
/** @var array<string, ClassType|InterfaceType|TraitType|EnumType> */
private array $classes = [];
/** @var array<string, GlobalFunction> */
private array $functions = [];
public function __construct(string $name)
{
if ($name !== '' && !Helpers::isNamespaceIdentifier($name)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid name.");
}
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
/**
* @internal
*/
public function setBracketedSyntax(bool $state = true): static
{
$this->bracketedSyntax = $state;
return $this;
}
public function hasBracketedSyntax(): bool
{
return $this->bracketedSyntax;
}
/**
* Adds a use statement to the namespace for class, function or constant.
* @param self::Name* $of
* @throws InvalidStateException
*/
public function addUse(string $name, ?string $alias = null, string $of = self::NameNormal): static
{
if (
!Helpers::isNamespaceIdentifier($name, allowLeadingSlash: true)
|| (Helpers::isIdentifier($name) && isset(Helpers::Keywords[strtolower($name)]))
) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid class/function/constant name.");
} elseif ($alias && (!Helpers::isIdentifier($alias) || isset(Helpers::Keywords[strtolower($alias)]))) {
throw new Nette\InvalidArgumentException("Value '$alias' is not valid alias.");
}
$name = ltrim($name, '\\');
$aliases = array_change_key_case($this->aliases[$of]);
$used = [self::NameNormal => $this->classes, self::NameFunction => $this->functions, self::NameConstant => []][$of];
if ($alias === null) {
$base = Helpers::extractShortName($name);
$counter = null;
do {
$alias = $base . $counter;
$lower = strtolower($alias);
$counter++;
} while ((isset($aliases[$lower]) && strcasecmp($aliases[$lower], $name) !== 0) || isset($used[$lower]));
} else {
$lower = strtolower($alias);
if (isset($aliases[$lower]) && strcasecmp($aliases[$lower], $name) !== 0) {
throw new InvalidStateException(
"Alias '$alias' used already for '{$aliases[$lower]}', cannot use for '$name'.",
);
} elseif (isset($used[$lower])) {
throw new Nette\InvalidStateException("Name '$alias' used already for '$this->name\\{$used[$lower]->getName()}'.");
}
}
$this->aliases[$of][$alias] = $name;
return $this;
}
/** @param self::Name* $of */
public function removeUse(string $name, string $of = self::NameNormal): void
{
foreach ($this->aliases[$of] as $alias => $item) {
if (strcasecmp($item, $name) === 0) {
unset($this->aliases[$of][$alias]);
}
}
}
/**
* Adds a use statement to the namespace for function.
*/
public function addUseFunction(string $name, ?string $alias = null): static
{
return $this->addUse($name, $alias, self::NameFunction);
}
/**
* Adds a use statement to the namespace for constant.
*/
public function addUseConstant(string $name, ?string $alias = null): static
{
return $this->addUse($name, $alias, self::NameConstant);
}
/**
* @param self::Name* $of
* @return array<string, string>
*/
public function getUses(string $of = self::NameNormal): array
{
uasort($this->aliases[$of], fn(string $a, string $b): int => strtr($a, '\\', ' ') <=> strtr($b, '\\', ' '));
return array_filter(
$this->aliases[$of],
fn($name, $alias) => (bool) strcasecmp(($this->name ? $this->name . '\\' : '') . $alias, $name),
ARRAY_FILTER_USE_BOTH,
);
}
/**
* Resolves relative name to full name.
* @param self::Name* $of
*/
public function resolveName(string $name, string $of = self::NameNormal): string
{
if (isset(Helpers::Keywords[strtolower($name)]) || $name === '') {
return $name;
} elseif ($name[0] === '\\') {
return substr($name, 1);
}
$aliases = array_change_key_case($this->aliases[$of]);
if ($of !== self::NameNormal) {
return $aliases[strtolower($name)]
?? $this->resolveName(Helpers::extractNamespace($name) . '\\') . Helpers::extractShortName($name);
}
$parts = explode('\\', $name, 2);
return ($res = $aliases[strtolower($parts[0])] ?? null)
? $res . (isset($parts[1]) ? '\\' . $parts[1] : '')
: $this->name . ($this->name ? '\\' : '') . $name;
}
/**
* Simplifies type hint with relative names.
* @param self::Name* $of
*/
public function simplifyType(string $type, string $of = self::NameNormal): string
{
return preg_replace_callback('~[\w\x7f-\xff\\\]+~', fn($m) => $this->simplifyName($m[0], $of), $type);
}
/**
* Simplifies the full name of a class, function, or constant to a relative name.
* @param self::Name* $of
*/
public function simplifyName(string $name, string $of = self::NameNormal): string
{
if (isset(Helpers::Keywords[strtolower($name)]) || $name === '') {
return $name;
}
$name = ltrim($name, '\\');
if ($of !== self::NameNormal) {
foreach ($this->aliases[$of] as $alias => $original) {
if (strcasecmp($original, $name) === 0) {
return $alias;
}
}
return $this->simplifyName(Helpers::extractNamespace($name) . '\\') . Helpers::extractShortName($name);
}
$shortest = null;
$relative = self::startsWith($name, $this->name . '\\')
? substr($name, strlen($this->name) + 1)
: null;
foreach ($this->aliases[$of] as $alias => $original) {
if ($relative && self::startsWith($relative . '\\', $alias . '\\')) {
$relative = null;
}
if (self::startsWith($name . '\\', $original . '\\')) {
$short = $alias . substr($name, strlen($original));
if (!isset($shortest) || strlen($shortest) > strlen($short)) {
$shortest = $short;
}
}
}
if (isset($shortest, $relative) && strlen($shortest) < strlen($relative)) {
return $shortest;
}
return $relative ?? $shortest ?? ($this->name ? '\\' : '') . $name;
}
/**
* Adds a class-like type or function to the namespace. If it already exists, throws an exception.
*/
public function add(ClassType|InterfaceType|TraitType|EnumType|GlobalFunction $item): static
{
$name = $item->getName() ?? throw new Nette\InvalidArgumentException('Class does not have a name.');
$lower = strtolower($name);
[$list, $type] = $item instanceof GlobalFunction ? [$this->functions, self::NameFunction] : [$this->classes, self::NameNormal];
if (isset($list[$lower]) && $list[$lower] !== $item) {
throw new Nette\InvalidStateException("Cannot add '$name', because it already exists.");
} elseif ($orig = array_change_key_case($this->aliases[$type])[$lower] ?? null) {
throw new Nette\InvalidStateException("Name '$name' used already as alias for $orig.");
}
if ($item instanceof GlobalFunction) {
$this->functions[$lower] = $item;
} else {
$this->classes[$lower] = $item;
$item->setNamespace($this);
}
return $this;
}
/**
* Adds a class to the namespace. If it already exists, throws an exception.
*/
public function addClass(string $name): ClassType
{
$this->add($class = (new ClassType($name))->setNamespace($this));
return $class;
}
/**
* Adds an interface to the namespace. If it already exists, throws an exception.
*/
public function addInterface(string $name): InterfaceType
{
$this->add($iface = (new InterfaceType($name))->setNamespace($this));
return $iface;
}
/**
* Adds a trait to the namespace. If it already exists, throws an exception.
*/
public function addTrait(string $name): TraitType
{
$this->add($trait = (new TraitType($name))->setNamespace($this));
return $trait;
}
/**
* Adds an enum to the namespace. If it already exists, throws an exception.
*/
public function addEnum(string $name): EnumType
{
$this->add($enum = (new EnumType($name))->setNamespace($this));
return $enum;
}
/**
* Returns a class-like type from the namespace.
*/
public function getClass(string $name): ClassType|InterfaceType|TraitType|EnumType
{
return $this->classes[strtolower($name)] ?? throw new Nette\InvalidArgumentException("Class '$name' not found.");
}
/**
* Returns all class-like types in the namespace.
* @return array<string, ClassType|InterfaceType|TraitType|EnumType>
*/
public function getClasses(): array
{
$res = [];
foreach ($this->classes as $class) {
$name = $class->getName();
assert($name !== null);
$res[$name] = $class;
}
return $res;
}
/**
* Removes a class-like type from namespace.
*/
public function removeClass(string $name): static
{
unset($this->classes[strtolower($name)]);
return $this;
}
/**
* Adds a function to the namespace. If it already exists, throws an exception.
*/
public function addFunction(string $name): GlobalFunction
{
$this->add($function = new GlobalFunction($name));
return $function;
}
/**
* Returns a function from the namespace.
*/
public function getFunction(string $name): GlobalFunction
{
return $this->functions[strtolower($name)] ?? throw new Nette\InvalidArgumentException("Function '$name' not found.");
}
/**
* Returns all functions in the namespace.
* @return array<string, GlobalFunction>
*/
public function getFunctions(): array
{
$res = [];
foreach ($this->functions as $fn) {
$res[$fn->getName()] = $fn;
}
return $res;
}
/**
* Removes a function type from namespace.
*/
public function removeFunction(string $name): static
{
unset($this->functions[strtolower($name)]);
return $this;
}
private static function startsWith(string $a, string $b): bool
{
return strncasecmp($a, $b, strlen($b)) === 0;
}
public function __toString(): string
{
return (new Printer)->printNamespace($this);
}
}

View file

@ -0,0 +1,539 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use Nette\Utils\Strings;
use function array_filter, array_map, count, end, get_debug_type, implode, is_scalar, ltrim, preg_replace, rtrim, str_contains, str_repeat, str_replace, strlen, substr;
/**
* Generates PHP code.
*/
class Printer
{
public int $wrapLength = 120;
public string $indentation = "\t";
public int $linesBetweenProperties = 0;
public int $linesBetweenMethods = 2;
public int $linesBetweenUseTypes = 0;
public string $returnTypeColon = ': ';
public bool $bracesOnNextLine = true;
public bool $singleParameterOnOneLine = false;
public bool $omitEmptyNamespaces = true;
public bool $declareOnOpenTag = false;
protected ?PhpNamespace $namespace = null;
protected Dumper $dumper;
private bool $resolveTypes = true;
public function __construct()
{
$this->dumper = new Dumper;
}
public function printFunction(GlobalFunction $function, ?PhpNamespace $namespace = null): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
$line = 'function '
. ($function->getReturnReference() ? '&' : '')
. $function->getName();
$returnType = $this->printReturnType($function);
$params = $this->printParameters($function, strlen($line) + strlen($returnType) + 2); // 2 = parentheses
$body = $this->printFunctionBody($function);
$braceOnNextLine = $this->isBraceOnNextLine(str_contains($params, "\n"), (bool) $returnType);
return $this->printDocComment($function)
. $this->printAttributes($function->getAttributes())
. $line
. $params
. $returnType
. ($braceOnNextLine ? "\n" : ' ')
. "{\n" . $this->indent($body) . "}\n";
}
public function printClosure(Closure $closure, ?PhpNamespace $namespace = null): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
$uses = [];
foreach ($closure->getUses() as $param) {
$uses[] = ($param->isReference() ? '&' : '') . '$' . $param->getName();
}
$useStr = strlen($tmp = implode(', ', $uses)) > $this->wrapLength && count($uses) > 1
? "\n" . $this->indentation . implode(",\n" . $this->indentation, $uses) . ",\n"
: $tmp;
$body = $this->printFunctionBody($closure);
return $this->printAttributes($closure->getAttributes(), inline: true)
. 'function '
. ($closure->getReturnReference() ? '&' : '')
. $this->printParameters($closure)
. ($uses ? " use ($useStr)" : '')
. $this->printReturnType($closure)
. " {\n" . $this->indent($body) . '}';
}
public function printArrowFunction(Closure $closure, ?PhpNamespace $namespace = null): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
foreach ($closure->getUses() as $use) {
if ($use->isReference()) {
throw new Nette\InvalidArgumentException('Arrow function cannot bind variables by-reference.');
}
}
$body = $this->printFunctionBody($closure);
return $this->printAttributes($closure->getAttributes())
. 'fn'
. ($closure->getReturnReference() ? '&' : '')
. $this->printParameters($closure)
. $this->printReturnType($closure)
. ' => ' . rtrim($body, "\n") . ';';
}
public function printMethod(Method $method, ?PhpNamespace $namespace = null, bool $isInterface = false): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
$method->validate();
$line = ($method->isAbstract() && !$isInterface ? 'abstract ' : '')
. ($method->isFinal() ? 'final ' : '')
. ($method->getVisibility() ? $method->getVisibility() . ' ' : '')
. ($method->isStatic() ? 'static ' : '')
. 'function '
. ($method->getReturnReference() ? '&' : '')
. $method->getName();
$returnType = $this->printReturnType($method);
$params = $this->printParameters($method, strlen($line) + strlen($returnType) + strlen($this->indentation) + 2);
$body = $this->printFunctionBody($method);
$braceOnNextLine = $this->isBraceOnNextLine(str_contains($params, "\n"), (bool) $returnType);
return $this->printDocComment($method)
. $this->printAttributes($method->getAttributes())
. $line
. $params
. $returnType
. ($method->isAbstract() || $isInterface
? ";\n"
: ($braceOnNextLine ? "\n" : ' ') . "{\n" . $this->indent($body) . "}\n");
}
private function printFunctionBody(Closure|GlobalFunction|Method|PropertyHook $function): string
{
$code = Helpers::simplifyTaggedNames($function->getBody(), $this->namespace);
$code = Strings::normalize($code);
return ltrim(rtrim($code) . "\n");
}
public function printClass(
ClassType|InterfaceType|TraitType|EnumType $class,
?PhpNamespace $namespace = null,
): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
$class->validate();
$resolver = $this->namespace
? $this->namespace->simplifyType(...)
: fn($s) => $s;
$traits = [];
if ($class instanceof ClassType || $class instanceof TraitType || $class instanceof EnumType) {
foreach ($class->getTraits() as $trait) {
$resolutions = implode(";\n", $trait->getResolutions());
$resolutions = Helpers::simplifyTaggedNames($resolutions, $this->namespace);
$traits[] = $this->printDocComment($trait)
. 'use ' . $resolver($trait->getName())
. ($resolutions
? " {\n" . $this->indent($resolutions) . ";\n}\n"
: ";\n");
}
}
$cases = [];
$enumType = null;
if ($class instanceof EnumType) {
$enumType = $class->getType();
foreach ($class->getCases() as $case) {
$enumType ??= is_scalar($case->getValue()) ? get_debug_type($case->getValue()) : null;
$cases[] = $this->printDocComment($case)
. $this->printAttributes($case->getAttributes())
. 'case ' . $case->getName()
. ($case->getValue() === null ? '' : ' = ' . $this->dump($case->getValue()))
. ";\n";
}
}
$readOnlyClass = $class instanceof ClassType && $class->isReadOnly();
$consts = [];
$methods = [];
foreach ($class->getConstants() as $const) {
$consts[] = $this->printConstant($const);
}
foreach ($class->getMethods() as $method) {
if ($readOnlyClass && $method->getName() === Method::Constructor) {
$method = clone $method;
array_map(fn($param) => $param instanceof PromotedParameter ? $param->setReadOnly(false) : null, $method->getParameters());
}
$methods[] = $this->printMethod($method, $namespace, $class->isInterface());
}
$properties = [];
if ($class instanceof ClassType || $class instanceof TraitType || $class instanceof InterfaceType) {
foreach ($class->getProperties() as $property) {
$properties[] = $this->printProperty($property, $readOnlyClass, $class instanceof InterfaceType);
}
}
$members = array_filter([
implode('', $traits),
$this->joinProperties($consts),
$this->joinProperties($cases),
$this->joinProperties($properties),
($methods && $properties ? str_repeat("\n", $this->linesBetweenMethods - 1) : '')
. implode(str_repeat("\n", $this->linesBetweenMethods), $methods),
]);
if ($class instanceof ClassType) {
$line[] = $class->isAbstract() ? 'abstract' : null;
$line[] = $class->isFinal() ? 'final' : null;
$line[] = $class->isReadOnly() ? 'readonly' : null;
}
$line[] = match (true) {
$class instanceof ClassType => $class->getName() ? 'class ' . $class->getName() : null,
$class instanceof InterfaceType => 'interface ' . $class->getName(),
$class instanceof TraitType => 'trait ' . $class->getName(),
$class instanceof EnumType => 'enum ' . $class->getName() . ($enumType ? $this->returnTypeColon . $enumType : ''),
};
$line[] = ($class instanceof ClassType || $class instanceof InterfaceType) && $class->getExtends()
? 'extends ' . implode(', ', array_map($resolver, (array) $class->getExtends()))
: null;
$line[] = ($class instanceof ClassType || $class instanceof EnumType) && $class->getImplements()
? 'implements ' . implode(', ', array_map($resolver, $class->getImplements()))
: null;
$line[] = $class->getName() ? null : '{';
return $this->printDocComment($class)
. $this->printAttributes($class->getAttributes())
. implode(' ', array_filter($line))
. ($class->getName() ? "\n{\n" : "\n")
. ($members ? $this->indent(implode("\n", $members)) : '')
. '}'
. ($class->getName() ? "\n" : '');
}
public function printNamespace(PhpNamespace $namespace): string
{
$this->namespace = $this->resolveTypes ? $namespace : null;
$name = $namespace->getName();
$uses = [
$this->printUses($namespace),
$this->printUses($namespace, PhpNamespace::NameFunction),
$this->printUses($namespace, PhpNamespace::NameConstant),
];
$uses = implode(str_repeat("\n", $this->linesBetweenUseTypes), array_filter($uses));
$items = [];
foreach ($namespace->getClasses() as $class) {
$items[] = $this->printClass($class, $namespace);
}
foreach ($namespace->getFunctions() as $function) {
$items[] = $this->printFunction($function, $namespace);
}
$body = ($uses ? $uses . "\n" : '')
. implode("\n", $items);
if ($namespace->hasBracketedSyntax()) {
return 'namespace' . ($name ? " $name" : '') . "\n{\n"
. $this->indent($body)
. "}\n";
} else {
return ($name ? "namespace $name;\n\n" : '')
. $body;
}
}
public function printFile(PhpFile $file): string
{
$namespaces = [];
foreach ($file->getNamespaces() as $namespace) {
if (!$this->omitEmptyNamespaces || $namespace->getClasses() || $namespace->getFunctions()) {
$namespaces[] = $this->printNamespace($namespace);
}
}
$strictTypes = $file->hasStrictTypes();
return '<?php' . ($strictTypes && $this->declareOnOpenTag ? ' declare(strict_types=1);' : '')
. "\n"
. ($file->getComment() ? "\n" . $this->printDocComment($file) : '')
. "\n"
. ($strictTypes && !$this->declareOnOpenTag ? "declare(strict_types=1);\n\n" : '')
. implode("\n\n", $namespaces);
}
/** @param PhpNamespace::Name* $of */
protected function printUses(PhpNamespace $namespace, string $of = PhpNamespace::NameNormal): string
{
$prefix = [
PhpNamespace::NameNormal => '',
PhpNamespace::NameFunction => 'function ',
PhpNamespace::NameConstant => 'const ',
][$of];
$uses = [];
foreach ($namespace->getUses($of) as $alias => $original) {
$uses[] = Helpers::extractShortName($original) === $alias
? "use $prefix$original;\n"
: "use $prefix$original as $alias;\n";
}
return implode('', $uses);
}
protected function printParameters(Closure|GlobalFunction|Method|PropertyHook $function, int $column = 0): string
{
$special = false;
foreach ($function->getParameters() as $param) {
$param->validate();
$special = $special || $param instanceof PromotedParameter || $param->getAttributes() || $param->getComment();
}
if (!$special || ($this->singleParameterOnOneLine && count($function->getParameters()) === 1)) {
$line = $this->formatParameters($function, multiline: false);
if (!str_contains($line, "\n") && strlen($line) + $column <= $this->wrapLength) {
return $line;
}
}
return $this->formatParameters($function, multiline: true);
}
private function formatParameters(Closure|GlobalFunction|Method|PropertyHook $function, bool $multiline): string
{
$params = $function->getParameters();
$res = '';
foreach ($params as $param) {
$variadic = !$function instanceof PropertyHook && $function->isVariadic() && $param === end($params);
$attrs = $this->printAttributes($param->getAttributes(), inline: true);
$res .=
$this->printDocComment($param)
. ($attrs ? ($multiline ? substr($attrs, 0, -1) . "\n" : $attrs) : '')
. ($param instanceof PromotedParameter
? ($param->isFinal() ? 'final ' : '')
. $this->printPropertyVisibility($param)
. ($param->isReadOnly() && $param->getType() ? ' readonly' : '')
. ' '
: '')
. ltrim($this->printType($param->getType(), $param->isNullable()) . ' ')
. ($param->isReference() ? '&' : '')
. ($variadic ? '...' : '')
. '$' . $param->getName()
. ($param->hasDefaultValue() && !$variadic ? ' = ' . $this->dump($param->getDefaultValue()) : '')
. ($param instanceof PromotedParameter ? $this->printHooks($param) : '')
. ($multiline ? ",\n" : ', ');
}
return $multiline
? "(\n" . $this->indent($res) . ')'
: '(' . substr($res, 0, -2) . ')';
}
private function printConstant(Constant $const): string
{
$def = ($const->isFinal() ? 'final ' : '')
. ($const->getVisibility() ? $const->getVisibility() . ' ' : '')
. 'const '
. ltrim($this->printType($const->getType(), nullable: false) . ' ')
. $const->getName() . ' = ';
return $this->printDocComment($const)
. $this->printAttributes($const->getAttributes())
. $def
. $this->dump($const->getValue(), strlen($def)) . ";\n";
}
private function printProperty(Property $property, bool $readOnlyClass = false, bool $isInterface = false): string
{
$property->validate();
$type = $property->getType();
$def = ($property->isAbstract() && !$isInterface ? 'abstract ' : '')
. ($property->isFinal() ? 'final ' : '')
. $this->printPropertyVisibility($property)
. ($property->isStatic() ? ' static' : '')
. (!$readOnlyClass && $property->isReadOnly() && $type ? ' readonly' : '')
. ' '
. ltrim($this->printType($type, $property->isNullable()) . ' ')
. '$' . $property->getName();
$defaultValue = $property->getValue() === null && !$property->isInitialized()
? ''
: ' = ' . $this->dump($property->getValue(), strlen($def) + 3); // 3 = ' = '
return $this->printDocComment($property)
. $this->printAttributes($property->getAttributes())
. $def
. $defaultValue
. ($this->printHooks($property, $isInterface) ?: ';')
. "\n";
}
private function printPropertyVisibility(Property|PromotedParameter $param): string
{
$get = $param->getVisibility(PropertyAccessMode::Get);
$set = $param->getVisibility(PropertyAccessMode::Set);
return $set
? ($get ? "$get $set(set)" : "$set(set)")
: $get ?? 'public';
}
protected function printType(?string $type, bool $nullable): string
{
if ($type === null) {
return '';
}
if ($this->namespace) {
$type = $this->namespace->simplifyType($type);
}
return $nullable
? Type::nullable($type)
: $type;
}
/** @param PhpFile|ClassLike|GlobalFunction|Method|Property|Constant|Parameter|EnumCase|TraitUse|PropertyHook $commentable */
protected function printDocComment(/*Traits\CommentAware*/ $commentable): string
{
$multiLine = $commentable instanceof GlobalFunction
|| $commentable instanceof Method
|| $commentable instanceof ClassLike
|| $commentable instanceof PhpFile;
return Helpers::formatDocComment((string) $commentable->getComment(), $multiLine);
}
protected function printReturnType(Closure|GlobalFunction|Method $function): string
{
return ($tmp = $this->printType($function->getReturnType(), $function->isReturnNullable()))
? $this->returnTypeColon . $tmp
: '';
}
/** @param list<Attribute> $attrs */
protected function printAttributes(array $attrs, bool $inline = false): string
{
if (!$attrs) {
return '';
}
$this->dumper->indentation = $this->indentation;
$items = [];
foreach ($attrs as $attr) {
$args = $this->dumper->format('...?:', $attr->getArguments());
$args = Helpers::simplifyTaggedNames($args, $this->namespace);
$items[] = $this->printType($attr->getName(), nullable: false) . ($args === '' ? '' : "($args)");
$inline = $inline && !str_contains($args, "\n");
}
return $inline
? '#[' . implode(', ', $items) . '] '
: '#[' . implode("]\n#[", $items) . "]\n";
}
private function printHooks(Property|PromotedParameter $property, bool $isInterface = false): string
{
$hooks = $property->getHooks();
if (!$hooks) {
return '';
}
$simple = true;
foreach ($hooks as $type => $hook) {
$simple = $simple && ($hook->isAbstract() || $isInterface);
$hooks[$type] = $this->printDocComment($hook)
. $this->printAttributes($hook->getAttributes())
. ($hook->isAbstract() || $isInterface
? ($hook->getReturnReference() ? '&' : '')
. $type . ';'
: ($hook->isFinal() ? 'final ' : '')
. ($hook->getReturnReference() ? '&' : '')
. $type
. ($hook->getParameters() ? $this->printParameters($hook) : '')
. ' '
. ($hook->isShort()
? '=> ' . $hook->getBody() . ';'
: "{\n" . $this->indent($this->printFunctionBody($hook)) . '}'));
}
return $simple
? ' { ' . implode(' ', $hooks) . ' }'
: " {\n" . $this->indent(implode("\n", $hooks)) . "\n}";
}
public function setTypeResolving(bool $state = true): static
{
$this->resolveTypes = $state;
return $this;
}
protected function indent(string $s): string
{
$s = str_replace("\t", $this->indentation, $s);
return Strings::indent($s, 1, $this->indentation);
}
protected function dump(mixed $var, int $column = 0): string
{
$this->dumper->indentation = $this->indentation;
$this->dumper->wrapLength = $this->wrapLength;
$s = $this->dumper->dump($var, $column);
$s = Helpers::simplifyTaggedNames($s, $this->namespace);
return $s;
}
/** @param string[] $props */
private function joinProperties(array $props): string
{
return $this->linesBetweenProperties
? implode(str_repeat("\n", $this->linesBetweenProperties), $props)
: preg_replace('#^(\w.*\n)\n(?=\w.*;)#m', '$1', implode("\n", $props));
}
protected function isBraceOnNextLine(bool $multiLine, bool $hasReturnType): bool
{
return $this->bracesOnNextLine && (!$multiLine || $hasReturnType);
}
}

View file

@ -0,0 +1,33 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of a promoted constructor parameter.
*/
final class PromotedParameter extends Parameter
{
use Traits\PropertyLike;
/** @throws Nette\InvalidStateException */
public function validate(): void
{
if ($this->readOnly && !$this->getType()) {
throw new Nette\InvalidStateException("Property \${$this->getName()}: Read-only properties are only supported on typed property.");
}
}
public function __clone(): void
{
$this->hooks = array_map(fn($item) => $item ? clone $item : $item, $this->hooks);
}
}

View file

@ -0,0 +1,136 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use Nette\Utils\Type;
/**
* Definition of a class property.
*/
final class Property
{
use Traits\NameAware;
use Traits\PropertyLike;
use Traits\CommentAware;
use Traits\AttributeAware;
private mixed $value = null;
private bool $static = false;
private ?string $type = null;
private bool $nullable = false;
private bool $initialized = false;
private bool $abstract = false;
public function setValue(mixed $val): static
{
$this->value = $val;
$this->initialized = true;
return $this;
}
public function &getValue(): mixed
{
return $this->value;
}
public function setStatic(bool $state = true): static
{
$this->static = $state;
return $this;
}
public function isStatic(): bool
{
return $this->static;
}
public function setType(?string $type): static
{
$this->type = Helpers::validateType($type, $this->nullable);
return $this;
}
/** @return ($asObject is true ? ?Type : ?string) */
public function getType(bool $asObject = false): Type|string|null
{
return $asObject && $this->type
? Type::fromString($this->type)
: $this->type;
}
public function setNullable(bool $state = true): static
{
$this->nullable = $state;
return $this;
}
public function isNullable(): bool
{
return $this->nullable || ($this->initialized && $this->value === null);
}
public function setInitialized(bool $state = true): static
{
$this->initialized = $state;
return $this;
}
public function isInitialized(): bool
{
return $this->initialized || $this->value !== null;
}
public function setAbstract(bool $state = true): static
{
$this->abstract = $state;
return $this;
}
public function isAbstract(): bool
{
return $this->abstract;
}
/** @throws Nette\InvalidStateException */
public function validate(): void
{
if ($this->readOnly && !$this->type) {
throw new Nette\InvalidStateException("Property \$$this->name: Read-only properties are only supported on typed property.");
} elseif ($this->abstract && $this->final) {
throw new Nette\InvalidStateException("Property \$$this->name cannot be abstract and final at the same time.");
} elseif (
$this->abstract
&& !Nette\Utils\Arrays::some($this->getHooks(), fn($hook) => $hook->isAbstract())
) {
throw new Nette\InvalidStateException("Property \$$this->name: Abstract property must have at least one abstract hook.");
}
}
public function __clone(): void
{
$this->hooks = array_map(fn($item) => $item ? clone $item : $item, $this->hooks);
}
}

View file

@ -0,0 +1,18 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Property access mode.
*/
enum PropertyAccessMode: string
{
case Set = 'set';
case Get = 'get';
}

View file

@ -0,0 +1,127 @@
<?php declare(strict_types=1);
namespace Nette\PhpGenerator;
use JetBrains\PhpStorm\Language;
/**
* Definition of a property hook.
*/
final class PropertyHook
{
use Traits\AttributeAware;
use Traits\CommentAware;
private string $body = '';
private bool $short = false;
private bool $final = false;
private bool $abstract = false;
/** @var array<string, Parameter> */
private array $parameters = [];
private bool $returnReference = false;
/** @param ?mixed[] $args */
public function setBody(
#[Language('PHP')]
string $code,
?array $args = null,
bool $short = false,
): static
{
$this->body = $args === null
? $code
: (new Dumper)->format($code, ...$args);
$this->short = $short;
return $this;
}
public function getBody(): string
{
return $this->body;
}
public function isShort(): bool
{
return $this->short && trim($this->body) !== '';
}
public function setFinal(bool $state = true): static
{
$this->final = $state;
return $this;
}
public function isFinal(): bool
{
return $this->final;
}
public function setAbstract(bool $state = true): static
{
$this->abstract = $state;
return $this;
}
public function isAbstract(): bool
{
return $this->abstract;
}
/**
* @param list<Parameter> $val
* @internal
*/
public function setParameters(array $val): static
{
(function (Parameter ...$val) {})(...$val);
$this->parameters = [];
foreach ($val as $v) {
$this->parameters[$v->getName()] = $v;
}
return $this;
}
/**
* @return array<string, Parameter>
* @internal
*/
public function getParameters(): array
{
return $this->parameters;
}
/**
* Adds a parameter. If it already exists, it overwrites it.
* @param string $name without $
*/
public function addParameter(string $name): Parameter
{
return $this->parameters[$name] = new Parameter($name);
}
public function setReturnReference(bool $state = true): static
{
$this->returnReference = $state;
return $this;
}
public function getReturnReference(): bool
{
return $this->returnReference;
}
}

View file

@ -0,0 +1,18 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Property hook type.
*/
enum PropertyHookType: string
{
case Set = 'set';
case Get = 'get';
}

View file

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Generates PHP code compatible with PSR-2 and PSR-12.
*/
class PsrPrinter extends Printer
{
public string $indentation = ' ';
public int $linesBetweenMethods = 1;
public int $linesBetweenUseTypes = 1;
protected function isBraceOnNextLine(bool $multiLine, bool $hasReturnType): bool
{
return !$multiLine;
}
}

View file

@ -0,0 +1,51 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of a trait with properties, methods, constants and traits.
*/
final class TraitType extends ClassLike
{
use Traits\ConstantsAware;
use Traits\MethodsAware;
use Traits\PropertiesAware;
use Traits\TraitsAware;
/**
* Adds a member. If it already exists, throws an exception or overwrites it if $overwrite is true.
*/
public function addMember(Method|Property|Constant|TraitUse $member, bool $overwrite = false): static
{
$name = $member->getName();
[$type, $n] = match (true) {
$member instanceof Constant => ['consts', $name],
$member instanceof Method => ['methods', strtolower($name)],
$member instanceof Property => ['properties', $name],
$member instanceof TraitUse => ['traits', $name],
};
if (!$overwrite && isset($this->$type[$n])) {
throw new Nette\InvalidStateException("Cannot add member '$name', because it already exists.");
}
$this->$type[$n] = $member;
return $this;
}
public function __clone(): void
{
parent::__clone();
$this->consts = array_map(fn(Constant $c) => clone $c, $this->consts);
$this->methods = array_map(fn(Method $m) => clone $m, $this->methods);
$this->properties = array_map(fn(Property $p) => clone $p, $this->properties);
$this->traits = array_map(fn(TraitUse $t) => clone $t, $this->traits);
}
}

View file

@ -0,0 +1,47 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
/**
* Definition of a trait use statement.
*/
final class TraitUse
{
use Traits\NameAware;
use Traits\CommentAware;
/** @var list<string> */
private array $resolutions = [];
public function __construct(string $name)
{
if (!Nette\PhpGenerator\Helpers::isNamespaceIdentifier($name, allowLeadingSlash: true)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid trait name.");
}
$this->name = $name;
}
public function addResolution(string $resolution): static
{
$this->resolutions[] = $resolution;
return $this;
}
/** @return list<string> */
public function getResolutions(): array
{
return $this->resolutions;
}
}

View file

@ -0,0 +1,47 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette\PhpGenerator\Attribute;
/**
* @internal
*/
trait AttributeAware
{
/** @var list<Attribute> */
private array $attributes = [];
/** @param mixed[] $args */
public function addAttribute(string $name, array $args = []): static
{
$this->attributes[] = new Attribute($name, $args);
return $this;
}
/**
* Replaces all attributes.
* @param list<Attribute> $attrs
*/
public function setAttributes(array $attrs): static
{
(function (Attribute ...$attrs) {})(...$attrs);
$this->attributes = $attrs;
return $this;
}
/** @return list<Attribute> */
public function getAttributes(): array
{
return $this->attributes;
}
}

View file

@ -0,0 +1,47 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
/**
* @internal
*/
trait CommentAware
{
private ?string $comment = null;
public function setComment(?string $val): static
{
$this->comment = $val;
return $this;
}
public function getComment(): ?string
{
return $this->comment;
}
/**
* Adds a new line to the comment.
*/
public function addComment(string $val): static
{
$this->comment .= $this->comment ? "\n$val" : $val;
return $this;
}
public function removeComment(): static
{
$this->comment = null;
return $this;
}
}

View file

@ -0,0 +1,77 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette;
use Nette\PhpGenerator\Constant;
/**
* @internal
*/
trait ConstantsAware
{
/** @var array<string, Constant> */
private array $consts = [];
/**
* Replaces all constants.
* @param list<Constant> $consts
*/
public function setConstants(array $consts): static
{
(function (Constant ...$consts) {})(...$consts);
$this->consts = [];
foreach ($consts as $const) {
$this->consts[$const->getName()] = $const;
}
return $this;
}
/** @return array<string, Constant> */
public function getConstants(): array
{
return $this->consts;
}
public function getConstant(string $name): Constant
{
return $this->consts[$name] ?? throw new Nette\InvalidArgumentException("Constant '$name' not found.");
}
/**
* Adds a constant. If it already exists, throws an exception or overwrites it if $overwrite is true.
*/
public function addConstant(string $name, mixed $value, bool $overwrite = false): Constant
{
if (!$overwrite && isset($this->consts[$name])) {
throw new Nette\InvalidStateException("Cannot add constant '$name', because it already exists.");
}
return $this->consts[$name] = (new Constant($name))
->setValue($value)
->setPublic();
}
public function removeConstant(string $name): static
{
unset($this->consts[$name]);
return $this;
}
public function hasConstant(string $name): bool
{
return isset($this->consts[$name]);
}
}

View file

@ -0,0 +1,175 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use JetBrains\PhpStorm\Language;
use Nette;
use Nette\PhpGenerator\Dumper;
use Nette\PhpGenerator\Parameter;
use Nette\Utils\Type;
use function func_num_args;
/**
* @internal
*/
trait FunctionLike
{
private string $body = '';
/** @var array<string, Parameter> */
private array $parameters = [];
private bool $variadic = false;
private ?string $returnType = null;
private bool $returnReference = false;
private bool $returnNullable = false;
/** @param ?mixed[] $args */
public function setBody(
#[Language('PHP')]
string $code,
?array $args = null,
): static
{
$this->body = $args === null
? $code
: (new Dumper)->format($code, ...$args);
return $this;
}
public function getBody(): string
{
return $this->body;
}
/** @param ?mixed[] $args */
public function addBody(
#[Language('PHP')]
string $code,
?array $args = null,
): static
{
$this->body .= ($args === null ? $code : (new Dumper)->format($code, ...$args)) . "\n";
return $this;
}
/** @param list<Parameter> $val */
public function setParameters(array $val): static
{
(function (Parameter ...$val) {})(...$val);
$this->parameters = [];
foreach ($val as $v) {
$this->parameters[$v->getName()] = $v;
}
return $this;
}
/** @return array<string, Parameter> */
public function getParameters(): array
{
return $this->parameters;
}
public function getParameter(string $name): Parameter
{
return $this->parameters[$name] ?? throw new Nette\InvalidArgumentException("Parameter '$name' not found.");
}
/**
* Adds a parameter. If it already exists, it overwrites it.
* @param string $name without $
*/
public function addParameter(string $name, mixed $defaultValue = null): Parameter
{
$param = new Parameter($name);
if (func_num_args() > 1) {
$param->setDefaultValue($defaultValue);
}
return $this->parameters[$name] = $param;
}
/**
* @param string $name without $
*/
public function removeParameter(string $name): static
{
unset($this->parameters[$name]);
return $this;
}
public function hasParameter(string $name): bool
{
return isset($this->parameters[$name]);
}
public function setVariadic(bool $state = true): static
{
$this->variadic = $state;
return $this;
}
public function isVariadic(): bool
{
return $this->variadic;
}
public function setReturnType(?string $type): static
{
$this->returnType = Nette\PhpGenerator\Helpers::validateType($type, $this->returnNullable);
return $this;
}
/** @return ($asObject is true ? ?Type : ?string) */
public function getReturnType(bool $asObject = false): Type|string|null
{
return $asObject && $this->returnType
? Type::fromString($this->returnType)
: $this->returnType;
}
public function setReturnReference(bool $state = true): static
{
$this->returnReference = $state;
return $this;
}
public function getReturnReference(): bool
{
return $this->returnReference;
}
public function setReturnNullable(bool $state = true): static
{
$this->returnNullable = $state;
return $this;
}
public function isReturnNullable(): bool
{
return $this->returnNullable;
}
}

View file

@ -0,0 +1,87 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette;
use Nette\PhpGenerator\Method;
use function strtolower;
/**
* @internal
*/
trait MethodsAware
{
/** @var array<string, Method> */
private array $methods = [];
/**
* Replaces all methods.
* @param list<Method> $methods
*/
public function setMethods(array $methods): static
{
(function (Method ...$methods) {})(...$methods);
$this->methods = [];
foreach ($methods as $m) {
$this->methods[strtolower($m->getName())] = $m;
}
return $this;
}
/** @return array<string, Method> */
public function getMethods(): array
{
$res = [];
foreach ($this->methods as $m) {
$res[$m->getName()] = $m;
}
return $res;
}
public function getMethod(string $name): Method
{
return $this->methods[strtolower($name)] ?? throw new Nette\InvalidArgumentException("Method '$name' not found.");
}
/**
* Adds a method. If it already exists, throws an exception or overwrites it if $overwrite is true.
*/
public function addMethod(string $name, bool $overwrite = false): Method
{
$lower = strtolower($name);
if (!$overwrite && isset($this->methods[$lower])) {
throw new Nette\InvalidStateException("Cannot add method '$name', because it already exists.");
}
$method = new Method($name);
if (!$this->isInterface()) {
$method->setPublic();
}
return $this->methods[$lower] = $method;
}
public function removeMethod(string $name): static
{
unset($this->methods[strtolower($name)]);
return $this;
}
public function hasMethod(string $name): bool
{
return isset($this->methods[strtolower($name)]);
}
}

View file

@ -0,0 +1,46 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette;
/**
* @internal
*/
trait NameAware
{
private string $name;
public function __construct(string $name)
{
if (!Nette\PhpGenerator\Helpers::isIdentifier($name)) {
throw new Nette\InvalidArgumentException("Value '$name' is not valid name.");
}
$this->name = $name;
}
public function getName(): string
{
return $this->name;
}
/**
* Returns clone with a different name.
*/
public function cloneWithName(string $name): static
{
$dolly = clone $this;
$dolly->__construct($name);
return $dolly;
}
}

View file

@ -0,0 +1,80 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette;
use Nette\PhpGenerator\Property;
use function func_num_args;
/**
* @internal
*/
trait PropertiesAware
{
/** @var array<string, Property> */
private array $properties = [];
/**
* Replaces all properties.
* @param list<Property> $props
*/
public function setProperties(array $props): static
{
(function (Property ...$props) {})(...$props);
$this->properties = [];
foreach ($props as $v) {
$this->properties[$v->getName()] = $v;
}
return $this;
}
/** @return array<string, Property> */
public function getProperties(): array
{
return $this->properties;
}
public function getProperty(string $name): Property
{
return $this->properties[$name] ?? throw new Nette\InvalidArgumentException("Property '$name' not found.");
}
/**
* Adds a property. If it already exists, throws an exception or overwrites it if $overwrite is true.
* @param string $name without $
*/
public function addProperty(string $name, mixed $value = null, bool $overwrite = false): Property
{
if (!$overwrite && isset($this->properties[$name])) {
throw new Nette\InvalidStateException("Cannot add property '$name', because it already exists.");
}
return $this->properties[$name] = func_num_args() > 1
? (new Property($name))->setValue($value)
: new Property($name);
}
/** @param string $name without $ */
public function removeProperty(string $name): static
{
unset($this->properties[$name]);
return $this;
}
public function hasProperty(string $name): bool
{
return isset($this->properties[$name]);
}
}

View file

@ -0,0 +1,172 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette\PhpGenerator\PropertyAccessMode;
use Nette\PhpGenerator\PropertyHook;
use Nette\PhpGenerator\PropertyHookType;
use Nette\PhpGenerator\Visibility;
use function array_filter, in_array, is_string;
/**
* @internal
*/
trait PropertyLike
{
/** @var array{set: ?Visibility, get: ?Visibility} */
private array $visibility = ['set' => null, 'get' => null];
private bool $final = false;
private bool $readOnly = false;
/** @var array<string, ?PropertyHook> */
private array $hooks = ['set' => null, 'get' => null];
/**
* @param Visibility|'public'|'protected'|'private'|null $get
* @param Visibility|'public'|'protected'|'private'|null $set
*/
public function setVisibility(Visibility|string|null $get, Visibility|string|null $set = null): static
{
$this->visibility = [
'set' => $set instanceof Visibility || $set === null ? $set : Visibility::from($set),
'get' => $get instanceof Visibility || $get === null ? $get : Visibility::from($get),
];
return $this;
}
/** @return 'public'|'protected'|'private'|null */
public function getVisibility(PropertyAccessMode|string $mode = PropertyAccessMode::Get): ?string
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
return $this->visibility[$mode->value]?->value;
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function setPublic(PropertyAccessMode|string $mode = PropertyAccessMode::Get): static
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
$this->visibility[$mode->value] = Visibility::Public;
return $this;
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function isPublic(PropertyAccessMode|string $mode = PropertyAccessMode::Get): bool
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
return in_array($this->visibility[$mode->value], [Visibility::Public, null], strict: true);
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function setProtected(PropertyAccessMode|string $mode = PropertyAccessMode::Get): static
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
$this->visibility[$mode->value] = Visibility::Protected;
return $this;
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function isProtected(PropertyAccessMode|string $mode = PropertyAccessMode::Get): bool
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
return $this->visibility[$mode->value] === Visibility::Protected;
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function setPrivate(PropertyAccessMode|string $mode = PropertyAccessMode::Get): static
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
$this->visibility[$mode->value] = Visibility::Private;
return $this;
}
/** @param PropertyAccessMode|'set'|'get' $mode */
public function isPrivate(PropertyAccessMode|string $mode = PropertyAccessMode::Get): bool
{
$mode = is_string($mode) ? PropertyAccessMode::from($mode) : $mode;
return $this->visibility[$mode->value] === Visibility::Private;
}
public function setFinal(bool $state = true): static
{
$this->final = $state;
return $this;
}
public function isFinal(): bool
{
return $this->final;
}
public function setReadOnly(bool $state = true): static
{
$this->readOnly = $state;
return $this;
}
public function isReadOnly(): bool
{
return $this->readOnly;
}
/**
* Replaces all hooks.
* @param array<string, PropertyHook> $hooks
*/
public function setHooks(array $hooks): static
{
(function (PropertyHook ...$hooks) {})(...$hooks);
$this->hooks = $hooks;
return $this;
}
/** @return array<string, PropertyHook> */
public function getHooks(): array
{
return array_filter($this->hooks);
}
/** @param PropertyHookType|'set'|'get' $type */
public function addHook(PropertyHookType|string $type, string $shortBody = ''): PropertyHook
{
$type = is_string($type) ? PropertyHookType::from($type) : $type;
return $this->hooks[$type->value] = (new PropertyHook)
->setBody($shortBody, short: true);
}
/** @param PropertyHookType|'set'|'get' $type */
public function getHook(PropertyHookType|string $type): ?PropertyHook
{
$type = is_string($type) ? PropertyHookType::from($type) : $type;
return $this->hooks[$type->value] ?? null;
}
/** @param PropertyHookType|'set'|'get' $type */
public function hasHook(PropertyHookType|string $type): bool
{
$type = is_string($type) ? PropertyHookType::from($type) : $type;
return isset($this->hooks[$type->value]);
}
}

View file

@ -0,0 +1,76 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette;
use Nette\PhpGenerator\TraitUse;
use function array_map, func_get_arg, func_num_args, is_array;
/**
* @internal
*/
trait TraitsAware
{
/** @var array<string, TraitUse> */
private array $traits = [];
/**
* Replaces all traits.
* @param list<TraitUse> $traits
*/
public function setTraits(array $traits): static
{
(function (TraitUse ...$traits) {})(...$traits);
$this->traits = [];
foreach ($traits as $trait) {
$this->traits[$trait->getName()] = $trait;
}
return $this;
}
/** @return array<string, TraitUse> */
public function getTraits(): array
{
return $this->traits;
}
/**
* Adds a method. If it already exists, throws an exception.
*/
public function addTrait(string $name): TraitUse
{
if (isset($this->traits[$name])) {
throw new Nette\InvalidStateException("Cannot add trait '$name', because it already exists.");
}
$this->traits[$name] = $trait = new TraitUse($name);
if (func_num_args() > 1 && is_array(func_get_arg(1))) { // back compatibility
trigger_error('Passing second argument to ' . __METHOD__ . '() is deprecated, use addResolution() instead.');
array_map($trait->addResolution(...), func_get_arg(1));
}
return $trait;
}
public function removeTrait(string $name): static
{
unset($this->traits[$name]);
return $this;
}
public function hasTrait(string $name): bool
{
return isset($this->traits[$name]);
}
}

View file

@ -0,0 +1,75 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator\Traits;
use Nette\PhpGenerator\Visibility;
/**
* @internal
*/
trait VisibilityAware
{
private ?Visibility $visibility = null;
/** @param Visibility|'public'|'protected'|'private'|null $value */
public function setVisibility(Visibility|string|null $value): static
{
$this->visibility = $value instanceof Visibility || $value === null
? $value
: Visibility::from($value);
return $this;
}
/** @return 'public'|'protected'|'private'|null */
public function getVisibility(): ?string
{
return $this->visibility?->value;
}
public function setPublic(): static
{
$this->visibility = Visibility::Public;
return $this;
}
public function isPublic(): bool
{
return $this->visibility === Visibility::Public || $this->visibility === null;
}
public function setProtected(): static
{
$this->visibility = Visibility::Protected;
return $this;
}
public function isProtected(): bool
{
return $this->visibility === Visibility::Protected;
}
public function setPrivate(): static
{
$this->visibility = Visibility::Private;
return $this;
}
public function isPrivate(): bool
{
return $this->visibility === Visibility::Private;
}
}

View file

@ -0,0 +1,121 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
use Nette;
use function implode, preg_match, preg_replace, str_contains;
/**
* PHP return, property and parameter types.
*/
class Type
{
public const
String = 'string',
Int = 'int',
Float = 'float',
Bool = 'bool',
Array = 'array',
Object = 'object',
Callable = 'callable',
Iterable = 'iterable',
Void = 'void',
Never = 'never',
Mixed = 'mixed',
True = 'true',
False = 'false',
Null = 'null',
Self = 'self',
Parent = 'parent',
Static = 'static';
#[\Deprecated('use Type::String')]
public const STRING = self::String;
#[\Deprecated('use Type::Int')]
public const INT = self::Int;
#[\Deprecated('use Type::Float')]
public const FLOAT = self::Float;
#[\Deprecated('use Type::Bool')]
public const BOOL = self::Bool;
#[\Deprecated('use Type::Array')]
public const ARRAY = self::Array;
#[\Deprecated('use Type::Object')]
public const OBJECT = self::Object;
#[\Deprecated('use Type::Callable')]
public const CALLABLE = self::Callable;
#[\Deprecated('use Type::Iterable')]
public const ITERABLE = self::Iterable;
#[\Deprecated('use Type::Void')]
public const VOID = self::Void;
#[\Deprecated('use Type::Never')]
public const NEVER = self::Never;
#[\Deprecated('use Type::Mixed')]
public const MIXED = self::Mixed;
#[\Deprecated('use Type::False')]
public const FALSE = self::False;
#[\Deprecated('use Type::Null')]
public const NULL = self::Null;
#[\Deprecated('use Type::Self')]
public const SELF = self::Self;
#[\Deprecated('use Type::Parent')]
public const PARENT = self::Parent;
#[\Deprecated('use Type::Static')]
public const STATIC = self::Static;
public static function nullable(string $type, bool $nullable = true): string
{
if (str_contains($type, '&')) {
return $nullable
? throw new Nette\InvalidArgumentException('Intersection types cannot be nullable.')
: $type;
}
$nnType = preg_replace('#^\?|^null\||\|null(?=\||$)#i', '', $type);
$always = (bool) preg_match('#^(null|mixed)$#i', $nnType);
if ($nullable) {
return match (true) {
$always, $type !== $nnType => $type,
str_contains($type, '|') => $type . '|null',
default => '?' . $type,
};
} else {
return $always
? throw new Nette\InvalidArgumentException("Type $type cannot be not nullable.")
: $nnType;
}
}
public static function union(string ...$types): string
{
return implode('|', $types);
}
public static function intersection(string ...$types): string
{
return implode('&', $types);
}
}

View file

@ -0,0 +1,19 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\PhpGenerator;
/**
* Member visibility.
*/
enum Visibility: string
{
case Public = 'public';
case Protected = 'protected';
case Private = 'private';
}

49
vendor/nette/schema/composer.json vendored Normal file
View file

@ -0,0 +1,49 @@
{
"name": "nette/schema",
"description": "📐 Nette Schema: validating data structures against a given Schema.",
"keywords": ["nette", "config"],
"homepage": "https://nette.org",
"license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"require": {
"php": "8.1 - 8.5",
"nette/utils": "^4.0"
},
"require-dev": {
"nette/tester": "^2.6",
"tracy/tracy": "^2.8",
"phpstan/phpstan": "^2.1.39@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0"
},
"autoload": {
"classmap": ["src/"],
"psr-4": {
"Nette\\": "src"
}
},
"minimum-stability": "dev",
"scripts": {
"phpstan": "phpstan analyse",
"tester": "tester tests -s"
},
"extra": {
"branch-alias": {
"dev-master": "1.3-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}

60
vendor/nette/schema/license.md vendored Normal file
View file

@ -0,0 +1,60 @@
Licenses
========
Good news! You may use Nette Framework under the terms of either
the New BSD License or the GNU General Public License (GPL) version 2 or 3.
The BSD License is recommended for most projects. It is easy to understand and it
places almost no restrictions on what you can do with the framework. If the GPL
fits better to your project, you can use the framework under this license.
You don't have to notify anyone which license you are using. You can freely
use Nette Framework in commercial projects as long as the copyright header
remains intact.
Please be advised that the name "Nette Framework" is a protected trademark and its
usage has some limitations. So please do not use word "Nette" in the name of your
project or top-level domain, and choose a name that stands on its own merits.
If your stuff is good, it will not take long to establish a reputation for yourselves.
New BSD License
---------------
Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of "Nette Framework" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright owner or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
GNU General Public License
--------------------------
GPL licenses are very very long, so instead of including them here we offer
you URLs with full text:
- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html)
- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)

536
vendor/nette/schema/readme.md vendored Normal file
View file

@ -0,0 +1,536 @@
# Nette Schema
[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema)
[![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions)
[![Coverage Status](https://coveralls.io/repos/github/nette/schema/badge.svg?branch=master)](https://coveralls.io/github/nette/schema?branch=master)
[![Latest Stable Version](https://poser.pugx.org/nette/schema/v/stable)](https://github.com/nette/schema/releases)
[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/schema/blob/master/license.md)
Introduction
============
A practical library for validation and normalization of data structures against a given schema with a smart & easy-to-understand API.
Documentation can be found on the [website](https://doc.nette.org/schema).
Installation:
```shell
composer require nette/schema
```
It requires PHP version 8.1 and supports PHP up to 8.5.
[Support Me](https://github.com/sponsors/dg)
--------------------------------------------
Do you like Nette Schema? Are you looking forward to the new features?
[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg)
Thank you!
Basic Usage
-----------
In variable `$schema` we have a validation schema (what exactly this means and how to create it we will say later) and in variable `$data` we have a data structure that we want to validate and normalize. This can be, for example, data sent by the user through an API, configuration file, etc.
The task is handled by the [Nette\Schema\Processor](https://api.nette.org/schema/master/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception on error.
```php
$processor = new Nette\Schema\Processor;
try {
$normalized = $processor->process($schema, $data);
} catch (Nette\Schema\ValidationException $e) {
echo 'Data is invalid: ' . $e->getMessage();
}
```
Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects.
Defining Schema
---------------
And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it, we actually define expectations of what the data should look like. Let's say that the input data must be a structure (e.g. an array) containing elements `processRefund` of type bool and `refundAmount` of type int.
```php
use Nette\Schema\Expect;
$schema = Expect::structure([
'processRefund' => Expect::bool(),
'refundAmount' => Expect::int(),
]);
```
We believe that the schema definition looks clear, even if you see it for the very first time.
Lets send the following data for validation:
```php
$data = [
'processRefund' => true,
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, it passes
```
The output, i.e. the value `$normalized`, is the object `stdClass`. If we want the output to be an array, we add a cast to schema `Expect::structure([...])->castTo('array')`.
All elements of the structure are optional and have a default value `null`. Example:
```php
$data = [
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, it passes
// $normalized = {'processRefund' => null, 'refundAmount' => 17}
```
The fact that the default value is `null` does not mean that it would be accepted in the input data `'processRefund' => null`. No, the input must be boolean, i.e. only `true` or `false`. We would have to explicitly allow `null` via `Expect::bool()->nullable()`.
An item can be made mandatory using `Expect::bool()->required()`. We change the default value to `false` using `Expect::bool()->default(false)` or shortly using `Expect::bool(false)`.
And what if we wanted to accept `1` and `0` besides booleans? Then we list the allowed values, which we will also normalize to boolean:
```php
$schema = Expect::structure([
'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'),
'refundAmount' => Expect::int(),
]);
$normalized = $processor->process($schema, $data);
is_bool($normalized->processRefund); // true
```
Now you know the basics of how the schema is defined and how the individual elements of the structure behave. We will now show what all the other elements can be used in defining a schema.
Data Types: type()
------------------
All standard PHP data types can be listed in the schema:
```php
Expect::string($default = null)
Expect::int($default = null)
Expect::float($default = null)
Expect::bool($default = null)
Expect::null()
Expect::array($default = [])
```
And then all types [supported by the Validators](https://doc.nette.org/validators#toc-expected-types) via `Expect::type('scalar')` or abbreviated `Expect::scalar()`. Also class or interface names are accepted, e.g. `Expect::type('AddressEntity')`.
You can also use union notation:
```php
Expect::type('bool|string|array')
```
The default value is always `null` except for `array` and `list`, where it is an empty array. (A list is an array indexed in ascending order of numeric keys from zero, that is, a non-associative array).
Array of Values: arrayOf() listOf()
-----------------------------------
The array is too general structure, it is more useful to specify exactly what elements it can contain. For example, an array whose elements can only be strings:
```php
$schema = Expect::arrayOf('string');
$processor->process($schema, ['hello', 'world']); // OK
$processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK
$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string
```
The second parameter can be used to specify keys (since version 1.2):
```php
$schema = Expect::arrayOf('string', 'int');
$processor->process($schema, ['hello', 'world']); // OK
$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not int
```
The list is an indexed array:
```php
$schema = Expect::listOf('string');
$processor->process($schema, ['a', 'b']); // OK
$processor->process($schema, ['a', 123]); // ERROR: 123 is not a string
$processor->process($schema, ['key' => 'a']); // ERROR: is not a list
$processor->process($schema, [1 => 'a', 0 => 'b']); // ERROR: is not a list
```
The parameter can also be a schema, so we can write:
```php
Expect::arrayOf(Expect::bool())
```
The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`.
Enumeration: anyOf()
--------------------
`anyOf()` is a set of values ​​or schemas that a value can be. Here's how to write an array of elements that can be either `'a'`, `true`, or `null`:
```php
$schema = Expect::listOf(
Expect::anyOf('a', true, null),
);
$processor->process($schema, ['a', true, null, 'a']); // OK
$processor->process($schema, ['a', false]); // ERROR: false does not belong there
```
The enumeration elements can also be schemas:
```php
$schema = Expect::listOf(
Expect::anyOf(Expect::string(), true, null),
);
$processor->process($schema, ['foo', true, null, 'bar']); // OK
$processor->process($schema, [123]); // ERROR
```
The `anyOf()` method accepts variants as individual parameters, not as array. To pass it an array of values, use the unpacking operator `anyOf(...$variants)`.
The default value is `null`. Use the `firstIsDefault()` method to make the first element the default:
```php
// default is 'hello'
Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault();
```
Structures
----------
Structures are objects with defined keys. Each of these key => value pairs is referred to as a "property":
Structures accept arrays and objects and return objects `stdClass` (unless you change it with `castTo('array')`, etc.).
By default, all properties are optional and have a default value of `null`. You can define mandatory properties using `required()`:
```php
$schema = Expect::structure([
'required' => Expect::string()->required(),
'optional' => Expect::string(), // the default value is null
]);
$processor->process($schema, ['optional' => '']);
// ERROR: option 'required' is missing
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo', 'optional' => null}
```
If you do not want to output properties with only a default value, use `skipDefaults()`:
```php
$schema = Expect::structure([
'required' => Expect::string()->required(),
'optional' => Expect::string(),
])->skipDefaults();
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo'}
```
Although `null` is the default value of the `optional` property, it is not allowed in the input data (the value must be a string). Properties accepting `null` are defined using `nullable()`:
```php
$schema = Expect::structure([
'optional' => Expect::string(),
'nullable' => Expect::string()->nullable(),
]);
$processor->process($schema, ['optional' => null]);
// ERROR: 'optional' expects to be string, null given.
$processor->process($schema, ['nullable' => null]);
// OK, returns {'optional' => null, 'nullable' => null}
```
By default, there can be no extra items in the input data:
```php
$schema = Expect::structure([
'key' => Expect::string(),
]);
$processor->process($schema, ['additional' => 1]);
// ERROR: Unexpected item 'additional'
```
Which we can change with `otherItems()`. As a parameter, we will specify the schema for each extra element:
```php
$schema = Expect::structure([
'key' => Expect::string(),
])->otherItems(Expect::int());
$processor->process($schema, ['additional' => 1]); // OK
$processor->process($schema, ['additional' => true]); // ERROR
```
Deprecations
------------
You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()`:
```php
$schema = Expect::structure([
'old' => Expect::int()->deprecated('The item %path% is deprecated'),
]);
$processor->process($schema, ['old' => 1]); // OK
$processor->getWarnings(); // ["The item 'old' is deprecated"]
```
Ranges: min() max()
-------------------
Use `min()` and `max()` to limit the number of elements for arrays:
```php
// array, at least 10 items, maximum 20 items
Expect::array()->min(10)->max(20);
```
For strings, limit their length:
```php
// string, at least 10 characters long, maximum 20 characters
Expect::string()->min(10)->max(20);
```
For numbers, limit their value:
```php
// integer, between 10 and 20 inclusive
Expect::int()->min(10)->max(20);
```
Of course, it is possible to mention only `min()`, or only `max()`:
```php
// string, maximum 20 characters
Expect::string()->max(20);
```
Regular Expressions: pattern()
------------------------------
Using `pattern()`, you can specify a regular expression which the **whole** input string must match (i.e. as if it were wrapped in characters `^` a `$`):
```php
// just 9 digits
Expect::string()->pattern('\d{9}');
```
Custom Assertions: assert()
---------------------------
You can add any other restrictions using `assert(callable $fn)`.
```php
$countIsEven = fn($v) => count($v) % 2 === 0;
$schema = Expect::arrayOf('string')
->assert($countIsEven); // the count must be even
$processor->process($schema, ['a', 'b']); // OK
$processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even
```
Or
```php
Expect::string()->assert('is_file'); // the file must exist
```
You can add your own description for each assertion. It will be part of the error message.
```php
$schema = Expect::arrayOf('string')
->assert($countIsEven, 'Even items in array');
$processor->process($schema, ['a', 'b', 'c']);
// Failed assertion "Even items in array" for item with value array.
```
The method can be called repeatedly to add multiple constraints. It can be intermixed with calls to `transform()` and `castTo()`.
Transformation: transform()
---------------------------
Successfully validated data can be modified using a custom function:
```php
// conversion to uppercase:
Expect::string()->transform(fn(string $s) => strtoupper($s));
```
The method can be called repeatedly to add multiple transformations. It can be intermixed with calls to `assert()` and `castTo()`. The operations will be executed in the order in which they are declared:
```php
Expect::type('string|int')
->castTo('string')
->assert('ctype_lower', 'All characters must be lowercased')
->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase
```
The `transform()` method can both transform and validate the value simultaneously. This is often simpler and less redundant than chaining `transform()` and `assert()`. For this purpose, the function receives a [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object with an `addError()` method, which can be used to add information about validation issues:
```php
Expect::string()
->transform(function (string $s, Nette\Schema\Context $context) {
if (!ctype_lower($s)) {
$context->addError('All characters must be lowercased', 'my.case.error');
return null;
}
return strtoupper($s);
});
```
Casting: castTo()
-----------------
Successfully validated data can be cast:
```php
Expect::scalar()->castTo('string');
```
In addition to native PHP types, you can also cast to classes. It distinguishes whether it is a simple class without a constructor or a class with a constructor. If the class has no constructor, an instance of it is created and all elements of the structure are written to its properties:
```php
class Info
{
public bool $processRefund;
public int $refundAmount;
}
Expect::structure([
'processRefund' => Expect::bool(),
'refundAmount' => Expect::int(),
])->castTo(Info::class);
// creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount
```
If the class has a constructor, the elements of the structure are passed as named parameters to the constructor:
```php
class Info
{
public function __construct(
public bool $processRefund,
public int $refundAmount,
) {
}
}
// creates $obj = new Info(processRefund: ..., refundAmount: ...)
```
Casting combined with a scalar parameter creates an object and passes the value as the sole parameter to the constructor:
```php
Expect::string()->castTo(DateTime::class);
// creates new DateTime(...)
```
Normalization: before()
-----------------------
Prior to the validation itself, the data can be normalized using the method `before()`. As an example, let's have an element that must be an array of strings (eg `['a', 'b', 'c']`), but receives input in the form of a string `a b c`:
```php
$explode = fn($v) => explode(' ', $v);
$schema = Expect::arrayOf('string')
->before($explode);
$normalized = $processor->process($schema, 'a b c');
// OK, returns ['a', 'b', 'c']
```
Mapping to Objects: from()
--------------------------
You can generate structure schema from the class. Example:
```php
class Config
{
/** @var string */
public $name;
/** @var string|null */
public $password;
/** @var bool */
public $admin = false;
}
$schema = Expect::from(new Config);
$data = [
'name' => 'jeff',
];
$normalized = $processor->process($schema, $data);
// $normalized instanceof Config
// $normalized = {'name' => 'jeff', 'password' => null, 'admin' => false}
```
If you are using PHP 7.4 or higher, you can use native types:
```php
class Config
{
public string $name;
public ?string $password;
public bool $admin = false;
}
$schema = Expect::from(new Config);
```
Anonymous classes are also supported:
```php
$schema = Expect::from(new class {
public string $name;
public ?string $password;
public bool $admin = false;
});
```
Because the information obtained from the class definition may not be sufficient, you can add a custom schema for the elements with the second parameter:
```php
$schema = Expect::from(new Config, [
'name' => Expect::string()->pattern('\w:.*'),
]);
```

View file

@ -0,0 +1,59 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use function count;
/**
* Accumulates errors and warnings during schema validation and tracks the current path.
*/
final class Context
{
public bool $skipDefaults = false;
/** @var list<int|string> */
public array $path = [];
public bool $isKey = false;
/** @var list<Message> */
public array $errors = [];
/** @var list<Message> */
public array $warnings = [];
/** @var list<array{DynamicParameter, string, list<int|string>}> */
public array $dynamics = [];
/** @param array<string, mixed> $variables */
public function addError(string $message, string $code, array $variables = []): Message
{
$variables['isKey'] = $this->isKey;
return $this->errors[] = new Message($message, $code, $this->path, $variables);
}
/** @param array<string, mixed> $variables */
public function addWarning(string $message, string $code, array $variables = []): Message
{
return $this->warnings[] = new Message($message, $code, $this->path, $variables);
}
/**
* Returns a closure that returns true as long as no new errors have been added since the call.
* @return \Closure(): bool
*/
public function createChecker(): \Closure
{
$count = count($this->errors);
return fn(): bool => $count === count($this->errors);
}
}

View file

@ -0,0 +1,13 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
interface DynamicParameter
{
}

View file

@ -0,0 +1,162 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use function array_merge, array_unique, implode, is_array;
/**
* Schema that accepts any of a fixed set of values or sub-schemas (union type / enumeration).
*/
final class AnyOf implements Schema
{
use Base;
/** @var mixed[] */
private array $set;
public function __construct(mixed ...$set)
{
if (!$set) {
throw new Nette\InvalidStateException('The enumeration must not be empty.');
}
$this->set = $set;
}
/**
* Sets the first variant as the default value (instead of null).
*/
public function firstIsDefault(): self
{
$this->default = $this->set[0];
return $this;
}
/**
* Allows null as an accepted value in addition to the defined variants.
*/
public function nullable(): self
{
$this->set[] = null;
return $this;
}
/**
* Allows the value to be a DynamicParameter as an accepted variant.
*/
public function dynamic(): self
{
$this->set[] = new Type(Nette\Schema\DynamicParameter::class);
return $this;
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
return $this->doNormalize($value, $context);
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
return $value;
}
return Helpers::merge($value, $base);
}
public function complete(mixed $value, Context $context): mixed
{
$isOk = $context->createChecker();
$value = $this->findAlternative($value, $context);
$isOk() && $value = $this->doTransform($value, $context);
return $isOk() ? $value : null;
}
private function findAlternative(mixed $value, Context $context): mixed
{
$expecteds = $innerErrors = [];
foreach ($this->set as $item) {
if ($item instanceof Schema) {
$dolly = new Context;
$dolly->skipDefaults = $context->skipDefaults;
$dolly->isKey = $context->isKey;
$dolly->path = $context->path;
$res = $item->complete($item->normalize($value, $dolly), $dolly);
if (!$dolly->errors) {
$context->warnings = array_merge($context->warnings, $dolly->warnings);
$context->dynamics = array_merge($context->dynamics, $dolly->dynamics);
return $res;
}
foreach ($dolly->errors as $error) {
if ($error->path !== $context->path || empty($error->variables['expected'])) {
$innerErrors[] = $error;
} else {
$expecteds[] = $error->variables['expected'];
}
}
} else {
if ($item === $value) {
return $value;
}
$expecteds[] = Nette\Schema\Helpers::formatValue($item);
}
}
if ($innerErrors) {
$context->errors = array_merge($context->errors, $innerErrors);
} else {
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Nette\Schema\Message::TypeMismatch,
[
'value' => $value,
'expected' => implode('|', array_unique($expecteds)),
],
);
}
return null;
}
public function completeDefault(Context $context): mixed
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
);
return null;
}
if ($this->default instanceof Schema) {
return $this->default->completeDefault($context);
}
return $this->default;
}
}

View file

@ -0,0 +1,182 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use function count, is_string;
/**
* @internal
*/
trait Base
{
private bool $required = false;
private mixed $default = null;
/** @var ?\Closure(mixed): mixed */
private ?\Closure $before = null;
/** @var list<\Closure(mixed, Context): mixed> */
private array $transforms = [];
private ?string $deprecated = null;
public function default(mixed $value): self
{
$this->default = $value;
return $this;
}
public function required(bool $state = true): self
{
$this->required = $state;
return $this;
}
/**
* Sets a pre-normalization callback applied to the raw input value before any validation.
* @param callable(mixed): mixed $handler
*/
public function before(callable $handler): self
{
$this->before = $handler(...);
return $this;
}
/**
* Casts the validated value to a built-in type or instantiates the given class.
*/
public function castTo(string $type): self
{
return $this->transform(Helpers::getCastStrategy($type));
}
/**
* Adds a post-validation transformation callback. The handler may also report errors via Context.
* @param callable(mixed, Context): mixed $handler
*/
public function transform(callable $handler): self
{
$this->transforms[] = $handler(...);
return $this;
}
/**
* Adds a custom validation assertion; optionally describe it for error messages.
* @param callable(mixed): bool $handler
*/
public function assert(callable $handler, ?string $description = null): self
{
$expected = $description ?? (is_string($handler) ? "$handler()" : '#' . count($this->transforms));
return $this->transform(function ($value, Context $context) use ($handler, $description, $expected) {
if ($handler($value)) {
return $value;
}
$context->addError(
'Failed assertion ' . ($description ? "'%assertion%'" : '%assertion%') . ' for %label% %path% with value %value%.',
Nette\Schema\Message::FailedAssertion,
['value' => $value, 'assertion' => $expected],
);
return null;
});
}
/**
* Marks the item as deprecated; emits a warning with the given message when the item is used.
*/
public function deprecated(string $message = 'The item %path% is deprecated.'): self
{
$this->deprecated = $message;
return $this;
}
public function completeDefault(Context $context): mixed
{
if ($this->required) {
$context->addError(
'The mandatory item %path% is missing.',
Nette\Schema\Message::MissingItem,
);
return null;
}
return $this->default;
}
public function doNormalize(mixed $value, Context $context): mixed
{
if ($this->before) {
$value = ($this->before)($value);
}
return $value;
}
private function doDeprecation(Context $context): void
{
if ($this->deprecated !== null) {
$context->addWarning(
$this->deprecated,
Nette\Schema\Message::Deprecated,
);
}
}
private function doTransform(mixed $value, Context $context): mixed
{
$isOk = $context->createChecker();
foreach ($this->transforms as $handler) {
$value = $handler($value, $context);
if (!$isOk()) {
return null;
}
}
return $value;
}
/** @deprecated use Nette\Schema\Helpers::validateType() */
private function doValidate(mixed $value, string $expected, Context $context): bool
{
$isOk = $context->createChecker();
Helpers::validateType($value, $expected, $context);
return $isOk();
}
/**
* @deprecated use Nette\Schema\Helpers::validateRange()
* @param array{?float, ?float} $range
*/
private static function doValidateRange(mixed $value, array $range, Context $context, string $types = ''): bool
{
$isOk = $context->createChecker();
Helpers::validateRange($value, $range, $context, $types);
return $isOk();
}
/** @deprecated use doTransform() */
private function doFinalize(mixed $value, Context $context): mixed
{
return $this->doTransform($value, $context);
}
}

View file

@ -0,0 +1,231 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette;
use Nette\Schema\Context;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use function array_diff_key, array_fill_keys, array_key_exists, array_keys, array_map, array_merge, array_pop, array_values, is_array, is_object, strval;
final class Structure implements Schema
{
use Base;
/** @var Schema[] */
private array $items;
/** for array|list */
private ?Schema $otherItems = null;
/** @var array{?int, ?int} */
private array $range = [null, null];
private bool $skipDefaults = false;
/** @param Schema[] $shape */
public function __construct(array $shape)
{
(function (Schema ...$items) {})(...array_values($shape));
$this->items = $shape;
$this->castTo('object');
$this->required = true;
}
/**
* Not supported for structures; always throws.
*/
public function default(mixed $value): self
{
throw new Nette\InvalidStateException('Structure cannot have default value.');
}
public function min(?int $min): self
{
$this->range[0] = $min;
return $this;
}
public function max(?int $max): self
{
$this->range[1] = $max;
return $this;
}
/**
* Allows extra keys not defined in the shape, validating their values against the given type.
*/
public function otherItems(string|Schema $type = 'mixed'): self
{
$this->otherItems = $type instanceof Schema ? $type : new Type($type);
return $this;
}
/**
* When enabled, properties whose value equals the default are omitted from the output.
*/
public function skipDefaults(bool $state = true): self
{
$this->skipDefaults = $state;
return $this;
}
/**
* Creates a new structure by merging this shape with additional properties.
* @param Schema[]|self $shape
*/
public function extend(array|self $shape): self
{
$shape = $shape instanceof self ? $shape->items : $shape;
return new self(array_merge($this->items, $shape));
}
/** @return Schema[] */
public function getShape(): array
{
return $this->items;
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
}
$value = $this->doNormalize($value, $context);
if (is_object($value)) {
$value = (array) $value;
}
if (is_array($value)) {
foreach ($value as $key => $val) {
$itemSchema = $this->items[$key] ?? $this->otherItems;
if ($itemSchema) {
$context->path[] = $key;
$value[$key] = $itemSchema->normalize($val, $context);
array_pop($context->path);
}
}
if ($prevent) {
$value[Helpers::PreventMerging] = true;
}
}
return $value;
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
$base = null;
}
if (is_array($value) && is_array($base)) {
$index = $this->otherItems === null ? null : 0;
foreach ($value as $key => $val) {
if ($key === $index) {
$base[] = $val;
$index++;
} else {
$base[$key] = array_key_exists($key, $base) && ($itemSchema = $this->items[$key] ?? $this->otherItems)
? $itemSchema->merge($val, $base[$key])
: $val;
}
}
return $base;
}
return $value ?? $base;
}
public function complete(mixed $value, Context $context): mixed
{
if ($value === null) {
$value = []; // is unable to distinguish null from array in NEON
}
$this->doDeprecation($context);
$isOk = $context->createChecker();
Helpers::validateType($value, 'array', $context);
$isOk() && Helpers::validateRange($value, $this->range, $context);
$isOk() && $this->validateItems($value, $context);
$isOk() && $value = $this->doTransform($value, $context);
return $isOk() ? $value : null;
}
/** @param array<mixed> $value */
private function validateItems(array &$value, Context $context): void
{
$items = $this->items;
if ($extraKeys = array_keys(array_diff_key($value, $items))) {
if ($this->otherItems) {
$items += array_fill_keys($extraKeys, $this->otherItems);
} else {
$keys = array_map(strval(...), array_keys($items));
foreach ($extraKeys as $key) {
$hint = Nette\Utils\Helpers::getSuggestion($keys, (string) $key);
$context->addError(
'Unexpected item %path%' . ($hint ? ", did you mean '%hint%'?" : '.'),
Nette\Schema\Message::UnexpectedItem,
['hint' => $hint],
)->path[] = $key;
}
}
}
foreach ($items as $itemKey => $itemVal) {
$context->path[] = $itemKey;
if (array_key_exists($itemKey, $value)) {
$value[$itemKey] = $itemVal->complete($value[$itemKey], $context);
} else {
$default = $itemVal->completeDefault($context); // checks required item
if (!$context->skipDefaults && !$this->skipDefaults) {
$value[$itemKey] = $default;
}
}
array_pop($context->path);
}
}
public function completeDefault(Context $context): mixed
{
if (!$this->required) {
return null;
}
// the item is missing in the input, do not report it as used deprecated
$deprecated = $this->deprecated;
$this->deprecated = null;
try {
return $this->complete([], $context);
} finally {
$this->deprecated = $deprecated;
}
}
}

View file

@ -0,0 +1,227 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema\Elements;
use Nette\Schema\Context;
use Nette\Schema\DynamicParameter;
use Nette\Schema\Helpers;
use Nette\Schema\Schema;
use Nette\Utils\Validators;
use function array_key_exists, array_pop, implode, is_array, str_replace, strpos;
final class Type implements Schema
{
use Base;
private string $type;
private ?Schema $itemsValue = null;
private ?Schema $itemsKey = null;
/** @var array{?float, ?float} */
private array $range = [null, null];
private ?string $pattern = null;
private bool $merge = true;
public function __construct(string $type)
{
$defaults = ['list' => [], 'array' => []];
$this->type = $type;
$this->default = strpos($type, '[]') ? [] : $defaults[$type] ?? null;
}
/**
* Allows the value to be null in addition to the declared type.
*/
public function nullable(): self
{
$this->type = 'null|' . $this->type;
return $this;
}
/**
* Controls whether the default value is merged with the input array (enabled by default).
*/
public function mergeDefaults(bool $state = true): self
{
$this->merge = $state;
return $this;
}
/**
* Allows the value to be a DynamicParameter, which is recorded for deferred validation.
*/
public function dynamic(): self
{
$this->type = DynamicParameter::class . '|' . $this->type;
return $this;
}
public function min(?float $min): self
{
$this->range[0] = $min;
return $this;
}
public function max(?float $max): self
{
$this->range[1] = $max;
return $this;
}
/**
* @internal use arrayOf() or listOf()
*/
public function items(string|Schema $valueType = 'mixed', string|Schema|null $keyType = null): self
{
$this->itemsValue = $valueType instanceof Schema
? $valueType
: new self($valueType);
$this->itemsKey = $keyType instanceof Schema || $keyType === null
? $keyType
: new self($keyType);
return $this;
}
/**
* Sets a regex pattern the string value must match entirely (anchored to start and end).
*/
public function pattern(?string $pattern): self
{
$this->pattern = $pattern;
return $this;
}
/********************* processing ****************d*g**/
public function normalize(mixed $value, Context $context): mixed
{
if ($prevent = (is_array($value) && isset($value[Helpers::PreventMerging]))) {
unset($value[Helpers::PreventMerging]);
}
$value = $this->doNormalize($value, $context);
if (is_array($value) && $this->itemsValue) {
$res = [];
foreach ($value as $key => $val) {
$context->path[] = $key;
$context->isKey = true;
$key = $this->itemsKey
? $this->itemsKey->normalize($key, $context)
: $key;
$context->isKey = false;
$res[$key] = $this->itemsValue->normalize($val, $context);
array_pop($context->path);
}
$value = $res;
}
if ($prevent && is_array($value)) {
$value[Helpers::PreventMerging] = true;
}
return $value;
}
public function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
return $value;
}
if (is_array($value) && is_array($base) && $this->itemsValue) {
$index = 0;
foreach ($value as $key => $val) {
if ($key === $index) {
$base[] = $val;
$index++;
} else {
$base[$key] = array_key_exists($key, $base)
? $this->itemsValue->merge($val, $base[$key])
: $val;
}
}
return $base;
}
return Helpers::merge($value, $base);
}
public function complete(mixed $value, Context $context): mixed
{
$merge = $this->merge;
if (is_array($value) && isset($value[Helpers::PreventMerging])) {
unset($value[Helpers::PreventMerging]);
$merge = false;
}
if ($value === null && is_array($this->default) && !Validators::is(null, $this->type)) {
$value = []; // is unable to distinguish null from array in NEON
}
$this->doDeprecation($context);
$isOk = $context->createChecker();
Helpers::validateType($value, $this->type, $context);
$isOk() && Helpers::validateRange($value, $this->range, $context, $this->type);
$isOk() && $value !== null && $this->pattern !== null && Helpers::validatePattern($value, $this->pattern, $context);
$isOk() && is_array($value) && $this->validateItems($value, $context);
$isOk() && $merge && $value !== null && $value = Helpers::merge($value, $this->default);
$isOk() && $value = $this->doTransform($value, $context);
if (!$isOk()) {
return null;
}
if ($value instanceof DynamicParameter && $this->type !== DynamicParameter::class) {
$expected = $this->type . ($this->range === [null, null] ? '' : ':' . implode('..', $this->range));
$context->dynamics[] = [$value, str_replace(DynamicParameter::class . '|', '', $expected), $context->path];
}
return $value;
}
/** @param array<mixed> $value */
private function validateItems(array &$value, Context $context): void
{
if (!($itemsValue = $this->itemsValue)) {
return;
}
$res = [];
foreach ($value as $key => $val) {
$context->path[] = $key;
$context->isKey = true;
$isKeyOk = $context->createChecker();
$key = $this->itemsKey ? $this->itemsKey->complete($key, $context) : $key;
$context->isKey = false;
$keyOk = $isKeyOk();
$val = $itemsValue->complete($val, $context);
if ($keyOk) {
$res[$key] = $val;
}
array_pop($context->path);
}
$value = $res;
}
}

View file

@ -0,0 +1,139 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
use Nette\Schema\Elements\AnyOf;
use Nette\Schema\Elements\Structure;
use Nette\Schema\Elements\Type;
use function is_object;
/**
* Schema generator.
*
* @method static Type scalar($default = null)
* @method static Type string($default = null)
* @method static Type int($default = null)
* @method static Type float($default = null)
* @method static Type bool($default = null)
* @method static Type null()
* @method static Type list($default = [])
* @method static Type mixed($default = null)
* @method static Type email($default = null)
* @method static Type unicode($default = null)
*/
final class Expect
{
/** @param list<mixed> $args */
public static function __callStatic(string $name, array $args): Type
{
$type = new Type($name);
if ($args) {
$type->default($args[0]);
}
return $type;
}
/**
* Creates a schema for a custom type expression (e.g., 'int|string', 'null|float').
*/
public static function type(string $type): Type
{
return new Type($type);
}
/**
* Creates a union schema that accepts any of the given values or sub-schemas.
*/
public static function anyOf(mixed ...$set): AnyOf
{
return new AnyOf(...$set);
}
/**
* Creates a structure schema with defined properties; output is stdClass.
* @param Schema[] $shape
*/
public static function structure(array $shape): Structure
{
return new Structure($shape);
}
/**
* Generates a structure schema from a class instance by reflecting its properties or constructor parameters.
* @param array<string, Schema> $items Optional overrides for specific properties.
*/
public static function from(object $object, array $items = []): Structure
{
$ro = new \ReflectionObject($object);
$props = $ro->hasMethod('__construct')
? $ro->getMethod('__construct')->getParameters()
: $ro->getProperties();
foreach ($props as $prop) {
$name = $prop->getName();
if (!isset($items[$name])) {
$type = Helpers::getPropertyType($prop) ?? 'mixed';
$item = new Type($type);
if ($prop instanceof \ReflectionProperty ? $prop->isInitialized($object) : $prop->isOptional()) {
$def = ($prop instanceof \ReflectionProperty ? $prop->getValue($object) : $prop->getDefaultValue());
if (is_object($def)) {
$item = static::from($def);
} elseif ($def === null && !Nette\Utils\Validators::is(null, $type)) {
$item->required();
} else {
$item->default($def);
}
} else {
$item->required();
}
$items[$name] = $item;
}
}
return (new Structure($items))->castTo($ro->getName());
}
/**
* Creates an array schema. When passed Schema elements, behaves like structure() but outputs an array.
* Without Schema elements, creates a plain array type with the given default value.
* @param mixed[] $shape
*/
public static function array(?array $shape = []): Structure|Type
{
$shape ??= [];
return Nette\Utils\Arrays::first($shape) instanceof Schema
? (new Structure($shape))->castTo('array')
: (new Type('array'))->default($shape);
}
/**
* Creates an associative or indexed array schema where every value matches the given type.
*/
public static function arrayOf(string|Schema $valueType, string|Schema|null $keyType = null): Type
{
return (new Type('array'))->items($valueType, $keyType);
}
/**
* Creates a list schema (sequentially indexed from 0) where every element matches the given type.
*/
public static function listOf(string|Schema $type): Type
{
return (new Type('list'))->items($type);
}
}

View file

@ -0,0 +1,231 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
use Nette\Utils\Reflection;
use function array_map, count, explode, get_debug_type, implode, in_array, is_array, is_float, is_int, is_object, is_scalar, is_string, is_subclass_of, method_exists, preg_match, preg_quote, preg_replace, preg_replace_callback, settype, str_replace, strlen, trim, var_export;
/**
* @internal
*/
final class Helpers
{
use Nette\StaticClass;
public const PreventMerging = '_prevent_merging';
/**
* Merges dataset. Left has higher priority than right one.
*/
public static function merge(mixed $value, mixed $base): mixed
{
if (is_array($value) && isset($value[self::PreventMerging])) {
unset($value[self::PreventMerging]);
return $value;
}
if (is_array($value) && is_array($base)) {
$index = 0;
foreach ($value as $key => $val) {
if ($key === $index) {
$base[] = $val;
$index++;
} else {
$base[$key] = static::merge($val, $base[$key] ?? null);
}
}
return $base;
} elseif ($value === null && is_array($base)) {
return $base;
} else {
return $value;
}
}
/**
* Returns the type of a property or parameter as a string, or null if not determinable.
*/
public static function getPropertyType(\ReflectionProperty|\ReflectionParameter $prop): ?string
{
if ($type = Nette\Utils\Type::fromReflection($prop)) {
return (string) $type;
} elseif (
($prop instanceof \ReflectionProperty)
&& ($type = preg_replace('#\s.*#', '', (string) self::parseAnnotation($prop, 'var')))
) {
$class = Reflection::getPropertyDeclaringClass($prop);
return preg_replace_callback('#[\w\\\]+#', fn($m) => Reflection::expandClassName($m[0], $class), $type);
}
return null;
}
/**
* Returns an annotation value.
* @param \ReflectionClass<object>|\ReflectionProperty $ref
*/
public static function parseAnnotation(\ReflectionClass|\ReflectionProperty $ref, string $name): ?string
{
if (!Reflection::areCommentsAvailable()) {
throw new Nette\InvalidStateException('You have to enable phpDoc comments in opcode cache.');
}
$re = '#[\s*]@' . preg_quote($name, '#') . '(?=\s|$)(?:[ \t]+([^@\s]\S*))?#';
if ($ref->getDocComment() && preg_match($re, trim($ref->getDocComment(), '/*'), $m)) {
return $m[1] ?? '';
}
return null;
}
/**
* Formats a value for use in error messages (e.g., 'hello', true, object stdClass).
*/
public static function formatValue(mixed $value): string
{
if ($value instanceof DynamicParameter) {
return 'dynamic';
} elseif (is_object($value)) {
return 'object ' . $value::class;
} elseif (is_string($value)) {
return "'" . Nette\Utils\Strings::truncate($value, 15, '...') . "'";
} elseif (is_scalar($value)) {
return var_export($value, return: true);
} else {
return get_debug_type($value);
}
}
/**
* Adds a TypeMismatch error to the context if the value does not match the expected type.
*/
public static function validateType(mixed $value, string $expected, Context $context): void
{
if (!Nette\Utils\Validators::is($value, $expected)) {
$expected = str_replace(DynamicParameter::class . '|', '', $expected);
$expected = str_replace(['|', ':'], [' or ', ' in range '], $expected);
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Message::TypeMismatch,
['value' => $value, 'expected' => $expected],
);
}
}
/**
* Adds a range error to the context if the value (or its length for strings/arrays) is outside the given range.
* @param array{?float, ?float} $range
*/
public static function validateRange(mixed $value, array $range, Context $context, string $types = ''): void
{
if (is_array($value) || is_string($value)) {
[$length, $label] = is_array($value)
? [count($value), 'items']
: (in_array('unicode', explode('|', $types), strict: true)
? [Nette\Utils\Strings::length($value), 'characters']
: [strlen($value), 'bytes']);
if (!self::isInRange($length, $range)) {
$context->addError(
"The length of %label% %path% expects to be in range %expected%, %length% $label given.",
Message::LengthOutOfRange,
['value' => $value, 'length' => $length, 'expected' => implode('..', $range)],
);
}
} elseif ((is_int($value) || is_float($value)) && !self::isInRange($value, $range)) {
$context->addError(
'The %label% %path% expects to be in range %expected%, %value% given.',
Message::ValueOutOfRange,
['value' => $value, 'expected' => implode('..', $range)],
);
}
}
/**
* Checks whether a value falls within the given [min, max] range (null means no bound).
* @param array{?float, ?float} $range
*/
public static function isInRange(mixed $value, array $range): bool
{
return ($range[0] === null || $value >= $range[0])
&& ($range[1] === null || $value <= $range[1]);
}
/**
* Adds a PatternMismatch error to the context if the value does not match the pattern.
*/
public static function validatePattern(string $value, string $pattern, Context $context): void
{
if (!preg_match("\x01^(?:$pattern)$\x01Du", $value)) {
$context->addError(
"The %label% %path% expects to match pattern '%pattern%', %value% given.",
Message::PatternMismatch,
['value' => $value, 'pattern' => $pattern],
);
}
}
/**
* Returns a closure that casts a value to the given type (built-in, backed enum, class with constructor, or plain class).
* @return \Closure(mixed, Context): mixed
*/
public static function getCastStrategy(string $type): \Closure
{
if (Nette\Utils\Validators::isBuiltinType($type)) {
return static function ($value) use ($type) {
settype($value, $type);
return $value;
};
} elseif (is_subclass_of($type, \BackedEnum::class)) {
return static function ($value, Context $context) use ($type) {
try {
return $type::from($value);
} catch (\TypeError | \ValueError) {
$context->addError(
'The %label% %path% expects to be %expected%, %value% given.',
Message::TypeMismatch,
['value' => $value, 'expected' => implode('|', array_map(fn(\BackedEnum $case) => self::formatValue($case->value), $type::cases()))],
);
return null;
}
};
} elseif (is_subclass_of($type, \UnitEnum::class)) {
throw new Nette\InvalidStateException("Cannot cast value to pure enum $type.");
}
$factory = method_exists($type, '__construct')
? static fn($value) => is_array($value) || $value instanceof \stdClass
? new $type(...(array) $value)
: new $type($value)
: static fn($value) => Nette\Utils\Arrays::toObject((array) $value, new $type);
return static function ($value) use ($factory, $type) {
try {
return $factory($value);
} catch (\Error $e) {
throw new Nette\InvalidStateException("Unable to cast value to $type: " . $e->getMessage(), 0, $e);
}
};
}
}

View file

@ -0,0 +1,97 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use function array_key_exists, implode, preg_replace_callback;
/**
* Represents a single validation error or warning with a message template, error code, path, and variables.
*/
final class Message
{
/** variables: {value: mixed, expected: string} */
public const TypeMismatch = 'schema.typeMismatch';
/** variables: {value: mixed, expected: string} */
public const ValueOutOfRange = 'schema.valueOutOfRange';
/** variables: {value: mixed, length: int, expected: string} */
public const LengthOutOfRange = 'schema.lengthOutOfRange';
/** variables: {value: string, pattern: string} */
public const PatternMismatch = 'schema.patternMismatch';
/** variables: {value: mixed, assertion: string} */
public const FailedAssertion = 'schema.failedAssertion';
/** no variables */
public const MissingItem = 'schema.missingItem';
/** variables: {hint: string} */
public const UnexpectedItem = 'schema.unexpectedItem';
/** no variables */
public const Deprecated = 'schema.deprecated';
/** @deprecated use Message::TypeMismatch */
public const TYPE_MISMATCH = self::TypeMismatch;
/** @deprecated use Message::ValueOutOfRange */
public const VALUE_OUT_OF_RANGE = self::ValueOutOfRange;
/** @deprecated use Message::LengthOutOfRange */
public const LENGTH_OUT_OF_RANGE = self::LengthOutOfRange;
/** @deprecated use Message::PatternMismatch */
public const PATTERN_MISMATCH = self::PatternMismatch;
/** @deprecated use Message::FailedAssertion */
public const FAILED_ASSERTION = self::FailedAssertion;
/** @deprecated use Message::MissingItem */
public const MISSING_ITEM = self::MissingItem;
/** @deprecated use Message::UnexpectedItem */
public const UNEXPECTED_ITEM = self::UnexpectedItem;
/** @deprecated use Message::Deprecated */
public const DEPRECATED = self::Deprecated;
public function __construct(
public string $message,
public string $code,
/** @var list<int|string> */
public array $path,
/** @var array<string, mixed> */
public array $variables = [],
) {
}
/**
* Formats the message template by substituting %variable% placeholders with their values.
*/
public function toString(): string
{
$vars = $this->variables;
$vars['label'] = empty($vars['isKey']) ? 'item' : 'key of item';
$vars['path'] = $this->path
? "'" . implode("\u{a0}›\u{a0}", $this->path) . "'"
: null;
$vars['value'] = Helpers::formatValue($vars['value'] ?? null);
return preg_replace_callback('~( ?)%(\w+)%~', function ($m) use ($vars) {
[, $space, $key] = $m;
return array_key_exists($key, $vars)
? ($vars[$key] === null ? '' : $space . $vars[$key])
: $m[0];
}, $this->message);
}
}

View file

@ -0,0 +1,102 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
/**
* Schema validator.
*/
final class Processor
{
/** @var list<\Closure(Context): void> */
public array $onNewContext = [];
private Context $context;
private bool $skipDefaults = false;
/**
* When enabled, properties with default values are omitted from the output.
*/
public function skipDefaults(bool $value = true): void
{
$this->skipDefaults = $value;
}
/**
* Normalizes and validates data. Result is a clean completed data.
* @throws ValidationException
*/
public function process(Schema $schema, mixed $data): mixed
{
$this->createContext();
$data = $schema->normalize($data, $this->context);
$this->throwErrors();
$data = $schema->complete($data, $this->context);
$this->throwErrors();
return $data;
}
/**
* Normalizes and validates and merges multiple data. Result is a clean completed data.
* @param list<mixed> $dataset
* @throws ValidationException
*/
public function processMultiple(Schema $schema, array $dataset): mixed
{
$this->createContext();
$flatten = null;
$first = true;
foreach ($dataset as $data) {
$data = $schema->normalize($data, $this->context);
$this->throwErrors();
$flatten = $first ? $data : $schema->merge($data, $flatten);
$first = false;
}
$data = $schema->complete($flatten, $this->context);
$this->throwErrors();
return $data;
}
/**
* Returns all deprecation warnings collected during the last processing run.
* @return list<string>
*/
public function getWarnings(): array
{
$res = [];
if (isset($this->context)) {
foreach ($this->context->warnings as $message) {
$res[] = $message->toString();
}
}
return $res;
}
private function throwErrors(): void
{
if ($this->context->errors) {
throw new ValidationException(null, $this->context->errors);
}
}
private function createContext(): void
{
$this->context = new Context;
$this->context->skipDefaults = $this->skipDefaults;
Nette\Utils\Arrays::invoke($this->onNewContext, $this->context);
}
}

View file

@ -0,0 +1,39 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
/**
* Defines the contract for schema elements used in data validation and normalization.
*/
interface Schema
{
/**
* Applies pre-processing transformations to the raw input value (e.g., via before() hooks).
* @return mixed
*/
function normalize(mixed $value, Context $context);
/**
* Merges two normalized values, with $value taking priority over $base.
* @return mixed
*/
function merge(mixed $value, mixed $base);
/**
* Validates the value and applies defaults, transforms, and assertions.
* @return mixed
*/
function complete(mixed $value, Context $context);
/**
* Returns the default value, or adds a missing-item error if the field is required.
* @return mixed
*/
function completeDefault(Context $context);
}

View file

@ -0,0 +1,50 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Schema;
use Nette;
/**
* Validation error.
*/
class ValidationException extends Nette\InvalidStateException
{
public function __construct(
?string $message,
/** @var list<Message> */
private readonly array $messages = [],
) {
parent::__construct($message ?? $messages[0]->toString());
}
/**
* Returns all validation error messages as formatted strings.
* @return list<string>
*/
public function getMessages(): array
{
$res = [];
foreach ($this->messages as $message) {
$res[] = $message->toString();
}
return $res;
}
/**
* Returns all validation error messages as Message objects.
* @return list<Message>
*/
public function getMessageObjects(): array
{
return $this->messages;
}
}

11
vendor/nette/utils/.phpstorm.meta.php vendored Normal file
View file

@ -0,0 +1,11 @@
<?php declare(strict_types=1);
namespace PHPSTORM_META;
override(\Nette\Utils\Arrays::get(0), elementType(0));
override(\Nette\Utils\Arrays::getRef(0), elementType(0));
override(\Nette\Utils\Arrays::grep(0), type(0));
override(\Nette\Utils\Arrays::toObject(0), type(1));
expectedArguments(\Nette\Utils\Image::resize(), 2, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover);
expectedArguments(\Nette\Utils\Image::calculateSize(), 4, \Nette\Utils\Image::ShrinkOnly, \Nette\Utils\Image::Stretch, \Nette\Utils\Image::OrSmaller, \Nette\Utils\Image::OrBigger, \Nette\Utils\Image::Cover);

61
vendor/nette/utils/composer.json vendored Normal file
View file

@ -0,0 +1,61 @@
{
"name": "nette/utils",
"description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.",
"keywords": ["nette", "images", "json", "password", "validation", "utility", "string", "array", "core", "slugify", "utf-8", "unicode", "paginator", "datetime"],
"homepage": "https://nette.org",
"license": ["BSD-3-Clause", "GPL-2.0-only", "GPL-3.0-only"],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"require": {
"php": "8.2 - 8.5"
},
"require-dev": {
"nette/tester": "^2.5",
"tracy/tracy": "^2.9",
"phpstan/phpstan": "^2.1@stable",
"phpstan/extension-installer": "^1.4@stable",
"nette/phpstan-rules": "^1.0",
"jetbrains/phpstorm-attributes": "^1.2"
},
"conflict": {
"nette/finder": "<3",
"nette/schema": "<1.2.2"
},
"suggest": {
"ext-iconv": "to use Strings::chr(), ord() and reverse()",
"ext-json": "to use Nette\\Utils\\Json",
"ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()",
"ext-mbstring": "to use Strings::lower() etc...",
"ext-gd": "to use Image",
"ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()"
},
"autoload": {
"classmap": ["src/"],
"psr-4": {
"Nette\\": "src"
}
},
"minimum-stability": "dev",
"scripts": {
"phpstan": "phpstan analyse",
"tester": "tester tests -s"
},
"extra": {
"branch-alias": {
"dev-master": "4.1-dev"
}
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}

60
vendor/nette/utils/license.md vendored Normal file
View file

@ -0,0 +1,60 @@
Licenses
========
Good news! You may use Nette Framework under the terms of either
the New BSD License or the GNU General Public License (GPL) version 2 or 3.
The BSD License is recommended for most projects. It is easy to understand and it
places almost no restrictions on what you can do with the framework. If the GPL
fits better to your project, you can use the framework under this license.
You don't have to notify anyone which license you are using. You can freely
use Nette Framework in commercial projects as long as the copyright header
remains intact.
Please be advised that the name "Nette Framework" is a protected trademark and its
usage has some limitations. So please do not use word "Nette" in the name of your
project or top-level domain, and choose a name that stands on its own merits.
If your stuff is good, it will not take long to establish a reputation for yourselves.
New BSD License
---------------
Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of "Nette Framework" nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright owner or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
GNU General Public License
--------------------------
GPL licenses are very very long, so instead of including them here we offer
you URLs with full text:
- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html)
- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)

55
vendor/nette/utils/readme.md vendored Normal file
View file

@ -0,0 +1,55 @@
[![Nette Utils](https://github.com/nette/utils/assets/194960/c33fdb74-0652-4cad-ac6e-c1ce0d29e32a)](https://doc.nette.org/en/utils)
[![Downloads this Month](https://img.shields.io/packagist/dm/nette/utils.svg)](https://packagist.org/packages/nette/utils)
[![Tests](https://github.com/nette/utils/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/utils/actions)
[![Coverage Status](https://coveralls.io/repos/github/nette/utils/badge.svg?branch=master)](https://coveralls.io/github/nette/utils?branch=master)
[![Latest Stable Version](https://poser.pugx.org/nette/utils/v/stable)](https://github.com/nette/utils/releases)
[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/utils/blob/master/license.md)
Introduction
------------
In package nette/utils you will find a set of useful classes for everyday use:
✅ [Arrays](https://doc.nette.org/utils/arrays)<br>
✅ [Callback](https://doc.nette.org/utils/callback) - PHP callbacks<br>
✅ [Filesystem](https://doc.nette.org/utils/filesystem) - copying, renaming, …<br>
✅ [Finder](https://doc.nette.org/utils/finder) - finds files and directories<br>
✅ [Floats](https://doc.nette.org/utils/floats) - floating point numbers<br>
✅ [Helper Functions](https://doc.nette.org/utils/helpers)<br>
✅ [HTML elements](https://doc.nette.org/utils/html-elements) - generate HTML<br>
✅ [Images](https://doc.nette.org/utils/images) - crop, resize, rotate images<br>
✅ [Iterables](https://doc.nette.org/utils/iterables) <br>
✅ [JSON](https://doc.nette.org/utils/json) - encoding and decoding<br>
✅ [Generating Random Strings](https://doc.nette.org/utils/random)<br>
✅ [Paginator](https://doc.nette.org/utils/paginator) - pagination math<br>
✅ [PHP Reflection](https://doc.nette.org/utils/reflection)<br>
✅ [Strings](https://doc.nette.org/utils/strings) - useful text functions<br>
✅ [SmartObject](https://doc.nette.org/utils/smartobject) - PHP object enhancements<br>
✅ [Type](https://doc.nette.org/utils/type) - PHP data type<br>
✅ [Validation](https://doc.nette.org/utils/validators) - validate inputs<br>
 <!---->
Installation
------------
The recommended way to install is via Composer:
```
composer require nette/utils
```
Nette Utils 4.1 is compatible with PHP 8.2 to 8.5.
 <!---->
[Support Me](https://github.com/sponsors/dg)
--------------------------------------------
Do you like Nette Utils? Are you looking forward to the new features?
[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg)
Thank you!

View file

@ -0,0 +1,23 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
/**
* Represents object convertible to HTML string.
*/
interface HtmlStringable
{
/**
* Returns string in HTML format.
*/
function __toString(): string;
}
interface_exists(Utils\IHtmlString::class);

View file

@ -0,0 +1,133 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Iterators;
use Nette;
/**
* Enhanced caching iterator with first/last/counter tracking.
*
* @template TKey
* @template TValue
* @extends \CachingIterator<TKey, TValue, \Iterator<TKey, TValue>>
* @property-read bool $first
* @property-read bool $last
* @property-read bool $empty
* @property-read bool $odd
* @property-read bool $even
* @property-read int $counter
* @property-read TKey $nextKey
* @property-read TValue $nextValue
*/
class CachingIterator extends \CachingIterator implements \Countable
{
use Nette\SmartObject;
private int $counter = 0;
/** @param iterable<TKey, TValue>|\stdClass $iterable */
public function __construct(iterable|\stdClass $iterable)
{
$iterable = $iterable instanceof \stdClass
? new \ArrayIterator((array) $iterable)
: Nette\Utils\Iterables::toIterator($iterable);
parent::__construct($iterable, 0);
}
/**
* Is the current element the first one?
*/
public function isFirst(?int $gridWidth = null): bool
{
return $this->counter === 1 || ($gridWidth && $this->counter !== 0 && (($this->counter - 1) % $gridWidth) === 0);
}
/**
* Is the current element the last one?
*/
public function isLast(?int $gridWidth = null): bool
{
return !$this->hasNext() || ($gridWidth && ($this->counter % $gridWidth) === 0);
}
public function isEmpty(): bool
{
return $this->counter === 0;
}
public function isOdd(): bool
{
return $this->counter % 2 === 1;
}
public function isEven(): bool
{
return $this->counter % 2 === 0;
}
public function getCounter(): int
{
return $this->counter;
}
public function count(): int
{
$inner = $this->getInnerIterator();
if ($inner instanceof \Countable) {
return $inner->count();
} else {
throw new Nette\NotSupportedException('Iterator is not countable.');
}
}
/**
* Forwards to the next element.
*/
public function next(): void
{
parent::next();
if (parent::valid()) {
$this->counter++;
}
}
/**
* Rewinds the Iterator.
*/
public function rewind(): void
{
parent::rewind();
$this->counter = parent::valid() ? 1 : 0;
}
/** @return TKey */
public function getNextKey(): mixed
{
return $this->getInnerIterator()->key();
}
/** @return TValue */
public function getNextValue(): mixed
{
return $this->getInnerIterator()->current();
}
}

View file

@ -0,0 +1,30 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Iterators;
/**
* @deprecated use Nette\Utils\Iterables::map()
*/
class Mapper extends \IteratorIterator
{
private \Closure $callback;
public function __construct(\Traversable $iterator, callable $callback)
{
parent::__construct($iterator);
$this->callback = $callback(...);
}
public function current(): mixed
{
return ($this->callback)(parent::current(), parent::key());
}
}

141
vendor/nette/utils/src/SmartObject.php vendored Normal file
View file

@ -0,0 +1,141 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
use Nette\Utils\ObjectHelpers;
/**
* Strict class for better experience.
* - 'did you mean' hints
* - access to undeclared members throws exceptions
* - support for @property annotations
* - support for calling event handlers stored in $onEvent via onEvent()
*/
trait SmartObject
{
/**
* @param mixed[] $args
* @return mixed
* @throws MemberAccessException
*/
public function __call(string $name, array $args)
{
$class = static::class;
if (ObjectHelpers::hasProperty($class, $name) === 'event') { // calling event handlers
$handlers = $this->$name ?? null;
if (is_iterable($handlers)) {
foreach ($handlers as $handler) {
$handler(...$args);
}
} elseif ($handlers !== null) {
throw new UnexpectedValueException("Property $class::$$name must be iterable or null, " . get_debug_type($handlers) . ' given.');
}
return null;
}
ObjectHelpers::strictCall($class, $name);
}
/**
* @param mixed[] $args
* @return never
* @throws MemberAccessException
*/
public static function __callStatic(string $name, array $args)
{
ObjectHelpers::strictStaticCall(static::class, $name);
}
/**
* @return mixed
* @throws MemberAccessException if the property is not defined.
*/
public function &__get(string $name)
{
$class = static::class;
if ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property getter
if (!($prop & 0b0001)) {
throw new MemberAccessException("Cannot read a write-only property $class::\$$name.");
}
$m = ($prop & 0b0010 ? 'get' : 'is') . ucfirst($name);
if ($prop & 0b10000) {
$trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call()
$loc = isset($trace['file'], $trace['line'])
? " in $trace[file] on line $trace[line]"
: '';
trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED);
}
if ($prop & 0b0100) { // return by reference
return $this->$m();
} else {
$val = $this->$m();
return $val;
}
} else {
ObjectHelpers::strictGet($class, $name);
}
}
/**
* @throws MemberAccessException if the property is not defined or is read-only
*/
public function __set(string $name, mixed $value): void
{
$class = static::class;
if (ObjectHelpers::hasProperty($class, $name)) { // unsetted property
$this->$name = $value;
} elseif ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { // property setter
if (!($prop & 0b1000)) {
throw new MemberAccessException("Cannot write to a read-only property $class::\$$name.");
}
$m = 'set' . ucfirst($name);
if ($prop & 0b10000) {
$trace = debug_backtrace(0, 1)[0]; // suppose this method is called from __call()
$loc = isset($trace['file'], $trace['line'])
? " in $trace[file] on line $trace[line]"
: '';
trigger_error("Property $class::\$$name is deprecated, use $class::$m() method$loc.", E_USER_DEPRECATED);
}
$this->$m($value);
} else {
ObjectHelpers::strictSet($class, $name);
}
}
/**
* @throws MemberAccessException
*/
public function __unset(string $name): void
{
$class = static::class;
if (!ObjectHelpers::hasProperty($class, $name)) {
throw new MemberAccessException("Cannot unset the property $class::\$$name.");
}
}
public function __isset(string $name): bool
{
return isset(ObjectHelpers::getMagicProperties(static::class)[$name]);
}
}

22
vendor/nette/utils/src/StaticClass.php vendored Normal file
View file

@ -0,0 +1,22 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
/**
* Prevents instantiation.
*/
trait StaticClass
{
/**
* Class is static and cannot be instantiated.
*/
private function __construct()
{
}
}

23
vendor/nette/utils/src/Translator.php vendored Normal file
View file

@ -0,0 +1,23 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Localization;
/**
* Translation provider.
*/
interface Translator
{
/**
* Translates the given string.
*/
function translate(string|\Stringable $message, mixed ...$parameters): string|\Stringable;
}
interface_exists(ITranslator::class);

View file

@ -0,0 +1,100 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function count, is_array, is_scalar, sprintf;
/**
* Array-like object with property access.
* @template T
* @implements \IteratorAggregate<array-key, T>
* @implements \ArrayAccess<array-key, T>
*/
class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
{
/**
* Transforms array to ArrayHash.
* @param array<T> $array
*/
public static function from(array $array, bool $recursive = true): static
{
$obj = new static;
foreach ($array as $key => $value) {
$obj->$key = $recursive && is_array($value)
? static::from($value)
: $value;
}
return $obj;
}
/**
* @return \Iterator<array-key, T>
*/
public function &getIterator(): \Iterator
{
foreach ((array) $this as $key => $foo) {
yield $key => $this->$key;
}
}
public function count(): int
{
return count((array) $this);
}
/**
* Replaces or appends an item.
* @param array-key $key
* @param T $value
*/
public function offsetSet($key, $value): void
{
if (!is_scalar($key)) { // prevents null
throw new Nette\InvalidArgumentException(sprintf('Key must be either a string or an integer, %s given.', get_debug_type($key)));
}
$this->$key = $value;
}
/**
* Returns an item.
* @param array-key $key
* @return T
*/
public function offsetGet($key): mixed
{
return $this->$key;
}
/**
* Determines whether an item exists.
* @param array-key $key
*/
public function offsetExists($key): bool
{
return isset($this->$key);
}
/**
* Removes the element from this list.
* @param array-key $key
*/
public function offsetUnset($key): void
{
unset($this->$key);
}
}

View file

@ -0,0 +1,130 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_splice, array_unshift, count, is_int;
/**
* Generic list with integer indices.
* @template T
* @implements \IteratorAggregate<int, T>
* @implements \ArrayAccess<int, T>
*/
class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate
{
/** @var list<T> */
private array $list = [];
/**
* Transforms array to ArrayList.
* @param list<T> $array
*/
public static function from(array $array): static
{
if (!Arrays::isList($array)) {
throw new Nette\InvalidArgumentException('Array is not valid list.');
}
$obj = new static;
$obj->list = $array;
return $obj;
}
/**
* @return \Iterator<int, T>
*/
public function &getIterator(): \Iterator
{
foreach ($this->list as &$item) {
yield $item;
}
}
public function count(): int
{
return count($this->list);
}
/**
* Replaces or appends an item.
* @param ?int $index
* @param T $value
* @throws Nette\OutOfRangeException
*/
public function offsetSet($index, $value): void
{
if ($index === null) {
$this->list[] = $value;
} elseif (!is_int($index) || $index < 0 || $index >= count($this->list)) {
throw new Nette\OutOfRangeException('Offset invalid or out of range');
} else {
$this->list[$index] = $value;
}
}
/**
* Returns an item.
* @param int $index
* @return T
* @throws Nette\OutOfRangeException
*/
public function offsetGet($index): mixed
{
if (!is_int($index) || $index < 0 || $index >= count($this->list)) {
throw new Nette\OutOfRangeException('Offset invalid or out of range');
}
return $this->list[$index];
}
/**
* Determines whether an item exists.
* @param int $index
*/
public function offsetExists($index): bool
{
return is_int($index) && $index >= 0 && $index < count($this->list);
}
/**
* Removes the element at the specified position in this list.
* @param int $index
* @throws Nette\OutOfRangeException
*/
public function offsetUnset($index): void
{
if (!is_int($index) || $index < 0 || $index >= count($this->list)) {
throw new Nette\OutOfRangeException('Offset invalid or out of range');
}
array_splice($this->list, $index, 1);
}
/**
* Prepends an item.
* @param T $value
*/
public function prepend(mixed $value): void
{
// route the value through offsetSet() first so a validation added in a subclass isn't bypassed
$this->offsetSet(null, $value);
array_unshift($this->list, ...array_splice($this->list, -1));
}
}

571
vendor/nette/utils/src/Utils/Arrays.php vendored Normal file
View file

@ -0,0 +1,571 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use JetBrains\PhpStorm\Language;
use Nette;
use function array_combine, array_intersect_key, array_is_list, array_key_exists, array_key_first, array_key_last, array_keys, array_reverse, array_search, array_slice, array_walk_recursive, count, func_num_args, in_array, is_array, is_int, is_object, key, preg_split;
use const PREG_GREP_INVERT, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY;
/**
* Array manipulation utilities.
*/
class Arrays
{
use Nette\StaticClass;
/**
* Returns item from array. If it does not exist, it throws an exception, unless a default value is set.
* @template T
* @param array<T> $array
* @param array-key|array-key[] $key
* @param ?T $default
* @return ?T
* @throws Nette\InvalidArgumentException if item does not exist and default value is not provided
*/
public static function get(array $array, string|int|array $key, mixed $default = null): mixed
{
foreach (is_array($key) ? $key : [$key] as $k) {
if (is_array($array) && array_key_exists($k, $array)) {
$array = $array[$k];
} else {
if (func_num_args() < 3) {
throw new Nette\InvalidArgumentException("Missing item '$k'.");
}
return $default;
}
}
return $array;
}
/**
* Returns reference to array item. If the index does not exist, new one is created with value null.
* @template T
* @param array<T> $array
* @param array-key|array-key[] $key
* @return ?T
* @throws Nette\InvalidArgumentException if traversed item is not an array
*/
public static function &getRef(array &$array, string|int|array $key): mixed
{
foreach (is_array($key) ? $key : [$key] as $k) {
if (is_array($array) || $array === null) {
$array = &$array[$k];
} else {
throw new Nette\InvalidArgumentException('Traversed item is not an array.');
}
}
return $array;
}
/**
* Recursively merges two arrays. Useful for merging tree structures. Behaves like the + operator:
* key/value pairs from the second array are added to the first, with the first array's values taking
* precedence on key collisions. Nested arrays are merged recursively instead of replaced.
* @template T1
* @template T2
* @param array<T1> $array1
* @param array<T2> $array2
* @return array<T1|T2|array<mixed>>
*/
public static function mergeTree(array $array1, array $array2): array
{
$res = $array1 + $array2;
foreach (array_intersect_key($array1, $array2) as $k => $v) {
if (is_array($v) && is_array($array2[$k])) {
$res[$k] = self::mergeTree($v, $array2[$k]);
}
}
return $res;
}
/**
* Returns zero-indexed position of given array key. Returns null if key is not found.
* @param array<mixed> $array
*/
public static function getKeyOffset(array $array, string|int $key): ?int
{
return Helpers::falseToNull(array_search(self::toKey($key), array_keys($array), strict: true));
}
/**
* @param array<mixed> $array
* @deprecated use getKeyOffset()
*/
public static function searchKey(array $array, string|int $key): ?int
{
return self::getKeyOffset($array, $key);
}
/**
* Tests an array for the presence of value.
* @param array<mixed> $array
*/
public static function contains(array $array, mixed $value): bool
{
return in_array($value, $array, strict: true);
}
/**
* Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* @template K of int|string
* @template V
* @template E
* @param array<K, V> $array
* @param ?callable(V, K, array<K, V>): bool $predicate
* @param ?callable(): E $else
* @return ($else is null ? ?V : V|E)
*/
public static function first(array $array, ?callable $predicate = null, ?callable $else = null): mixed
{
$key = self::firstKey($array, $predicate);
return $key === null
? ($else ? $else() : null)
: $array[$key];
}
/**
* Returns the last item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* @template K of int|string
* @template V
* @template E
* @param array<K, V> $array
* @param ?callable(V, K, array<K, V>): bool $predicate
* @param ?callable(): E $else
* @return ($else is null ? ?V : V|E)
*/
public static function last(array $array, ?callable $predicate = null, ?callable $else = null): mixed
{
$key = self::lastKey($array, $predicate);
return $key === null
? ($else ? $else() : null)
: $array[$key];
}
/**
* Returns the key of first item (matching the specified predicate if given) or null if there is no such item.
* @template K of int|string
* @template V
* @param array<K, V> $array
* @param ?callable(V, K, array<K, V>): bool $predicate
* @return ?K
*/
public static function firstKey(array $array, ?callable $predicate = null): int|string|null
{
if (!$predicate) {
return array_key_first($array);
}
foreach ($array as $k => $v) {
if ($predicate($v, $k, $array)) {
return $k;
}
}
return null;
}
/**
* Returns the key of last item (matching the specified predicate if given) or null if there is no such item.
* @template K of int|string
* @template V
* @param array<K, V> $array
* @param ?callable(V, K, array<K, V>): bool $predicate
* @return ?K
*/
public static function lastKey(array $array, ?callable $predicate = null): int|string|null
{
return $predicate
? self::firstKey(array_reverse($array, preserve_keys: true), $predicate)
: array_key_last($array);
}
/**
* Inserts the contents of the $inserted array into the $array immediately before the $key.
* If $key is null (or does not exist), it is inserted at the beginning.
* @param array<mixed> $array
* @param array<mixed> $inserted
*/
public static function insertBefore(array &$array, string|int|null $key, array $inserted): void
{
$offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key);
$array = array_slice($array, 0, $offset, preserve_keys: true)
+ $inserted
+ array_slice($array, $offset, count($array), preserve_keys: true);
}
/**
* Inserts the contents of the $inserted array into the $array immediately after the $key.
* If $key is null (or does not exist), it is inserted at the end.
* @param array<mixed> $array
* @param array<mixed> $inserted
*/
public static function insertAfter(array &$array, string|int|null $key, array $inserted): void
{
if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) {
$offset = count($array) - 1;
}
$array = array_slice($array, 0, $offset + 1, preserve_keys: true)
+ $inserted
+ array_slice($array, $offset + 1, count($array), preserve_keys: true);
}
/**
* Renames key in array.
* @param array<mixed> $array
*/
public static function renameKey(array &$array, string|int $oldKey, string|int $newKey): bool
{
$offset = self::getKeyOffset($array, $oldKey);
if ($offset === null) {
return false;
}
$val = &$array[$oldKey];
$keys = array_keys($array);
$keys[$offset] = $newKey;
$array = array_combine($keys, $array);
$array[$newKey] = &$val;
return true;
}
/**
* Returns only those array items, which matches a regular expression $pattern.
* @param string[] $array
* @return string[]
*/
public static function grep(
array $array,
#[Language('RegExp')]
string $pattern,
bool|int $invert = false,
): array
{
$flags = $invert ? PREG_GREP_INVERT : 0;
return Strings::pcre('preg_grep', [$pattern, $array, $flags]);
}
/**
* Transforms multidimensional array to flat array.
* @param array<mixed> $array
* @return array<mixed>
*/
public static function flatten(array $array, bool $preserveKeys = false): array
{
$res = [];
$cb = $preserveKeys
? function ($v, $k) use (&$res): void { $res[$k] = $v; }
: function ($v) use (&$res): void { $res[] = $v; };
array_walk_recursive($array, $cb);
return $res;
}
/**
* Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list.
* @return ($value is list ? true : false)
*/
public static function isList(mixed $value): bool
{
return is_array($value) && array_is_list($value);
}
/**
* Transforms a flat array of rows into an associative tree using a path expression like 'field|field[]field->field=field'.
* @param array<mixed> $array
* @param string|list<string> $path
* @return array<mixed>|\stdClass
*/
public static function associate(array $array, string|array $path): array|\stdClass
{
$parts = is_array($path)
? $path
: preg_split('#(\[]|->|=|\|)#', $path, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
if (!$parts || $parts === ['->'] || $parts[0] === '=' || $parts[0] === '|') {
throw new Nette\InvalidArgumentException("Invalid path '" . (is_array($path) ? implode('', $path) : $path) . "'.");
}
$res = $parts[0] === '->' ? new \stdClass : [];
foreach ($array as $rowOrig) {
$row = (array) $rowOrig;
$x = &$res;
for ($i = 0; $i < count($parts); $i++) {
$part = $parts[$i];
if ($part === '[]') {
$x = &$x[];
} elseif ($part === '=') {
if (isset($parts[++$i])) {
$x = $row[$parts[$i]];
$row = null;
}
break; // '=' is always the final operation
} elseif ($part === '->') {
if (isset($parts[++$i])) {
if ($x === null) {
$x = new \stdClass;
}
$x = &$x->{$row[$parts[$i]]};
} else {
$row = is_object($rowOrig) ? $rowOrig : (object) $row;
}
} elseif ($part !== '|') {
$x = &$x[(string) $row[$part]];
}
}
if ($x === null) {
$x = $row;
}
}
return $res;
}
/**
* Converts array to associative: items with numeric keys are converted to keys, with $filling as their value.
* @param array<mixed> $array
* @return array<string, mixed>
*/
public static function normalize(array $array, mixed $filling = null): array
{
$res = [];
foreach ($array as $k => $v) {
$res[is_int($k) ? $v : $k] = is_int($k) ? $filling : $v;
}
return $res;
}
/**
* Returns and removes the value of an item from an array. If it does not exist, it throws an exception,
* or returns $default, if provided.
* @template T
* @param array<T> $array
* @param ?T $default
* @return ?T
* @throws Nette\InvalidArgumentException if item does not exist and default value is not provided
*/
public static function pick(array &$array, string|int $key, mixed $default = null): mixed
{
if (array_key_exists($key, $array)) {
$value = $array[$key];
unset($array[$key]);
return $value;
} elseif (func_num_args() < 3) {
throw new Nette\InvalidArgumentException("Missing item '$key'.");
} else {
return $default;
}
}
/**
* Tests whether at least one element in the array passes the test implemented by the provided function.
* @template K of int|string
* @template V
* @param array<K, V> $array
* @param callable(V, K, array<K, V>): bool $predicate
*/
public static function some(iterable $array, callable $predicate): bool
{
foreach ($array as $k => $v) {
if ($predicate($v, $k, $array)) {
return true;
}
}
return false;
}
/**
* Tests whether all elements in the array pass the test implemented by the provided function.
* @template K of int|string
* @template V
* @param array<K, V> $array
* @param callable(V, K, array<K, V>): bool $predicate
*/
public static function every(iterable $array, callable $predicate): bool
{
foreach ($array as $k => $v) {
if (!$predicate($v, $k, $array)) {
return false;
}
}
return true;
}
/**
* Returns a new array containing all key-value pairs matching the given $predicate.
* @template K of int|string
* @template V
* @param array<K, V> $array
* @param callable(V, K, array<K, V>): bool $predicate
* @return array<K, V>
*/
public static function filter(array $array, callable $predicate): array
{
$res = [];
foreach ($array as $k => $v) {
if ($predicate($v, $k, $array)) {
$res[$k] = $v;
}
}
return $res;
}
/**
* Returns an array containing the original keys and results of applying the given transform function to each element.
* @template K of int|string
* @template V
* @template R
* @param array<K, V> $array
* @param callable(V, K, array<K, V>): R $transformer
* @return array<K, R>
*/
public static function map(iterable $array, callable $transformer): array
{
$res = [];
foreach ($array as $k => $v) {
$res[$k] = $transformer($v, $k, $array);
}
return $res;
}
/**
* Returns an array containing new keys and values generated by applying the given transform function to each element.
* If the function returns null, the element is skipped.
* @template K of int|string
* @template V
* @template ResK of int|string
* @template ResV
* @param array<K, V> $array
* @param callable(V, K, array<K, V>): ?array{ResK, ResV} $transformer
* @return array<ResK, ResV>
*/
public static function mapWithKeys(array $array, callable $transformer): array
{
$res = [];
foreach ($array as $k => $v) {
$pair = $transformer($v, $k, $array);
if ($pair) {
$res[$pair[0]] = $pair[1];
}
}
return $res;
}
/**
* Invokes all callbacks and returns array of results.
* @param iterable<callable> $callbacks
* @return array<mixed>
*/
public static function invoke(iterable $callbacks, mixed ...$args): array
{
$res = [];
foreach ($callbacks as $k => $cb) {
$res[$k] = $cb(...$args);
}
return $res;
}
/**
* Invokes method on every object in an array and returns array of results.
* @param iterable<object> $objects
* @return array<mixed>
*/
public static function invokeMethod(iterable $objects, string $method, mixed ...$args): array
{
$res = [];
foreach ($objects as $k => $obj) {
$res[$k] = $obj->$method(...$args);
}
return $res;
}
/**
* Copies the elements of the $array array to the $object object and then returns it.
* @template T of object
* @param iterable<mixed> $array
* @param T $object
* @return T
*/
public static function toObject(iterable $array, object $object): object
{
foreach ($array as $k => $v) {
$object->$k = $v;
}
return $object;
}
/**
* Converts value to array key.
*/
public static function toKey(mixed $value): int|string
{
return key(@[$value => null]);
}
/**
* Returns a copy of $array where every item is cast to string and wrapped with $prefix and $suffix.
* @param string[] $array
* @return string[]
*/
public static function wrap(array $array, string $prefix = '', string $suffix = ''): array
{
$res = [];
foreach ($array as $k => $v) {
$res[$k] = $prefix . $v . $suffix;
}
return $res;
}
}

View file

@ -0,0 +1,140 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function explode, func_get_args, ini_get, is_array, is_callable, is_object, is_string, preg_replace, restore_error_handler, set_error_handler, sprintf, str_contains, str_ends_with;
/**
* PHP callable tools.
*/
final class Callback
{
use Nette\StaticClass;
/**
* Invokes internal PHP function with own error handler.
* @param callable-string $function
* @param list<mixed> $args
* @param callable(string, int): (bool|void|null) $onError
*/
public static function invokeSafe(string $function, array $args, callable $onError): mixed
{
$prev = set_error_handler(function (int $severity, string $message, string $file, int $line) use ($onError, &$prev, $function): bool {
if ($file === __FILE__) {
$msg = ini_get('html_errors')
? Html::htmlToText($message)
: $message;
$msg = (string) preg_replace("#^$function\\(.*?\\): #", '', $msg);
if ($onError($msg, $severity) !== false) {
return true;
}
}
return $prev ? $prev(...func_get_args()) !== false : false;
});
try {
return $function(...$args);
} finally {
restore_error_handler();
}
}
/**
* Checks that $callable is a valid PHP callback and returns it. With $syntax set to true, only verifies
* the structural validity without checking whether the class or method actually exists.
* @return callable
* @throws Nette\InvalidArgumentException
*/
public static function check(mixed $callable, bool $syntax = false): mixed
{
if (!is_callable($callable, $syntax)) {
throw new Nette\InvalidArgumentException(
$syntax
? 'Given value is not a callable type.'
: sprintf("Callback '%s' is not callable.", self::toString($callable)),
);
}
return $callable;
}
/**
* Converts PHP callback to textual form. Class or method may not exists.
*/
public static function toString(mixed $callable): string
{
if ($callable instanceof \Closure) {
$inner = self::unwrap($callable);
return '{closure' . ($inner instanceof \Closure ? '}' : ' ' . self::toString($inner) . '}');
} else {
is_callable(is_object($callable) ? [$callable, '__invoke'] : $callable, true, $textual);
return $textual;
}
}
/**
* Returns reflection for method or function used in PHP callback.
* @param callable $callable type check is escalated to ReflectionException
* @throws \ReflectionException if callback is not valid
*/
public static function toReflection(mixed $callable): \ReflectionMethod|\ReflectionFunction
{
if ($callable instanceof \Closure) {
$callable = self::unwrap($callable);
}
if (is_string($callable) && str_contains($callable, '::')) {
return new ReflectionMethod(...explode('::', $callable, 2));
} elseif (is_array($callable)) {
return new ReflectionMethod($callable[0], $callable[1]);
} elseif (is_object($callable) && !$callable instanceof \Closure) {
return new ReflectionMethod($callable, '__invoke');
} else {
assert($callable instanceof \Closure || is_string($callable));
return new \ReflectionFunction($callable);
}
}
/**
* Checks whether PHP callback is function or static method.
*/
public static function isStatic(callable $callable): bool
{
return is_string(is_array($callable) ? $callable[0] : $callable);
}
/**
* Unwraps closure created by Closure::fromCallable().
* @return callable|array{object|class-string, string}|string
*/
public static function unwrap(\Closure $closure): callable|array|string
{
$r = new \ReflectionFunction($closure);
$class = $r->getClosureScopeClass()?->name;
if (str_ends_with($r->name, '}')) {
return $closure;
} elseif (($obj = $r->getClosureThis()) && $obj::class === $class) {
return [$obj, $r->name];
} elseif ($class) {
return [$class, $r->name];
} else {
return $r->name;
}
}
}

View file

@ -0,0 +1,207 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use function array_merge, checkdate, implode, is_numeric, is_string, preg_replace_callback, sprintf, time, trim;
/**
* Extends PHP's DateTime with strict validation and additional factory methods.
*/
class DateTime extends \DateTime implements \JsonSerializable
{
/** minute in seconds */
public const MINUTE = 60;
/** hour in seconds */
public const HOUR = 60 * self::MINUTE;
/** day in seconds */
public const DAY = 24 * self::HOUR;
/** week in seconds */
public const WEEK = 7 * self::DAY;
/** average month in seconds */
public const MONTH = 2_629_800;
/** average year in seconds */
public const YEAR = 31_557_600;
/**
* Creates a DateTime object from a string, UNIX timestamp, or other DateTimeInterface object.
* @throws \Exception if the date and time are not valid.
*/
public static function from(string|int|\DateTimeInterface|null $time): static
{
if ($time instanceof \DateTimeInterface) {
return static::createFromInterface($time);
} elseif (is_numeric($time)) {
if ($time <= self::YEAR) {
$time += time();
}
return (new static)->setTimestamp((int) $time);
} else { // textual or null
return new static((string) $time);
}
}
/**
* Creates DateTime object.
* @throws \Exception if the date and time are not valid.
*/
public static function fromParts(
int $year,
int $month,
int $day,
int $hour = 0,
int $minute = 0,
float $second = 0.0,
): static
{
$sec = (int) floor($second);
return (new static(''))
->setDate($year, $month, $day)
->setTime($hour, $minute, $sec, (int) round(($second - $sec) * 1e6));
}
/**
* Returns a new DateTime object formatted according to the specified format.
*/
public static function createFromFormat(
string $format,
string $datetime,
string|\DateTimeZone|null $timezone = null,
): static|false
{
if (is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);
}
$date = parent::createFromFormat($format, $datetime, $timezone);
return $date ? static::from($date) : false;
}
public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = null)
{
$this->apply($datetime, $timezone, true);
}
public function modify(string $modifier): static
{
$this->apply($modifier);
return $this;
}
public function setDate(int $year, int $month, int $day): static
{
if (!checkdate($month, $day, $year)) {
throw new \Exception(sprintf('The date %04d-%02d-%02d is not valid.', $year, $month, $day));
}
return parent::setDate($year, $month, $day);
}
public function setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): static
{
if (
$hour < 0 || $hour > 23
|| $minute < 0 || $minute > 59
|| $second < 0 || $second >= 60
|| $microsecond < 0 || $microsecond >= 1_000_000
) {
throw new \Exception(sprintf('The time %02d:%02d:%08.5F is not valid.', $hour, $minute, $second + $microsecond / 1_000_000));
}
return parent::setTime($hour, $minute, $second, $microsecond);
}
/**
* Converts a relative time string (e.g. '10 minut') to seconds.
*/
public static function relativeToSeconds(string $relativeTime): int
{
return (new self('@0 ' . $relativeTime))
->getTimestamp();
}
private function apply(string $datetime, ?\DateTimeZone $timezone = null, bool $ctr = false): void
{
$relPart = '';
$absPart = preg_replace_callback(
'/[+-]?\s*\d+\s+((microsecond|millisecond|[mµu]sec)s?|[mµ]s|sec(ond)?s?|min(ute)?s?|hours?)(\s+ago)?\b/iu',
function ($m) use (&$relPart) {
$relPart .= $m[0] . ' ';
return '';
},
$datetime,
);
if ($ctr) {
parent::__construct($absPart, $timezone);
$this->handleErrors($datetime);
} elseif (trim($absPart)) {
parent::modify($absPart) && $this->handleErrors($datetime);
}
if ($relPart) {
$timezone ??= $this->getTimezone();
$this->setTimezone(new \DateTimeZone('UTC'));
parent::modify($relPart) && $this->handleErrors($datetime);
$this->setTimezone($timezone);
}
}
/**
* Returns JSON representation in ISO 8601 (used by JavaScript).
*/
public function jsonSerialize(): string
{
return $this->format('c');
}
/**
* Returns the date and time in the format 'Y-m-d H:i:s'.
*/
public function __toString(): string
{
return $this->format('Y-m-d H:i:s');
}
/**
* Returns a modified copy of the object. Use (clone $dt)->modify(...) for better type safety.
*/
public function modifyClone(string $modify = ''): static
{
$dolly = clone $this;
return $modify ? $dolly->modify($modify) : $dolly;
}
private function handleErrors(string $value): void
{
$errors = self::getLastErrors();
$errors = array_merge($errors['errors'] ?? [], $errors['warnings'] ?? []);
if ($errors) {
throw new \Exception(implode(', ', $errors) . " '$value'");
}
}
}

View file

@ -0,0 +1,187 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use function array_merge, checkdate, implode, is_int, is_string, preg_match, preg_replace_callback, sprintf, trim;
/**
* Extends PHP's DateTimeImmutable with strict validation and additional factory methods.
* Invalid dates and times are rejected with an exception instead of being silently adjusted.
* All modifications return a new instance, the original object never changes.
*/
class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
{
/** matches relative sub-day parts (minutes, seconds, ...) that must be applied in UTC to be DST-safe */
private const RelativePattern = '/[+-]?\s*\d+\s+((microsecond|millisecond|[mµu]sec)s?|[mµ]s|sec(ond)?s?|min(ute)?s?|hours?)(\s+ago)?\b/iu';
/**
* Creates a DateTimeImmutable object from a string, UNIX timestamp, or other DateTimeInterface object.
* @throws \Exception if the date and time are not valid.
*/
public static function from(string|int|\DateTimeInterface|null $time): static
{
if ($time instanceof \DateTimeInterface) {
return static::createFromInterface($time);
} elseif (is_int($time)) {
return (new static)->setTimestamp($time);
} else { // textual or null
return new static((string) $time);
}
}
/**
* Creates DateTimeImmutable object.
* @throws \Exception if the date and time are not valid.
*/
public static function fromParts(
int $year,
int $month,
int $day,
int $hour = 0,
int $minute = 0,
float $second = 0.0,
): static
{
$sec = (int) floor($second);
return (new static)
->setDate($year, $month, $day)
->setTime($hour, $minute, $sec, (int) round(($second - $sec) * 1e6));
}
/**
* Returns a new DateTimeImmutable object formatted according to the specified format.
*/
public static function createFromFormat(
string $format,
string $datetime,
string|\DateTimeZone|null $timezone = null,
): static|false
{
if (is_string($timezone)) {
$timezone = new \DateTimeZone($timezone);
}
$date = parent::createFromFormat($format, $datetime, $timezone);
return $date ? static::from($date) : false;
}
public function __construct(string $datetime = 'now', ?\DateTimeZone $timezone = null)
{
if (preg_match(self::RelativePattern, $datetime)) {
// sub-day relative parts must be applied in UTC, which cannot happen inside a constructor => resolve & re-parse
$result = self::resolve(null, $datetime, $timezone);
parent::__construct($result->format('Y-m-d H:i:s.u'), $result->getTimezone());
} else {
parent::__construct($datetime, $timezone);
self::handleErrors($datetime);
}
}
public function modify(string $modifier): static
{
return static::createFromInterface(self::resolve($this, $modifier, null));
}
public function setDate(int $year, int $month, int $day): static
{
if (!checkdate($month, $day, $year)) {
throw new \Exception(sprintf('The date %04d-%02d-%02d is not valid.', $year, $month, $day));
}
return parent::setDate($year, $month, $day);
}
public function setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): static
{
if (
$hour < 0 || $hour > 23
|| $minute < 0 || $minute > 59
|| $second < 0 || $second >= 60
|| $microsecond < 0 || $microsecond >= 1_000_000
) {
throw new \Exception(sprintf('The time %02d:%02d:%08.5F is not valid.', $hour, $minute, $second + $microsecond / 1_000_000));
}
return parent::setTime($hour, $minute, $second, $microsecond);
}
/**
* Splits the input into absolute and relative parts and returns the resulting instant. Relative sub-day
* parts are applied in UTC so that crossing a DST boundary does not shift the result.
*/
private static function resolve(?\DateTimeInterface $base, string $input, ?\DateTimeZone $timezone): \DateTimeImmutable
{
$relPart = '';
$absPart = preg_replace_callback(
self::RelativePattern,
function ($m) use (&$relPart) {
$relPart .= $m[0] . ' ';
return '';
},
$input,
);
if ($base === null) {
$result = new \DateTimeImmutable($absPart, $timezone);
self::handleErrors($input);
} else {
$result = \DateTimeImmutable::createFromInterface($base);
if (trim($absPart) !== '') {
$modified = @$result->modify($absPart); // @ - on PHP 8.2 an invalid modifier emits a warning and returns false instead of throwing; handleErrors() turns it into an exception
self::handleErrors($input);
$result = $modified ?: $result;
}
}
if ($relPart !== '') {
$timezone ??= $result->getTimezone();
$result = $result
->setTimezone(new \DateTimeZone('UTC'))
->modify($relPart)
->setTimezone($timezone);
self::handleErrors($input);
}
return $result;
}
/**
* Returns JSON representation in ISO 8601 (used by JavaScript).
*/
public function jsonSerialize(): string
{
return $this->format('c');
}
/**
* Returns the date and time in the format 'Y-m-d H:i:s'.
*/
public function __toString(): string
{
return $this->format('Y-m-d H:i:s');
}
private static function handleErrors(string $value): void
{
$errors = self::getLastErrors();
$errors = array_merge($errors['errors'] ?? [], $errors['warnings'] ?? []);
if ($errors) {
throw new \Exception(implode(', ', $errors) . " '$value'");
}
}
}

View file

@ -0,0 +1,66 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use const DIRECTORY_SEPARATOR;
/**
* Represents the file or directory returned by the Finder.
* @internal do not create instances directly
*/
final class FileInfo extends \SplFileInfo
{
public function __construct(
string $file,
private readonly string $relativePath = '',
) {
parent::__construct($file);
$this->setInfoClass(self::class);
}
/**
* Returns the relative directory path.
*/
public function getRelativePath(): string
{
return $this->relativePath;
}
/**
* Returns the relative path including file name.
*/
public function getRelativePathname(): string
{
return ($this->relativePath === '' ? '' : $this->relativePath . DIRECTORY_SEPARATOR)
. $this->getBasename();
}
/**
* Returns the contents of the file.
* @throws Nette\IOException
*/
public function read(): string
{
return FileSystem::read($this->getPathname());
}
/**
* Writes the contents to the file.
* @throws Nette\IOException
*/
public function write(string $content): void
{
FileSystem::write($this->getPathname(), $content);
}
}

View file

@ -0,0 +1,385 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_pop, chmod, decoct, dirname, end, fclose, file_exists, file_get_contents, file_put_contents, fopen, implode, is_dir, is_file, is_link, mkdir, preg_match, preg_split, realpath, rename, rmdir, rtrim, sprintf, str_replace, stream_copy_to_stream, stream_is_local, strtr, uniqid, unlink, usleep;
use const DIRECTORY_SEPARATOR;
/**
* File system tool.
*/
final class FileSystem
{
/**
* Creates a directory if it does not exist, including parent directories.
* @throws Nette\IOException on error occurred
*/
public static function createDir(string $dir, int $mode = 0o777): void
{
if (!is_dir($dir) && !@mkdir($dir, $mode, recursive: true) && !is_dir($dir)) { // @ - dir may already exist
throw new Nette\IOException(sprintf(
"Unable to create directory '%s' with mode %s. %s",
self::normalizePath($dir),
decoct($mode),
Helpers::getLastError(),
));
}
}
/**
* Copies a file or an entire directory. Overwrites existing files and directories by default.
* @throws Nette\IOException on error occurred
* @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists
*/
public static function copy(string $origin, string $target, bool $overwrite = true): void
{
if (stream_is_local($origin) && !file_exists($origin)) {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin)));
} elseif (!$overwrite && file_exists($target)) {
throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target)));
} elseif (is_dir($origin)) {
static::createDir($target);
foreach (new \FilesystemIterator($target) as $item) {
\assert($item instanceof \SplFileInfo);
static::delete($item->getPathname());
}
foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) {
if ($item->isDir()) {
static::createDir($target . '/' . $iterator->getSubPathname());
} else {
static::copy($item->getPathname(), $target . '/' . $iterator->getSubPathname());
}
}
} else {
static::createDir(dirname($target));
if (@stream_copy_to_stream(static::open($origin, 'rb'), static::open($target, 'wb')) === false) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to copy file '%s' to '%s'. %s",
self::normalizePath($origin),
self::normalizePath($target),
Helpers::getLastError(),
));
}
}
}
/**
* Opens file and returns resource.
* @return resource
* @throws Nette\IOException on error occurred
*/
public static function open(string $path, string $mode)
{
$f = @fopen($path, $mode); // @ is escalated to exception
if (!$f) {
throw new Nette\IOException(sprintf(
"Unable to open file '%s'. %s",
self::normalizePath($path),
Helpers::getLastError(),
));
}
return $f;
}
/**
* Deletes a file or an entire directory if exists. If the directory is not empty, it deletes its contents first.
* @throws Nette\IOException on error occurred
*/
public static function delete(string $path): void
{
if (is_file($path) || is_link($path)) {
$func = DIRECTORY_SEPARATOR === '\\' && is_dir($path) ? 'rmdir' : 'unlink';
if (!@$func($path)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to delete '%s'. %s",
self::normalizePath($path),
Helpers::getLastError(),
));
}
} elseif (is_dir($path)) {
foreach (new \FilesystemIterator($path) as $item) {
\assert($item instanceof \SplFileInfo);
static::delete($item->getPathname());
}
if (!@rmdir($path)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to delete directory '%s'. %s",
self::normalizePath($path),
Helpers::getLastError(),
));
}
}
}
/**
* Renames or moves a file or a directory. Overwrites existing files and directories by default.
* @throws Nette\IOException on error occurred
* @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists
*/
public static function rename(string $origin, string $target, bool $overwrite = true): void
{
if (!$overwrite && file_exists($target)) {
throw new Nette\InvalidStateException(sprintf("File or directory '%s' already exists.", self::normalizePath($target)));
} elseif (!file_exists($origin)) {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($origin)));
} else {
static::createDir(dirname($target));
if (realpath($origin) !== realpath($target)) {
static::delete($target);
}
if (!@rename($origin, $target)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to rename file or directory '%s' to '%s'. %s",
self::normalizePath($origin),
self::normalizePath($target),
Helpers::getLastError(),
));
}
}
}
/**
* Reads the content of a file.
* @throws Nette\IOException on error occurred
*/
public static function read(string $file): string
{
$content = @file_get_contents($file); // @ is escalated to exception
if ($content === false) {
throw new Nette\IOException(sprintf(
"Unable to read file '%s'. %s",
self::normalizePath($file),
Helpers::getLastError(),
));
}
return $content;
}
/**
* Reads the file content line by line. Because it reads continuously as we iterate over the lines,
* it is possible to read files larger than the available memory.
* @return \Generator<int, string>
* @throws Nette\IOException on error occurred
*/
public static function readLines(string $file, bool $stripNewLines = true): \Generator
{
return (function ($f) use ($file, $stripNewLines) {
$counter = 0;
do {
$line = Callback::invokeSafe('fgets', [$f], fn($error) => throw new Nette\IOException(sprintf(
"Unable to read file '%s'. %s",
self::normalizePath($file),
$error,
)));
if ($line === false) {
fclose($f);
break;
}
if ($stripNewLines) {
$line = rtrim($line, "\r\n");
}
yield $counter++ => $line;
} while (true);
})(static::open($file, 'r'));
}
/**
* Writes the string to a file. Creates the parent directory if it does not exist. Pass null as $mode to skip chmod.
* @throws Nette\IOException on error occurred
*/
public static function write(string $file, string $content, ?int $mode = 0o666): void
{
static::createDir(dirname($file));
if (@file_put_contents($file, $content) === false) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to write file '%s'. %s",
self::normalizePath($file),
Helpers::getLastError(),
));
}
if ($mode !== null && !@chmod($file, $mode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod file '%s' to mode %s. %s",
self::normalizePath($file),
decoct($mode),
Helpers::getLastError(),
));
}
}
/**
* Writes the string to a file atomically: the content is written to a temporary file, which then replaces
* the target, so a concurrent reader never sees the file partially written or truncated.
* Creates the parent directory if it does not exist. Pass null as $mode to skip chmod.
* @throws Nette\IOException on error occurred
*/
public static function writeAtomic(string $file, string $content, ?int $mode = 0o666): void
{
$file = realpath($file) ?: $file; // writes through a symlink to its target, as write() does
$tmp = $file . '.' . uniqid('', more_entropy: true) . '.tmp';
try {
static::write($tmp, $content, $mode);
// plain rename() is atomic; static::rename() must not be used here, it deletes the target first
for ($i = 0; !@rename($tmp, $file); $i++) { // @ is escalated to exception
if (!Helpers::IsWindows || $i >= 20) {
throw new Nette\IOException(sprintf(
"Unable to write file '%s'. %s",
self::normalizePath($file),
Helpers::getLastError(),
));
}
usleep(5_000); // on Windows, rename fails while the target is open in another process
}
} catch (\Throwable $e) {
@unlink($tmp);
throw $e;
}
}
/**
* Sets file permissions to `$fileMode` or directory permissions to `$dirMode`.
* Recursively traverses and sets permissions on the entire contents of the directory as well.
* @throws Nette\IOException on error occurred
*/
public static function makeWritable(string $path, int $dirMode = 0o777, int $fileMode = 0o666): void
{
if (is_file($path)) {
if (!@chmod($path, $fileMode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod file '%s' to mode %s. %s",
self::normalizePath($path),
decoct($fileMode),
Helpers::getLastError(),
));
}
} elseif (is_dir($path)) {
foreach (new \FilesystemIterator($path) as $item) {
\assert($item instanceof \SplFileInfo);
static::makeWritable($item->getPathname(), $dirMode, $fileMode);
}
if (!@chmod($path, $dirMode)) { // @ is escalated to exception
throw new Nette\IOException(sprintf(
"Unable to chmod directory '%s' to mode %s. %s",
self::normalizePath($path),
decoct($dirMode),
Helpers::getLastError(),
));
}
} else {
throw new Nette\IOException(sprintf("File or directory '%s' not found.", self::normalizePath($path)));
}
}
/**
* Determines if the path is absolute.
*/
public static function isAbsolute(string $path): bool
{
return (bool) preg_match('#([a-z]:)?[/\\\]|[a-z][a-z0-9+.-]*://#Ai', $path);
}
/**
* Determines whether the string is a valid cross-platform filename without any path information.
*/
public static function isValidFilename(string $name): bool
{
[$stem] = explode('.', $name, 2);
return $name !== '' && $name !== '.' && $name !== '..'
&& !preg_match('#[\x00-\x1F<>:"|?*\\\/]#', $name) // control and reserved characters
&& !str_ends_with($name, '.') && !str_ends_with($name, ' ') // trailing dots/spaces
&& !preg_match('#^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$#i', $stem); // Windows reserved device names
}
/**
* Normalizes `..` and `.` and directory separators in path.
*/
public static function normalizePath(string $path): string
{
$parts = $path === '' ? [] : preg_split('~[/\\\]+~', $path);
$res = [];
foreach ($parts as $part) {
if ($part === '..' && $res && end($res) !== '..' && end($res) !== '') {
array_pop($res);
} elseif ($part !== '.') {
$res[] = $part;
}
}
return $res === ['']
? DIRECTORY_SEPARATOR
: implode(DIRECTORY_SEPARATOR, $res);
}
/**
* Joins all segments of the path and normalizes the result.
*/
public static function joinPaths(string ...$paths): string
{
return self::normalizePath(implode('/', $paths));
}
/**
* Resolves a path against a base path. If the path is absolute, returns it directly, if it's relative, joins it with the base path.
*/
public static function resolvePath(string $basePath, string $path): string
{
return match (true) {
self::isAbsolute($path) => self::platformSlashes($path),
$path === '' => self::platformSlashes($basePath),
default => self::joinPaths($basePath, $path),
};
}
/**
* Converts backslashes to slashes.
*/
public static function unixSlashes(string $path): string
{
return strtr($path, '\\', '/');
}
/**
* Converts slashes to platform-specific directory separators.
*/
public static function platformSlashes(string $path): string
{
return DIRECTORY_SEPARATOR === '/'
? strtr($path, '\\', '/')
: str_replace(':\\\\', '://', strtr($path, '/', '\\')); // protocol://
}
}

544
vendor/nette/utils/src/Utils/Finder.php vendored Normal file
View file

@ -0,0 +1,544 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_filter, array_merge, array_values, count, func_get_args, func_num_args, glob, implode, is_array, is_dir, iterator_to_array, preg_match, preg_quote, preg_replace, preg_split, rtrim, spl_object_id, sprintf, str_starts_with, strnatcmp, strpbrk, strrpos, strtolower, strtr, substr, trigger_error, usort;
use const DIRECTORY_SEPARATOR, E_USER_DEPRECATED, GLOB_NOESCAPE, GLOB_NOSORT, GLOB_ONLYDIR;
/**
* Searches for files and directories in directory trees.
*
* Finder::findFiles('*.php')
* ->size('> 10kB')
* ->from('.')
* ->exclude('temp');
*
* @implements \IteratorAggregate<string, FileInfo>
*/
class Finder implements \IteratorAggregate
{
/** @var array<array{string, string}> */
private array $find = [];
/** @var string[] */
private array $in = [];
/** @var array<\Closure(FileInfo): bool> */
private array $filters = [];
/** @var array<\Closure(FileInfo): bool> */
private array $descentFilters = [];
/** @var array<string|self> */
private array $appends = [];
private bool $childFirst = false;
/** @var ?(\Closure(FileInfo, FileInfo): int) */
private ?\Closure $sort = null;
private int $maxDepth = -1;
private bool $ignoreUnreadableDirs = true;
/**
* Begins search for files and directories matching mask. The ** wildcard searches recursively; a trailing slash limits the mask to directories.
* @param string|list<string> $masks
*/
public static function find(string|array $masks = ['*']): static
{
$masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
$files = array_filter($masks, fn(string $mask): bool => !self::hasTrailingSeparator($mask)); // trailing slash means directories only
return (new static)->addMask($masks, 'dir')->addMask(array_values($files), 'file');
}
/**
* Begins search for files matching mask. The ** wildcard searches recursively.
* @param string|list<string> $masks
*/
public static function findFiles(string|array $masks = ['*']): static
{
$masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
return (new static)->addMask($masks, 'file');
}
/**
* Begins search for directories matching mask. The ** wildcard searches recursively.
* @param string|list<string> $masks
*/
public static function findDirectories(string|array $masks = ['*']): static
{
$masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
return (new static)->addMask($masks, 'dir');
}
/**
* Finds files matching the specified masks.
* @param string|list<string> $masks
*/
public function files(string|array $masks = ['*']): static
{
return $this->addMask((array) $masks, 'file');
}
/**
* Finds directories matching the specified masks.
* @param string|list<string> $masks
*/
public function directories(string|array $masks = ['*']): static
{
return $this->addMask((array) $masks, 'dir');
}
/** @param list<string> $masks */
private function addMask(array $masks, string $mode): static
{
foreach ($masks as $mask) {
$orig = $mask;
if ($mode === 'dir') {
$mask = rtrim($mask, '/\\');
}
if ($mask === '' || ($mode === 'file' && self::hasTrailingSeparator($mask))) {
throw new Nette\InvalidArgumentException("Invalid mask '$orig'");
}
$this->find[] = [self::expandGlobStar($mask), $mode];
}
return $this;
}
private static function hasTrailingSeparator(string $mask): bool
{
return ($last = substr($mask, -1)) === '/' || $last === '\\';
}
// Expands a ** that is not followed by a slash into **/*, so that e.g. "test/**" and "**.c" search recursively.
private static function expandGlobStar(string $mask): string
{
return preg_replace('~(?<=^|[/\\\])\*\*(?![/\\\])~', '**/*', $mask);
}
/**
* Searches in the given directories. Wildcards * and ? are allowed; unlike in masks, [ and ] are taken literally.
* @param string|list<string> $paths
*/
public function in(string|array $paths): static
{
$paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic
$this->addLocation($paths, '');
return $this;
}
/**
* Searches recursively from the given directories. Wildcards * and ? are allowed; unlike in masks, [ and ] are taken literally.
* @param string|list<string> $paths
*/
public function from(string|array $paths): static
{
$paths = is_array($paths) ? $paths : func_get_args(); // compatibility with variadic
$this->addLocation($paths, DIRECTORY_SEPARATOR . '**');
return $this;
}
/** @param list<string> $paths */
private function addLocation(array $paths, string $ext): void
{
foreach ($paths as $path) {
if ($path === '') {
throw new Nette\InvalidArgumentException("Invalid directory '$path'");
}
$path = rtrim($path, '/\\');
$this->in[] = $path . $ext;
}
}
/**
* Lists directory's contents before the directory itself. By default, this is disabled.
*/
public function childFirst(bool $state = true): static
{
$this->childFirst = $state;
return $this;
}
/**
* Ignores unreadable directories. By default, this is enabled.
*/
public function ignoreUnreadableDirs(bool $state = true): static
{
$this->ignoreUnreadableDirs = $state;
return $this;
}
/**
* Sets a comparison function for sorting entries within each directory.
* @param callable(FileInfo, FileInfo): int $callback
*/
public function sortBy(callable $callback): static
{
$this->sort = $callback(...);
return $this;
}
/**
* Sorts files in each directory naturally by name.
*/
public function sortByName(): static
{
$this->sort = fn(FileInfo $a, FileInfo $b): int => strnatcmp($a->getBasename(), $b->getBasename());
return $this;
}
/**
* Appends the specified file paths to results. Passing null creates and returns a new sub-finder whose results are appended.
* @param string|list<string>|null $paths
*/
public function append(string|array|null $paths = null): static
{
if ($paths === null) {
return $this->appends[] = new static;
}
$this->appends = array_merge($this->appends, (array) $paths);
return $this;
}
/********************* filtering ****************d*g**/
/**
* Skips entries that match the given masks, using the same grammar as find() masks, relative to the directories from in() or from().
* A trailing slash excludes directories only; a trailing /* or /** excludes the contents while keeping the directory itself.
* @param string|list<string> $masks
*/
public function exclude(string|array $masks): static
{
$masks = is_array($masks) ? $masks : func_get_args(); // compatibility with variadic
foreach ($masks as $mask) {
$orig = $mask;
$mask = FileSystem::unixSlashes($mask);
if (FileSystem::isAbsolute($mask) || $mask === '..' || str_starts_with($mask, '../')) {
trigger_error("Absolute or ../ mask '$orig' in exclude() is deprecated and will change meaning, use a mask relative to the searched directory.", E_USER_DEPRECATED);
}
if (!preg_match('~^/?(\*\*/)?(.+?)(/\*\*|/\*|/|)$~D', $mask, $m)) {
throw new Nette\InvalidArgumentException("Invalid mask '$orig'");
}
$end = $m[3];
$re = $this->buildPattern(self::expandGlobStar($m[2]));
$filter = fn(FileInfo $file): bool => ($end && !$file->isDir())
|| !preg_match($re, FileSystem::unixSlashes($file->getRelativePathname()));
$this->descentFilter($filter);
if ($end === '' || $end === '/') {
$this->filter($filter);
}
}
return $this;
}
/**
* Yields only entries which satisfy the given filter.
* @param callable(FileInfo): bool $callback
*/
public function filter(callable $callback): static
{
$this->filters[] = $callback(...);
return $this;
}
/**
* It descends only to directories that match the specified filter.
* @param callable(FileInfo): bool $callback
*/
public function descentFilter(callable $callback): static
{
$this->descentFilters[] = $callback(...);
return $this;
}
/**
* Sets the maximum depth of entries.
*/
public function limitDepth(?int $depth): static
{
$this->maxDepth = $depth ?? -1;
return $this;
}
/**
* Restricts the search by size. $operator accepts "[operator] [size] [unit]" example: >=10kB
* @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator or predicate string
*/
public function size(string $operator, ?int $size = null): static
{
if (func_num_args() === 1) { // in $operator is predicate
if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?$#Di', $operator, $matches)) {
throw new Nette\InvalidArgumentException('Invalid size predicate format.');
}
[, $operator, $size, $unit] = $matches;
$units = ['' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9];
$size = (float) $size * $units[strtolower($unit)];
$operator = $operator ?: '=';
}
return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getSize(), $operator, $size));
}
/**
* Restricts the search by modified time. $operator accepts "[operator] [date]" example: >1978-01-23
* @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator or predicate string
*/
public function date(string $operator, string|int|\DateTimeInterface|null $date = null): static
{
if (func_num_args() === 1) { // in $operator is predicate
if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)$#Di', $operator, $matches)) {
throw new Nette\InvalidArgumentException('Invalid date predicate format.');
}
[, $operator, $date] = $matches;
$operator = $operator ?: '=';
}
$date = DateTime::from($date)->getTimestamp();
return $this->filter(fn(FileInfo $file): bool => !$file->isFile() || Helpers::compare($file->getMTime(), $operator, $date));
}
/********************* iterator generator ****************d*g**/
/**
* Returns an array with all found files and directories.
* @return list<FileInfo>
*/
public function collect(): array
{
return iterator_to_array($this->getIterator(), preserve_keys: false);
}
/** @return \Generator<string, FileInfo> */
public function getIterator(): \Generator
{
$plan = $this->buildPlan();
foreach ($plan as $dir => $searches) {
yield from $this->traverseDir($dir, $searches);
}
foreach ($this->appends as $item) {
if ($item instanceof self) {
yield from $item->getIterator();
} else {
yield $item => new FileInfo($item);
}
}
}
/**
* @param array<object{pattern: string, mode: string, recursive: bool}> $searches
* @param string[] $subdirs
* @return \Generator<string, FileInfo>
*/
private function traverseDir(string $dir, array $searches, array $subdirs = []): \Generator
{
if ($this->maxDepth >= 0 && count($subdirs) > $this->maxDepth) {
return;
} elseif (!is_dir($dir)) {
throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($dir, '/\\')));
}
try {
$pathNames = new \FilesystemIterator($dir, \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::CURRENT_AS_PATHNAME);
} catch (\UnexpectedValueException $e) {
if ($this->ignoreUnreadableDirs) {
return;
} else {
throw new Nette\InvalidStateException($e->getMessage());
}
}
$files = $this->convertToFiles($pathNames, implode(DIRECTORY_SEPARATOR, $subdirs), FileSystem::isAbsolute($dir));
if ($this->sort) {
$files = iterator_to_array($files);
usort($files, $this->sort);
}
foreach ($files as $file) {
$pathName = $file->getPathname();
$cache = $subSearch = [];
if ($file->isDir()) {
foreach ($searches as $search) {
if ($search->recursive && $this->proveFilters($this->descentFilters, $file, $cache)) {
$subSearch[] = $search;
}
}
}
if ($this->childFirst && $subSearch) {
yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()]));
}
$relativePathname = FileSystem::unixSlashes($file->getRelativePathname());
foreach ($searches as $search) {
if (
"is_$search->mode"(Helpers::IsWindows && $file->isLink() ? $file->getLinkTarget() : $file->getPathname())
&& preg_match($search->pattern, $relativePathname)
&& $this->proveFilters($this->filters, $file, $cache)
) {
yield $pathName => $file;
break;
}
}
if (!$this->childFirst && $subSearch) {
yield from $this->traverseDir($pathName, $subSearch, array_merge($subdirs, [$file->getBasename()]));
}
}
}
/** @param iterable<string> $pathNames */
private function convertToFiles(iterable $pathNames, string $relativePath, bool $absolute): \Generator
{
foreach ($pathNames as $pathName) {
if (!$absolute) {
$pathName = preg_replace('~\.?[\\\/]~A', '', $pathName);
}
yield new FileInfo($pathName, $relativePath);
}
}
/**
* @param (\Closure(FileInfo): bool)[] $filters
* @param array<int, bool> $cache
*/
private function proveFilters(array $filters, FileInfo $file, array &$cache): bool
{
foreach ($filters as $filter) {
$res = &$cache[spl_object_id($filter)];
$res ??= $filter($file);
if (!$res) {
return false;
}
}
return true;
}
/** @return array<string, array<object{pattern: string, mode: string, recursive: bool}>> */
private function buildPlan(): array
{
$plan = $dirCache = [];
foreach ($this->find as [$mask, $mode]) {
$splits = [];
if (FileSystem::isAbsolute($mask)) {
if ($this->in) {
throw new Nette\InvalidStateException("You cannot combine the absolute path in the mask '$mask' and the directory to search '{$this->in[0]}'.");
}
$splits[] = self::splitRecursivePart($mask);
} else {
foreach ($this->in ?: ['.'] as $in) {
$in = strtr($in, ['[' => '[[]', ']' => '[]]']); // in path, do not treat [ and ] as a pattern by glob()
$splits[] = self::splitRecursivePart($in . DIRECTORY_SEPARATOR . $mask);
}
}
foreach ($splits as [$base, $rest, $recursive]) {
$base = $base === '' ? '.' : $base;
$dirs = $dirCache[$base] ??= strpbrk($base, '*?[')
? glob($base, GLOB_NOSORT | GLOB_ONLYDIR | GLOB_NOESCAPE)
: [strtr($base, ['[[]' => '[', '[]]' => ']'])]; // unescape [ and ]
if (!$dirs) {
throw new Nette\InvalidStateException(sprintf("Directory '%s' does not exist.", rtrim($base, '/\\')));
}
$search = (object) ['pattern' => $this->buildPattern($rest), 'mode' => $mode, 'recursive' => $recursive];
foreach ($dirs as $dir) {
$plan[$dir][] = $search;
}
}
}
return $plan;
}
/**
* Since glob() does not know ** wildcard, we divide the path into a part for glob and a part for manual traversal.
* @return array{string, string, bool}
*/
private static function splitRecursivePart(string $path): array
{
$pos = strrpos(strtr($path, '\\', '/'), '/');
$dir = $pos === false ? '' : substr($path, 0, $pos + 1);
$file = $pos === false ? $path : substr($path, $pos + 1);
$parts = preg_split('~(?<=^|[\\\/])\*\*($|[\\\/])~', $dir, 2);
return isset($parts[1])
? [$parts[0], $parts[1] . $file, true]
: [$parts[0], $file, false];
}
/**
* Converts wildcards to regular expression.
*/
private function buildPattern(string $mask): string
{
$mask = FileSystem::unixSlashes($mask);
if ($mask === '*') {
return '##';
} elseif (str_starts_with($mask, './')) {
$anchor = '^';
$mask = substr($mask, 2);
} else {
$anchor = '(?:^|/)';
}
$pattern = strtr(
preg_quote($mask, '#'),
[
'\*\*/' => '(.+/)?',
'\*' => '[^/]*',
'\?' => '[^/]',
'\[\!' => '[^',
'\[' => '[',
'\]' => ']',
'\-' => '-',
],
);
return '#' . $anchor . $pattern . '$#D' . (Helpers::IsWindows ? 'i' : '');
}
}

106
vendor/nette/utils/src/Utils/Floats.php vendored Normal file
View file

@ -0,0 +1,106 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function abs, is_finite, is_nan, max, round;
/**
* Floating-point numbers comparison.
*/
class Floats
{
use Nette\StaticClass;
private const Epsilon = 1e-10;
public static function isZero(float $value): bool
{
return abs($value) < self::Epsilon;
}
public static function isInteger(float $value): bool
{
return abs(round($value) - $value) < self::Epsilon;
}
/**
* Compare two floats. If $a < $b it returns -1, if they are equal it returns 0 and if $a > $b it returns 1
* @throws \LogicException if one of parameters is NAN
*/
public static function compare(float $a, float $b): int
{
if (is_nan($a) || is_nan($b)) {
throw new \LogicException('Trying to compare NAN');
} elseif (!is_finite($a) && !is_finite($b) && $a === $b) {
return 0;
}
$diff = abs($a - $b);
if (($diff < self::Epsilon || ($diff / max(abs($a), abs($b)) < self::Epsilon))) {
return 0;
}
return $a < $b ? -1 : 1;
}
/**
* Returns true if $a = $b
* @throws \LogicException if one of parameters is NAN
*/
public static function areEqual(float $a, float $b): bool
{
return self::compare($a, $b) === 0;
}
/**
* Returns true if $a < $b
* @throws \LogicException if one of parameters is NAN
*/
public static function isLessThan(float $a, float $b): bool
{
return self::compare($a, $b) < 0;
}
/**
* Returns true if $a <= $b
* @throws \LogicException if one of parameters is NAN
*/
public static function isLessThanOrEqualTo(float $a, float $b): bool
{
return self::compare($a, $b) <= 0;
}
/**
* Returns true if $a > $b
* @throws \LogicException if one of parameters is NAN
*/
public static function isGreaterThan(float $a, float $b): bool
{
return self::compare($a, $b) > 0;
}
/**
* Returns true if $a >= $b
* @throws \LogicException if one of parameters is NAN
*/
public static function isGreaterThanOrEqualTo(float $a, float $b): bool
{
return self::compare($a, $b) >= 0;
}
}

125
vendor/nette/utils/src/Utils/Helpers.php vendored Normal file
View file

@ -0,0 +1,125 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_unique, ini_get, levenshtein, max, min, ob_end_clean, ob_get_clean, ob_start, preg_replace, strlen;
use const PHP_OS_FAMILY;
/**
* Miscellaneous utilities.
*/
class Helpers
{
public const IsWindows = PHP_OS_FAMILY === 'Windows';
/**
* Executes a callback and returns the captured output as a string.
* @param callable(): void $func
*/
public static function capture(callable $func): string
{
ob_start(fn() => '');
try {
$func();
return ob_get_clean();
} catch (\Throwable $e) {
ob_end_clean();
throw $e;
}
}
/**
* Returns the last occurred PHP error or an empty string if no error occurred. Unlike error_get_last(),
* it is not affected by the PHP directive html_errors and always returns text, not HTML.
*/
public static function getLastError(): string
{
$message = error_get_last()['message'] ?? '';
$message = ini_get('html_errors') ? Html::htmlToText($message) : $message;
$message = preg_replace('#^\w+\(.*?\): #', '', $message);
return $message;
}
/**
* Converts false to null, does not change other values.
*/
public static function falseToNull(mixed $value): mixed
{
return $value === false ? null : $value;
}
/**
* Returns value clamped to the inclusive range of min and max.
* @return ($value is float ? float : ($min is float ? float : ($max is float ? float : int)))
*/
public static function clamp(int|float $value, int|float $min, int|float $max): int|float
{
if ($min > $max) {
throw new Nette\InvalidArgumentException("Minimum ($min) is not less than maximum ($max).");
}
return min(max($value, $min), $max);
}
/**
* Finds the string from $possibilities most similar to $value using Levenshtein distance, or null if none is close enough.
* @param string[] $possibilities
*/
public static function getSuggestion(array $possibilities, string $value): ?string
{
$best = null;
$min = (strlen($value) / 4 + 1) * 10 + .1;
foreach (array_unique($possibilities) as $item) {
if ($item !== $value && ($len = levenshtein($item, $value, 10, 11, 10)) < $min) {
$min = $len;
$best = $item;
}
}
return $best;
}
/**
* Compares two values in the same way that PHP does. Recognizes operators: >, >=, <, <=, =, ==, ===, !=, !==, <>
* @param '>'|'>='|'<'|'<='|'='|'=='|'==='|'!='|'!=='|'<>' $operator
*/
public static function compare(mixed $left, string $operator, mixed $right): bool
{
return match ($operator) {
'>' => $left > $right,
'>=' => $left >= $right,
'<' => $left < $right,
'<=' => $left <= $right,
'=', '==' => $left == $right,
'===' => $left === $right,
'!=', '<>' => $left != $right,
'!==' => $left !== $right,
default => throw new Nette\InvalidArgumentException("Unknown operator '$operator'"),
};
}
/**
* Splits a class name into namespace and short class name.
* @return array{string, string}
*/
public static function splitClassName(string $name): array
{
return ($pos = strrpos($name, '\\')) === false
? ['', $name]
: [substr($name, 0, $pos), substr($name, $pos + 1)];
}
}

888
vendor/nette/utils/src/Utils/Html.php vendored Normal file
View file

@ -0,0 +1,888 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette\HtmlStringable;
use function array_merge, array_splice, count, explode, func_num_args, html_entity_decode, htmlspecialchars, http_build_query, implode, is_array, is_bool, is_float, is_object, is_string, json_encode, max, number_format, rtrim, str_contains, str_repeat, str_replace, strip_tags, strncmp, strpbrk, substr, trigger_error, ucfirst;
use const E_USER_DEPRECATED, ENT_HTML5, ENT_NOQUOTES, ENT_QUOTES;
/**
* Generates HTML elements with automatic attribute escaping.
*
* @property ?string $accept
* @property ?string $accesskey
* @property ?string $action
* @property ?string $align
* @property ?string $allow
* @property ?string $alt
* @property ?bool $async
* @property ?string $autocapitalize
* @property ?string $autocomplete
* @property ?bool $autofocus
* @property ?bool $autoplay
* @property ?string $charset
* @property ?bool $checked
* @property ?string $cite
* @property ?string $class
* @property ?int $cols
* @property ?int $colspan
* @property ?string $content
* @property ?bool $contenteditable
* @property ?bool $controls
* @property ?string $coords
* @property ?string $crossorigin
* @property ?string $data
* @property ?string $datetime
* @property ?string $decoding
* @property ?bool $default
* @property ?bool $defer
* @property ?string $dir
* @property ?string $dirname
* @property ?bool $disabled
* @property ?bool $download
* @property ?string $draggable
* @property ?string $dropzone
* @property ?string $enctype
* @property ?string $for
* @property ?string $form
* @property ?string $formaction
* @property ?string $formenctype
* @property ?string $formmethod
* @property ?bool $formnovalidate
* @property ?string $formtarget
* @property ?string $headers
* @property ?int $height
* @property ?bool $hidden
* @property ?float $high
* @property ?string $href
* @property ?string $hreflang
* @property ?string $id
* @property ?string $integrity
* @property ?string $inputmode
* @property ?bool $ismap
* @property ?string $itemprop
* @property ?string $kind
* @property ?string $label
* @property ?string $lang
* @property ?string $list
* @property ?bool $loop
* @property ?float $low
* @property ?float $max
* @property ?int $maxlength
* @property ?int $minlength
* @property ?string $media
* @property ?string $method
* @property ?float $min
* @property ?bool $multiple
* @property ?bool $muted
* @property ?string $name
* @property ?bool $novalidate
* @property ?bool $open
* @property ?float $optimum
* @property ?string $pattern
* @property ?string $ping
* @property ?string $placeholder
* @property ?string $poster
* @property ?string $preload
* @property ?string $radiogroup
* @property ?bool $readonly
* @property ?string $rel
* @property ?bool $required
* @property ?bool $reversed
* @property ?int $rows
* @property ?int $rowspan
* @property ?string $sandbox
* @property ?string $scope
* @property ?bool $selected
* @property ?string $shape
* @property ?int $size
* @property ?string $sizes
* @property ?string $slot
* @property ?int $span
* @property ?string $spellcheck
* @property ?string $src
* @property ?string $srcdoc
* @property ?string $srclang
* @property ?string $srcset
* @property ?int $start
* @property ?float $step
* @property ?string $style
* @property ?int $tabindex
* @property ?string $target
* @property ?string $title
* @property ?string $translate
* @property ?string $type
* @property ?string $usemap
* @property ?string $value
* @property ?int $width
* @property ?string $wrap
*
* @method self accept(?string $val)
* @method self accesskey(?string $val, bool $state = null)
* @method self action(?string $val)
* @method self align(?string $val)
* @method self allow(?string $val, bool $state = null)
* @method self alt(?string $val)
* @method self async(?bool $val)
* @method self autocapitalize(?string $val)
* @method self autocomplete(?string $val)
* @method self autofocus(?bool $val)
* @method self autoplay(?bool $val)
* @method self charset(?string $val)
* @method self checked(?bool $val)
* @method self cite(?string $val)
* @method self class(?string $val, bool $state = null)
* @method self cols(?int $val)
* @method self colspan(?int $val)
* @method self content(?string $val)
* @method self contenteditable(?bool $val)
* @method self controls(?bool $val)
* @method self coords(?string $val)
* @method self crossorigin(?string $val)
* @method self datetime(?string $val)
* @method self decoding(?string $val)
* @method self default(?bool $val)
* @method self defer(?bool $val)
* @method self dir(?string $val)
* @method self dirname(?string $val)
* @method self disabled(?bool $val)
* @method self download(?bool $val)
* @method self draggable(?string $val)
* @method self dropzone(?string $val)
* @method self enctype(?string $val)
* @method self for(?string $val)
* @method self form(?string $val)
* @method self formaction(?string $val)
* @method self formenctype(?string $val)
* @method self formmethod(?string $val)
* @method self formnovalidate(?bool $val)
* @method self formtarget(?string $val)
* @method self headers(?string $val, bool $state = null)
* @method self height(?int $val)
* @method self hidden(?bool $val)
* @method self high(?float $val)
* @method self hreflang(?string $val)
* @method self id(?string $val)
* @method self integrity(?string $val)
* @method self inputmode(?string $val)
* @method self ismap(?bool $val)
* @method self itemprop(?string $val)
* @method self kind(?string $val)
* @method self label(?string $val)
* @method self lang(?string $val)
* @method self list(?string $val)
* @method self loop(?bool $val)
* @method self low(?float $val)
* @method self max(?float $val)
* @method self maxlength(?int $val)
* @method self minlength(?int $val)
* @method self media(?string $val)
* @method self method(?string $val)
* @method self min(?float $val)
* @method self multiple(?bool $val)
* @method self muted(?bool $val)
* @method self name(?string $val)
* @method self novalidate(?bool $val)
* @method self open(?bool $val)
* @method self optimum(?float $val)
* @method self pattern(?string $val)
* @method self ping(?string $val, bool $state = null)
* @method self placeholder(?string $val)
* @method self poster(?string $val)
* @method self preload(?string $val)
* @method self radiogroup(?string $val)
* @method self readonly(?bool $val)
* @method self rel(?string $val)
* @method self required(?bool $val)
* @method self reversed(?bool $val)
* @method self rows(?int $val)
* @method self rowspan(?int $val)
* @method self sandbox(?string $val, bool $state = null)
* @method self scope(?string $val)
* @method self selected(?bool $val)
* @method self shape(?string $val)
* @method self size(?int $val)
* @method self sizes(?string $val)
* @method self slot(?string $val)
* @method self span(?int $val)
* @method self spellcheck(?string $val)
* @method self src(?string $val)
* @method self srcdoc(?string $val)
* @method self srclang(?string $val)
* @method self srcset(?string $val)
* @method self start(?int $val)
* @method self step(?float $val)
* @method self style(?string $property, string $val = null)
* @method self tabindex(?int $val)
* @method self target(?string $val)
* @method self title(?string $val)
* @method self translate(?string $val)
* @method self type(?string $val)
* @method self usemap(?string $val)
* @method self value(?string $val)
* @method self width(?int $val)
* @method self wrap(?string $val)
*
* @method static static text(mixed $text)
* @method static static html(mixed $html)
*
* @implements \IteratorAggregate<int, self|string>
* @implements \ArrayAccess<int, self|string>
*/
class Html implements \ArrayAccess, \Countable, \IteratorAggregate, HtmlStringable
{
/** @var array<string, mixed> element's attributes */
public array $attrs = [];
/** @var array<string, int> void elements */
public static array $emptyElements = [
'img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1,
'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1,
'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1,
];
/** @var array<int, self|string> nodes */
protected array $children = [];
/** element's name */
private string $name = '';
private bool $isEmpty = false;
/**
* Constructs new HTML element.
* @param array<string, mixed>|string|null $attrs element's attributes or plain text content
*/
public static function el(?string $name = null, array|string|null $attrs = null): static
{
$el = new static;
$parts = explode(' ', (string) $name, 2);
$el->setName($parts[0]);
if (is_array($attrs)) {
$el->attrs = $attrs;
} elseif ($attrs !== null) {
$el->setText($attrs);
}
if (isset($parts[1])) {
foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\2|\s))?#i') as $m) {
$el->attrs[$m[1]] = $m[3] ?? true;
}
}
return $el;
}
/**
* Creates a nameless element (fragment) containing the given children.
* Everything except HtmlStringable is escaped; use Html::html() for raw HTML. Nulls are skipped.
*/
public static function fragment(HtmlStringable|\Stringable|string|int|null ...$children): static
{
return (new static)->add(...$children);
}
/**
* Returns an object representing HTML text.
* @deprecated use Html::html()
*/
public static function fromHtml(string $html): static
{
return (new static)->setHtml($html);
}
/**
* Returns an object representing plain text.
* @deprecated use Html::text()
*/
public static function fromText(string $text): static
{
return (new static)->setText($text);
}
/**
* Converts to HTML.
*/
final public function toHtml(): string
{
return $this->render();
}
/**
* Converts to plain text.
*/
final public function toText(): string
{
return $this->getText();
}
/**
* Converts given HTML code to plain text.
*/
public static function htmlToText(string $html): string
{
return html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Changes element's name.
*/
final public function setName(string $name, ?bool $isEmpty = null): static
{
$this->name = $name;
$this->isEmpty = $isEmpty ?? isset(static::$emptyElements[$name]);
return $this;
}
/**
* Returns element's name.
*/
final public function getName(): string
{
return $this->name;
}
/**
* Checks whether the element is a void (self-closing) element.
*/
final public function isEmpty(): bool
{
return $this->isEmpty;
}
/**
* Sets multiple attributes.
* @param array<string, mixed> $attrs
*/
public function addAttributes(array $attrs): static
{
$this->attrs = array_merge($this->attrs, $attrs);
return $this;
}
/**
* Appends value to element's attribute.
*/
public function appendAttribute(string $name, mixed $value, mixed $option = true): static
{
if (is_array($value)) {
$prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : [];
$this->attrs[$name] = $value + $prev;
} elseif ((string) $value === '') {
$tmp = &$this->attrs[$name]; // appending empty value? -> ignore, but ensure it exists
} elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) { // needs array
$this->attrs[$name][$value] = $option;
} else {
$this->attrs[$name] = [$this->attrs[$name] => true, $value => $option];
}
return $this;
}
/**
* Sets element's attribute.
*/
public function setAttribute(string $name, mixed $value): static
{
$this->attrs[$name] = $value;
return $this;
}
/**
* Returns element's attribute.
*/
public function getAttribute(string $name): mixed
{
return $this->attrs[$name] ?? null;
}
/**
* Unsets element's attribute.
*/
public function removeAttribute(string $name): static
{
unset($this->attrs[$name]);
return $this;
}
/**
* Unsets element's attributes.
* @param list<string> $attributes
*/
public function removeAttributes(array $attributes): static
{
foreach ($attributes as $name) {
unset($this->attrs[$name]);
}
return $this;
}
/**
* Sets element's attribute via property assignment.
*/
final public function __set(string $name, mixed $value): void
{
$this->attrs[$name] = $value;
}
/**
* Returns element's attribute via property access.
*/
final public function &__get(string $name): mixed
{
return $this->attrs[$name];
}
/**
* Checks if element's attribute is set.
*/
final public function __isset(string $name): bool
{
return isset($this->attrs[$name]);
}
/**
* Unsets element's attribute via property unset.
*/
final public function __unset(string $name): void
{
unset($this->attrs[$name]);
}
/**
* Sets or returns element's attribute via method call.
* @param mixed[] $args
*/
final public function __call(string $m, array $args): mixed
{
if ($m === 'text' || $m === 'html') {
trigger_error("Method \$el->$m() is deprecated, use set" . ucfirst($m) . "() for content or setAttribute() for the '$m' attribute; Html::$m() is a static factory.", E_USER_DEPRECATED);
}
$p = substr($m, 0, 3);
if ($p === 'get' || $p === 'set' || $p === 'add') {
$m = substr($m, 3);
$m[0] = $m[0] | "\x20";
if ($p === 'get') {
return $this->attrs[$m] ?? null;
} elseif ($p === 'add') {
$args[] = true;
}
}
if (count($args) === 0) { // invalid
} elseif (count($args) === 1) { // set
$this->attrs[$m] = $args[0];
} else { // add
$this->appendAttribute($m, $args[0], $args[1]);
}
return $this;
}
/**
* Creates element with escaped text (Html::text()) or raw HTML (Html::html()) content.
* @param mixed[] $args
*/
final public static function __callStatic(string $name, array $args): static
{
return match ($name) {
'text' => (new static)->setText(...$args),
'html' => (new static)->setHtml(...$args),
default => ObjectHelpers::strictStaticCall(static::class, $name),
};
}
/**
* Special setter for element's attribute.
* @param array<string, mixed> $query
*/
final public function href(string $path, array $query = []): static
{
if ($query) {
$query = http_build_query($query, '', '&');
if ($query !== '') {
$path .= '?' . $query;
}
}
$this->attrs['href'] = $path;
return $this;
}
/**
* Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'.
*/
public function data(string $name, mixed $value = null): static
{
if (func_num_args() === 1) {
$this->attrs['data'] = $name;
} else {
$this->attrs["data-$name"] = is_bool($value)
? json_encode($value)
: $value;
}
return $this;
}
/**
* Sets element's HTML content.
*/
final public function setHtml(mixed $html): static
{
$this->children = [(string) $html];
return $this;
}
/**
* Returns element's HTML content.
*/
final public function getHtml(): string
{
return implode('', $this->children);
}
/**
* Sets element's textual content.
*/
final public function setText(mixed $text): static
{
if (!$text instanceof HtmlStringable) {
$text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8');
}
$this->children = [(string) $text];
return $this;
}
/**
* Returns element's textual content.
*/
final public function getText(): string
{
return self::htmlToText($this->getHtml());
}
/**
* Appends the given children. Everything except HtmlStringable is escaped; use Html::html() for raw HTML. Nulls are skipped.
*/
public function add(HtmlStringable|\Stringable|string|int|null ...$children): static
{
foreach ($children as $child) {
if ($child !== null) {
$this->addText($child);
}
}
return $this;
}
/**
* Adds new element's child.
*/
final public function addHtml(HtmlStringable|string $child): static
{
return $this->insert(null, $child);
}
/**
* Appends plain-text string to element content.
*/
public function addText(\Stringable|string|int|null $text): static
{
if (!$text instanceof HtmlStringable) {
$text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8');
}
return $this->insert(null, $text);
}
/**
* Creates and adds a new Html child.
* @param array<string, mixed>|string|null $attrs
*/
final public function create(string $name, array|string|null $attrs = null): static
{
$this->insert(null, $child = static::el($name, $attrs));
return $child;
}
/**
* Inserts child node.
*/
public function insert(?int $index, HtmlStringable|string $child, bool $replace = false): static
{
$child = $child instanceof self ? $child : (string) $child;
if ($index === null) { // append
$this->children[] = $child;
} else { // insert or replace
array_splice($this->children, $index, $replace ? 1 : 0, [$child]);
}
return $this;
}
/**
* Inserts (replaces) child node (\ArrayAccess implementation).
* @param ?int $index position or null for appending
* @param Html|string $child Html node or raw HTML string
*/
final public function offsetSet($index, $child): void
{
$this->insert($index, $child, replace: true);
}
/**
* Returns child node (\ArrayAccess implementation).
* @param int $index
*/
final public function offsetGet($index): self|string
{
return $this->children[$index];
}
/**
* Exists child node? (\ArrayAccess implementation).
* @param int $index
*/
final public function offsetExists($index): bool
{
return isset($this->children[$index]);
}
/**
* Removes child node (\ArrayAccess implementation).
* @param int $index
*/
public function offsetUnset($index): void
{
if (isset($this->children[$index])) {
array_splice($this->children, $index, 1);
}
}
/**
* Returns children count.
*/
final public function count(): int
{
return count($this->children);
}
/**
* Removes all children.
*/
public function removeChildren(): void
{
$this->children = [];
}
/**
* Iterates over elements.
* @return \ArrayIterator<int, self|string>
*/
final public function getIterator(): \ArrayIterator
{
return new \ArrayIterator($this->children);
}
/**
* Returns all children.
* @return array<int, self|string>
*/
final public function getChildren(): array
{
return $this->children;
}
/**
* Renders element's start tag, content and end tag. Pass indent level to enable pretty-printing.
*/
final public function render(?int $indent = null): string
{
$s = $this->startTag();
if (!$this->isEmpty) {
// add content
if ($indent !== null) {
$indent++;
}
foreach ($this->children as $child) {
if ($child instanceof self) {
$s .= $child->render($indent);
} else {
$s .= $child;
}
}
// add end tag
$s .= $this->endTag();
}
if ($indent !== null) {
return "\n" . str_repeat("\t", $indent - 1) . $s . "\n" . str_repeat("\t", max(0, $indent - 2));
}
return $s;
}
final public function __toString(): string
{
return $this->render();
}
/**
* Returns element's start tag.
*/
final public function startTag(): string
{
return $this->name
? '<' . $this->name . $this->attributes() . '>'
: '';
}
/**
* Returns element's end tag.
*/
final public function endTag(): string
{
return $this->name && !$this->isEmpty ? '</' . $this->name . '>' : '';
}
/**
* Returns element's attributes.
* @internal
*/
final public function attributes(): string
{
$s = '';
$attrs = $this->attrs;
foreach ($attrs as $key => $value) {
if ($value === null || $value === false) {
continue;
} elseif ($value === true) {
$s .= ' ' . $key;
continue;
} elseif (is_array($value)) {
if (str_starts_with($key, 'data-')) {
$value = Json::encode($value);
} else {
$tmp = null;
foreach ($value as $k => $v) {
if ($v != null) { // intentionally ==, skip nulls & empty string
// composite 'style' vs. 'others'
$tmp[] = $v === true
? $k
: (is_string($k) ? $k . ':' . $v : $v);
}
}
if ($tmp === null) {
continue;
}
$value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp);
}
} elseif (is_float($value)) {
$value = rtrim(rtrim(number_format($value, 10, '.', ''), '0'), '.');
} else {
$value = (string) $value;
}
$q = str_contains($value, '"') ? "'" : '"';
$s .= ' ' . $key . '=' . $q
. str_replace(
['&', $q],
['&amp;', $q === '"' ? '&quot;' : '&#39;'],
$value,
)
. (str_contains($value, '`') && strpbrk($value, ' <>"\'') === false ? ' ' : '')
. $q;
}
$s = str_replace('@', '&#64;', $s);
return $s;
}
/**
* Clones all children too.
*/
public function __clone()
{
foreach ($this->children as $key => $value) {
if (is_object($value)) {
$this->children[$key] = clone $value;
}
}
}
}

853
vendor/nette/utils/src/Utils/Image.php vendored Normal file
View file

@ -0,0 +1,853 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function is_array, is_int, is_string;
use const IMG_BMP, IMG_FLIP_BOTH, IMG_FLIP_HORIZONTAL, IMG_FLIP_VERTICAL, IMG_GIF, IMG_JPG, IMG_PNG, IMG_WEBP, PATHINFO_EXTENSION;
/**
* Basic manipulation with images. Supported types are JPEG, PNG, GIF, WEBP, AVIF and BMP.
*
* <code>
* $image = Image::fromFile('nette.jpg');
* $image->resize(150, 100);
* $image->sharpen();
* $image->send();
* </code>
*
* @method Image affine(array<int, float|int> $affine, ?array{x: int, y: int, width: int, height: int} $clip = null)
* @method void alphaBlending(bool $enable)
* @method void antialias(bool $enable)
* @method void arc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color)
* @method int colorAllocate(int $red, int $green, int $blue)
* @method int colorAllocateAlpha(int $red, int $green, int $blue, int $alpha)
* @method int colorAt(int $x, int $y)
* @method int colorClosest(int $red, int $green, int $blue)
* @method int colorClosestAlpha(int $red, int $green, int $blue, int $alpha)
* @method int colorClosestHWB(int $red, int $green, int $blue)
* @method void colorDeallocate(int $color)
* @method int colorExact(int $red, int $green, int $blue)
* @method int colorExactAlpha(int $red, int $green, int $blue, int $alpha)
* @method void colorMatch(Image $image2)
* @method int colorResolve(int $red, int $green, int $blue)
* @method int colorResolveAlpha(int $red, int $green, int $blue, int $alpha)
* @method void colorSet(int $index, int $red, int $green, int $blue, int $alpha = 0)
* @method array{red: int, green: int, blue: int, alpha: int} colorsForIndex(int $color)
* @method int colorsTotal()
* @method int colorTransparent(?int $color = null)
* @method void convolution(array<int, array<int, float>> $matrix, float $div, float $offset)
* @method void copy(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH)
* @method void copyMerge(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
* @method void copyMergeGray(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $srcW, int $srcH, int $pct)
* @method void copyResampled(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
* @method void copyResized(Image $src, int $dstX, int $dstY, int $srcX, int $srcY, int $dstW, int $dstH, int $srcW, int $srcH)
* @method Image cropAuto(int $mode = 0, float $threshold = .5, ?ImageColor $color = null)
* @method void ellipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
* @method void fill(int $x, int $y, ImageColor $color)
* @method void filledArc(int $centerX, int $centerY, int $width, int $height, int $startAngle, int $endAngle, ImageColor $color, int $style)
* @method void filledEllipse(int $centerX, int $centerY, int $width, int $height, ImageColor $color)
* @method void filledPolygon(array<int, int> $points, ImageColor $color)
* @method void filledRectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
* @method void fillToBorder(int $x, int $y, ImageColor $borderColor, ImageColor $color)
* @method void filter(int $filter, ...$args)
* @method void flip(int $mode)
* @method array<int, int> ftText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontFile, string $text, array<string, mixed> $options = [])
* @method void gammaCorrect(float $inputgamma, float $outputgamma)
* @method array{int, int, int, int} getClip()
* @method int getInterpolation()
* @method int interlace(?bool $enable = null)
* @method bool isTrueColor()
* @method void layerEffect(int $effect)
* @method void line(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
* @method void openPolygon(array<int, int> $points, ImageColor $color)
* @method void paletteCopy(Image $source)
* @method void paletteToTrueColor()
* @method void polygon(array<int, int> $points, ImageColor $color)
* @method void rectangle(int $x1, int $y1, int $x2, int $y2, ImageColor $color)
* @method mixed resolution(?int $resolutionX = null, ?int $resolutionY = null)
* @method Image rotate(float $angle, ImageColor $backgroundColor)
* @method void saveAlpha(bool $enable)
* @method Image scale(int $newWidth, int $newHeight = -1, int $mode = 3)
* @method void setBrush(Image $brush)
* @method void setClip(int $x1, int $y1, int $x2, int $y2)
* @method void setInterpolation(int $method = 3)
* @method void setPixel(int $x, int $y, ImageColor $color)
* @method void setStyle(array<int, int> $style)
* @method void setThickness(int $thickness)
* @method void setTile(Image $tile)
* @method void trueColorToPalette(bool $dither, int $ncolors)
* @method array<int, int> ttfText(float $size, float $angle, int $x, int $y, ImageColor $color, string $fontfile, string $text, array<string, mixed> $options = [])
* @property-read positive-int $width
* @property-read positive-int $height
* @property-read \GdImage $imageResource
*/
class Image
{
use Nette\SmartObject;
/** Prevent from getting resized to a bigger size than the original */
public const ShrinkOnly = 0b0001;
/** Resizes to a specified width and height without keeping aspect ratio */
public const Stretch = 0b0010;
/** Resizes to fit into a specified width and height and preserves aspect ratio */
public const OrSmaller = 0b0000;
/** Resizes while bounding the smaller dimension to the specified width or height and preserves aspect ratio */
public const OrBigger = 0b0100;
/** Resizes to the smallest possible size to completely cover specified width and height and reserves aspect ratio */
public const Cover = 0b1000;
/** @deprecated use Image::ShrinkOnly */
public const SHRINK_ONLY = self::ShrinkOnly;
/** @deprecated use Image::Stretch */
public const STRETCH = self::Stretch;
/** @deprecated use Image::OrSmaller */
public const FIT = self::OrSmaller;
/** @deprecated use Image::OrBigger */
public const FILL = self::OrBigger;
/** @deprecated use Image::Cover */
public const EXACT = self::Cover;
/** @deprecated use Image::EmptyGIF */
public const EMPTY_GIF = self::EmptyGIF;
/** image types */
public const
JPEG = ImageType::JPEG,
PNG = ImageType::PNG,
GIF = ImageType::GIF,
WEBP = ImageType::WEBP,
AVIF = ImageType::AVIF,
BMP = ImageType::BMP;
public const EmptyGIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;";
private const Formats = [ImageType::JPEG => 'jpeg', ImageType::PNG => 'png', ImageType::GIF => 'gif', ImageType::WEBP => 'webp', ImageType::AVIF => 'avif', ImageType::BMP => 'bmp'];
private const Sentinel = "\0";
private \GdImage $image;
/**
* Returns RGB color (0..255) and transparency (0..127).
* @deprecated use ImageColor::rgb()
* @return array{red: int, green: int, blue: int, alpha: int}
*/
public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array
{
return [
'red' => max(0, min(255, $red)),
'green' => max(0, min(255, $green)),
'blue' => max(0, min(255, $blue)),
'alpha' => max(0, min(127, $transparency)),
];
}
/**
* Reads an image from a file and returns its type in $type. If $warnings is passed, recoverable decoder
* warnings are returned in it instead of being raised as a PHP warning.
* @param-out ?string $warnings
* @throws Nette\NotSupportedException if gd extension is not loaded
* @throws UnknownImageFileException if file not found or file type is not known
*/
public static function fromFile(string $file, ?int &$type = null, ?string &$warnings = self::Sentinel): static
{
self::ensureExtension();
$type = self::detectTypeFromFile($file);
if (!$type) {
throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found.");
}
return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '$file'.", __METHOD__, $warnings);
}
/**
* Reads an image from a string and returns its type in $type. If $warnings is passed, recoverable decoder
* warnings are returned in it instead of being raised as a PHP warning.
* @param-out ?string $warnings
* @throws Nette\NotSupportedException if gd extension is not loaded
* @throws ImageException
*/
public static function fromString(string $s, ?int &$type = null, ?string &$warnings = self::Sentinel): static
{
self::ensureExtension();
$type = self::detectTypeFromString($s);
if (!$type) {
throw new UnknownImageFileException('Unknown type of image.');
}
return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__, $warnings);
}
/** @param callable-string $func */
private static function invokeSafe(
string $func,
string $arg,
string $message,
string $callee,
?string &$warnings = self::Sentinel,
): static
{
$errors = [];
$res = Callback::invokeSafe($func, [$arg], function (string $message) use (&$errors): void {
$errors[] = $message;
});
$raiseWarning = $warnings === self::Sentinel;
$warnings = $errors ? implode(', ', $errors) : null;
if (!$res) {
throw new ImageException($message . ' Errors: ' . $warnings);
} elseif ($errors && $raiseWarning) {
trigger_error($callee . '(): ' . $warnings, E_USER_WARNING);
}
return new static($res);
}
/**
* Creates a new true color image of the given dimensions. The default color is black.
* @param positive-int $width
* @param positive-int $height
* @param ImageColor|array{red: int, green: int, blue: int, alpha?: int}|null $color
* @throws Nette\NotSupportedException if gd extension is not loaded
*/
public static function fromBlank(int $width, int $height, ImageColor|array|null $color = null): static
{
self::ensureExtension();
if ($width < 1 || $height < 1) {
throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.');
}
$image = new static(imagecreatetruecolor($width, $height));
if ($color) {
$image->alphaBlending(false);
$image->filledRectangle(0, 0, $width - 1, $height - 1, self::normalizeColor($color));
$image->alphaBlending(true);
}
return $image;
}
/**
* Returns the type of image from file.
* @param-out ?int $width
* @param-out ?int $height
* @return ?ImageType::*
*/
public static function detectTypeFromFile(string $file, mixed &$width = null, mixed &$height = null): ?int
{
[$width, $height, $type] = Helpers::falseToNull(@getimagesize($file)); // @ - files smaller than 12 bytes causes read error
return $type && isset(self::Formats[$type]) ? $type : null;
}
/**
* Returns the type of image from string.
* @param-out ?int $width
* @param-out ?int $height
* @return ?ImageType::*
*/
public static function detectTypeFromString(string $s, mixed &$width = null, mixed &$height = null): ?int
{
[$width, $height, $type] = Helpers::falseToNull(@getimagesizefromstring($s)); // @ - strings smaller than 12 bytes causes read error
return $type && isset(self::Formats[$type]) ? $type : null;
}
/**
* Returns the file extension for the given image type.
* @param ImageType::* $type
* @return value-of<self::Formats>
*/
public static function typeToExtension(int $type): string
{
if (!isset(self::Formats[$type])) {
throw new Nette\InvalidArgumentException("Unsupported image type '$type'.");
}
return self::Formats[$type];
}
/**
* Returns the image type for given file extension.
* @return ImageType::*
*/
public static function extensionToType(string $extension): int
{
$extensions = array_flip(self::Formats) + ['jpg' => ImageType::JPEG];
$extension = strtolower($extension);
if (!isset($extensions[$extension])) {
throw new Nette\InvalidArgumentException("Unsupported file extension '$extension'.");
}
return $extensions[$extension];
}
/**
* Returns the mime type for the given image type.
* @param ImageType::* $type
*/
public static function typeToMimeType(int $type): string
{
return 'image/' . self::typeToExtension($type);
}
/**
* Checks whether the given image type is supported by the GD extension.
* @param ImageType::* $type
*/
public static function isTypeSupported(int $type): bool
{
self::ensureExtension();
return (bool) (imagetypes() & match ($type) {
ImageType::JPEG => IMG_JPG,
ImageType::PNG => IMG_PNG,
ImageType::GIF => IMG_GIF,
ImageType::WEBP => IMG_WEBP,
ImageType::AVIF => IMG_AVIF,
ImageType::BMP => IMG_BMP,
default => 0,
});
}
/**
* Returns list of image types supported by the GD extension.
* @return ImageType::*[]
*/
public static function getSupportedTypes(): array
{
self::ensureExtension();
$flag = imagetypes();
return array_filter([
$flag & IMG_GIF ? ImageType::GIF : null,
$flag & IMG_JPG ? ImageType::JPEG : null,
$flag & IMG_PNG ? ImageType::PNG : null,
$flag & IMG_WEBP ? ImageType::WEBP : null,
$flag & IMG_AVIF ? ImageType::AVIF : null,
$flag & IMG_BMP ? ImageType::BMP : null,
]);
}
/**
* Wraps GD image.
*/
public function __construct(\GdImage $image)
{
$this->setImageResource($image);
imagesavealpha($image, true);
}
/**
* Returns image width.
* @return positive-int
*/
public function getWidth(): int
{
return imagesx($this->image);
}
/**
* Returns image height.
* @return positive-int
*/
public function getHeight(): int
{
return imagesy($this->image);
}
/**
* Sets image resource.
*/
protected function setImageResource(\GdImage $image): static
{
$this->image = $image;
return $this;
}
/**
* Returns image GD resource.
*/
public function getImageResource(): \GdImage
{
return $this->image;
}
/**
* Scales an image. Width and height accept pixels or percent.
* @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode
*/
public function resize(int|string|null $width, int|string|null $height, int $mode = self::OrSmaller): static
{
if ($mode & self::Cover) {
if ($width === null || $height === null) {
throw new Nette\InvalidArgumentException('Both width and height must be set for Cover mode.');
}
return $this->resize($width, $height, self::OrBigger)->crop('50%', '50%', $width, $height);
}
[$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $mode);
if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { // resize
$newImage = static::fromBlank($newWidth, $newHeight, ImageColor::rgb(0, 0, 0, 0))->getImageResource();
imagecopyresampled(
$newImage,
$this->image,
0,
0,
0,
0,
$newWidth,
$newHeight,
$this->getWidth(),
$this->getHeight(),
);
$this->image = $newImage;
}
if ($width < 0 || $height < 0) {
imageflip($this->image, $width < 0 ? ($height < 0 ? IMG_FLIP_BOTH : IMG_FLIP_HORIZONTAL) : IMG_FLIP_VERTICAL);
}
return $this;
}
/**
* Calculates dimensions of resized image. Width and height accept pixels or percent.
* @param int-mask-of<self::OrSmaller|self::OrBigger|self::Stretch|self::Cover|self::ShrinkOnly> $mode
* @return array{int<1, max>, int<1, max>}
*/
public static function calculateSize(
int $srcWidth,
int $srcHeight,
int|string|null $newWidth,
int|string|null $newHeight,
int $mode = self::OrSmaller,
): array
{
if ($newWidth === null) {
} elseif (self::isPercent($newWidth)) {
$newWidth = (int) round($srcWidth / 100 * abs($newWidth));
$percents = true;
} else {
$newWidth = abs($newWidth);
}
if ($newHeight === null) {
} elseif (self::isPercent($newHeight)) {
$newHeight = (int) round($srcHeight / 100 * abs($newHeight));
$mode |= empty($percents) ? 0 : self::Stretch;
} else {
$newHeight = abs($newHeight);
}
if ($mode & self::Stretch) { // non-proportional
if (!$newWidth || !$newHeight) {
throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.');
}
if ($mode & self::ShrinkOnly) {
$newWidth = min($srcWidth, $newWidth);
$newHeight = min($srcHeight, $newHeight);
}
} else { // proportional
if (!$newWidth && !$newHeight) {
throw new Nette\InvalidArgumentException('At least width or height must be specified.');
}
$scale = [];
if ($newWidth > 0) { // fit width
$scale[] = $newWidth / $srcWidth;
}
if ($newHeight > 0) { // fit height
$scale[] = $newHeight / $srcHeight;
}
if ($mode & self::OrBigger) {
$scale = [max($scale ?: [1])];
}
if ($mode & self::ShrinkOnly) {
$scale[] = 1;
}
$scale = min($scale ?: [1]);
$newWidth = (int) round($srcWidth * $scale);
$newHeight = (int) round($srcHeight * $scale);
}
return [max((int) $newWidth, 1), max((int) $newHeight, 1)];
}
/**
* Crops image. Arguments accepts pixels or percent.
*/
public function crop(int|string $left, int|string $top, int|string $width, int|string $height): static
{
[$r['x'], $r['y'], $r['width'], $r['height']]
= static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height);
if (gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') {
$this->image = imagecrop($this->image, $r);
imagesavealpha($this->image, true);
} else {
$newImage = static::fromBlank(max(1, $r['width']), max(1, $r['height']), ImageColor::rgb(0, 0, 0, 0))->getImageResource();
imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']);
$this->image = $newImage;
}
return $this;
}
/**
* Calculates dimensions of cutout in image. Arguments accepts pixels or percent.
* @return array{int, int, int, int}
*/
public static function calculateCutout(
int $srcWidth,
int $srcHeight,
int|string $left,
int|string $top,
int|string $newWidth,
int|string $newHeight,
): array
{
$newWidth = (int) (self::isPercent($newWidth) ? round($srcWidth / 100 * $newWidth) : $newWidth);
$newHeight = (int) (self::isPercent($newHeight) ? round($srcHeight / 100 * $newHeight) : $newHeight);
$left = (int) (self::isPercent($left) ? round(($srcWidth - $newWidth) / 100 * $left) : $left);
$top = (int) (self::isPercent($top) ? round(($srcHeight - $newHeight) / 100 * $top) : $top);
if ($left < 0) {
$newWidth += $left;
$left = 0;
}
if ($top < 0) {
$newHeight += $top;
$top = 0;
}
$newWidth = min($newWidth, $srcWidth - $left);
$newHeight = min($newHeight, $srcHeight - $top);
return [$left, $top, $newWidth, $newHeight];
}
/**
* Sharpens image a little bit.
*/
public function sharpen(): static
{
imageconvolution($this->image, [ // my magic numbers ;)
[-1, -1, -1],
[-1, 24, -1],
[-1, -1, -1],
], 16, 0);
return $this;
}
/**
* Puts another image into this image. Left and top accepts pixels or percent.
* @param int<0, 100> $opacity 0..100
*/
public function place(self $image, int|string $left = 0, int|string $top = 0, int $opacity = 100): static
{
$opacity = max(0, min(100, $opacity));
if ($opacity === 0) {
return $this;
}
$width = $image->getWidth();
$height = $image->getHeight();
$left = (int) (self::isPercent($left) ? round(($this->getWidth() - $width) / 100 * $left) : $left);
$top = (int) (self::isPercent($top) ? round(($this->getHeight() - $height) / 100 * $top) : $top);
$output = $input = $image->image;
if ($opacity < 100) {
$tbl = [];
for ($i = 0; $i < 128; $i++) {
$tbl[$i] = round(127 - (127 - $i) * $opacity / 100);
}
$output = imagecreatetruecolor($width, $height);
imagealphablending($output, false);
if (!$image->isTrueColor()) {
$input = $output;
imagefilledrectangle($output, 0, 0, $width, $height, (int) imagecolorallocatealpha($output, 0, 0, 0, 127));
imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height);
}
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$c = \imagecolorat($input, $x, $y);
$c = ($c & 0xFFFFFF) + ($tbl[$c >> 24] << 24);
\imagesetpixel($output, $x, $y, $c);
}
}
imagealphablending($output, true);
}
imagecopy(
$this->image,
$output,
$left,
$top,
0,
0,
$width,
$height,
);
return $this;
}
/**
* Calculates the bounding box for a TrueType text. Returns keys left, top, width and height.
* @param array<string, mixed> $options
* @return array{left: int, top: int, width: int, height: int}
*/
public static function calculateTextBox(
string $text,
string $fontFile,
float $size,
float $angle = 0,
array $options = [],
): array
{
self::ensureExtension();
$box = imagettfbbox($size, $angle, $fontFile, $text, $options);
return [
'left' => $minX = min([$box[0], $box[2], $box[4], $box[6]]),
'top' => $minY = min([$box[1], $box[3], $box[5], $box[7]]),
'width' => max([$box[0], $box[2], $box[4], $box[6]]) - $minX + 1,
'height' => max([$box[1], $box[3], $box[5], $box[7]]) - $minY + 1,
];
}
/**
* Draws a rectangle using top-left coordinates and dimensions instead of two corner coordinates.
*/
public function rectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
{
if ($width !== 0 && $height !== 0) {
$this->rectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
}
}
/**
* Draws a filled rectangle using top-left coordinates and dimensions instead of two corner coordinates.
*/
public function filledRectangleWH(int $x, int $y, int $width, int $height, ImageColor $color): void
{
if ($width !== 0 && $height !== 0) {
$this->filledRectangle($x, $y, $x + $width + ($width > 0 ? -1 : 1), $y + $height + ($height > 0 ? -1 : 1), $color);
}
}
/**
* Saves image to the file. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
* @param ?ImageType::* $type
* @throws ImageException
*/
public function save(string $file, ?int $quality = null, ?int $type = null): void
{
$type ??= self::extensionToType(pathinfo($file, PATHINFO_EXTENSION));
$this->output($type, $quality, $file);
}
/**
* Outputs image to string. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
* @param ImageType::* $type
*/
public function toString(int $type = ImageType::JPEG, ?int $quality = null): string
{
return Helpers::capture(function () use ($type, $quality): void {
$this->output($type, $quality);
});
}
/**
* Outputs image to string.
*/
public function __toString(): string
{
return $this->toString();
}
/**
* Outputs image to browser. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9).
* @param ImageType::* $type
* @throws ImageException
*/
public function send(int $type = ImageType::JPEG, ?int $quality = null): void
{
header('Content-Type: ' . self::typeToMimeType($type));
$this->output($type, $quality);
}
/**
* Outputs image to browser or file.
* @param ImageType::* $type
* @throws ImageException
*/
private function output(int $type, ?int $quality, ?string $file = null): void
{
[$defQuality, $min, $max] = match ($type) {
ImageType::JPEG => [85, 0, 100],
ImageType::PNG => [9, 0, 9],
ImageType::GIF => [null, null, null],
ImageType::WEBP => [80, 0, 100],
ImageType::AVIF => [30, 0, 100],
ImageType::BMP => [null, null, null],
default => throw new Nette\InvalidArgumentException("Unsupported image type '$type'."),
};
$args = [$this->image, $file];
if ($defQuality !== null) {
$args[] = $quality === null ? $defQuality : max($min, min($max, $quality));
}
Callback::invokeSafe('image' . self::Formats[$type], $args, function (string $message) use ($file): void {
if ($file !== null) {
@unlink($file);
}
throw new ImageException($message);
});
}
/**
* Call to undefined method.
* @param mixed[] $args
* @throws Nette\MemberAccessException
*/
public function __call(string $name, array $args): mixed
{
$function = 'image' . $name;
if (!function_exists($function)) {
ObjectHelpers::strictCall(static::class, $name);
}
foreach ($args as $key => $value) {
if ($value instanceof self) {
$args[$key] = $value->getImageResource();
} elseif ($value instanceof ImageColor || (is_array($value) && isset($value['red']))) {
/** @var ImageColor|array{red: int, green: int, blue: int, alpha?: int} $value */
$args[$key] = $this->resolveColor($value);
}
}
$res = $function($this->image, ...$args);
return $res instanceof \GdImage
? $this->setImageResource($res)
: $res;
}
public function __clone()
{
ob_start(fn() => '');
imagepng($this->image, null, 0);
$this->setImageResource(imagecreatefromstring(ob_get_clean()) ?: throw new Nette\ShouldNotHappenException);
}
/** @param-out int|float $num */
private static function isPercent(int|string &$num): bool
{
if (is_string($num) && str_ends_with($num, '%')) {
$num = (float) substr($num, 0, -1);
return true;
} elseif (is_int($num) || $num === (string) (int) $num) {
$num = (int) $num;
return false;
}
throw new Nette\InvalidArgumentException("Expected dimension in int|string, '$num' given.");
}
/**
* Prevents serialization.
*/
public function __serialize(): array
{
throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.');
}
/**
* Resolves a color to a GD color index for the current image.
* @param ImageColor|array{red: int, green: int, blue: int, alpha?: int} $color
*/
public function resolveColor(ImageColor|array $color): int
{
$color = self::normalizeColor($color)->toRGBA();
return imagecolorallocatealpha($this->image, ...$color) ?: imagecolorresolvealpha($this->image, ...$color);
}
/** @param ImageColor|array{red: int, green: int, blue: int, alpha?: int} $color */
private static function normalizeColor(ImageColor|array $color): ImageColor
{
return $color instanceof ImageColor
? $color
: ImageColor::rgb(
$color['red'],
$color['green'],
$color['blue'],
(127 - ($color['alpha'] ?? 0)) / 127,
);
}
private static function ensureExtension(): void
{
if (!extension_loaded('gd')) {
throw new Nette\NotSupportedException('PHP extension GD is not loaded.');
}
}
}

View file

@ -0,0 +1,81 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function hexdec, ltrim, max, min, round, strlen;
/**
* Represent RGB color (0..255) with opacity (0..1).
*/
class ImageColor
{
/**
* Creates a color from RGB components (0..255) and opacity (0..1).
*/
public static function rgb(int $red, int $green, int $blue, float $opacity = 1): self
{
return new self($red, $green, $blue, $opacity);
}
/**
* Accepts formats #RRGGBB, #RRGGBBAA, #RGB, #RGBA
*/
public static function hex(string $hex): self
{
$hex = ltrim($hex, '#');
$len = strlen($hex);
if ($len === 3 || $len === 4) {
return new self(
(int) hexdec($hex[0]) * 17,
(int) hexdec($hex[1]) * 17,
(int) hexdec($hex[2]) * 17,
(int) hexdec($hex[3] ?? 'F') * 17 / 255,
);
} elseif ($len === 6 || $len === 8) {
return new self(
(int) hexdec($hex[0] . $hex[1]),
(int) hexdec($hex[2] . $hex[3]),
(int) hexdec($hex[4] . $hex[5]),
(int) hexdec(($hex[6] ?? 'F') . ($hex[7] ?? 'F')) / 255,
);
} else {
throw new Nette\InvalidArgumentException('Invalid hex color format.');
}
}
private function __construct(
public int $red,
public int $green,
public int $blue,
public float $opacity = 1,
) {
$this->red = max(0, min(255, $red));
$this->green = max(0, min(255, $green));
$this->blue = max(0, min(255, $blue));
$this->opacity = max(0, min(1, $opacity));
}
/**
* Returns GD-compatible color array [R, G, B, alpha].
* @return array{int<0, 255>, int<0, 255>, int<0, 255>, int<0, 127>}
*/
public function toRGBA(): array
{
return [
max(0, min(255, $this->red)),
max(0, min(255, $this->green)),
max(0, min(255, $this->blue)),
max(0, min(127, (int) round(127 - $this->opacity * 127))),
];
}
}

View file

@ -0,0 +1,25 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use const IMAGETYPE_BMP, IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_WEBP;
/**
* Type of image file.
*/
/*enum*/ final class ImageType
{
public const
JPEG = IMAGETYPE_JPEG,
PNG = IMAGETYPE_PNG,
GIF = IMAGETYPE_GIF,
WEBP = IMAGETYPE_WEBP,
AVIF = 19, // IMAGETYPE_AVIF,
BMP = IMAGETYPE_BMP;
}

View file

@ -0,0 +1,271 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function is_array;
/**
* Utilities for iterables.
*/
final class Iterables
{
use Nette\StaticClass;
/**
* Tests for the presence of value.
* @param iterable<mixed> $iterable
*/
public static function contains(iterable $iterable, mixed $value): bool
{
foreach ($iterable as $v) {
if ($v === $value) {
return true;
}
}
return false;
}
/**
* Tests for the presence of key.
* @param iterable<mixed> $iterable
*/
public static function containsKey(iterable $iterable, mixed $key): bool
{
foreach ($iterable as $k => $v) {
if ($k === $key) {
return true;
}
}
return false;
}
/**
* Returns the first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* @template K
* @template V
* @template E
* @param iterable<K, V> $iterable
* @param ?callable(V, K, iterable<K, V>): bool $predicate
* @param ?callable(): E $else
* @return ($else is null ? ?V : V|E)
*/
public static function first(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed
{
foreach ($iterable as $k => $v) {
if (!$predicate || $predicate($v, $k, $iterable)) {
return $v;
}
}
return $else ? $else() : null;
}
/**
* Returns the key of first item (matching the specified predicate if given). If there is no such item, it returns result of invoking $else or null.
* @template K
* @template V
* @template E
* @param iterable<K, V> $iterable
* @param ?callable(V, K, iterable<K, V>): bool $predicate
* @param ?callable(): E $else
* @return ($else is null ? ?K : K|E)
*/
public static function firstKey(iterable $iterable, ?callable $predicate = null, ?callable $else = null): mixed
{
foreach ($iterable as $k => $v) {
if (!$predicate || $predicate($v, $k, $iterable)) {
return $k;
}
}
return $else ? $else() : null;
}
/**
* Tests whether at least one element in the iterable passes the test implemented by the provided function.
* @template K
* @template V
* @param iterable<K, V> $iterable
* @param callable(V, K, iterable<K, V>): bool $predicate
*/
public static function some(iterable $iterable, callable $predicate): bool
{
foreach ($iterable as $k => $v) {
if ($predicate($v, $k, $iterable)) {
return true;
}
}
return false;
}
/**
* Tests whether all elements in the iterable pass the test implemented by the provided function.
* @template K
* @template V
* @param iterable<K, V> $iterable
* @param callable(V, K, iterable<K, V>): bool $predicate
*/
public static function every(iterable $iterable, callable $predicate): bool
{
foreach ($iterable as $k => $v) {
if (!$predicate($v, $k, $iterable)) {
return false;
}
}
return true;
}
/**
* Returns a generator that yields only elements matching the given $predicate. Maintains original keys.
* @template K
* @template V
* @param iterable<K, V> $iterable
* @param callable(V, K, iterable<K, V>): bool $predicate
* @return \Generator<K, V>
*/
public static function filter(iterable $iterable, callable $predicate): \Generator
{
foreach ($iterable as $k => $v) {
if ($predicate($v, $k, $iterable)) {
yield $k => $v;
}
}
}
/**
* Returns a generator that transforms values by calling $transformer. Maintains original keys.
* @template K
* @template V
* @template R
* @param iterable<K, V> $iterable
* @param callable(V, K, iterable<K, V>): R $transformer
* @return \Generator<K, R>
*/
public static function map(iterable $iterable, callable $transformer): \Generator
{
foreach ($iterable as $k => $v) {
yield $k => $transformer($v, $k, $iterable);
}
}
/**
* Returns a generator that transforms keys and values by calling $transformer. If it returns null, the element is skipped.
* @template K
* @template V
* @template ResK
* @template ResV
* @param iterable<K, V> $iterable
* @param callable(V, K, iterable<K, V>): ?array{ResK, ResV} $transformer
* @return \Generator<ResK, ResV>
*/
public static function mapWithKeys(iterable $iterable, callable $transformer): \Generator
{
foreach ($iterable as $k => $v) {
$pair = $transformer($v, $k, $iterable);
if ($pair) {
yield $pair[0] => $pair[1];
}
}
}
/**
* Creates a repeatable iterator from a factory function.
* The factory is called every time the iterator is iterated.
* @template K
* @template V
* @param callable(): iterable<K, V> $factory
* @return \IteratorAggregate<K, V>
*/
public static function repeatable(callable $factory): \IteratorAggregate
{
return new class ($factory(...)) implements \IteratorAggregate {
public function __construct(
/** @var \Closure(): iterable<mixed, mixed> */
private readonly \Closure $factory,
) {
}
public function getIterator(): \Iterator
{
return Iterables::toIterator(($this->factory)());
}
};
}
/**
* Wraps around iterator and caches its keys and values during iteration.
* This allows the data to be re-iterated multiple times.
* @template K
* @template V
* @param iterable<K, V> $iterable
* @return \IteratorAggregate<K, V>
*/
public static function memoize(iterable $iterable): \IteratorAggregate
{
return new class (self::toIterator($iterable)) implements \IteratorAggregate {
public function __construct(
private readonly \Iterator $iterator,
/** @var array<array{mixed, mixed}> */
private array $cache = [],
) {
}
public function getIterator(): \Generator
{
if (!$this->cache) {
$this->iterator->rewind();
}
$i = 0;
while (true) {
if (isset($this->cache[$i])) {
[$k, $v] = $this->cache[$i];
} elseif ($this->iterator->valid()) {
$k = $this->iterator->key();
$v = $this->iterator->current();
$this->iterator->next();
$this->cache[$i] = [$k, $v];
} else {
break;
}
yield $k => $v;
$i++;
}
}
};
}
/**
* Creates an iterator from anything that is iterable.
* @template K
* @template V
* @param iterable<K, V> $iterable
* @return \Iterator<K, V>
*/
public static function toIterator(iterable $iterable): \Iterator
{
return match (true) {
$iterable instanceof \Iterator => $iterable,
$iterable instanceof \IteratorAggregate => self::toIterator($iterable->getIterator()),
is_array($iterable) => new \ArrayIterator($iterable),
default => throw new Nette\ShouldNotHappenException,
};
}
}

83
vendor/nette/utils/src/Utils/Json.php vendored Normal file
View file

@ -0,0 +1,83 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function is_int, json_decode, json_encode, json_last_error, json_last_error_msg;
use const JSON_BIGINT_AS_STRING, JSON_FORCE_OBJECT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_HEX_QUOT, JSON_HEX_TAG, JSON_OBJECT_AS_ARRAY, JSON_PRESERVE_ZERO_FRACTION, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_UNESCAPED_UNICODE;
/**
* JSON encoder and decoder.
*/
final class Json
{
use Nette\StaticClass;
/** @deprecated use Json::decode(..., forceArrays: true) */
public const FORCE_ARRAY = JSON_OBJECT_AS_ARRAY;
/** @deprecated use Json::encode(..., pretty: true) */
public const PRETTY = JSON_PRETTY_PRINT;
/** @deprecated use Json::encode(..., asciiSafe: true) */
public const ESCAPE_UNICODE = 1 << 19;
/**
* Converts value to JSON format. Use $pretty for formatted output, $asciiSafe for ASCII-only output,
* $htmlSafe for HTML-safe output, and $forceObjects to encode non-associative arrays as objects.
* @throws JsonException
*/
public static function encode(
mixed $value,
bool|int $pretty = false,
bool $asciiSafe = false,
bool $htmlSafe = false,
bool $forceObjects = false,
): string
{
if (is_int($pretty)) { // back compatibility
$flags = ($pretty & self::ESCAPE_UNICODE ? 0 : JSON_UNESCAPED_UNICODE) | ($pretty & ~self::ESCAPE_UNICODE);
} else {
$flags = ($asciiSafe ? 0 : JSON_UNESCAPED_UNICODE)
| ($pretty ? JSON_PRETTY_PRINT : 0)
| ($forceObjects ? JSON_FORCE_OBJECT : 0)
| ($htmlSafe ? JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_TAG : 0);
}
$flags |= JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION;
$json = json_encode($value, $flags);
if ($error = json_last_error()) {
throw new JsonException(json_last_error_msg(), $error);
}
return $json;
}
/**
* Decodes a JSON string to a PHP value. Use $forceArrays to decode objects as arrays.
* @throws JsonException
*/
public static function decode(string $json, bool|int $forceArrays = false): mixed
{
$flags = is_int($forceArrays) // back compatibility
? $forceArrays
: ($forceArrays ? JSON_OBJECT_AS_ARRAY : 0);
$flags |= JSON_BIGINT_AS_STRING;
$value = json_decode($json, flags: $flags);
if ($error = json_last_error()) {
throw new JsonException(json_last_error_msg(), $error);
}
return $value;
}
}

View file

@ -0,0 +1,229 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use Nette\MemberAccessException;
use function array_filter, array_merge, array_pop, array_unique, get_class_methods, get_parent_class, implode, is_a, levenshtein, method_exists, preg_match_all, preg_replace, strlen, ucfirst;
use const PREG_SET_ORDER, SORT_REGULAR;
/**
* Nette\SmartObject helpers.
* @internal
*/
final class ObjectHelpers
{
use Nette\StaticClass;
/**
* @return never
* @throws MemberAccessException
*/
public static function strictGet(string $class, string $name): void
{
$rc = new \ReflectionClass($class);
$hint = self::getSuggestion(array_merge(
array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()),
self::parseFullDoc($rc, '~^[ \t*]*@property(?:-read)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'),
), $name);
throw new MemberAccessException("Cannot read an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
}
/**
* @return never
* @throws MemberAccessException
*/
public static function strictSet(string $class, string $name): void
{
$rc = new \ReflectionClass($class);
$hint = self::getSuggestion(array_merge(
array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), fn($p) => !$p->isStatic()),
self::parseFullDoc($rc, '~^[ \t*]*@property(?:-write)?[ \t]+(?:\S+[ \t]+)??\$(\w+)~m'),
), $name);
throw new MemberAccessException("Cannot write to an undeclared property $class::\$$name" . ($hint ? ", did you mean \$$hint?" : '.'));
}
/**
* @return never
* @throws MemberAccessException
*/
public static function strictCall(string $class, string $method, array $additionalMethods = []): void
{
$trace = debug_backtrace(0, 3); // suppose this method is called from __call()
$context = ($trace[1]['function'] ?? null) === '__call'
? ($trace[2]['class'] ?? null)
: null;
if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
$class = get_parent_class($context);
}
if (method_exists($class, $method)) { // insufficient visibility
$rm = new \ReflectionMethod($class, $method);
$visibility = $rm->isPrivate()
? 'private '
: ($rm->isProtected() ? 'protected ' : '');
throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
} else {
$hint = self::getSuggestion(array_merge(
get_class_methods($class),
self::parseFullDoc(new \ReflectionClass($class), '~^[ \t*]*@method[ \t]+(?:static[ \t]+)?(?:\S+[ \t]+)??(\w+)\(~m'),
$additionalMethods,
), $method);
throw new MemberAccessException("Call to undefined method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
}
}
/**
* @return never
* @throws MemberAccessException
*/
public static function strictStaticCall(string $class, string $method): void
{
$trace = debug_backtrace(0, 3); // suppose this method is called from __callStatic()
$context = ($trace[1]['function'] ?? null) === '__callStatic'
? ($trace[2]['class'] ?? null)
: null;
if ($context && is_a($class, $context, true) && method_exists($context, $method)) { // called parent::$method()
$class = get_parent_class($context);
}
if (method_exists($class, $method)) { // insufficient visibility
$rm = new \ReflectionMethod($class, $method);
$visibility = $rm->isPrivate()
? 'private '
: ($rm->isProtected() ? 'protected ' : '');
throw new MemberAccessException("Call to {$visibility}method $class::$method() from " . ($context ? "scope $context." : 'global scope.'));
} else {
$hint = self::getSuggestion(
array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), fn($m) => $m->isStatic()),
$method,
);
throw new MemberAccessException("Call to undefined static method $class::$method()" . ($hint ? ", did you mean $hint()?" : '.'));
}
}
/**
* Returns array of magic properties defined by annotation @property.
* @return array of [name => bit mask]
* @internal
*/
public static function getMagicProperties(string $class): array
{
static $cache;
$props = &$cache[$class];
if ($props !== null) {
return $props;
}
$rc = new \ReflectionClass($class);
preg_match_all(
'~^ [ \t*]* @property(|-read|-write|-deprecated) [ \t]+ [^\s$]+ [ \t]+ \$ (\w+) ()~mx',
(string) $rc->getDocComment(),
$matches,
PREG_SET_ORDER,
);
$props = [];
foreach ($matches as [, $type, $name]) {
$uname = ucfirst($name);
$write = $type !== '-read'
&& $rc->hasMethod($nm = 'set' . $uname)
&& ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
$read = $type !== '-write'
&& ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname))
&& ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic();
if ($read || $write) {
$props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4;
}
}
foreach ($rc->getTraits() as $trait) {
$props += self::getMagicProperties($trait->name);
}
if ($parent = get_parent_class($class)) {
$props += self::getMagicProperties($parent);
}
return $props;
}
/**
* Finds the best suggestion (for 8-bit encoding).
* @param (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[] $possibilities
* @internal
*/
public static function getSuggestion(array $possibilities, string $value): ?string
{
$norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value);
$best = null;
$min = (strlen($value) / 4 + 1) * 10 + .1;
foreach (array_unique($possibilities, SORT_REGULAR) as $item) {
$item = $item instanceof \Reflector ? $item->name : $item;
if ($item !== $value && (
($len = levenshtein($item, $value, 10, 11, 10)) < $min
|| ($len = levenshtein(preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min
)) {
$min = $len;
$best = $item;
}
}
return $best;
}
private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array
{
do {
$doc[] = $rc->getDocComment();
$traits = $rc->getTraits();
while ($trait = array_pop($traits)) {
$doc[] = $trait->getDocComment();
$traits += $trait->getTraits();
}
} while ($rc = $rc->getParentClass());
return preg_match_all($pattern, implode('', $doc), $m) ? $m[1] : [];
}
/**
* Checks if the public non-static property exists.
* Returns 'event' if the property exists and has event like name
* @internal
*/
public static function hasProperty(string $class, string $name): bool|string
{
static $cache;
$prop = &$cache[$class][$name];
if ($prop === null) {
$prop = false;
try {
$rp = new \ReflectionProperty($class, $name);
if ($rp->isPublic() && !$rp->isStatic()) {
$prop = $name >= 'onA' && $name < 'on_' ? 'event' : true;
}
} catch (\ReflectionException) {
}
}
return $prop;
}
}

View file

@ -0,0 +1,210 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
/**
* Paginating math.
*
* @property int $page
* @property-read int $firstPage
* @property-read ?int $lastPage
* @property-read int<0,max> $firstItemOnPage
* @property-read int<0,max> $lastItemOnPage
* @property int $base
* @property-read bool $first
* @property-read bool $last
* @property-read ?int<0,max> $pageCount
* @property positive-int $itemsPerPage
* @property ?int<0,max> $itemCount
* @property-read int<0,max> $offset
* @property-read ?int<0,max> $countdownOffset
* @property-read int<0,max> $length
*/
class Paginator
{
use Nette\SmartObject;
private int $base = 1;
/** @var positive-int */
private int $itemsPerPage = 1;
private int $page = 1;
/** @var ?int<0, max> */
private ?int $itemCount = null;
public function setPage(int $page): static
{
$this->page = $page;
return $this;
}
public function getPage(): int
{
return $this->base + $this->getPageIndex();
}
public function getFirstPage(): int
{
return $this->base;
}
public function getLastPage(): ?int
{
return $this->itemCount === null
? null
: $this->base + max(0, $this->getPageCount() - 1);
}
/**
* Returns the 1-based index of the first item on the current page, or 0 if the page is empty.
* @return int<0, max>
*/
public function getFirstItemOnPage(): int
{
return $this->itemCount !== 0
? $this->offset + 1
: 0;
}
/**
* Returns the 1-based index of the last item on the current page.
* @return int<0, max>
*/
public function getLastItemOnPage(): int
{
return $this->offset + $this->length;
}
public function setBase(int $base): static
{
$this->base = $base;
return $this;
}
public function getBase(): int
{
return $this->base;
}
/**
* Returns zero-based page number.
* @return int<0, max>
*/
protected function getPageIndex(): int
{
$index = max(0, $this->page - $this->base);
return $this->itemCount === null
? $index
: min($index, max(0, $this->getPageCount() - 1));
}
public function isFirst(): bool
{
return $this->getPageIndex() === 0;
}
public function isLast(): bool
{
return $this->itemCount === null
? false
: $this->getPageIndex() >= $this->getPageCount() - 1;
}
/**
* @return ?int<0, max>
*/
public function getPageCount(): ?int
{
return $this->itemCount === null
? null
: max(0, (int) ceil($this->itemCount / $this->itemsPerPage));
}
public function setItemsPerPage(int $itemsPerPage): static
{
$this->itemsPerPage = max(1, $itemsPerPage);
return $this;
}
/**
* @return positive-int
*/
public function getItemsPerPage(): int
{
return $this->itemsPerPage;
}
public function setItemCount(?int $itemCount = null): static
{
$this->itemCount = $itemCount === null ? null : max(0, $itemCount);
return $this;
}
/**
* @return ?int<0, max>
*/
public function getItemCount(): ?int
{
return $this->itemCount;
}
/**
* Returns the absolute index of the first item on current page.
* @return int<0, max>
*/
public function getOffset(): int
{
return $this->getPageIndex() * $this->itemsPerPage;
}
/**
* Returns the absolute index of the first item on current page in countdown paging.
* @return ?int<0, max>
*/
public function getCountdownOffset(): ?int
{
return $this->itemCount === null
? null
: max(0, $this->itemCount - ($this->getPageIndex() + 1) * $this->itemsPerPage);
}
/**
* Returns the number of items on current page.
* @return int<0, max>
*/
public function getLength(): int
{
return $this->itemCount === null
? $this->itemsPerPage
: max(0, min($this->itemsPerPage, $this->itemCount - $this->getPageIndex() * $this->itemsPerPage));
}
}

560
vendor/nette/utils/src/Utils/Process.php vendored Normal file
View file

@ -0,0 +1,560 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function is_resource, is_string, strlen;
use const PHP_VERSION_ID;
/**
* Represents a process, which can be started and controlled (reading output, writing input, waiting for completion).
*/
final class Process
{
private const PollInterval = 10_000;
private const DefaultTimeout = 60;
private const StdIn = 0;
private const StdOut = 1;
private const StdErr = 2;
/** @var resource */
private mixed $process;
/** @var array<string, mixed> result of proc_get_status() */
private array $status = ['running' => true];
/** @var resource */
private mixed $inputPipe;
/** @var array<int, resource|string[]> pipe resources, or ['file', path, mode] descriptors for discarded output */
private array $outputPipes = [];
/** @var string[] */
private array $outputBuffers = [];
/** @var int[] Number of bytes already read from buffers. */
private array $outputBufferOffsets = [];
/** @var array<int, true> Output IDs whose target resource was supplied by the caller and must not be closed here. */
private array $callerOutputs = [];
/** @var array<int, true> Output IDs whose pipe is backed by a temporary file (Windows < 8.5 workaround). */
private array $fileBackedOutputs = [];
private float $startTime;
private bool $detached = false;
/**
* Starts an executable with given arguments. Because the arguments are passed as an array, the shell is
* never involved, so they need no escaping and there is no risk of shell injection.
* @param string $executable Path to the executable binary.
* @param list<string> $arguments Arguments passed to the executable.
* @param string[]|null $env Environment variables or null to use the same environment as the current process.
* @param array<string, mixed> $options Additional options for proc_open(). On Windows the executable is launched directly, without cmd.exe.
* @param mixed $stdin Input: string, a readable resource (its content is copied to STDIN), a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()).
* @param mixed $stdout Output target: string filename, a writable resource backed by a real OS file descriptor (not php://memory etc.), false to discard, or null to capture into memory.
* @param mixed $stderr Error output target (same options as $stdout).
* @param string|null $directory Working directory.
* @param float|null $timeout Time limit in seconds, checked while waiting for or reading the process; null disables it.
*/
public static function runExecutable(
string $executable,
array $arguments = [],
?array $env = null,
array $options = [],
mixed $stdin = '',
mixed $stdout = null,
mixed $stderr = null,
?string $directory = null,
?float $timeout = self::DefaultTimeout,
): self
{
return new self([$executable, ...$arguments], $env, $options, $directory, $stdin, $stdout, $stderr, $timeout);
}
/**
* Starts a process from a command string interpreted by the shell (/bin/sh on POSIX, cmd.exe on Windows).
* Because the shell parses the string, NEVER pass unescaped user input here - use runExecutable() for that.
* @param string $command Shell command to run.
* @param string[]|null $env Environment variables or null to use the same environment as the current process.
* @param array<string, mixed> $options Options for proc_open(), e.g. ['bypass_shell' => true] on Windows to skip cmd.exe.
* @param mixed $stdin Input: string, a readable resource (its content is copied to STDIN), a Process (its STDOUT is piped in), or null (STDIN stays open for writeStdInput()).
* @param mixed $stdout Output target: string filename, a writable resource backed by a real OS file descriptor (not php://memory etc.), false to discard, or null to capture into memory.
* @param mixed $stderr Error output target (same options as $stdout).
* @param string|null $directory Working directory.
* @param float|null $timeout Time limit in seconds, checked while waiting for or reading the process; null disables it.
*/
public static function runCommand(
string $command,
?array $env = null,
array $options = [],
mixed $stdin = '',
mixed $stdout = null,
mixed $stderr = null,
?string $directory = null,
?float $timeout = self::DefaultTimeout,
): self
{
return new self($command, $env, $options, $directory, $stdin, $stdout, $stderr, $timeout);
}
/**
* @param list<string>|string $command
* @param array<string, string>|null $env
* @param array<string, mixed> $options
*/
private function __construct(
string|array $command,
?array $env,
array $options,
?string $directory,
mixed $stdin,
mixed $stdout,
mixed $stderr,
private readonly ?float $timeout,
) {
$descriptors = [
self::StdIn => $this->createInputDescriptor($stdin),
self::StdOut => $this->createOutputDescriptor(self::StdOut, $stdout),
self::StdErr => $this->createOutputDescriptor(self::StdErr, $stderr),
];
$process = @proc_open($command, $descriptors, $pipes, $directory, $env, $options);
if (!is_resource($process)) {
throw new ProcessFailedException('Failed to start process: ' . Helpers::getLastError());
}
$this->process = $process;
[$this->inputPipe, $this->outputPipes[self::StdOut], $this->outputPipes[self::StdErr]] = $pipes + $descriptors;
if ($stdin instanceof self) {
// the source process hands over its STDOUT pipe; from now on this process owns it
unset(
$stdin->outputBuffers[self::StdOut],
$stdin->outputBufferOffsets[self::StdOut],
$stdin->outputPipes[self::StdOut],
);
}
$this->writeInitialInput($stdin);
$this->startTime = microtime(true);
}
public function __destruct()
{
if ($this->detached) {
return;
}
$this->outputBuffers = [];
$this->terminate();
}
/**
* Detaches the process: it keeps running in the background and is not terminated when the object
* is destroyed. STDIN and output pipes are closed, so the output must not be captured in memory
* (pass a file name, a resource or false as $stdout/$stderr). Only the destructor behavior changes:
* wait() and getExitCode() still block ($timeout still applies) and terminate() still kills it.
* On POSIX, a detached child that exits early stays a zombie until the script ends.
*/
public function detach(): void
{
if ($this->outputBuffers !== []) {
throw new Nette\InvalidStateException('Cannot detach process: its output is captured in memory, pass a file name, a resource or false as $stdout/$stderr.');
}
$this->detached = true;
$this->closeStdInput();
$this->closeOutputPipes();
}
/**
* Checks if the process is currently running.
*/
public function isRunning(): bool
{
if (!$this->status['running']) {
return false;
}
$this->status = proc_get_status($this->process);
if (!$this->status['running']) {
$this->close();
}
return $this->status['running'];
}
/**
* Finishes the process by waiting for its completion. While waiting, the captured output is read
* continuously and kept in memory; an optional callback is invoked with each new output/error chunk.
*
* @param (\Closure(string, string): void)|null $callback
*/
public function wait(?\Closure $callback = null): void
{
while ($this->isRunning()) {
$this->enforceTimeout();
$this->drainPipes();
$this->dispatchCallback($callback);
usleep(self::PollInterval);
}
$this->dispatchCallback($callback);
}
/**
* Reads any new data from the captured pipes into the buffers, so a process producing more output
* than the OS pipe buffer holds does not block. With $final (process already finished) reads to EOF.
*/
private function drainPipes(bool $final = false): void
{
foreach ([self::StdOut, self::StdErr] as $id) {
$this->readFromPipe($id, $final);
}
}
/**
* Terminates the running process if it is still running.
*/
public function terminate(): void
{
if (!$this->isRunning()) {
return;
} elseif (Helpers::IsWindows) {
exec("taskkill /F /T /PID {$this->getPid()} 2>&1");
} else {
proc_terminate($this->process, 9); // 9 = SIGKILL: cannot be trapped, so the following proc_close() won't hang
}
$this->status['running'] = false;
$this->close();
}
/**
* Returns the process exit code. If the process is still running, waits until it finishes.
*/
public function getExitCode(): int
{
$this->wait();
return $this->status['exitcode'] ?? -1;
}
/**
* Returns true if the process terminated with exit code 0.
*/
public function isSuccess(): bool
{
return $this->getExitCode() === 0;
}
/**
* Waits for the process to finish and throws ProcessFailedException if exit code is not zero.
*/
public function ensureSuccess(): void
{
$code = $this->getExitCode();
if ($code !== 0) {
throw new ProcessFailedException("Process failed with non-zero exit code: $code");
}
}
/**
* Returns the PID of the running process, or null if it is not running.
*/
public function getPid(): ?int
{
return $this->isRunning() ? $this->status['pid'] : null;
}
/**
* Waits for the process to finish and returns everything it wrote to STDOUT.
*/
public function getStdOutput(): string
{
$this->wait();
return $this->outputBuffers[self::StdOut] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
}
/**
* Waits for the process to finish and returns everything it wrote to STDERR.
*/
public function getStdError(): string
{
$this->wait();
return $this->outputBuffers[self::StdErr] ?? throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
}
/**
* Returns the STDOUT data produced since the previous consumeStdOutput() call.
* To read everything incrementally, poll `while ($p->isRunning())` calling this, then call it once more
* after the loop; that last call returns whatever the process wrote just before the loop noticed it had exited.
*/
public function consumeStdOutput(): string
{
return $this->consumeBuffer(self::StdOut);
}
/**
* Returns the STDERR data produced since the previous consumeStdError() call. See consumeStdOutput().
*/
public function consumeStdError(): string
{
return $this->consumeBuffer(self::StdErr);
}
/**
* Returns newly available data from the specified buffer and advances the read pointer.
*/
private function consumeBuffer(int $id): string
{
if (!isset($this->outputBuffers[$id])) {
throw new Nette\InvalidStateException('Cannot read output: it is not captured (it was redirected, discarded or piped).');
} elseif ($this->isRunning()) {
$this->enforceTimeout();
$this->readFromPipe($id);
}
return $this->extractNewData($id);
}
/**
* Returns the buffered data not returned yet and advances the read pointer.
*/
private function extractNewData(int $id): string
{
if (!isset($this->outputBuffers[$id])) {
return '';
}
$res = substr($this->outputBuffers[$id], $this->outputBufferOffsets[$id]);
$this->outputBufferOffsets[$id] = strlen($this->outputBuffers[$id]);
return $res;
}
/**
* Writes data into the process' STDIN. If STDIN is closed, throws exception.
*/
public function writeStdInput(string $string): void
{
if (!is_resource($this->inputPipe)) {
throw new Nette\InvalidStateException('Cannot write to process: STDIN pipe is closed');
}
$this->writeToPipe($string);
}
/**
* Writes the whole string to STDIN, handling partial writes. Stops (and lets fwrite() warn) on a broken pipe,
* i.e. when the process stopped reading its STDIN.
*/
private function writeToPipe(string $string): void
{
$length = strlen($string);
for ($written = 0; $written < $length; $written += $bytes) {
$bytes = fwrite($this->inputPipe, substr($string, $written));
if (!$bytes) {
break;
}
}
}
/**
* Closes the STDIN pipe, indicating no more data will be sent.
*/
public function closeStdInput(): void
{
if (is_resource($this->inputPipe)) {
fclose($this->inputPipe);
}
}
/**
* If a callback is given, invokes it with the output/error produced since the previous call.
* @param (\Closure(string, string): void)|null $callback
*/
private function dispatchCallback(?\Closure $callback): void
{
if (!$callback) {
return;
}
$output = $this->extractNewData(self::StdOut);
$error = $this->extractNewData(self::StdErr);
if ($output !== '' || $error !== '') {
$callback($output, $error);
}
}
/**
* Checks if the timeout has expired. If yes, terminates the process.
*/
private function enforceTimeout(): void
{
if ($this->timeout !== null && (microtime(true) - $this->startTime) >= $this->timeout) {
$this->terminate();
throw new ProcessTimeoutException('Process exceeded the time limit of ' . $this->timeout . ' seconds');
}
}
/**
* Reads any new data from the specified pipe and appends it to the buffer. Does nothing if the output
* is not captured or the pipe is already closed (or handed over to another process).
*/
private function readFromPipe(int $id, bool $final = false): void
{
$pipe = $this->outputPipes[$id] ?? null;
if (!isset($this->outputBuffers[$id]) || !is_resource($pipe)) {
return;
} elseif (isset($this->fileBackedOutputs[$id])) {
// Windows < 8.5: captured output is a temporary file; read whatever was appended since last time
fseek($pipe, strlen($this->outputBuffers[$id]));
$this->outputBuffers[$id] .= stream_get_contents($pipe);
} elseif ($final) {
// the process has finished, everything is buffered in the pipe; non-blocking read on POSIX
// (cannot hang on a leaked descendant still holding the write end), blocking read to EOF on
// Windows, where non-blocking mode does not work and stream_select() may miss buffered data
stream_set_blocking($pipe, Helpers::IsWindows);
$this->outputBuffers[$id] .= stream_get_contents($pipe);
} else {
// non-blocking drain: stream_set_blocking(false) works on POSIX only, so reads are also
// guarded by stream_select(), which works on Windows pipes since PHP 8.5 (PeekNamedPipe fix)
stream_set_blocking($pipe, false);
$read = [$pipe];
$write = $except = [];
while (@stream_select($read, $write, $except, 0, 0) > 0) {
$chunk = fread($pipe, 8192);
if ($chunk === false || $chunk === '') {
break;
}
$this->outputBuffers[$id] .= $chunk;
$read = [$pipe];
}
}
}
/**
* Sends the initial input to the process: writes and closes a string or stream input,
* or leaves STDIN open when input is null (until closeStdInput()) or another Process (fed by that process).
* The input type was already validated by createInputDescriptor().
*
* Note: a string or stream input is written upfront, so if it is large and the process does not read it
* while filling its own output, this can block; in that case pass null and feed STDIN via writeStdInput().
*/
private function writeInitialInput(mixed $input): void
{
if ($input === null || $input instanceof self) {
// STDIN stays open
} elseif (is_string($input)) {
$this->writeToPipe($input);
$this->closeStdInput();
} elseif (is_resource($input)) {
stream_copy_to_stream($input, $this->inputPipe);
$this->closeStdInput();
}
}
/**
* Validates the input and determines the STDIN descriptor based on its type.
*/
private function createInputDescriptor(mixed $input): mixed
{
if ($input === null || is_string($input) || is_resource($input)) {
return ['pipe', 'r'];
} elseif (!$input instanceof self) {
throw new Nette\InvalidArgumentException('Input must be string, resource, Process or null, ' . get_debug_type($input) . ' given.');
} elseif (Helpers::IsWindows) {
throw new Nette\NotSupportedException('Process piping is not supported on Windows.');
} elseif (!isset($input->outputBuffers[self::StdOut]) || !is_resource($input->outputPipes[self::StdOut] ?? null)) {
throw new Nette\InvalidStateException('Cannot pipe from the given process: its STDOUT must be captured (it must not be redirected elsewhere).');
}
return $input->outputPipes[self::StdOut];
}
/**
* Determines the descriptor for STDOUT or STDERR based on the specified output target.
*/
private function createOutputDescriptor(int $id, mixed $output): mixed
{
if (is_resource($output)) {
$this->callerOutputs[$id] = true;
return $output;
} elseif (is_string($output)) {
return FileSystem::open($output, 'w');
} elseif ($output === false) {
return ['file', Helpers::IsWindows ? 'NUL' : '/dev/null', 'w'];
} elseif ($output === null) {
$this->outputBuffers[$id] = '';
$this->outputBufferOffsets[$id] = 0;
if (Helpers::IsWindows && PHP_VERSION_ID < 80500) {
// Windows < 8.5: stream_select() doesn't work on pipes, capture into a temp file that reads non-blockingly
$this->fileBackedOutputs[$id] = true;
return tmpfile();
}
return ['pipe', 'w'];
} else {
throw new Nette\InvalidArgumentException('Output must be string, resource, bool or null, ' . get_debug_type($output) . ' given.');
}
}
/**
* Closes all pipes and the process resource.
*/
private function close(): void
{
$this->drainPipes(final: true);
$this->closeStdInput();
$this->closeOutputPipes();
proc_close($this->process);
}
/**
* Closes the output pipes that this class opened; resources supplied by the caller are left untouched.
* (The temporary file backing captured output on Windows < 8.5 is removed by fclose() itself.)
*/
private function closeOutputPipes(): void
{
foreach ($this->outputPipes as $id => $pipe) {
if (is_resource($pipe) && !isset($this->callerOutputs[$id])) {
fclose($pipe);
}
}
}
}

52
vendor/nette/utils/src/Utils/Random.php vendored Normal file
View file

@ -0,0 +1,52 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use Random\Randomizer;
use function strlen;
use const PHP_VERSION_ID;
/**
* Secure random string generator.
*/
final class Random
{
use Nette\StaticClass;
/**
* Generates a random string of given length from characters specified in second argument.
* Supports intervals, such as `0-9` or `A-Z`.
*/
public static function generate(int $length = 10, string $charlist = '0-9a-z'): string
{
$charlist = preg_replace_callback(
'#.-.#',
fn(array $m): string => implode('', range($m[0][0], $m[0][2])),
$charlist,
);
$charlist = count_chars($charlist, mode: 3);
$chLen = strlen($charlist);
if ($length < 1) {
throw new Nette\InvalidArgumentException('Length must be greater than zero.');
} elseif ($chLen < 2) {
throw new Nette\InvalidArgumentException('Character list must contain at least two chars.');
} elseif (PHP_VERSION_ID >= 80300) {
return (new Randomizer)->getBytesFromString($charlist, $length);
}
$res = '';
for ($i = 0; $i < $length; $i++) {
$res .= $charlist[random_int(0, $chLen - 1)];
}
return $res;
}
}

View file

@ -0,0 +1,335 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function constant, current, defined, end, explode, file_get_contents, implode, ltrim, next, ord, strrchr, strtolower, substr;
use const T_AS, T_CLASS, T_COMMENT, T_CURLY_OPEN, T_DOC_COMMENT, T_DOLLAR_OPEN_CURLY_BRACES, T_ENUM, T_INTERFACE, T_NAME_FULLY_QUALIFIED, T_NAME_QUALIFIED, T_NAMESPACE, T_NS_SEPARATOR, T_STRING, T_TRAIT, T_USE, T_WHITESPACE, TOKEN_PARSE;
/**
* PHP reflection helpers.
*/
final class Reflection
{
use Nette\StaticClass;
/** @deprecated use Nette\Utils\Validators::isBuiltinType() */
public static function isBuiltinType(string $type): bool
{
return Validators::isBuiltinType($type);
}
#[\Deprecated('use Nette\Utils\Validators::isClassKeyword()')]
public static function isClassKeyword(string $name): bool
{
return Validators::isClassKeyword($name);
}
/**
* Returns the default value of a parameter. Resolves constants and class constants used as default values.
* @throws \ReflectionException if the constant cannot be resolved
*/
public static function getParameterDefaultValue(\ReflectionParameter $param): mixed
{
if ($param->isDefaultValueConstant()) {
$const = $orig = $param->getDefaultValueConstantName() ?? throw new Nette\ShouldNotHappenException;
$pair = explode('::', $const);
if (isset($pair[1])) {
$pair[0] = Type::resolve($pair[0], $param);
try {
$rcc = new \ReflectionClassConstant($pair[0], $pair[1]);
} catch (\ReflectionException $e) {
$name = self::toString($param);
throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.", 0, $e);
}
return $rcc->getValue();
} elseif (!defined($const)) {
$const = substr((string) strrchr($const, '\\'), 1);
if (!defined($const)) {
$name = self::toString($param);
throw new \ReflectionException("Unable to resolve constant $orig used as default value of $name.");
}
}
return constant($const);
}
return $param->getDefaultValue();
}
/**
* Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait.
* @return \ReflectionClass<object>
*/
public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass
{
foreach ($prop->getDeclaringClass()->getTraits() as $trait) {
if ($trait->hasProperty($prop->name)
// doc-comment guessing as workaround for insufficient PHP reflection
&& $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment()
) {
return self::getPropertyDeclaringClass($trait->getProperty($prop->name));
}
}
return $prop->getDeclaringClass();
}
/**
* Returns a reflection of a method that contains a declaration of $method.
* Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name.
*/
public static function getMethodDeclaringMethod(\ReflectionMethod $method): \ReflectionMethod
{
// file & line guessing as workaround for insufficient PHP reflection
$decl = $method->getDeclaringClass();
if ($decl->getFileName() === $method->getFileName()
&& $decl->getStartLine() <= $method->getStartLine()
&& $decl->getEndLine() >= $method->getEndLine()
) {
return $method;
}
$hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()];
if (($alias = $decl->getTraitAliases()[$method->name] ?? null)
&& ($m = new \ReflectionMethod(...explode('::', $alias, 2)))
&& $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
) {
return self::getMethodDeclaringMethod($m);
}
foreach ($decl->getTraits() as $trait) {
if ($trait->hasMethod($method->name)
&& ($m = $trait->getMethod($method->name))
&& $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]
) {
return self::getMethodDeclaringMethod($m);
}
}
return $method;
}
/**
* Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache.
*/
public static function areCommentsAvailable(): bool
{
static $res;
return $res ?? $res = (bool) (new \ReflectionMethod(self::class, __FUNCTION__))->getDocComment();
}
/**
* Returns a human-readable string representation of a reflection object.
*/
public static function toString(\Reflector $ref): string
{
if ($ref instanceof \ReflectionClass) {
return $ref->name;
} elseif ($ref instanceof \ReflectionMethod) {
return $ref->getDeclaringClass()->name . '::' . $ref->name . '()';
} elseif ($ref instanceof \ReflectionFunction) {
return $ref->isAnonymous() ? '{closure}()' : $ref->name . '()';
} elseif ($ref instanceof \ReflectionProperty) {
return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name;
} elseif ($ref instanceof \ReflectionParameter) {
return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction());
} else {
throw new Nette\InvalidArgumentException;
}
}
/**
* Expands the name of the class to full name in the given context of given class.
* Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context.
* @param \ReflectionClass<object> $context
* @throws Nette\InvalidArgumentException
*/
public static function expandClassName(string $name, \ReflectionClass $context): string
{
$lower = strtolower($name);
if (empty($name)) {
throw new Nette\InvalidArgumentException('Class name must not be empty.');
} elseif (Validators::isBuiltinType($lower)) {
return $lower;
} elseif ($lower === 'self' || $lower === 'static') {
return $context->name;
} elseif ($lower === 'parent') {
return $context->getParentClass()
? $context->getParentClass()->name
: 'parent';
} elseif ($name[0] === '\\') { // fully qualified name
return ltrim($name, '\\');
}
$uses = self::getUseStatements($context);
$parts = explode('\\', $name, 2);
if (isset($uses[$parts[0]])) {
$parts[0] = $uses[$parts[0]];
return implode('\\', $parts);
} elseif ($context->inNamespace()) {
return $context->getNamespaceName() . '\\' . $name;
} else {
return $name;
}
}
/**
* Returns the use statements from the file where the class is defined.
* @param \ReflectionClass<object> $class
* @return array<string, class-string> Map of alias to fully qualified class name
*/
public static function getUseStatements(\ReflectionClass $class): array
{
if ($class->isAnonymous()) {
throw new Nette\NotImplementedException('Anonymous classes are not supported.');
}
static $cache = [];
if (!isset($cache[$name = $class->name])) {
if ($class->isInternal()) {
$cache[$name] = [];
} else {
$code = (string) file_get_contents((string) $class->getFileName());
$cache = self::parseUseStatements($code, $name) + $cache;
}
}
return $cache[$name];
}
/**
* Parses PHP code to [class => [alias => class, ...]]
* @return array<string, array<string, string>>
*/
private static function parseUseStatements(string $code, ?string $forClass = null): array
{
try {
$tokens = \PhpToken::tokenize($code, TOKEN_PARSE);
} catch (\ParseError $e) {
trigger_error($e->getMessage());
$tokens = [];
}
$namespace = $class = null;
$classLevel = $level = 0;
$res = $uses = [];
$nameTokens = [T_STRING, T_NS_SEPARATOR, T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED];
while ($token = current($tokens)) {
next($tokens);
switch ($token->id) {
case T_NAMESPACE:
$namespace = ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\');
$uses = [];
break;
case T_CLASS:
case T_INTERFACE:
case T_TRAIT:
case T_ENUM:
if ($name = self::fetch($tokens, T_STRING)) {
$class = $namespace . $name;
$classLevel = $level + 1;
$res[$class] = $uses;
if ($class === $forClass) {
return $res;
}
}
break;
case T_USE:
while (!$class && ($name = self::fetch($tokens, $nameTokens))) {
$name = ltrim($name, '\\');
if (self::fetch($tokens, '{')) {
while ($suffix = self::fetch($tokens, $nameTokens)) {
if (self::fetch($tokens, T_AS) && ($alias = self::fetch($tokens, T_STRING))) {
$uses[$alias] = $name . $suffix;
} else {
$tmp = explode('\\', $suffix);
$uses[end($tmp)] = $name . $suffix;
}
if (!self::fetch($tokens, ',')) {
break;
}
}
} elseif (self::fetch($tokens, T_AS) && ($alias = self::fetch($tokens, T_STRING))) {
$uses[$alias] = $name;
} else {
$tmp = explode('\\', $name);
$uses[end($tmp)] = $name;
}
if (!self::fetch($tokens, ',')) {
break;
}
}
break;
case T_CURLY_OPEN:
case T_DOLLAR_OPEN_CURLY_BRACES:
case ord('{'):
$level++;
break;
case ord('}'):
if ($level === $classLevel) {
$class = $classLevel = 0;
}
$level--;
}
}
return $res;
}
/**
* @param \PhpToken[] $tokens
* @param string|int|int[] $take
*/
private static function fetch(array &$tokens, string|int|array $take): ?string
{
$res = null;
while ($token = current($tokens)) {
if ($token->is($take)) {
$res .= $token->text;
} elseif (!$token->is([T_DOC_COMMENT, T_WHITESPACE, T_COMMENT])) {
break;
}
next($tokens);
}
return $res;
}
}

View file

@ -0,0 +1,39 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use function explode, is_string, str_contains;
/**
* ReflectionMethod preserving the original class name.
* @internal
*/
final class ReflectionMethod extends \ReflectionMethod
{
/** @var \ReflectionClass<object> */
private readonly \ReflectionClass $originalClass;
/** @param class-string|object $objectOrMethod */
public function __construct(object|string $objectOrMethod, ?string $method = null)
{
if (is_string($objectOrMethod) && str_contains($objectOrMethod, '::')) {
[$objectOrMethod, $method] = explode('::', $objectOrMethod, 2);
}
parent::__construct($objectOrMethod, $method);
$this->originalClass = new \ReflectionClass($objectOrMethod);
}
/** @return \ReflectionClass<object> */
public function getOriginalClass(): \ReflectionClass
{
return $this->originalClass;
}
}

730
vendor/nette/utils/src/Utils/Strings.php vendored Normal file
View file

@ -0,0 +1,730 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use JetBrains\PhpStorm\Language;
use Nette;
use function array_keys, array_map, array_shift, array_values, bin2hex, class_exists, defined, extension_loaded, function_exists, htmlspecialchars, htmlspecialchars_decode, iconv, iconv_strlen, iconv_substr, implode, in_array, is_array, is_callable, is_int, is_object, is_string, key, max, mb_convert_case, mb_strlen, mb_strtolower, mb_strtoupper, mb_substr, pack, preg_last_error, preg_last_error_msg, preg_quote, preg_replace, str_contains, str_ends_with, str_repeat, str_replace, str_starts_with, strlen, strpos, strrev, strrpos, strtolower, strtoupper, strtr, substr, trim, unpack;
use const ENT_IGNORE, ENT_NOQUOTES, ICONV_IMPL, MB_CASE_TITLE, PHP_EOL, PREG_OFFSET_CAPTURE, PREG_PATTERN_ORDER, PREG_SET_ORDER, PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_NO_EMPTY, PREG_SPLIT_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL;
/**
* String tools library.
*/
class Strings
{
use Nette\StaticClass;
public const TrimCharacters = " \t\n\r\0\x0B\u{A0}\u{2000}\u{2001}\u{2002}\u{2003}\u{2004}\u{2005}\u{2006}\u{2007}\u{2008}\u{2009}\u{200A}\u{200B}\u{2028}\u{3000}";
#[\Deprecated('use Strings::TrimCharacters')]
public const TRIM_CHARACTERS = self::TrimCharacters;
/**
* @deprecated use Nette\Utils\Validators::isUnicode()
*/
public static function checkEncoding(string $s): bool
{
return $s === self::fixEncoding($s);
}
/**
* Removes all invalid UTF-8 characters from a string.
*/
public static function fixEncoding(string $s): string
{
// removes xD800-xDFFF, x110000 and higher
return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES);
}
/**
* Returns a specific character in UTF-8 from code point (number in range 0x0000..D7FF or 0xE000..10FFFF).
* @throws Nette\InvalidArgumentException if code point is not in valid range
*/
public static function chr(int $code): string
{
if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) {
throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.');
} elseif (!extension_loaded('iconv')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
}
$res = iconv('UTF-32BE', 'UTF-8//IGNORE', pack('N', $code));
return $res === false ? throw new Nette\ShouldNotHappenException : $res;
}
/**
* Returns a code point of specific character in UTF-8 (number in range 0x0000..D7FF or 0xE000..10FFFF).
*/
public static function ord(string $c): int
{
if (!extension_loaded('iconv')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
}
$tmp = iconv('UTF-8', 'UTF-32BE//IGNORE', $c);
if ($tmp === false || $tmp === '') {
throw new Nette\InvalidArgumentException('Invalid UTF-8 character "' . ($c === '' ? '' : '\x' . strtoupper(bin2hex($c))) . '".');
}
return unpack('N', $tmp)[1] ?? throw new Nette\ShouldNotHappenException;
}
/**
* @deprecated use str_starts_with()
*/
public static function startsWith(string $haystack, string $needle): bool
{
return str_starts_with($haystack, $needle);
}
/**
* @deprecated use str_ends_with()
*/
public static function endsWith(string $haystack, string $needle): bool
{
return str_ends_with($haystack, $needle);
}
/**
* @deprecated use str_contains()
*/
public static function contains(string $haystack, string $needle): bool
{
return str_contains($haystack, $needle);
}
/**
* Returns a part of UTF-8 string specified by starting position and length. If start is negative,
* the returned string will start at the start'th character from the end of string.
*/
public static function substring(string $s, int $start, ?int $length = null): string
{
if (function_exists('mb_substr')) {
return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster
} elseif (!extension_loaded('iconv')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.');
} elseif ($length === null) {
$length = self::length($s);
} elseif ($start < 0 && $length < 0) {
$start += self::length($s); // unifies iconv_substr behavior with mb_substr
}
$res = iconv_substr($s, $start, $length, 'UTF-8');
return $res === false ? throw new Nette\InvalidStateException('iconv_substr() failed.') : $res;
}
/**
* Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines,
* trims end spaces on lines, normalizes UTF-8 to the normal form of NFC.
*/
public static function normalize(string $s): string
{
// convert to compressed normal form (NFC)
if (class_exists('Normalizer', autoload: false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== false) {
$s = $n;
}
$s = self::unixNewLines($s);
// remove control characters; leave \t + \n
$s = self::pcre('preg_replace', ['#[\x00-\x08\x0B-\x1F\x7F-\x9F]+#u', '', $s]);
// right trim
$s = self::pcre('preg_replace', ['#[\t ]+$#m', '', $s]);
// leading and trailing blank lines
$s = trim($s, "\n");
return $s;
}
/** @deprecated use Strings::unixNewLines() */
public static function normalizeNewLines(string $s): string
{
return self::unixNewLines($s);
}
/**
* Converts line endings to \n used on Unix-like systems.
* Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator.
*/
public static function unixNewLines(string $s): string
{
return preg_replace("~\r\n?|\u{2028}|\u{2029}~", "\n", $s);
}
/**
* Converts line endings to platform-specific, i.e. \r\n on Windows and \n elsewhere.
* Line endings are: \n, \r, \r\n, U+2028 line separator, U+2029 paragraph separator.
*/
public static function platformNewLines(string $s): string
{
return preg_replace("~\r\n?|\n|\u{2028}|\u{2029}~", PHP_EOL, $s);
}
/**
* Converts UTF-8 string to ASCII, ie removes diacritics etc.
*/
public static function toAscii(string $s): string
{
if (!extension_loaded('intl')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires INTL extension that is not loaded.');
}
$iconv = defined('ICONV_IMPL') ? trim(ICONV_IMPL, '"\'') : null;
// remove control characters and check UTF-8 validity
$s = self::pcre('preg_replace', ['#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s]);
// transliteration (by Transliterator and iconv) is not optimal, replace some characters directly
$s = strtr($s, ["\u{201E}" => '"', "\u{201C}" => '"', "\u{201D}" => '"', "\u{201A}" => "'", "\u{2018}" => "'", "\u{2019}" => "'", "\u{B0}" => '^', "\u{42F}" => 'Ya', "\u{44F}" => 'ya', "\u{42E}" => 'Yu', "\u{44E}" => 'yu', "\u{c4}" => 'Ae', "\u{d6}" => 'Oe', "\u{dc}" => 'Ue', "\u{1e9e}" => 'Ss', "\u{e4}" => 'ae', "\u{f6}" => 'oe', "\u{fc}" => 'ue', "\u{df}" => 'ss']); // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß
if ($iconv !== 'libiconv') {
$s = strtr($s, ["\u{AE}" => '(R)', "\u{A9}" => '(c)', "\u{2026}" => '...', "\u{AB}" => '<<', "\u{BB}" => '>>', "\u{A3}" => 'lb', "\u{A5}" => 'yen', "\u{B2}" => '^2', "\u{B3}" => '^3', "\u{B5}" => 'u', "\u{B9}" => '^1', "\u{BA}" => 'o', "\u{BF}" => '?', "\u{2CA}" => "'", "\u{2CD}" => '_', "\u{2DD}" => '"', "\u{1FEF}" => '', "\u{20AC}" => 'EUR', "\u{2122}" => 'TM', "\u{212E}" => 'e', "\u{2190}" => '<-', "\u{2191}" => '^', "\u{2192}" => '->', "\u{2193}" => 'V', "\u{2194}" => '<->']); // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔
}
$s = \Transliterator::create('Any-Latin; Latin-ASCII')?->transliterate($s)
?? throw new Nette\InvalidStateException('Transliterator::transliterate() failed.');
// use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ
if ($iconv === 'glibc') {
$s = strtr($s, '?', "\x01"); // temporarily hide ? to distinguish them from the garbage that iconv creates
$s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
if ($s === false) {
throw new Nette\InvalidStateException('iconv() failed.');
}
$s = str_replace(['?', "\x01"], ['', '?'], $s); // remove garbage and restore ? characters
} elseif ($iconv === 'libiconv') {
$s = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s);
if ($s === false) {
throw new Nette\InvalidStateException('iconv() failed.');
}
} else { // null or 'unknown' (#216)
$s = self::pcre('preg_replace', ['#[^\x00-\x7F]++#', '', $s]); // remove non-ascii chars
}
return $s;
}
/**
* Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters
* except letters of the English alphabet and numbers with a hyphens.
*/
public static function webalize(string $s, ?string $charlist = null, bool $lower = true): string
{
$s = self::toAscii($s);
if ($lower) {
$s = strtolower($s);
}
$s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? preg_quote($charlist, '#') : '') . ']+#i', '-', $s]);
$s = trim($s, '-');
return $s;
}
/**
* Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated,
* an ellipsis (or something else set with third argument) is appended to the string.
*/
public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string
{
if (self::length($s) > $maxLen) {
$maxLen -= self::length($append);
if ($maxLen < 1) {
return $append;
} elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us')) {
return $matches[0] . $append;
} else {
return self::substring($s, 0, $maxLen) . $append;
}
}
return $s;
}
/**
* Indents a multiline text from the left. Second argument sets how many indentation chars should be used,
* while the indent itself is the third argument (*tab* by default).
*/
public static function indent(string $s, int $level = 1, string $chars = "\t"): string
{
if ($level > 0) {
$s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level));
}
return $s;
}
/**
* Converts all characters of UTF-8 string to lower case.
*/
public static function lower(string $s): string
{
return mb_strtolower($s, 'UTF-8');
}
/**
* Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged.
*/
public static function firstLower(string $s): string
{
return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1);
}
/**
* Converts all characters of a UTF-8 string to upper case.
*/
public static function upper(string $s): string
{
return mb_strtoupper($s, 'UTF-8');
}
/**
* Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged.
*/
public static function firstUpper(string $s): string
{
return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1);
}
/**
* Converts the first character of every word of a UTF-8 string to upper case and the others to lower case.
*/
public static function capitalize(string $s): string
{
return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8');
}
/**
* Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared,
* if it is negative, the corresponding number of characters from the end of the strings is compared,
* otherwise the appropriate number of characters from the beginning is compared.
*/
public static function compare(string $left, string $right, ?int $length = null): bool
{
if (class_exists('Normalizer', autoload: false)) {
$left = \Normalizer::normalize($left, \Normalizer::FORM_D) ?: $left; // form NFD is faster, false on invalid UTF-8
$right = \Normalizer::normalize($right, \Normalizer::FORM_D) ?: $right; // form NFD is faster, false on invalid UTF-8
}
if ($length < 0) {
$left = self::substring($left, $length, -$length);
$right = self::substring($right, $length, -$length);
} elseif ($length !== null) {
$left = self::substring($left, 0, $length);
$right = self::substring($right, 0, $length);
}
return self::lower($left) === self::lower($right);
}
/**
* Finds the common prefix of strings or returns empty string if the prefix was not found.
* @param string[] $strings
*/
public static function findPrefix(array $strings): string
{
$first = array_shift($strings);
if ($first === null) {
return '';
}
for ($i = 0; $i < strlen($first); $i++) {
foreach ($strings as $s) {
if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
$i--;
}
return substr($first, 0, $i);
}
}
}
return $first;
}
/**
* Returns number of characters (not bytes) in UTF-8 string.
* That is the number of Unicode code points which may differ from the number of graphemes.
*/
public static function length(string $s): int
{
return match (true) {
extension_loaded('mbstring') => (int) mb_strlen($s, 'UTF-8'),
extension_loaded('iconv') => (int) iconv_strlen($s, 'UTF-8'),
default => strlen((string) preg_replace('#[\x80-\xBF]#', '', $s)), // strips UTF-8 continuation bytes
};
}
/**
* Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string.
*/
public static function trim(string $s, string $charlist = self::TrimCharacters): string
{
$charlist = preg_quote($charlist, '#');
return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du');
}
/**
* Pads a UTF-8 string to given length by prepending the $pad string to the beginning.
* @param non-empty-string $pad
*/
public static function padLeft(string $s, int $length, string $pad = ' '): string
{
$length = max(0, $length - self::length($s));
$padLen = self::length($pad);
return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
}
/**
* Pads UTF-8 string to given length by appending the $pad string to the end.
* @param non-empty-string $pad
*/
public static function padRight(string $s, int $length, string $pad = ' '): string
{
$length = max(0, $length - self::length($s));
$padLen = self::length($pad);
return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
}
/**
* Reverses UTF-8 string.
*/
public static function reverse(string $s): string
{
if (!extension_loaded('iconv')) {
throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.');
}
$tmp = iconv('UTF-8', 'UTF-32BE', $s);
return $tmp === false
? throw new Nette\InvalidStateException('iconv() failed.')
: (string) iconv('UTF-32LE', 'UTF-8', strrev($tmp));
}
/**
* Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found.
* Negative value means searching from the end.
*/
public static function before(string $haystack, string $needle, int $nth = 1): ?string
{
$pos = self::pos($haystack, $needle, $nth);
return $pos === null
? null
: substr($haystack, 0, $pos);
}
/**
* Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found.
* Negative value means searching from the end.
*/
public static function after(string $haystack, string $needle, int $nth = 1): ?string
{
$pos = self::pos($haystack, $needle, $nth);
return $pos === null
? null
: substr($haystack, $pos + strlen($needle));
}
/**
* Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found.
* Negative value of `$nth` means searching from the end.
*/
public static function indexOf(string $haystack, string $needle, int $nth = 1): ?int
{
$pos = self::pos($haystack, $needle, $nth);
return $pos === null
? null
: self::length(substr($haystack, 0, $pos));
}
/**
* Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found.
*/
private static function pos(string $haystack, string $needle, int $nth = 1): ?int
{
if (!$nth) {
return null;
} elseif ($nth > 0) {
if ($needle === '') {
return 0;
}
$pos = 0;
while (($pos = strpos($haystack, $needle, $pos)) !== false && --$nth) {
$pos++;
}
} else {
$len = strlen($haystack);
if ($needle === '') {
return $len;
} elseif ($len === 0) {
return null;
}
$pos = $len - 1;
while (($pos = strrpos($haystack, $needle, $pos - $len)) !== false && ++$nth) {
$pos--;
}
}
return Helpers::falseToNull($pos);
}
/**
* Splits the string by a regular expression. Expressions in parentheses will be captured and returned as well.
* @return list<string>
*/
public static function split(
string $subject,
#[Language('RegExp')]
string $pattern,
bool|int $captureOffset = false,
bool $skipEmpty = false,
int $limit = -1,
bool $utf8 = false,
): array
{
$flags = is_int($captureOffset) // back compatibility
? $captureOffset
: ($captureOffset ? PREG_SPLIT_OFFSET_CAPTURE : 0) | ($skipEmpty ? PREG_SPLIT_NO_EMPTY : 0);
$pattern .= $utf8 ? 'u' : '';
$m = self::pcre('preg_split', [$pattern, $subject, $limit, $flags | PREG_SPLIT_DELIM_CAPTURE]);
return $utf8 && $captureOffset
? self::bytesToChars($subject, [$m])[0]
: $m;
}
/**
* Searches the string for the first match of the regular expression and returns
* an array with the found expression and individual subexpressions, or null.
* @return ?array<string>
*/
public static function match(
string $subject,
#[Language('RegExp')]
string $pattern,
bool|int $captureOffset = false,
int $offset = 0,
bool $unmatchedAsNull = false,
bool $utf8 = false,
): ?array
{
$flags = is_int($captureOffset) // back compatibility
? $captureOffset
: ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
if ($utf8) {
$offset = strlen(self::substring($subject, 0, $offset));
$pattern .= 'u';
}
$m = [];
if ($offset > strlen($subject)) {
return null;
} elseif (!self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])) {
return null;
} elseif ($utf8 && $captureOffset) {
return self::bytesToChars($subject, [$m])[0];
} else {
return $m;
}
}
/**
* Searches the string for all occurrences matching the regular expression and returns
* an array of arrays containing the found expression and each subexpression.
* @return ($lazy is true ? \Generator<int, array<string>> : list<array<string>>)
*/
public static function matchAll(
string $subject,
#[Language('RegExp')]
string $pattern,
bool|int $captureOffset = false,
int $offset = 0,
bool $unmatchedAsNull = false,
bool $patternOrder = false,
bool $utf8 = false,
bool $lazy = false,
): array|\Generator
{
if ($utf8) {
$offset = strlen(self::substring($subject, 0, $offset));
$pattern .= 'u';
}
if ($lazy) {
$flags = PREG_OFFSET_CAPTURE | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
return (function () use ($utf8, $captureOffset, $flags, $subject, $pattern, $offset) {
$counter = 0;
$m = [];
while (
$offset <= strlen($subject) - ($counter ? 1 : 0)
&& self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset])
) {
/** @var list<array{string, int}> $m */
$offset = $m[0][1] + max(1, strlen($m[0][0]));
if (!$captureOffset) {
$m = array_map(fn($item) => $item[0], $m);
} elseif ($utf8) {
$m = self::bytesToChars($subject, [$m])[0];
}
yield $counter++ => $m;
}
})();
}
if ($offset > strlen($subject)) {
return [];
}
$flags = is_int($captureOffset) // back compatibility
? $captureOffset
: ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0) | ($patternOrder ? PREG_PATTERN_ORDER : 0);
$m = [];
self::pcre('preg_match_all', [
$pattern, $subject, &$m,
($flags & PREG_PATTERN_ORDER) ? $flags : ($flags | PREG_SET_ORDER),
$offset,
]);
return $utf8 && $captureOffset
? self::bytesToChars($subject, $m)
: $m;
}
/**
* Replaces all occurrences matching the regular expression $pattern, which can be a string or array in the form `pattern => replacement`.
* @param string|array<string, string> $pattern
*/
public static function replace(
string $subject,
#[Language('RegExp')]
string|array $pattern,
string|callable $replacement = '',
int $limit = -1,
bool $captureOffset = false,
bool $unmatchedAsNull = false,
bool $utf8 = false,
): string
{
if (is_object($replacement) || is_array($replacement)) {
if (!is_callable($replacement, false, $textual)) {
throw new Nette\InvalidStateException("Callback '$textual' is not callable.");
}
$flags = ($captureOffset ? PREG_OFFSET_CAPTURE : 0) | ($unmatchedAsNull ? PREG_UNMATCHED_AS_NULL : 0);
if ($utf8) {
$pattern = is_array($pattern) ? array_map(fn($item) => $item . 'u', $pattern) : $pattern . 'u';
if ($captureOffset) {
$replacement = fn($m) => $replacement(self::bytesToChars($subject, [$m])[0]);
}
}
return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit, 0, $flags]);
} elseif (is_array($pattern) && is_string(key($pattern))) {
$replacement = array_values($pattern);
$pattern = array_keys($pattern);
}
if ($utf8) {
$pattern = array_map(fn($item) => $item . 'u', (array) $pattern);
}
return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]);
}
/**
* @param list<array<array{string, int}>> $groups
* @return list<array<array{string, int}>>
*/
private static function bytesToChars(string $s, array $groups): array
{
$lastBytes = $lastChars = 0;
foreach ($groups as &$matches) {
foreach ($matches as &$match) {
if ($match[1] > $lastBytes) {
$lastChars += self::length(substr($s, $lastBytes, $match[1] - $lastBytes));
} elseif ($match[1] < $lastBytes) {
$lastChars -= self::length(substr($s, $match[1], $lastBytes - $match[1]));
}
$lastBytes = $match[1];
$match[1] = $lastChars;
}
}
return $groups;
}
/**
* @param callable-string $func
* @param list<mixed> $args
* @internal
*/
public static function pcre(string $func, array $args): mixed
{
$res = Callback::invokeSafe($func, $args, function (string $message) use ($args): void {
// compile-time error, not detectable by preg_last_error
throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0]));
});
if (($code = preg_last_error()) // run-time error, but preg_last_error & return code are liars
&& ($res === null || !in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], strict: true))
) {
throw new RegexpException(preg_last_error_msg()
. ' (pattern: ' . implode(' or ', (array) $args[0]) . ')', $code);
}
return $res;
}
}

314
vendor/nette/utils/src/Utils/Type.php vendored Normal file
View file

@ -0,0 +1,314 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_map, array_search, array_splice, array_values, count, explode, implode, is_a, is_resource, is_string, strcasecmp, strtolower, substr, trim;
/**
* PHP type reflection.
*/
final readonly class Type
{
/** @var list<string|self> */
private array $types;
private ?string $singleName;
private string $kind; // | &
/**
* Creates a Type object based on reflection. Resolves self, static and parent to the actual class name.
* If the subject has no type, it returns null.
*/
public static function fromReflection(
\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $reflection,
): ?self
{
$type = $reflection instanceof \ReflectionFunctionAbstract
? $reflection->getReturnType() ?? ($reflection instanceof \ReflectionMethod ? $reflection->getTentativeReturnType() : null)
: $reflection->getType();
return $type ? self::fromReflectionType($type, $reflection, asObject: true) : null;
}
/** @return ($asObject is true ? self : self|string) */
private static function fromReflectionType(
\ReflectionType $type,
\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of,
bool $asObject,
): self|string
{
if ($type instanceof \ReflectionNamedType) {
$name = self::resolve($type->getName(), $of);
return $asObject
? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name])
: $name;
} elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) {
return new self(
array_map(fn($t) => self::fromReflectionType($t, $of, asObject: false), $type->getTypes()),
$type instanceof \ReflectionUnionType ? '|' : '&',
);
} else {
throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of));
}
}
/**
* Creates the Type object according to the text notation.
*/
public static function fromString(string $type): self
{
if (!Validators::isTypeDeclaration($type)) {
throw new Nette\InvalidArgumentException("Invalid type '$type'.");
}
if ($type[0] === '?') {
return new self([substr($type, 1), 'null']);
}
$unions = [];
foreach (explode('|', $type) as $part) {
$part = explode('&', trim($part, '()'));
$unions[] = count($part) === 1 ? $part[0] : new self($part, '&');
}
return count($unions) === 1 && $unions[0] instanceof self
? $unions[0]
: new self($unions);
}
/**
* Creates a Type object based on the actual type of value.
*/
public static function fromValue(mixed $value): self
{
$type = get_debug_type($value);
if (is_resource($value)) {
$type = 'mixed';
} elseif (str_ends_with($type, '@anonymous')) {
$parent = substr($type, 0, -10);
$type = $parent === 'class' ? 'object' : $parent;
}
return new self([$type]);
}
/**
* Resolves 'self', 'static' and 'parent' to the actual class name.
*/
public static function resolve(
string $type,
\ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $of,
): string
{
$lower = strtolower($type);
if ($of instanceof \ReflectionFunction) {
return $type;
}
$class = $of->getDeclaringClass();
if ($class === null) {
return $type;
} elseif ($lower === 'self') {
return $class->name;
} elseif ($lower === 'static') {
return ($of instanceof ReflectionMethod ? $of->getOriginalClass() : $class)->name;
} elseif ($lower === 'parent' && $class->getParentClass()) {
return $class->getParentClass()->name;
} else {
return $type;
}
}
/** @param array<string|self> $types */
private function __construct(array $types, string $kind = '|')
{
$o = array_search('null', $types, strict: true);
if ($o !== false) { // null as last
array_splice($types, (int) $o, 1);
$types[] = 'null';
}
$this->types = array_values($types);
$this->singleName = is_string($types[0]) && ($types[1] ?? 'null') === 'null' ? $types[0] : null;
$this->kind = count($types) > 1 ? $kind : '';
}
public function __toString(): string
{
$multi = count($this->types) > 1;
if ($this->singleName !== null) {
return ($multi ? '?' : '') . $this->singleName;
}
$res = [];
foreach ($this->types as $type) {
$res[] = $type instanceof self && $multi ? "($type)" : $type;
}
return implode($this->kind, $res);
}
/**
* Returns a union type that accepts both the current type and the given type.
*/
public function with(string|self $type): self
{
$type = is_string($type) ? self::fromString($type) : $type;
return match (true) {
$this->allows($type) => $this,
$type->allows($this) => $type,
default => new self(array_unique(
array_merge($this->isIntersection() ? [$this] : $this->types, $type->isIntersection() ? [$type] : $type->types),
SORT_REGULAR,
), '|'),
};
}
/**
* Returns the array of subtypes that make up the compound type as strings.
* @return list<string|array<string|array<mixed>>>
*/
public function getNames(): array
{
return array_map(fn($t) => $t instanceof self ? $t->getNames() : $t, $this->types);
}
/**
* Returns the array of subtypes that make up the compound type as Type objects.
* @return list<self>
*/
public function getTypes(): array
{
return array_map(fn($t) => $t instanceof self ? $t : new self([$t]), $this->types);
}
/**
* Returns the type name for simple types, otherwise null.
*/
public function getSingleName(): ?string
{
return $this->singleName;
}
/**
* Returns true whether it is a union type.
*/
public function isUnion(): bool
{
return $this->kind === '|';
}
/**
* Returns true whether it is an intersection type.
*/
public function isIntersection(): bool
{
return $this->kind === '&';
}
/**
* Checks whether it is a simple (non-compound) type. Single nullable types such as ?int are also considered simple.
*/
public function isSimple(): bool
{
return $this->singleName !== null;
}
#[\Deprecated('use isSimple()')]
public function isSingle(): bool
{
return $this->singleName !== null;
}
/**
* Checks whether it is a simple PHP built-in type (int, string, bool, etc.).
*/
public function isBuiltin(): bool
{
return $this->singleName !== null && Validators::isBuiltinType($this->singleName);
}
/**
* Checks whether it is a simple class or interface name (not a built-in type).
*/
public function isClass(): bool
{
return $this->singleName !== null && !Validators::isBuiltinType($this->singleName);
}
/**
* Determines if type is special class name self/parent/static.
*/
public function isClassKeyword(): bool
{
return $this->singleName !== null && Validators::isClassKeyword($this->singleName);
}
/**
* Checks whether a value of the given type could be assigned to this type.
*/
public function allows(string|self $type): bool
{
if ($this->types === ['mixed']) {
return true;
}
$type = is_string($type) ? self::fromString($type) : $type;
return $type->isUnion()
? Arrays::every($type->types, fn($t) => $this->allowsAny($t instanceof self ? $t->types : [$t]))
: $this->allowsAny($type->types);
}
/** @param array<string> $givenTypes */
private function allowsAny(array $givenTypes): bool
{
return $this->isUnion()
? Arrays::some($this->types, fn($t) => $this->allowsAll($t instanceof self ? $t->types : [$t], $givenTypes))
: $this->allowsAll($this->types, $givenTypes);
}
/**
* @param array<string> $ourTypes
* @param array<string> $givenTypes
*/
private function allowsAll(array $ourTypes, array $givenTypes): bool
{
return Arrays::every(
$ourTypes,
fn(string $ourType) => Arrays::some(
$givenTypes,
fn(string $givenType) => Validators::isBuiltinType($ourType)
? strcasecmp($ourType, $givenType) === 0
: is_a($givenType, $ourType, allow_string: true),
),
);
}
}

View file

@ -0,0 +1,417 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
use function array_key_exists, class_exists, explode, gettype, interface_exists, is_callable, is_float, is_int, is_iterable, is_numeric, is_object, is_string, preg_match, str_ends_with, str_replace, str_starts_with, strlen, strtolower, substr, trait_exists, var_export;
/**
* Validation utilities.
*/
class Validators
{
use Nette\StaticClass;
private const BuiltinTypes = [
'string' => 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'array' => 1, 'object' => 1,
'callable' => 1, 'iterable' => 1, 'void' => 1, 'null' => 1, 'mixed' => 1, 'false' => 1,
'never' => 1, 'true' => 1,
];
/** @var array<string, ?(callable(mixed): bool)> */
protected static $validators = [
// PHP types
'array' => 'is_array',
'bool' => 'is_bool',
'boolean' => 'is_bool',
'float' => 'is_float',
'int' => 'is_int',
'integer' => 'is_int',
'null' => 'is_null',
'object' => 'is_object',
'resource' => 'is_resource',
'scalar' => 'is_scalar',
'string' => 'is_string',
// pseudo-types
'callable' => [self::class, 'isCallable'],
'iterable' => 'is_iterable',
'list' => [Arrays::class, 'isList'],
'mixed' => [self::class, 'isMixed'],
'none' => [self::class, 'isNone'],
'number' => [self::class, 'isNumber'],
'numeric' => [self::class, 'isNumeric'],
'numericint' => [self::class, 'isNumericInt'],
// string patterns
'alnum' => 'ctype_alnum',
'alpha' => 'ctype_alpha',
'digit' => 'ctype_digit',
'lower' => 'ctype_lower',
'pattern' => null,
'space' => 'ctype_space',
'unicode' => [self::class, 'isUnicode'],
'upper' => 'ctype_upper',
'xdigit' => 'ctype_xdigit',
// syntax validation
'email' => [self::class, 'isEmail'],
'identifier' => [self::class, 'isPhpIdentifier'],
'uri' => [self::class, 'isUri'],
'url' => [self::class, 'isUrl'],
// environment validation
'class' => 'class_exists',
'interface' => 'interface_exists',
'directory' => 'is_dir',
'file' => 'is_file',
'type' => [self::class, 'isType'],
];
/** @var array<string, callable(mixed): int> */
protected static $counters = [
'string' => 'strlen',
'unicode' => [Strings::class, 'length'],
'array' => 'count',
'list' => 'count',
'alnum' => 'strlen',
'alpha' => 'strlen',
'digit' => 'strlen',
'lower' => 'strlen',
'space' => 'strlen',
'upper' => 'strlen',
'xdigit' => 'strlen',
];
/**
* Verifies that the value is of expected types separated by pipe.
* @throws AssertionException
*/
public static function assert(mixed $value, string $expected, string $label = 'variable'): void
{
if (!static::is($value, $expected)) {
$expected = str_replace(['|', ':'], [' or ', ' in range '], $expected);
$translate = ['boolean' => 'bool', 'integer' => 'int', 'double' => 'float', 'NULL' => 'null'];
$type = $translate[gettype($value)] ?? gettype($value);
if (is_int($value) || is_float($value) || (is_string($value) && strlen($value) < 40)) {
$type .= ' ' . var_export($value, return: true);
} elseif (is_object($value)) {
$type .= ' ' . $value::class;
}
throw new AssertionException("The $label expects to be $expected, $type given.");
}
}
/**
* Verifies that item $key in array exists and is of expected types separated by pipe.
* @param mixed[] $array
* @throws AssertionException
*/
public static function assertField(
array $array,
int|string $key,
?string $expected = null,
string $label = "item '%' in array",
): void
{
if (!array_key_exists($key, $array)) {
throw new AssertionException('Missing ' . str_replace('%', (string) $key, $label) . '.');
} elseif ($expected) {
static::assert($array[$key], $expected, str_replace('%', (string) $key, $label));
}
}
/**
* Verifies that the value is of expected types separated by pipe.
*/
public static function is(mixed $value, string $expected): bool
{
foreach (explode('|', $expected) as $item) {
if (str_ends_with($item, '[]')) {
if (is_iterable($value) && self::everyIs($value, substr($item, 0, -2))) {
return true;
}
continue;
} elseif (str_starts_with($item, '?')) {
$item = substr($item, 1);
if ($value === null) {
return true;
}
}
[$type] = $item = explode(':', $item, 2);
if (isset(static::$validators[$type])) {
try {
if (!static::$validators[$type]($value)) {
continue;
}
} catch (\TypeError) {
continue;
}
} elseif ($type === 'pattern') {
if (Strings::match($value, '|^' . ($item[1] ?? '') . '$|D')) {
return true;
}
continue;
} elseif (!$value instanceof $type) {
continue;
}
if (isset($item[1])) {
$length = $value;
if (isset(static::$counters[$type])) {
$length = static::$counters[$type]($value);
}
$range = explode('..', $item[1]);
if (!isset($range[1])) {
$range[1] = $range[0];
}
if (($range[0] !== '' && $length < $range[0]) || ($range[1] !== '' && $length > $range[1])) {
continue;
}
}
return true;
}
return false;
}
/**
* Finds whether all values are of expected types separated by pipe.
* @param iterable<mixed> $values
*/
public static function everyIs(iterable $values, string $expected): bool
{
foreach ($values as $value) {
if (!static::is($value, $expected)) {
return false;
}
}
return true;
}
/**
* Checks if the value is an integer or a float.
* @return ($value is int|float ? true : false)
*/
public static function isNumber(mixed $value): bool
{
return is_int($value) || is_float($value);
}
/**
* Checks if the value is an integer or a integer written in a string.
* @return ($value is non-empty-string ? bool : ($value is int ? true : false))
*/
public static function isNumericInt(mixed $value): bool
{
return is_int($value) || (is_string($value) && preg_match('#^[+-]?[0-9]+$#D', $value));
}
/**
* Checks if the value is a number or a number written in a string.
* @return ($value is non-empty-string ? bool : ($value is int|float ? true : false))
*/
public static function isNumeric(mixed $value): bool
{
return is_float($value) || is_int($value) || (is_string($value) && preg_match('#^[+-]?([0-9]++\.?[0-9]*|\.[0-9]+)$#D', $value));
}
/**
* Checks if the value is a syntactically correct callback.
*/
public static function isCallable(mixed $value): bool
{
return $value && is_callable($value, syntax_only: true);
}
/**
* Checks if the value is a valid UTF-8 string.
*/
public static function isUnicode(mixed $value): bool
{
return is_string($value) && preg_match('##u', $value);
}
/**
* Checks if the value is 0, '', false or null.
* @return ($value is 0|0.0|''|false|null ? true : false)
*/
public static function isNone(mixed $value): bool
{
return $value == null; // intentionally ==
}
/** @internal */
public static function isMixed(): bool
{
return true;
}
/**
* Checks if a variable is a zero-based integer indexed array.
* @deprecated use Nette\Utils\Arrays::isList
* @return ($value is list ? true : false)
*/
public static function isList(mixed $value): bool
{
return Arrays::isList($value);
}
/**
* Checks if the value is in the given range [min, max], where the upper or lower limit can be omitted (null).
* Numbers, strings and DateTime objects can be compared.
* @param array{int|float|string|\DateTimeInterface|null, int|float|string|\DateTimeInterface|null} $range
*/
public static function isInRange(mixed $value, array $range): bool
{
if ($value === null || !(isset($range[0]) || isset($range[1]))) {
return false;
}
$limit = $range[0] ?? $range[1];
if (is_string($limit)) {
$value = (string) $value;
} elseif ($limit instanceof \DateTimeInterface) {
if (!$value instanceof \DateTimeInterface) {
return false;
}
} elseif (is_numeric($value)) {
$value *= 1;
} else {
return false;
}
return (!isset($range[0]) || ($value >= $range[0])) && (!isset($range[1]) || ($value <= $range[1]));
}
/**
* Checks if the value is a valid email address. It does not verify that the domain actually exists, only the syntax is verified.
*/
public static function isEmail(string $value): bool
{
$atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part
$alpha = "a-z\x80-\xFF"; // superset of IDN
return (bool) preg_match(<<<XX
(^(?n)
("([ !#-[\\]-~]*|\\\\[ -~])+"|$atom+(\\.$atom+)*) # quoted or unquoted
@
([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+ # domain - RFC 1034
[$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain
$)Dix
XX, $value);
}
/**
* Checks if the value is a valid URL address.
*/
public static function isUrl(string $value): bool
{
$alpha = "a-z\x80-\xFF";
$octet = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])'; // 0..255
return (bool) preg_match(<<<XX
(^(?n)
https?://(
(([-_0-9$alpha]+\\.)* # subdomain
[0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)? # domain
[$alpha]([-0-9$alpha]{0,17}[$alpha])? # top domain
|$octet(\\.$octet){3} # IPv4
|\\[[0-9a-f:]{3,39}] # IPv6
)(:\\d{1,5})? # port
(/\\S*)? # path
(\\?\\S*)? # query
(\\#\\S*)? # fragment
$)Dix
XX, $value);
}
/**
* Checks if the value is a valid URI address, that is, actually a string beginning with a syntactically valid schema.
*/
public static function isUri(string $value): bool
{
return (bool) preg_match('#^[a-z\d+.-]+:\S+$#Di', $value);
}
/**
* Checks whether the input is a class, interface or trait.
* @deprecated
*/
public static function isType(string $type): bool
{
return class_exists($type) || interface_exists($type) || trait_exists($type);
}
/**
* Checks whether the input is a valid PHP identifier.
*/
public static function isPhpIdentifier(string $value): bool
{
return preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$#D', $value) === 1;
}
/**
* Determines if type is PHP built-in type. Otherwise, it is the class name.
*/
public static function isBuiltinType(string $type): bool
{
return isset(self::BuiltinTypes[strtolower($type)]);
}
/**
* Determines if type is special class name self/parent/static.
*/
public static function isClassKeyword(string $name): bool
{
return (bool) preg_match('#^(self|parent|static)$#Di', $name);
}
/**
* Checks whether the given type declaration is syntactically valid.
*/
public static function isTypeDeclaration(string $type): bool
{
return (bool) preg_match(<<<'XX'
~((?n)
\?? (?<type> \\? (?<name> [a-zA-Z_\x7f-\xff][\w\x7f-\xff]*) (\\ (?&name))* ) |
(?<intersection> (?&type) (& (?&type))+ ) |
(?<upart> (?&type) | \( (?&intersection) \) ) (\| (?&upart))+
)$~xAD
XX, $type);
}
}

View file

@ -0,0 +1,64 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
/**
* An error occurred while working with the image.
*/
class ImageException extends \Exception
{
}
/**
* The image file is invalid or in an unsupported format.
*/
class UnknownImageFileException extends ImageException
{
}
/**
* JSON encoding or decoding failed.
*/
class JsonException extends \JsonException
{
}
/**
* Regular expression pattern or execution failed.
*/
class RegexpException extends \Exception
{
}
/**
* Type validation failed. The value doesn't match the expected type constraints.
*/
class AssertionException extends \Exception
{
}
/**
* The process failed to run successfully.
*/
class ProcessFailedException extends \RuntimeException
{
}
/**
* The process execution exceeded its timeout limit.
*/
class ProcessTimeoutException extends \RuntimeException
{
}

View file

@ -0,0 +1,30 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Utils;
use Nette;
if (false) {
/** @deprecated use Nette\HtmlStringable */
interface IHtmlString extends Nette\HtmlStringable
{
}
} elseif (!interface_exists(IHtmlString::class)) {
class_alias(Nette\HtmlStringable::class, IHtmlString::class);
}
namespace Nette\Localization;
if (false) {
/** @deprecated use Nette\Localization\Translator */
interface ITranslator extends Translator
{
}
} elseif (!interface_exists(ITranslator::class)) {
class_alias(Translator::class, ITranslator::class);
}

112
vendor/nette/utils/src/exceptions.php vendored Normal file
View file

@ -0,0 +1,112 @@
<?php declare(strict_types=1);
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette;
/**
* The value is outside the allowed range.
*/
class ArgumentOutOfRangeException extends \InvalidArgumentException
{
}
/**
* The object is in a state that does not allow the requested operation.
*/
class InvalidStateException extends \RuntimeException
{
}
/**
* The requested feature is not implemented.
*/
class NotImplementedException extends \LogicException
{
}
/**
* The requested operation is not supported.
*/
class NotSupportedException extends \LogicException
{
}
/**
* The requested feature is deprecated and no longer available.
*/
class DeprecatedException extends NotSupportedException
{
}
/**
* Cannot access the requested class property or method.
*/
class MemberAccessException extends \Error
{
}
/**
* Failed to read from or write to a file or stream.
*/
class IOException extends \RuntimeException
{
}
/**
* The requested file does not exist.
*/
class FileNotFoundException extends IOException
{
}
/**
* The requested directory does not exist.
*/
class DirectoryNotFoundException extends IOException
{
}
/**
* The provided argument has invalid type or format.
*/
class InvalidArgumentException extends \InvalidArgumentException
{
}
/**
* The requested array or collection index does not exist.
*/
class OutOfRangeException extends \OutOfRangeException
{
}
/**
* The returned value has unexpected type or format.
*/
class UnexpectedValueException extends \UnexpectedValueException
{
}
/**
* Houston, we have a problem.
*/
class ShouldNotHappenException extends \LogicException
{
}