first commit

This commit is contained in:
CHIEFSOFT\ameye
2025-11-22 09:54:51 -05:00
commit 07a07ab49f
722 changed files with 125787 additions and 0 deletions
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
abstract class AbstractPlugin implements ConstructablePluginInterface
{
private Parser $parser;
public function __construct(Parser $parser)
{
$this->parser = $parser;
}
public function setParser(Parser $p): void
{
$this->parser = $p;
}
protected function getParser(): Parser
{
return $this->parser;
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use InvalidArgumentException;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ProfileRepresentation;
use Kint\Value\Representation\ValueRepresentation;
class ArrayLimitPlugin extends AbstractPlugin implements PluginBeginInterface
{
/**
* Maximum size of arrays before limiting.
*/
public static int $trigger = 1000;
/**
* Maximum amount of items to show in a limited array.
*/
public static int $limit = 50;
/**
* Don't limit arrays with string keys.
*/
public static bool $numeric_only = true;
public function __construct(Parser $p)
{
if (self::$limit < 0) {
throw new InvalidArgumentException('ArrayLimitPlugin::$limit can not be lower than 0');
}
if (self::$limit >= self::$trigger) {
throw new InvalidArgumentException('ArrayLimitPlugin::$limit can not be lower than ArrayLimitPlugin::$trigger');
}
parent::__construct($p);
}
public function getTypes(): array
{
return ['array'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_BEGIN;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
$parser = $this->getParser();
$pdepth = $parser->getDepthLimit();
if (!$pdepth) {
return null;
}
$cdepth = $c->getDepth();
if ($cdepth >= $pdepth - 1) {
return null;
}
if (\count($var) < self::$trigger) {
return null;
}
if (self::$numeric_only && Utils::isAssoc($var)) {
return null;
}
$slice = \array_slice($var, 0, self::$limit, true);
$array = $parser->parse($slice, $c);
if (!$array instanceof ArrayValue) {
return null;
}
$base = new BaseContext($c->getName());
$base->depth = $pdepth - 1;
$base->access_path = $c->getAccessPath();
$slice = \array_slice($var, self::$limit, null, true);
$slice = $parser->parse($slice, $base);
if (!$slice instanceof ArrayValue) {
return null;
}
foreach ($slice->getContents() as $child) {
$this->replaceDepthLimit($child, $cdepth + 1);
}
$out = new ArrayValue($c, \count($var), \array_merge($array->getContents(), $slice->getContents()));
$out->flags = $array->flags;
// Explicitly copy over profile plugin
$arrayp = $array->getRepresentation('profiling');
$slicep = $slice->getRepresentation('profiling');
if ($arrayp instanceof ProfileRepresentation && $slicep instanceof ProfileRepresentation) {
$out->addRepresentation(new ProfileRepresentation($arrayp->complexity + $slicep->complexity));
}
// Add contents. Check is in case some bad plugin empties both $slice and $array
if ($contents = $out->getContents()) {
$out->addRepresentation(new ContainerRepresentation('Contents', $contents, null, true));
}
return $out;
}
protected function replaceDepthLimit(AbstractValue $v, int $depth): void
{
$c = $v->getContext();
if ($c instanceof BaseContext) {
$c->depth = $depth;
}
$pdepth = $this->getParser()->getDepthLimit();
if (($v->flags & AbstractValue::FLAG_DEPTH_LIMIT) && $pdepth && $depth < $pdepth) {
$v->flags = $v->flags & ~AbstractValue::FLAG_DEPTH_LIMIT | AbstractValue::FLAG_ARRAY_LIMIT;
}
$reps = $v->getRepresentations();
foreach ($reps as $rep) {
if ($rep instanceof ContainerRepresentation) {
foreach ($rep->getContents() as $child) {
$this->replaceDepthLimit($child, $depth + 1);
}
} elseif ($rep instanceof ValueRepresentation) {
$this->replaceDepthLimit($rep->getValue(), $depth + 1);
}
}
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use ArrayObject;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ContextInterface;
class ArrayObjectPlugin extends AbstractPlugin implements PluginBeginInterface
{
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_BEGIN;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
if (!$var instanceof ArrayObject) {
return null;
}
$flags = $var->getFlags();
if (ArrayObject::STD_PROP_LIST === $flags) {
return null;
}
$parser = $this->getParser();
$var->setFlags(ArrayObject::STD_PROP_LIST);
$v = $parser->parse($var, $c);
$var->setFlags($flags);
return $v;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\StringValue;
class Base64Plugin extends AbstractPlugin implements PluginCompleteInterface
{
/**
* The minimum length before a string will be considered for base64 decoding.
*/
public static int $min_length_hard = 16;
/**
* The minimum length before the base64 decoding will take precedence.
*/
public static int $min_length_soft = 50;
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (\strlen($var) < self::$min_length_hard || \strlen($var) % 4) {
return $v;
}
if (\preg_match('/^[A-Fa-f0-9]+$/', $var)) {
return $v;
}
if (!\preg_match('/^[A-Za-z0-9+\\/=]+$/', $var)) {
return $v;
}
$data = \base64_decode($var, true);
if (false === $data) {
return $v;
}
$c = $v->getContext();
$base = new BaseContext('base64_decode('.$c->getName().')');
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'base64_decode('.$ap.')';
}
$data = $this->getParser()->parse($data, $base);
$data->flags |= AbstractValue::FLAG_GENERATED;
if (!$data instanceof StringValue || false === $data->getEncoding()) {
return $v;
}
$r = new ValueRepresentation('Base64', $data);
if (\strlen($var) > self::$min_length_soft) {
$v->addRepresentation($r, 0);
} else {
$v->addRepresentation($r);
}
return $v;
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\BinaryRepresentation;
use Kint\Value\StringValue;
class BinaryPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if ($v instanceof StringValue && false === $v->getEncoding()) {
$v->addRepresentation(new BinaryRepresentation($v->getValue(), true), 0);
}
return $v;
}
}
+96
View File
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ContextInterface;
use Kint\Value\InstanceValue;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
class BlacklistPlugin extends AbstractPlugin implements PluginBeginInterface
{
/**
* List of classes and interfaces to blacklist.
*
* @var class-string[]
*/
public static array $blacklist = [];
/**
* List of classes and interfaces to blacklist except when dumped directly.
*
* @var class-string[]
*/
public static array $shallow_blacklist = [
ContainerInterface::class,
EventDispatcherInterface::class,
];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_BEGIN;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
foreach (self::$blacklist as $class) {
if ($var instanceof $class) {
return $this->blacklistValue($var, $c);
}
}
if ($c->getDepth() <= 0) {
return null;
}
foreach (self::$shallow_blacklist as $class) {
if ($var instanceof $class) {
return $this->blacklistValue($var, $c);
}
}
return null;
}
/**
* @param object &$var
*/
protected function blacklistValue(&$var, ContextInterface $c): InstanceValue
{
$object = new InstanceValue($c, \get_class($var), \spl_object_hash($var), \spl_object_id($var));
$object->flags |= AbstractValue::FLAG_BLACKLIST;
return $object;
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\MethodContext;
use Kint\Value\Context\PropertyContext;
use Kint\Value\DeclaredCallableBag;
use Kint\Value\InstanceValue;
use Kint\Value\MethodValue;
use Kint\Value\Representation\ContainerRepresentation;
use ReflectionProperty;
class ClassHooksPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static bool $verbose = false;
/** @psalm-var array<class-string, array<string, MethodValue[]>> */
private array $cache = [];
/** @psalm-var array<class-string, array<string, MethodValue[]>> */
private array $cache_verbose = [];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
if (!KINT_PHP84) {
return Parser::TRIGGER_NONE; // @codeCoverageIgnore
}
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof InstanceValue) {
return $v;
}
$props = $v->getRepresentation('properties');
if (!$props instanceof ContainerRepresentation) {
return $v;
}
foreach ($props->getContents() as $prop) {
$c = $prop->getContext();
if (!$c instanceof PropertyContext || PropertyContext::HOOK_NONE === $c->hooks) {
continue;
}
$cname = $c->getName();
$cowner = $c->owner_class;
if (!isset($this->cache_verbose[$cowner][$cname])) {
$ref = new ReflectionProperty($cowner, $cname);
$hooks = $ref->getHooks();
foreach ($hooks as $hook) {
if (!self::$verbose && false === $hook->getDocComment()) {
continue;
}
$m = new MethodValue(
new MethodContext($hook),
new DeclaredCallableBag($hook)
);
$this->cache_verbose[$cowner][$cname][] = $m;
if (false !== $hook->getDocComment()) {
$this->cache[$cowner][$cname][] = $m;
}
}
$this->cache[$cowner][$cname] ??= [];
if (self::$verbose) {
$this->cache_verbose[$cowner][$cname] ??= [];
}
}
$cache = self::$verbose ? $this->cache_verbose : $this->cache;
$cache = $cache[$cowner][$cname] ?? [];
if (\count($cache)) {
$prop->addRepresentation(new ContainerRepresentation('Hooks', $cache, 'propertyhooks'));
}
}
return $v;
}
}
+225
View File
@@ -0,0 +1,225 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\MethodContext;
use Kint\Value\DeclaredCallableBag;
use Kint\Value\InstanceValue;
use Kint\Value\MethodValue;
use Kint\Value\Representation\ContainerRepresentation;
use ReflectionClass;
use ReflectionMethod;
class ClassMethodsPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static bool $show_access_path = true;
/**
* Whether to go out of the way to show constructor paths
* when the instance isn't accessible.
*
* Disabling this improves performance.
*/
public static bool $show_constructor_path = false;
/** @psalm-var array<class-string, MethodValue[]> */
private array $instance_cache = [];
/** @psalm-var array<class-string, MethodValue[]> */
private array $static_cache = [];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
/**
* @psalm-template T of AbstractValue
*
* @psalm-param mixed $var
* @psalm-param T $v
*
* @psalm-return T
*/
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof InstanceValue) {
return $v;
}
$class = $v->getClassName();
$scope = $this->getParser()->getCallerClass();
if ($contents = $this->getCachedMethods($class)) {
if (self::$show_access_path) {
if (null !== $v->getContext()->getAccessPath()) {
// If we have an access path we can generate them for the children
foreach ($contents as $key => $val) {
if ($val->getContext()->isAccessible($scope)) {
$val = clone $val;
$val->getContext()->setAccessPathFromParent($v);
$contents[$key] = $val;
}
}
} elseif (self::$show_constructor_path && isset($contents['__construct'])) {
// __construct is the only exception: The only non-static method
// that can be called without access to the parent instance.
// Technically I guess it really is a static method but so long
// as PHP continues to refer to it as a normal one so will we.
$val = $contents['__construct'];
if ($val->getContext()->isAccessible($scope)) {
$val = clone $val;
$val->getContext()->setAccessPathFromParent($v);
$contents['__construct'] = $val;
}
}
}
$v->addRepresentation(new ContainerRepresentation('Methods', $contents));
}
if ($contents = $this->getCachedStaticMethods($class)) {
$v->addRepresentation(new ContainerRepresentation('Static methods', $contents));
}
return $v;
}
/**
* @psalm-param class-string $class
*
* @psalm-return MethodValue[]
*/
private function getCachedMethods(string $class): array
{
if (!isset($this->instance_cache[$class])) {
$methods = [];
$r = new ReflectionClass($class);
$parent_methods = [];
if ($parent = \get_parent_class($class)) {
$parent_methods = $this->getCachedMethods($parent);
}
foreach ($r->getMethods() as $mr) {
if ($mr->isStatic()) {
continue;
}
$canon_name = \strtolower($mr->name);
if ($mr->isPrivate() && '__construct' !== $canon_name) {
$canon_name = \strtolower($mr->getDeclaringClass()->name).'::'.$canon_name;
}
if ($mr->getDeclaringClass()->name === $class) {
$method = new MethodValue(new MethodContext($mr), new DeclaredCallableBag($mr));
$methods[$canon_name] = $method;
unset($parent_methods[$canon_name]);
} elseif (isset($parent_methods[$canon_name])) {
$method = $parent_methods[$canon_name];
unset($parent_methods[$canon_name]);
if (!$method->getContext()->inherited) {
$method = clone $method;
$method->getContext()->inherited = true;
}
$methods[$canon_name] = $method;
} elseif ($mr->getDeclaringClass()->isInterface()) {
$c = new MethodContext($mr);
$c->inherited = true;
$methods[$canon_name] = new MethodValue($c, new DeclaredCallableBag($mr));
}
}
foreach ($parent_methods as $name => $method) {
if (!$method->getContext()->inherited) {
$method = clone $method;
$method->getContext()->inherited = true;
}
if ('__construct' === $name) {
$methods['__construct'] = $method;
} else {
$methods[] = $method;
}
}
$this->instance_cache[$class] = $methods;
}
return $this->instance_cache[$class];
}
/**
* @psalm-param class-string $class
*
* @psalm-return MethodValue[]
*/
private function getCachedStaticMethods(string $class): array
{
if (!isset($this->static_cache[$class])) {
$methods = [];
$r = new ReflectionClass($class);
$parent_methods = [];
if ($parent = \get_parent_class($class)) {
$parent_methods = $this->getCachedStaticMethods($parent);
}
foreach ($r->getMethods(ReflectionMethod::IS_STATIC) as $mr) {
$canon_name = \strtolower($mr->getDeclaringClass()->name.'::'.$mr->name);
if ($mr->getDeclaringClass()->name === $class) {
$method = new MethodValue(new MethodContext($mr), new DeclaredCallableBag($mr));
$methods[$canon_name] = $method;
} elseif (isset($parent_methods[$canon_name])) {
$methods[$canon_name] = $parent_methods[$canon_name];
} elseif ($mr->getDeclaringClass()->isInterface()) {
$c = new MethodContext($mr);
$c->inherited = true;
$methods[$canon_name] = new MethodValue($c, new DeclaredCallableBag($mr));
}
unset($parent_methods[$canon_name]);
}
$this->static_cache[$class] = $methods + $parent_methods;
}
return $this->static_cache[$class];
}
}
+230
View File
@@ -0,0 +1,230 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ClassConstContext;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\StaticPropertyContext;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\UninitializedValue;
use ReflectionClass;
use ReflectionClassConstant;
use ReflectionProperty;
use UnitEnum;
class ClassStaticsPlugin extends AbstractPlugin implements PluginCompleteInterface
{
/** @psalm-var array<class-string, array<1|0, array<AbstractValue>>> */
private array $cache = [];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
/**
* @psalm-template T of AbstractValue
*
* @psalm-param mixed $var
* @psalm-param T $v
*
* @psalm-return T
*/
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof InstanceValue) {
return $v;
}
$deep = 0 === $this->getParser()->getDepthLimit();
$r = new ReflectionClass($v->getClassName());
if ($statics = $this->getStatics($r, $v->getContext()->getDepth() + 1)) {
$v->addRepresentation(new ContainerRepresentation('Static properties', \array_values($statics), 'statics'));
}
if ($consts = $this->getCachedConstants($r, $deep)) {
$v->addRepresentation(new ContainerRepresentation('Class constants', \array_values($consts), 'constants'));
}
return $v;
}
/** @psalm-return array<AbstractValue> */
private function getStatics(ReflectionClass $r, int $depth): array
{
$cdepth = $depth ?: 1;
$class = $r->getName();
$parent = $r->getParentClass();
$parent_statics = $parent ? $this->getStatics($parent, $depth) : [];
$statics = [];
foreach ($r->getProperties(ReflectionProperty::IS_STATIC) as $pr) {
$canon_name = \strtolower($pr->getDeclaringClass()->name.'::'.$pr->name);
if ($pr->getDeclaringClass()->name === $class) {
$statics[$canon_name] = $this->buildStaticValue($pr, $cdepth);
} elseif (isset($parent_statics[$canon_name])) {
$statics[$canon_name] = $parent_statics[$canon_name];
unset($parent_statics[$canon_name]);
} else {
// This should never happen since abstract static properties can't exist
$statics[$canon_name] = $this->buildStaticValue($pr, $cdepth); // @codeCoverageIgnore
}
}
foreach ($parent_statics as $canon_name => $value) {
$statics[$canon_name] = $value;
}
return $statics;
}
private function buildStaticValue(ReflectionProperty $pr, int $depth): AbstractValue
{
$context = new StaticPropertyContext(
$pr->name,
$pr->getDeclaringClass()->name,
ClassDeclaredContext::ACCESS_PUBLIC
);
$context->depth = $depth;
$context->final = KINT_PHP84 && $pr->isFinal();
if ($pr->isProtected()) {
$context->access = ClassDeclaredContext::ACCESS_PROTECTED;
} elseif ($pr->isPrivate()) {
$context->access = ClassDeclaredContext::ACCESS_PRIVATE;
}
$parser = $this->getParser();
if ($context->isAccessible($parser->getCallerClass())) {
$context->access_path = '\\'.$context->owner_class.'::$'.$context->name;
}
$pr->setAccessible(true);
/**
* @psalm-suppress TooFewArguments
* Appears to have been fixed in master.
*/
if (!$pr->isInitialized()) {
$context->access_path = null;
return new UninitializedValue($context);
}
$val = $pr->getValue();
$out = $this->getParser()->parse($val, $context);
$context->access_path = null;
return $out;
}
/** @psalm-return array<AbstractValue> */
private function getCachedConstants(ReflectionClass $r, bool $deep): array
{
$parser = $this->getParser();
$cdepth = $parser->getDepthLimit() ?: 1;
$deepkey = (int) $deep;
$class = $r->getName();
// Separate cache for dumping with/without depth limit
// This means we can do immediate depth limit on normal dumps
if (!isset($this->cache[$class][$deepkey])) {
$consts = [];
$parent_consts = [];
if ($parent = $r->getParentClass()) {
$parent_consts = $this->getCachedConstants($parent, $deep);
}
foreach ($r->getConstants() as $name => $val) {
$cr = new ReflectionClassConstant($class, $name);
// Skip enum constants
if ($cr->class === $class && \is_a($class, UnitEnum::class, true)) {
continue;
}
$canon_name = \strtolower($cr->getDeclaringClass()->name.'::'.$name);
if ($cr->getDeclaringClass()->name === $class) {
$context = $this->buildConstContext($cr);
$context->depth = $cdepth;
$consts[$canon_name] = $parser->parse($val, $context);
$context->access_path = null;
} elseif (isset($parent_consts[$canon_name])) {
$consts[$canon_name] = $parent_consts[$canon_name];
} else {
$context = $this->buildConstContext($cr);
$context->depth = $cdepth;
$consts[$canon_name] = $parser->parse($val, $context);
$context->access_path = null;
}
unset($parent_consts[$canon_name]);
}
$this->cache[$class][$deepkey] = $consts + $parent_consts;
}
return $this->cache[$class][$deepkey];
}
private function buildConstContext(ReflectionClassConstant $cr): ClassConstContext
{
$context = new ClassConstContext(
$cr->name,
$cr->getDeclaringClass()->name,
ClassDeclaredContext::ACCESS_PUBLIC
);
$context->final = KINT_PHP81 && $cr->isFinal();
if ($cr->isProtected()) {
$context->access = ClassDeclaredContext::ACCESS_PROTECTED;
} elseif ($cr->isPrivate()) {
$context->access = ClassDeclaredContext::ACCESS_PRIVATE;
} else {
$context->access_path = '\\'.$context->owner_class.'::'.$context->name;
}
return $context;
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\InstanceValue;
use ReflectionClass;
class ClassStringsPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static array $blacklist = [];
protected ClassMethodsPlugin $methods_plugin;
protected ClassStaticsPlugin $statics_plugin;
public function __construct(Parser $parser)
{
parent::__construct($parser);
$this->methods_plugin = new ClassMethodsPlugin($parser);
$this->statics_plugin = new ClassStaticsPlugin($parser);
}
public function setParser(Parser $p): void
{
parent::setParser($p);
$this->methods_plugin->setParser($p);
$this->statics_plugin->setParser($p);
}
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
$c = $v->getContext();
if ($c->getDepth() > 0) {
return $v;
}
if (!\class_exists($var, true)) {
return $v;
}
if (\in_array($var, self::$blacklist, true)) {
return $v;
}
$r = new ReflectionClass($var);
$fakeC = new BaseContext($c->getName());
$fakeC->access_path = null;
$fakeV = new InstanceValue($fakeC, $r->getName(), 'badhash', -1);
$fakeVar = null;
$fakeV = $this->methods_plugin->parseComplete($fakeVar, $fakeV, Parser::TRIGGER_SUCCESS);
$fakeV = $this->statics_plugin->parseComplete($fakeVar, $fakeV, Parser::TRIGGER_SUCCESS);
foreach (['methods', 'static_methods', 'statics', 'constants'] as $rep) {
if ($rep = $fakeV->getRepresentation($rep)) {
$v->addRepresentation($rep);
}
}
return $v;
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Closure;
use Kint\Value\AbstractValue;
use Kint\Value\ClosureValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ContainerRepresentation;
use ReflectionFunction;
use ReflectionReference;
class ClosurePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof Closure) {
return $v;
}
$c = $v->getContext();
$object = new ClosureValue($c, $var);
$object->flags = $v->flags;
$object->appendRepresentations($v->getRepresentations());
$object->removeRepresentation('properties');
$closure = new ReflectionFunction($var);
$statics = [];
if ($v = $closure->getClosureThis()) {
$statics = ['this' => $v];
}
$statics = $statics + $closure->getStaticVariables();
$cdepth = $c->getDepth();
if (\count($statics)) {
$statics_parsed = [];
$parser = $this->getParser();
foreach ($statics as $name => $_) {
$base = new BaseContext('$'.$name);
$base->depth = $cdepth + 1;
$base->reference = null !== ReflectionReference::fromArrayElement($statics, $name);
$statics_parsed[$name] = $parser->parse($statics[$name], $base);
}
$object->addRepresentation(new ContainerRepresentation('Uses', $statics_parsed), 0);
}
return $object;
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use InvalidArgumentException;
use Kint\Value\AbstractValue;
use Kint\Value\ColorValue;
use Kint\Value\Representation\ColorRepresentation;
use Kint\Value\StringValue;
class ColorPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (\strlen($var) > 32) {
return $v;
}
if (!$v instanceof StringValue) {
return $v;
}
$trimmed = \strtolower(\trim($var));
if (!isset(ColorRepresentation::$color_map[$trimmed]) && !\preg_match('/^(?:(?:rgb|hsl)[^\\)]{6,}\\)|#[0-9a-fA-F]{3,8})$/', $trimmed)) {
return $v;
}
try {
$rep = new ColorRepresentation($var);
} catch (InvalidArgumentException $e) {
return $v;
}
$out = new ColorValue($v->getContext(), $v->getValue(), $v->getEncoding());
$out->flags = $v->flags;
$out->appendRepresentations($v->getRepresentations());
$out->removeRepresentation('contents');
$out->addRepresentation($rep, 0);
return $out;
}
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
interface ConstructablePluginInterface extends PluginInterface
{
public function __construct(Parser $p);
}
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use DateTimeInterface;
use Error;
use Kint\Value\AbstractValue;
use Kint\Value\DateTimeValue;
use Kint\Value\InstanceValue;
class DateTimePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof DateTimeInterface || !$v instanceof InstanceValue) {
return $v;
}
try {
$dtv = new DateTimeValue($v->getContext(), $var);
} catch (Error $e) {
// Only happens if someone makes a DateTimeInterface with a private __clone
return $v;
}
$dtv->setChildren($v->getChildren());
$dtv->flags = $v->flags;
$dtv->appendRepresentations($v->getRepresentations());
return $dtv;
}
}
+543
View File
@@ -0,0 +1,543 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Dom\Attr;
use Dom\CharacterData;
use Dom\Document;
use Dom\DocumentType;
use Dom\Element;
use Dom\HTMLElement;
use Dom\NamedNodeMap;
use Dom\Node;
use Dom\NodeList;
use DOMAttr;
use DOMCharacterData;
use DOMDocumentType;
use DOMElement;
use DOMNamedNodeMap;
use DOMNode;
use DOMNodeList;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Context\PropertyContext;
use Kint\Value\DomNodeListValue;
use Kint\Value\DomNodeValue;
use Kint\Value\FixedWidthValue;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\StringValue;
use LogicException;
class DomPlugin extends AbstractPlugin implements PluginBeginInterface
{
/**
* Reflection doesn't work below 8.1, also it won't show readonly status.
*
* In order to ensure this is stable enough we're only going to provide
* properties for element and node. If subclasses like attr or document
* have their own fields then tough shit we're not showing them.
*
* @psalm-var non-empty-array<string, bool> Property names to readable status
*/
public const NODE_PROPS = [
'nodeType' => true,
'nodeName' => true,
'baseURI' => true,
'isConnected' => true,
'ownerDocument' => true,
'parentNode' => true,
'parentElement' => true,
'childNodes' => true,
'firstChild' => true,
'lastChild' => true,
'previousSibling' => true,
'nextSibling' => true,
'nodeValue' => true,
'textContent' => false,
];
/**
* @psalm-var non-empty-array<string, bool> Property names to readable status
*/
public const ELEMENT_PROPS = [
'namespaceURI' => true,
'prefix' => true,
'localName' => true,
'tagName' => true,
'id' => false,
'className' => false,
'classList' => true,
'attributes' => true,
'firstElementChild' => true,
'lastElementChild' => true,
'childElementCount' => true,
'previousElementSibling' => true,
'nextElementSibling' => true,
'innerHTML' => false,
'outerHTML' => false,
'substitutedNodeValue' => false,
];
public const DOM_NS_VERSIONS = [
'outerHTML' => KINT_PHP85,
];
/**
* @psalm-var non-empty-array<string, bool> Property names to readable status
*/
public const DOMNODE_PROPS = [
'nodeName' => true,
'nodeValue' => false,
'nodeType' => true,
'parentNode' => true,
'parentElement' => true,
'childNodes' => true,
'firstChild' => true,
'lastChild' => true,
'previousSibling' => true,
'nextSibling' => true,
'attributes' => true,
'isConnected' => true,
'ownerDocument' => true,
'namespaceURI' => true,
'prefix' => false,
'localName' => true,
'baseURI' => true,
'textContent' => false,
];
/**
* @psalm-var non-empty-array<string, bool> Property names to readable status
*/
public const DOMELEMENT_PROPS = [
'tagName' => true,
'className' => false,
'id' => false,
'schemaTypeInfo' => true,
'firstElementChild' => true,
'lastElementChild' => true,
'childElementCount' => true,
'previousElementSibling' => true,
'nextElementSibling' => true,
];
public const DOM_VERSIONS = [
'parentElement' => KINT_PHP83,
'isConnected' => KINT_PHP83,
'className' => KINT_PHP83,
'id' => KINT_PHP83,
'firstElementChild' => KINT_PHP80,
'lastElementChild' => KINT_PHP80,
'childElementCount' => KINT_PHP80,
'previousElementSibling' => KINT_PHP80,
'nextElementSibling' => KINT_PHP80,
];
/**
* List of properties to skip parsing.
*
* The properties of a Dom\Node can do a *lot* of damage to debuggers. The
* Dom\Node contains not one, not two, but 13 different ways to recurse into itself:
* * parentNode
* * firstChild
* * lastChild
* * previousSibling
* * nextSibling
* * parentElement
* * firstElementChild
* * lastElementChild
* * previousElementSibling
* * nextElementSibling
* * childNodes
* * attributes
* * ownerDocument
*
* All of this combined: the tiny SVGs used as the caret in Kint were already
* enough to make parsing and rendering take over a second, and send memory
* usage over 128 megs, back in the old DOM API. So we blacklist every field
* we don't strictly need and hope that that's good enough.
*
* In retrospect -- this is probably why print_r does the same
*
* @psalm-var array<string, true>
*/
public static array $blacklist = [
'parentNode' => true,
'firstChild' => true,
'lastChild' => true,
'previousSibling' => true,
'nextSibling' => true,
'firstElementChild' => true,
'lastElementChild' => true,
'parentElement' => true,
'previousElementSibling' => true,
'nextElementSibling' => true,
'ownerDocument' => true,
];
/**
* Show all properties and methods.
*/
public static bool $verbose = false;
protected ClassMethodsPlugin $methods_plugin;
protected ClassStaticsPlugin $statics_plugin;
public function __construct(Parser $parser)
{
parent::__construct($parser);
$this->methods_plugin = new ClassMethodsPlugin($parser);
$this->statics_plugin = new ClassStaticsPlugin($parser);
}
public function setParser(Parser $p): void
{
parent::setParser($p);
$this->methods_plugin->setParser($p);
$this->statics_plugin->setParser($p);
}
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_BEGIN;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
// Attributes and chardata (Which is parent of comments and text
// nodes) don't need children or attributes of their own
if ($var instanceof Attr || $var instanceof CharacterData || $var instanceof DOMAttr || $var instanceof DOMCharacterData) {
return $this->parseText($var, $c);
}
if ($var instanceof NamedNodeMap || $var instanceof NodeList || $var instanceof DOMNamedNodeMap || $var instanceof DOMNodeList) {
return $this->parseList($var, $c);
}
if ($var instanceof Node || $var instanceof DOMNode) {
return $this->parseNode($var, $c);
}
return null;
}
/** @psalm-param Node|DOMNode $var */
private function parseProperty(object $var, string $prop, ContextInterface $c): AbstractValue
{
if (!isset($var->{$prop})) {
return new FixedWidthValue($c, null);
}
$parser = $this->getParser();
$value = $var->{$prop};
if (\is_scalar($value)) {
return $parser->parse($value, $c);
}
if (isset(self::$blacklist[$prop])) {
$b = new InstanceValue($c, \get_class($value), \spl_object_hash($value), \spl_object_id($value));
$b->flags |= AbstractValue::FLAG_GENERATED | AbstractValue::FLAG_BLACKLIST;
return $b;
}
// Everything we can handle in parseBegin
if ($value instanceof Attr || $value instanceof CharacterData || $value instanceof DOMAttr || $value instanceof DOMCharacterData || $value instanceof NamedNodeMap || $value instanceof NodeList || $value instanceof DOMNamedNodeMap || $value instanceof DOMNodeList || $value instanceof Node || $value instanceof DOMNode) {
$out = $this->parseBegin($value, $c);
}
if (!isset($out)) {
// Shouldn't ever happen
$out = $parser->parse($value, $c); // @codeCoverageIgnore
}
$out->flags |= AbstractValue::FLAG_GENERATED;
return $out;
}
/** @psalm-param Attr|CharacterData|DOMAttr|DOMCharacterData $var */
private function parseText(object $var, ContextInterface $c): AbstractValue
{
if ($c instanceof BaseContext && null !== $c->access_path) {
$c->access_path .= '->nodeValue';
}
return $this->parseProperty($var, 'nodeValue', $c);
}
/** @psalm-param NamedNodeMap|NodeList|DOMNamedNodeMap|DOMNodeList $var */
private function parseList(object $var, ContextInterface $c): InstanceValue
{
if ($var instanceof NodeList || $var instanceof DOMNodeList) {
$v = new DomNodeListValue($c, $var);
} else {
$v = new InstanceValue($c, \get_class($var), \spl_object_hash($var), \spl_object_id($var));
}
$parser = $this->getParser();
$pdepth = $parser->getDepthLimit();
// Depth limit
// Use empty iterator representation since we need it to point out depth limits
if (($var instanceof NodeList || $var instanceof DOMNodeList) && $pdepth && $c->getDepth() >= $pdepth) {
$v->flags |= AbstractValue::FLAG_DEPTH_LIMIT;
return $v;
}
if (self::$verbose) {
$v = $this->methods_plugin->parseComplete($var, $v, Parser::TRIGGER_SUCCESS);
$v = $this->statics_plugin->parseComplete($var, $v, Parser::TRIGGER_SUCCESS);
}
if (0 === $var->length) {
$v->setChildren([]);
return $v;
}
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
$contents = [];
foreach ($var as $key => $item) {
$base_obj = new BaseContext($item->nodeName);
$base_obj->depth = $cdepth + 1;
if ($var instanceof NamedNodeMap || $var instanceof DOMNamedNodeMap) {
if (null !== $ap) {
$base_obj->access_path = $ap.'['.\var_export($item->nodeName, true).']';
}
} else { // NodeList
if (null !== $ap) {
$base_obj->access_path = $ap.'['.\var_export($key, true).']';
}
}
if ($item instanceof HTMLElement) {
$base_obj->name = $item->localName;
}
$item = $parser->parse($item, $base_obj);
$item->flags |= AbstractValue::FLAG_GENERATED;
$contents[] = $item;
}
$v->setChildren($contents);
if ($contents) {
$v->addRepresentation(new ContainerRepresentation('Iterator', $contents), 0);
}
return $v;
}
/** @psalm-param Node|DOMNode $var */
private function parseNode(object $var, ContextInterface $c): DomNodeValue
{
$class = \get_class($var);
$pdepth = $this->getParser()->getDepthLimit();
if ($pdepth && $c->getDepth() >= $pdepth) {
$v = new DomNodeValue($c, $var);
$v->flags |= AbstractValue::FLAG_DEPTH_LIMIT;
return $v;
}
if (($var instanceof DocumentType || $var instanceof DOMDocumentType) && $c instanceof BaseContext && $c->name === $var->nodeName) {
$c->name = '!DOCTYPE '.$c->name;
}
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
$properties = [];
$children = [];
$attributes = [];
foreach (self::getKnownProperties($var) as $prop => $readonly) {
$prop_c = new PropertyContext($prop, $class, ClassDeclaredContext::ACCESS_PUBLIC);
$prop_c->depth = $cdepth + 1;
$prop_c->readonly = KINT_PHP81 && $readonly;
if (null !== $ap) {
$prop_c->access_path = $ap.'->'.$prop;
}
$properties[] = $prop_obj = $this->parseProperty($var, $prop, $prop_c);
if ('childNodes' === $prop) {
if (!$prop_obj instanceof DomNodeListValue) {
throw new LogicException('childNodes property parsed incorrectly'); // @codeCoverageIgnore
}
$children = self::getChildren($prop_obj);
} elseif ('attributes' === $prop) {
$attributes = $prop_obj->getRepresentation('iterator');
$attributes = $attributes instanceof ContainerRepresentation ? $attributes->getContents() : [];
} elseif ('classList' === $prop) {
if ($iter = $prop_obj->getRepresentation('iterator')) {
$prop_obj->removeRepresentation($iter);
$prop_obj->addRepresentation($iter, 0);
}
}
}
$v = new DomNodeValue($c, $var);
// If we're in text mode, we can see children through the childNodes property
$v->setChildren($properties);
if ($children) {
$v->addRepresentation(new ContainerRepresentation('Children', $children, null, true));
}
if ($attributes) {
$v->addRepresentation(new ContainerRepresentation('Attributes', $attributes));
}
if (self::$verbose) {
$v->addRepresentation(new ContainerRepresentation('Properties', $properties));
$v = $this->methods_plugin->parseComplete($var, $v, Parser::TRIGGER_SUCCESS);
$v = $this->statics_plugin->parseComplete($var, $v, Parser::TRIGGER_SUCCESS);
}
return $v;
}
/**
* @psalm-param Node|DOMNode $var
*
* @psalm-return non-empty-array<string, bool>
*/
public static function getKnownProperties(object $var): array
{
if ($var instanceof Node) {
$known_properties = self::NODE_PROPS;
if ($var instanceof Element) {
$known_properties += self::ELEMENT_PROPS;
}
if ($var instanceof Document) {
$known_properties['textContent'] = true;
}
if ($var instanceof Attr || $var instanceof CharacterData) {
$known_properties['nodeValue'] = false;
}
foreach (self::DOM_NS_VERSIONS as $key => $val) {
/**
* @psalm-var bool $val
* Psalm bug #4509
*/
if (false === $val) {
unset($known_properties[$key]); // @codeCoverageIgnore
}
}
} else {
$known_properties = self::DOMNODE_PROPS;
if ($var instanceof DOMElement) {
$known_properties += self::DOMELEMENT_PROPS;
}
foreach (self::DOM_VERSIONS as $key => $val) {
/**
* @psalm-var bool $val
* Psalm bug #4509
*/
if (false === $val) {
unset($known_properties[$key]); // @codeCoverageIgnore
}
}
}
/** @psalm-var non-empty-array $known_properties */
if (!self::$verbose) {
$known_properties = \array_intersect_key($known_properties, [
'nodeValue' => null,
'childNodes' => null,
'attributes' => null,
]);
}
return $known_properties;
}
/** @psalm-return list<AbstractValue> */
private static function getChildren(DomNodeListValue $property): array
{
if (0 === $property->getLength()) {
return [];
}
if ($property->flags & AbstractValue::FLAG_DEPTH_LIMIT) {
return [$property];
}
$list_items = $property->getChildren();
if (null === $list_items) {
// This is here for psalm but all DomNodeListValue should
// either be depth_limit or have array children
return []; // @codeCoverageIgnore
}
$children = [];
foreach ($list_items as $node) {
// Remove text nodes if theyre empty
if ($node instanceof StringValue && '#text' === $node->getContext()->getName()) {
/**
* @psalm-suppress InvalidArgument
* Psalm bug #11055
*/
if (\ctype_space($node->getValue()) || '' === $node->getValue()) {
continue;
}
}
$children[] = $node;
}
return $children;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\EnumValue;
use Kint\Value\Representation\ContainerRepresentation;
use UnitEnum;
class EnumPlugin extends AbstractPlugin implements PluginCompleteInterface
{
private array $cache = [];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
if (!KINT_PHP81) {
return Parser::TRIGGER_NONE;
}
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof UnitEnum) {
return $v;
}
$c = $v->getContext();
$class = \get_class($var);
if (!isset($this->cache[$class])) {
$contents = [];
foreach ($var->cases() as $case) {
$base = new BaseContext($case->name);
$base->access_path = '\\'.$class.'::'.$case->name;
$base->depth = $c->getDepth() + 1;
$contents[] = new EnumValue($base, $case);
}
/** @psalm-var non-empty-array<EnumValue> $contents */
$this->cache[$class] = new ContainerRepresentation('Enum values', $contents, 'enum');
}
$object = new EnumValue($c, $var);
$object->flags = $v->flags;
$object->appendRepresentations($v->getRepresentations());
$object->addRepresentation($this->cache[$class], 0);
return $object;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Representation\SplFileInfoRepresentation;
use SplFileInfo;
use TypeError;
class FsPathPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static array $blacklist = ['/', '.'];
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (\strlen($var) > 2048) {
return $v;
}
if (!\preg_match('/[\\/\\'.DIRECTORY_SEPARATOR.']/', $var)) {
return $v;
}
if (\preg_match('/[?<>"*|]/', $var)) {
return $v;
}
try {
if (!@\file_exists($var)) {
return $v;
}
} catch (TypeError $e) {// @codeCoverageIgnore
// Only possible in PHP 7
return $v; // @codeCoverageIgnore
}
if (\in_array($var, self::$blacklist, true)) {
return $v;
}
$v->addRepresentation(new SplFileInfoRepresentation(new SplFileInfo($var)), 0);
return $v;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Dom\HTMLDocument;
use DOMException;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ValueRepresentation;
class HtmlPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
if (!KINT_PHP84) {
return Parser::TRIGGER_NONE; // @codeCoverageIgnore
}
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if ('<!doctype html>' !== \strtolower(\substr($var, 0, 15))) {
return $v;
}
try {
$html = HTMLDocument::createFromString($var, LIBXML_NOERROR);
} catch (DOMException $e) { // @codeCoverageIgnore
return $v; // @codeCoverageIgnore
}
$c = $v->getContext();
$base = new BaseContext('childNodes');
$base->depth = $c->getDepth();
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = '\\Dom\\HTMLDocument::createFromString('.$ap.')->childNodes';
}
$out = $this->getParser()->parse($html->childNodes, $base);
$iter = $out->getRepresentation('iterator');
if ($out->flags & AbstractValue::FLAG_DEPTH_LIMIT) {
$out->flags |= AbstractValue::FLAG_GENERATED;
$v->addRepresentation(new ValueRepresentation('HTML', $out), 0);
} elseif ($iter instanceof ContainerRepresentation) {
$v->addRepresentation(new ContainerRepresentation('HTML', $iter->getContents()), 0);
}
return $v;
}
}
+146
View File
@@ -0,0 +1,146 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Dom\NamedNodeMap;
use Dom\NodeList;
use DOMNamedNodeMap;
use DOMNodeList;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\UninitializedValue;
use mysqli_result;
use PDOStatement;
use SimpleXMLElement;
use SplFileObject;
use Throwable;
use Traversable;
class IteratorPlugin extends AbstractPlugin implements PluginCompleteInterface
{
/**
* List of classes and interfaces to blacklist.
*
* Certain classes (Such as PDOStatement) irreversibly lose information
* when traversed. Others are just huge. Either way, put them in here
* and you won't have to worry about them being parsed.
*
* @psalm-var class-string[]
*/
public static array $blacklist = [
NamedNodeMap::class,
NodeList::class,
DOMNamedNodeMap::class,
DOMNodeList::class,
mysqli_result::class,
PDOStatement::class,
SimpleXMLElement::class,
SplFileObject::class,
];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof Traversable || !$v instanceof InstanceValue || $v->getRepresentation('iterator')) {
return $v;
}
$c = $v->getContext();
foreach (self::$blacklist as $class) {
/**
* @psalm-suppress RedundantCondition
* Psalm bug #11076
*/
if ($var instanceof $class) {
$base = new BaseContext($class.' Iterator Contents');
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'iterator_to_array('.$ap.', false)';
}
$b = new UninitializedValue($base);
$b->flags |= AbstractValue::FLAG_BLACKLIST;
$v->addRepresentation(new ValueRepresentation('Iterator', $b));
return $v;
}
}
try {
$data = \iterator_to_array($var, false);
} catch (Throwable $t) {
return $v;
}
if (!\count($data)) {
return $v;
}
$base = new BaseContext('Iterator Contents');
$base->depth = $c->getDepth();
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'iterator_to_array('.$ap.', false)';
}
$iter_val = $this->getParser()->parse($data, $base);
// Since we didn't get TRIGGER_DEPTH_LIMIT and set the iterator to the
// same depth we can assume at least 1 level deep will exist
if ($iter_val instanceof ArrayValue && $iterator_items = $iter_val->getContents()) {
$r = new ContainerRepresentation('Iterator', $iterator_items);
$iterator_items = \array_values($iterator_items);
} else {
$r = new ValueRepresentation('Iterator', $iter_val);
$iterator_items = [$iter_val];
}
if ((bool) $v->getChildren()) {
$v->addRepresentation($r);
} else {
$v->setChildren($iterator_items);
$v->addRepresentation($r, 0);
}
return $v;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use JsonException;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ValueRepresentation;
class JsonPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!isset($var[0]) || ('{' !== $var[0] && '[' !== $var[0])) {
return $v;
}
try {
$json = \json_decode($var, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return $v;
}
$json = (array) $json;
$c = $v->getContext();
$base = new BaseContext('JSON Decode');
$base->depth = $c->getDepth();
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'json_decode('.$ap.', true)';
}
$json = $this->getParser()->parse($json, $base);
if ($json instanceof ArrayValue && (~$json->flags & AbstractValue::FLAG_DEPTH_LIMIT) && $contents = $json->getContents()) {
foreach ($contents as $value) {
$value->flags |= AbstractValue::FLAG_GENERATED;
}
$v->addRepresentation(new ContainerRepresentation('Json', $contents), 0);
} else {
$json->flags |= AbstractValue::FLAG_GENERATED;
$v->addRepresentation(new ValueRepresentation('Json', $json), 0);
}
return $v;
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\MicrotimeValue;
use Kint\Value\Representation\MicrotimeRepresentation;
class MicrotimePlugin extends AbstractPlugin implements PluginCompleteInterface
{
private static ?array $last = null;
private static ?float $start = null;
private static int $times = 0;
private static ?string $group = null;
public function getTypes(): array
{
return ['string', 'double'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
$c = $v->getContext();
if ($c->getDepth() > 0) {
return $v;
}
if (\is_string($var)) {
if ('microtime()' !== $c->getName() || !\preg_match('/^0\\.[0-9]{8} [0-9]{10}$/', $var)) {
return $v;
}
$usec = (int) \substr($var, 2, 6);
$sec = (int) \substr($var, 11, 10);
} else {
if ('microtime(...)' !== $c->getName()) {
return $v;
}
$sec = (int) \floor($var);
$usec = $var - $sec;
$usec = (int) \floor($usec * 1000000);
}
$time = $sec + ($usec / 1000000);
if (null !== self::$last) {
$last_time = self::$last[0] + (self::$last[1] / 1000000);
$lap = $time - $last_time;
++self::$times;
} else {
$lap = null;
self::$start = $time;
}
self::$last = [$sec, $usec];
if (null !== $lap) {
$total = $time - self::$start;
$r = new MicrotimeRepresentation($sec, $usec, self::getGroup(), $lap, $total, self::$times);
} else {
$r = new MicrotimeRepresentation($sec, $usec, self::getGroup());
}
$out = new MicrotimeValue($v);
$out->removeRepresentation('contents');
$out->addRepresentation($r);
return $out;
}
/** @psalm-api */
public static function clean(): void
{
self::$last = null;
self::$start = null;
self::$times = 0;
self::newGroup();
}
private static function getGroup(): string
{
if (null === self::$group) {
return self::newGroup();
}
return self::$group;
}
private static function newGroup(): string
{
return self::$group = \bin2hex(\random_bytes(4));
}
}
+176
View File
@@ -0,0 +1,176 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\PropertyContext;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use mysqli;
use Throwable;
/**
* Adds support for mysqli object parsing.
*
* Due to the way mysqli is implemented in PHP, this will cause
* warnings on certain mysqli objects if screaming is enabled.
*/
class MysqliPlugin extends AbstractPlugin implements PluginCompleteInterface
{
// These 'properties' are actually globals
public const ALWAYS_READABLE = [
'client_version' => true,
'connect_errno' => true,
'connect_error' => true,
];
// These are readable on empty mysqli objects, but not on failed connections
public const EMPTY_READABLE = [
'client_info' => true,
'errno' => true,
'error' => true,
];
// These are only readable on connected mysqli objects
public const CONNECTED_READABLE = [
'affected_rows' => true,
'error_list' => true,
'field_count' => true,
'host_info' => true,
'info' => true,
'insert_id' => true,
'server_info' => true,
'server_version' => true,
'sqlstate' => true,
'protocol_version' => true,
'thread_id' => true,
'warning_count' => true,
];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_COMPLETE;
}
/**
* Before 8.1: Properties were nulls when cast to array
* After 8.1: Properties are readonly and uninitialized when cast to array (Aka missing).
*/
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof mysqli || !$v instanceof InstanceValue) {
return $v;
}
$props = $v->getRepresentation('properties');
if (!$props instanceof ContainerRepresentation) {
return $v;
}
/**
* @psalm-var ?string $var->sqlstate
* @psalm-var ?string $var->client_info
* Psalm bug #4502
*/
try {
$connected = \is_string(@$var->sqlstate);
} catch (Throwable $t) {
$connected = false;
}
try {
$empty = !$connected && \is_string(@$var->client_info);
} catch (Throwable $t) { // @codeCoverageIgnore
// Only possible in PHP 8.0. Before 8.0 there's no exception,
// after 8.1 there are no failed connection objects
$empty = false; // @codeCoverageIgnore
}
$parser = $this->getParser();
$new_contents = [];
foreach ($props->getContents() as $key => $obj) {
$new_contents[$key] = $obj;
$c = $obj->getContext();
if (!$c instanceof PropertyContext) {
continue;
}
if (isset(self::CONNECTED_READABLE[$c->getName()])) {
$c->readonly = KINT_PHP81;
if (!$connected) {
// No failed connections after PHP 8.1
continue; // @codeCoverageIgnore
}
} elseif (isset(self::EMPTY_READABLE[$c->getName()])) {
$c->readonly = KINT_PHP81;
// No failed connections after PHP 8.1
if (!$connected && !$empty) { // @codeCoverageIgnore
continue; // @codeCoverageIgnore
}
} elseif (!isset(self::ALWAYS_READABLE[$c->getName()])) {
continue; // @codeCoverageIgnore
}
$c->readonly = KINT_PHP81;
// Only handle unparsed properties
if ((KINT_PHP81 ? 'uninitialized' : 'null') !== $obj->getType()) {
continue;
}
$param = $var->{$c->getName()};
// If it really was a null
if (!KINT_PHP81 && null === $param) {
continue; // @codeCoverageIgnore
}
$new_contents[$key] = $parser->parse($param, $c);
}
$new_contents = \array_values($new_contents);
$v->setChildren($new_contents);
if ($new_contents) {
$v->replaceRepresentation(new ContainerRepresentation('Properties', $new_contents));
}
return $v;
}
}
+592
View File
@@ -0,0 +1,592 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use DomainException;
use InvalidArgumentException;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\ClosedResourceValue;
use Kint\Value\Context\ArrayContext;
use Kint\Value\Context\ClassDeclaredContext;
use Kint\Value\Context\ClassOwnedContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Context\PropertyContext;
use Kint\Value\FixedWidthValue;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\StringRepresentation;
use Kint\Value\ResourceValue;
use Kint\Value\StringValue;
use Kint\Value\UninitializedValue;
use Kint\Value\UnknownValue;
use Kint\Value\VirtualValue;
use ReflectionClass;
use ReflectionObject;
use ReflectionProperty;
use ReflectionReference;
use Throwable;
/**
* @psalm-type ParserTrigger int-mask-of<Parser::TRIGGER_*>
*/
class Parser
{
/**
* Plugin triggers.
*
* These are constants indicating trigger points for plugins
*
* BEGIN: Before normal parsing
* SUCCESS: After successful parsing
* RECURSION: After parsing cancelled by recursion
* DEPTH_LIMIT: After parsing cancelled by depth limit
* COMPLETE: SUCCESS | RECURSION | DEPTH_LIMIT
*
* While a plugin's getTriggers may return any of these only one should
* be given to the plugin when PluginInterface::parse is called
*/
public const TRIGGER_NONE = 0;
public const TRIGGER_BEGIN = 1 << 0;
public const TRIGGER_SUCCESS = 1 << 1;
public const TRIGGER_RECURSION = 1 << 2;
public const TRIGGER_DEPTH_LIMIT = 1 << 3;
public const TRIGGER_COMPLETE = self::TRIGGER_SUCCESS | self::TRIGGER_RECURSION | self::TRIGGER_DEPTH_LIMIT;
/** @psalm-var ?class-string */
protected ?string $caller_class;
protected int $depth_limit = 0;
protected array $array_ref_stack = [];
protected array $object_hashes = [];
protected array $plugins = [];
/**
* @param int $depth_limit Maximum depth to parse data
* @param ?string $caller Caller class name
*
* @psalm-param ?class-string $caller
*/
public function __construct(int $depth_limit = 0, ?string $caller = null)
{
$this->depth_limit = $depth_limit;
$this->caller_class = $caller;
}
/**
* Set the caller class.
*
* @psalm-param ?class-string $caller
*/
public function setCallerClass(?string $caller = null): void
{
$this->noRecurseCall();
$this->caller_class = $caller;
}
/** @psalm-return ?class-string */
public function getCallerClass(): ?string
{
return $this->caller_class;
}
/**
* Set the depth limit.
*
* @param int $depth_limit Maximum depth to parse data, 0 for none
*/
public function setDepthLimit(int $depth_limit = 0): void
{
$this->noRecurseCall();
$this->depth_limit = $depth_limit;
}
public function getDepthLimit(): int
{
return $this->depth_limit;
}
/**
* Parses a variable into a Kint object structure.
*
* @param mixed &$var The input variable
*/
public function parse(&$var, ContextInterface $c): AbstractValue
{
$type = \strtolower(\gettype($var));
if ($v = $this->applyPluginsBegin($var, $c, $type)) {
return $v;
}
switch ($type) {
case 'array':
return $this->parseArray($var, $c);
case 'boolean':
case 'double':
case 'integer':
case 'null':
return $this->parseFixedWidth($var, $c);
case 'object':
return $this->parseObject($var, $c);
case 'resource':
return $this->parseResource($var, $c);
case 'string':
return $this->parseString($var, $c);
case 'resource (closed)':
return $this->parseResourceClosed($var, $c);
case 'unknown type': // @codeCoverageIgnore
default:
// These should never happen. Unknown is resource (closed) from old
// PHP versions and there shouldn't be any other types.
return $this->parseUnknown($var, $c); // @codeCoverageIgnore
}
}
public function addPlugin(PluginInterface $p): void
{
try {
$this->noRecurseCall();
} catch (DomainException $e) { // @codeCoverageIgnore
\trigger_error('Calling Kint\\Parser::addPlugin from inside a parse is deprecated', E_USER_DEPRECATED); // @codeCoverageIgnore
}
if (!$types = $p->getTypes()) {
return;
}
if (!$triggers = $p->getTriggers()) {
return;
}
if ($triggers & self::TRIGGER_BEGIN && !$p instanceof PluginBeginInterface) {
throw new InvalidArgumentException('Parsers triggered on begin must implement PluginBeginInterface');
}
if ($triggers & self::TRIGGER_COMPLETE && !$p instanceof PluginCompleteInterface) {
throw new InvalidArgumentException('Parsers triggered on completion must implement PluginCompleteInterface');
}
$p->setParser($this);
foreach ($types as $type) {
$this->plugins[$type] ??= [
self::TRIGGER_BEGIN => [],
self::TRIGGER_SUCCESS => [],
self::TRIGGER_RECURSION => [],
self::TRIGGER_DEPTH_LIMIT => [],
];
foreach ($this->plugins[$type] as $trigger => &$pool) {
if ($triggers & $trigger) {
$pool[] = $p;
}
}
}
}
public function clearPlugins(): void
{
try {
$this->noRecurseCall();
} catch (DomainException $e) { // @codeCoverageIgnore
\trigger_error('Calling Kint\\Parser::clearPlugins from inside a parse is deprecated', E_USER_DEPRECATED); // @codeCoverageIgnore
}
$this->plugins = [];
}
protected function noRecurseCall(): void
{
$bt = \debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS);
\reset($bt);
/** @psalm-var class-string $caller_frame['class'] */
$caller_frame = \next($bt);
foreach ($bt as $frame) {
if (isset($frame['object']) && $frame['object'] === $this && 'parse' === $frame['function']) {
throw new DomainException($caller_frame['class'].'::'.$caller_frame['function'].' cannot be called from inside a parse');
}
}
}
/**
* @psalm-param null|bool|float|int &$var
*/
private function parseFixedWidth(&$var, ContextInterface $c): AbstractValue
{
$v = new FixedWidthValue($c, $var);
return $this->applyPluginsComplete($var, $v, self::TRIGGER_SUCCESS);
}
private function parseString(string &$var, ContextInterface $c): AbstractValue
{
$string = new StringValue($c, $var, Utils::detectEncoding($var));
if (false !== $string->getEncoding() && \strlen($var)) {
$string->addRepresentation(new StringRepresentation('Contents', $var, null, true));
}
return $this->applyPluginsComplete($var, $string, self::TRIGGER_SUCCESS);
}
private function parseArray(array &$var, ContextInterface $c): AbstractValue
{
$size = \count($var);
$contents = [];
$parentRef = ReflectionReference::fromArrayElement([&$var], 0)->getId();
if (isset($this->array_ref_stack[$parentRef])) {
$array = new ArrayValue($c, $size, $contents);
$array->flags |= AbstractValue::FLAG_RECURSION;
return $this->applyPluginsComplete($var, $array, self::TRIGGER_RECURSION);
}
try {
$this->array_ref_stack[$parentRef] = true;
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
if ($size > 0 && $this->depth_limit && $cdepth >= $this->depth_limit) {
$array = new ArrayValue($c, $size, $contents);
$array->flags |= AbstractValue::FLAG_DEPTH_LIMIT;
return $this->applyPluginsComplete($var, $array, self::TRIGGER_DEPTH_LIMIT);
}
foreach ($var as $key => $_) {
$child = new ArrayContext($key);
$child->depth = $cdepth + 1;
$child->reference = null !== ReflectionReference::fromArrayElement($var, $key);
if (null !== $ap) {
$child->access_path = $ap.'['.\var_export($key, true).']';
}
$contents[$key] = $this->parse($var[$key], $child);
}
$array = new ArrayValue($c, $size, $contents);
if ($contents) {
$array->addRepresentation(new ContainerRepresentation('Contents', $contents, null, true));
}
return $this->applyPluginsComplete($var, $array, self::TRIGGER_SUCCESS);
} finally {
unset($this->array_ref_stack[$parentRef]);
}
}
/**
* @psalm-return ReflectionProperty[]
*/
private function getPropsOrdered(ReflectionClass $r): array
{
if ($parent = $r->getParentClass()) {
$props = self::getPropsOrdered($parent);
} else {
$props = [];
}
foreach ($r->getProperties() as $prop) {
if ($prop->isStatic()) {
continue;
}
if ($prop->isPrivate()) {
$props[] = $prop;
} else {
$props[$prop->name] = $prop;
}
}
return $props;
}
/**
* @codeCoverageIgnore
*
* @psalm-return ReflectionProperty[]
*/
private function getPropsOrderedOld(ReflectionClass $r): array
{
$props = [];
foreach ($r->getProperties() as $prop) {
if ($prop->isStatic()) {
continue;
}
$props[] = $prop;
}
while ($r = $r->getParentClass()) {
foreach ($r->getProperties(ReflectionProperty::IS_PRIVATE) as $prop) {
if ($prop->isStatic()) {
continue;
}
$props[] = $prop;
}
}
return $props;
}
private function parseObject(object &$var, ContextInterface $c): AbstractValue
{
$hash = \spl_object_hash($var);
$classname = \get_class($var);
if (isset($this->object_hashes[$hash])) {
$object = new InstanceValue($c, $classname, $hash, \spl_object_id($var));
$object->flags |= AbstractValue::FLAG_RECURSION;
return $this->applyPluginsComplete($var, $object, self::TRIGGER_RECURSION);
}
try {
$this->object_hashes[$hash] = true;
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
if ($this->depth_limit && $cdepth >= $this->depth_limit) {
$object = new InstanceValue($c, $classname, $hash, \spl_object_id($var));
$object->flags |= AbstractValue::FLAG_DEPTH_LIMIT;
return $this->applyPluginsComplete($var, $object, self::TRIGGER_DEPTH_LIMIT);
}
if (KINT_PHP81) {
$props = $this->getPropsOrdered(new ReflectionObject($var));
} else {
$props = $this->getPropsOrderedOld(new ReflectionObject($var)); // @codeCoverageIgnore
}
$values = (array) $var;
$properties = [];
foreach ($props as $rprop) {
$rprop->setAccessible(true);
$name = $rprop->getName();
// Casting object to array:
// private properties show in the form "\0$owner_class_name\0$property_name";
// protected properties show in the form "\0*\0$property_name";
// public properties show in the form "$property_name";
// http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
$key = $name;
if ($rprop->isProtected()) {
$key = "\0*\0".$name;
} elseif ($rprop->isPrivate()) {
$key = "\0".$rprop->getDeclaringClass()->getName()."\0".$name;
}
$initialized = \array_key_exists($key, $values);
if ($key === (string) (int) $key) {
$key = (int) $key;
}
if ($rprop->isDefault()) {
$child = new PropertyContext(
$name,
$rprop->getDeclaringClass()->getName(),
ClassDeclaredContext::ACCESS_PUBLIC
);
$child->readonly = KINT_PHP81 && $rprop->isReadOnly();
if ($rprop->isProtected()) {
$child->access = ClassDeclaredContext::ACCESS_PROTECTED;
} elseif ($rprop->isPrivate()) {
$child->access = ClassDeclaredContext::ACCESS_PRIVATE;
}
if (KINT_PHP84) {
if ($rprop->isProtectedSet()) {
$child->access_set = ClassDeclaredContext::ACCESS_PROTECTED;
} elseif ($rprop->isPrivateSet()) {
$child->access_set = ClassDeclaredContext::ACCESS_PRIVATE;
}
$hooks = $rprop->getHooks();
if (isset($hooks['get'])) {
$child->hooks |= PropertyContext::HOOK_GET;
if ($hooks['get']->returnsReference()) {
$child->hooks |= PropertyContext::HOOK_GET_REF;
}
}
if (isset($hooks['set'])) {
$child->hooks |= PropertyContext::HOOK_SET;
$child->hook_set_type = (string) $rprop->getSettableType();
if ($child->hook_set_type !== (string) $rprop->getType()) {
$child->hooks |= PropertyContext::HOOK_SET_TYPE;
} elseif ('' === $child->hook_set_type) {
$child->hook_set_type = null;
}
}
}
} else {
$child = new ClassOwnedContext($name, $rprop->getDeclaringClass()->getName());
}
$child->reference = $initialized && null !== ReflectionReference::fromArrayElement($values, $key);
$child->depth = $cdepth + 1;
if (null !== $ap && $child->isAccessible($this->caller_class)) {
/** @psalm-var string $child->name */
if (Utils::isValidPhpName($child->name)) {
$child->access_path = $ap.'->'.$child->name;
} else {
$child->access_path = $ap.'->{'.\var_export($child->name, true).'}';
}
}
if (KINT_PHP84 && $rprop->isVirtual()) {
$properties[] = new VirtualValue($child);
} elseif (!$initialized) {
$properties[] = new UninitializedValue($child);
} else {
$properties[] = $this->parse($values[$key], $child);
}
}
$object = new InstanceValue($c, $classname, $hash, \spl_object_id($var));
if ($props) {
$object->setChildren($properties);
}
if ($properties) {
$object->addRepresentation(new ContainerRepresentation('Properties', $properties));
}
return $this->applyPluginsComplete($var, $object, self::TRIGGER_SUCCESS);
} finally {
unset($this->object_hashes[$hash]);
}
}
/**
* @psalm-param resource $var
*/
private function parseResource(&$var, ContextInterface $c): AbstractValue
{
$resource = new ResourceValue($c, \get_resource_type($var));
$resource = $this->applyPluginsComplete($var, $resource, self::TRIGGER_SUCCESS);
return $resource;
}
/**
* @psalm-param mixed $var
*/
private function parseResourceClosed(&$var, ContextInterface $c): AbstractValue
{
$v = new ClosedResourceValue($c);
$v = $this->applyPluginsComplete($var, $v, self::TRIGGER_SUCCESS);
return $v;
}
/**
* Catch-all for any unexpectedgettype.
*
* This should never happen.
*
* @codeCoverageIgnore
*
* @psalm-param mixed $var
*/
private function parseUnknown(&$var, ContextInterface $c): AbstractValue
{
$v = new UnknownValue($c);
$v = $this->applyPluginsComplete($var, $v, self::TRIGGER_SUCCESS);
return $v;
}
/**
* Applies plugins for a yet-unparsed value.
*
* @param mixed &$var The input variable
*/
private function applyPluginsBegin(&$var, ContextInterface $c, string $type): ?AbstractValue
{
$plugins = $this->plugins[$type][self::TRIGGER_BEGIN] ?? [];
foreach ($plugins as $plugin) {
try {
if ($v = $plugin->parseBegin($var, $c)) {
return $v;
}
} catch (Throwable $e) {
\trigger_error(
Utils::errorSanitizeString(\get_class($e)).' was thrown in '.$e->getFile().' on line '.$e->getLine().' while executing '.Utils::errorSanitizeString(\get_class($plugin)).'->parseBegin. Error message: '.Utils::errorSanitizeString($e->getMessage()),
E_USER_WARNING
);
}
}
return null;
}
/**
* Applies plugins for a parsed AbstractValue.
*
* @param mixed &$var The input variable
*/
private function applyPluginsComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
$plugins = $this->plugins[$v->getType()][$trigger] ?? [];
foreach ($plugins as $plugin) {
try {
$v = $plugin->parseComplete($var, $v, $trigger);
} catch (Throwable $e) {
\trigger_error(
Utils::errorSanitizeString(\get_class($e)).' was thrown in '.$e->getFile().' on line '.$e->getLine().' while executing '.Utils::errorSanitizeString(\get_class($plugin)).'->parseComplete. Error message: '.Utils::errorSanitizeString($e->getMessage()),
E_USER_WARNING
);
}
}
return $v;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ContextInterface;
interface PluginBeginInterface extends PluginInterface
{
/**
* @psalm-param mixed &$var
*/
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue;
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
/**
* @psalm-import-type ParserTrigger from Parser
*/
interface PluginCompleteInterface extends PluginInterface
{
/**
* @psalm-param mixed &$var
* @psalm-param ParserTrigger $trigger
*/
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue;
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
/**
* @psalm-import-type ParserTrigger from Parser
*/
interface PluginInterface
{
public function setParser(Parser $p): void;
public function getTypes(): array;
/**
* @psalm-return ParserTrigger
*/
public function getTriggers(): int;
}
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\FixedWidthValue;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ProfileRepresentation;
/** @psalm-api */
class ProfilePlugin extends AbstractPlugin implements PluginBeginInterface, PluginCompleteInterface
{
protected array $instance_counts = [];
protected array $instance_complexity = [];
protected array $instance_count_stack = [];
protected array $class_complexity = [];
protected array $class_count_stack = [];
public function getTypes(): array
{
return ['string', 'object', 'array', 'integer', 'double', 'resource'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_BEGIN | Parser::TRIGGER_COMPLETE;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
if (0 === $c->getDepth()) {
$this->instance_counts = [];
$this->instance_complexity = [];
$this->instance_count_stack = [];
$this->class_complexity = [];
$this->class_count_stack = [];
}
if (\is_object($var)) {
$hash = \spl_object_hash($var);
$this->instance_counts[$hash] ??= 0;
$this->instance_complexity[$hash] ??= 0;
$this->instance_count_stack[$hash] ??= 0;
if (0 === $this->instance_count_stack[$hash]) {
foreach (\class_parents($var) as $class) {
$this->class_count_stack[$class] ??= 0;
++$this->class_count_stack[$class];
}
foreach (\class_implements($var) as $iface) {
$this->class_count_stack[$iface] ??= 0;
++$this->class_count_stack[$iface];
}
}
++$this->instance_count_stack[$hash];
}
return null;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if ($v instanceof InstanceValue) {
--$this->instance_count_stack[$v->getSplObjectHash()];
if (0 === $this->instance_count_stack[$v->getSplObjectHash()]) {
foreach (\class_parents($var) as $class) {
--$this->class_count_stack[$class];
}
foreach (\class_implements($var) as $iface) {
--$this->class_count_stack[$iface];
}
}
}
// Don't check subs if we're in recursion or array limit
if (~$trigger & Parser::TRIGGER_SUCCESS) {
return $v;
}
$sub_complexity = 1;
foreach ($v->getRepresentations() as $rep) {
if ($rep instanceof ContainerRepresentation) {
foreach ($rep->getContents() as $value) {
$profile = $value->getRepresentation('profiling');
$sub_complexity += $profile instanceof ProfileRepresentation ? $profile->complexity : 1;
}
} else {
++$sub_complexity;
}
}
if ($v instanceof InstanceValue) {
++$this->instance_counts[$v->getSplObjectHash()];
if (0 === $this->instance_count_stack[$v->getSplObjectHash()]) {
$this->instance_complexity[$v->getSplObjectHash()] += $sub_complexity;
$this->class_complexity[$v->getClassName()] ??= 0;
$this->class_complexity[$v->getClassName()] += $sub_complexity;
foreach (\class_parents($var) as $class) {
$this->class_complexity[$class] ??= 0;
if (0 === $this->class_count_stack[$class]) {
$this->class_complexity[$class] += $sub_complexity;
}
}
foreach (\class_implements($var) as $iface) {
$this->class_complexity[$iface] ??= 0;
if (0 === $this->class_count_stack[$iface]) {
$this->class_complexity[$iface] += $sub_complexity;
}
}
}
}
if (0 === $v->getContext()->getDepth()) {
$contents = [];
\arsort($this->class_complexity);
foreach ($this->class_complexity as $name => $complexity) {
$contents[] = new FixedWidthValue(new BaseContext($name), $complexity);
}
if ($contents) {
$v->addRepresentation(new ContainerRepresentation('Class complexity', $contents), 0);
}
}
$rep = new ProfileRepresentation($sub_complexity);
/** @psalm-suppress UnsupportedReferenceUsage */
if ($v instanceof InstanceValue) {
$rep->instance_counts = &$this->instance_counts[$v->getSplObjectHash()];
$rep->instance_complexity = &$this->instance_complexity[$v->getSplObjectHash()];
}
$v->addRepresentation($rep, 0);
return $v;
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ContextInterface;
/**
* @psalm-import-type ParserTrigger from Parser
*
* @psalm-api
*/
class ProxyPlugin implements PluginBeginInterface, PluginCompleteInterface
{
protected array $types;
/** @psalm-var ParserTrigger */
protected int $triggers;
/** @psalm-var callable */
protected $callback;
private ?Parser $parser = null;
/**
* @psalm-param ParserTrigger $triggers
* @psalm-param callable $callback
*/
public function __construct(array $types, int $triggers, $callback)
{
$this->types = $types;
$this->triggers = $triggers;
$this->callback = $callback;
}
public function setParser(Parser $p): void
{
$this->parser = $p;
}
public function getTypes(): array
{
return $this->types;
}
public function getTriggers(): int
{
return $this->triggers;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
return \call_user_func_array($this->callback, [
&$var,
$c,
Parser::TRIGGER_BEGIN,
$this->parser,
]);
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
return \call_user_func_array($this->callback, [
&$var,
$v,
$trigger,
$this->parser,
]);
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\UninitializedValue;
/** @psalm-api */
class SerializePlugin extends AbstractPlugin implements PluginCompleteInterface
{
/**
* Disables automatic unserialization on arrays and objects.
*
* As the PHP manual notes:
*
* > Unserialization can result in code being loaded and executed due to
* > object instantiation and autoloading, and a malicious user may be able
* > to exploit this.
*
* The natural way to stop that from happening is to just refuse to unserialize
* stuff by default. Which is what we're doing for anything that's not scalar.
*/
public static bool $safe_mode = true;
/**
* @psalm-var bool|class-string[]
*/
public static $allowed_classes = false;
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
$trimmed = \rtrim($var);
if ('N;' !== $trimmed && !\preg_match('/^(?:[COabis]:\\d+[:;]|d:\\d+(?:\\.\\d+);)/', $trimmed)) {
return $v;
}
$options = ['allowed_classes' => self::$allowed_classes];
$c = $v->getContext();
$base = new BaseContext('unserialize('.$c->getName().')');
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'unserialize('.$ap;
if (true === self::$allowed_classes) {
$base->access_path .= ')';
} else {
$base->access_path .= ', '.\var_export($options, true).')';
}
}
if (self::$safe_mode && \in_array($trimmed[0], ['C', 'O', 'a'], true)) {
$data = new UninitializedValue($base);
$data->flags |= AbstractValue::FLAG_BLACKLIST;
} else {
// Suppress warnings on unserializeable variable
$data = @\unserialize($trimmed, $options);
if (false === $data && 'b:0;' !== \substr($trimmed, 0, 4)) {
return $v;
}
$data = $this->getParser()->parse($data, $base);
}
$data->flags |= AbstractValue::FLAG_GENERATED;
$v->addRepresentation(new ValueRepresentation('Serialized', $data), 0);
return $v;
}
}
+295
View File
@@ -0,0 +1,295 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ArrayContext;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ClassOwnedContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\SimpleXMLElementValue;
use SimpleXMLElement;
class SimpleXMLElementPlugin extends AbstractPlugin implements PluginBeginInterface
{
/**
* Show all properties and methods.
*/
public static bool $verbose = false;
protected ClassMethodsPlugin $methods_plugin;
public function __construct(Parser $parser)
{
parent::__construct($parser);
$this->methods_plugin = new ClassMethodsPlugin($parser);
}
public function setParser(Parser $p): void
{
parent::setParser($p);
$this->methods_plugin->setParser($p);
}
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
// SimpleXMLElement is a weirdo. No recursion (Or rather everything is
// recursion) and depth limit will have to be handled manually anyway.
return Parser::TRIGGER_BEGIN;
}
public function parseBegin(&$var, ContextInterface $c): ?AbstractValue
{
if (!$var instanceof SimpleXMLElement) {
return null;
}
return $this->parseElement($var, $c);
}
protected function parseElement(SimpleXMLElement &$var, ContextInterface $c): SimpleXMLElementValue
{
$parser = $this->getParser();
$pdepth = $parser->getDepthLimit();
$cdepth = $c->getDepth();
$depthlimit = $pdepth && $cdepth >= $pdepth;
$has_children = self::hasChildElements($var);
if ($depthlimit && $has_children) {
$x = new SimpleXMLElementValue($c, $var, [], null);
$x->flags |= AbstractValue::FLAG_DEPTH_LIMIT;
return $x;
}
$children = $this->getChildren($c, $var);
$attributes = $this->getAttributes($c, $var);
$toString = (string) $var;
$string_body = !$has_children && \strlen($toString);
$x = new SimpleXMLElementValue($c, $var, $children, \strlen($toString) ? $toString : null);
if (self::$verbose) {
$x = $this->methods_plugin->parseComplete($var, $x, Parser::TRIGGER_SUCCESS);
}
if ($attributes) {
$x->addRepresentation(new ContainerRepresentation('Attributes', $attributes), 0);
}
if ($string_body) {
$base = new BaseContext('(string) '.$c->getName());
$base->depth = $cdepth + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = '(string) '.$ap;
}
$toString = $parser->parse($toString, $base);
$x->addRepresentation(new ValueRepresentation('toString', $toString, null, true), 0);
}
if ($children) {
$x->addRepresentation(new ContainerRepresentation('Children', $children), 0);
}
return $x;
}
/** @psalm-return list<AbstractValue> */
protected function getAttributes(ContextInterface $c, SimpleXMLElement $var): array
{
$parser = $this->getParser();
$namespaces = \array_merge(['' => null], $var->getDocNamespaces());
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
$contents = [];
foreach ($namespaces as $nsAlias => $_) {
if ((bool) $nsAttribs = $var->attributes($nsAlias, true)) {
foreach ($nsAttribs as $name => $attrib) {
$obj = new ArrayContext($name);
$obj->depth = $cdepth + 1;
if (null !== $ap) {
$obj->access_path = '(string) '.$ap;
if ('' !== $nsAlias) {
$obj->access_path .= '->attributes('.\var_export($nsAlias, true).', true)';
}
$obj->access_path .= '['.\var_export($name, true).']';
}
if ('' !== $nsAlias) {
$obj->name = $nsAlias.':'.$obj->name;
}
$string = (string) $attrib;
$attribute = $parser->parse($string, $obj);
$contents[] = $attribute;
}
}
}
return $contents;
}
/**
* Alright kids, let's learn about SimpleXMLElement::children!
* children can take a namespace url or alias and provide a list of
* child nodes. This is great since just accessing the members through
* properties doesn't work on SimpleXMLElement when they have a
* namespace at all!
*
* Unfortunately SimpleXML decided to go the retarded route of
* categorizing elements by their tag name rather than by their local
* name (to put it in Dom terms) so if you have something like this:
*
* <root xmlns:localhost="http://localhost/">
* <tag />
* <tag xmlns="http://localhost/" />
* <localhost:tag />
* </root>
*
* * children(null) will get the first 2 results
* * children('', true) will get the first 2 results
* * children('http://localhost/') will get the last 2 results
* * children('localhost', true) will get the last result
*
* So let's just give up and stick to aliases because fuck that mess!
*
* @psalm-return list<SimpleXMLElementValue>
*/
protected function getChildren(ContextInterface $c, SimpleXMLElement $var): array
{
$namespaces = \array_merge(['' => null], $var->getDocNamespaces());
$cdepth = $c->getDepth();
$ap = $c->getAccessPath();
$contents = [];
foreach ($namespaces as $nsAlias => $_) {
if ((bool) $nsChildren = $var->children($nsAlias, true)) {
$nsap = [];
foreach ($nsChildren as $name => $child) {
$base = new ClassOwnedContext((string) $name, SimpleXMLElement::class);
$base->depth = $cdepth + 1;
if ('' !== $nsAlias) {
$base->name = $nsAlias.':'.$name;
}
if (null !== $ap) {
if ('' === $nsAlias) {
$base->access_path = $ap.'->';
} else {
$base->access_path = $ap.'->children('.\var_export($nsAlias, true).', true)->';
}
if (Utils::isValidPhpName((string) $name)) {
$base->access_path .= (string) $name;
} else {
$base->access_path .= '{'.\var_export((string) $name, true).'}';
}
if (isset($nsap[$base->access_path])) {
++$nsap[$base->access_path];
$base->access_path .= '['.$nsap[$base->access_path].']';
} else {
$nsap[$base->access_path] = 0;
}
}
$v = $this->parseElement($child, $base);
$v->flags |= AbstractValue::FLAG_GENERATED;
$contents[] = $v;
}
}
}
return $contents;
}
/**
* More SimpleXMLElement bullshit.
*
* If we want to know if the element contains text we can cast to string.
* Except if it contains text mixed with elements simplexml for some stupid
* reason decides to concatenate the text from between those elements
* rather than all the text in the hierarchy...
*
* So we have NO way of getting text nodes between elements, but we can
* still tell if we have elements right? If we have elements we assume it's
* not a string and call it a day!
*
* Well if you cast the element to an array attributes will be on it so
* you'd have to remove that key, and if it's a string it'll also have the
* 0 index used for the string contents too...
*
* Wait, can we use the 0 index to tell if it's a string? Nope! CDATA
* doesn't show up AT ALL when casting to anything but string, and we'll
* still get those concatenated strings of mostly whitespace if we just do
* (string) and check the length.
*
* Luckily, I found the only way to do this reliably is through children().
* We still have to loop through all the namespaces and see if there's a
* match but then we have the problem of the attributes showing up again...
*
* Or at least that's what var_dump says. And when we cast the result to
* bool it's true too... But if we cast it to array then it's suddenly empty!
*
* Long story short the function below is the only way to reliably check if
* a SimpleXMLElement has children
*/
protected static function hasChildElements(SimpleXMLElement $var): bool
{
$namespaces = \array_merge(['' => null], $var->getDocNamespaces());
foreach ($namespaces as $nsAlias => $_) {
if ((array) $var->children($nsAlias, true)) {
return true;
}
}
return false;
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\SplFileInfoRepresentation;
use Kint\Value\SplFileInfoValue;
use SplFileInfo;
use SplFileObject;
class SplFileInfoPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
// SplFileObject throws exceptions in normal use in places SplFileInfo doesn't
if (!$var instanceof SplFileInfo || $var instanceof SplFileObject) {
return $v;
}
if (!$v instanceof InstanceValue) {
return $v;
}
$out = new SplFileInfoValue($v->getContext(), $var);
$out->setChildren($v->getChildren());
$out->flags = $v->flags;
$out->addRepresentation(new SplFileInfoRepresentation(clone $var));
$out->appendRepresentations($v->getRepresentations());
return $out;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\ArrayContext;
use Kint\Value\ResourceValue;
use Kint\Value\StreamValue;
use TypeError;
class StreamPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['resource'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof ResourceValue) {
return $v;
}
// Doublecheck that the resource is open before we get the metadata
if (!\is_resource($var)) {
return $v;
}
try {
$meta = \stream_get_meta_data($var);
} catch (TypeError $e) {
return $v;
}
$c = $v->getContext();
$parser = $this->getParser();
$parsed_meta = [];
foreach ($meta as $key => $val) {
$base = new ArrayContext($key);
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'stream_get_meta_data('.$ap.')['.\var_export($key, true).']';
}
$val = $parser->parse($val, $base);
$val->flags |= AbstractValue::FLAG_GENERATED;
$parsed_meta[] = $val;
}
$stream = new StreamValue($c, $parsed_meta, $meta['uri'] ?? null);
$stream->flags = $v->flags;
$stream->appendRepresentations($v->getRepresentations());
return $stream;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Representation\TableRepresentation;
// Note: Interaction with ArrayLimitPlugin:
// Any array limited children will be shown in tables identically to
// non-array-limited children since the table only shows that it is an array
// and it's size anyway. Because ArrayLimitPlugin halts the parse on finding
// a limit all other plugins including this one are stopped, so you cannot get
// a tabular representation of an array that is longer than the limit.
class TablePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static int $max_width = 300;
public static int $min_width = 2;
public function getTypes(): array
{
return ['array'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof ArrayValue) {
return $v;
}
if (\count($var) < 2) {
return $v;
}
// Ensure this is an array of arrays and that all child arrays have the
// same keys. We don't care about their children - if there's another
// "table" inside we'll just make another one down the value tab
$keys = null;
foreach ($var as $elem) {
if (!\is_array($elem)) {
return $v;
}
if (null === $keys) {
if (\count($elem) < self::$min_width || \count($elem) > self::$max_width) {
return $v;
}
$keys = \array_keys($elem);
} elseif (\array_keys($elem) !== $keys) {
return $v;
}
}
$children = $v->getContents();
if (!$children) {
return $v;
}
// Ensure none of the child arrays are recursion or depth limit. We
// don't care if their children are since they are the table cells
foreach ($children as $childarray) {
if (!$childarray instanceof ArrayValue || empty($childarray->getContents())) {
return $v;
}
}
$v->addRepresentation(new TableRepresentation($children), 0);
return $v;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\InstanceValue;
use Kint\Value\Representation\SourceRepresentation;
use Kint\Value\ThrowableValue;
use RuntimeException;
use Throwable;
class ThrowablePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$var instanceof Throwable || !$v instanceof InstanceValue) {
return $v;
}
$throw = new ThrowableValue($v->getContext(), $var);
$throw->setChildren($v->getChildren());
$throw->flags = $v->flags;
$throw->appendRepresentations($v->getRepresentations());
try {
$throw->addRepresentation(new SourceRepresentation($var->getFile(), $var->getLine(), null, true), 0);
} catch (RuntimeException $e) {
}
return $throw;
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use DateTimeImmutable;
use Kint\Value\AbstractValue;
use Kint\Value\FixedWidthValue;
use Kint\Value\Representation\StringRepresentation;
use Kint\Value\StringValue;
class TimestampPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static array $blacklist = [
2147483648,
2147483647,
1073741824,
1073741823,
];
public function getTypes(): array
{
return ['string', 'integer'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (\is_string($var) && !\ctype_digit($var)) {
return $v;
}
if ($var < 0) {
return $v;
}
if (\in_array($var, self::$blacklist, true)) {
return $v;
}
$len = \strlen((string) $var);
// Guess for anything between March 1973 and November 2286
if ($len < 9 || $len > 10) {
return $v;
}
if (!$v instanceof StringValue && !$v instanceof FixedWidthValue) {
return $v;
}
if (!$dt = DateTimeImmutable::createFromFormat('U', (string) $var)) {
return $v;
}
$v->removeRepresentation('contents');
$v->addRepresentation(new StringRepresentation('Timestamp', $dt->format('c'), null, true));
return $v;
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Representation\ValueRepresentation;
use ReflectionClass;
use SimpleXMLElement;
use SplFileInfo;
use Throwable;
class ToStringPlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static array $blacklist = [
SimpleXMLElement::class,
SplFileInfo::class,
];
public function getTypes(): array
{
return ['object'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
$reflection = new ReflectionClass($var);
if (!$reflection->hasMethod('__toString')) {
return $v;
}
foreach (self::$blacklist as $class) {
if ($var instanceof $class) {
return $v;
}
}
try {
$string = (string) $var;
} catch (Throwable $t) {
return $v;
}
$c = $v->getContext();
$base = new BaseContext($c->getName());
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = '(string) '.$ap;
}
$string = $this->getParser()->parse($string, $base);
$v->addRepresentation(new ValueRepresentation('toString', $string));
return $v;
}
}
+156
View File
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Kint\Utils;
use Kint\Value\AbstractValue;
use Kint\Value\ArrayValue;
use Kint\Value\Context\ArrayContext;
use Kint\Value\Representation\ContainerRepresentation;
use Kint\Value\Representation\SourceRepresentation;
use Kint\Value\Representation\ValueRepresentation;
use Kint\Value\TraceFrameValue;
use Kint\Value\TraceValue;
use RuntimeException;
/**
* @psalm-import-type TraceFrame from TraceFrameValue
*/
class TracePlugin extends AbstractPlugin implements PluginCompleteInterface
{
public static array $blacklist = ['spl_autoload_call'];
public static array $path_blacklist = [];
public function getTypes(): array
{
return ['array'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if (!$v instanceof ArrayValue) {
return $v;
}
// Shallow copy so we don't have to worry about touching var
$trace = $var;
if (!Utils::isTrace($trace)) {
return $v;
}
$pdepth = $this->getParser()->getDepthLimit();
$c = $v->getContext();
// We need at least 2 levels in order to get $trace[n]['args']
if ($pdepth && $c->getDepth() + 2 >= $pdepth) {
return $v;
}
$contents = $v->getContents();
self::$blacklist = Utils::normalizeAliases(self::$blacklist);
$path_blacklist = self::normalizePaths(self::$path_blacklist);
$frames = [];
foreach ($contents as $frame) {
if (!$frame instanceof ArrayValue || !$frame->getContext() instanceof ArrayContext) {
continue;
}
$index = $frame->getContext()->getName();
if (!isset($trace[$index]) || Utils::traceFrameIsListed($trace[$index], self::$blacklist)) {
continue;
}
if (isset($trace[$index]['file']) && false !== ($realfile = \realpath($trace[$index]['file']))) {
foreach ($path_blacklist as $path) {
if (0 === \strpos($realfile, $path)) {
continue 2;
}
}
}
$frame = new TraceFrameValue($frame, $trace[$index]);
if (null !== ($file = $frame->getFile()) && null !== ($line = $frame->getLine())) {
try {
$frame->addRepresentation(new SourceRepresentation($file, $line));
} catch (RuntimeException $e) {
}
}
if ($args = $frame->getArgs()) {
$frame->addRepresentation(new ContainerRepresentation('Arguments', $args));
}
if ($obj = $frame->getObject()) {
$frame->addRepresentation(
new ValueRepresentation(
'Callee object ['.$obj->getClassName().']',
$obj,
'callee_object'
)
);
}
$frames[$index] = $frame;
}
$traceobj = new TraceValue($c, \count($frames), $frames);
if ($frames) {
$traceobj->addRepresentation(new ContainerRepresentation('Contents', $frames, null, true));
}
return $traceobj;
}
protected static function normalizePaths(array $paths): array
{
$normalized = [];
foreach ($paths as $path) {
$realpath = \realpath($path);
if (\is_dir($realpath)) {
$realpath .= DIRECTORY_SEPARATOR;
}
$normalized[] = $realpath;
}
return $normalized;
}
}
+179
View File
@@ -0,0 +1,179 @@
<?php
declare(strict_types=1);
/*
* The MIT License (MIT)
*
* Copyright (c) 2013 Jonathan Vollebregt (jnvsor@gmail.com), Rokas Šleinius (raveren@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Kint\Parser;
use Dom\Node;
use Dom\XMLDocument;
use DOMDocument;
use DOMException;
use DOMNode;
use InvalidArgumentException;
use Kint\Value\AbstractValue;
use Kint\Value\Context\BaseContext;
use Kint\Value\Context\ContextInterface;
use Kint\Value\Representation\ValueRepresentation;
use Throwable;
class XmlPlugin extends AbstractPlugin implements PluginCompleteInterface
{
/**
* Which method to parse the variable with.
*
* DOMDocument provides more information including the text between nodes,
* however it's memory usage is very high and it takes longer to parse and
* render. Plus it's a pain to work with. So SimpleXML is the default.
*
* @psalm-var 'SimpleXML'|'DOMDocument'|'XMLDocument'
*/
public static string $parse_method = 'SimpleXML';
public function getTypes(): array
{
return ['string'];
}
public function getTriggers(): int
{
return Parser::TRIGGER_SUCCESS;
}
public function parseComplete(&$var, AbstractValue $v, int $trigger): AbstractValue
{
if ('<?xml' !== \substr($var, 0, 5)) {
return $v;
}
if (!\method_exists($this, 'xmlTo'.self::$parse_method)) {
return $v;
}
$c = $v->getContext();
$out = \call_user_func([$this, 'xmlTo'.self::$parse_method], $var, $c);
if (null === $out) {
return $v;
}
$out->flags |= AbstractValue::FLAG_GENERATED;
$v->addRepresentation(new ValueRepresentation('XML', $out), 0);
return $v;
}
/** @psalm-suppress PossiblyUnusedMethod */
protected function xmlToSimpleXML(string $var, ContextInterface $c): ?AbstractValue
{
$errors = \libxml_use_internal_errors(true);
try {
$xml = \simplexml_load_string($var);
if (!(bool) $xml) {
throw new InvalidArgumentException('Bad XML parse in XmlPlugin::xmlToSimpleXML');
}
} catch (Throwable $t) {
return null;
} finally {
\libxml_use_internal_errors($errors);
\libxml_clear_errors();
}
$base = new BaseContext($xml->getName());
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = 'simplexml_load_string('.$ap.')';
}
return $this->getParser()->parse($xml, $base);
}
/**
* Get the DOMDocument info.
*
* If it errors loading then we wouldn't have gotten this far in the first place.
*
* @psalm-suppress PossiblyUnusedMethod
*
* @psalm-param non-empty-string $var
*/
protected function xmlToDOMDocument(string $var, ContextInterface $c): ?AbstractValue
{
try {
$xml = new DOMDocument();
$check = $xml->loadXML($var, LIBXML_NOWARNING | LIBXML_NOERROR);
if (false === $check) {
throw new InvalidArgumentException('Bad XML parse in XmlPlugin::xmlToDOMDocument');
}
} catch (Throwable $t) {
return null;
}
$xml = $xml->firstChild;
/**
* @psalm-var DOMNode $xml
* Psalm bug #11120
*/
$base = new BaseContext($xml->nodeName);
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = '(function($s){$x = new \\DomDocument(); $x->loadXML($s); return $x;})('.$ap.')->firstChild';
}
return $this->getParser()->parse($xml, $base);
}
/** @psalm-suppress PossiblyUnusedMethod */
protected function xmlToXMLDocument(string $var, ContextInterface $c): ?AbstractValue
{
if (!KINT_PHP84) {
return null; // @codeCoverageIgnore
}
try {
$xml = XMLDocument::createFromString($var, LIBXML_NOWARNING | LIBXML_NOERROR);
} catch (DOMException $e) {
return null;
}
$xml = $xml->firstChild;
/**
* @psalm-var Node $xml
* Psalm bug #11120
*/
$base = new BaseContext($xml->nodeName);
$base->depth = $c->getDepth() + 1;
if (null !== ($ap = $c->getAccessPath())) {
$base->access_path = '\\Dom\\XMLDocument::createFromString('.$ap.')->firstChild';
}
return $this->getParser()->parse($xml, $base);
}
}