code
stringlengths
31
1.39M
docstring
stringlengths
23
16.8k
func_name
stringlengths
1
126
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
166
url
stringlengths
50
220
license
stringclasses
7 values
public static function ctype_print($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); }
Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. @see https://php.net/ctype-print @param mixed $text @return bool
ctype_print
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
public static function ctype_punct($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); }
Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. @see https://php.net/ctype-punct @param mixed $text @return bool
ctype_punct
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
public static function ctype_space($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); }
Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. @see https://php.net/ctype-space @param mixed $text @return bool
ctype_space
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
public static function ctype_upper($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); }
Returns TRUE if every character in text is an uppercase letter. @see https://php.net/ctype-upper @param mixed $text @return bool
ctype_upper
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
public static function ctype_xdigit($text) { $text = self::convert_int_to_char_for_ctype($text, __FUNCTION__); return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); }
Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. @see https://php.net/ctype-xdigit @param mixed $text @return bool
ctype_xdigit
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
private static function convert_int_to_char_for_ctype($int, $function) { if (!\is_int($int)) { return $int; } if ($int < -128 || $int > 255) { return (string) $int; } if (\PHP_VERSION_ID >= 80100) { @trigger_error($function.'(): Argument of type int will be interpreted as string in the future', \E_USER_DEPRECATED); } if ($int < 0) { $int += 256; } return \chr($int); }
Converts integers to their char versions according to normal ctype behaviour, if needed. If an integer between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. @param mixed $int @param string $function @return mixed
convert_int_to_char_for_ctype
php
deptrac/deptrac
vendor/symfony/polyfill-ctype/Ctype.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/polyfill-ctype/Ctype.php
MIT
public function __construct(public ?string $key = null, public ?string $type = null, public bool $nullable = \false, array|object $attributes = []) { $this->attributes = \is_array($attributes) ? $attributes : [$attributes]; }
@param string|null $key The key to use for the service @param class-string|null $type The service class @param bool $nullable Whether the service is optional @param object|object[] $attributes One or more dependency injection attributes to use
__construct
php
deptrac/deptrac
vendor/symfony/service-contracts/Attribute/SubscribedService.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/service-contracts/Attribute/SubscribedService.php
MIT
public static function unwrap(array $values) : array { foreach ($values as $k => $v) { if ($v instanceof self) { $values[$k] = $v->__toString(); } elseif (\is_array($v) && $values[$k] !== ($v = static::unwrap($v))) { $values[$k] = $v; } } return $values; }
Unwraps instances of AbstractString back to strings. @return string[]|array
unwrap
php
deptrac/deptrac
vendor/symfony/string/AbstractString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/AbstractString.php
MIT
public static function wrap(array $values) : array { $i = 0; $keys = null; foreach ($values as $k => $v) { if (\is_string($k) && '' !== $k && $k !== ($j = (string) new static($k))) { $keys ??= \array_keys($values); $keys[$i] = $j; } if (\is_string($v)) { $values[$k] = new static($v); } elseif (\is_array($v) && $values[$k] !== ($v = static::wrap($v))) { $values[$k] = $v; } ++$i; } return null !== $keys ? \array_combine($keys, $values) : $values; }
Wraps (and normalizes) strings in instances of AbstractString. @return static[]|array
wrap
php
deptrac/deptrac
vendor/symfony/string/AbstractString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/AbstractString.php
MIT
private function wcswidth(string $string) : int { $width = 0; foreach (\preg_split('//u', $string, -1, \PREG_SPLIT_NO_EMPTY) as $c) { $codePoint = \mb_ord($c, 'UTF-8'); if (0 === $codePoint || 0x34f === $codePoint || 0x200b <= $codePoint && 0x200f >= $codePoint || 0x2028 === $codePoint || 0x2029 === $codePoint || 0x202a <= $codePoint && 0x202e >= $codePoint || 0x2060 <= $codePoint && 0x2063 >= $codePoint) { continue; } // Non printable characters if (32 > $codePoint || 0x7f <= $codePoint && 0xa0 > $codePoint) { return -1; } self::$tableZero ??= (require __DIR__ . '/Resources/data/wcswidth_table_zero.php'); if ($codePoint >= self::$tableZero[0][0] && $codePoint <= self::$tableZero[$ubound = \count(self::$tableZero) - 1][1]) { $lbound = 0; while ($ubound >= $lbound) { $mid = \floor(($lbound + $ubound) / 2); if ($codePoint > self::$tableZero[$mid][1]) { $lbound = $mid + 1; } elseif ($codePoint < self::$tableZero[$mid][0]) { $ubound = $mid - 1; } else { continue 2; } } } self::$tableWide ??= (require __DIR__ . '/Resources/data/wcswidth_table_wide.php'); if ($codePoint >= self::$tableWide[0][0] && $codePoint <= self::$tableWide[$ubound = \count(self::$tableWide) - 1][1]) { $lbound = 0; while ($ubound >= $lbound) { $mid = \floor(($lbound + $ubound) / 2); if ($codePoint > self::$tableWide[$mid][1]) { $lbound = $mid + 1; } elseif ($codePoint < self::$tableWide[$mid][0]) { $ubound = $mid - 1; } else { $width += 2; continue 2; } } } ++$width; } return $width; }
Based on https://github.com/jquast/wcwidth, a Python implementation of https://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c.
wcswidth
php
deptrac/deptrac
vendor/symfony/string/AbstractUnicodeString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/AbstractUnicodeString.php
MIT
public static function fromCallable(callable|array $callback, mixed ...$arguments) : static { if (\is_array($callback) && !\is_callable($callback) && !(($callback[0] ?? null) instanceof \Closure || 2 < \count($callback))) { throw new \TypeError(\sprintf('Argument 1 passed to "%s()" must be a callable or a [Closure, method] lazy-callable, "%s" given.', __METHOD__, '[' . \implode(', ', \array_map('get_debug_type', $callback)) . ']')); } $lazyString = new static(); $lazyString->value = static function () use(&$callback, &$arguments) : string { static $value; if (null !== $arguments) { if (!\is_callable($callback)) { $callback[0] = $callback[0](); $callback[1] ??= '__invoke'; } $value = $callback(...$arguments); $callback = !\is_scalar($value) && !$value instanceof \Stringable ? self::getPrettyName($callback) : 'callable'; $arguments = null; } return $value ?? ''; }; return $lazyString; }
@param callable|array $callback A callable or a [Closure, method] lazy-callable
fromCallable
php
deptrac/deptrac
vendor/symfony/string/LazyString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/LazyString.php
MIT
public static final function isStringable(mixed $value) : bool { return \is_string($value) || $value instanceof \Stringable || \is_scalar($value); }
Tells whether the provided value can be cast to string.
isStringable
php
deptrac/deptrac
vendor/symfony/string/LazyString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/LazyString.php
MIT
public static final function resolve(\Stringable|string|int|float|bool $value) : string { return $value; }
Casts scalars and stringable objects to strings. @throws \TypeError When the provided value is not stringable
resolve
php
deptrac/deptrac
vendor/symfony/string/LazyString.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/LazyString.php
MIT
public function withEmoji(bool|string $emoji = \true) : static { if (\false !== $emoji && !\class_exists(EmojiTransliterator::class)) { throw new \LogicException(\sprintf('You cannot use the "%s()" method as the "symfony/intl" package is not installed. Try running "composer require symfony/intl".', __METHOD__)); } $new = clone $this; $new->emoji = $emoji; return $new; }
@param bool|string $emoji true will use the same locale, false will disable emoji, and a string to use a specific locale
withEmoji
php
deptrac/deptrac
vendor/symfony/string/Slugger/AsciiSlugger.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/string/Slugger/AsciiSlugger.php
MIT
public static function hydrate(object $instance, array $properties = [], array $scopedProperties = []) : object { if ($properties) { $class = $instance::class; $propertyScopes = InternalHydrator::$propertyScopes[$class] ??= InternalHydrator::getPropertyScopes($class); foreach ($properties as $name => &$value) { [$scope, $name, $readonlyScope] = $propertyScopes[$name] ?? [$class, $name, $class]; $scopedProperties[$readonlyScope ?? $scope][$name] =& $value; } unset($value); } foreach ($scopedProperties as $scope => $properties) { if ($properties) { (InternalHydrator::$simpleHydrators[$scope] ??= InternalHydrator::getSimpleHydrator($scope))($properties, $instance); } } return $instance; }
Sets the properties of an object, including private and protected ones. For example: // Sets the public or protected $object->propertyName property Hydrator::hydrate($object, ['propertyName' => $propertyValue]); // Sets a private property defined on its parent Bar class: Hydrator::hydrate($object, ["\0Bar\0privateBarProperty" => $propertyValue]); // Alternative way to set the private $object->privateBarProperty property Hydrator::hydrate($object, [], [ Bar::class => ['privateBarProperty' => $propertyValue], ]); Instances of ArrayObject, ArrayIterator and SplObjectStorage can be hydrated by using the special "\0" property name to define their internal value: // Hydrates an SplObjectStorage where $info1 is attached to $obj1, etc. Hydrator::hydrate($object, ["\0" => [$obj1, $info1, $obj2, $info2...]]); // Hydrates an ArrayObject populated with $inputArray Hydrator::hydrate($object, ["\0" => [$inputArray]]); @template T of object @param T $instance The object to hydrate @param array<string, mixed> $properties The properties to set on the instance @param array<class-string, array<string, mixed>> $scopedProperties The properties to set on the instance, keyed by their declaring class @return T
hydrate
php
deptrac/deptrac
vendor/symfony/var-exporter/Hydrator.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/Hydrator.php
MIT
public static function instantiate(string $class, array $properties = [], array $scopedProperties = []) : object { $reflector = Registry::$reflectors[$class] ??= Registry::getClassReflector($class); if (Registry::$cloneable[$class]) { $instance = clone Registry::$prototypes[$class]; } elseif (Registry::$instantiableWithoutConstructor[$class]) { $instance = $reflector->newInstanceWithoutConstructor(); } elseif (null === Registry::$prototypes[$class]) { throw new NotInstantiableTypeException($class); } elseif ($reflector->implementsInterface('Serializable') && !\method_exists($class, '__unserialize')) { $instance = \unserialize('C:' . \strlen($class) . ':"' . $class . '":0:{}'); } else { $instance = \unserialize('O:' . \strlen($class) . ':"' . $class . '":0:{}'); } return $properties || $scopedProperties ? Hydrator::hydrate($instance, $properties, $scopedProperties) : $instance; }
Creates an object and sets its properties without calling its constructor nor any other methods. @see Hydrator::hydrate() for examples @template T of object @param class-string<T> $class The class of the instance to create @param array<string, mixed> $properties The properties to set on the instance @param array<class-string, array<string, mixed>> $scopedProperties The properties to set on the instance, keyed by their declaring class @return T @throws ExceptionInterface When the instance cannot be created
instantiate
php
deptrac/deptrac
vendor/symfony/var-exporter/Instantiator.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/Instantiator.php
MIT
public static function createLazyGhost(\Closure|array $initializer, ?array $skippedProperties = null, ?object $instance = null) : static { if (\is_array($initializer)) { \DEPTRAC_INTERNAL\trigger_deprecation('symfony/var-exporter', '6.4', 'Per-property lazy-initializers are deprecated and won\'t be supported anymore in 7.0, use an object initializer instead.'); } $onlyProperties = null === $skippedProperties && \is_array($initializer) ? $initializer : null; if (self::class !== ($class = $instance ? $instance::class : static::class)) { $skippedProperties["\x00" . self::class . "\x00lazyObjectState"] = \true; } elseif (\defined($class . '::LAZY_OBJECT_PROPERTY_SCOPES')) { Hydrator::$propertyScopes[$class] ??= $class::LAZY_OBJECT_PROPERTY_SCOPES; } $instance ??= (Registry::$classReflectors[$class] ??= new \ReflectionClass($class))->newInstanceWithoutConstructor(); Registry::$defaultProperties[$class] ??= (array) $instance; $instance->lazyObjectState = new LazyObjectState($initializer, $skippedProperties ??= []); foreach (Registry::$classResetters[$class] ??= Registry::getClassResetters($class) as $reset) { $reset($instance, $skippedProperties, $onlyProperties); } return $instance; }
Creates a lazy-loading ghost instance. Skipped properties should be indexed by their array-cast identifier, see https://php.net/manual/language.types.array#language.types.array.casting @param (\Closure(static):void $initializer The closure should initialize the object it receives as argument @param array<string, true>|null $skippedProperties An array indexed by the properties to skip, a.k.a. the ones that the initializer doesn't initialize, if any @param static|null $instance
createLazyGhost
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyGhostTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyGhostTrait.php
MIT
#[Ignore] public function isLazyObjectInitialized(bool $partial = \false) : bool { if (!($state = $this->lazyObjectState ?? null)) { return \true; } if (!\is_array($state->initializer)) { return LazyObjectState::STATUS_INITIALIZED_FULL === $state->status; } $class = $this::class; $properties = (array) $this; if ($partial) { return (bool) \array_intersect_key($state->initializer, $properties); } $propertyScopes = Hydrator::$propertyScopes[$class] ??= Hydrator::getPropertyScopes($class); foreach ($state->initializer as $key => $initializer) { if (!\array_key_exists($key, $properties) && isset($propertyScopes[$key])) { return \false; } } return \true; }
Returns whether the object is initialized. @param $partial Whether partially initialized objects should be considered as initialized
isLazyObjectInitialized
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyGhostTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyGhostTrait.php
MIT
public function initializeLazyObject() : static { if (!($state = $this->lazyObjectState ?? null)) { return $this; } if (!\is_array($state->initializer)) { if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) { $state->initialize($this, '', null); } return $this; } $values = isset($state->initializer["\x00"]) ? null : []; $class = $this::class; $properties = (array) $this; $propertyScopes = Hydrator::$propertyScopes[$class] ??= Hydrator::getPropertyScopes($class); foreach ($state->initializer as $key => $initializer) { if (\array_key_exists($key, $properties) || !([$scope, $name, $readonlyScope] = $propertyScopes[$key] ?? null)) { continue; } $scope = $readonlyScope ?? ('*' !== $scope ? $scope : $class); if (null === $values) { if (!\is_array($values = $state->initializer["\x00"]($this, Registry::$defaultProperties[$class]))) { throw new \TypeError(\sprintf('The lazy-initializer defined for instance of "%s" must return an array, got "%s".', $class, \get_debug_type($values))); } if (\array_key_exists($key, $properties = (array) $this)) { continue; } } if (\array_key_exists($key, $values)) { $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope); $accessor['set']($this, $name, $properties[$key] = $values[$key]); } else { $state->initialize($this, $name, $scope); $properties = (array) $this; } } return $this; }
Forces initialization of a lazy object and returns it.
initializeLazyObject
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyGhostTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyGhostTrait.php
MIT
public function resetLazyObject() : bool { if (!($state = $this->lazyObjectState ?? null)) { return \false; } if (LazyObjectState::STATUS_UNINITIALIZED_FULL !== $state->status) { $state->reset($this); } return \true; }
@return bool Returns false when the object cannot be reset, ie when it's not a lazy object
resetLazyObject
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyGhostTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyGhostTrait.php
MIT
public static function createLazyProxy(\Closure $initializer, ?object $instance = null) : static { if (self::class !== ($class = $instance ? $instance::class : static::class)) { $skippedProperties = ["\x00" . self::class . "\x00lazyObjectState" => \true]; } elseif (\defined($class . '::LAZY_OBJECT_PROPERTY_SCOPES')) { Hydrator::$propertyScopes[$class] ??= $class::LAZY_OBJECT_PROPERTY_SCOPES; } $instance ??= (Registry::$classReflectors[$class] ??= new \ReflectionClass($class))->newInstanceWithoutConstructor(); $instance->lazyObjectState = new LazyObjectState($initializer); foreach (Registry::$classResetters[$class] ??= Registry::getClassResetters($class) as $reset) { $reset($instance, $skippedProperties ??= []); } return $instance; }
Creates a lazy-loading virtual proxy. @param \Closure():object $initializer Returns the proxied object @param static|null $instance
createLazyProxy
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyProxyTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyProxyTrait.php
MIT
#[Ignore] public function isLazyObjectInitialized(bool $partial = \false) : bool { return !isset($this->lazyObjectState) || isset($this->lazyObjectState->realInstance) || Registry::$noInitializerState === $this->lazyObjectState->initializer; }
Returns whether the object is initialized. @param $partial Whether partially initialized objects should be considered as initialized
isLazyObjectInitialized
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyProxyTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyProxyTrait.php
MIT
public function initializeLazyObject() : parent { if ($state = $this->lazyObjectState ?? null) { return $state->realInstance ??= ($state->initializer)(); } return $this; }
Forces initialization of a lazy object and returns it.
initializeLazyObject
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyProxyTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyProxyTrait.php
MIT
public function resetLazyObject() : bool { if (!isset($this->lazyObjectState) || Registry::$noInitializerState === $this->lazyObjectState->initializer) { return \false; } unset($this->lazyObjectState->realInstance); return \true; }
@return bool Returns false when the object cannot be reset, ie when it's not a lazy object
resetLazyObject
php
deptrac/deptrac
vendor/symfony/var-exporter/LazyProxyTrait.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/LazyProxyTrait.php
MIT
public static function generateLazyGhost(\ReflectionClass $class) : string { if (\PHP_VERSION_ID >= 80200 && \PHP_VERSION_ID < 80300 && $class->isReadOnly()) { throw new LogicException(\sprintf('Cannot generate lazy ghost with PHP < 8.3: class "%s" is readonly.', $class->name)); } if ($class->isFinal()) { throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is final.', $class->name)); } if ($class->isInterface() || $class->isAbstract()) { throw new LogicException(\sprintf('Cannot generate lazy ghost: "%s" is not a concrete class.', $class->name)); } if (\stdClass::class !== $class->name && $class->isInternal()) { throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" is internal.', $class->name)); } if ($class->hasMethod('__get') && 'mixed' !== (self::exportType($class->getMethod('__get')) ?? 'mixed')) { throw new LogicException(\sprintf('Cannot generate lazy ghost: return type of method "%s::__get()" should be "mixed".', $class->name)); } static $traitMethods; $traitMethods ??= (new \ReflectionClass(LazyGhostTrait::class))->getMethods(); foreach ($traitMethods as $method) { if ($class->hasMethod($method->name) && $class->getMethod($method->name)->isFinal()) { throw new LogicException(\sprintf('Cannot generate lazy ghost: method "%s::%s()" is final.', $class->name, $method->name)); } } $parent = $class; while ($parent = $parent->getParentClass()) { if (\stdClass::class !== $parent->name && $parent->isInternal()) { throw new LogicException(\sprintf('Cannot generate lazy ghost: class "%s" extends "%s" which is internal.', $class->name, $parent->name)); } } $propertyScopes = self::exportPropertyScopes($class->name); return <<<EOPHP extends \\{$class->name} implements \\Symfony\\Component\\VarExporter\\LazyObjectInterface { use \\Symfony\\Component\\VarExporter\\LazyGhostTrait; private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes}; } // Help opcache.preload discover always-needed symbols class_exists(\\Symfony\\Component\\VarExporter\\Internal\\Hydrator::class); class_exists(\\Symfony\\Component\\VarExporter\\Internal\\LazyObjectRegistry::class); class_exists(\\Symfony\\Component\\VarExporter\\Internal\\LazyObjectState::class); EOPHP; }
Helps generate lazy-loading ghost objects. @throws LogicException When the class is incompatible with ghost objects
generateLazyGhost
php
deptrac/deptrac
vendor/symfony/var-exporter/ProxyHelper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/ProxyHelper.php
MIT
public static function generateLazyProxy(?\ReflectionClass $class, array $interfaces = []) : string { if (!\class_exists($class?->name ?? \stdClass::class, \false)) { throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not a class.', $class->name)); } if ($class?->isFinal()) { throw new LogicException(\sprintf('Cannot generate lazy proxy: class "%s" is final.', $class->name)); } if (\PHP_VERSION_ID >= 80200 && \PHP_VERSION_ID < 80300 && $class?->isReadOnly()) { throw new LogicException(\sprintf('Cannot generate lazy proxy with PHP < 8.3: class "%s" is readonly.', $class->name)); } $methodReflectors = [$class?->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) ?? []]; foreach ($interfaces as $interface) { if (!$interface->isInterface()) { throw new LogicException(\sprintf('Cannot generate lazy proxy: "%s" is not an interface.', $interface->name)); } $methodReflectors[] = $interface->getMethods(); } $methodReflectors = \array_merge(...$methodReflectors); $extendsInternalClass = \false; if ($parent = $class) { do { $extendsInternalClass = \stdClass::class !== $parent->name && $parent->isInternal(); } while (!$extendsInternalClass && ($parent = $parent->getParentClass())); } $methodsHaveToBeProxied = $extendsInternalClass; $methods = []; foreach ($methodReflectors as $method) { if ('__get' !== \strtolower($method->name) || 'mixed' === ($type = self::exportType($method) ?? 'mixed')) { continue; } $methodsHaveToBeProxied = \true; $trait = new \ReflectionMethod(LazyProxyTrait::class, '__get'); $body = \array_slice(\file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine()); $body[0] = \str_replace('): mixed', '): ' . $type, $body[0]); $methods['__get'] = \strtr(\implode('', $body) . ' }', ['Hydrator' => '\\' . Hydrator::class, 'Registry' => '\\' . LazyObjectRegistry::class]); break; } foreach ($methodReflectors as $method) { if ($method->isStatic() && !$method->isAbstract() || isset($methods[$lcName = \strtolower($method->name)])) { continue; } if ($method->isFinal()) { if ($extendsInternalClass || $methodsHaveToBeProxied || \method_exists(LazyProxyTrait::class, $method->name)) { throw new LogicException(\sprintf('Cannot generate lazy proxy: method "%s::%s()" is final.', $class->name, $method->name)); } continue; } if (\method_exists(LazyProxyTrait::class, $method->name) || $method->isProtected() && !$method->isAbstract()) { continue; } $signature = self::exportSignature($method, \true, $args); $parentCall = $method->isAbstract() ? "throw new \\BadMethodCallException('Cannot forward abstract method \"{$method->class}::{$method->name}()\".')" : "parent::{$method->name}({$args})"; if ($method->isStatic()) { $body = " {$parentCall};"; } elseif (\str_ends_with($signature, '): never') || \str_ends_with($signature, '): void')) { $body = <<<EOPHP if (isset(\$this->lazyObjectState)) { (\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)())->{$method->name}({$args}); } else { {$parentCall}; } EOPHP; } else { if (!$methodsHaveToBeProxied && !$method->isAbstract()) { // Skip proxying methods that might return $this foreach (\preg_split('/[()|&]++/', self::exportType($method) ?? 'static') as $type) { if (\in_array($type = \ltrim($type, '?'), ['static', 'object'], \true)) { continue 2; } foreach ([$class, ...$interfaces] as $r) { if ($r && \is_a($r->name, $type, \true)) { continue 3; } } } } $body = <<<EOPHP if (isset(\$this->lazyObjectState)) { return (\$this->lazyObjectState->realInstance ??= (\$this->lazyObjectState->initializer)())->{$method->name}({$args}); } return {$parentCall}; EOPHP; } $methods[$lcName] = " {$signature}\n {\n{$body}\n }"; } $types = $interfaces = \array_unique(\array_column($interfaces, 'name')); $interfaces[] = LazyObjectInterface::class; $interfaces = \implode(', \\', $interfaces); $parent = $class ? ' extends \\' . $class->name : ''; \array_unshift($types, $class ? 'parent' : ''); $type = \ltrim(\implode('&\\', $types), '&'); if (!$class) { $trait = new \ReflectionMethod(LazyProxyTrait::class, 'initializeLazyObject'); $body = \array_slice(\file($trait->getFileName()), $trait->getStartLine() - 1, $trait->getEndLine() - $trait->getStartLine()); $body[0] = \str_replace('): parent', '): ' . $type, $body[0]); $methods = ['initializeLazyObject' => \implode('', $body) . ' }'] + $methods; } $body = $methods ? "\n" . \implode("\n\n", $methods) . "\n" : ''; $propertyScopes = $class ? self::exportPropertyScopes($class->name) : '[]'; if ($class?->hasMethod('__unserialize') && !$class->getMethod('__unserialize')->getParameters()[0]->getType()) { // fix contravariance type problem when $class declares a `__unserialize()` method without typehint. $lazyProxyTraitStatement = <<<EOPHP use \\Symfony\\Component\\VarExporter\\LazyProxyTrait { __unserialize as private __doUnserialize; } EOPHP; $body .= <<<EOPHP public function __unserialize(\$data): void { \$this->__doUnserialize(\$data); } EOPHP; } else { $lazyProxyTraitStatement = <<<EOPHP use \\Symfony\\Component\\VarExporter\\LazyProxyTrait; EOPHP; } return <<<EOPHP {$parent} implements \\{$interfaces} { {$lazyProxyTraitStatement} private const LAZY_OBJECT_PROPERTY_SCOPES = {$propertyScopes}; {$body}} // Help opcache.preload discover always-needed symbols class_exists(\\Symfony\\Component\\VarExporter\\Internal\\Hydrator::class); class_exists(\\Symfony\\Component\\VarExporter\\Internal\\LazyObjectRegistry::class); class_exists(\\Symfony\\Component\\VarExporter\\Internal\\LazyObjectState::class); EOPHP; }
Helps generate lazy-loading virtual proxies. @param \ReflectionClass[] $interfaces @throws LogicException When the class is incompatible with virtual proxies
generateLazyProxy
php
deptrac/deptrac
vendor/symfony/var-exporter/ProxyHelper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/ProxyHelper.php
MIT
public static function export(mixed $value, ?bool &$isStaticValue = null, array &$foundClasses = []) : string { $isStaticValue = \true; if (!\is_object($value) && !(\is_array($value) && $value) && !\is_resource($value) || $value instanceof \UnitEnum) { return Exporter::export($value); } $objectsPool = new \SplObjectStorage(); $refsPool = []; $objectsCount = 0; try { $value = Exporter::prepare([$value], $objectsPool, $refsPool, $objectsCount, $isStaticValue)[0]; } finally { $references = []; foreach ($refsPool as $i => $v) { if ($v[0]->count) { $references[1 + $i] = $v[2]; } $v[0] = $v[1]; } } if ($isStaticValue) { return Exporter::export($value); } $classes = []; $values = []; $states = []; foreach ($objectsPool as $i => $v) { [, $class, $values[], $wakeup] = $objectsPool[$v]; $foundClasses[$class] = $classes[] = $class; if (0 < $wakeup) { $states[$wakeup] = $i; } elseif (0 > $wakeup) { $states[-$wakeup] = [$i, \array_pop($values)]; $values[] = []; } } \ksort($states); $wakeups = [null]; foreach ($states as $v) { if (\is_array($v)) { $wakeups[-$v[0]] = $v[1]; } else { $wakeups[] = $v; } } if (null === $wakeups[0]) { unset($wakeups[0]); } $properties = []; foreach ($values as $i => $vars) { foreach ($vars as $class => $values) { foreach ($values as $name => $v) { $properties[$class][$name][$i] = $v; } } } if ($classes || $references) { $value = new Hydrator(new Registry($classes), $references ? new Values($references) : null, $properties, $value, $wakeups); } else { $isStaticValue = \true; } return Exporter::export($value); }
Exports a serializable PHP value to PHP code. @param bool &$isStaticValue Set to true after execution if the provided value is static, false otherwise @param array &$foundClasses Classes found in the value are added to this list as both keys and values @throws ExceptionInterface When the provided value cannot be serialized
export
php
deptrac/deptrac
vendor/symfony/var-exporter/VarExporter.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/VarExporter.php
MIT
public static function prepare($values, $objectsPool, &$refsPool, &$objectsCount, &$valuesAreStatic) { $refs = $values; foreach ($values as $k => $value) { if (\is_resource($value)) { throw new NotInstantiableTypeException(\get_resource_type($value) . ' resource'); } $refs[$k] = $objectsPool; if ($isRef = !($valueIsStatic = $values[$k] !== $objectsPool)) { $values[$k] =& $value; // Break hard references to make $values completely unset($value); // independent from the original structure $refs[$k] = $value = $values[$k]; if ($value instanceof Reference && 0 > $value->id) { $valuesAreStatic = \false; ++$value->count; continue; } $refsPool[] = [&$refs[$k], $value, &$value]; $refs[$k] = $values[$k] = new Reference(-\count($refsPool), $value); } if (\is_array($value)) { if ($value) { $value = self::prepare($value, $objectsPool, $refsPool, $objectsCount, $valueIsStatic); } goto handle_value; } elseif (!\is_object($value) || $value instanceof \UnitEnum) { goto handle_value; } $valueIsStatic = \false; if (isset($objectsPool[$value])) { ++$objectsCount; $value = new Reference($objectsPool[$value][0]); goto handle_value; } $class = $value::class; $reflector = Registry::$reflectors[$class] ??= Registry::getClassReflector($class); $properties = []; if ($reflector->hasMethod('__serialize')) { if (!$reflector->getMethod('__serialize')->isPublic()) { throw new \Error(\sprintf('Call to %s method "%s::__serialize()".', $reflector->getMethod('__serialize')->isProtected() ? 'protected' : 'private', $class)); } if (!\is_array($serializeProperties = $value->__serialize())) { throw new \TypeError($class . '::__serialize() must return an array'); } if ($reflector->hasMethod('__unserialize')) { $properties = $serializeProperties; } else { foreach ($serializeProperties as $n => $v) { $c = $reflector->hasProperty($n) && ($p = $reflector->getProperty($n))->isReadOnly() ? $p->class : 'stdClass'; $properties[$c][$n] = $v; } } goto prepare_value; } $sleep = null; $proto = Registry::$prototypes[$class]; if (($value instanceof \ArrayIterator || $value instanceof \ArrayObject) && null !== $proto) { // ArrayIterator and ArrayObject need special care because their "flags" // option changes the behavior of the (array) casting operator. [$arrayValue, $properties] = self::getArrayObjectProperties($value, $proto); // populates Registry::$prototypes[$class] with a new instance Registry::getClassReflector($class, Registry::$instantiableWithoutConstructor[$class], Registry::$cloneable[$class]); } elseif ($value instanceof \SplObjectStorage && Registry::$cloneable[$class] && null !== $proto) { // By implementing Serializable, SplObjectStorage breaks // internal references; let's deal with it on our own. foreach (clone $value as $v) { $properties[] = $v; $properties[] = $value[$v]; } $properties = ['SplObjectStorage' => ["\x00" => $properties]]; $arrayValue = (array) $value; } elseif ($value instanceof \Serializable || $value instanceof \__PHP_Incomplete_Class || \PHP_VERSION_ID < 80200 && $value instanceof \DatePeriod) { ++$objectsCount; $objectsPool[$value] = [$id = \count($objectsPool), \serialize($value), [], 0]; $value = new Reference($id); goto handle_value; } else { if (\method_exists($class, '__sleep')) { if (!\is_array($sleep = $value->__sleep())) { \trigger_error('serialize(): __sleep should return an array only containing the names of instance-variables to serialize', \E_USER_NOTICE); $value = null; goto handle_value; } $sleep = \array_flip($sleep); } $arrayValue = (array) $value; } $proto = (array) $proto; foreach ($arrayValue as $name => $v) { $i = 0; $n = (string) $name; if ('' === $n || "\x00" !== $n[0]) { $c = $reflector->hasProperty($n) && ($p = $reflector->getProperty($n))->isReadOnly() ? $p->class : 'stdClass'; } elseif ('*' === $n[1]) { $n = \substr($n, 3); $c = $reflector->getProperty($n)->class; if ('Error' === $c) { $c = 'TypeError'; } elseif ('Exception' === $c) { $c = 'ErrorException'; } } else { $i = \strpos($n, "\x00", 2); $c = \substr($n, 1, $i - 1); $n = \substr($n, 1 + $i); } if (null !== $sleep) { if (!isset($sleep[$name]) && (!isset($sleep[$n]) || $i && $c !== $class)) { unset($arrayValue[$name]); continue; } unset($sleep[$name], $sleep[$n]); } if (!\array_key_exists($name, $proto) || $proto[$name] !== $v || "\x00Error\x00trace" === $name || "\x00Exception\x00trace" === $name) { $properties[$c][$n] = $v; } } if ($sleep) { foreach ($sleep as $n => $v) { \trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $n), \E_USER_NOTICE); } } if (\method_exists($class, '__unserialize')) { $properties = $arrayValue; } prepare_value: $objectsPool[$value] = [$id = \count($objectsPool)]; $properties = self::prepare($properties, $objectsPool, $refsPool, $objectsCount, $valueIsStatic); ++$objectsCount; $objectsPool[$value] = [$id, $class, $properties, \method_exists($class, '__unserialize') ? -$objectsCount : (\method_exists($class, '__wakeup') ? $objectsCount : 0)]; $value = new Reference($id); handle_value: if ($isRef) { unset($value); // Break the hard reference created above } elseif (!$valueIsStatic) { $values[$k] = $value; } $valuesAreStatic = $valueIsStatic && $valuesAreStatic; } return $values; }
Prepares an array of values for VarExporter. For performance this method is public and has no type-hints. @param array &$values @param \SplObjectStorage $objectsPool @param array &$refsPool @param int &$objectsCount @param bool &$valuesAreStatic @return array @throws NotInstantiableTypeException When a value cannot be serialized
prepare
php
deptrac/deptrac
vendor/symfony/var-exporter/Internal/Exporter.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/Internal/Exporter.php
MIT
private static function getArrayObjectProperties($value, $proto) : array { $reflector = $value instanceof \ArrayIterator ? 'ArrayIterator' : 'ArrayObject'; $reflector = Registry::$reflectors[$reflector] ??= Registry::getClassReflector($reflector); $properties = [$arrayValue = (array) $value, $reflector->getMethod('getFlags')->invoke($value), $value instanceof \ArrayObject ? $reflector->getMethod('getIteratorClass')->invoke($value) : 'ArrayIterator']; $reflector = $reflector->getMethod('setFlags'); $reflector->invoke($proto, \ArrayObject::STD_PROP_LIST); if ($properties[1] & \ArrayObject::STD_PROP_LIST) { $reflector->invoke($value, 0); $properties[0] = (array) $value; } else { $reflector->invoke($value, \ArrayObject::STD_PROP_LIST); $arrayValue = (array) $value; } $reflector->invoke($value, $properties[1]); if ([[], 0, 'ArrayIterator'] === $properties) { $properties = []; } else { if ('ArrayIterator' === $properties[2]) { unset($properties[2]); } $properties = [$reflector->class => ["\x00" => $properties]]; } return [$arrayValue, $properties]; }
@param \ArrayIterator|\ArrayObject $value @param \ArrayIterator|\ArrayObject $proto
getArrayObjectProperties
php
deptrac/deptrac
vendor/symfony/var-exporter/Internal/Exporter.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/var-exporter/Internal/Exporter.php
MIT
public function dump(mixed $input, int $inline = 0, int $indent = 0, int $flags = 0) : string { $output = ''; $prefix = $indent ? \str_repeat(' ', $indent) : ''; $dumpObjectAsInlineMap = \true; if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($input instanceof \ArrayObject || $input instanceof \stdClass)) { $dumpObjectAsInlineMap = empty((array) $input); } if ($inline <= 0 || !\is_array($input) && !$input instanceof TaggedValue && $dumpObjectAsInlineMap || empty($input)) { $output .= $prefix . Inline::dump($input, $flags); } elseif ($input instanceof TaggedValue) { $output .= $this->dumpTaggedValue($input, $inline, $indent, $flags, $prefix); } else { $dumpAsMap = Inline::isHash($input); foreach ($input as $key => $value) { if ('' !== $output && "\n" !== $output[-1]) { $output .= "\n"; } if (\is_int($key) && Yaml::DUMP_NUMERIC_KEY_AS_STRING & $flags) { $key = (string) $key; } if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value) && \str_contains($value, "\n") && !\str_contains($value, "\r")) { $blockIndentationIndicator = $this->getBlockIndentationIndicator($value); if (isset($value[-2]) && "\n" === $value[-2] && "\n" === $value[-1]) { $blockChompingIndicator = '+'; } elseif ("\n" === $value[-1]) { $blockChompingIndicator = ''; } else { $blockChompingIndicator = '-'; } $output .= \sprintf('%s%s%s |%s%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags) . ':' : '-', '', $blockIndentationIndicator, $blockChompingIndicator); foreach (\explode("\n", $value) as $row) { if ('' === $row) { $output .= "\n"; } else { $output .= \sprintf("\n%s%s%s", $prefix, \str_repeat(' ', $this->indentation), $row); } } continue; } if ($value instanceof TaggedValue) { $output .= \sprintf('%s%s !%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags) . ':' : '-', $value->getTag()); if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value->getValue()) && \str_contains($value->getValue(), "\n") && !\str_contains($value->getValue(), "\r\n")) { $blockIndentationIndicator = $this->getBlockIndentationIndicator($value->getValue()); $output .= \sprintf(' |%s', $blockIndentationIndicator); foreach (\explode("\n", $value->getValue()) as $row) { $output .= \sprintf("\n%s%s%s", $prefix, \str_repeat(' ', $this->indentation), $row); } continue; } if ($inline - 1 <= 0 || null === $value->getValue() || \is_scalar($value->getValue())) { $output .= ' ' . $this->dump($value->getValue(), $inline - 1, 0, $flags) . "\n"; } else { $output .= "\n"; $output .= $this->dump($value->getValue(), $inline - 1, $dumpAsMap ? $indent + $this->indentation : $indent + 2, $flags); } continue; } $dumpObjectAsInlineMap = \true; if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \ArrayObject || $value instanceof \stdClass)) { $dumpObjectAsInlineMap = empty((array) $value); } $willBeInlined = $inline - 1 <= 0 || !\is_array($value) && $dumpObjectAsInlineMap || empty($value); $output .= \sprintf('%s%s%s%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags) . ':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $flags)) . ($willBeInlined ? "\n" : ''); } } return $output; }
Dumps a PHP value to YAML. @param mixed $input The PHP value @param int $inline The level where you switch to inline YAML @param int $indent The level of indentation (used internally) @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
dump
php
deptrac/deptrac
vendor/symfony/yaml/Dumper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Dumper.php
MIT
public static function requiresDoubleQuoting(string $value) : bool { return 0 < \preg_match('/' . self::REGEX_CHARACTER_TO_ESCAPE . '/u', $value); }
Determines if a PHP value would require double quoting in YAML. @param string $value A PHP value
requiresDoubleQuoting
php
deptrac/deptrac
vendor/symfony/yaml/Escaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Escaper.php
MIT
public static function escapeWithDoubleQuotes(string $value) : string { return \sprintf('"%s"', \str_replace(self::ESCAPEES, self::ESCAPED, $value)); }
Escapes and surrounds a PHP value with double quotes. @param string $value A PHP value
escapeWithDoubleQuotes
php
deptrac/deptrac
vendor/symfony/yaml/Escaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Escaper.php
MIT
public static function requiresSingleQuoting(string $value) : bool { // Determines if a PHP value is entirely composed of a value that would // require single quoting in YAML. if (\in_array(\strtolower($value), ['null', '~', 'true', 'false', 'y', 'n', 'yes', 'no', 'on', 'off'])) { return \true; } // Determines if the PHP value contains any single characters that would // cause it to require single quoting in YAML. return 0 < \preg_match('/[ \\s \' " \\: \\{ \\} \\[ \\] , & \\* \\# \\?] | \\A[ \\- ? | < > = ! % @ ` \\p{Zs}]/xu', $value); }
Determines if a PHP value would require single quoting in YAML. @param string $value A PHP value
requiresSingleQuoting
php
deptrac/deptrac
vendor/symfony/yaml/Escaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Escaper.php
MIT
public static function escapeWithSingleQuotes(string $value) : string { return \sprintf("'%s'", \str_replace('\'', '\'\'', $value)); }
Escapes and surrounds a PHP value with single quotes. @param string $value A PHP value
escapeWithSingleQuotes
php
deptrac/deptrac
vendor/symfony/yaml/Escaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Escaper.php
MIT
public static function parse(string $value, int $flags = 0, array &$references = []) : mixed { self::initialize($flags); $value = \trim($value); if ('' === $value) { return ''; } $i = 0; $tag = self::parseTag($value, $i, $flags); switch ($value[$i]) { case '[': $result = self::parseSequence($value, $flags, $i, $references); ++$i; break; case '{': $result = self::parseMapping($value, $flags, $i, $references); ++$i; break; default: $result = self::parseScalar($value, $flags, null, $i, \true, $references); } // some comments are allowed at the end if (\preg_replace('/\\s*#.*$/A', '', \substr($value, $i))) { throw new ParseException(\sprintf('Unexpected characters near "%s".', \substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename); } if (null !== $tag && '' !== $tag) { return new TaggedValue($tag, $result); } return $result; }
Converts a YAML string to a PHP value. @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior @param array $references Mapping of variable names to values @throws ParseException
parse
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
public static function dump(mixed $value, int $flags = 0) : string { switch (\true) { case \is_resource($value): if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { throw new DumpException(\sprintf('Unable to dump PHP resources in a YAML file ("%s").', \get_resource_type($value))); } return self::dumpNull($flags); case $value instanceof \DateTimeInterface: return $value->format(match (\true) { !($length = \strlen(\rtrim($value->format('u'), '0'))) => 'c', $length < 4 => 'Y-m-d\\TH:i:s.vP', default => 'Y-m-d\\TH:i:s.uP', }); case $value instanceof \UnitEnum: return \sprintf('!php/const %s::%s', $value::class, $value->name); case \is_object($value): if ($value instanceof TaggedValue) { return '!' . $value->getTag() . ' ' . self::dump($value->getValue(), $flags); } if (Yaml::DUMP_OBJECT & $flags) { return '!php/object ' . self::dump(\serialize($value)); } if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { return self::dumpHashArray($value, $flags); } if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { throw new DumpException('Object support when dumping a YAML file has been disabled.'); } return self::dumpNull($flags); case \is_array($value): return self::dumpArray($value, $flags); case null === $value: return self::dumpNull($flags); case \true === $value: return 'true'; case \false === $value: return 'false'; case \is_int($value): return $value; case \is_numeric($value) && \false === \strpbrk($value, "\f\n\r\t\v"): $locale = \setlocale(\LC_NUMERIC, 0); if (\false !== $locale) { \setlocale(\LC_NUMERIC, 'C'); } if (\is_float($value)) { $repr = (string) $value; if (\is_infinite($value)) { $repr = \str_ireplace('INF', '.Inf', $repr); } elseif (\floor($value) == $value && $repr == $value) { // Preserve float data type since storing a whole number will result in integer value. if (!\str_contains($repr, 'E')) { $repr .= '.0'; } } } else { $repr = \is_string($value) ? "'{$value}'" : (string) $value; } if (\false !== $locale) { \setlocale(\LC_NUMERIC, $locale); } return $repr; case '' == $value: return "''"; case self::isBinaryString($value): return '!!binary ' . \base64_encode($value); case Escaper::requiresDoubleQuoting($value): return Escaper::escapeWithDoubleQuotes($value); case Escaper::requiresSingleQuoting($value): $singleQuoted = Escaper::escapeWithSingleQuotes($value); if (!\str_contains($value, "'")) { return $singleQuoted; } // Attempt double-quoting the string instead to see if it's more efficient. $doubleQuoted = Escaper::escapeWithDoubleQuotes($value); return \strlen($doubleQuoted) < \strlen($singleQuoted) ? $doubleQuoted : $singleQuoted; case Parser::preg_match('{^[0-9]+[_0-9]*$}', $value): case Parser::preg_match(self::getHexRegex(), $value): case Parser::preg_match(self::getTimestampRegex(), $value): return Escaper::escapeWithSingleQuotes($value); default: return $value; } }
Dumps a given PHP variable to a YAML string. @param mixed $value The PHP variable to convert @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string @throws DumpException When trying to dump PHP resource
dump
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
public static function isHash(array|\ArrayObject|\stdClass $value) : bool { if ($value instanceof \stdClass || $value instanceof \ArrayObject) { return \true; } $expectedKey = 0; foreach ($value as $key => $val) { if ($key !== $expectedKey++) { return \true; } } return \false; }
Check if given array is hash or just normal indexed array.
isHash
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function dumpArray(array $value, int $flags) : string { // array if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) { $output = []; foreach ($value as $val) { $output[] = self::dump($val, $flags); } return \sprintf('[%s]', \implode(', ', $output)); } return self::dumpHashArray($value, $flags); }
Dumps a PHP array to a YAML string. @param array $value The PHP array to dump @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
dumpArray
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function dumpHashArray(array|\ArrayObject|\stdClass $value, int $flags) : string { $output = []; foreach ($value as $key => $val) { if (\is_int($key) && Yaml::DUMP_NUMERIC_KEY_AS_STRING & $flags) { $key = (string) $key; } $output[] = \sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); } return \sprintf('{ %s }', \implode(', ', $output)); }
Dumps hash array to a YAML string. @param array|\ArrayObject|\stdClass $value The hash array to dump @param int $flags A bit field of Yaml::DUMP_* constants to customize the dumped YAML string
dumpHashArray
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
public static function parseScalar(string $scalar, int $flags = 0, ?array $delimiters = null, int &$i = 0, bool $evaluate = \true, array &$references = [], ?bool &$isQuoted = null) : mixed { if (\in_array($scalar[$i], ['"', "'"], \true)) { // quoted scalar $isQuoted = \true; $output = self::parseQuotedScalar($scalar, $i); if (null !== $delimiters) { $tmp = \ltrim(\substr($scalar, $i), " \n"); if ('' === $tmp) { throw new ParseException(\sprintf('Unexpected end of line, expected one of "%s".', \implode('', $delimiters)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } if (!\in_array($tmp[0], $delimiters)) { throw new ParseException(\sprintf('Unexpected characters (%s).', \substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } } } else { // "normal" string $isQuoted = \false; if (!$delimiters) { $output = \substr($scalar, $i); $i += \strlen($output); // remove comments if (Parser::preg_match('/[ \\t]+#/', $output, $match, \PREG_OFFSET_CAPTURE)) { $output = \substr($output, 0, $match[0][1]); } } elseif (Parser::preg_match('/^(.*?)(' . \implode('|', $delimiters) . ')/', \substr($scalar, $i), $match)) { $output = $match[1]; $i += \strlen($output); $output = \trim($output); } else { throw new ParseException(\sprintf('Malformed inline YAML string: "%s".', $scalar), self::$parsedLineNumber + 1, null, self::$parsedFilename); } // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >) if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0] || '%' === $output[0])) { throw new ParseException(\sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0]), self::$parsedLineNumber + 1, $output, self::$parsedFilename); } if ($evaluate) { $output = self::evaluateScalar($output, $flags, $references, $isQuoted); } } return $output; }
Parses a YAML scalar. @throws ParseException When malformed inline YAML string is parsed
parseScalar
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function parseQuotedScalar(string $scalar, int &$i = 0) : string { if (!Parser::preg_match('/' . self::REGEX_QUOTED_STRING . '/Au', \substr($scalar, $i), $match)) { throw new ParseException(\sprintf('Malformed inline YAML string: "%s".', \substr($scalar, $i)), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } $output = \substr($match[0], 1, -1); $unescaper = new Unescaper(); if ('"' == $scalar[$i]) { $output = $unescaper->unescapeDoubleQuotedString($output); } else { $output = $unescaper->unescapeSingleQuotedString($output); } $i += \strlen($match[0]); return $output; }
Parses a YAML quoted scalar. @throws ParseException When malformed inline YAML string is parsed
parseQuotedScalar
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function parseSequence(string $sequence, int $flags, int &$i = 0, array &$references = []) : array { $output = []; $len = \strlen($sequence); ++$i; // [foo, bar, ...] $lastToken = null; while ($i < $len) { if (']' === $sequence[$i]) { return $output; } if (',' === $sequence[$i] || ' ' === $sequence[$i]) { if (',' === $sequence[$i] && (null === $lastToken || 'separator' === $lastToken)) { $output[] = null; } elseif (',' === $sequence[$i]) { $lastToken = 'separator'; } ++$i; continue; } $tag = self::parseTag($sequence, $i, $flags); switch ($sequence[$i]) { case '[': // nested sequence $value = self::parseSequence($sequence, $flags, $i, $references); break; case '{': // nested mapping $value = self::parseMapping($sequence, $flags, $i, $references); break; default: $value = self::parseScalar($sequence, $flags, [',', ']'], $i, null === $tag, $references, $isQuoted); // the value can be an array if a reference has been resolved to an array var if (\is_string($value) && !$isQuoted && \str_contains($value, ': ')) { // embedded mapping? try { $pos = 0; $value = self::parseMapping('{' . $value . '}', $flags, $pos, $references); } catch (\InvalidArgumentException) { // no, it's not } } if (!$isQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) { $references[$matches['ref']] = $matches['value']; $value = $matches['value']; } --$i; } if (null !== $tag && '' !== $tag) { $value = new TaggedValue($tag, $value); } $output[] = $value; $lastToken = 'value'; ++$i; } throw new ParseException(\sprintf('Malformed inline YAML string: "%s".', $sequence), self::$parsedLineNumber + 1, null, self::$parsedFilename); }
Parses a YAML sequence. @throws ParseException When malformed inline YAML string is parsed
parseSequence
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function parseMapping(string $mapping, int $flags, int &$i = 0, array &$references = []) : array|\stdClass { $output = []; $len = \strlen($mapping); ++$i; $allowOverwrite = \false; // {foo: bar, bar:foo, ...} while ($i < $len) { switch ($mapping[$i]) { case ' ': case ',': case "\n": ++$i; continue 2; case '}': if (self::$objectForMap) { return (object) $output; } return $output; } // key $offsetBeforeKeyParsing = $i; $isKeyQuoted = \in_array($mapping[$i], ['"', "'"], \true); $key = self::parseScalar($mapping, $flags, [':', ' '], $i, \false); if ($offsetBeforeKeyParsing === $i) { throw new ParseException('Missing mapping key.', self::$parsedLineNumber + 1, $mapping); } if ('!php/const' === $key || '!php/enum' === $key) { $key .= ' ' . self::parseScalar($mapping, $flags, [':'], $i, \false); $key = self::evaluateScalar($key, $flags); } if (\false === ($i = \strpos($mapping, ':', $i))) { break; } if (!$isKeyQuoted) { $evaluatedKey = self::evaluateScalar($key, $flags, $references); if ('' !== $key && $evaluatedKey !== $key && !\is_string($evaluatedKey) && !\is_int($evaluatedKey)) { throw new ParseException('Implicit casting of incompatible mapping keys to strings is not supported. Quote your evaluable mapping keys instead.', self::$parsedLineNumber + 1, $mapping); } } if (!$isKeyQuoted && (!isset($mapping[$i + 1]) || !\in_array($mapping[$i + 1], [' ', ',', '[', ']', '{', '}', "\n"], \true))) { throw new ParseException('Colons must be followed by a space or an indication character (i.e. " ", ",", "[", "]", "{", "}").', self::$parsedLineNumber + 1, $mapping); } if ('<<' === $key) { $allowOverwrite = \true; } while ($i < $len) { if (':' === $mapping[$i] || ' ' === $mapping[$i] || "\n" === $mapping[$i]) { ++$i; continue; } $tag = self::parseTag($mapping, $i, $flags); switch ($mapping[$i]) { case '[': // nested sequence $value = self::parseSequence($mapping, $flags, $i, $references); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. // But overwriting is allowed when a merge node is used in current block. if ('<<' === $key) { foreach ($value as $parsedValue) { $output += $parsedValue; } } elseif ($allowOverwrite || !isset($output[$key])) { if (null !== $tag) { $output[$key] = new TaggedValue($tag, $value); } else { $output[$key] = $value; } } elseif (isset($output[$key])) { throw new ParseException(\sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); } break; case '{': // nested mapping $value = self::parseMapping($mapping, $flags, $i, $references); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. // But overwriting is allowed when a merge node is used in current block. if ('<<' === $key) { $output += $value; } elseif ($allowOverwrite || !isset($output[$key])) { if (null !== $tag) { $output[$key] = new TaggedValue($tag, $value); } else { $output[$key] = $value; } } elseif (isset($output[$key])) { throw new ParseException(\sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); } break; default: $value = self::parseScalar($mapping, $flags, [',', '}', "\n"], $i, null === $tag, $references, $isValueQuoted); // Spec: Keys MUST be unique; first one wins. // Parser cannot abort this mapping earlier, since lines // are processed sequentially. // But overwriting is allowed when a merge node is used in current block. if ('<<' === $key) { $output += $value; } elseif ($allowOverwrite || !isset($output[$key])) { if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && !self::isBinaryString($value) && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) { $references[$matches['ref']] = $matches['value']; $value = $matches['value']; } if (null !== $tag) { $output[$key] = new TaggedValue($tag, $value); } else { $output[$key] = $value; } } elseif (isset($output[$key])) { throw new ParseException(\sprintf('Duplicate key "%s" detected.', $key), self::$parsedLineNumber + 1, $mapping); } --$i; } ++$i; continue 2; } } throw new ParseException(\sprintf('Malformed inline YAML string: "%s".', $mapping), self::$parsedLineNumber + 1, null, self::$parsedFilename); }
Parses a YAML mapping. @throws ParseException When malformed inline YAML string is parsed
parseMapping
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function evaluateScalar(string $scalar, int $flags, array &$references = [], ?bool &$isQuotedString = null) : mixed { $isQuotedString = \false; $scalar = \trim($scalar); if (\str_starts_with($scalar, '*')) { if (\false !== ($pos = \strpos($scalar, '#'))) { $value = \substr($scalar, 1, $pos - 2); } else { $value = \substr($scalar, 1); } // an unquoted * if (\false === $value || '' === $value) { throw new ParseException('A reference must contain at least one character.', self::$parsedLineNumber + 1, $value, self::$parsedFilename); } if (!\array_key_exists($value, $references)) { throw new ParseException(\sprintf('Reference "%s" does not exist.', $value), self::$parsedLineNumber + 1, $value, self::$parsedFilename); } return $references[$value]; } $scalarLower = \strtolower($scalar); switch (\true) { case 'null' === $scalarLower: case '' === $scalar: case '~' === $scalar: return null; case 'true' === $scalarLower: return \true; case 'false' === $scalarLower: return \false; case '!' === $scalar[0]: switch (\true) { case \str_starts_with($scalar, '!!str '): $s = (string) \substr($scalar, 6); if (\in_array($s[0] ?? '', ['"', "'"], \true)) { $isQuotedString = \true; $s = self::parseQuotedScalar($s); } return $s; case \str_starts_with($scalar, '! '): return \substr($scalar, 2); case \str_starts_with($scalar, '!php/object'): if (self::$objectSupport) { if (!isset($scalar[12])) { throw new ParseException('Missing value for tag "!php/object".', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } return \unserialize(self::parseScalar(\substr($scalar, 12))); } if (self::$exceptionOnInvalidType) { throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } return null; case \str_starts_with($scalar, '!php/const'): if (self::$constantSupport) { if (!isset($scalar[11])) { throw new ParseException('Missing value for tag "!php/const".', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } $i = 0; if (\defined($const = self::parseScalar(\substr($scalar, 11), 0, null, $i, \false))) { return \constant($const); } throw new ParseException(\sprintf('The constant "%s" is not defined.', $const), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } if (self::$exceptionOnInvalidType) { throw new ParseException(\sprintf('The string "%s" could not be parsed as a constant. Did you forget to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } return null; case \str_starts_with($scalar, '!php/enum'): if (self::$constantSupport) { if (!isset($scalar[11])) { throw new ParseException('Missing value for tag "!php/enum".', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } $i = 0; $enum = self::parseScalar(\substr($scalar, 10), 0, null, $i, \false); if ($useValue = \str_ends_with($enum, '->value')) { $enum = \substr($enum, 0, -7); } if (!\defined($enum)) { throw new ParseException(\sprintf('The enum "%s" is not defined.', $enum), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } $value = \constant($enum); if (!$value instanceof \UnitEnum) { throw new ParseException(\sprintf('The string "%s" is not the name of a valid enum.', $enum), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } if (!$useValue) { return $value; } if (!$value instanceof \BackedEnum) { throw new ParseException(\sprintf('The enum "%s" defines no value next to its name.', $enum), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } return $value->value; } if (self::$exceptionOnInvalidType) { throw new ParseException(\sprintf('The string "%s" could not be parsed as an enum. Did you forget to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } return null; case \str_starts_with($scalar, '!!float '): return (float) \substr($scalar, 8); case \str_starts_with($scalar, '!!binary '): return self::evaluateBinaryScalar(\substr($scalar, 9)); } throw new ParseException(\sprintf('The string "%s" could not be parsed as it uses an unsupported built-in tag.', $scalar), self::$parsedLineNumber, $scalar, self::$parsedFilename); case \preg_match('/^(?:\\+|-)?0o(?P<value>[0-7_]++)$/', $scalar, $matches): $value = \str_replace('_', '', $matches['value']); if ('-' === $scalar[0]) { return -\octdec($value); } return \octdec($value); case \in_array($scalar[0], ['+', '-', '.'], \true) || \is_numeric($scalar[0]): if (Parser::preg_match('{^[+-]?[0-9][0-9_]*$}', $scalar)) { $scalar = \str_replace('_', '', $scalar); } switch (\true) { case \ctype_digit($scalar): case '-' === $scalar[0] && \ctype_digit(\substr($scalar, 1)): $cast = (int) $scalar; return $scalar === (string) $cast ? $cast : $scalar; case \is_numeric($scalar): case Parser::preg_match(self::getHexRegex(), $scalar): $scalar = \str_replace('_', '', $scalar); return '0x' === $scalar[0] . $scalar[1] ? \hexdec($scalar) : (float) $scalar; case '.inf' === $scalarLower: case '.nan' === $scalarLower: return -\log(0); case '-.inf' === $scalarLower: return \log(0); case Parser::preg_match('/^(-|\\+)?[0-9][0-9_]*(\\.[0-9_]+)?$/', $scalar): return (float) \str_replace('_', '', $scalar); case Parser::preg_match(self::getTimestampRegex(), $scalar): try { // When no timezone is provided in the parsed date, YAML spec says we must assume UTC. $time = new \DateTimeImmutable($scalar, new \DateTimeZone('UTC')); } catch (\Exception $e) { // Some dates accepted by the regex are not valid dates. throw new ParseException(\sprintf('The date "%s" could not be parsed as it is an invalid date.', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename, $e); } if (Yaml::PARSE_DATETIME & $flags) { return $time; } if ('' !== \rtrim($time->format('u'), '0')) { return (float) $time->format('U.u'); } try { if (\false !== ($scalar = $time->getTimestamp())) { return $scalar; } } catch (\ValueError) { // no-op } return $time->format('U'); } } return (string) $scalar; }
Evaluates scalars and replaces magic values. @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
evaluateScalar
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function getTimestampRegex() : string { return <<<EOF ~^ (?P<year>[0-9][0-9][0-9][0-9]) -(?P<month>[0-9][0-9]?) -(?P<day>[0-9][0-9]?) (?:(?:[Tt]|[ \t]+) (?P<hour>[0-9][0-9]?) :(?P<minute>[0-9][0-9]) :(?P<second>[0-9][0-9]) (?:\\.(?P<fraction>[0-9]*))? (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?) (?::(?P<tz_minute>[0-9][0-9]))?))?)? \$~x EOF; }
Gets a regex that matches a YAML date. @see http://www.yaml.org/spec/1.2/spec.html#id2761573
getTimestampRegex
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
private static function getHexRegex() : string { return '~^0x[0-9a-f_]++$~i'; }
Gets a regex that matches a YAML number in hexadecimal notation.
getHexRegex
php
deptrac/deptrac
vendor/symfony/yaml/Inline.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Inline.php
MIT
public function parseFile(string $filename, int $flags = 0) : mixed { if (!\is_file($filename)) { throw new ParseException(\sprintf('File "%s" does not exist.', $filename)); } if (!\is_readable($filename)) { throw new ParseException(\sprintf('File "%s" cannot be read.', $filename)); } $this->filename = $filename; try { return $this->parse(\file_get_contents($filename), $flags); } finally { $this->filename = null; } }
Parses a YAML file into a PHP value. @param string $filename The path to the YAML file to be parsed @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior @throws ParseException If the file could not be read or the YAML is not valid
parseFile
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
public function parse(string $value, int $flags = 0) : mixed { if (\false === \preg_match('//u', $value)) { throw new ParseException('The YAML value does not appear to be valid UTF-8.', -1, null, $this->filename); } $this->refs = []; try { $data = $this->doParse($value, $flags); } finally { $this->refsBeingParsed = []; $this->offset = 0; $this->lines = []; $this->currentLine = ''; $this->numberOfParsedLines = 0; $this->refs = []; $this->skippedLineNumbers = []; $this->locallySkippedLineNumbers = []; $this->totalNumberOfLines = null; } return $data; }
Parses a YAML string to a PHP value. @param string $value A YAML string @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior @throws ParseException If the YAML is not valid
parse
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
public function getRealCurrentLineNb() : int { $realCurrentLineNumber = $this->currentLineNb + $this->offset; foreach ($this->skippedLineNumbers as $skippedLineNumber) { if ($skippedLineNumber > $realCurrentLineNumber) { break; } ++$realCurrentLineNumber; } return $realCurrentLineNumber; }
Returns the current line number (takes the offset into account). @internal
getRealCurrentLineNb
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function getNextEmbedBlock(?int $indentation = null, bool $inSequence = \false) : string { $oldLineIndentation = $this->getCurrentLineIndentation(); if (!$this->moveToNextLine()) { return ''; } if (null === $indentation) { $newIndent = null; $movements = 0; do { $EOF = \false; // empty and comment-like lines do not influence the indentation depth if ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) { $EOF = !$this->moveToNextLine(); if (!$EOF) { ++$movements; } } else { $newIndent = $this->getCurrentLineIndentation(); } } while (!$EOF && null === $newIndent); for ($i = 0; $i < $movements; ++$i) { $this->moveToPreviousLine(); } $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem(); if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) { throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); } } else { $newIndent = $indentation; } $data = []; if ($this->getCurrentLineIndentation() >= $newIndent) { $data[] = \substr($this->currentLine, $newIndent ?? 0); } elseif ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()) { $data[] = $this->currentLine; } else { $this->moveToPreviousLine(); return ''; } if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) { // the previous line contained a dash but no item content, this line is a sequence item with the same indentation // and therefore no nested list or mapping $this->moveToPreviousLine(); return ''; } $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); $isItComment = $this->isCurrentLineComment(); while ($this->moveToNextLine()) { if ($isItComment && !$isItUnindentedCollection) { $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); $isItComment = $this->isCurrentLineComment(); } $indent = $this->getCurrentLineIndentation(); if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) { $this->moveToPreviousLine(); break; } if ($this->isCurrentLineBlank()) { $data[] = \substr($this->currentLine, $newIndent ?? 0); continue; } if ($indent >= $newIndent) { $data[] = \substr($this->currentLine, $newIndent ?? 0); } elseif ($this->isCurrentLineComment()) { $data[] = $this->currentLine; } elseif (0 == $indent) { $this->moveToPreviousLine(); break; } else { throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); } } return \implode("\n", $data); }
Returns the next embed block of YAML. @param int|null $indentation The indent level at which the block is to be read, or null for default @param bool $inSequence True if the enclosing data structure is a sequence @throws ParseException When indentation problem are detected
getNextEmbedBlock
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function moveToNextLine() : bool { if ($this->currentLineNb >= $this->numberOfParsedLines - 1) { return \false; } $this->currentLine = $this->lines[++$this->currentLineNb]; return \true; }
Moves the parser to the next line.
moveToNextLine
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function moveToPreviousLine() : bool { if ($this->currentLineNb < 1) { return \false; } $this->currentLine = $this->lines[--$this->currentLineNb]; return \true; }
Moves the parser to the previous line.
moveToPreviousLine
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function parseValue(string $value, int $flags, string $context) : mixed { if (\str_starts_with($value, '*')) { if (\false !== ($pos = \strpos($value, '#'))) { $value = \substr($value, 1, $pos - 2); } else { $value = \substr($value, 1); } if (!\array_key_exists($value, $this->refs)) { if (\false !== ($pos = \array_search($value, $this->refsBeingParsed, \true))) { throw new ParseException(\sprintf('Circular reference [%s] detected for reference "%s".', \implode(', ', \array_merge(\array_slice($this->refsBeingParsed, $pos), [$value])), $value), $this->currentLineNb + 1, $this->currentLine, $this->filename); } throw new ParseException(\sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine, $this->filename); } return $this->refs[$value]; } if (\in_array($value[0], ['!', '|', '>'], \true) && self::preg_match('/^(?:' . self::TAG_PATTERN . ' +)?' . self::BLOCK_SCALAR_HEADER_PATTERN . '$/', $value, $matches)) { $modifiers = $matches['modifiers'] ?? ''; $data = $this->parseBlockScalar($matches['separator'], \preg_replace('#\\d+#', '', $modifiers), \abs((int) $modifiers)); if ('' !== $matches['tag'] && '!' !== $matches['tag']) { if ('!!binary' === $matches['tag']) { return Inline::evaluateBinaryScalar($data); } return new TaggedValue(\substr($matches['tag'], 1), $data); } return $data; } try { if ('' !== $value && '{' === $value[0]) { $cursor = \strlen(\rtrim($this->currentLine)) - \strlen(\rtrim($value)); return Inline::parse($this->lexInlineMapping($cursor), $flags, $this->refs); } elseif ('' !== $value && '[' === $value[0]) { $cursor = \strlen(\rtrim($this->currentLine)) - \strlen(\rtrim($value)); return Inline::parse($this->lexInlineSequence($cursor), $flags, $this->refs); } switch ($value[0] ?? '') { case '"': case "'": $cursor = \strlen(\rtrim($this->currentLine)) - \strlen(\rtrim($value)); $parsedValue = Inline::parse($this->lexInlineQuotedString($cursor), $flags, $this->refs); if (isset($this->currentLine[$cursor]) && \preg_replace('/\\s*(#.*)?$/A', '', \substr($this->currentLine, $cursor))) { throw new ParseException(\sprintf('Unexpected characters near "%s".', \substr($this->currentLine, $cursor))); } return $parsedValue; default: $lines = []; while ($this->moveToNextLine()) { // unquoted strings end before the first unindented line if (0 === $this->getCurrentLineIndentation()) { $this->moveToPreviousLine(); break; } $lines[] = \trim($this->currentLine); } for ($i = 0, $linesCount = \count($lines), $previousLineBlank = \false; $i < $linesCount; ++$i) { if ('' === $lines[$i]) { $value .= "\n"; $previousLineBlank = \true; } elseif ($previousLineBlank) { $value .= $lines[$i]; $previousLineBlank = \false; } else { $value .= ' ' . $lines[$i]; $previousLineBlank = \false; } } Inline::$parsedLineNumber = $this->getRealCurrentLineNb(); $parsedValue = Inline::parse($value, $flags, $this->refs); if ('mapping' === $context && \is_string($parsedValue) && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && \str_contains($parsedValue, ': ')) { throw new ParseException('A colon cannot be used in an unquoted mapping value.', $this->getRealCurrentLineNb() + 1, $value, $this->filename); } return $parsedValue; } } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); throw $e; } }
Parses a YAML value. @param string $value A YAML value @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior @param string $context The parser context (either sequence or mapping) @throws ParseException When reference does not exist
parseValue
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0) : string { $notEOF = $this->moveToNextLine(); if (!$notEOF) { return ''; } $isCurrentLineBlank = $this->isCurrentLineBlank(); $blockLines = []; // leading blank lines are consumed before determining indentation while ($notEOF && $isCurrentLineBlank) { // newline only if not EOF if ($notEOF = $this->moveToNextLine()) { $blockLines[] = ''; $isCurrentLineBlank = $this->isCurrentLineBlank(); } } // determine indentation if not specified if (0 === $indentation) { $currentLineLength = \strlen($this->currentLine); for ($i = 0; $i < $currentLineLength && ' ' === $this->currentLine[$i]; ++$i) { ++$indentation; } } if ($indentation > 0) { $pattern = \sprintf('/^ {%d}(.*)$/', $indentation); while ($notEOF && ($isCurrentLineBlank || self::preg_match($pattern, $this->currentLine, $matches))) { if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) { $blockLines[] = \substr($this->currentLine, $indentation); } elseif ($isCurrentLineBlank) { $blockLines[] = ''; } else { $blockLines[] = $matches[1]; } // newline only if not EOF if ($notEOF = $this->moveToNextLine()) { $isCurrentLineBlank = $this->isCurrentLineBlank(); } } } elseif ($notEOF) { $blockLines[] = ''; } if ($notEOF) { $blockLines[] = ''; $this->moveToPreviousLine(); } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) { $blockLines[] = ''; } // folded style if ('>' === $style) { $text = ''; $previousLineIndented = \false; $previousLineBlank = \false; for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) { if ('' === $blockLines[$i]) { $text .= "\n"; $previousLineIndented = \false; $previousLineBlank = \true; } elseif (' ' === $blockLines[$i][0]) { $text .= "\n" . $blockLines[$i]; $previousLineIndented = \true; $previousLineBlank = \false; } elseif ($previousLineIndented) { $text .= "\n" . $blockLines[$i]; $previousLineIndented = \false; $previousLineBlank = \false; } elseif ($previousLineBlank || 0 === $i) { $text .= $blockLines[$i]; $previousLineIndented = \false; $previousLineBlank = \false; } else { $text .= ' ' . $blockLines[$i]; $previousLineIndented = \false; $previousLineBlank = \false; } } } else { $text = \implode("\n", $blockLines); } // deal with trailing newlines if ('' === $chomping) { $text = \preg_replace('/\\n+$/', "\n", $text); } elseif ('-' === $chomping) { $text = \preg_replace('/\\n+$/', '', $text); } return $text; }
Parses a block scalar. @param string $style The style indicator that was used to begin this block scalar (| or >) @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -) @param int $indentation The indentation indicator that was used to begin this block scalar
parseBlockScalar
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function isNextLineIndented() : bool { $currentIndentation = $this->getCurrentLineIndentation(); $movements = 0; do { $EOF = !$this->moveToNextLine(); if (!$EOF) { ++$movements; } } while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment())); if ($EOF) { for ($i = 0; $i < $movements; ++$i) { $this->moveToPreviousLine(); } return \false; } $ret = $this->getCurrentLineIndentation() > $currentIndentation; for ($i = 0; $i < $movements; ++$i) { $this->moveToPreviousLine(); } return $ret; }
Returns true if the next line is indented.
isNextLineIndented
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
public static function preg_match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : int { if (\false === ($ret = \preg_match($pattern, $subject, $matches, $flags, $offset))) { throw new ParseException(\preg_last_error_msg()); } return $ret; }
A local wrapper for "preg_match" which will throw a ParseException if there is an internal error in the PCRE engine. This avoids us needing to check for "false" every time PCRE is used in the YAML engine @throws ParseException on a PCRE internal error @internal
preg_match
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
private function trimTag(string $value) : string { if ('!' === $value[0]) { return \ltrim(\substr($value, 1, \strcspn($value, " \r\n", 1)), ' '); } return $value; }
Trim the tag on top of the value. Prevent values such as "!foo {quz: bar}" to be considered as a mapping block.
trimTag
php
deptrac/deptrac
vendor/symfony/yaml/Parser.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Parser.php
MIT
public function unescapeSingleQuotedString(string $value) : string { return \str_replace('\'\'', '\'', $value); }
Unescapes a single quoted string. @param string $value A single quoted string
unescapeSingleQuotedString
php
deptrac/deptrac
vendor/symfony/yaml/Unescaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Unescaper.php
MIT
public function unescapeDoubleQuotedString(string $value) : string { $callback = fn($match) => $this->unescapeCharacter($match[0]); // evaluate the string return \preg_replace_callback('/' . self::REGEX_ESCAPED_CHARACTER . '/u', $callback, $value); }
Unescapes a double quoted string. @param string $value A double quoted string
unescapeDoubleQuotedString
php
deptrac/deptrac
vendor/symfony/yaml/Unescaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Unescaper.php
MIT
private static function utf8chr(int $c) : string { if (0x80 > ($c %= 0x200000)) { return \chr($c); } if (0x800 > $c) { return \chr(0xc0 | $c >> 6) . \chr(0x80 | $c & 0x3f); } if (0x10000 > $c) { return \chr(0xe0 | $c >> 12) . \chr(0x80 | $c >> 6 & 0x3f) . \chr(0x80 | $c & 0x3f); } return \chr(0xf0 | $c >> 18) . \chr(0x80 | $c >> 12 & 0x3f) . \chr(0x80 | $c >> 6 & 0x3f) . \chr(0x80 | $c & 0x3f); }
Get the UTF-8 character for the given code point.
utf8chr
php
deptrac/deptrac
vendor/symfony/yaml/Unescaper.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Unescaper.php
MIT
public static function parseFile(string $filename, int $flags = 0) : mixed { $yaml = new Parser(); return $yaml->parseFile($filename, $flags); }
Parses a YAML file into a PHP value. Usage: $array = Yaml::parseFile('config.yml'); print_r($array); @param string $filename The path to the YAML file to be parsed @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior @throws ParseException If the file could not be read or the YAML is not valid
parseFile
php
deptrac/deptrac
vendor/symfony/yaml/Yaml.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Yaml.php
MIT
public static function parse(string $input, int $flags = 0) : mixed { $yaml = new Parser(); return $yaml->parse($input, $flags); }
Parses YAML into a PHP value. Usage: <code> $array = Yaml::parse(file_get_contents('config.yml')); print_r($array); </code> @param string $input A string containing YAML @param int $flags A bit field of PARSE_* constants to customize the YAML parser behavior @throws ParseException If the YAML is not valid
parse
php
deptrac/deptrac
vendor/symfony/yaml/Yaml.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Yaml.php
MIT
public static function dump(mixed $input, int $inline = 2, int $indent = 4, int $flags = 0) : string { $yaml = new Dumper($indent); return $yaml->dump($input, $inline, 0, $flags); }
Dumps a PHP value to a YAML string. The dump method, when supplied with an array, will do its best to convert the array into friendly YAML. @param mixed $input The PHP value @param int $inline The level where you switch to inline YAML @param int $indent The amount of spaces to use for indentation of nested nodes @param int $flags A bit field of DUMP_* constants to customize the dumped YAML string
dump
php
deptrac/deptrac
vendor/symfony/yaml/Yaml.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Yaml.php
MIT
public function __construct(string $message, int $parsedLine = -1, ?string $snippet = null, ?string $parsedFile = null, ?\Throwable $previous = null) { $this->parsedFile = $parsedFile; $this->parsedLine = $parsedLine; $this->snippet = $snippet; $this->rawMessage = $message; $this->updateRepr(); parent::__construct($this->message, 0, $previous); }
@param string $message The error message @param int $parsedLine The line where the error occurred @param string|null $snippet The snippet of code near the problem @param string|null $parsedFile The file name where the error occurred
__construct
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function getSnippet() : string { return $this->snippet; }
Gets the snippet of code near the error.
getSnippet
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function setSnippet(string $snippet) { $this->snippet = $snippet; $this->updateRepr(); }
Sets the snippet of code near the error. @return void
setSnippet
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function getParsedFile() : string { return $this->parsedFile; }
Gets the filename where the error occurred. This method returns null if a string is parsed.
getParsedFile
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function setParsedFile(string $parsedFile) { $this->parsedFile = $parsedFile; $this->updateRepr(); }
Sets the filename where the error occurred. @return void
setParsedFile
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function getParsedLine() : int { return $this->parsedLine; }
Gets the line where the error occurred.
getParsedLine
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function setParsedLine(int $parsedLine) { $this->parsedLine = $parsedLine; $this->updateRepr(); }
Sets the line where the error occurred. @return void
setParsedLine
php
deptrac/deptrac
vendor/symfony/yaml/Exception/ParseException.php
https://github.com/deptrac/deptrac/blob/master/vendor/symfony/yaml/Exception/ParseException.php
MIT
public function __construct(DropboxApp $app, array $config = []) { //Configuration $config = array_merge([ 'http_client_handler' => null, 'random_string_generator' => null, 'persistent_data_store' => null ], $config); //Set the app $this->app = $app; //Set the access token $this->setAccessToken($app->getAccessToken()); //Make the HTTP Client $httpClient = DropboxHttpClientFactory::make($config['http_client_handler']); //Make and Set the DropboxClient $this->client = new DropboxClient($httpClient); //Make and Set the Random String Generator $this->randomStringGenerator = RandomStringGeneratorFactory::makeRandomStringGenerator($config['random_string_generator']); //Make and Set the Persistent Data Store $this->persistentDataStore = PersistentDataStoreFactory::makePersistentDataStore($config['persistent_data_store']); }
Create a new Dropbox instance @param \Kunnu\Dropbox\DropboxApp @param array $config Configuration Array @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
__construct
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getAuthHelper() { return new DropboxAuthHelper( $this->getOAuth2Client(), $this->getRandomStringGenerator(), $this->getPersistentDataStore() ); }
Get Dropbox Auth Helper @return \Kunnu\Dropbox\Authentication\DropboxAuthHelper
getAuthHelper
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getApp() { return $this->app; }
Get the Dropbox App. @return \Kunnu\Dropbox\DropboxApp Dropbox App
getApp
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getClient() { return $this->client; }
Get the Client @return \Kunnu\Dropbox\DropboxClient
getClient
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getRandomStringGenerator() { return $this->randomStringGenerator; }
Get the Random String Generator @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
getRandomStringGenerator
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getPersistentDataStore() { return $this->persistentDataStore; }
Get Persistent Data Store @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface
getPersistentDataStore
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getMetadata($path, array $params = []) { //Root folder is unsupported if ($path === '/') { throw new DropboxClientException("Metadata for the root folder is unsupported."); } //Set the path $params['path'] = $path; //Get File Metadata $response = $this->postToAPI('/files/get_metadata', $params); //Make and Return the Model return $this->makeModelFromResponse($response); }
Get the Metadata for a file or folder @param string $path Path of the file or folder @param array $params Additional Params @return \Kunnu\Dropbox\Models\FileMetadata | \Kunnu\Dropbox\Models\FolderMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
getMetadata
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function postToAPI($endpoint, array $params = [], $accessToken = null) { return $this->sendRequest("POST", $endpoint, 'api', $params, $accessToken); }
Make a HTTP POST Request to the API endpoint type @param string $endpoint API Endpoint to send Request to @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @return \Kunnu\Dropbox\DropboxResponse @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
postToAPI
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function sendRequest($method, $endpoint, $endpointType = 'api', array $params = [], $accessToken = null, DropboxFile $responseFile = null) { //Access Token $accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken; //Make a DropboxRequest object $request = new DropboxRequest($method, $endpoint, $accessToken, $endpointType, $params); //Make a DropboxResponse object if a response should be saved to the file $response = $responseFile ? new DropboxResponseToFile($request, $responseFile) : null; //Send Request through the DropboxClient //Fetch and return the Response return $this->getClient()->sendRequest($request, $response); }
Make Request to the API @param string $method HTTP Request Method @param string $endpoint API Endpoint to send Request to @param string $endpointType Endpoint type ['api'|'content'] @param array $params Request Query Params @param string $accessToken Access Token to send with the Request @param DropboxFile $responseFile Save response to the file @return \Kunnu\Dropbox\DropboxResponse @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
sendRequest
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getAccessToken() { return $this->accessToken; }
Get the Access Token. @return string Access Token
getAccessToken
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function setAccessToken($accessToken) { $this->accessToken = $accessToken; return $this; }
Set the Access Token. @param string $accessToken Access Token @return \Kunnu\Dropbox\Dropbox Dropbox Client
setAccessToken
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function makeModelFromResponse(DropboxResponse $response) { //Get the Decoded Body $body = $response->getDecodedBody(); if (is_null($body)) { $body = []; } //Make and Return the Model return ModelFactory::make($body); }
Make Model from DropboxResponse @param DropboxResponse $response @return \Kunnu\Dropbox\Models\ModelInterface @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
makeModelFromResponse
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function listFolder($path = null, array $params = []) { //Specify the root folder as an //empty string rather than as "/" if ($path === '/') { $path = ""; } //Set the path $params['path'] = $path; //Get File Metadata $response = $this->postToAPI('/files/list_folder', $params); //Make and Return the Model return $this->makeModelFromResponse($response); }
Get the contents of a Folder @param string $path Path to the folder. Defaults to root. @param array $params Additional Params @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder @return \Kunnu\Dropbox\Models\MetadataCollection @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
listFolder
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function listFolderContinue($cursor) { $response = $this->postToAPI('/files/list_folder/continue', ['cursor' => $cursor]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Paginate through all files and retrieve updates to the folder, using the cursor retrieved from listFolder or listFolderContinue @param string $cursor The cursor returned by your last call to listFolder or listFolderContinue @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue @return \Kunnu\Dropbox\Models\MetadataCollection @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
listFolderContinue
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function listFolderLatestCursor($path, array $params = []) { //Specify the root folder as an //empty string rather than as "/" if ($path === '/') { $path = ""; } //Set the path $params['path'] = $path; //Fetch the cursor $response = $this->postToAPI('/files/list_folder/get_latest_cursor', $params); //Retrieve the cursor $body = $response->getDecodedBody(); $cursor = isset($body['cursor']) ? $body['cursor'] : false; //No cursor returned if (!$cursor) { throw new DropboxClientException("Could not retrieve cursor. Something went wrong."); } //Return the cursor return $cursor; }
Get a cursor for the folder's state. @param string $path Path to the folder. Defaults to root. @param array $params Additional Params @return string The Cursor for the folder's state @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor
listFolderLatestCursor
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function listRevisions($path, array $params = []) { //Set the Path $params['path'] = $path; //Fetch the Revisions $response = $this->postToAPI('/files/list_revisions', $params); //The file metadata of the entries, returned by this //endpoint doesn't include a '.tag' attribute, which //is used by the ModelFactory to resolve the correct //model. But since we know that revisions returned //are file metadata objects, we can explicitly cast //them as \Kunnu\Dropbox\Models\FileMetadata manually. $body = $response->getDecodedBody(); $entries = isset($body['entries']) ? $body['entries'] : []; $processedEntries = []; foreach ($entries as $entry) { $processedEntries[] = new FileMetadata($entry); } return new ModelCollection($processedEntries); }
Get Revisions of a File @param string $path Path to the file @param array $params Additional Params @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_revisions @return \Kunnu\Dropbox\Models\ModelCollection @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
listRevisions
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function search($path, $query, array $params = []) { //Specify the root folder as an //empty string rather than as "/" if ($path === '/') { $path = ""; } //Set the path and query $params['path'] = $path; $params['query'] = $query; //Fetch Search Results $response = $this->postToAPI('/files/search', $params); //Make and Return the Model return $this->makeModelFromResponse($response); }
Search a folder for files/folders @param string $path Path to search @param string $query Search Query @param array $params Additional Params @link https://www.dropbox.com/developers/documentation/http/documentation#files-search @return \Kunnu\Dropbox\Models\SearchResults @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
search
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function createFolder($path, $autorename = false) { //Path cannot be null if (is_null($path)) { throw new DropboxClientException("Path cannot be null."); } //Create Folder $response = $this->postToAPI('/files/create_folder', ['path' => $path, 'autorename' => $autorename]); //Fetch the Metadata $body = $response->getDecodedBody(); //Make and Return the Model return new FolderMetadata($body); }
Create a folder at the given path @param string $path Path to create @param boolean $autorename Auto Rename File @return \Kunnu\Dropbox\Models\FolderMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
createFolder
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function delete($path) { //Path cannot be null if (is_null($path)) { throw new DropboxClientException("Path cannot be null."); } //Delete $response = $this->postToAPI('/files/delete_v2', ['path' => $path]); $body = $response->getDecodedBody(); //Response doesn't have Metadata if (!isset($body['metadata']) || !is_array($body['metadata'])) { throw new DropboxClientException("Invalid Response."); } return new DeletedMetadata($body['metadata']); }
Delete a file or folder at the given path @param string $path Path to file/folder to delete @return \Kunnu\Dropbox\Models\DeletedMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
delete
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function move($fromPath, $toPath) { //From and To paths cannot be null if (is_null($fromPath) || is_null($toPath)) { throw new DropboxClientException("From and To paths cannot be null."); } //Response $response = $this->postToAPI('/files/move', ['from_path' => $fromPath, 'to_path' => $toPath]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Move a file or folder to a different location @param string $fromPath Path to be moved @param string $toPath Path to be moved to @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
move
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function copy($fromPath, $toPath) { //From and To paths cannot be null if (is_null($fromPath) || is_null($toPath)) { throw new DropboxClientException("From and To paths cannot be null."); } //Response $response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Copy a file or folder to a different location @param string $fromPath Path to be copied @param string $toPath Path to be copied to @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
copy
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function restore($path, $rev) { //Path and Revision cannot be null if (is_null($path) || is_null($rev)) { throw new DropboxClientException("Path and Revision cannot be null."); } //Response $response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]); //Fetch the Metadata $body = $response->getDecodedBody(); //Make and Return the Model return new FileMetadata($body); }
Restore a file to the specific version @param string $path Path to the file to restore @param string $rev Revision to store for the file @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-restore
restore
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getCopyReference($path) { //Path cannot be null if (is_null($path)) { throw new DropboxClientException("Path cannot be null."); } //Get Copy Reference $response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]); $body = $response->getDecodedBody(); //Make and Return the Model return new CopyReference($body); }
Get Copy Reference @param string $path Path to the file or folder to get a copy reference to @return \Kunnu\Dropbox\Models\CopyReference @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get
getCopyReference
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function saveCopyReference($path, $copyReference) { //Path and Copy Reference cannot be null if (is_null($path) || is_null($copyReference)) { throw new DropboxClientException("Path and Copy Reference cannot be null."); } //Save Copy Reference $response = $this->postToAPI('/files/copy_reference/save', ['path' => $path, 'copy_reference' => $copyReference]); $body = $response->getDecodedBody(); //Response doesn't have Metadata if (!isset($body['metadata']) || !is_array($body['metadata'])) { throw new DropboxClientException("Invalid Response."); } //Make and return the Model return ModelFactory::make($body['metadata']); }
Save Copy Reference @param string $path Path to the file or folder to get a copy reference to @param string $copyReference Copy reference returned by getCopyReference @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save
saveCopyReference
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function getTemporaryLink($path) { //Path cannot be null if (is_null($path)) { throw new DropboxClientException("Path cannot be null."); } //Get Temporary Link $response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]); //Make and Return the Model return $this->makeModelFromResponse($response); }
Get a temporary link to stream contents of a file @param string $path Path to the file you want a temporary link to https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link @return \Kunnu\Dropbox\Models\TemporaryLink @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
getTemporaryLink
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function saveUrl($path, $url) { //Path and URL cannot be null if (is_null($path) || is_null($url)) { throw new DropboxClientException("Path and URL cannot be null."); } //Save URL $response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]); $body = $response->getDecodedBody(); if (!isset($body['async_job_id'])) { throw new DropboxClientException("Could not retrieve Async Job ID."); } //Return the Async Job ID return $body['async_job_id']; }
Save a specified URL into a file in user's Dropbox @param string $path Path where the URL will be saved @param string $url URL to be saved @return string Async Job ID @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
saveUrl
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function checkJobStatus($asyncJobId) { //Async Job ID cannot be null if (is_null($asyncJobId)) { throw new DropboxClientException("Async Job ID cannot be null."); } //Get Job Status $response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]); $body = $response->getDecodedBody(); //Status $status = isset($body['.tag']) ? $body['.tag'] : ''; //If status is complete if ($status === 'complete') { return new FileMetadata($body); } //Return the status return $status; }
Save a specified URL into a file in user's Dropbox @param $asyncJobId @return \Kunnu\Dropbox\Models\FileMetadata|string Status (failed|in_progress) or FileMetadata (if complete) @throws \Kunnu\Dropbox\Exceptions\DropboxClientException @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url-check_job_status
checkJobStatus
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function upload($dropboxFile, $path, array $params = []) { //Make Dropbox File $dropboxFile = $this->makeDropboxFile($dropboxFile); //If the file is larger than the Chunked Upload Threshold if ($dropboxFile->getSize() > static::AUTO_CHUNKED_UPLOAD_THRESHOLD) { //Upload the file in sessions/chunks return $this->uploadChunked($dropboxFile, $path, null, null, $params); } //Simple file upload return $this->simpleUpload($dropboxFile, $path, $params); }
Upload a File to Dropbox @param string|DropboxFile $dropboxFile DropboxFile object or Path to file @param string $path Path to upload the file to @param array $params Additional Params @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload @return \Kunnu\Dropbox\Models\FileMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
upload
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function makeDropboxFile($dropboxFile, $maxLength = null, $offset = null, $mode = DropboxFile::MODE_READ) { //Uploading file by file path if (!$dropboxFile instanceof DropboxFile) { //Create a DropboxFile Object $dropboxFile = new DropboxFile($dropboxFile, $mode); } elseif ($mode !== $dropboxFile->getMode()) { //Reopen the file with expected mode $dropboxFile->close(); $dropboxFile = new DropboxFile($dropboxFile->getFilePath(), $mode); } if (!is_null($offset)) { $dropboxFile->setOffset($offset); } if (!is_null($maxLength)) { $dropboxFile->setMaxLength($maxLength); } //Return the DropboxFile Object return $dropboxFile; }
Make DropboxFile Object @param string|DropboxFile $dropboxFile DropboxFile object or Path to file @param int $maxLength Max Bytes to read from the file @param int $offset Seek to specified offset before reading @param string $mode The type of access @return \Kunnu\Dropbox\DropboxFile
makeDropboxFile
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT
public function uploadChunked($dropboxFile, $path, $fileSize = null, $chunkSize = null, array $params = array()) { //Make Dropbox File $dropboxFile = $this->makeDropboxFile($dropboxFile); //No file size specified explicitly if (is_null($fileSize)) { $fileSize = $dropboxFile->getSize(); } //No chunk size specified, use default size if (is_null($chunkSize)) { $chunkSize = static::DEFAULT_CHUNK_SIZE; } //If the fileSize is smaller //than the chunk size, we'll //make the chunk size relatively //smaller than the file size if ($fileSize <= $chunkSize) { $chunkSize = intval($fileSize / 2); } //Start the Upload Session with the file path //since the DropboxFile object will be created //again using the new chunk size. $sessionId = $this->startUploadSession($dropboxFile->getFilePath(), $chunkSize); //Uploaded $uploaded = $chunkSize; //Remaining $remaining = $fileSize - $chunkSize; //While the remaining bytes are //more than the chunk size, append //the chunk to the upload session. while ($remaining > $chunkSize) { //Append the next chunk to the Upload session $sessionId = $this->appendUploadSession($dropboxFile, $sessionId, $uploaded, $chunkSize); //Update remaining and uploaded $uploaded = $uploaded + $chunkSize; $remaining = $remaining - $chunkSize; } //Finish the Upload Session and return the Uploaded File Metadata return $this->finishUploadSession($dropboxFile, $sessionId, $uploaded, $remaining, $path, $params); }
Upload file in sessions/chunks @param string|DropboxFile $dropboxFile DropboxFile object or Path to file @param string $path Path to save the file to, on Dropbox @param int $fileSize The size of the file @param int $chunkSize The amount of data to upload in each chunk @param array $params Additional Params @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2 @return \Kunnu\Dropbox\Models\FileMetadata @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
uploadChunked
php
kunalvarma05/dropbox-php-sdk
src/Dropbox/Dropbox.php
https://github.com/kunalvarma05/dropbox-php-sdk/blob/master/src/Dropbox/Dropbox.php
MIT