This commit is contained in:
2026-10-06 18:51:23 -06:00
parent 8424dacd03
commit e2c26b7f21
4223 changed files with 737986 additions and 53 deletions
+22
View File
@@ -0,0 +1,22 @@
<?php
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
throw new RuntimeException($err);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitaed462212d3f4c500a68ea77cbd9569f::getLoader();
@@ -0,0 +1,579 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see https://www.php-fig.org/psr/psr-0/
* @see https://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
/** @var \Closure(string):void */
private static $includeFile;
/** @var string|null */
private $vendorDir;
// PSR-4
/**
* @var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array<string, list<string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* List of PSR-0 prefixes
*
* Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2')))
*
* @var array<string, array<string, list<string>>>
*/
private $prefixesPsr0 = array();
/**
* @var list<string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var array<string, bool>
*/
private $missingClasses = array();
/** @var string|null */
private $apcuPrefix;
/**
* @var array<string, self>
*/
private static $registeredLoaders = array();
/**
* @param string|null $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array<string, list<string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return list<string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return list<string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return array<string, string> Array of classname => path
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array<string, string> $classMap Class to filename map
*
* @return void
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*
* @return void
*/
public function add($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
$paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
$paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
$paths = (array) $paths;
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
$paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
$paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
$paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param list<string>|string $paths The PSR-0 base directories
*
* @return void
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param list<string>|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*
* @return void
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*
* @return void
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*
* @return void
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*
* @return void
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
}
/**
* Unregisters this instance as an autoloader.
*
* @return void
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return true|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
$includeFile = self::$includeFile;
$includeFile($file);
return true;
}
return null;
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
/**
* Returns the currently registered loaders keyed by their corresponding vendor directories.
*
* @return array<string, self>
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = \Closure::bind(static function($file) {
include $file;
}, null, null);
}
}
@@ -0,0 +1,345 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Composer;
use JooosiFonDeps\Composer\Autoload\ClassLoader;
use JooosiFonDeps\Composer\Semver\VersionParser;
/**
* This class is copied in every Composer installed project and available to all
*
* See also https://getcomposer.org/doc/07-runtime.md#installed-versions
*
* To require its presence, you can require `composer-runtime-api ^2.0`
*
* @final
*/
class InstalledVersions
{
/**
* @var string|null if set (by reflection by Composer), this should be set to the path where this class is being copied to
* @internal
*/
private static $selfDir = null;
/**
* @var mixed[]|null
* @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}|array{}|null
*/
private static $installed;
/**
* @var bool
*/
private static $installedIsLocalDir;
/**
* @var bool|null
*/
private static $canGetVendors;
/**
* @var array[]
* @psalm-var array<string, array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static $installedByVendor = array();
/**
* Returns a list of all package names which are present, either by being installed, replaced or provided
*
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackages()
{
$packages = array();
foreach (self::getInstalled() as $installed) {
$packages[] = array_keys($installed['versions']);
}
if (1 === \count($packages)) {
return $packages[0];
}
return array_keys(array_flip(\call_user_func_array('array_merge', $packages)));
}
/**
* Returns a list of all package names with a specific type e.g. 'library'
*
* @param string $type
* @return string[]
* @psalm-return list<string>
*/
public static function getInstalledPackagesByType($type)
{
$packagesByType = array();
foreach (self::getInstalled() as $installed) {
foreach ($installed['versions'] as $name => $package) {
if (isset($package['type']) && $package['type'] === $type) {
$packagesByType[] = $name;
}
}
}
return $packagesByType;
}
/**
* Checks whether the given package is installed
*
* This also returns true if the package name is provided or replaced by another package
*
* @param string $packageName
* @param bool $includeDevRequirements
* @return bool
*/
public static function isInstalled($packageName, $includeDevRequirements = \true)
{
foreach (self::getInstalled() as $installed) {
if (isset($installed['versions'][$packageName])) {
return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === \false;
}
}
return \false;
}
/**
* Checks whether the given package satisfies a version constraint
*
* e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call:
*
* Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3')
*
* @param VersionParser $parser Install composer/semver to have access to this class and functionality
* @param string $packageName
* @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package
* @return bool
*/
public static function satisfies(VersionParser $parser, $packageName, $constraint)
{
$constraint = $parser->parseConstraints((string) $constraint);
$provided = $parser->parseConstraints(self::getVersionRanges($packageName));
return $provided->matches($constraint);
}
/**
* Returns a version constraint representing all the range(s) which are installed for a given package
*
* It is easier to use this via isInstalled() with the $constraint argument if you need to check
* whether a given version of a package is installed, and not just whether it exists
*
* @param string $packageName
* @return string Version constraint usable with composer/semver
*/
public static function getVersionRanges($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
$ranges = array();
if (isset($installed['versions'][$packageName]['pretty_version'])) {
$ranges[] = $installed['versions'][$packageName]['pretty_version'];
}
if (array_key_exists('aliases', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']);
}
if (array_key_exists('replaced', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']);
}
if (array_key_exists('provided', $installed['versions'][$packageName])) {
$ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']);
}
return implode(' || ', $ranges);
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['version'])) {
return null;
}
return $installed['versions'][$packageName]['version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present
*/
public static function getPrettyVersion($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['pretty_version'])) {
return null;
}
return $installed['versions'][$packageName]['pretty_version'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference
*/
public static function getReference($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
if (!isset($installed['versions'][$packageName]['reference'])) {
return null;
}
return $installed['versions'][$packageName]['reference'];
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @param string $packageName
* @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path.
*/
public static function getInstallPath($packageName)
{
foreach (self::getInstalled() as $installed) {
if (!isset($installed['versions'][$packageName])) {
continue;
}
return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null;
}
throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed');
}
/**
* @return array
* @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
public static function getRootPackage()
{
$installed = self::getInstalled();
return $installed[0]['root'];
}
/**
* Returns the raw installed.php data for custom implementations
*
* @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect.
* @return array[]
* @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
public static function getRawData()
{
@trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', \E_USER_DEPRECATED);
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
self::$installed = include __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
return self::$installed;
}
/**
* Returns the raw data of all installed.php which are currently loaded for custom implementations
*
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
public static function getAllRawData()
{
return self::getInstalled();
}
/**
* Lets you reload the static array from another file
*
* This is only useful for complex integrations in which a project needs to use
* this class but then also needs to execute another project's autoloader in process,
* and wants to ensure both projects have access to their version of installed.php.
*
* A typical case would be PHPUnit, where it would need to make sure it reads all
* the data it needs from this class, then call reload() with
* `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure
* the project in which it runs can then also use this class safely, without
* interference between PHPUnit's dependencies and the project's dependencies.
*
* @param array[] $data A vendor/composer/installed.php data set
* @return void
*
* @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $data
*/
public static function reload($data)
{
self::$installed = $data;
self::$installedByVendor = array();
// when using reload, we disable the duplicate protection to ensure that self::$installed data is
// always returned, but we cannot know whether it comes from the installed.php in __DIR__ or not,
// so we have to assume it does not, and that may result in duplicate data being returned when listing
// all installed packages for example
self::$installedIsLocalDir = \false;
}
/**
* @return string
*/
private static function getSelfDir()
{
if (self::$selfDir === null) {
self::$selfDir = strtr(__DIR__, '\\', '/');
}
return self::$selfDir;
}
/**
* @return array[]
* @psalm-return list<array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}>
*/
private static function getInstalled()
{
if (null === self::$canGetVendors) {
self::$canGetVendors = method_exists('JooosiFonDeps\Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
$copiedLocalDir = \false;
if (self::$canGetVendors) {
$selfDir = self::getSelfDir();
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
$vendorDir = strtr($vendorDir, '\\', '/');
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir . '/composer/installed.php')) {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require $vendorDir . '/composer/installed.php';
self::$installedByVendor[$vendorDir] = $required;
$installed[] = $required;
if (self::$installed === null && $vendorDir . '/composer' === $selfDir) {
self::$installed = $required;
self::$installedIsLocalDir = \true;
}
}
if (self::$installedIsLocalDir && $vendorDir . '/composer' === $selfDir) {
$copiedLocalDir = \true;
}
}
}
if (null === self::$installed) {
// only require the installed.php file if this file is loaded from its dumped location,
// and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937
if (substr(__DIR__, -8, 1) !== 'C') {
/** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>} $required */
$required = require __DIR__ . '/installed.php';
self::$installed = $required;
} else {
self::$installed = array();
}
}
if (self::$installed !== array() && !$copiedLocalDir) {
$installed[] = self::$installed;
}
return $installed;
}
}
+21
View File
@@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,226 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Client' => $vendorDir . '/hidehalo/nanoid-php/src/Client.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Core' => $vendorDir . '/hidehalo/nanoid-php/src/Core.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\CoreInterface' => $vendorDir . '/hidehalo/nanoid-php/src/CoreInterface.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Generator' => $vendorDir . '/hidehalo/nanoid-php/src/Generator.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\GeneratorInterface' => $vendorDir . '/hidehalo/nanoid-php/src/GeneratorInterface.php',
'JooosiFonDeps\\Psr\\Container\\ContainerExceptionInterface' => $vendorDir . '/psr/container/src/ContainerExceptionInterface.php',
'JooosiFonDeps\\Psr\\Container\\ContainerInterface' => $vendorDir . '/psr/container/src/ContainerInterface.php',
'JooosiFonDeps\\Psr\\Container\\NotFoundExceptionInterface' => $vendorDir . '/psr/container/src/NotFoundExceptionInterface.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\AtRuleBlockList' => $vendorDir . '/sabberworm/php-css-parser/src/CSSList/AtRuleBlockList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\CSSBlockList' => $vendorDir . '/sabberworm/php-css-parser/src/CSSList/CSSBlockList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\CSSList' => $vendorDir . '/sabberworm/php-css-parser/src/CSSList/CSSList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\Document' => $vendorDir . '/sabberworm/php-css-parser/src/CSSList/Document.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\KeyFrame' => $vendorDir . '/sabberworm/php-css-parser/src/CSSList/KeyFrame.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Comment\\Comment' => $vendorDir . '/sabberworm/php-css-parser/src/Comment/Comment.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Comment\\Commentable' => $vendorDir . '/sabberworm/php-css-parser/src/Comment/Commentable.php',
'JooosiFonDeps\\Sabberworm\\CSS\\OutputFormat' => $vendorDir . '/sabberworm/php-css-parser/src/OutputFormat.php',
'JooosiFonDeps\\Sabberworm\\CSS\\OutputFormatter' => $vendorDir . '/sabberworm/php-css-parser/src/OutputFormatter.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parser' => $vendorDir . '/sabberworm/php-css-parser/src/Parser.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\Anchor' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/Anchor.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\OutputException' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/OutputException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\ParserState' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/ParserState.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\SourceException' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/SourceException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\UnexpectedEOFException' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/UnexpectedEOFException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\UnexpectedTokenException' => $vendorDir . '/sabberworm/php-css-parser/src/Parsing/UnexpectedTokenException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\AtRule' => $vendorDir . '/sabberworm/php-css-parser/src/Property/AtRule.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\CSSNamespace' => $vendorDir . '/sabberworm/php-css-parser/src/Property/CSSNamespace.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Charset' => $vendorDir . '/sabberworm/php-css-parser/src/Property/Charset.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Import' => $vendorDir . '/sabberworm/php-css-parser/src/Property/Import.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\KeyframeSelector' => $vendorDir . '/sabberworm/php-css-parser/src/Property/KeyframeSelector.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Selector' => $vendorDir . '/sabberworm/php-css-parser/src/Property/Selector.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Renderable' => $vendorDir . '/sabberworm/php-css-parser/src/Renderable.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\AtRuleSet' => $vendorDir . '/sabberworm/php-css-parser/src/RuleSet/AtRuleSet.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\DeclarationBlock' => $vendorDir . '/sabberworm/php-css-parser/src/RuleSet/DeclarationBlock.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\RuleSet' => $vendorDir . '/sabberworm/php-css-parser/src/RuleSet/RuleSet.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Rule\\Rule' => $vendorDir . '/sabberworm/php-css-parser/src/Rule/Rule.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Settings' => $vendorDir . '/sabberworm/php-css-parser/src/Settings.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CSSFunction' => $vendorDir . '/sabberworm/php-css-parser/src/Value/CSSFunction.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CSSString' => $vendorDir . '/sabberworm/php-css-parser/src/Value/CSSString.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CalcFunction' => $vendorDir . '/sabberworm/php-css-parser/src/Value/CalcFunction.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CalcRuleValueList' => $vendorDir . '/sabberworm/php-css-parser/src/Value/CalcRuleValueList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Color' => $vendorDir . '/sabberworm/php-css-parser/src/Value/Color.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\LineName' => $vendorDir . '/sabberworm/php-css-parser/src/Value/LineName.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\PrimitiveValue' => $vendorDir . '/sabberworm/php-css-parser/src/Value/PrimitiveValue.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\RuleValueList' => $vendorDir . '/sabberworm/php-css-parser/src/Value/RuleValueList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Size' => $vendorDir . '/sabberworm/php-css-parser/src/Value/Size.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\URL' => $vendorDir . '/sabberworm/php-css-parser/src/Value/URL.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Value' => $vendorDir . '/sabberworm/php-css-parser/src/Value/Value.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\ValueList' => $vendorDir . '/sabberworm/php-css-parser/src/Value/ValueList.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\Comparator' => $vendorDir . '/symfony/finder/Comparator/Comparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\DateComparator' => $vendorDir . '/symfony/finder/Comparator/DateComparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\NumberComparator' => $vendorDir . '/symfony/finder/Comparator/NumberComparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => $vendorDir . '/symfony/finder/Exception/AccessDeniedException.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Exception\\DirectoryNotFoundException' => $vendorDir . '/symfony/finder/Exception/DirectoryNotFoundException.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Finder' => $vendorDir . '/symfony/finder/Finder.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Gitignore' => $vendorDir . '/symfony/finder/Gitignore.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Glob' => $vendorDir . '/symfony/finder/Glob.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => $vendorDir . '/symfony/finder/Iterator/CustomFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => $vendorDir . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\LazyIterator' => $vendorDir . '/symfony/finder/Iterator/LazyIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => $vendorDir . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => $vendorDir . '/symfony/finder/Iterator/PathFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => $vendorDir . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\SortableIterator' => $vendorDir . '/symfony/finder/Iterator/SortableIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\VcsIgnoredFilterIterator' => $vendorDir . '/symfony/finder/Iterator/VcsIgnoredFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\SplFileInfo' => $vendorDir . '/symfony/finder/SplFileInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\AccessException' => $vendorDir . '/symfony/property-access/Exception/AccessException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/property-access/Exception/ExceptionInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/property-access/Exception/InvalidArgumentException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\InvalidPropertyPathException' => $vendorDir . '/symfony/property-access/Exception/InvalidPropertyPathException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\NoSuchIndexException' => $vendorDir . '/symfony/property-access/Exception/NoSuchIndexException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\NoSuchPropertyException' => $vendorDir . '/symfony/property-access/Exception/NoSuchPropertyException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\OutOfBoundsException' => $vendorDir . '/symfony/property-access/Exception/OutOfBoundsException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\RuntimeException' => $vendorDir . '/symfony/property-access/Exception/RuntimeException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\UnexpectedTypeException' => $vendorDir . '/symfony/property-access/Exception/UnexpectedTypeException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\UninitializedPropertyException' => $vendorDir . '/symfony/property-access/Exception/UninitializedPropertyException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccess' => $vendorDir . '/symfony/property-access/PropertyAccess.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessor' => $vendorDir . '/symfony/property-access/PropertyAccessor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder' => $vendorDir . '/symfony/property-access/PropertyAccessorBuilder.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessorInterface' => $vendorDir . '/symfony/property-access/PropertyAccessorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPath' => $vendorDir . '/symfony/property-access/PropertyPath.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathBuilder' => $vendorDir . '/symfony/property-access/PropertyPathBuilder.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathInterface' => $vendorDir . '/symfony/property-access/PropertyPathInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathIterator' => $vendorDir . '/symfony/property-access/PropertyPathIterator.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathIteratorInterface' => $vendorDir . '/symfony/property-access/PropertyPathIteratorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\DependencyInjection\\PropertyInfoConstructorPass' => $vendorDir . '/symfony/property-info/DependencyInjection/PropertyInfoConstructorPass.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\DependencyInjection\\PropertyInfoPass' => $vendorDir . '/symfony/property-info/DependencyInjection/PropertyInfoPass.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorArgumentTypeExtractorInterface' => $vendorDir . '/symfony/property-info/Extractor/ConstructorArgumentTypeExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorExtractor' => $vendorDir . '/symfony/property-info/Extractor/ConstructorExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\PhpDocExtractor' => $vendorDir . '/symfony/property-info/Extractor/PhpDocExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\PhpStanExtractor' => $vendorDir . '/symfony/property-info/Extractor/PhpStanExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ReflectionExtractor' => $vendorDir . '/symfony/property-info/Extractor/ReflectionExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor' => $vendorDir . '/symfony/property-info/Extractor/SerializerExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PhpStan\\NameScope' => $vendorDir . '/symfony/property-info/PhpStan/NameScope.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PhpStan\\NameScopeFactory' => $vendorDir . '/symfony/property-info/PhpStan/NameScopeFactory.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyAccessExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyDescriptionExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoCacheExtractor' => $vendorDir . '/symfony/property-info/PropertyInfoCacheExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor' => $vendorDir . '/symfony/property-info/PropertyInfoExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInitializableExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyInitializableExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyListExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyListExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyReadInfo' => $vendorDir . '/symfony/property-info/PropertyReadInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyReadInfoExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyReadInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyTypeExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyWriteInfo' => $vendorDir . '/symfony/property-info/PropertyWriteInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyWriteInfoExtractorInterface' => $vendorDir . '/symfony/property-info/PropertyWriteInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Type' => $vendorDir . '/symfony/property-info/Type.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Util\\PhpDocTypeHelper' => $vendorDir . '/symfony/property-info/Util/PhpDocTypeHelper.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Util\\PhpStanTypeHelper' => $vendorDir . '/symfony/property-info/Util/PhpStanTypeHelper.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\Section' => $vendorDir . '/symfony/stopwatch/Section.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\Stopwatch' => $vendorDir . '/symfony/stopwatch/Stopwatch.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\StopwatchEvent' => $vendorDir . '/symfony/stopwatch/StopwatchEvent.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\StopwatchPeriod' => $vendorDir . '/symfony/stopwatch/StopwatchPeriod.php',
'JooosiFonDeps\\Symfony\\Component\\String\\AbstractString' => $vendorDir . '/symfony/string/AbstractString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\AbstractUnicodeString' => $vendorDir . '/symfony/string/AbstractUnicodeString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\ByteString' => $vendorDir . '/symfony/string/ByteString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\CodePointString' => $vendorDir . '/symfony/string/CodePointString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/string/Exception/ExceptionInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/string/Exception/InvalidArgumentException.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\RuntimeException' => $vendorDir . '/symfony/string/Exception/RuntimeException.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\EnglishInflector' => $vendorDir . '/symfony/string/Inflector/EnglishInflector.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\FrenchInflector' => $vendorDir . '/symfony/string/Inflector/FrenchInflector.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\InflectorInterface' => $vendorDir . '/symfony/string/Inflector/InflectorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\LazyString' => $vendorDir . '/symfony/string/LazyString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Slugger\\AsciiSlugger' => $vendorDir . '/symfony/string/Slugger/AsciiSlugger.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Slugger\\SluggerInterface' => $vendorDir . '/symfony/string/Slugger/SluggerInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\UnicodeString' => $vendorDir . '/symfony/string/UnicodeString.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Attribute\\Required' => $vendorDir . '/symfony/service-contracts/Attribute/Required.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Attribute\\SubscribedService' => $vendorDir . '/symfony/service-contracts/Attribute/SubscribedService.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ResetInterface' => $vendorDir . '/symfony/service-contracts/ResetInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceLocatorTrait' => $vendorDir . '/symfony/service-contracts/ServiceLocatorTrait.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceProviderInterface' => $vendorDir . '/symfony/service-contracts/ServiceProviderInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberTrait.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Test\\ServiceLocatorTest' => $vendorDir . '/symfony/service-contracts/Test/ServiceLocatorTest.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Test\\ServiceLocatorTestCase' => $vendorDir . '/symfony/service-contracts/Test/ServiceLocatorTestCase.php',
'JooosiFon\\Admin\\AdminPage' => $baseDir . '/src/Admin/AdminPage.php',
'JooosiFon\\Api\\AbstractApi' => $baseDir . '/src/Api/AbstractApi.php',
'JooosiFon\\Api\\ApiInterface' => $baseDir . '/src/Api/ApiInterface.php',
'JooosiFon\\Api\\Font' => $baseDir . '/src/Api/Font.php',
'JooosiFon\\Api\\Migrations\\BrainstormForceCustomFonts' => $baseDir . '/src/Api/Migrations/BrainstormForceCustomFonts.php',
'JooosiFon\\Api\\Migrations\\BricksCustomFonts' => $baseDir . '/src/Api/Migrations/BricksCustomFonts.php',
'JooosiFon\\Api\\Migrations\\CustomAdobeFonts' => $baseDir . '/src/Api/Migrations/CustomAdobeFonts.php',
'JooosiFon\\Api\\Migrations\\DpluginsFontHero' => $baseDir . '/src/Api/Migrations/DpluginsFontHero.php',
'JooosiFon\\Api\\Migrations\\ElementorProCustomFonts' => $baseDir . '/src/Api/Migrations/ElementorProCustomFonts.php',
'JooosiFon\\Api\\Migrations\\FontsPlugin' => $baseDir . '/src/Api/Migrations/FontsPlugin.php',
'JooosiFon\\Api\\Migrations\\Support\\SourceFontNormalizer' => $baseDir . '/src/Api/Migrations/Support/SourceFontNormalizer.php',
'JooosiFon\\Api\\Migrations\\UseAnyFont' => $baseDir . '/src/Api/Migrations/UseAnyFont.php',
'JooosiFon\\Api\\Router' => $baseDir . '/src/Api/Router.php',
'JooosiFon\\Api\\Setting\\AdobeFonts' => $baseDir . '/src/Api/Setting/AdobeFonts.php',
'JooosiFon\\Api\\Setting\\Cache' => $baseDir . '/src/Api/Setting/Cache.php',
'JooosiFon\\Api\\Setting\\License' => $baseDir . '/src/Api/Setting/License.php',
'JooosiFon\\Api\\Setting\\Option' => $baseDir . '/src/Api/Setting/Option.php',
'JooosiFon\\Api\\Support\\FontCodec' => $baseDir . '/src/Api/Support/FontCodec.php',
'JooosiFon\\Api\\Support\\FontEvents' => $baseDir . '/src/Api/Support/FontEvents.php',
'JooosiFon\\Api\\Support\\FontRepository' => $baseDir . '/src/Api/Support/FontRepository.php',
'JooosiFon\\Api\\Support\\GoogleFontFileSelector' => $baseDir . '/src/Api/Support/GoogleFontFileSelector.php',
'JooosiFon\\Api\\Support\\GoogleFontsClient' => $baseDir . '/src/Api/Support/GoogleFontsClient.php',
'JooosiFon\\Api\\Support\\MediaImportService' => $baseDir . '/src/Api/Support/MediaImportService.php',
'JooosiFon\\Api\\Support\\RequestValidator' => $baseDir . '/src/Api/Support/RequestValidator.php',
'JooosiFon\\Builder\\BuilderInterface' => $baseDir . '/src/Builder/BuilderInterface.php',
'JooosiFon\\Builder\\Builderius\\Main' => $baseDir . '/src/Builder/Builderius/Main.php',
'JooosiFon\\Builder\\ClassicEditor\\Main' => $baseDir . '/src/Builder/ClassicEditor/Main.php',
'JooosiFon\\Builder\\Elementor\\Main' => $baseDir . '/src/Builder/Elementor/Main.php',
'JooosiFon\\Builder\\GeneratePress\\Main' => $baseDir . '/src/Builder/GeneratePress/Main.php',
'JooosiFon\\Builder\\Gutenberg\\Main' => $baseDir . '/src/Builder/Gutenberg/Main.php',
'JooosiFon\\Builder\\Integration' => $baseDir . '/src/Builder/Integration.php',
'JooosiFon\\Builder\\Kadence\\Main' => $baseDir . '/src/Builder/Kadence/Main.php',
'JooosiFon\\Builder\\Pinegrow\\Main' => $baseDir . '/src/Builder/Pinegrow/Main.php',
'JooosiFon\\Core\\Cache' => $baseDir . '/src/Core/Cache.php',
'JooosiFon\\Core\\Cache\\FontCacheSnapshotBuilder' => $baseDir . '/src/Core/Cache/FontCacheSnapshotBuilder.php',
'JooosiFon\\Core\\Cache\\FontCssRenderer' => $baseDir . '/src/Core/Cache/FontCssRenderer.php',
'JooosiFon\\Core\\Cache\\FontPreloadRenderer' => $baseDir . '/src/Core/Cache/FontPreloadRenderer.php',
'JooosiFon\\Core\\Frontpage' => $baseDir . '/src/Core/Frontpage.php',
'JooosiFon\\Core\\Runtime' => $baseDir . '/src/Core/Runtime.php',
'JooosiFon\\Database\\FontTable' => $baseDir . '/src/Database/FontTable.php',
'JooosiFon\\Database\\Migration\\AbstractMigration' => $baseDir . '/src/Database/Migration/AbstractMigration.php',
'JooosiFon\\Database\\Migration\\Exception\\AbortMigration' => $baseDir . '/src/Database/Migration/Exception/AbortMigration.php',
'JooosiFon\\Database\\Migration\\Exception\\MigrationException' => $baseDir . '/src/Database/Migration/Exception/MigrationException.php',
'JooosiFon\\Database\\Migration\\Exception\\SkipMigration' => $baseDir . '/src/Database/Migration/Exception/SkipMigration.php',
'JooosiFon\\Database\\Migration\\MigrationCommand' => $baseDir . '/src/Database/Migration/MigrationCommand.php',
'JooosiFon\\Database\\Migration\\MigrationConfiguration' => $baseDir . '/src/Database/Migration/MigrationConfiguration.php',
'JooosiFon\\Database\\Migration\\MigrationDefinition' => $baseDir . '/src/Database/Migration/MigrationDefinition.php',
'JooosiFon\\Database\\Migration\\MigrationGenerator' => $baseDir . '/src/Database/Migration/MigrationGenerator.php',
'JooosiFon\\Database\\Migration\\MigrationHistoryUpgrader' => $baseDir . '/src/Database/Migration/MigrationHistoryUpgrader.php',
'JooosiFon\\Database\\Migration\\MigrationManager' => $baseDir . '/src/Database/Migration/MigrationManager.php',
'JooosiFon\\Database\\Migration\\MigrationRegistry' => $baseDir . '/src/Database/Migration/MigrationRegistry.php',
'JooosiFon\\Database\\Migration\\MigrationRepository' => $baseDir . '/src/Database/Migration/MigrationRepository.php',
'JooosiFon\\Licensing\\Manager' => $baseDir . '/src/Licensing/Manager.php',
'JooosiFon\\Migration' => $baseDir . '/src/Migration.php',
'JooosiFon\\Plugin' => $baseDir . '/src/Plugin.php',
'JooosiFon\\Upgrade\\LegacyRebrandUpgrade' => $baseDir . '/src/Upgrade/LegacyRebrandUpgrade.php',
'JooosiFon\\Utils\\Common' => $baseDir . '/src/Utils/Common.php',
'JooosiFon\\Utils\\Config' => $baseDir . '/src/Utils/Config.php',
'JooosiFon\\Utils\\Debug' => $baseDir . '/src/Utils/Debug.php',
'JooosiFon\\Utils\\Font' => $baseDir . '/src/Utils/Font.php',
'JooosiFon\\Utils\\Notice' => $baseDir . '/src/Utils/Notice.php',
'JooosiFon\\Utils\\Upload' => $baseDir . '/src/Utils/Upload.php',
'Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'Symfony\\Polyfill\\Ctype\\Ctype' => $vendorDir . '/symfony/polyfill-ctype/Ctype.php',
'Symfony\\Polyfill\\Intl\\Grapheme\\Grapheme' => $vendorDir . '/symfony/polyfill-intl-grapheme/Grapheme.php',
'Symfony\\Polyfill\\Intl\\Normalizer\\Normalizer' => $vendorDir . '/symfony/polyfill-intl-normalizer/Normalizer.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php',
'Symfony\\Polyfill\\Php80\\Php80' => $vendorDir . '/symfony/polyfill-php80/Php80.php',
'Symfony\\Polyfill\\Php80\\PhpToken' => $vendorDir . '/symfony/polyfill-php80/PhpToken.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
@@ -0,0 +1,18 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php',
'6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => $vendorDir . '/symfony/string/Resources/functions.php',
'3c9ebf3d7a29b377eb2a8001857b1f68' => $vendorDir . '/nabasa/vp-wp/vp-wp.php',
'0bbfc80052757111b911b3f36b5757c3' => $baseDir . '/constant.php',
);
@@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);
@@ -0,0 +1,24 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Intl\\Normalizer\\' => array($vendorDir . '/symfony/polyfill-intl-normalizer'),
'Symfony\\Polyfill\\Intl\\Grapheme\\' => array($vendorDir . '/symfony/polyfill-intl-grapheme'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'JooosiFon\\' => array($baseDir . '/src'),
'JooosiFonDeps\\Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'),
'JooosiFonDeps\\Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'),
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\' => array($vendorDir . '/symfony/stopwatch'),
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\' => array($vendorDir . '/symfony/property-info'),
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\' => array($vendorDir . '/symfony/property-access'),
'JooosiFonDeps\\Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'JooosiFonDeps\\Sabberworm\\CSS\\' => array($vendorDir . '/sabberworm/php-css-parser/src'),
'JooosiFonDeps\\Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
'JooosiFonDeps\\Hidehalo\\Nanoid\\' => array($vendorDir . '/hidehalo/nanoid-php/src'),
);
@@ -0,0 +1,51 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitaed462212d3f4c500a68ea77cbd9569f
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInitaed462212d3f4c500a68ea77cbd9569f', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInitaed462212d3f4c500a68ea77cbd9569f', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f::getInitializer($loader));
$loader->setClassMapAuthoritative(true);
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader;
}
}
@@ -0,0 +1,337 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f
{
public static $files = array (
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'b6b991a57620e2fb6b2f66f03fe9ddc2' => __DIR__ . '/..' . '/symfony/string/Resources/functions.php',
'3c9ebf3d7a29b377eb2a8001857b1f68' => __DIR__ . '/..' . '/nabasa/vp-wp/vp-wp.php',
'0bbfc80052757111b911b3f36b5757c3' => __DIR__ . '/../..' . '/constant.php',
);
public static $prefixLengthsPsr4 = array (
'S' =>
array (
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Intl\\Normalizer\\' => 33,
'Symfony\\Polyfill\\Intl\\Grapheme\\' => 31,
'Symfony\\Polyfill\\Ctype\\' => 23,
),
'J' =>
array (
'JooosiFon\\' => 10,
'JooosiFonDeps\\Symfony\\Contracts\\Service\\' => 40,
'JooosiFonDeps\\Symfony\\Component\\String\\' => 39,
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\' => 42,
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\' => 45,
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\' => 47,
'JooosiFonDeps\\Symfony\\Component\\Finder\\' => 39,
'JooosiFonDeps\\Sabberworm\\CSS\\' => 29,
'JooosiFonDeps\\Psr\\Container\\' => 28,
'JooosiFonDeps\\Hidehalo\\Nanoid\\' => 30,
),
);
public static $prefixDirsPsr4 = array (
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Intl\\Normalizer\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer',
),
'Symfony\\Polyfill\\Intl\\Grapheme\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'JooosiFon\\' =>
array (
0 => __DIR__ . '/../..' . '/src',
),
'JooosiFonDeps\\Symfony\\Contracts\\Service\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/service-contracts',
),
'JooosiFonDeps\\Symfony\\Component\\String\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/string',
),
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/stopwatch',
),
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/property-info',
),
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/property-access',
),
'JooosiFonDeps\\Symfony\\Component\\Finder\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/finder',
),
'JooosiFonDeps\\Sabberworm\\CSS\\' =>
array (
0 => __DIR__ . '/..' . '/sabberworm/php-css-parser/src',
),
'JooosiFonDeps\\Psr\\Container\\' =>
array (
0 => __DIR__ . '/..' . '/psr/container/src',
),
'JooosiFonDeps\\Hidehalo\\Nanoid\\' =>
array (
0 => __DIR__ . '/..' . '/hidehalo/nanoid-php/src',
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Client' => __DIR__ . '/..' . '/hidehalo/nanoid-php/src/Client.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Core' => __DIR__ . '/..' . '/hidehalo/nanoid-php/src/Core.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\CoreInterface' => __DIR__ . '/..' . '/hidehalo/nanoid-php/src/CoreInterface.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\Generator' => __DIR__ . '/..' . '/hidehalo/nanoid-php/src/Generator.php',
'JooosiFonDeps\\Hidehalo\\Nanoid\\GeneratorInterface' => __DIR__ . '/..' . '/hidehalo/nanoid-php/src/GeneratorInterface.php',
'JooosiFonDeps\\Psr\\Container\\ContainerExceptionInterface' => __DIR__ . '/..' . '/psr/container/src/ContainerExceptionInterface.php',
'JooosiFonDeps\\Psr\\Container\\ContainerInterface' => __DIR__ . '/..' . '/psr/container/src/ContainerInterface.php',
'JooosiFonDeps\\Psr\\Container\\NotFoundExceptionInterface' => __DIR__ . '/..' . '/psr/container/src/NotFoundExceptionInterface.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\AtRuleBlockList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/CSSList/AtRuleBlockList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\CSSBlockList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/CSSList/CSSBlockList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\CSSList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/CSSList/CSSList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\Document' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/CSSList/Document.php',
'JooosiFonDeps\\Sabberworm\\CSS\\CSSList\\KeyFrame' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/CSSList/KeyFrame.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Comment\\Comment' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Comment/Comment.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Comment\\Commentable' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Comment/Commentable.php',
'JooosiFonDeps\\Sabberworm\\CSS\\OutputFormat' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/OutputFormat.php',
'JooosiFonDeps\\Sabberworm\\CSS\\OutputFormatter' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/OutputFormatter.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parser' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parser.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\Anchor' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/Anchor.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\OutputException' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/OutputException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\ParserState' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/ParserState.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\SourceException' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/SourceException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\UnexpectedEOFException' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/UnexpectedEOFException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Parsing\\UnexpectedTokenException' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Parsing/UnexpectedTokenException.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\AtRule' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/AtRule.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\CSSNamespace' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/CSSNamespace.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Charset' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/Charset.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Import' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/Import.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\KeyframeSelector' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/KeyframeSelector.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Property\\Selector' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Property/Selector.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Renderable' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Renderable.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\AtRuleSet' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/RuleSet/AtRuleSet.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\DeclarationBlock' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/RuleSet/DeclarationBlock.php',
'JooosiFonDeps\\Sabberworm\\CSS\\RuleSet\\RuleSet' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/RuleSet/RuleSet.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Rule\\Rule' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Rule/Rule.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Settings' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Settings.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CSSFunction' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/CSSFunction.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CSSString' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/CSSString.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CalcFunction' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/CalcFunction.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\CalcRuleValueList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/CalcRuleValueList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Color' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/Color.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\LineName' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/LineName.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\PrimitiveValue' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/PrimitiveValue.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\RuleValueList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/RuleValueList.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Size' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/Size.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\URL' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/URL.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\Value' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/Value.php',
'JooosiFonDeps\\Sabberworm\\CSS\\Value\\ValueList' => __DIR__ . '/..' . '/sabberworm/php-css-parser/src/Value/ValueList.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\Comparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/Comparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\DateComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/DateComparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Comparator\\NumberComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/NumberComparator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => __DIR__ . '/..' . '/symfony/finder/Exception/AccessDeniedException.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Exception\\DirectoryNotFoundException' => __DIR__ . '/..' . '/symfony/finder/Exception/DirectoryNotFoundException.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Finder' => __DIR__ . '/..' . '/symfony/finder/Finder.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Gitignore' => __DIR__ . '/..' . '/symfony/finder/Gitignore.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Glob' => __DIR__ . '/..' . '/symfony/finder/Glob.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/CustomFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DateRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DepthRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FileTypeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilecontentFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilenameFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\LazyIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/LazyIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/PathFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SizeRangeFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\SortableIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SortableIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\Iterator\\VcsIgnoredFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/VcsIgnoredFilterIterator.php',
'JooosiFonDeps\\Symfony\\Component\\Finder\\SplFileInfo' => __DIR__ . '/..' . '/symfony/finder/SplFileInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\AccessException' => __DIR__ . '/..' . '/symfony/property-access/Exception/AccessException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/property-access/Exception/ExceptionInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/property-access/Exception/InvalidArgumentException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\InvalidPropertyPathException' => __DIR__ . '/..' . '/symfony/property-access/Exception/InvalidPropertyPathException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\NoSuchIndexException' => __DIR__ . '/..' . '/symfony/property-access/Exception/NoSuchIndexException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\NoSuchPropertyException' => __DIR__ . '/..' . '/symfony/property-access/Exception/NoSuchPropertyException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\OutOfBoundsException' => __DIR__ . '/..' . '/symfony/property-access/Exception/OutOfBoundsException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/property-access/Exception/RuntimeException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\UnexpectedTypeException' => __DIR__ . '/..' . '/symfony/property-access/Exception/UnexpectedTypeException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\Exception\\UninitializedPropertyException' => __DIR__ . '/..' . '/symfony/property-access/Exception/UninitializedPropertyException.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccess' => __DIR__ . '/..' . '/symfony/property-access/PropertyAccess.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessor' => __DIR__ . '/..' . '/symfony/property-access/PropertyAccessor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessorBuilder' => __DIR__ . '/..' . '/symfony/property-access/PropertyAccessorBuilder.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyAccessorInterface' => __DIR__ . '/..' . '/symfony/property-access/PropertyAccessorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPath' => __DIR__ . '/..' . '/symfony/property-access/PropertyPath.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathBuilder' => __DIR__ . '/..' . '/symfony/property-access/PropertyPathBuilder.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathInterface' => __DIR__ . '/..' . '/symfony/property-access/PropertyPathInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathIterator' => __DIR__ . '/..' . '/symfony/property-access/PropertyPathIterator.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyAccess\\PropertyPathIteratorInterface' => __DIR__ . '/..' . '/symfony/property-access/PropertyPathIteratorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\DependencyInjection\\PropertyInfoConstructorPass' => __DIR__ . '/..' . '/symfony/property-info/DependencyInjection/PropertyInfoConstructorPass.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\DependencyInjection\\PropertyInfoPass' => __DIR__ . '/..' . '/symfony/property-info/DependencyInjection/PropertyInfoPass.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorArgumentTypeExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/Extractor/ConstructorArgumentTypeExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ConstructorExtractor' => __DIR__ . '/..' . '/symfony/property-info/Extractor/ConstructorExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\PhpDocExtractor' => __DIR__ . '/..' . '/symfony/property-info/Extractor/PhpDocExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\PhpStanExtractor' => __DIR__ . '/..' . '/symfony/property-info/Extractor/PhpStanExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\ReflectionExtractor' => __DIR__ . '/..' . '/symfony/property-info/Extractor/ReflectionExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Extractor\\SerializerExtractor' => __DIR__ . '/..' . '/symfony/property-info/Extractor/SerializerExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PhpStan\\NameScope' => __DIR__ . '/..' . '/symfony/property-info/PhpStan/NameScope.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PhpStan\\NameScopeFactory' => __DIR__ . '/..' . '/symfony/property-info/PhpStan/NameScopeFactory.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyAccessExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyAccessExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyDescriptionExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyDescriptionExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoCacheExtractor' => __DIR__ . '/..' . '/symfony/property-info/PropertyInfoCacheExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoExtractor' => __DIR__ . '/..' . '/symfony/property-info/PropertyInfoExtractor.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInfoExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyInitializableExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyInitializableExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyListExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyListExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyReadInfo' => __DIR__ . '/..' . '/symfony/property-info/PropertyReadInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyReadInfoExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyReadInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyTypeExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyTypeExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyWriteInfo' => __DIR__ . '/..' . '/symfony/property-info/PropertyWriteInfo.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\PropertyWriteInfoExtractorInterface' => __DIR__ . '/..' . '/symfony/property-info/PropertyWriteInfoExtractorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Type' => __DIR__ . '/..' . '/symfony/property-info/Type.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Util\\PhpDocTypeHelper' => __DIR__ . '/..' . '/symfony/property-info/Util/PhpDocTypeHelper.php',
'JooosiFonDeps\\Symfony\\Component\\PropertyInfo\\Util\\PhpStanTypeHelper' => __DIR__ . '/..' . '/symfony/property-info/Util/PhpStanTypeHelper.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\Section' => __DIR__ . '/..' . '/symfony/stopwatch/Section.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\Stopwatch' => __DIR__ . '/..' . '/symfony/stopwatch/Stopwatch.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\StopwatchEvent' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchEvent.php',
'JooosiFonDeps\\Symfony\\Component\\Stopwatch\\StopwatchPeriod' => __DIR__ . '/..' . '/symfony/stopwatch/StopwatchPeriod.php',
'JooosiFonDeps\\Symfony\\Component\\String\\AbstractString' => __DIR__ . '/..' . '/symfony/string/AbstractString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\AbstractUnicodeString' => __DIR__ . '/..' . '/symfony/string/AbstractUnicodeString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\ByteString' => __DIR__ . '/..' . '/symfony/string/ByteString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\CodePointString' => __DIR__ . '/..' . '/symfony/string/CodePointString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/string/Exception/ExceptionInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/string/Exception/InvalidArgumentException.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/string/Exception/RuntimeException.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\EnglishInflector' => __DIR__ . '/..' . '/symfony/string/Inflector/EnglishInflector.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\FrenchInflector' => __DIR__ . '/..' . '/symfony/string/Inflector/FrenchInflector.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Inflector\\InflectorInterface' => __DIR__ . '/..' . '/symfony/string/Inflector/InflectorInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\LazyString' => __DIR__ . '/..' . '/symfony/string/LazyString.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Slugger\\AsciiSlugger' => __DIR__ . '/..' . '/symfony/string/Slugger/AsciiSlugger.php',
'JooosiFonDeps\\Symfony\\Component\\String\\Slugger\\SluggerInterface' => __DIR__ . '/..' . '/symfony/string/Slugger/SluggerInterface.php',
'JooosiFonDeps\\Symfony\\Component\\String\\UnicodeString' => __DIR__ . '/..' . '/symfony/string/UnicodeString.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Attribute\\Required' => __DIR__ . '/..' . '/symfony/service-contracts/Attribute/Required.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Attribute\\SubscribedService' => __DIR__ . '/..' . '/symfony/service-contracts/Attribute/SubscribedService.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ResetInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ResetInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceLocatorTrait' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceLocatorTrait.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceProviderInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceProviderInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberInterface.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberTrait.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Test\\ServiceLocatorTest' => __DIR__ . '/..' . '/symfony/service-contracts/Test/ServiceLocatorTest.php',
'JooosiFonDeps\\Symfony\\Contracts\\Service\\Test\\ServiceLocatorTestCase' => __DIR__ . '/..' . '/symfony/service-contracts/Test/ServiceLocatorTestCase.php',
'JooosiFon\\Admin\\AdminPage' => __DIR__ . '/../..' . '/src/Admin/AdminPage.php',
'JooosiFon\\Api\\AbstractApi' => __DIR__ . '/../..' . '/src/Api/AbstractApi.php',
'JooosiFon\\Api\\ApiInterface' => __DIR__ . '/../..' . '/src/Api/ApiInterface.php',
'JooosiFon\\Api\\Font' => __DIR__ . '/../..' . '/src/Api/Font.php',
'JooosiFon\\Api\\Migrations\\BrainstormForceCustomFonts' => __DIR__ . '/../..' . '/src/Api/Migrations/BrainstormForceCustomFonts.php',
'JooosiFon\\Api\\Migrations\\BricksCustomFonts' => __DIR__ . '/../..' . '/src/Api/Migrations/BricksCustomFonts.php',
'JooosiFon\\Api\\Migrations\\CustomAdobeFonts' => __DIR__ . '/../..' . '/src/Api/Migrations/CustomAdobeFonts.php',
'JooosiFon\\Api\\Migrations\\DpluginsFontHero' => __DIR__ . '/../..' . '/src/Api/Migrations/DpluginsFontHero.php',
'JooosiFon\\Api\\Migrations\\ElementorProCustomFonts' => __DIR__ . '/../..' . '/src/Api/Migrations/ElementorProCustomFonts.php',
'JooosiFon\\Api\\Migrations\\FontsPlugin' => __DIR__ . '/../..' . '/src/Api/Migrations/FontsPlugin.php',
'JooosiFon\\Api\\Migrations\\Support\\SourceFontNormalizer' => __DIR__ . '/../..' . '/src/Api/Migrations/Support/SourceFontNormalizer.php',
'JooosiFon\\Api\\Migrations\\UseAnyFont' => __DIR__ . '/../..' . '/src/Api/Migrations/UseAnyFont.php',
'JooosiFon\\Api\\Router' => __DIR__ . '/../..' . '/src/Api/Router.php',
'JooosiFon\\Api\\Setting\\AdobeFonts' => __DIR__ . '/../..' . '/src/Api/Setting/AdobeFonts.php',
'JooosiFon\\Api\\Setting\\Cache' => __DIR__ . '/../..' . '/src/Api/Setting/Cache.php',
'JooosiFon\\Api\\Setting\\License' => __DIR__ . '/../..' . '/src/Api/Setting/License.php',
'JooosiFon\\Api\\Setting\\Option' => __DIR__ . '/../..' . '/src/Api/Setting/Option.php',
'JooosiFon\\Api\\Support\\FontCodec' => __DIR__ . '/../..' . '/src/Api/Support/FontCodec.php',
'JooosiFon\\Api\\Support\\FontEvents' => __DIR__ . '/../..' . '/src/Api/Support/FontEvents.php',
'JooosiFon\\Api\\Support\\FontRepository' => __DIR__ . '/../..' . '/src/Api/Support/FontRepository.php',
'JooosiFon\\Api\\Support\\GoogleFontFileSelector' => __DIR__ . '/../..' . '/src/Api/Support/GoogleFontFileSelector.php',
'JooosiFon\\Api\\Support\\GoogleFontsClient' => __DIR__ . '/../..' . '/src/Api/Support/GoogleFontsClient.php',
'JooosiFon\\Api\\Support\\MediaImportService' => __DIR__ . '/../..' . '/src/Api/Support/MediaImportService.php',
'JooosiFon\\Api\\Support\\RequestValidator' => __DIR__ . '/../..' . '/src/Api/Support/RequestValidator.php',
'JooosiFon\\Builder\\BuilderInterface' => __DIR__ . '/../..' . '/src/Builder/BuilderInterface.php',
'JooosiFon\\Builder\\Builderius\\Main' => __DIR__ . '/../..' . '/src/Builder/Builderius/Main.php',
'JooosiFon\\Builder\\ClassicEditor\\Main' => __DIR__ . '/../..' . '/src/Builder/ClassicEditor/Main.php',
'JooosiFon\\Builder\\Elementor\\Main' => __DIR__ . '/../..' . '/src/Builder/Elementor/Main.php',
'JooosiFon\\Builder\\GeneratePress\\Main' => __DIR__ . '/../..' . '/src/Builder/GeneratePress/Main.php',
'JooosiFon\\Builder\\Gutenberg\\Main' => __DIR__ . '/../..' . '/src/Builder/Gutenberg/Main.php',
'JooosiFon\\Builder\\Integration' => __DIR__ . '/../..' . '/src/Builder/Integration.php',
'JooosiFon\\Builder\\Kadence\\Main' => __DIR__ . '/../..' . '/src/Builder/Kadence/Main.php',
'JooosiFon\\Builder\\Pinegrow\\Main' => __DIR__ . '/../..' . '/src/Builder/Pinegrow/Main.php',
'JooosiFon\\Core\\Cache' => __DIR__ . '/../..' . '/src/Core/Cache.php',
'JooosiFon\\Core\\Cache\\FontCacheSnapshotBuilder' => __DIR__ . '/../..' . '/src/Core/Cache/FontCacheSnapshotBuilder.php',
'JooosiFon\\Core\\Cache\\FontCssRenderer' => __DIR__ . '/../..' . '/src/Core/Cache/FontCssRenderer.php',
'JooosiFon\\Core\\Cache\\FontPreloadRenderer' => __DIR__ . '/../..' . '/src/Core/Cache/FontPreloadRenderer.php',
'JooosiFon\\Core\\Frontpage' => __DIR__ . '/../..' . '/src/Core/Frontpage.php',
'JooosiFon\\Core\\Runtime' => __DIR__ . '/../..' . '/src/Core/Runtime.php',
'JooosiFon\\Database\\FontTable' => __DIR__ . '/../..' . '/src/Database/FontTable.php',
'JooosiFon\\Database\\Migration\\AbstractMigration' => __DIR__ . '/../..' . '/src/Database/Migration/AbstractMigration.php',
'JooosiFon\\Database\\Migration\\Exception\\AbortMigration' => __DIR__ . '/../..' . '/src/Database/Migration/Exception/AbortMigration.php',
'JooosiFon\\Database\\Migration\\Exception\\MigrationException' => __DIR__ . '/../..' . '/src/Database/Migration/Exception/MigrationException.php',
'JooosiFon\\Database\\Migration\\Exception\\SkipMigration' => __DIR__ . '/../..' . '/src/Database/Migration/Exception/SkipMigration.php',
'JooosiFon\\Database\\Migration\\MigrationCommand' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationCommand.php',
'JooosiFon\\Database\\Migration\\MigrationConfiguration' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationConfiguration.php',
'JooosiFon\\Database\\Migration\\MigrationDefinition' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationDefinition.php',
'JooosiFon\\Database\\Migration\\MigrationGenerator' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationGenerator.php',
'JooosiFon\\Database\\Migration\\MigrationHistoryUpgrader' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationHistoryUpgrader.php',
'JooosiFon\\Database\\Migration\\MigrationManager' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationManager.php',
'JooosiFon\\Database\\Migration\\MigrationRegistry' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationRegistry.php',
'JooosiFon\\Database\\Migration\\MigrationRepository' => __DIR__ . '/../..' . '/src/Database/Migration/MigrationRepository.php',
'JooosiFon\\Licensing\\Manager' => __DIR__ . '/../..' . '/src/Licensing/Manager.php',
'JooosiFon\\Migration' => __DIR__ . '/../..' . '/src/Migration.php',
'JooosiFon\\Plugin' => __DIR__ . '/../..' . '/src/Plugin.php',
'JooosiFon\\Upgrade\\LegacyRebrandUpgrade' => __DIR__ . '/../..' . '/src/Upgrade/LegacyRebrandUpgrade.php',
'JooosiFon\\Utils\\Common' => __DIR__ . '/../..' . '/src/Utils/Common.php',
'JooosiFon\\Utils\\Config' => __DIR__ . '/../..' . '/src/Utils/Config.php',
'JooosiFon\\Utils\\Debug' => __DIR__ . '/../..' . '/src/Utils/Debug.php',
'JooosiFon\\Utils\\Font' => __DIR__ . '/../..' . '/src/Utils/Font.php',
'JooosiFon\\Utils\\Notice' => __DIR__ . '/../..' . '/src/Utils/Notice.php',
'JooosiFon\\Utils\\Upload' => __DIR__ . '/../..' . '/src/Utils/Upload.php',
'Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Resources/stubs/Normalizer.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'Symfony\\Polyfill\\Ctype\\Ctype' => __DIR__ . '/..' . '/symfony/polyfill-ctype/Ctype.php',
'Symfony\\Polyfill\\Intl\\Grapheme\\Grapheme' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/Grapheme.php',
'Symfony\\Polyfill\\Intl\\Normalizer\\Normalizer' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/Normalizer.php',
'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php',
'Symfony\\Polyfill\\Php80\\Php80' => __DIR__ . '/..' . '/symfony/polyfill-php80/Php80.php',
'Symfony\\Polyfill\\Php80\\PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/PhpToken.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitaed462212d3f4c500a68ea77cbd9569f::$classMap;
}, null, ClassLoader::class);
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,25 @@
<?php
// platform_check.php @generated by Composer
$issues = array();
if (!(PHP_VERSION_ID >= 70400)) {
$issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.';
}
if ($issues) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL);
} elseif (!headers_sent()) {
echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL;
}
}
throw new \RuntimeException(
'Composer detected issues in your platform: ' . implode(' ', $issues)
);
}
@@ -0,0 +1,62 @@
{
"name": "hidehalo\/nanoid-php",
"type": "library",
"description": "A copy of nanoid in PHP",
"keywords": [
"hidehalo",
"nanoid-php"
],
"homepage": "https:\/\/github.com\/hidehalo\/nanoid-php",
"license": "MIT",
"authors": [
{
"name": "hidehalo",
"email": "tianchen_cc@yeah.net",
"homepage": "https:\/\/github.com\/hidehalo",
"role": "Owner"
}
],
"require": {
"php": "~5.6|~7.0|~8.0",
"paragonie\/random_compat": ">=2.0"
},
"require-dev": {
"phpunit\/phpunit": ">=5.6",
"squizlabs\/php_codesniffer": "^2.3"
},
"archive": {
"exclude": [
"tests\/",
"benchmark\/",
"examples\/",
".gitignore",
".editorconfig",
"*.md",
"*.yml",
"*.xml"
]
},
"autoload": {
"psr-4": {
"JooosiFonDeps\\Hidehalo\\Nanoid\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"JooosiFonDeps\\Hidehalo\\Nanoid\\Test\\": "tests"
}
},
"scripts": {
"test": "phpunit",
"check-style": "phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests",
"fix-style": "phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests"
},
"extra": {
"branch-alias": {
"dev-master": "1.0-dev"
}
},
"config": {
"sort-packages": true
}
}
@@ -0,0 +1,110 @@
<?php
namespace JooosiFonDeps\Hidehalo\Nanoid;
class Client
{
/**
* Random mode flags
*
* @const MODE_NORMAL 1
* @const MODEL_DYNAMIC 2
*/
const MODE_NORMAL = 1;
const MODE_DYNAMIC = 2;
/**
* @param string $alphabet Symbols to be used in ID.
* @param integer $size number of symbols in ID.
*/
protected $alphabet;
protected $size;
/**
* @var CoreInterface $core Core dynamic random
*/
private $core;
/**
* @var GeneratorInterface $generator Random Btyes Generator
*/
protected $generator;
/**
* Constructor of Client
*
* @codeCoverageIgnore
* @param integer $size
* @param GeneratorInterface $generator
*/
public function __construct($size = 21, GeneratorInterface $generator = null)
{
$this->size = $size > 0 ? $size : 21;
$this->generator = $generator ?: new Generator();
$this->core = new Core();
$this->alphabet = CoreInterface::SAFE_SYMBOLS;
}
/**
* Generate nanoid via optional modes
*
* @param integer $size
* @param integer $mode Client::MODE_NORMAL|Client::MODE_DYNAMIC
* @return string
*/
public function generateId($size = 0, $mode = self::MODE_NORMAL)
{
$size = $size > 0 ? $size : $this->size;
switch ($mode) {
case self::MODE_DYNAMIC:
return $this->core->random($this->generator, $size, $this->alphabet);
default:
return $this->normalRandom($size);
}
}
/**
* The original API of nanoid. Use it be careful, Please make sure
* you have been implements your custom GeneratorInterface as correctly.
* Otherwise use the build-in default random bytes generator
*
* @param GeneratorInterface $generator
* @param integer $size
* @param string $alphabet default CoreInterface::SAFE_SYMBOLS
* @return string
*/
public function formattedId($alphabet, $size = 0, GeneratorInterface $generator = null)
{
$alphabet = $alphabet ?: CoreInterface::SAFE_SYMBOLS;
$size = $size > 0 ? $size : $this->size;
$generator = $generator ?: $this->generator;
return $this->core->random($generator, $size, $alphabet);
}
/**
* Backwards-compatible method name.
*
* @param string $alphabet
* @param integer $size
* @param GeneratorInterface $generator
*
* @return string
* @since 1.0.0
*/
public function formatedId($alphabet, $size = 0, GeneratorInterface $generator = null)
{
$size = $size > 0 ? $size : $this->size;
return $this->formattedId($alphabet, $size, $generator);
}
/**
* Generate secure URL-friendly unique ID.
* By default, ID will have 21 symbols to have same collisions probability
* as UUID v4.
*
* @see https://github.com/ai/nanoid/blob/master/non-secure/index.js#L19
* @param integer $size
* @return string
*/
private function normalRandom($size)
{
$id = '';
while (1 <= $size--) {
$rand = mt_rand() / (mt_getrandmax() + 1);
$id .= $this->alphabet[intval($rand * 64)];
}
return $id;
}
}
@@ -0,0 +1,32 @@
<?php
namespace JooosiFonDeps\Hidehalo\Nanoid;
class Core implements CoreInterface
{
/**
* @inheritDoc
* @see https://github.com/ai/nanoid/blob/master/async/index.browser.js#L4
*/
public function random(GeneratorInterface $generator, $size, $alphabet = CoreInterface::SAFE_SYMBOLS)
{
$len = strlen($alphabet);
$mask = (2 << (int) (log($len - 1) / \M_LN2)) - 1;
$step = (int) ceil(1.6 * $mask * $size / $len);
$id = '';
while (\true) {
$bytes = $generator->random($step);
// NOTE: `$bytes` maybe not a normal "Array"
// sometimes it's begin from index 1, use iterator please
foreach ($bytes as $byte) {
$byte &= $mask;
if (isset($alphabet[$byte])) {
$id .= $alphabet[$byte];
if (strlen($id) === $size) {
return $id;
}
}
}
}
}
}
@@ -0,0 +1,19 @@
<?php
namespace JooosiFonDeps\Hidehalo\Nanoid;
interface CoreInterface
{
const SAFE_SYMBOLS = '_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const MASKS = [15, 31, 63, 127, 255];
/**
* Secure random string generator with custom alphabet.
* Alphabet must contain 256 symbols or less. Otherwise, the generator
* will not be secure.
*
* @param GeneratorInterface $generator
* @param string $alphabet
* @param integer $size
*/
public function random(GeneratorInterface $generator, $size, $alphabet = CoreInterface::SAFE_SYMBOLS);
}
@@ -0,0 +1,14 @@
<?php
namespace JooosiFonDeps\Hidehalo\Nanoid;
class Generator implements GeneratorInterface
{
/**
* @inheritDoc
*/
public function random($size)
{
return unpack('C*', \random_bytes($size));
}
}
@@ -0,0 +1,14 @@
<?php
namespace JooosiFonDeps\Hidehalo\Nanoid;
interface GeneratorInterface
{
/**
* Return random bytes array
*
* @param integer $size
* @return array
*/
public function random($size);
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,240 @@
# vp-wp
[![build status](https://github.com/nabasa-dev/vp-wp/actions/workflows/ci.yml/badge.svg)](https://github.com/nabasa-dev/vp-wp/actions/workflows/ci.yml)
[![npm version](https://img.shields.io/npm/v/%40nabasa%2Fvp-wp?logo=npm)](https://www.npmjs.com/package/@nabasa/vp-wp)
[![npm downloads](https://img.shields.io/npm/dm/%40nabasa%2Fvp-wp?logo=npm)](https://www.npmjs.com/package/@nabasa/vp-wp)
[![composer version](https://img.shields.io/packagist/v/nabasa/vp-wp?logo=packagist)](https://packagist.org/packages/nabasa/vp-wp)
[![composer downloads](https://img.shields.io/packagist/dt/nabasa/vp-wp?logo=packagist)](https://packagist.org/packages/nabasa/vp-wp)
[![pkg.pr.new](https://pkg.pr.new/badge/nabasa-dev/vp-wp)](https://pkg.pr.new/~/nabasa-dev/vp-wp)
[![license](https://img.shields.io/github/license/nabasa-dev/vp-wp)](https://github.com/nabasa-dev/vp-wp/blob/main/LICENSE)
`vp-wp` brings a modern Vite+ workflow to WordPress plugins and themes.
Use it to build and serve frontend assets with WordPress-friendly defaults, a compact TypeScript API, and a lightweight PHP runtime.
## Install
Install the JavaScript package with Vite+:
```sh
vp add -D vite-plus @nabasa/vp-wp
```
If you also want the PHP runtime helpers through Composer:
```sh
composer require nabasa/vp-wp
```
If you are not using Composer, copy `vp-wp.php` into your plugin or theme and require it manually.
## Migration
Moving from `@kucrut/vite-for-wp`? See [`docs/migrating-from-vite-for-wp.md`](docs/migrating-from-vite-for-wp.md).
## Vite+ config
A minimal Vite+ config looks like this:
```ts
import { defineConfig } from "vite-plus";
import { wordpress, wordpressExternals } from "@nabasa/vp-wp";
export default defineConfig({
plugins: [
wordpress({
entry: {
app: "resources/app.ts",
},
outDir: "assets/dist",
}),
wordpressExternals(),
],
});
```
Then run the usual Vite+ commands:
```sh
vp dev
vp build
```
`wordpress()` applies WordPress-friendly defaults:
- `base: './'`
- `build.manifest: 'manifest.json'`
- `build.modulePreload: false`
- `css.devSourcemap: true`
- a development manifest at `vite-dev-server.json`
These defaults keep asset URLs, manifests, and CSS handling aligned with WordPress expectations.
`wordpressExternals()` keeps common WordPress globals out of your bundle and treats React as external by default.
## PHP runtime
A typical enqueue setup looks like this:
```php
<?php
use function Nabasa\VitePlus\assets;
$vite = assets( __DIR__ . '/assets/dist' );
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
$vite->enqueue(
'resources/app.ts',
[
'handle' => 'my-plugin-app',
'dependencies' => [ 'react', 'react-dom' ],
'in_footer' => true,
]
);
} );
```
Exposed PHP runtime API:
Supported public API:
- `Nabasa\VitePlus\assets()` creates a reusable `Assets` helper.
- `Nabasa\VitePlus\register_asset()` registers an entry and extracted CSS.
- `Nabasa\VitePlus\enqueue_asset()` registers and enqueues an entry.
- `Nabasa\VitePlus\asset_url()` resolves a public asset URL.
- `Nabasa\VitePlus\Assets::__construct()` creates the helper directly.
- `Nabasa\VitePlus\Assets::manifest_dir()` gets the bound manifest directory.
- `Nabasa\VitePlus\Assets::scope()` gets the normalized scope.
- `Nabasa\VitePlus\Assets::register()` registers an entry.
- `Nabasa\VitePlus\Assets::enqueue()` registers and enqueues an entry.
- `Nabasa\VitePlus\Assets::url()` resolves an asset URL.
Advanced callable helpers:
- `Nabasa\VitePlus\filter_value()` applies shared and scoped filters.
- `Nabasa\VitePlus\normalize_scope()` sanitizes a hook scope.
- `Nabasa\VitePlus\get_manifest()` loads and caches manifest data.
- `Nabasa\VitePlus\parse_options()` merges options with defaults.
- `Nabasa\VitePlus\default_asset_handle()` generates a default handle.
- `Nabasa\VitePlus\stylesheet_handle()` generates a deterministic style handle.
- `Nabasa\VitePlus\prepare_asset_url()` builds a manifest base URL.
- `Nabasa\VitePlus\join_asset_url()` joins a base URL and asset path.
Internal and compatibility helpers:
- `Nabasa\VitePlus\load_development_asset()`
- `Nabasa\VitePlus\load_production_asset()`
- `Nabasa\VitePlus\register_stylesheets()`
- `Nabasa\VitePlus\register_vite_client_script()`
- `Nabasa\VitePlus\inject_react_refresh_preamble()`
- `Nabasa\VitePlus\development_asset_src()`
- `Nabasa\VitePlus\filter_script_tag()`
- `Nabasa\VitePlus\set_script_type_attribute()`
- `Nabasa\VitePlus\should_inject_react_refresh()`
- `Nabasa\VitePlus\string_ends_with()`
Core PHP filters:
- `nabasa_vite_plus/manifest_data`
- `nabasa_vite_plus/development_assets`
- `nabasa_vite_plus/production_assets`
- `nabasa_vite_plus/{scope}/manifest_data`
- `nabasa_vite_plus/{scope}/development_assets`
- `nabasa_vite_plus/{scope}/production_assets`
Use `assets()` when you want to bind a manifest directory once and reuse it across hooks or callbacks:
```php
<?php
use function Nabasa\VitePlus\assets;
$vite = assets( __DIR__ . '/assets/dist' );
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
$vite->enqueue( 'resources/app.ts', [
'handle' => 'theme-app',
] );
} );
```
Pass a second argument to `assets()` when you want a plugin- or theme-specific hook namespace:
```php
<?php
use function Nabasa\VitePlus\assets;
$vite = assets( __DIR__ . '/assets/dist', 'windpress' );
add_filter( 'nabasa_vite_plus/windpress/production_assets', function ( array $assets ) {
return $assets;
} );
```
Scoped helpers still trigger the shared `nabasa_vite_plus/*` hooks as well as the scoped `nabasa_vite_plus/{scope}/*` hooks. The scope is normalized with `sanitize_key()`.
If you prefer standalone functions, `register_asset()` and `enqueue_asset()` accept the same scope as a fourth argument.
Supported PHP options include:
- `handle`
- `dependencies`
- `css_dependencies`
- `css_media`
- `css_only`
- `in_footer`
During `vp dev`, `vp-wp` reads `vite-dev-server.json` and serves assets from the active dev server. During `vp build`, it reads `manifest.json` and registers the compiled JavaScript and extracted CSS assets.
Use `asset_url()` when you need the public URL for a file in the built assets directory without looking it up in the manifest:
```php
<?php
use function Nabasa\VitePlus\asset_url;
$logo_url = asset_url( __DIR__ . '/assets/dist', 'images/logo.svg' );
```
## Externals presets
Pick a preset when you want tighter control over which globals stay external:
```ts
wordpressExternals({ preset: "wordpress" });
```
Built-in presets:
- `wordpress`
- `wordpress+react`
You can also extend or trim the externals map to fit your project:
```ts
wordpressExternals({
include: {
"@acme/ui": "AcmeUI",
},
exclude: ["lodash"],
});
```
## Development
```sh
vp install
vp check
vp test
vp pack
```
## Credits
`vp-wp` is a fork and rewrite inspired by [`@kucrut/vite-for-wp`](https://github.com/kucrut/vite-for-wp).
## Examples
Need a working reference? See [`examples/README.md`](examples/README.md) for React, Vue, Svelte, SolidJS, and vanilla JavaScript. Each example includes the full plugin structure, Vite config, PHP bootstrap, and frontend entry for its framework.
@@ -0,0 +1,24 @@
{
"name": "nabasa\/vp-wp",
"description": "WordPress integration for Vite+.",
"type": "library",
"license": "MIT",
"homepage": "https:\/\/github.com\/nabasa-dev\/vp-wp",
"keywords": [
"vite",
"vite-plus",
"wordpress"
],
"support": {
"issues": "https:\/\/github.com\/nabasa-dev\/vp-wp\/issues",
"source": "https:\/\/github.com\/nabasa-dev\/vp-wp"
},
"require": {
"php": ">=7.4"
},
"autoload": {
"files": [
"vp-wp.php"
]
}
}
@@ -0,0 +1,255 @@
# Migrating from `vite-for-wp`
`vp-wp` is a fork and rewrite inspired by [`@kucrut/vite-for-wp`](https://github.com/kucrut/vite-for-wp).
If your plugin or theme already uses `vite-for-wp`, the migration is mostly mechanical:
1. replace the JavaScript and Composer package names
2. swap `v4wp()` for `wordpress()`
3. rename a few PHP option keys from kebab-case to snake_case
4. update any runtime filter names
You do not need to rename your source folders. If your project already uses paths like `js/src` and `js/dist`, you can keep them.
## Quick mapping
| `vite-for-wp` | `vp-wp` | Notes |
| ------------------------------ | --------------------------------- | ------------------------ |
| `@kucrut/vite-for-wp` | `@nabasa/vp-wp` | JavaScript package |
| `kucrut/vite-for-wp` | `nabasa/vp-wp` | Composer package |
| `v4wp()` | `wordpress()` | Vite+ plugin |
| `input` | `entry` | JavaScript plugin option |
| `wp_scripts()` | `wordpressExternals()` | Externals helper |
| `wp_scripts({ extraScripts })` | `wordpressExternals({ include })` | Add custom globals |
| `Kucrut\Vite` | `Nabasa\VitePlus` | PHP namespace |
| `css-dependencies` | `css_dependencies` | PHP option key |
| `css-media` | `css_media` | PHP option key |
| `css-only` | `css_only` | PHP option key |
| `in-footer` | `in_footer` | PHP option key |
| `vite_for_wp__*` | `nabasa_vite_plus/*` | Runtime filters |
## 1. Replace dependencies
Install the new packages with your preferred package manager. With `pnpm`, that looks like this:
```sh
pnpm remove vite @kucrut/vite-for-wp
pnpm add -D vite-plus @nabasa/vp-wp
composer remove kucrut/vite-for-wp
composer require nabasa/vp-wp
```
If you previously copied `vite-for-wp.php` into your project instead of using Composer, replace it with `vp-wp.php` from this repository and update your `require` path.
## 2. Update your Vite config
Before:
```js
import { v4wp } from "@kucrut/vite-for-wp";
import { wp_scripts } from "@kucrut/vite-for-wp/plugins";
import react from "@vitejs/plugin-react";
export default {
plugins: [
react(),
v4wp({
input: {
app: "js/src/main.jsx",
},
outDir: "js/dist",
}),
wp_scripts(),
],
};
```
After:
```js
import { defineConfig } from "vite-plus";
import react from "@vitejs/plugin-react";
import { wordpress, wordpressExternals } from "@nabasa/vp-wp";
export default defineConfig({
plugins: [
react(),
wordpress({
entry: {
app: "js/src/main.jsx",
},
outDir: "js/dist",
}),
wordpressExternals(),
],
});
```
What changed:
- import `defineConfig` from `vite-plus`
- replace `v4wp()` with `wordpress()`
- rename `input` to `entry`
- replace `wp_scripts()` with `wordpressExternals()`
- replace `extraScripts` with `include` if you add custom externals
- use `exclude` when you want to remove a default external
Example externals migration:
```js
wordpressExternals({
include: {
"@acme/ui": "AcmeUI",
},
exclude: ["lodash"],
});
```
Unlike `vite-for-wp`, `vp-wp` already ships the dependencies needed by `wordpressExternals()`, so you do not need to install `rollup-plugin-external-globals` or `vite-plugin-external` yourself.
## 3. Update package scripts
Switch your scripts from Vite commands to Vite+ commands:
```json
{
"scripts": {
"dev": "vp dev",
"build": "vp build"
}
}
```
## 4. Update PHP imports and option keys
Before:
```php
<?php
use Kucrut\Vite;
add_action( 'wp_enqueue_scripts', function (): void {
Vite\enqueue_asset(
__DIR__ . '/js/dist',
'js/src/main.jsx',
[
'handle' => 'my-plugin-app',
'dependencies' => [ 'react', 'react-dom' ],
'css-dependencies' => [ 'wp-components' ],
'css-media' => 'all',
'css-only' => false,
'in-footer' => true,
]
);
} );
```
After:
```php
<?php
use function Nabasa\VitePlus\enqueue_asset;
add_action( 'wp_enqueue_scripts', function (): void {
enqueue_asset(
__DIR__ . '/js/dist',
'js/src/main.jsx',
[
'handle' => 'my-plugin-app',
'dependencies' => [ 'react', 'react-dom' ],
'css_dependencies' => [ 'wp-components' ],
'css_media' => 'all',
'css_only' => false,
'in_footer' => true,
]
);
} );
```
`register_asset()` and `enqueue_asset()` still exist, but they now live under the `Nabasa\VitePlus` namespace and expect snake_case option keys.
If you were calling lower-level PHP helpers directly, use this mapping:
| `vite-for-wp` | `vp-wp` | Notes |
| ---------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------------- |
| `Kucrut\Vite\get_manifest()` | `Nabasa\VitePlus\get_manifest()` | Same role; adds `$scope` and passes `$is_dev` to filters |
| `Kucrut\Vite\filter_script_tag()` | `Nabasa\VitePlus\filter_script_tag()` | Same role; duplicate handle filters are skipped |
| `Kucrut\Vite\set_script_type_attribute()` | `Nabasa\VitePlus\set_script_type_attribute()` | Same role |
| `Kucrut\Vite\generate_development_asset_src()` | `Nabasa\VitePlus\development_asset_src()` | Renamed; same role |
| `Kucrut\Vite\register_vite_client_script()` | `Nabasa\VitePlus\register_vite_client_script()` | Same role |
| `Kucrut\Vite\inject_react_refresh_preamble_script()` | `Nabasa\VitePlus\inject_react_refresh_preamble()` | Renamed; also supports `reactRefresh` |
| `Kucrut\Vite\load_development_asset()` | `Nabasa\VitePlus\load_development_asset()` | Same role; adds `$scope` and deduplicates dependencies |
| `Kucrut\Vite\load_production_asset()` | `Nabasa\VitePlus\load_production_asset()` | Same role; adds `$scope` and scoped filters |
| `Kucrut\Vite\register_stylesheets()` | `Nabasa\VitePlus\register_stylesheets()` | Same role; style handles are hashed and deduplicated |
| `Kucrut\Vite\parse_options()` | `Nabasa\VitePlus\parse_options()` | Same role; defaults use snake_case keys |
| `Kucrut\Vite\prepare_asset_url()` | `Nabasa\VitePlus\prepare_asset_url()` | Same role |
| `Kucrut\Vite\register_asset()` | `Nabasa\VitePlus\register_asset()` | Same role; adds `$scope` and default handle generation |
| `Kucrut\Vite\enqueue_asset()` | `Nabasa\VitePlus\enqueue_asset()` | Same role; adds `$scope` and default handle generation |
New in `vp-wp`:
- `Nabasa\VitePlus\assets()`
- `Nabasa\VitePlus\asset_url()`
- `Nabasa\VitePlus\filter_value()`
- `Nabasa\VitePlus\normalize_scope()`
- `Nabasa\VitePlus\default_asset_handle()`
- `Nabasa\VitePlus\stylesheet_handle()`
- `Nabasa\VitePlus\join_asset_url()`
## 5. Optional: adopt the `assets()` helper
`vp-wp` adds an `assets()` helper that binds a manifest directory once and lets you reuse it across hooks:
```php
<?php
use function Nabasa\VitePlus\assets;
$vite = assets( __DIR__ . '/js/dist', 'my-plugin' );
add_action( 'wp_enqueue_scripts', function () use ( $vite ): void {
$vite->enqueue( 'js/src/main.jsx', [
'handle' => 'my-plugin-app',
'dependencies' => [ 'react', 'react-dom' ],
'in_footer' => true,
] );
} );
```
The optional second argument is a scope. Scoped helpers still run the shared hooks and also add scope-specific hooks like `nabasa_vite_plus/my-plugin/production_assets`.
## 6. Update runtime filters
If you hooked into `vite-for-wp` filters, rename them like this:
| `vite-for-wp` | `vp-wp` |
| --------------------------------- | ------------------------------------- |
| `vite_for_wp__manifest_data` | `nabasa_vite_plus/manifest_data` |
| `vite_for_wp__development_assets` | `nabasa_vite_plus/development_assets` |
| `vite_for_wp__production_assets` | `nabasa_vite_plus/production_assets` |
Notes:
- `nabasa_vite_plus/manifest_data` now also receives `$is_dev` as the last callback argument
- scoped variants are available as `nabasa_vite_plus/{scope}/manifest_data`, `nabasa_vite_plus/{scope}/development_assets`, and `nabasa_vite_plus/{scope}/production_assets`
- generated CSS handles now include a hash suffix, so avoid hardcoding them; if you need exact handles, read the return value from `register_asset()`
## 7. Verify the migration
After updating the config and runtime calls:
```sh
vp dev
vp build
```
Then confirm that:
- `vite-dev-server.json` is written during development
- `manifest.json` is written during builds
- your WordPress page loads the expected entrypoint
- CSS files still load in production
- any custom runtime filters still fire with their updated names
@@ -0,0 +1,479 @@
<?php
declare (strict_types=1);
namespace JooosiFonDeps\Nabasa\VitePlus;
use Exception;
use WP_HTML_Tag_Processor;
const DEV_MANIFEST_FILE = 'vite-dev-server.json';
const VITE_CLIENT_HANDLE = 'vp-wp-client';
/**
* Reusable asset helper bound to a single manifest directory.
*/
final class Assets
{
private string $manifest_dir;
private string $scope;
/**
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
* and `vite-dev-server.json`.
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
*/
public function __construct(string $manifest_dir, string $scope = '')
{
$this->manifest_dir = $manifest_dir;
$this->scope = normalize_scope($scope);
}
/**
* @return string Absolute path to the bound manifest directory.
*/
public function manifest_dir(): string
{
return $this->manifest_dir;
}
/**
* @return string Normalized hook scope for this asset helper.
*/
public function scope(): string
{
return $this->scope;
}
/**
* Register a Vite entry and its extracted CSS files.
*
* @param string $entry Manifest entry key, such as `resources/app.ts`.
* @param array{
* handle?: string,
* dependencies?: list<string>,
* css_dependencies?: list<string>,
* css_media?: string,
* css_only?: bool,
* in_footer?: bool
* } $options Asset registration options.
* @return array{
* scripts: list<string>,
* styles: list<string>
* }|null Registered WordPress handles or `null` when registration fails.
*/
public function register(string $entry, array $options = []): ?array
{
return register_asset($this->manifest_dir, $entry, $options, $this->scope);
}
/**
* Register and immediately enqueue a Vite entry.
*
* @param string $entry Manifest entry key, such as `resources/app.ts`.
* @param array{
* handle?: string,
* dependencies?: list<string>,
* css_dependencies?: list<string>,
* css_media?: string,
* css_only?: bool,
* in_footer?: bool
* } $options Asset enqueue options.
* @return bool True when at least the registration flow succeeds, otherwise false.
*/
public function enqueue(string $entry, array $options = []): bool
{
return enqueue_asset($this->manifest_dir, $entry, $options, $this->scope);
}
/**
* Resolve the public URL for a file inside the bound manifest directory.
*
* @param string $asset Relative asset path inside the manifest directory.
* @return string Public asset URL.
*/
public function url(string $asset = ''): string
{
return asset_url($this->manifest_dir, $asset);
}
}
/**
* Create a reusable asset helper for a manifest directory.
*
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
* and `vite-dev-server.json`.
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
*/
function assets(string $manifest_dir, string $scope = ''): Assets
{
return new Assets($manifest_dir, $scope);
}
/**
* Register and enqueue a Vite entry from a manifest directory.
*
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
* and `vite-dev-server.json`.
* @param string $entry Manifest entry key, such as `resources/app.ts`.
* @param array{
* handle?: string,
* dependencies?: list<string>,
* css_dependencies?: list<string>,
* css_media?: string,
* css_only?: bool,
* in_footer?: bool
* } $options Asset enqueue options.
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
* @return bool True when the asset flow succeeds, otherwise false.
*/
function enqueue_asset(string $manifest_dir, string $entry, array $options = [], string $scope = ''): bool
{
$assets = register_asset($manifest_dir, $entry, $options, $scope);
if (null === $assets) {
return \false;
}
$callbacks = ['scripts' => 'wp_enqueue_script', 'styles' => 'wp_enqueue_style'];
foreach ($assets as $group => $handles) {
$callback = $callbacks[$group];
foreach ($handles as $handle) {
$callback($handle);
}
}
return \true;
}
/**
* Register a Vite entry and its related assets from a manifest directory.
*
* @param string $manifest_dir Absolute path to the directory that contains `manifest.json`
* and `vite-dev-server.json`.
* @param string $entry Manifest entry key, such as `resources/app.ts`.
* @param array{
* handle?: string,
* dependencies?: list<string>,
* css_dependencies?: list<string>,
* css_media?: string,
* css_only?: bool,
* in_footer?: bool
* } $options Asset registration options.
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
* @return array{
* scripts: list<string>,
* styles: list<string>
* }|null Registered WordPress handles or `null` when registration fails.
*/
function register_asset(string $manifest_dir, string $entry, array $options = [], string $scope = ''): ?array
{
$scope = normalize_scope($scope);
try {
$manifest = get_manifest($manifest_dir, $scope);
} catch (Exception $exception) {
if (defined('WP_DEBUG') && \WP_DEBUG) {
wp_die(esc_html($exception->getMessage()));
}
return null;
}
$options = parse_options($options);
if ('' === $options['handle']) {
$options['handle'] = default_asset_handle($entry);
}
return $manifest->is_dev ? load_development_asset($manifest, $entry, $options, $scope) : load_production_asset($manifest, $entry, $options, $scope);
}
/**
* Load and cache the first available manifest for a directory.
*
* Prefers the Vite development manifest when present, then falls back to the
* production `manifest.json` file.
*
* @param string $manifest_dir Absolute path to the directory that contains manifest files.
* @param string $scope Optional hook scope. Scoped hooks are normalized with `sanitize_key()`.
* @return object{
* data: object,
* dir: string,
* is_dev: bool
* } Decoded manifest data with directory metadata.
* @throws Exception When no readable manifest exists or the manifest cannot be decoded.
*/
function get_manifest(string $manifest_dir, string $scope = ''): object
{
static $manifests = [];
$manifest_paths = ["{$manifest_dir}/" . DEV_MANIFEST_FILE, "{$manifest_dir}/manifest.json"];
foreach ($manifest_paths as $manifest_path) {
if (isset($manifests[$manifest_path])) {
return $manifests[$manifest_path];
}
if (is_file($manifest_path) && is_readable($manifest_path)) {
$is_dev = string_ends_with($manifest_path, DEV_MANIFEST_FILE);
break;
}
}
if (!isset($manifest_path, $is_dev)) {
throw new Exception(sprintf('[vp-wp] No manifest found in %s.', $manifest_dir));
}
$manifest = wp_json_file_decode($manifest_path, ['associative' => \false]);
if (!$manifest) {
throw new Exception(sprintf('[vp-wp] Failed to read manifest file %s.', $manifest_path));
}
$manifest = filter_value('manifest_data', $manifest, $scope, $manifest_dir, $manifest_path, $is_dev);
$manifests[$manifest_path] = (object) ['data' => $manifest, 'dir' => $manifest_dir, 'is_dev' => $is_dev];
return $manifests[$manifest_path];
}
function load_development_asset(object $manifest, string $entry, array $options, string $scope = ''): ?array
{
if (string_ends_with($entry, '.css')) {
$src = development_asset_src($manifest, $entry);
if (!wp_register_style($options['handle'], $src, $options['css_dependencies'], null, $options['css_media'])) {
return null;
}
$assets = ['scripts' => [], 'styles' => [$options['handle']]];
return filter_value('development_assets', $assets, $scope, $manifest, $entry, $options);
}
register_vite_client_script($manifest);
inject_react_refresh_preamble($manifest);
$dependencies = array_values(array_unique(array_merge([VITE_CLIENT_HANDLE], $options['dependencies'])));
$src = development_asset_src($manifest, $entry);
filter_script_tag($options['handle']);
if (!wp_register_script($options['handle'], $src, $dependencies, null, $options['in_footer'])) {
return null;
}
$assets = ['scripts' => [$options['handle']], 'styles' => $options['css_dependencies']];
return filter_value('development_assets', $assets, $scope, $manifest, $entry, $options);
}
function load_production_asset(object $manifest, string $entry, array $options, string $scope = ''): ?array
{
if (!isset($manifest->data->{$entry})) {
if (defined('WP_DEBUG') && \WP_DEBUG) {
wp_die(esc_html(sprintf('[vp-wp] Entry %s not found.', $entry)));
}
return null;
}
$item = $manifest->data->{$entry};
$url = asset_url($manifest->dir);
$assets = ['scripts' => [], 'styles' => []];
if (string_ends_with($item->file, '.css')) {
if (wp_register_style($options['handle'], join_asset_url($url, $item->file), $options['css_dependencies'], null, $options['css_media'])) {
$assets['styles'][] = $options['handle'];
}
return filter_value('production_assets', $assets, $scope, $manifest, $entry, $options);
}
if (!$options['css_only']) {
filter_script_tag($options['handle']);
if (wp_register_script($options['handle'], join_asset_url($url, $item->file), $options['dependencies'], null, $options['in_footer'])) {
$assets['scripts'][] = $options['handle'];
}
}
if (!empty($item->imports)) {
$register_imports = static function (array $imports) use (&$register_imports, &$assets, $manifest, $options, $url): void {
foreach ($imports as $import) {
$import_item = $manifest->data->{$import};
if (!empty($import_item->imports)) {
$register_imports($import_item->imports);
}
if (!empty($import_item->css)) {
register_stylesheets($assets, $import_item->css, $url, $options);
}
}
};
$register_imports($item->imports);
}
if (!empty($item->css)) {
register_stylesheets($assets, $item->css, $url, $options);
}
return filter_value('production_assets', $assets, $scope, $manifest, $entry, $options);
}
/**
* Merge asset registration options with package defaults.
*
* @param array{
* handle?: string,
* dependencies?: list<string>,
* css_dependencies?: list<string>,
* css_media?: string,
* css_only?: bool,
* in_footer?: bool
* } $options Partial asset options.
* @return array{
* handle: string,
* dependencies: list<string>,
* css_dependencies: list<string>,
* css_media: string,
* css_only: bool,
* in_footer: bool
* } Normalized asset options.
*/
function parse_options(array $options): array
{
return wp_parse_args($options, ['css_dependencies' => [], 'css_media' => 'all', 'css_only' => \false, 'dependencies' => [], 'handle' => '', 'in_footer' => \false]);
}
/**
* Generate a default WordPress handle from a manifest entry.
*
* @param string $entry Manifest entry key, such as `resources/app.ts`.
* @return string Sanitized lowercase handle.
*/
function default_asset_handle(string $entry): string
{
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', pathinfo($entry, \PATHINFO_FILENAME)), '-'));
}
function register_stylesheets(array &$assets, array $stylesheets, string $url, array $options): void
{
foreach ($stylesheets as $stylesheet) {
$style_handle = stylesheet_handle($options['handle'], $stylesheet);
if (in_array($style_handle, $assets['styles'], \true)) {
continue;
}
if (wp_register_style($style_handle, join_asset_url($url, $stylesheet), $options['css_dependencies'], null, $options['css_media'])) {
$assets['styles'][] = $style_handle;
}
}
}
/**
* Generate a deterministic stylesheet handle for a built CSS asset.
*
* @param string $handle Base script or entry handle.
* @param string $stylesheet Relative stylesheet path from the manifest.
* @return string Stable stylesheet handle.
*/
function stylesheet_handle(string $handle, string $stylesheet): string
{
$normalized_stylesheet = trim(wp_normalize_path($stylesheet), '/');
$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', pathinfo($normalized_stylesheet, \PATHINFO_FILENAME)), '-'));
$hash = substr(md5($normalized_stylesheet), 0, 8);
return "{$handle}-{$slug}-{$hash}";
}
function register_vite_client_script(object $manifest): void
{
if (wp_script_is(VITE_CLIENT_HANDLE, 'registered')) {
return;
}
$src = development_asset_src($manifest, '@vite/client');
wp_register_script(VITE_CLIENT_HANDLE, $src, [], null, \false);
filter_script_tag(VITE_CLIENT_HANDLE);
}
function inject_react_refresh_preamble(object $manifest): void
{
static $did_print_preamble = \false;
if ($did_print_preamble || !should_inject_react_refresh($manifest->data)) {
return;
}
$script = <<<JS
import RefreshRuntime from "{$manifest->data->origin}/@react-refresh";
RefreshRuntime.injectIntoGlobalHook(window);
window.\$RefreshReg\$ = () => {};
window.\$RefreshSig\$ = () => (type) => type;
window.__vite_plugin_react_preamble_installed__ = true;
JS;
wp_add_inline_script(VITE_CLIENT_HANDLE, $script, 'after');
add_filter('wp_inline_script_attributes', static function (array $attributes): array {
if (isset($attributes['id']) && VITE_CLIENT_HANDLE . '-js-after' === $attributes['id']) {
$attributes['type'] = 'module';
}
return $attributes;
});
$did_print_preamble = \true;
}
function development_asset_src(object $manifest, string $entry): string
{
$base = trim(preg_replace('/[\/]{2,}/', '/', "{$manifest->data->base}/{$entry}"), '/');
return sprintf('%s/%s', untrailingslashit($manifest->data->origin), $base);
}
function filter_script_tag(string $handle): void
{
static $filtered_handles = [];
if (isset($filtered_handles[$handle])) {
return;
}
add_filter('script_loader_tag', static fn(...$args) => set_script_type_attribute($handle, ...$args), 10, 3);
$filtered_handles[$handle] = \true;
}
function set_script_type_attribute(string $target_handle, string $tag, string $handle, string $src): string
{
if ($target_handle !== $handle) {
return $tag;
}
$processor = new WP_HTML_Tag_Processor($tag);
while ($processor->next_tag('script')) {
if ($processor->get_attribute('src') === $src) {
$processor->set_attribute('type', 'module');
break;
}
}
return $processor->get_updated_html();
}
/**
* Build a public base URL for assets inside a manifest directory.
*
* The resulting URL is normalized so it works for assets located inside plugin
* or theme directories under `wp-content`.
*
* @param string $dir Absolute path to the manifest directory.
* @return string Public base URL for the manifest directory.
*/
function prepare_asset_url(string $dir): string
{
$content_dir = wp_normalize_path(\WP_CONTENT_DIR);
$manifest_dir = wp_normalize_path($dir);
$url = content_url(str_replace($content_dir, '', $manifest_dir));
$url_matches_pattern = preg_match('/(?<address>http(?:s?):\/\/.*\/)(?<fullPath>wp-content(?<removablePath>\/.*)\/(?:plugins|themes)\/.*)/', $url, $url_parts);
if (0 === $url_matches_pattern) {
return $url;
}
['address' => $address, 'fullPath' => $full_path, 'removablePath' => $removable_path] = $url_parts;
return sprintf('%s%s', $address, str_replace($removable_path, '', $full_path));
}
/**
* Apply both global and optional scoped filters for the runtime.
*
* @param string $hook Hook suffix, such as `manifest_data`.
* @param mixed $value Filtered value.
* @param string $scope Normalized hook scope.
* @param mixed ...$args Additional filter arguments.
* @return mixed Filtered value.
*/
function filter_value(string $hook, $value, string $scope = '', ...$args)
{
$value = apply_filters("nabasa_vite_plus/{$hook}", $value, ...$args);
if ('' === $scope) {
return $value;
}
return apply_filters("nabasa_vite_plus/{$scope}/{$hook}", $value, ...$args);
}
/**
* Normalize a hook scope so it is safe to use in dynamic hook names.
*
* @param string $scope Raw hook scope.
* @return string Normalized scope.
*/
function normalize_scope(string $scope): string
{
return sanitize_key($scope);
}
function should_inject_react_refresh(object $manifest_data): bool
{
if (!empty($manifest_data->reactRefresh)) {
return \true;
}
return isset($manifest_data->plugins) && is_array($manifest_data->plugins) && in_array('vite:react-refresh', $manifest_data->plugins, \true);
}
function string_ends_with(string $value, string $suffix): bool
{
if ('' === $suffix) {
return \true;
}
return substr($value, -strlen($suffix)) === $suffix;
}
/**
* Resolve the public URL for a file inside a manifest directory.
*
* @param string $manifest_dir Absolute path to the directory that contains built assets.
* @param string $asset Relative asset path inside the manifest directory.
* @return string Public asset URL.
*/
function asset_url(string $manifest_dir, string $asset = ''): string
{
$base_url = prepare_asset_url($manifest_dir);
if ('' === $asset) {
return $base_url;
}
return join_asset_url($base_url, $asset);
}
/**
* Join a base asset URL with a relative asset path.
*
* @param string $base_url Base public URL.
* @param string $asset Relative asset path.
* @return string Combined asset URL.
*/
function join_asset_url(string $base_url, string $asset): string
{
return sprintf('%s/%s', untrailingslashit($base_url), ltrim($asset, '/'));
}
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Paragon Initiative Enterprises
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) )
php -dphar.readonly=0 "$basedir/other/build_phar.php" $*
@@ -0,0 +1,34 @@
{
"name": "paragonie\/random_compat",
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
"keywords": [
"csprng",
"random",
"polyfill",
"pseudorandom"
],
"license": "MIT",
"type": "library",
"authors": [
{
"name": "Paragon Initiative Enterprises",
"email": "security@paragonie.com",
"homepage": "https:\/\/paragonie.com"
}
],
"support": {
"issues": "https:\/\/github.com\/paragonie\/random_compat\/issues",
"email": "info@paragonie.com",
"source": "https:\/\/github.com\/paragonie\/random_compat"
},
"require": {
"php": ">= 7"
},
"require-dev": {
"vimeo\/psalm": "^1",
"phpunit\/phpunit": "4.*|5.*"
},
"suggest": {
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
}
}
@@ -0,0 +1,5 @@
-----BEGIN PUBLIC KEY-----
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm
pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p
+h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc
-----END PUBLIC KEY-----
@@ -0,0 +1,11 @@
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.22 (MingW32)
iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip
QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg
1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW
NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA
NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV
JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74=
=B6+8
-----END PGP SIGNATURE-----
@@ -0,0 +1,34 @@
<?php
namespace JooosiFonDeps;
/**
* Random_* Compatibility Library
* for using the new PHP 7 random_* API in PHP 5 projects
*
* @version 2.99.99
* @released 2018-06-06
*
* The MIT License (MIT)
*
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// NOP
@@ -0,0 +1,44 @@
<?php
namespace JooosiFonDeps;
$dist = \dirname(__DIR__) . '/dist';
if (!\is_dir($dist)) {
\mkdir($dist, 0755);
}
if (\file_exists($dist . '/random_compat.phar')) {
\unlink($dist . '/random_compat.phar');
}
$phar = new \Phar($dist . '/random_compat.phar', \FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME, 'random_compat.phar');
\rename(\dirname(__DIR__) . '/lib/random.php', \dirname(__DIR__) . '/lib/index.php');
$phar->buildFromDirectory(\dirname(__DIR__) . '/lib');
\rename(\dirname(__DIR__) . '/lib/index.php', \dirname(__DIR__) . '/lib/random.php');
/**
* If we pass an (optional) path to a private key as a second argument, we will
* sign the Phar with OpenSSL.
*
* If you leave this out, it will produce an unsigned .phar!
*/
if ($argc > 1) {
if (!@\is_readable($argv[1])) {
echo 'Could not read the private key file:', $argv[1], "\n";
exit(255);
}
$pkeyFile = \file_get_contents($argv[1]);
$private = \openssl_get_privatekey($pkeyFile);
if ($private !== \false) {
$pkey = '';
\openssl_pkey_export($private, $pkey);
$phar->setSignatureAlgorithm(\Phar::OPENSSL, $pkey);
/**
* Save the corresponding public key to the file
*/
if (!@\is_readable($dist . '/random_compat.phar.pubkey')) {
$details = \openssl_pkey_get_details($private);
\file_put_contents($dist . '/random_compat.phar.pubkey', $details['key']);
}
} else {
echo 'An error occurred reading the private key from OpenSSL.', "\n";
exit(255);
}
}
@@ -0,0 +1,10 @@
<?php
namespace JooosiFonDeps;
require_once 'lib/byte_safe_strings.php';
require_once 'lib/cast_to_int.php';
require_once 'lib/error_polyfill.php';
require_once 'other/ide_stubs/libsodium.php';
require_once 'lib/random.php';
$int = \random_int(0, 65536);
@@ -0,0 +1,19 @@
<?xml version="1.0"?>
<psalm
autoloader="psalm-autoload.php"
stopOnFirstError="false"
useDocblockTypes="true"
>
<projectFiles>
<directory name="lib" />
</projectFiles>
<issueHandlers>
<RedundantConditionGivenDocblockType errorLevel="info" />
<UnresolvableInclude errorLevel="info" />
<DuplicateClass errorLevel="info" />
<InvalidOperand errorLevel="info" />
<UndefinedConstant errorLevel="info" />
<MissingReturnType errorLevel="info" />
<InvalidReturnType errorLevel="info" />
</issueHandlers>
</psalm>
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2013-2016 container-interop
Copyright (c) 2016 PHP Framework Interoperability Group
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,13 @@
Container interface
==============
This repository holds all interfaces related to [PSR-11 (Container Interface)][psr-url].
Note that this is not a Container implementation of its own. It is merely abstractions that describe the components of a Dependency Injection Container.
The installable [package][package-url] and [implementations][implementation-url] are listed on Packagist.
[psr-url]: https://www.php-fig.org/psr/psr-11/
[package-url]: https://packagist.org/packages/psr/container
[implementation-url]: https://packagist.org/providers/psr/container-implementation
@@ -0,0 +1,28 @@
{
"name": "psr\/container",
"type": "library",
"description": "Common Container Interface (PHP FIG PSR-11)",
"keywords": [
"psr",
"psr-11",
"container",
"container-interop",
"container-interface"
],
"homepage": "https:\/\/github.com\/php-fig\/container",
"license": "MIT",
"authors": [
{
"name": "PHP-FIG",
"homepage": "https:\/\/www.php-fig.org\/"
}
],
"require": {
"php": ">=7.4.0"
},
"autoload": {
"psr-4": {
"JooosiFonDeps\\Psr\\Container\\": "src\/"
}
}
}
@@ -0,0 +1,11 @@
<?php
namespace JooosiFonDeps\Psr\Container;
use Throwable;
/**
* Base interface representing a generic exception in a container.
*/
interface ContainerExceptionInterface extends Throwable
{
}
@@ -0,0 +1,34 @@
<?php
declare (strict_types=1);
namespace JooosiFonDeps\Psr\Container;
/**
* Describes the interface of a container that exposes methods to read its entries.
*/
interface ContainerInterface
{
/**
* Finds an entry of the container by its identifier and returns it.
*
* @param string $id Identifier of the entry to look for.
*
* @throws NotFoundExceptionInterface No entry was found for **this** identifier.
* @throws ContainerExceptionInterface Error while retrieving the entry.
*
* @return mixed Entry.
*/
public function get(string $id);
/**
* Returns true if the container can return an entry for the given identifier.
* Returns false otherwise.
*
* `has($id)` returning true does not mean that `get($id)` will not throw an exception.
* It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface`.
*
* @param string $id Identifier of the entry to look for.
*
* @return bool
*/
public function has(string $id);
}
@@ -0,0 +1,10 @@
<?php
namespace JooosiFonDeps\Psr\Container;
/**
* No entry was found in the container.
*/
interface NotFoundExceptionInterface extends ContainerExceptionInterface
{
}
@@ -0,0 +1,33 @@
<?php
declare(strict_types=1);
/**
* Compatibility stub for the first update from Yabe Webfont.
*
* WordPress keeps the old plugin classes in memory while it replaces the
* plugin directory. The old Migrator can therefore run after the new package
* has removed vendor/rosua/migrations. Keep the class available for that one
* request; the new migration manager takes over on the next request.
*/
namespace _YabeWebfont\Rosua\Migrations;
final class MigrationRepository
{
/**
* @param mixed $configuration
*/
public function __construct($configuration)
{
}
/**
* The new package owns migration discovery and execution.
*
* @return array<string, array{version: string, executed: bool, executed_at: null, execution_time: null}>
*/
public function getMigrationVersions(): array
{
return [];
}
}
@@ -0,0 +1,400 @@
# Changelog
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/).
## x.y.z
### Added
### Changed
### Deprecated
### Removed
### Fixed
## 8.8.0: Bug fixes and deprecations
### Added
- `OutputFormat` properties for space around specific list separators (#880)
### Changed
- Mark the `OutputFormat` the constructor as `@internal` (#1131)
- Mark `OutputFormatter` as `@internal` (#896)
- Mark `Selector::isValid()` as `@internal` (#1037)
- Mark parsing-related methods of most CSS elements as `@internal` (#908)
- Mark `OutputFormat::nextLevel()` as `@internal` (#901)
- Make all non-private properties `@internal` (#886)
### Deprecated
- Deprecate extending `OutputFormat` (#1131)
- Deprecate `OutputFormat::get()` and `::set()` (#1107)
- Deprecate support for `-webkit-calc` and `-moz-calc` (#1086)
- Deprecate `__toString()` (#1006)
- Deprecate greedy calculation of selector specificity (#1018)
- Deprecate the IE hack in `Rule` (#993, #1003)
- `OutputFormat` properties for space around list separators as an array (#880)
- Deprecate `OutputFormat::level()` (#870)
### Fixed
- Include comments for all rules in declaration block (#1169)
- Render rules in line and column number order (#1059)
- Create `Size` with correct types in `expandBackgroundShorthand` (#814)
- Parse `@font-face` `src` property as comma-delimited list (#794)
## 8.7.0: Add support for PHP 8.4
### Added
- Add support for PHP 8.4 (#675, #701, #746, #751)
### Changed
- Mark parsing-internal classes and methods as `@internal` (#711)
- Block installations on unsupported higher PHP versions (#691)
### Deprecated
- Deprecate magic method forwarding from `OutputFormat` to `OutputFormatter`
(#894)
- Deprecate the expansion of shorthand properties (#719)
- Deprecate `Parser::setCharset()` and `Parser::getCharset()` (#703)
### Fixed
- Fix type errors in PHP strict mode (#695)
## 8.6.0
### Added
- Support arithmetic operators in CSS function arguments (#607)
- Add support for inserting an item in a CSS list (#545)
- Add support for the `dvh`, `lvh` and `svh` length units (#415)
### Changed
- Improve performance of Value::parseValue with many delimiters by refactoring
to remove `array_search()` (#413)
## 8.5.2
### Changed
- Mark all class constants as `@internal` (#500)
### Fixed
- Fix undefined local variable in `CalcFunction::parse()` (#593)
## 8.5.1
### Fixed
- Fix PHP notice caused by parsing invalid color values having less than
6 characters (#485)
- Fix (regression) failure to parse at-rules with strict parsing (#456)
## 8.5.0
### Added
- Add a method to get an import's media queries (#384)
- Add more unit tests (#381, #382)
### Fixed
- Retain CSSList and Rule comments when rendering CSS (#351)
- Replace invalid `turns` unit with `turn` (#350)
- Also allow string values for rules (#348)
- Fix invalid calc parsing (#169)
- Handle scientific notation when parsing sizes (#179)
- Fix PHP 8.1 compatibility in `ParserState::strsplit()` (#344)
## 8.4.0
### Features
* Support for PHP 8.x
* PHPDoc annotations
* Allow usage of CSS variables inside color functions (by parsing them as
regular functions)
* Use PSR-12 code style
* *No deprecations*
### Bugfixes
* Improved handling of whitespace in `calc()`
* Fix parsing units whose prefix is also a valid unit, like `vmin`
* Allow passing an object to `CSSList#replace`
* Fix PHP 7.3 warnings
* Correctly parse keyframes with `%`
* Don’t convert large numbers to scientific notation
* Allow a file to end after an `@import`
* Preserve case of CSS variables as specced
* Allow identifiers to use escapes the same way as strings
* No longer use `eval` for the comparison in `getSelectorsBySpecificity`, in
case it gets passed untrusted input (CVE-2020-13756). Also fixed in 8.3.1,
8.2.1, 8.1.1, 8.0.1, 7.0.4, 6.0.2, 5.2.1, 5.1.3, 5.0.9, 4.0.1, 3.0.1, 2.0.1,
1.0.1.
* Prevent an infinite loop when parsing invalid grid line names
* Remove invalid unit `vm`
* Retain rule order after expanding shorthands
### Backwards-incompatible changes
* PHP ≥ 5.6 is now required
* HHVM compatibility target dropped
## 8.3.0 (2019-02-22)
* Refactor parsing logic to mostly reside in the class files whose data
structure is to be parsed (this should eventually allow us to unit-test
specific parts of the parsing logic individually).
* Fix error in parsing `calc` expessions when the first operand is a negative
number, thanks to @raxbg.
* Support parsing CSS4 colors in hex notation with alpha values, thanks to
@raxbg.
* Swallow more errors in lenient mode, thanks to @raxbg.
* Allow specifying arbitrary strings to output before and after declaration
blocks, thanks to @westonruter.
* *No backwards-incompatible changes*
* *No deprecations*
## 8.2.0 (2018-07-13)
* Support parsing `calc()`, thanks to @raxbg.
* Support parsing grid-lines, again thanks to @raxbg.
* Support parsing legacy IE filters (`progid:`) in lenient mode, thanks to
@FMCorz
* Performance improvements parsing large files, again thanks to @FMCorz
* *No backwards-incompatible changes*
* *No deprecations*
## 8.1.0 (2016-07-19)
* Comments are no longer silently ignored but stored with the object with which
they appear (no render support, though). Thanks to @FMCorz.
* The IE hacks using `\0` and `\9` can now be parsed (and rendered) in lenient
mode. Thanks (again) to @FMCorz.
* Media queries with or without spaces before the query are parsed. Still no
*real* parsing support, though. Sorry…
* PHPUnit is now listed as a dev-dependency in composer.json.
* *No backwards-incompatible changes*
* *No deprecations*
## 8.0.0 (2016-06-30)
* Store source CSS line numbers in tokens and parsing exceptions.
* *No deprecations*
### Backwards-incompatible changes
* Unrecoverable parser errors throw an exception of type
`Sabberworm\CSS\Parsing\SourceException` instead of `\Exception`.
## 7.0.3 (2016-04-27)
* Fixed parsing empty CSS when multibyte is off
* *No backwards-incompatible changes*
* *No deprecations*
## 7.0.2 (2016-02-11)
* 150 time performance boost thanks
to @[ossinkine](https://github.com/ossinkine)
* *No backwards-incompatible changes*
* *No deprecations*
## 7.0.1 (2015-12-25)
* No more suppressed `E_NOTICE`
* *No backwards-incompatible changes*
* *No deprecations*
## 7.0.0 (2015-08-24)
* Compatibility with PHP 7. Well timed, eh?
* *No deprecations*
### Backwards-incompatible changes
* The `Sabberworm\CSS\Value\String` class has been renamed to
`Sabberworm\CSS\Value\CSSString`.
## 6.0.1 (2015-08-24)
* Remove some declarations in interfaces incompatible with PHP 5.3 (< 5.3.9)
* *No deprecations*
## 6.0.0 (2014-07-03)
* Format output using Sabberworm\CSS\OutputFormat
* *No backwards-incompatible changes*
### Deprecations
* The parse() method replaces __toString with an optional argument (instance of
the OutputFormat class)
## 5.2.0 (2014-06-30)
* Support removing a selector from a declaration block using
`$oBlock->removeSelector($mSelector)`
* Introduce a specialized exception (Sabberworm\CSS\Parsing\OuputException) for
exceptions during output rendering
* *No deprecations*
#### Backwards-incompatible changes
* Outputting a declaration block that has no selectors throws an OuputException
instead of outputting an invalid ` {…}` into the CSS document.
## 5.1.2 (2013-10-30)
* Remove the use of consumeUntil in comment parsing. This makes it possible to
parse comments such as `/** Perfectly valid **/`
* Add fr relative size unit
* Fix some issues with HHVM
* *No backwards-incompatible changes*
* *No deprecations*
## 5.1.1 (2013-10-28)
* Updated CHANGELOG.md to reflect changes since 5.0.4
* *No backwards-incompatible changes*
* *No deprecations*
## 5.1.0 (2013-10-24)
* Performance enhancements by Michael M Slusarz
* More rescue entry points for lenient parsing (unexpected tokens between
declaration blocks and unclosed comments)
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.8 (2013-08-15)
* Make default settings’ multibyte parsing option dependent on whether or not
the mbstring extension is actually installed.
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.7 (2013-08-04)
* Fix broken decimal point output optimization
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.6 (2013-05-31)
* Fix broken unit test
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.5 (2013-04-17)
* Initial support for lenient parsing (setting this parser option will catch
some exceptions internally and recover the parser’s state as neatly as
possible).
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.4 (2013-03-21)
* Don’t output floats with locale-aware separator chars
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.3 (2013-03-21)
* More size units recognized
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.2 (2013-03-21)
* CHANGELOG.md file added to distribution
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.1 (2013-03-20)
* Internal cleanup
* *No backwards-incompatible changes*
* *No deprecations*
## 5.0.0 (2013-03-20)
* Correctly parse all known CSS 3 units (including Hz and kHz).
* Output RGB colors in short (#aaa or #ababab) notation
* Be case-insensitive when parsing identifiers.
* *No deprecations*
### Backwards-incompatible changes
* `Sabberworm\CSS\Value\Color`’s `__toString` method overrides `CSSList`’s to
maybe return something other than `type(value, …)` (see above).
## 4.0.0 (2013-03-19)
* Support for more @-rules
* Generic interface `Sabberworm\CSS\Property\AtRule`, implemented by all @-rule
classes
* *No deprecations*
### Backwards-incompatible changes
* `Sabberworm\CSS\RuleSet\AtRule` renamed to `Sabberworm\CSS\RuleSet\AtRuleSet`
* `Sabberworm\CSS\CSSList\MediaQuery` renamed to
`Sabberworm\CSS\RuleSet\CSSList\AtRuleBlockList` with differing semantics and
API (which also works for other block-list-based @-rules like `@supports`).
## 3.0.0 (2013-03-06)
* Support for lenient parsing (on by default)
* *No deprecations*
### Backwards-incompatible changes
* All properties (like whether or not to use `mb_`-functions, which default
charset to use and – new – whether or not to be forgiving when parsing) are
now encapsulated in an instance of `Sabberworm\CSS\Settings` which can be
passed as the second argument to `Sabberworm\CSS\Parser->__construct()`.
* Specifying a charset as the second argument to
`Sabberworm\CSS\Parser->__construct()` is no longer supported. Use
`Sabberworm\CSS\Settings::create()->withDefaultCharset('some-charset')`
instead.
* Setting `Sabberworm\CSS\Parser->bUseMbFunctions` has no effect. Use
`Sabberworm\CSS\Settings::create()->withMultibyteSupport(true/false)` instead.
* `Sabberworm\CSS\Parser->parse()` may throw a
`Sabberworm\CSS\Parsing\UnexpectedTokenException` when in strict parsing mode.
## 2.0.0 (2013-01-29)
* Allow multiple rules of the same type per rule set
### Backwards-incompatible changes
* `Sabberworm\CSS\RuleSet->getRules()` returns an index-based array instead of
an associative array. Use `Sabberworm\CSS\RuleSet->getRulesAssoc()` (which
eliminates duplicate rules and lets the later rule of the same name win).
* `Sabberworm\CSS\RuleSet->removeRule()` works as it did before except when
passed an instance of `Sabberworm\CSS\Rule\Rule`, in which case it would only
remove the exact rule given instead of all the rules of the same type. To get
the old behaviour, use `Sabberworm\CSS\RuleSet->removeRule($oRule->getRule()`;
## 1.0
Initial release of a stable public API.
## 0.9
Last version not to use PSR-0 project organization semantics.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2011 Raphael Schweikert, https://www.sabberworm.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,637 @@
# PHP CSS Parser
[![Build Status](https://github.com/sabberworm/PHP-CSS-Parser/workflows/CI/badge.svg?branch=master)](https://github.com/sabberworm/PHP-CSS-Parser/actions/)
A Parser for CSS Files written in PHP. Allows extraction of CSS files into a data structure, manipulation of said structure and output as (optimized) CSS.
## Usage
### Installation using Composer
```bash
composer require sabberworm/php-css-parser
```
### Extraction
To use the CSS Parser, create a new instance. The constructor takes the following form:
```php
new \Sabberworm\CSS\Parser($css);
```
To read a file, for example, you’d do the following:
```php
$parser = new \Sabberworm\CSS\Parser(file_get_contents('somefile.css'));
$cssDocument = $parser->parse();
```
The resulting CSS document structure can be manipulated prior to being output.
### Options
#### Charset
The charset option will only be used if the CSS file does not contain an `@charset` declaration. UTF-8 is the default, so you won’t have to create a settings object at all if you don’t intend to change that.
```php
$settings = \Sabberworm\CSS\Settings::create()
->withDefaultCharset('windows-1252');
$parser = new \Sabberworm\CSS\Parser($css, $settings);
```
#### Strict parsing
To have the parser throw an exception when encountering invalid/unknown constructs (as opposed to trying to ignore them and carry on parsing), supply a thusly configured `\Sabberworm\CSS\Settings` object:
```php
$parser = new \Sabberworm\CSS\Parser(
file_get_contents('somefile.css'),
\Sabberworm\CSS\Settings::create()->beStrict()
);
```
Note that this will also disable a workaround for parsing the unquoted variant of the legacy IE-specific `filter` rule.
#### Disable multibyte functions
To achieve faster parsing, you can choose to have PHP-CSS-Parser use regular string functions instead of `mb_*` functions. This should work fine in most cases, even for UTF-8 files, as all the multibyte characters are in string literals. Still it’s not recommended using this with input you have no control over as it’s not thoroughly covered by test cases.
```php
$settings = \Sabberworm\CSS\Settings::create()->withMultibyteSupport(false);
$parser = new \Sabberworm\CSS\Parser($css, $settings);
```
### Manipulation
The resulting data structure consists mainly of five basic types: `CSSList`, `RuleSet`, `Rule`, `Selector` and `Value`. There are two additional types used: `Import` and `Charset`, which you won’t use often.
#### CSSList
`CSSList` represents a generic CSS container, most likely containing declaration blocks (rule sets with a selector), but it may also contain at-rules, charset declarations, etc.
To access the items stored in a `CSSList` – like the document you got back when calling `$parser->parse()` –, use `getContents()`, then iterate over that collection and use `instanceof` to check whether you’re dealing with another `CSSList`, a `RuleSet`, a `Import` or a `Charset`.
To append a new item (selector, media query, etc.) to an existing `CSSList`, construct it using the constructor for this class and use the `append($oItem)` method.
#### RuleSet
`RuleSet` is a container for individual rules. The most common form of a rule set is one constrained by a selector. The following concrete subtypes exist:
* `AtRuleSet` – for generic at-rules for generic at-rules which are not covered by specific classes, i.e., not `@import`, `@charset` or `@media`. A common example for this is `@font-face`.
* `DeclarationBlock` – a `RuleSet` constrained by a `Selector`; contains an array of selector objects (comma-separated in the CSS) as well as the rules to be applied to the matching elements.
Note: A `CSSList` can contain other `CSSList`s (and `Import`s as well as a `Charset`), while a `RuleSet` can only contain `Rule`s.
If you want to manipulate a `RuleSet`, use the methods `addRule(Rule $rule)`, `getRules()` and `removeRule($rule)` (which accepts either a `Rule` or a rule name; optionally suffixed by a dash to remove all related rules).
#### Rule
`Rule`s just have a string key (the rule) and a `Value`.
#### Value
`Value` is an abstract class that only defines the `render` method. The concrete subclasses for atomic value types are:
* `Size` – consists of a numeric `size` value and a unit.
* `Color` – colors can be input in the form #rrggbb, #rgb or schema(val1, val2, …) but are always stored as an array of ('s' => val1, 'c' => val2, 'h' => val3, …) and output in the second form.
* `CSSString` – this is just a wrapper for quoted strings to distinguish them from keywords; always output with double quotes.
* `URL` – URLs in CSS; always output in `URL("")` notation.
There is another abstract subclass of `Value`, `ValueList`: A `ValueList` represents a lists of `Value`s, separated by some separation character (mostly `,`, whitespace, or `/`).
There are two types of `ValueList`s:
* `RuleValueList` – The default type, used to represent all multivalued rules like `font: bold 12px/3 Helvetica, Verdana, sans-serif;` (where the value would be a whitespace-separated list of the primitive value `bold`, a slash-separated list and a comma-separated list).
* `CSSFunction` – A special kind of value that also contains a function name and where the values are the function’s arguments. Also handles equals-sign-separated argument lists like `filter: alpha(opacity=90);`.
#### Convenience methods
There are a few convenience methods on `Document` to ease finding, manipulating and deleting rules:
* `getAllDeclarationBlocks()` – does what it says; no matter how deeply nested the selectors are. Aliased as `getAllSelectors()`.
* `getAllRuleSets()` – does what it says; no matter how deeply nested the rule sets are.
* `getAllValues()` – finds all `Value` objects inside `Rule`s.
## To-Do
* More convenience methods (like `selectorsWithElement($sId/Class/TagName)`, `attributesOfType($type)`, `removeAttributesOfType($type)`)
* Real multibyte support. Currently, only multibyte charsets whose first 255 code points take up only one byte and are identical with ASCII are supported (yes, UTF-8 fits this description).
* Named color support (using `Color` instead of an anonymous string literal)
## Use cases
### Use `Parser` to prepend an ID to all selectors
```php
$myId = "#my_id";
$parser = new \Sabberworm\CSS\Parser($css);
$cssDocument = $parser->parse();
foreach ($cssDocument->getAllDeclarationBlocks() as $block) {
foreach ($block->getSelectors() as $selector) {
// Loop over all selector parts (the comma-separated strings in a
// selector) and prepend the ID.
$selector->setSelector($myId.' '.$selector->getSelector());
}
}
```
### Shrink all absolute sizes to half
```php
$parser = new \Sabberworm\CSS\Parser($css);
$cssDocument = $parser->parse();
foreach ($cssDocument->getAllValues() as $value) {
if ($value instanceof CSSSize && !$value->isRelative()) {
$value->setSize($value->getSize() / 2);
}
}
```
### Remove unwanted rules
```php
$parser = new \Sabberworm\CSS\Parser($css);
$cssDocument = $parser->parse();
foreach($cssDocument->getAllRuleSets() as $oRuleSet) {
// Note that the added dash will make this remove all rules starting with
// `font-` (like `font-size`, `font-weight`, etc.) as well as a potential
// `font` rule.
$oRuleSet->removeRule('font-');
$oRuleSet->removeRule('cursor');
}
```
### Output
To output the entire CSS document into a variable, just use `->render()`:
```php
$parser = new \Sabberworm\CSS\Parser(file_get_contents('somefile.css'));
$cssDocument = $parser->parse();
print $cssDocument->render();
```
If you want to format the output, pass an instance of type `\Sabberworm\CSS\OutputFormat`:
```php
$format = \Sabberworm\CSS\OutputFormat::create()
->indentWithSpaces(4)->setSpaceBetweenRules("\n");
print $cssDocument->render($format);
```
Or use one of the predefined formats:
```php
print $cssDocument->render(Sabberworm\CSS\OutputFormat::createPretty());
print $cssDocument->render(Sabberworm\CSS\OutputFormat::createCompact());
```
To see what you can do with output formatting, look at the tests in `tests/OutputFormatTest.php`.
## Examples
### Example 1 (At-Rules)
#### Input
```css
@charset "utf-8";
@font-face {
font-family: "CrassRoots";
src: url("../media/cr.ttf");
}
html, body {
font-size: 1.6em;
}
@keyframes mymove {
from { top: 0px; }
to { top: 200px; }
}
```
<details>
<summary><b>Structure (<code>var_dump()</code>)</b></summary>
```php
class Sabberworm\CSS\CSSList\Document#4 (2) {
protected $aContents =>
array(4) {
[0] =>
class Sabberworm\CSS\Property\Charset#6 (2) {
private $sCharset =>
class Sabberworm\CSS\Value\CSSString#5 (2) {
private $sString =>
string(5) "utf-8"
protected $iLineNo =>
int(1)
}
protected $iLineNo =>
int(1)
}
[1] =>
class Sabberworm\CSS\RuleSet\AtRuleSet#7 (4) {
private $sType =>
string(9) "font-face"
private $sArgs =>
string(0) ""
private $aRules =>
array(2) {
'font-family' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#8 (4) {
private $sRule =>
string(11) "font-family"
private $mValue =>
class Sabberworm\CSS\Value\CSSString#9 (2) {
private $sString =>
string(10) "CrassRoots"
protected $iLineNo =>
int(4)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(4)
}
}
'src' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#10 (4) {
private $sRule =>
string(3) "src"
private $mValue =>
class Sabberworm\CSS\Value\URL#11 (2) {
private $oURL =>
class Sabberworm\CSS\Value\CSSString#12 (2) {
private $sString =>
string(15) "../media/cr.ttf"
protected $iLineNo =>
int(5)
}
protected $iLineNo =>
int(5)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(5)
}
}
}
protected $iLineNo =>
int(3)
}
[2] =>
class Sabberworm\CSS\RuleSet\DeclarationBlock#13 (3) {
private $aSelectors =>
array(2) {
[0] =>
class Sabberworm\CSS\Property\Selector#14 (2) {
private $sSelector =>
string(4) "html"
private $iSpecificity =>
NULL
}
[1] =>
class Sabberworm\CSS\Property\Selector#15 (2) {
private $sSelector =>
string(4) "body"
private $iSpecificity =>
NULL
}
}
private $aRules =>
array(1) {
'font-size' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#16 (4) {
private $sRule =>
string(9) "font-size"
private $mValue =>
class Sabberworm\CSS\Value\Size#17 (4) {
private $fSize =>
double(1.6)
private $sUnit =>
string(2) "em"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(9)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(9)
}
}
}
protected $iLineNo =>
int(8)
}
[3] =>
class Sabberworm\CSS\CSSList\KeyFrame#18 (4) {
private $vendorKeyFrame =>
string(9) "keyframes"
private $animationName =>
string(6) "mymove"
protected $aContents =>
array(2) {
[0] =>
class Sabberworm\CSS\RuleSet\DeclarationBlock#19 (3) {
private $aSelectors =>
array(1) {
[0] =>
class Sabberworm\CSS\Property\Selector#20 (2) {
private $sSelector =>
string(4) "from"
private $iSpecificity =>
NULL
}
}
private $aRules =>
array(1) {
'top' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#21 (4) {
private $sRule =>
string(3) "top"
private $mValue =>
class Sabberworm\CSS\Value\Size#22 (4) {
private $fSize =>
double(0)
private $sUnit =>
string(2) "px"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(13)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(13)
}
}
}
protected $iLineNo =>
int(13)
}
[1] =>
class Sabberworm\CSS\RuleSet\DeclarationBlock#23 (3) {
private $aSelectors =>
array(1) {
[0] =>
class Sabberworm\CSS\Property\Selector#24 (2) {
private $sSelector =>
string(2) "to"
private $iSpecificity =>
NULL
}
}
private $aRules =>
array(1) {
'top' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#25 (4) {
private $sRule =>
string(3) "top"
private $mValue =>
class Sabberworm\CSS\Value\Size#26 (4) {
private $fSize =>
double(200)
private $sUnit =>
string(2) "px"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(14)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(14)
}
}
}
protected $iLineNo =>
int(14)
}
}
protected $iLineNo =>
int(12)
}
}
protected $iLineNo =>
int(1)
}
```
</details>
#### Output (`render()`)
```css
@charset "utf-8";
@font-face {font-family: "CrassRoots";src: url("../media/cr.ttf");}
html, body {font-size: 1.6em;}
@keyframes mymove {from {top: 0px;} to {top: 200px;}}
```
### Example 2 (Values)
#### Input
```css
#header {
margin: 10px 2em 1cm 2%;
font-family: Verdana, Helvetica, "Gill Sans", sans-serif;
color: red !important;
}
```
<details>
<summary><b>Structure (<code>var_dump()</code>)</b></summary>
```php
class Sabberworm\CSS\CSSList\Document#4 (2) {
protected $aContents =>
array(1) {
[0] =>
class Sabberworm\CSS\RuleSet\DeclarationBlock#5 (3) {
private $aSelectors =>
array(1) {
[0] =>
class Sabberworm\CSS\Property\Selector#6 (2) {
private $sSelector =>
string(7) "#header"
private $iSpecificity =>
NULL
}
}
private $aRules =>
array(3) {
'margin' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#7 (4) {
private $sRule =>
string(6) "margin"
private $mValue =>
class Sabberworm\CSS\Value\RuleValueList#12 (3) {
protected $aComponents =>
array(4) {
[0] =>
class Sabberworm\CSS\Value\Size#8 (4) {
private $fSize =>
double(10)
private $sUnit =>
string(2) "px"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(2)
}
[1] =>
class Sabberworm\CSS\Value\Size#9 (4) {
private $fSize =>
double(2)
private $sUnit =>
string(2) "em"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(2)
}
[2] =>
class Sabberworm\CSS\Value\Size#10 (4) {
private $fSize =>
double(1)
private $sUnit =>
string(2) "cm"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(2)
}
[3] =>
class Sabberworm\CSS\Value\Size#11 (4) {
private $fSize =>
double(2)
private $sUnit =>
string(1) "%"
private $bIsColorComponent =>
bool(false)
protected $iLineNo =>
int(2)
}
}
protected $sSeparator =>
string(1) " "
protected $iLineNo =>
int(2)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(2)
}
}
'font-family' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#13 (4) {
private $sRule =>
string(11) "font-family"
private $mValue =>
class Sabberworm\CSS\Value\RuleValueList#15 (3) {
protected $aComponents =>
array(4) {
[0] =>
string(7) "Verdana"
[1] =>
string(9) "Helvetica"
[2] =>
class Sabberworm\CSS\Value\CSSString#14 (2) {
private $sString =>
string(9) "Gill Sans"
protected $iLineNo =>
int(3)
}
[3] =>
string(10) "sans-serif"
}
protected $sSeparator =>
string(1) ","
protected $iLineNo =>
int(3)
}
private $bIsImportant =>
bool(false)
protected $iLineNo =>
int(3)
}
}
'color' =>
array(1) {
[0] =>
class Sabberworm\CSS\Rule\Rule#16 (4) {
private $sRule =>
string(5) "color"
private $mValue =>
string(3) "red"
private $bIsImportant =>
bool(true)
protected $iLineNo =>
int(4)
}
}
}
protected $iLineNo =>
int(1)
}
}
protected $iLineNo =>
int(1)
}
```
</details>
#### Output (`render()`)
```css
#header {margin: 10px 2em 1cm 2%;font-family: Verdana,Helvetica,"Gill Sans",sans-serif;color: red !important;}
```
## Contributors/Thanks to
* [oliverklee](https://github.com/oliverklee) for lots of refactorings, code modernizations and CI integrations
* [raxbg](https://github.com/raxbg) for contributions to parse `calc`, grid lines, and various bugfixes.
* [westonruter](https://github.com/westonruter) for bugfixes and improvements.
* [FMCorz](https://github.com/FMCorz) for many patches and suggestions, for being able to parse comments and IE hacks (in lenient mode).
* [Lullabot](https://github.com/Lullabot) for a patch that allows to know the line number for each parsed token.
* [ju1ius](https://github.com/ju1ius) for the specificity parsing code and the ability to expand/compact shorthand properties.
* [ossinkine](https://github.com/ossinkine) for a 150 time performance boost.
* [GaryJones](https://github.com/GaryJones) for lots of input and [https://css-specificity.info/](https://css-specificity.info/).
* [docteurklein](https://github.com/docteurklein) for output formatting and `CSSList->remove()` inspiration.
* [nicolopignatelli](https://github.com/nicolopignatelli) for PSR-0 compatibility.
* [diegoembarcadero](https://github.com/diegoembarcadero) for keyframe at-rule parsing.
* [goetas](https://github.com/goetas) for @namespace at-rule support.
* [View full list](https://github.com/sabberworm/PHP-CSS-Parser/contributors)
## Misc
* Legacy Support: The latest pre-PSR-0 version of this project can be checked with the `0.9.0` tag.
* Running Tests: To run all unit tests for this project, run `composer install` to install phpunit and use `./vendor/bin/phpunit`.
@@ -0,0 +1,50 @@
{
"name": "sabberworm\/php-css-parser",
"type": "library",
"description": "Parser for CSS Files written in PHP",
"keywords": [
"parser",
"css",
"stylesheet"
],
"homepage": "https:\/\/www.sabberworm.com\/blog\/2010\/6\/10\/php-css-parser",
"license": "MIT",
"authors": [
{
"name": "Raphael Schweikert"
},
{
"name": "Oliver Klee",
"email": "github@oliverklee.de"
},
{
"name": "Jake Hotson",
"email": "jake.github@qzdesign.co.uk"
}
],
"require": {
"php": "^5.6.20 || ^7.0.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0",
"ext-iconv": "*"
},
"require-dev": {
"phpunit\/phpunit": "5.7.27 || 6.5.14 || 7.5.20 || 8.5.41"
},
"suggest": {
"ext-mbstring": "for parsing UTF-8 CSS"
},
"autoload": {
"psr-4": {
"JooosiFonDeps\\Sabberworm\\CSS\\": "src\/"
}
},
"autoload-dev": {
"psr-4": {
"JooosiFonDeps\\Sabberworm\\CSS\\Tests\\": "tests\/"
}
},
"extra": {
"branch-alias": {
"dev-main": "9.0.x-dev"
}
}
}
@@ -0,0 +1,80 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\CSSList;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Property\AtRule;
/**
* A `BlockList` constructed by an unknown at-rule. `@media` rules are rendered into `AtRuleBlockList` objects.
*/
class AtRuleBlockList extends CSSBlockList implements AtRule
{
/**
* @var string
*/
private $sType;
/**
* @var string
*/
private $sArgs;
/**
* @param string $sType
* @param string $sArgs
* @param int $iLineNo
*/
public function __construct($sType, $sArgs = '', $iLineNo = 0)
{
parent::__construct($iLineNo);
$this->sType = $sType;
$this->sArgs = $sArgs;
}
/**
* @return string
*/
public function atRuleName()
{
return $this->sType;
}
/**
* @return string
*/
public function atRuleArgs()
{
return $this->sArgs;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
$sResult .= $oOutputFormat->sBeforeAtRuleBlock;
$sArgs = $this->sArgs;
if ($sArgs) {
$sArgs = ' ' . $sArgs;
}
$sResult .= "@{$this->sType}{$sArgs}{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= $this->renderListContents($oOutputFormat);
$sResult .= '}';
$sResult .= $oOutputFormat->sAfterAtRuleBlock;
return $sResult;
}
/**
* @return bool
*/
public function isRootList()
{
return \false;
}
}
@@ -0,0 +1,138 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\CSSList;
use JooosiFonDeps\Sabberworm\CSS\Property\Selector;
use JooosiFonDeps\Sabberworm\CSS\Rule\Rule;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\DeclarationBlock;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\Value\CSSFunction;
use JooosiFonDeps\Sabberworm\CSS\Value\Value;
use JooosiFonDeps\Sabberworm\CSS\Value\ValueList;
/**
* A `CSSBlockList` is a `CSSList` whose `DeclarationBlock`s are guaranteed to contain valid declaration blocks or
* at-rules.
*
* Most `CSSList`s conform to this category but some at-rules (such as `@keyframes`) do not.
*/
abstract class CSSBlockList extends CSSList
{
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct($iLineNo);
}
/**
* @param array<int, DeclarationBlock> $aResult
*
* @return void
*/
protected function allDeclarationBlocks(array &$aResult)
{
foreach ($this->aContents as $mContent) {
if ($mContent instanceof DeclarationBlock) {
$aResult[] = $mContent;
} elseif ($mContent instanceof CSSBlockList) {
$mContent->allDeclarationBlocks($aResult);
}
}
}
/**
* @param array<int, RuleSet> $aResult
*
* @return void
*/
protected function allRuleSets(array &$aResult)
{
foreach ($this->aContents as $mContent) {
if ($mContent instanceof RuleSet) {
$aResult[] = $mContent;
} elseif ($mContent instanceof CSSBlockList) {
$mContent->allRuleSets($aResult);
}
}
}
/**
* @param CSSList|Rule|RuleSet|Value $oElement
* @param array<int, Value> $aResult
* @param string|null $sSearchString
* @param bool $bSearchInFunctionArguments
*
* @return void
*/
protected function allValues($oElement, array &$aResult, $sSearchString = null, $bSearchInFunctionArguments = \false)
{
if ($oElement instanceof CSSBlockList) {
foreach ($oElement->getContents() as $oContent) {
$this->allValues($oContent, $aResult, $sSearchString, $bSearchInFunctionArguments);
}
} elseif ($oElement instanceof RuleSet) {
foreach ($oElement->getRules($sSearchString) as $oRule) {
$this->allValues($oRule, $aResult, $sSearchString, $bSearchInFunctionArguments);
}
} elseif ($oElement instanceof Rule) {
$this->allValues($oElement->getValue(), $aResult, $sSearchString, $bSearchInFunctionArguments);
} elseif ($oElement instanceof ValueList) {
if ($bSearchInFunctionArguments || !$oElement instanceof CSSFunction) {
foreach ($oElement->getListComponents() as $mComponent) {
$this->allValues($mComponent, $aResult, $sSearchString, $bSearchInFunctionArguments);
}
}
} else {
// Non-List `Value` or `CSSString` (CSS identifier)
$aResult[] = $oElement;
}
}
/**
* @param array<int, Selector> $aResult
* @param string|null $sSpecificitySearch
*
* @return void
*/
protected function allSelectors(array &$aResult, $sSpecificitySearch = null)
{
/** @var array<int, DeclarationBlock> $aDeclarationBlocks */
$aDeclarationBlocks = [];
$this->allDeclarationBlocks($aDeclarationBlocks);
foreach ($aDeclarationBlocks as $oBlock) {
foreach ($oBlock->getSelectors() as $oSelector) {
if ($sSpecificitySearch === null) {
$aResult[] = $oSelector;
} else {
$sComparator = '===';
$aSpecificitySearch = explode(' ', $sSpecificitySearch);
$iTargetSpecificity = $aSpecificitySearch[0];
if (count($aSpecificitySearch) > 1) {
$sComparator = $aSpecificitySearch[0];
$iTargetSpecificity = $aSpecificitySearch[1];
}
$iTargetSpecificity = (int) $iTargetSpecificity;
$iSelectorSpecificity = $oSelector->getSpecificity();
$bMatches = \false;
switch ($sComparator) {
case '<=':
$bMatches = $iSelectorSpecificity <= $iTargetSpecificity;
break;
case '<':
$bMatches = $iSelectorSpecificity < $iTargetSpecificity;
break;
case '>=':
$bMatches = $iSelectorSpecificity >= $iTargetSpecificity;
break;
case '>':
$bMatches = $iSelectorSpecificity > $iTargetSpecificity;
break;
default:
$bMatches = $iSelectorSpecificity === $iTargetSpecificity;
break;
}
if ($bMatches) {
$aResult[] = $oSelector;
}
}
}
}
}
}
@@ -0,0 +1,460 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\CSSList;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\Comment\Commentable;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
use JooosiFonDeps\Sabberworm\CSS\Property\AtRule;
use JooosiFonDeps\Sabberworm\CSS\Property\Charset;
use JooosiFonDeps\Sabberworm\CSS\Property\CSSNamespace;
use JooosiFonDeps\Sabberworm\CSS\Property\Import;
use JooosiFonDeps\Sabberworm\CSS\Property\Selector;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\AtRuleSet;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\DeclarationBlock;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\Settings;
use JooosiFonDeps\Sabberworm\CSS\Value\CSSString;
use JooosiFonDeps\Sabberworm\CSS\Value\URL;
use JooosiFonDeps\Sabberworm\CSS\Value\Value;
/**
* This is the most generic container available. It can contain `DeclarationBlock`s (rule sets with a selector),
* `RuleSet`s as well as other `CSSList` objects.
*
* It can also contain `Import` and `Charset` objects stemming from at-rules.
*/
abstract class CSSList implements Renderable, Commentable
{
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @var array<int, RuleSet|CSSList|Import|Charset>
*
* @internal since 8.8.0
*/
protected $aContents;
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
$this->aComments = [];
$this->aContents = [];
$this->iLineNo = $iLineNo;
}
/**
* @return void
*
* @throws UnexpectedTokenException
* @throws SourceException
*
* @internal since V8.8.0
*/
public static function parseList(ParserState $oParserState, CSSList $oList)
{
$bIsRoot = $oList instanceof Document;
if (is_string($oParserState)) {
$oParserState = new ParserState($oParserState, Settings::create());
}
$bLenientParsing = $oParserState->getSettings()->bLenientParsing;
$aComments = [];
while (!$oParserState->isEnd()) {
$aComments = array_merge($aComments, $oParserState->consumeWhiteSpace());
$oListItem = null;
if ($bLenientParsing) {
try {
$oListItem = self::parseListItem($oParserState, $oList);
} catch (UnexpectedTokenException $e) {
$oListItem = \false;
}
} else {
$oListItem = self::parseListItem($oParserState, $oList);
}
if ($oListItem === null) {
// List parsing finished
return;
}
if ($oListItem) {
$oListItem->addComments($aComments);
$oList->append($oListItem);
}
$aComments = $oParserState->consumeWhiteSpace();
}
$oList->addComments($aComments);
if (!$bIsRoot && !$bLenientParsing) {
throw new SourceException("Unexpected end of document", $oParserState->currentLine());
}
}
/**
* @return AtRuleBlockList|KeyFrame|Charset|CSSNamespace|Import|AtRuleSet|DeclarationBlock|null|false
*
* @throws SourceException
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
private static function parseListItem(ParserState $oParserState, CSSList $oList)
{
$bIsRoot = $oList instanceof Document;
if ($oParserState->comes('@')) {
$oAtRule = self::parseAtRule($oParserState);
if ($oAtRule instanceof Charset) {
if (!$bIsRoot) {
throw new UnexpectedTokenException('@charset may only occur in root document', '', 'custom', $oParserState->currentLine());
}
if (count($oList->getContents()) > 0) {
throw new UnexpectedTokenException('@charset must be the first parseable token in a document', '', 'custom', $oParserState->currentLine());
}
$oParserState->setCharset($oAtRule->getCharset());
}
return $oAtRule;
} elseif ($oParserState->comes('}')) {
if ($bIsRoot) {
if ($oParserState->getSettings()->bLenientParsing) {
return DeclarationBlock::parse($oParserState);
} else {
throw new SourceException("Unopened {", $oParserState->currentLine());
}
} else {
// End of list
return null;
}
} else {
return DeclarationBlock::parse($oParserState, $oList);
}
}
/**
* @param ParserState $oParserState
*
* @return AtRuleBlockList|KeyFrame|Charset|CSSNamespace|Import|AtRuleSet|null
*
* @throws SourceException
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*/
private static function parseAtRule(ParserState $oParserState)
{
$oParserState->consume('@');
$sIdentifier = $oParserState->parseIdentifier();
$iIdentifierLineNum = $oParserState->currentLine();
$oParserState->consumeWhiteSpace();
if ($sIdentifier === 'import') {
$oLocation = URL::parse($oParserState);
$oParserState->consumeWhiteSpace();
$sMediaQuery = null;
if (!$oParserState->comes(';')) {
$sMediaQuery = trim($oParserState->consumeUntil([';', ParserState::EOF]));
}
$oParserState->consumeUntil([';', ParserState::EOF], \true, \true);
return new Import($oLocation, $sMediaQuery ?: null, $iIdentifierLineNum);
} elseif ($sIdentifier === 'charset') {
$oCharsetString = CSSString::parse($oParserState);
$oParserState->consumeWhiteSpace();
$oParserState->consumeUntil([';', ParserState::EOF], \true, \true);
return new Charset($oCharsetString, $iIdentifierLineNum);
} elseif (self::identifierIs($sIdentifier, 'keyframes')) {
$oResult = new KeyFrame($iIdentifierLineNum);
$oResult->setVendorKeyFrame($sIdentifier);
$oResult->setAnimationName(trim($oParserState->consumeUntil('{', \false, \true)));
CSSList::parseList($oParserState, $oResult);
if ($oParserState->comes('}')) {
$oParserState->consume('}');
}
return $oResult;
} elseif ($sIdentifier === 'namespace') {
$sPrefix = null;
$mUrl = Value::parsePrimitiveValue($oParserState);
if (!$oParserState->comes(';')) {
$sPrefix = $mUrl;
$mUrl = Value::parsePrimitiveValue($oParserState);
}
$oParserState->consumeUntil([';', ParserState::EOF], \true, \true);
if ($sPrefix !== null && !is_string($sPrefix)) {
throw new UnexpectedTokenException('Wrong namespace prefix', $sPrefix, 'custom', $iIdentifierLineNum);
}
if (!($mUrl instanceof CSSString || $mUrl instanceof URL)) {
throw new UnexpectedTokenException('Wrong namespace url of invalid type', $mUrl, 'custom', $iIdentifierLineNum);
}
return new CSSNamespace($mUrl, $sPrefix, $iIdentifierLineNum);
} else {
// Unknown other at rule (font-face or such)
$sArgs = trim($oParserState->consumeUntil('{', \false, \true));
if (substr_count($sArgs, "(") != substr_count($sArgs, ")")) {
if ($oParserState->getSettings()->bLenientParsing) {
return null;
} else {
throw new SourceException("Unmatched brace count in media query", $oParserState->currentLine());
}
}
$bUseRuleSet = \true;
foreach (explode('/', AtRule::BLOCK_RULES) as $sBlockRuleName) {
if (self::identifierIs($sIdentifier, $sBlockRuleName)) {
$bUseRuleSet = \false;
break;
}
}
if ($bUseRuleSet) {
$oAtRule = new AtRuleSet($sIdentifier, $sArgs, $iIdentifierLineNum);
RuleSet::parseRuleSet($oParserState, $oAtRule);
} else {
$oAtRule = new AtRuleBlockList($sIdentifier, $sArgs, $iIdentifierLineNum);
CSSList::parseList($oParserState, $oAtRule);
if ($oParserState->comes('}')) {
$oParserState->consume('}');
}
}
return $oAtRule;
}
}
/**
* Tests an identifier for a given value. Since identifiers are all keywords, they can be vendor-prefixed.
* We need to check for these versions too.
*
* @param string $sIdentifier
* @param string $sMatch
*
* @return bool
*/
private static function identifierIs($sIdentifier, $sMatch)
{
return strcasecmp($sIdentifier, $sMatch) === 0 ?: preg_match("/^(-\\w+-)?{$sMatch}\$/i", $sIdentifier) === 1;
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* Prepends an item to the list of contents.
*
* @param RuleSet|CSSList|Import|Charset $oItem
*
* @return void
*/
public function prepend($oItem)
{
array_unshift($this->aContents, $oItem);
}
/**
* Appends an item to the list of contents.
*
* @param RuleSet|CSSList|Import|Charset $oItem
*
* @return void
*/
public function append($oItem)
{
$this->aContents[] = $oItem;
}
/**
* Splices the list of contents.
*
* @param int $iOffset
* @param int $iLength
* @param array<int, RuleSet|CSSList|Import|Charset> $mReplacement
*
* @return void
*/
public function splice($iOffset, $iLength = null, $mReplacement = null)
{
array_splice($this->aContents, $iOffset, $iLength, $mReplacement);
}
/**
* Inserts an item in the CSS list before its sibling. If the desired sibling cannot be found,
* the item is appended at the end.
*
* @param RuleSet|CSSList|Import|Charset $item
* @param RuleSet|CSSList|Import|Charset $sibling
*/
public function insertBefore($item, $sibling)
{
if (in_array($sibling, $this->aContents, \true)) {
$this->replace($sibling, [$item, $sibling]);
} else {
$this->append($item);
}
}
/**
* Removes an item from the CSS list.
*
* @param RuleSet|Import|Charset|CSSList $oItemToRemove
* May be a RuleSet (most likely a DeclarationBlock), a Import,
* a Charset or another CSSList (most likely a MediaQuery)
*
* @return bool whether the item was removed
*/
public function remove($oItemToRemove)
{
$iKey = array_search($oItemToRemove, $this->aContents, \true);
if ($iKey !== \false) {
unset($this->aContents[$iKey]);
return \true;
}
return \false;
}
/**
* Replaces an item from the CSS list.
*
* @param RuleSet|Import|Charset|CSSList $oOldItem
* May be a `RuleSet` (most likely a `DeclarationBlock`), an `Import`, a `Charset`
* or another `CSSList` (most likely a `MediaQuery`)
*
* @return bool
*/
public function replace($oOldItem, $mNewItem)
{
$iKey = array_search($oOldItem, $this->aContents, \true);
if ($iKey !== \false) {
if (is_array($mNewItem)) {
array_splice($this->aContents, $iKey, 1, $mNewItem);
} else {
array_splice($this->aContents, $iKey, 1, [$mNewItem]);
}
return \true;
}
return \false;
}
/**
* @param array<int, RuleSet|Import|Charset|CSSList> $aContents
*/
public function setContents(array $aContents)
{
$this->aContents = [];
foreach ($aContents as $content) {
$this->append($content);
}
}
/**
* Removes a declaration block from the CSS list if it matches all given selectors.
*
* @param DeclarationBlock|array<array-key, Selector>|string $mSelector the selectors to match
* @param bool $bRemoveAll whether to stop at the first declaration block found or remove all blocks
*
* @return void
*/
public function removeDeclarationBlockBySelector($mSelector, $bRemoveAll = \false)
{
if ($mSelector instanceof DeclarationBlock) {
$mSelector = $mSelector->getSelectors();
}
if (!is_array($mSelector)) {
$mSelector = explode(',', $mSelector);
}
foreach ($mSelector as $iKey => &$mSel) {
if (!$mSel instanceof Selector) {
if (!Selector::isValid($mSel)) {
throw new UnexpectedTokenException("Selector did not match '" . Selector::SELECTOR_VALIDATION_RX . "'.", $mSel, "custom");
}
$mSel = new Selector($mSel);
}
}
foreach ($this->aContents as $iKey => $mItem) {
if (!$mItem instanceof DeclarationBlock) {
continue;
}
if ($mItem->getSelectors() == $mSelector) {
unset($this->aContents[$iKey]);
if (!$bRemoveAll) {
return;
}
}
}
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @return string
*/
protected function renderListContents(OutputFormat $oOutputFormat)
{
$sResult = '';
$bIsFirst = \true;
$oNextLevel = $oOutputFormat;
if (!$this->isRootList()) {
$oNextLevel = $oOutputFormat->nextLevel();
}
foreach ($this->aContents as $oContent) {
$sRendered = $oOutputFormat->safely(function () use ($oNextLevel, $oContent) {
return $oContent->render($oNextLevel);
});
if ($sRendered === null) {
continue;
}
if ($bIsFirst) {
$bIsFirst = \false;
$sResult .= $oNextLevel->spaceBeforeBlocks();
} else {
$sResult .= $oNextLevel->spaceBetweenBlocks();
}
$sResult .= $sRendered;
}
if (!$bIsFirst) {
// Had some output
$sResult .= $oOutputFormat->spaceAfterBlocks();
}
return $sResult;
}
/**
* Return true if the list can not be further outdented. Only important when rendering.
*
* @return bool
*/
abstract public function isRootList();
/**
* Returns the stored items.
*
* @return array<int, RuleSet|Import|Charset|CSSList>
*/
public function getContents()
{
return $this->aContents;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<array-key, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
}
@@ -0,0 +1,168 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\CSSList;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Property\Selector;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\DeclarationBlock;
use JooosiFonDeps\Sabberworm\CSS\RuleSet\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\Value\Value;
/**
* This class represents the root of a parsed CSS file. It contains all top-level CSS contents: mostly declaration
* blocks, but also any at-rules encountered (`Import` and `Charset`).
*/
class Document extends CSSBlockList
{
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct($iLineNo);
}
/**
* @return Document
*
* @throws SourceException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState)
{
$oDocument = new Document($oParserState->currentLine());
CSSList::parseList($oParserState, $oDocument);
return $oDocument;
}
/**
* Gets all `DeclarationBlock` objects recursively, no matter how deeply nested the selectors are.
* Aliased as `getAllSelectors()`.
*
* @return array<int, DeclarationBlock>
*/
public function getAllDeclarationBlocks()
{
/** @var array<int, DeclarationBlock> $aResult */
$aResult = [];
$this->allDeclarationBlocks($aResult);
return $aResult;
}
/**
* Gets all `DeclarationBlock` objects recursively.
*
* @return array<int, DeclarationBlock>
*
* @deprecated will be removed in version 9.0; use `getAllDeclarationBlocks()` instead
*/
public function getAllSelectors()
{
return $this->getAllDeclarationBlocks();
}
/**
* Returns all `RuleSet` objects recursively found in the tree, no matter how deeply nested the rule sets are.
*
* @return array<int, RuleSet>
*/
public function getAllRuleSets()
{
/** @var array<int, RuleSet> $aResult */
$aResult = [];
$this->allRuleSets($aResult);
return $aResult;
}
/**
* Returns all `Value` objects found recursively in `Rule`s in the tree.
*
* @param CSSList|RuleSet|string $mElement
* the `CSSList` or `RuleSet` to start the search from (defaults to the whole document).
* If a string is given, it is used as rule name filter.
* @param bool $bSearchInFunctionArguments whether to also return Value objects used as Function arguments.
*
* @return array<int, Value>
*
* @see RuleSet->getRules()
*/
public function getAllValues($mElement = null, $bSearchInFunctionArguments = \false)
{
$sSearchString = null;
if ($mElement === null) {
$mElement = $this;
} elseif (is_string($mElement)) {
$sSearchString = $mElement;
$mElement = $this;
}
/** @var array<int, Value> $aResult */
$aResult = [];
$this->allValues($mElement, $aResult, $sSearchString, $bSearchInFunctionArguments);
return $aResult;
}
/**
* Returns all `Selector` objects with the requested specificity found recursively in the tree.
*
* Note that this does not yield the full `DeclarationBlock` that the selector belongs to
* (and, currently, there is no way to get to that).
*
* @param string|null $sSpecificitySearch
* An optional filter by specificity.
* May contain a comparison operator and a number or just a number (defaults to "==").
*
* @return array<int, Selector>
* @example `getSelectorsBySpecificity('>= 100')`
*
*/
public function getSelectorsBySpecificity($sSpecificitySearch = null)
{
/** @var array<int, Selector> $aResult */
$aResult = [];
$this->allSelectors($aResult, $sSpecificitySearch);
return $aResult;
}
/**
* Expands all shorthand properties to their long value.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandShorthands()
{
foreach ($this->getAllDeclarationBlocks() as $oDeclaration) {
$oDeclaration->expandShorthands();
}
}
/**
* Create shorthands properties whenever possible.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createShorthands()
{
foreach ($this->getAllDeclarationBlocks() as $oDeclaration) {
$oDeclaration->createShorthands();
}
}
/**
* Overrides `render()` to make format argument optional.
*
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat = null)
{
if ($oOutputFormat === null) {
$oOutputFormat = new OutputFormat();
}
return $oOutputFormat->comments($this) . $this->renderListContents($oOutputFormat);
}
/**
* @return bool
*/
public function isRootList()
{
return \true;
}
}
@@ -0,0 +1,97 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\CSSList;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Property\AtRule;
class KeyFrame extends CSSList implements AtRule
{
/**
* @var string|null
*/
private $vendorKeyFrame;
/**
* @var string|null
*/
private $animationName;
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct($iLineNo);
$this->vendorKeyFrame = null;
$this->animationName = null;
}
/**
* @param string $vendorKeyFrame
*/
public function setVendorKeyFrame($vendorKeyFrame)
{
$this->vendorKeyFrame = $vendorKeyFrame;
}
/**
* @return string|null
*/
public function getVendorKeyFrame()
{
return $this->vendorKeyFrame;
}
/**
* @param string $animationName
*/
public function setAnimationName($animationName)
{
$this->animationName = $animationName;
}
/**
* @return string|null
*/
public function getAnimationName()
{
return $this->animationName;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
$sResult .= "@{$this->vendorKeyFrame} {$this->animationName}{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= $this->renderListContents($oOutputFormat);
$sResult .= '}';
return $sResult;
}
/**
* @return bool
*/
public function isRootList()
{
return \false;
}
/**
* @return string|null
*/
public function atRuleName()
{
return $this->vendorKeyFrame;
}
/**
* @return string|null
*/
public function atRuleArgs()
{
return $this->animationName;
}
}
@@ -0,0 +1,71 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Comment;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
class Comment implements Renderable
{
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @var string
*
* @internal since 8.8.0
*/
protected $sComment;
/**
* @param string $sComment
* @param int $iLineNo
*/
public function __construct($sComment = '', $iLineNo = 0)
{
$this->sComment = $sComment;
$this->iLineNo = $iLineNo;
}
/**
* @return string
*/
public function getComment()
{
return $this->sComment;
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @param string $sComment
*
* @return void
*/
public function setComment($sComment)
{
$this->sComment = $sComment;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return '/*' . $this->sComment . '*/';
}
}
@@ -0,0 +1,23 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Comment;
interface Commentable
{
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments);
/**
* @return array<array-key, Comment>
*/
public function getComments();
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments);
}
@@ -0,0 +1,382 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS;
/**
* Extending this class is deprecated in version 8.8.0; it will be made `final` in version 9.0.0.
*
* @method OutputFormat setSemicolonAfterLastRule(bool $bSemicolonAfterLastRule) Set whether semicolons are added after
* last rule.
*/
class OutputFormat
{
/**
* Value format: `"` means double-quote, `'` means single-quote
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sStringQuotingType = '"';
/**
* Output RGB colors in hash notation if possible
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bRGBHashNotation = \true;
/**
* Declaration format
*
* Semicolon after the last rule of a declaration block can be omitted. To do that, set this false.
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bSemicolonAfterLastRule = \true;
/**
* Spacing
* Note that these strings are not sanity-checked: the value should only consist of whitespace
* Any newline character will be indented according to the current level.
* The triples (After, Before, Between) can be set using a wildcard (e.g. `$oFormat->set('Space*Rules', "\n");`)
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceAfterRuleName = ' ';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBeforeRules = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceAfterRules = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBetweenRules = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBeforeBlocks = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceAfterBlocks = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBetweenBlocks = "\n";
/**
* Content injected in and around at-rule blocks.
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sBeforeAtRuleBlock = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sAfterAtRuleBlock = '';
/**
* This is what’s printed before and after the comma if a declaration block contains multiple selectors.
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBeforeSelectorSeparator = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceAfterSelectorSeparator = ' ';
/**
* This is what’s inserted before the separator in value lists, by default.
*
* `array` is deprecated in version 8.8.0, and will be removed in version 9.0.0.
* To set the spacing for specific separators, use {@see $aSpaceBeforeListArgumentSeparators} instead.
*
* @var string|array<non-empty-string, string>
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBeforeListArgumentSeparator = '';
/**
* Keys are separators (e.g. `,`). Values are the space sequence to insert, or an empty string.
*
* @var array<non-empty-string, string>
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $aSpaceBeforeListArgumentSeparators = [];
/**
* This is what’s inserted after the separator in value lists, by default.
*
* `array` is deprecated in version 8.8.0, and will be removed in version 9.0.0.
* To set the spacing for specific separators, use {@see $aSpaceAfterListArgumentSeparators} instead.
*
* @var string|array<non-empty-string, string>
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceAfterListArgumentSeparator = '';
/**
* Keys are separators (e.g. `,`). Values are the space sequence to insert, or an empty string.
*
* @var array<non-empty-string, string>
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $aSpaceAfterListArgumentSeparators = [];
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sSpaceBeforeOpeningBrace = ' ';
/**
* Content injected in and around declaration blocks.
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sBeforeDeclarationBlock = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sAfterDeclarationBlockSelectors = '';
/**
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sAfterDeclarationBlock = '';
/**
* Indentation character(s) per level. Only applicable if newlines are used in any of the spacing settings.
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sIndentation = "\t";
/**
* Output exceptions.
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bIgnoreExceptions = \false;
/**
* Render comments for lists and RuleSets
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bRenderComments = \false;
/**
* @var OutputFormatter|null
*/
private $oFormatter = null;
/**
* @var OutputFormat|null
*/
private $oNextLevelFormat = null;
/**
* @var int
*/
private $iIndentationLevel = 0;
/**
* @internal since V8.8.0. Use the factory methods `create()`, `createCompact()`, or `createPretty()` instead.
*/
public function __construct()
{
}
/**
* @param string $sName
*
* @return string|null
*
* @deprecated since 8.8.0, will be removed in 9.0.0. Use specific getters instead.
*/
public function get($sName)
{
$aVarPrefixes = ['a', 's', 'm', 'b', 'f', 'o', 'c', 'i'];
foreach ($aVarPrefixes as $sPrefix) {
$sFieldName = $sPrefix . ucfirst($sName);
if (isset($this->{$sFieldName})) {
return $this->{$sFieldName};
}
}
return null;
}
/**
* @param array<array-key, string>|string $aNames
* @param mixed $mValue
*
* @return self|false
*
* @deprecated since 8.8.0, will be removed in 9.0.0. Use specific setters instead.
*/
public function set($aNames, $mValue)
{
$aVarPrefixes = ['a', 's', 'm', 'b', 'f', 'o', 'c', 'i'];
if (is_string($aNames) && strpos($aNames, '*') !== \false) {
$aNames = [str_replace('*', 'Before', $aNames), str_replace('*', 'Between', $aNames), str_replace('*', 'After', $aNames)];
} elseif (!is_array($aNames)) {
$aNames = [$aNames];
}
foreach ($aVarPrefixes as $sPrefix) {
$bDidReplace = \false;
foreach ($aNames as $sName) {
$sFieldName = $sPrefix . ucfirst($sName);
if (isset($this->{$sFieldName})) {
$this->{$sFieldName} = $mValue;
$bDidReplace = \true;
}
}
if ($bDidReplace) {
return $this;
}
}
// Break the chain so the user knows this option is invalid
return \false;
}
/**
* @param string $sMethodName
* @param array<array-key, mixed> $aArguments
*
* @return mixed
*
* @throws \Exception
*/
public function __call($sMethodName, array $aArguments)
{
if (strpos($sMethodName, 'set') === 0) {
return $this->set(substr($sMethodName, 3), $aArguments[0]);
} elseif (strpos($sMethodName, 'get') === 0) {
return $this->get(substr($sMethodName, 3));
} elseif (method_exists(OutputFormatter::class, $sMethodName)) {
// @deprecated since 8.8.0, will be removed in 9.0.0. Call the method on the formatter directly instead.
return call_user_func_array([$this->getFormatter(), $sMethodName], $aArguments);
} else {
throw new \Exception('Unknown OutputFormat method called: ' . $sMethodName);
}
}
/**
* @param int $iNumber
*
* @return self
*/
public function indentWithTabs($iNumber = 1)
{
return $this->setIndentation(str_repeat("\t", $iNumber));
}
/**
* @param int $iNumber
*
* @return self
*/
public function indentWithSpaces($iNumber = 2)
{
return $this->setIndentation(str_repeat(" ", $iNumber));
}
/**
* @return OutputFormat
*
* @internal since V8.8.0
*/
public function nextLevel()
{
if ($this->oNextLevelFormat === null) {
$this->oNextLevelFormat = clone $this;
$this->oNextLevelFormat->iIndentationLevel++;
$this->oNextLevelFormat->oFormatter = null;
}
return $this->oNextLevelFormat;
}
/**
* @return void
*/
public function beLenient()
{
$this->bIgnoreExceptions = \true;
}
/**
* @return OutputFormatter
*
* @internal since 8.8.0
*/
public function getFormatter()
{
if ($this->oFormatter === null) {
$this->oFormatter = new OutputFormatter($this);
}
return $this->oFormatter;
}
/**
* @return int
*
* @deprecated #869 since version V8.8.0, will be removed in V9.0.0. Use `getIndentationLevel()` instead.
*/
public function level()
{
return $this->iIndentationLevel;
}
/**
* Creates an instance of this class without any particular formatting settings.
*
* @return self
*/
public static function create()
{
return new OutputFormat();
}
/**
* Creates an instance of this class with a preset for compact formatting.
*
* @return self
*/
public static function createCompact()
{
$format = self::create();
$format->set('Space*Rules', "")->set('Space*Blocks', "")->setSpaceAfterRuleName('')->setSpaceBeforeOpeningBrace('')->setSpaceAfterSelectorSeparator('')->setRenderComments(\false);
return $format;
}
/**
* Creates an instance of this class with a preset for pretty formatting.
*
* @return self
*/
public static function createPretty()
{
$format = self::create();
$format->set('Space*Rules', "\n")->set('Space*Blocks', "\n")->setSpaceBetweenBlocks("\n\n")->set('SpaceAfterListArgumentSeparators', [',' => ' '])->setRenderComments(\true);
return $format;
}
}
@@ -0,0 +1,244 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS;
use JooosiFonDeps\Sabberworm\CSS\Comment\Commentable;
use JooosiFonDeps\Sabberworm\CSS\Parsing\OutputException;
/**
* @internal since 8.8.0
*/
class OutputFormatter
{
/**
* @var OutputFormat
*/
private $oFormat;
public function __construct(OutputFormat $oFormat)
{
$this->oFormat = $oFormat;
}
/**
* @param string $sName
* @param string|null $sType
*
* @return string
*/
public function space($sName, $sType = null)
{
$sSpaceString = $this->oFormat->get("Space{$sName}");
// If $sSpaceString is an array, we have multiple values configured
// depending on the type of object the space applies to
if (is_array($sSpaceString)) {
if ($sType !== null && isset($sSpaceString[$sType])) {
$sSpaceString = $sSpaceString[$sType];
} else {
$sSpaceString = reset($sSpaceString);
}
}
return $this->prepareSpace($sSpaceString);
}
/**
* @return string
*/
public function spaceAfterRuleName()
{
return $this->space('AfterRuleName');
}
/**
* @return string
*/
public function spaceBeforeRules()
{
return $this->space('BeforeRules');
}
/**
* @return string
*/
public function spaceAfterRules()
{
return $this->space('AfterRules');
}
/**
* @return string
*/
public function spaceBetweenRules()
{
return $this->space('BetweenRules');
}
/**
* @return string
*/
public function spaceBeforeBlocks()
{
return $this->space('BeforeBlocks');
}
/**
* @return string
*/
public function spaceAfterBlocks()
{
return $this->space('AfterBlocks');
}
/**
* @return string
*/
public function spaceBetweenBlocks()
{
return $this->space('BetweenBlocks');
}
/**
* @return string
*/
public function spaceBeforeSelectorSeparator()
{
return $this->space('BeforeSelectorSeparator');
}
/**
* @return string
*/
public function spaceAfterSelectorSeparator()
{
return $this->space('AfterSelectorSeparator');
}
/**
* @param string $sSeparator
*
* @return string
*/
public function spaceBeforeListArgumentSeparator($sSeparator)
{
$spaceForSeparator = $this->oFormat->getSpaceBeforeListArgumentSeparators();
if (isset($spaceForSeparator[$sSeparator])) {
return $spaceForSeparator[$sSeparator];
}
return $this->space('BeforeListArgumentSeparator', $sSeparator);
}
/**
* @param string $sSeparator
*
* @return string
*/
public function spaceAfterListArgumentSeparator($sSeparator)
{
$spaceForSeparator = $this->oFormat->getSpaceAfterListArgumentSeparators();
if (isset($spaceForSeparator[$sSeparator])) {
return $spaceForSeparator[$sSeparator];
}
return $this->space('AfterListArgumentSeparator', $sSeparator);
}
/**
* @return string
*/
public function spaceBeforeOpeningBrace()
{
return $this->space('BeforeOpeningBrace');
}
/**
* Runs the given code, either swallowing or passing exceptions, depending on the `bIgnoreExceptions` setting.
*
* @param string $cCode the name of the function to call
*
* @return string|null
*/
public function safely($cCode)
{
if ($this->oFormat->get('IgnoreExceptions')) {
// If output exceptions are ignored, run the code with exception guards
try {
return $cCode();
} catch (OutputException $e) {
return null;
}
// Do nothing
} else {
// Run the code as-is
return $cCode();
}
}
/**
* Clone of the `implode` function, but calls `render` with the current output format instead of `__toString()`.
*
* @param string $sSeparator
* @param array<array-key, Renderable|string> $aValues
* @param bool $bIncreaseLevel
*
* @return string
*/
public function implode($sSeparator, array $aValues, $bIncreaseLevel = \false)
{
$sResult = '';
$oFormat = $this->oFormat;
if ($bIncreaseLevel) {
$oFormat = $oFormat->nextLevel();
}
$bIsFirst = \true;
foreach ($aValues as $mValue) {
if ($bIsFirst) {
$bIsFirst = \false;
} else {
$sResult .= $sSeparator;
}
if ($mValue instanceof Renderable) {
$sResult .= $mValue->render($oFormat);
} else {
$sResult .= $mValue;
}
}
return $sResult;
}
/**
* @param string $sString
*
* @return string
*/
public function removeLastSemicolon($sString)
{
if ($this->oFormat->get('SemicolonAfterLastRule')) {
return $sString;
}
$sString = explode(';', $sString);
if (count($sString) < 2) {
return $sString[0];
}
$sLast = array_pop($sString);
$sNextToLast = array_pop($sString);
array_push($sString, $sNextToLast . $sLast);
return implode(';', $sString);
}
/**
*
* @param array<Commentable> $aComments
*
* @return string
*/
public function comments(Commentable $oCommentable)
{
if (!$this->oFormat->bRenderComments) {
return '';
}
$sResult = '';
$aComments = $oCommentable->getComments();
$iLastCommentIndex = count($aComments) - 1;
foreach ($aComments as $i => $oComment) {
$sResult .= $oComment->render($this->oFormat);
$sResult .= $i === $iLastCommentIndex ? $this->spaceAfterBlocks() : $this->spaceBetweenBlocks();
}
return $sResult;
}
/**
* @param string $sSpaceString
*
* @return string
*/
private function prepareSpace($sSpaceString)
{
return str_replace("\n", "\n" . $this->indent(), $sSpaceString);
}
/**
* @return string
*/
private function indent()
{
return str_repeat($this->oFormat->sIndentation, $this->oFormat->getIndentationLevel());
}
}
@@ -0,0 +1,65 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS;
use JooosiFonDeps\Sabberworm\CSS\CSSList\Document;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
/**
* This class parses CSS from text into a data structure.
*/
class Parser
{
/**
* @var ParserState
*/
private $oParserState;
/**
* @param string $sText the complete CSS as text (i.e., usually the contents of a CSS file)
* @param Settings|null $oParserSettings
* @param int $iLineNo the line number (starting from 1, not from 0)
*/
public function __construct($sText, $oParserSettings = null, $iLineNo = 1)
{
if ($oParserSettings === null) {
$oParserSettings = Settings::create();
}
$this->oParserState = new ParserState($sText, $oParserSettings, $iLineNo);
}
/**
* Sets the charset to be used if the CSS does not contain an `@charset` declaration.
*
* @param string $sCharset
*
* @return void
*
* @deprecated since 8.7.0, will be removed in version 9.0.0 with #687
*/
public function setCharset($sCharset)
{
$this->oParserState->setCharset($sCharset);
}
/**
* Returns the charset that is used if the CSS does not contain an `@charset` declaration.
*
* @return void
*
* @deprecated since 8.7.0, will be removed in version 9.0.0 with #687
*/
public function getCharset()
{
// Note: The `return` statement is missing here. This is a bug that needs to be fixed.
$this->oParserState->getCharset();
}
/**
* Parses the CSS provided to the constructor and creates a `Document` from it.
*
* @return Document
*
* @throws SourceException
*/
public function parse()
{
return Document::parse($this->oParserState);
}
}
@@ -0,0 +1,34 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
/**
* @internal since 8.7.0
*/
class Anchor
{
/**
* @var int
*/
private $iPosition;
/**
* @var \Sabberworm\CSS\Parsing\ParserState
*/
private $oParserState;
/**
* @param int $iPosition
* @param \Sabberworm\CSS\Parsing\ParserState $oParserState
*/
public function __construct($iPosition, ParserState $oParserState)
{
$this->iPosition = $iPosition;
$this->oParserState = $oParserState;
}
/**
* @return void
*/
public function backtrack()
{
$this->oParserState->setPosition($this->iPosition);
}
}
@@ -0,0 +1,18 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
/**
* Thrown if the CSS parser attempts to print something invalid.
*/
class OutputException extends SourceException
{
/**
* @param string $sMessage
* @param int $iLineNo
*/
public function __construct($sMessage, $iLineNo = 0)
{
parent::__construct($sMessage, $iLineNo);
}
}
@@ -0,0 +1,494 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\Settings;
/**
* @internal since 8.7.0
*/
class ParserState
{
/**
* @var null
*
* @internal since 8.5.2
*/
const EOF = null;
/**
* @var Settings
*/
private $oParserSettings;
/**
* @var string
*/
private $sText;
/**
* @var array<int, string>
*/
private $aText;
/**
* @var int
*/
private $iCurrentPosition;
/**
* will only be used if the CSS does not contain an `@charset` declaration
*
* @var string
*/
private $sCharset;
/**
* @var int
*/
private $iLength;
/**
* @var int
*/
private $iLineNo;
/**
* @param string $sText the complete CSS as text (i.e., usually the contents of a CSS file)
* @param int $iLineNo
*/
public function __construct($sText, Settings $oParserSettings, $iLineNo = 1)
{
$this->oParserSettings = $oParserSettings;
$this->sText = $sText;
$this->iCurrentPosition = 0;
$this->iLineNo = $iLineNo;
$this->setCharset($this->oParserSettings->sDefaultCharset);
}
/**
* Sets the charset to be used if the CSS does not contain an `@charset` declaration.
*
* @param string $sCharset
*
* @return void
*/
public function setCharset($sCharset)
{
$this->sCharset = $sCharset;
$this->aText = $this->strsplit($this->sText);
if (is_array($this->aText)) {
$this->iLength = count($this->aText);
}
}
/**
* Returns the charset that is used if the CSS does not contain an `@charset` declaration.
*
* @return string
*/
public function getCharset()
{
return $this->sCharset;
}
/**
* @return int
*/
public function currentLine()
{
return $this->iLineNo;
}
/**
* @return int
*/
public function currentColumn()
{
return $this->iCurrentPosition;
}
/**
* @return Settings
*/
public function getSettings()
{
return $this->oParserSettings;
}
/**
* @return \Sabberworm\CSS\Parsing\Anchor
*/
public function anchor()
{
return new Anchor($this->iCurrentPosition, $this);
}
/**
* @param int $iPosition
*
* @return void
*/
public function setPosition($iPosition)
{
$this->iCurrentPosition = $iPosition;
}
/**
* @param bool $bIgnoreCase
*
* @return string
*
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public function parseIdentifier($bIgnoreCase = \true)
{
if ($this->isEnd()) {
throw new UnexpectedEOFException('', '', 'identifier', $this->iLineNo);
}
$sResult = $this->parseCharacter(\true);
if ($sResult === null) {
throw new UnexpectedTokenException($sResult, $this->peek(5), 'identifier', $this->iLineNo);
}
$sCharacter = null;
while (!$this->isEnd() && ($sCharacter = $this->parseCharacter(\true)) !== null) {
if (preg_match('/[a-zA-Z0-9\x{00A0}-\x{FFFF}_-]/Sux', $sCharacter)) {
$sResult .= $sCharacter;
} else {
$sResult .= '\\' . $sCharacter;
}
}
if ($bIgnoreCase) {
$sResult = $this->strtolower($sResult);
}
return $sResult;
}
/**
* @param bool $bIsForIdentifier
*
* @return string|null
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public function parseCharacter($bIsForIdentifier)
{
if ($this->peek() === '\\') {
if ($bIsForIdentifier && $this->oParserSettings->bLenientParsing && ($this->comes('\0') || $this->comes('\9'))) {
// Non-strings can contain \0 or \9 which is an IE hack supported in lenient parsing.
return null;
}
$this->consume('\\');
if ($this->comes('\n') || $this->comes('\r')) {
return '';
}
if (preg_match('/[0-9a-fA-F]/Su', $this->peek()) === 0) {
return $this->consume(1);
}
$sUnicode = $this->consumeExpression('/^[0-9a-fA-F]{1,6}/u', 6);
if ($this->strlen($sUnicode) < 6) {
// Consume whitespace after incomplete unicode escape
if (preg_match('/\s/isSu', $this->peek())) {
if ($this->comes('JooosiFonDeps\r\n')) {
$this->consume(2);
} else {
$this->consume(1);
}
}
}
$iUnicode = intval($sUnicode, 16);
$sUtf32 = "";
for ($i = 0; $i < 4; ++$i) {
$sUtf32 .= chr($iUnicode & 0xff);
$iUnicode = $iUnicode >> 8;
}
return iconv('utf-32le', $this->sCharset, $sUtf32);
}
if ($bIsForIdentifier) {
$peek = ord($this->peek());
// Ranges: a-z A-Z 0-9 - _
if ($peek >= 97 && $peek <= 122 || $peek >= 65 && $peek <= 90 || $peek >= 48 && $peek <= 57 || $peek === 45 || $peek === 95 || $peek > 0xa1) {
return $this->consume(1);
}
} else {
return $this->consume(1);
}
return null;
}
/**
* @return array<int, Comment>|void
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
public function consumeWhiteSpace()
{
$aComments = [];
do {
while (preg_match('/\s/isSu', $this->peek()) === 1) {
$this->consume(1);
}
if ($this->oParserSettings->bLenientParsing) {
try {
$oComment = $this->consumeComment();
} catch (UnexpectedEOFException $e) {
$this->iCurrentPosition = $this->iLength;
return $aComments;
}
} else {
$oComment = $this->consumeComment();
}
if ($oComment !== \false) {
$aComments[] = $oComment;
}
} while ($oComment !== \false);
return $aComments;
}
/**
* @param string $sString
* @param bool $bCaseInsensitive
*
* @return bool
*/
public function comes($sString, $bCaseInsensitive = \false)
{
$sPeek = $this->peek(strlen($sString));
return $sPeek == '' ? \false : $this->streql($sPeek, $sString, $bCaseInsensitive);
}
/**
* @param int $iLength
* @param int $iOffset
*
* @return string
*/
public function peek($iLength = 1, $iOffset = 0)
{
$iOffset += $this->iCurrentPosition;
if ($iOffset >= $this->iLength) {
return '';
}
return $this->substr($iOffset, $iLength);
}
/**
* @param int $mValue
*
* @return string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
public function consume($mValue = 1)
{
if (is_string($mValue)) {
$iLineCount = substr_count($mValue, "\n");
$iLength = $this->strlen($mValue);
if (!$this->streql($this->substr($this->iCurrentPosition, $iLength), $mValue)) {
throw new UnexpectedTokenException($mValue, $this->peek(max($iLength, 5)), $this->iLineNo);
}
$this->iLineNo += $iLineCount;
$this->iCurrentPosition += $this->strlen($mValue);
return $mValue;
} else {
if ($this->iCurrentPosition + $mValue > $this->iLength) {
throw new UnexpectedEOFException($mValue, $this->peek(5), 'count', $this->iLineNo);
}
$sResult = $this->substr($this->iCurrentPosition, $mValue);
$iLineCount = substr_count($sResult, "\n");
$this->iLineNo += $iLineCount;
$this->iCurrentPosition += $mValue;
return $sResult;
}
}
/**
* @param string $mExpression
* @param int|null $iMaxLength
*
* @return string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
public function consumeExpression($mExpression, $iMaxLength = null)
{
$aMatches = null;
$sInput = $iMaxLength !== null ? $this->peek($iMaxLength) : $this->inputLeft();
if (preg_match($mExpression, $sInput, $aMatches, \PREG_OFFSET_CAPTURE) === 1) {
return $this->consume($aMatches[0][0]);
}
throw new UnexpectedTokenException($mExpression, $this->peek(5), 'expression', $this->iLineNo);
}
/**
* @return Comment|false
*/
public function consumeComment()
{
$mComment = \false;
if ($this->comes('/*')) {
$iLineNo = $this->iLineNo;
$this->consume(1);
$mComment = '';
while (($char = $this->consume(1)) !== '') {
$mComment .= $char;
if ($this->comes('*/')) {
$this->consume(2);
break;
}
}
}
if ($mComment !== \false) {
// We skip the * which was included in the comment.
return new Comment(substr($mComment, 1), $iLineNo);
}
return $mComment;
}
/**
* @return bool
*/
public function isEnd()
{
return $this->iCurrentPosition >= $this->iLength;
}
/**
* @param array<array-key, string>|string $aEnd
* @param string $bIncludeEnd
* @param string $consumeEnd
* @param array<int, Comment> $comments
*
* @return string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
public function consumeUntil($aEnd, $bIncludeEnd = \false, $consumeEnd = \false, array &$comments = [])
{
$aEnd = is_array($aEnd) ? $aEnd : [$aEnd];
$out = '';
$start = $this->iCurrentPosition;
while (!$this->isEnd()) {
$char = $this->consume(1);
if (in_array($char, $aEnd)) {
if ($bIncludeEnd) {
$out .= $char;
} elseif (!$consumeEnd) {
$this->iCurrentPosition -= $this->strlen($char);
}
return $out;
}
$out .= $char;
if ($comment = $this->consumeComment()) {
$comments[] = $comment;
}
}
if (in_array(self::EOF, $aEnd)) {
return $out;
}
$this->iCurrentPosition = $start;
throw new UnexpectedEOFException('One of ("' . implode('","', $aEnd) . '")', $this->peek(5), 'search', $this->iLineNo);
}
/**
* @return string
*/
private function inputLeft()
{
return $this->substr($this->iCurrentPosition, -1);
}
/**
* @param string $sString1
* @param string $sString2
* @param bool $bCaseInsensitive
*
* @return bool
*/
public function streql($sString1, $sString2, $bCaseInsensitive = \true)
{
if ($bCaseInsensitive) {
return $this->strtolower($sString1) === $this->strtolower($sString2);
} else {
return $sString1 === $sString2;
}
}
/**
* @param int $iAmount
*
* @return void
*/
public function backtrack($iAmount)
{
$this->iCurrentPosition -= $iAmount;
}
/**
* @param string $sString
*
* @return int
*/
public function strlen($sString)
{
if ($this->oParserSettings->bMultibyteSupport) {
return mb_strlen($sString, $this->sCharset);
} else {
return strlen($sString);
}
}
/**
* @param int $iStart
* @param int $iLength
*
* @return string
*/
private function substr($iStart, $iLength)
{
if ($iLength < 0) {
$iLength = $this->iLength - $iStart + $iLength;
}
if ($iStart + $iLength > $this->iLength) {
$iLength = $this->iLength - $iStart;
}
$sResult = '';
while ($iLength > 0) {
$sResult .= $this->aText[$iStart];
$iStart++;
$iLength--;
}
return $sResult;
}
/**
* @param string $sString
*
* @return string
*/
private function strtolower($sString)
{
if ($this->oParserSettings->bMultibyteSupport) {
return mb_strtolower($sString, $this->sCharset);
} else {
return strtolower($sString);
}
}
/**
* @param string $sString
*
* @return array<int, string>
*/
private function strsplit($sString)
{
if ($this->oParserSettings->bMultibyteSupport) {
if ($this->streql($this->sCharset, 'utf-8')) {
return preg_split('//u', $sString, -1, \PREG_SPLIT_NO_EMPTY);
} else {
$iLength = mb_strlen($sString, $this->sCharset);
$aResult = [];
for ($i = 0; $i < $iLength; ++$i) {
$aResult[] = mb_substr($sString, $i, 1, $this->sCharset);
}
return $aResult;
}
} else if ($sString === '') {
return [];
} else {
return str_split($sString);
}
}
/**
* @param string $sString
* @param string $sNeedle
* @param int $iOffset
*
* @return int|false
*/
private function strpos($sString, $sNeedle, $iOffset)
{
if ($this->oParserSettings->bMultibyteSupport) {
return mb_strpos($sString, $sNeedle, $iOffset, $this->sCharset);
} else {
return strpos($sString, $sNeedle, $iOffset);
}
}
}
@@ -0,0 +1,30 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
class SourceException extends \Exception
{
/**
* @var int
*/
private $iLineNo;
/**
* @param string $sMessage
* @param int $iLineNo
*/
public function __construct($sMessage, $iLineNo = 0)
{
$this->iLineNo = $iLineNo;
if (!empty($iLineNo)) {
$sMessage .= " [line no: {$iLineNo}]";
}
parent::__construct($sMessage);
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
}
@@ -0,0 +1,12 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
/**
* Thrown if the CSS parser encounters end of file it did not expect.
*
* Extends `UnexpectedTokenException` in order to preserve backwards compatibility.
*/
class UnexpectedEOFException extends UnexpectedTokenException
{
}
@@ -0,0 +1,47 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Parsing;
/**
* Thrown if the CSS parser encounters a token it did not expect.
*/
class UnexpectedTokenException extends SourceException
{
/**
* @var string
*/
private $sExpected;
/**
* @var string
*/
private $sFound;
/**
* Possible values: literal, identifier, count, expression, search
*
* @var string
*/
private $sMatchType;
/**
* @param string $sExpected
* @param string $sFound
* @param string $sMatchType
* @param int $iLineNo
*/
public function __construct($sExpected, $sFound, $sMatchType = 'literal', $iLineNo = 0)
{
$this->sExpected = $sExpected;
$this->sFound = $sFound;
$this->sMatchType = $sMatchType;
$sMessage = "Token “{$sExpected}” ({$sMatchType}) not found. Got “{$sFound}”.";
if ($this->sMatchType === 'search') {
$sMessage = "Search for “{$sExpected}” returned no results. Context: “{$sFound}”.";
} elseif ($this->sMatchType === 'count') {
$sMessage = "Next token was expected to have {$sExpected} chars. Context: “{$sFound}”.";
} elseif ($this->sMatchType === 'identifier') {
$sMessage = "Identifier expected. Got “{$sFound}”";
} elseif ($this->sMatchType === 'custom') {
$sMessage = trim("{$sExpected} {$sFound}");
}
parent::__construct($sMessage, $iLineNo);
}
}
@@ -0,0 +1,34 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
use JooosiFonDeps\Sabberworm\CSS\Comment\Commentable;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
interface AtRule extends Renderable, Commentable
{
/**
* Since there are more set rules than block rules,
* we’re whitelisting the block rules and have anything else be treated as a set rule.
*
* @var string
*
* @internal since 8.5.2
*/
const BLOCK_RULES = 'media/document/supports/region-style/font-feature-values';
/**
* … and more font-specific ones (to be used inside font-feature-values)
*
* @var string
*
* @internal since 8.5.2
*/
const SET_RULES = 'font-face/counter-style/page/swash/styleset/annotation';
/**
* @return string|null
*/
public function atRuleName();
/**
* @return string|null
*/
public function atRuleArgs();
}
@@ -0,0 +1,142 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
/**
* `CSSNamespace` represents an `@namespace` rule.
*/
class CSSNamespace implements AtRule
{
/**
* @var string
*/
private $mUrl;
/**
* @var string
*/
private $sPrefix;
/**
* @var int
*/
private $iLineNo;
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @param string $mUrl
* @param string|null $sPrefix
* @param int $iLineNo
*/
public function __construct($mUrl, $sPrefix = null, $iLineNo = 0)
{
$this->mUrl = $mUrl;
$this->sPrefix = $sPrefix;
$this->iLineNo = $iLineNo;
$this->aComments = [];
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return '@namespace ' . ($this->sPrefix === null ? '' : $this->sPrefix . ' ') . $this->mUrl->render($oOutputFormat) . ';';
}
/**
* @return string
*/
public function getUrl()
{
return $this->mUrl;
}
/**
* @return string|null
*/
public function getPrefix()
{
return $this->sPrefix;
}
/**
* @param string $mUrl
*
* @return void
*/
public function setUrl($mUrl)
{
$this->mUrl = $mUrl;
}
/**
* @param string $sPrefix
*
* @return void
*/
public function setPrefix($sPrefix)
{
$this->sPrefix = $sPrefix;
}
/**
* @return string
*/
public function atRuleName()
{
return 'namespace';
}
/**
* @return array<int, string>
*/
public function atRuleArgs()
{
$aResult = [$this->mUrl];
if ($this->sPrefix) {
array_unshift($aResult, $this->sPrefix);
}
return $aResult;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<array-key, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
}
@@ -0,0 +1,125 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Value\CSSString;
/**
* Class representing an `@charset` rule.
*
* The following restrictions apply:
* - May not be found in any CSSList other than the Document.
* - May only appear at the very top of a Document’s contents.
* - Must not appear more than once.
*/
class Charset implements AtRule
{
/**
* @var CSSString
*/
private $oCharset;
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @param CSSString $oCharset
* @param int $iLineNo
*/
public function __construct(CSSString $oCharset, $iLineNo = 0)
{
$this->oCharset = $oCharset;
$this->iLineNo = $iLineNo;
$this->aComments = [];
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @param string|CSSString $oCharset
*
* @return void
*/
public function setCharset($sCharset)
{
$sCharset = $sCharset instanceof CSSString ? $sCharset : new CSSString($sCharset);
$this->oCharset = $sCharset;
}
/**
* @return string
*/
public function getCharset()
{
return $this->oCharset->getString();
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return "{$oOutputFormat->comments($this)}@charset {$this->oCharset->render($oOutputFormat)};";
}
/**
* @return string
*/
public function atRuleName()
{
return 'charset';
}
/**
* @return string
*/
public function atRuleArgs()
{
return $this->oCharset;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<array-key, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
}
@@ -0,0 +1,136 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Value\URL;
/**
* Class representing an `@import` rule.
*/
class Import implements AtRule
{
/**
* @var URL
*/
private $oLocation;
/**
* @var string
*/
private $sMediaQuery;
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @param URL $oLocation
* @param string $sMediaQuery
* @param int $iLineNo
*/
public function __construct(URL $oLocation, $sMediaQuery, $iLineNo = 0)
{
$this->oLocation = $oLocation;
$this->sMediaQuery = $sMediaQuery;
$this->iLineNo = $iLineNo;
$this->aComments = [];
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @param URL $oLocation
*
* @return void
*/
public function setLocation($oLocation)
{
$this->oLocation = $oLocation;
}
/**
* @return URL
*/
public function getLocation()
{
return $this->oLocation;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return $oOutputFormat->comments($this) . "@import " . $this->oLocation->render($oOutputFormat) . ($this->sMediaQuery === null ? '' : ' ' . $this->sMediaQuery) . ';';
}
/**
* @return string
*/
public function atRuleName()
{
return 'import';
}
/**
* @return array<int, URL|string>
*/
public function atRuleArgs()
{
$aResult = [$this->oLocation];
if ($this->sMediaQuery) {
array_push($aResult, $this->sMediaQuery);
}
return $aResult;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<array-key, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
/**
* @return string
*/
public function getMediaQuery()
{
return $this->sMediaQuery;
}
}
@@ -0,0 +1,25 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
class KeyframeSelector extends Selector
{
/**
* regexp for specificity calculations
*
* @var string
*
* @internal since 8.5.2
*/
const SELECTOR_VALIDATION_RX = '/
^(
(?:
[a-zA-Z0-9\x{00A0}-\x{FFFF}_^$|*="\'~\[\]()\-\s\.:#+>]* # any sequence of valid unescaped characters
(?:\\\\.)? # a single escaped character
(?:([\'"]).*?(?<!\\\\)\2)? # a quoted text like [id="example"]
)*
)|
(\d+%) # keyframe animation progress percentage (e.g. 50%)
$
/ux';
}
@@ -0,0 +1,138 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Property;
/**
* Class representing a single CSS selector. Selectors have to be split by the comma prior to being passed into this
* class.
*/
class Selector
{
/**
* regexp for specificity calculations
*
* @var string
*
* @internal
*/
const NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX = '/
(\.[\w]+) # classes
|
\[(\w+) # attributes
|
(\:( # pseudo classes
link|visited|active
|hover|focus
|lang
|target
|enabled|disabled|checked|indeterminate
|root
|nth-child|nth-last-child|nth-of-type|nth-last-of-type
|first-child|last-child|first-of-type|last-of-type
|only-child|only-of-type
|empty|contains
))
/ix';
/**
* regexp for specificity calculations
*
* @var string
*
* @internal
*/
const ELEMENTS_AND_PSEUDO_ELEMENTS_RX = '/
((^|[\s\+\>\~]+)[\w]+ # elements
|
\:{1,2}( # pseudo-elements
after|before|first-letter|first-line|selection
))
/ix';
/**
* regexp for specificity calculations
*
* @var string
*
* @internal since 8.5.2
*/
const SELECTOR_VALIDATION_RX = '/
^(
(?:
[a-zA-Z0-9\x{00A0}-\x{FFFF}_^$|*="\'~\[\]()\-\s\.:#+>]* # any sequence of valid unescaped characters
(?:\\\\.)? # a single escaped character
(?:([\'"]).*?(?<!\\\\)\2)? # a quoted text like [id="example"]
)*
)$
/ux';
/**
* @var string
*/
private $sSelector;
/**
* @var int|null
*/
private $iSpecificity;
/**
* @param string $sSelector
*
* @return bool
*
* @internal since V8.8.0
*/
public static function isValid($sSelector)
{
return preg_match(static::SELECTOR_VALIDATION_RX, $sSelector);
}
/**
* @param string $sSelector
* @param bool $bCalculateSpecificity @deprecated since V8.8.0, will be removed in V9.0.0
*/
public function __construct($sSelector, $bCalculateSpecificity = \false)
{
$this->setSelector($sSelector);
if ($bCalculateSpecificity) {
$this->getSpecificity();
}
}
/**
* @return string
*/
public function getSelector()
{
return $this->sSelector;
}
/**
* @param string $sSelector
*
* @return void
*/
public function setSelector($sSelector)
{
$this->sSelector = trim($sSelector);
$this->iSpecificity = null;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->getSelector();
}
/**
* @return int
*/
public function getSpecificity()
{
if ($this->iSpecificity === null) {
$a = 0;
/// @todo should exclude \# as well as "#"
$aMatches = null;
$b = substr_count($this->sSelector, '#');
$c = preg_match_all(self::NON_ID_ATTRIBUTES_AND_PSEUDO_CLASSES_RX, $this->sSelector, $aMatches);
$d = preg_match_all(self::ELEMENTS_AND_PSEUDO_ELEMENTS_RX, $this->sSelector, $aMatches);
$this->iSpecificity = $a * 1000 + $b * 100 + $c * 10 + $d;
}
return $this->iSpecificity;
}
}
@@ -0,0 +1,23 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS;
interface Renderable
{
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString();
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat);
/**
* @return int
*/
public function getLineNo();
}
@@ -0,0 +1,385 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Rule;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\Comment\Commentable;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
use JooosiFonDeps\Sabberworm\CSS\Value\RuleValueList;
use JooosiFonDeps\Sabberworm\CSS\Value\Value;
/**
* `Rule`s just have a string key (the rule) and a 'Value'.
*
* In CSS, `Rule`s are expressed as follows: “key: value[0][0] value[0][1], value[1][0] value[1][1];”
*/
class Rule implements Renderable, Commentable
{
/**
* @var string
*/
private $sRule;
/**
* @var RuleValueList|string|null
*/
private $mValue;
/**
* @var bool
*/
private $bIsImportant;
/**
* @var array<int, int>
*/
private $aIeHack;
/**
* @var int
*/
protected $iLineNo;
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iColNo;
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @param string $sRule
* @param int $iLineNo
* @param int $iColNo
*/
public function __construct($sRule, $iLineNo = 0, $iColNo = 0)
{
$this->sRule = $sRule;
$this->mValue = null;
$this->bIsImportant = \false;
$this->aIeHack = [];
$this->iLineNo = $iLineNo;
$this->iColNo = $iColNo;
$this->aComments = [];
}
/**
* @param array<int, Comment> $commentsBeforeRule
*
* @return Rule
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $commentsBeforeRule = [])
{
$aComments = \array_merge($commentsBeforeRule, $oParserState->consumeWhiteSpace());
$oRule = new Rule($oParserState->parseIdentifier(!$oParserState->comes("--")), $oParserState->currentLine(), $oParserState->currentColumn());
$oRule->setComments($aComments);
$oRule->addComments($oParserState->consumeWhiteSpace());
$oParserState->consume(':');
$oValue = Value::parseValue($oParserState, self::listDelimiterForRule($oRule->getRule()));
$oRule->setValue($oValue);
if ($oParserState->getSettings()->bLenientParsing) {
while ($oParserState->comes('\\')) {
$oParserState->consume('\\');
$oRule->addIeHack($oParserState->consume());
$oParserState->consumeWhiteSpace();
}
}
$oParserState->consumeWhiteSpace();
if ($oParserState->comes('!')) {
$oParserState->consume('!');
$oParserState->consumeWhiteSpace();
$oParserState->consume('important');
$oRule->setIsImportant(\true);
}
$oParserState->consumeWhiteSpace();
while ($oParserState->comes(';')) {
$oParserState->consume(';');
}
return $oRule;
}
/**
* Returns a list of delimiters (or separators).
* The first item is the innermost separator (or, put another way, the highest-precedence operator).
* The sequence continues to the outermost separator (or lowest-precedence operator).
*
* @param string $sRule
*
* @return list<non-empty-string>
*/
private static function listDelimiterForRule($sRule)
{
if (preg_match('/^font($|-)/', $sRule)) {
return [',', '/', ' '];
}
switch ($sRule) {
case 'src':
return [' ', ','];
default:
return [',', ' ', '/'];
}
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @return int
*/
public function getColNo()
{
return $this->iColNo;
}
/**
* @param int $iLine
* @param int $iColumn
*
* @return void
*/
public function setPosition($iLine, $iColumn)
{
$this->iColNo = $iColumn;
$this->iLineNo = $iLine;
}
/**
* @param string $sRule
*
* @return void
*/
public function setRule($sRule)
{
$this->sRule = $sRule;
}
/**
* @return string
*/
public function getRule()
{
return $this->sRule;
}
/**
* @return RuleValueList|string|null
*/
public function getValue()
{
return $this->mValue;
}
/**
* @param RuleValueList|string|null $mValue
*
* @return void
*/
public function setValue($mValue)
{
$this->mValue = $mValue;
}
/**
* @param array<array-key, array<array-key, RuleValueList>> $aSpaceSeparatedValues
*
* @return RuleValueList
*
* @deprecated will be removed in version 9.0
* Old-Style 2-dimensional array given. Retained for (some) backwards-compatibility.
* Use `setValue()` instead and wrap the value inside a RuleValueList if necessary.
*/
public function setValues(array $aSpaceSeparatedValues)
{
$oSpaceSeparatedList = null;
if (count($aSpaceSeparatedValues) > 1) {
$oSpaceSeparatedList = new RuleValueList(' ', $this->iLineNo);
}
foreach ($aSpaceSeparatedValues as $aCommaSeparatedValues) {
$oCommaSeparatedList = null;
if (count($aCommaSeparatedValues) > 1) {
$oCommaSeparatedList = new RuleValueList(',', $this->iLineNo);
}
foreach ($aCommaSeparatedValues as $mValue) {
if (!$oSpaceSeparatedList && !$oCommaSeparatedList) {
$this->mValue = $mValue;
return $mValue;
}
if ($oCommaSeparatedList) {
$oCommaSeparatedList->addListComponent($mValue);
} else {
$oSpaceSeparatedList->addListComponent($mValue);
}
}
if (!$oSpaceSeparatedList) {
$this->mValue = $oCommaSeparatedList;
return $oCommaSeparatedList;
} else {
$oSpaceSeparatedList->addListComponent($oCommaSeparatedList);
}
}
$this->mValue = $oSpaceSeparatedList;
return $oSpaceSeparatedList;
}
/**
* @return array<int, array<int, RuleValueList>>
*
* @deprecated will be removed in version 9.0
* Old-Style 2-dimensional array returned. Retained for (some) backwards-compatibility.
* Use `getValue()` instead and check for the existence of a (nested set of) ValueList object(s).
*/
public function getValues()
{
if (!$this->mValue instanceof RuleValueList) {
return [[$this->mValue]];
}
if ($this->mValue->getListSeparator() === ',') {
return [$this->mValue->getListComponents()];
}
$aResult = [];
foreach ($this->mValue->getListComponents() as $mValue) {
if (!$mValue instanceof RuleValueList || $mValue->getListSeparator() !== ',') {
$aResult[] = [$mValue];
continue;
}
if ($this->mValue->getListSeparator() === ' ' || count($aResult) === 0) {
$aResult[] = [];
}
foreach ($mValue->getListComponents() as $mValue) {
$aResult[count($aResult) - 1][] = $mValue;
}
}
return $aResult;
}
/**
* Adds a value to the existing value. Value will be appended if a `RuleValueList` exists of the given type.
* Otherwise, the existing value will be wrapped by one.
*
* @param RuleValueList|array<int, RuleValueList> $mValue
* @param string $sType
*
* @return void
*/
public function addValue($mValue, $sType = ' ')
{
if (!is_array($mValue)) {
$mValue = [$mValue];
}
if (!$this->mValue instanceof RuleValueList || $this->mValue->getListSeparator() !== $sType) {
$mCurrentValue = $this->mValue;
$this->mValue = new RuleValueList($sType, $this->iLineNo);
if ($mCurrentValue) {
$this->mValue->addListComponent($mCurrentValue);
}
}
foreach ($mValue as $mValueItem) {
$this->mValue->addListComponent($mValueItem);
}
}
/**
* @param int $iModifier
*
* @return void
*
* @deprecated since V8.8.0, will be removed in V9.0
*/
public function addIeHack($iModifier)
{
$this->aIeHack[] = $iModifier;
}
/**
* @param array<int, int> $aModifiers
*
* @return void
*
* @deprecated since V8.8.0, will be removed in V9.0
*/
public function setIeHack(array $aModifiers)
{
$this->aIeHack = $aModifiers;
}
/**
* @return array<int, int>
*
* @deprecated since V8.8.0, will be removed in V9.0
*/
public function getIeHack()
{
return $this->aIeHack;
}
/**
* @param bool $bIsImportant
*
* @return void
*/
public function setIsImportant($bIsImportant)
{
$this->bIsImportant = $bIsImportant;
}
/**
* @return bool
*/
public function getIsImportant()
{
return $this->bIsImportant;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$sResult = "{$oOutputFormat->comments($this)}{$this->sRule}:{$oOutputFormat->spaceAfterRuleName()}";
if ($this->mValue instanceof Value) {
// Can also be a ValueList
$sResult .= $this->mValue->render($oOutputFormat);
} else {
$sResult .= $this->mValue;
}
if (!empty($this->aIeHack)) {
$sResult .= ' \\' . implode('\\', $this->aIeHack);
}
if ($this->bIsImportant) {
$sResult .= ' !important';
}
$sResult .= ';';
return $sResult;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<array-key, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<array-key, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
}
@@ -0,0 +1,74 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Property\AtRule;
/**
* This class represents rule sets for generic at-rules which are not covered by specific classes, i.e., not
* `@import`, `@charset` or `@media`.
*
* A common example for this is `@font-face`.
*/
class AtRuleSet extends RuleSet implements AtRule
{
/**
* @var string
*/
private $sType;
/**
* @var string
*/
private $sArgs;
/**
* @param string $sType
* @param string $sArgs
* @param int $iLineNo
*/
public function __construct($sType, $sArgs = '', $iLineNo = 0)
{
parent::__construct($iLineNo);
$this->sType = $sType;
$this->sArgs = $sArgs;
}
/**
* @return string
*/
public function atRuleName()
{
return $this->sType;
}
/**
* @return string
*/
public function atRuleArgs()
{
return $this->sArgs;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
$sArgs = $this->sArgs;
if ($sArgs) {
$sArgs = ' ' . $sArgs;
}
$sResult .= "@{$this->sType}{$sArgs}{$oOutputFormat->spaceBeforeOpeningBrace()}{";
$sResult .= $this->renderRules($oOutputFormat);
$sResult .= '}';
return $sResult;
}
}
@@ -0,0 +1,736 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\CSSList\CSSList;
use JooosiFonDeps\Sabberworm\CSS\CSSList\KeyFrame;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\OutputException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
use JooosiFonDeps\Sabberworm\CSS\Property\KeyframeSelector;
use JooosiFonDeps\Sabberworm\CSS\Property\Selector;
use JooosiFonDeps\Sabberworm\CSS\Rule\Rule;
use JooosiFonDeps\Sabberworm\CSS\Value\Color;
use JooosiFonDeps\Sabberworm\CSS\Value\RuleValueList;
use JooosiFonDeps\Sabberworm\CSS\Value\Size;
use JooosiFonDeps\Sabberworm\CSS\Value\URL;
use JooosiFonDeps\Sabberworm\CSS\Value\Value;
/**
* This class represents a `RuleSet` constrained by a `Selector`.
*
* It contains an array of selector objects (comma-separated in the CSS) as well as the rules to be applied to the
* matching elements.
*
* Declaration blocks usually appear directly inside a `Document` or another `CSSList` (mostly a `MediaQuery`).
*/
class DeclarationBlock extends RuleSet
{
/**
* @var array<int, Selector|string>
*/
private $aSelectors;
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct($iLineNo);
$this->aSelectors = [];
}
/**
* @param CSSList|null $oList
*
* @return DeclarationBlock|false
*
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $oList = null)
{
$aComments = [];
$oResult = new DeclarationBlock($oParserState->currentLine());
try {
$aSelectorParts = [];
$sStringWrapperChar = \false;
do {
$aSelectorParts[] = $oParserState->consume(1) . $oParserState->consumeUntil(['{', '}', '\'', '"'], \false, \false, $aComments);
if (in_array($oParserState->peek(), ['\'', '"']) && substr(end($aSelectorParts), -1) != "\\") {
if ($sStringWrapperChar === \false) {
$sStringWrapperChar = $oParserState->peek();
} elseif ($sStringWrapperChar == $oParserState->peek()) {
$sStringWrapperChar = \false;
}
}
} while (!in_array($oParserState->peek(), ['{', '}']) || $sStringWrapperChar !== \false);
$oResult->setSelectors(implode('', $aSelectorParts), $oList);
if ($oParserState->comes('{')) {
$oParserState->consume(1);
}
} catch (UnexpectedTokenException $e) {
if ($oParserState->getSettings()->bLenientParsing) {
if (!$oParserState->comes('}')) {
$oParserState->consumeUntil('}', \false, \true);
}
return \false;
} else {
throw $e;
}
}
$oResult->setComments($aComments);
RuleSet::parseRuleSet($oParserState, $oResult);
return $oResult;
}
/**
* @param array<int, Selector|string>|string $mSelector
* @param CSSList|null $oList
*
* @throws UnexpectedTokenException
*/
public function setSelectors($mSelector, $oList = null)
{
if (is_array($mSelector)) {
$this->aSelectors = $mSelector;
} else {
$this->aSelectors = explode(',', $mSelector);
}
foreach ($this->aSelectors as $iKey => $mSelector) {
if (!$mSelector instanceof Selector) {
if ($oList === null || !$oList instanceof KeyFrame) {
if (!Selector::isValid($mSelector)) {
throw new UnexpectedTokenException("Selector did not match '" . Selector::SELECTOR_VALIDATION_RX . "'.", $mSelector, "custom");
}
$this->aSelectors[$iKey] = new Selector($mSelector);
} else {
if (!KeyframeSelector::isValid($mSelector)) {
throw new UnexpectedTokenException("Selector did not match '" . KeyframeSelector::SELECTOR_VALIDATION_RX . "'.", $mSelector, "custom");
}
$this->aSelectors[$iKey] = new KeyframeSelector($mSelector);
}
}
}
}
/**
* Remove one of the selectors of the block.
*
* @param Selector|string $mSelector
*
* @return bool
*/
public function removeSelector($mSelector)
{
if ($mSelector instanceof Selector) {
$mSelector = $mSelector->getSelector();
}
foreach ($this->aSelectors as $iKey => $oSelector) {
if ($oSelector->getSelector() === $mSelector) {
unset($this->aSelectors[$iKey]);
return \true;
}
}
return \false;
}
/**
* @return array<int, Selector|string>
*
* @deprecated will be removed in version 9.0; use `getSelectors()` instead
*/
public function getSelector()
{
return $this->getSelectors();
}
/**
* @param Selector|string $mSelector
* @param CSSList|null $oList
*
* @return void
*
* @deprecated will be removed in version 9.0; use `setSelectors()` instead
*/
public function setSelector($mSelector, $oList = null)
{
$this->setSelectors($mSelector, $oList);
}
/**
* @return array<int, Selector|string>
*/
public function getSelectors()
{
return $this->aSelectors;
}
/**
* Splits shorthand declarations (e.g. `margin` or `font`) into their constituent parts.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandShorthands()
{
// border must be expanded before dimensions
$this->expandBorderShorthand();
$this->expandDimensionsShorthand();
$this->expandFontShorthand();
$this->expandBackgroundShorthand();
$this->expandListStyleShorthand();
}
/**
* Creates shorthand declarations (e.g. `margin` or `font`) whenever possible.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createShorthands()
{
$this->createBackgroundShorthand();
$this->createDimensionsShorthand();
// border must be shortened after dimensions
$this->createBorderShorthand();
$this->createFontShorthand();
$this->createListStyleShorthand();
}
/**
* Splits shorthand border declarations (e.g. `border: 1px red;`).
*
* Additional splitting happens in expandDimensionsShorthand.
*
* Multiple borders are not yet supported as of 3.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandBorderShorthand()
{
$aBorderRules = ['border', 'border-left', 'border-right', 'border-top', 'border-bottom'];
$aBorderSizes = ['thin', 'medium', 'thick'];
$aRules = $this->getRulesAssoc();
foreach ($aBorderRules as $sBorderRule) {
if (!isset($aRules[$sBorderRule])) {
continue;
}
$oRule = $aRules[$sBorderRule];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
foreach ($aValues as $mValue) {
if ($mValue instanceof Value) {
$mNewValue = clone $mValue;
} else {
$mNewValue = $mValue;
}
if ($mValue instanceof Size) {
$sNewRuleName = $sBorderRule . "-width";
} elseif ($mValue instanceof Color) {
$sNewRuleName = $sBorderRule . "-color";
} else if (in_array($mValue, $aBorderSizes)) {
$sNewRuleName = $sBorderRule . "-width";
} else {
$sNewRuleName = $sBorderRule . "-style";
}
$oNewRule = new Rule($sNewRuleName, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->setIsImportant($oRule->getIsImportant());
$oNewRule->addValue([$mNewValue]);
$this->addRule($oNewRule);
}
$this->removeRule($sBorderRule);
}
}
/**
* Splits shorthand dimensional declarations (e.g. `margin: 0px auto;`)
* into their constituent parts.
*
* Handles `margin`, `padding`, `border-color`, `border-style` and `border-width`.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandDimensionsShorthand()
{
$aExpansions = ['margin' => 'margin-%s', 'padding' => 'padding-%s', 'border-color' => 'border-%s-color', 'border-style' => 'border-%s-style', 'border-width' => 'border-%s-width'];
$aRules = $this->getRulesAssoc();
foreach ($aExpansions as $sProperty => $sExpanded) {
if (!isset($aRules[$sProperty])) {
continue;
}
$oRule = $aRules[$sProperty];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
$top = $right = $bottom = $left = null;
switch (count($aValues)) {
case 1:
$top = $right = $bottom = $left = $aValues[0];
break;
case 2:
$top = $bottom = $aValues[0];
$left = $right = $aValues[1];
break;
case 3:
$top = $aValues[0];
$left = $right = $aValues[1];
$bottom = $aValues[2];
break;
case 4:
$top = $aValues[0];
$right = $aValues[1];
$bottom = $aValues[2];
$left = $aValues[3];
break;
}
foreach (['top', 'right', 'bottom', 'left'] as $sPosition) {
$oNewRule = new Rule(sprintf($sExpanded, $sPosition), $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->setIsImportant($oRule->getIsImportant());
$oNewRule->addValue(${$sPosition});
$this->addRule($oNewRule);
}
$this->removeRule($sProperty);
}
}
/**
* Converts shorthand font declarations
* (e.g. `font: 300 italic 11px/14px verdana, helvetica, sans-serif;`)
* into their constituent parts.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandFontShorthand()
{
$aRules = $this->getRulesAssoc();
if (!isset($aRules['font'])) {
return;
}
$oRule = $aRules['font'];
// reset properties to 'normal' per http://www.w3.org/TR/21/fonts.html#font-shorthand
$aFontProperties = ['font-style' => 'normal', 'font-variant' => 'normal', 'font-weight' => 'normal', 'font-size' => 'normal', 'line-height' => 'normal'];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
foreach ($aValues as $mValue) {
if (!$mValue instanceof Value) {
$mValue = mb_strtolower($mValue);
}
if (in_array($mValue, ['normal', 'inherit'])) {
foreach (['font-style', 'font-weight', 'font-variant'] as $sProperty) {
if (!isset($aFontProperties[$sProperty])) {
$aFontProperties[$sProperty] = $mValue;
}
}
} elseif (in_array($mValue, ['italic', 'oblique'])) {
$aFontProperties['font-style'] = $mValue;
} elseif ($mValue == 'small-caps') {
$aFontProperties['font-variant'] = $mValue;
} elseif (in_array($mValue, ['bold', 'bolder', 'lighter']) || $mValue instanceof Size && in_array($mValue->getSize(), range(100, 900, 100))) {
$aFontProperties['font-weight'] = $mValue;
} elseif ($mValue instanceof RuleValueList && $mValue->getListSeparator() == '/') {
list($oSize, $oHeight) = $mValue->getListComponents();
$aFontProperties['font-size'] = $oSize;
$aFontProperties['line-height'] = $oHeight;
} elseif ($mValue instanceof Size && $mValue->getUnit() !== null) {
$aFontProperties['font-size'] = $mValue;
} else {
$aFontProperties['font-family'] = $mValue;
}
}
foreach ($aFontProperties as $sProperty => $mValue) {
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->addValue($mValue);
$oNewRule->setIsImportant($oRule->getIsImportant());
$this->addRule($oNewRule);
}
$this->removeRule('font');
}
/**
* Converts shorthand background declarations
* (e.g. `background: url("chess.png") gray 50% repeat fixed;`)
* into their constituent parts.
*
* @see http://www.w3.org/TR/21/colors.html#propdef-background
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandBackgroundShorthand()
{
$aRules = $this->getRulesAssoc();
if (!isset($aRules['background'])) {
return;
}
$oRule = $aRules['background'];
$aBgProperties = ['background-color' => ['transparent'], 'background-image' => ['none'], 'background-repeat' => ['repeat'], 'background-attachment' => ['scroll'], 'background-position' => [new Size(0, '%', \false, $this->iLineNo), new Size(0, '%', \false, $this->iLineNo)]];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
if (count($aValues) == 1 && $aValues[0] == 'inherit') {
foreach ($aBgProperties as $sProperty => $mValue) {
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->addValue('inherit');
$oNewRule->setIsImportant($oRule->getIsImportant());
$this->addRule($oNewRule);
}
$this->removeRule('background');
return;
}
$iNumBgPos = 0;
foreach ($aValues as $mValue) {
if (!$mValue instanceof Value) {
$mValue = mb_strtolower($mValue);
}
if ($mValue instanceof URL) {
$aBgProperties['background-image'] = $mValue;
} elseif ($mValue instanceof Color) {
$aBgProperties['background-color'] = $mValue;
} elseif (in_array($mValue, ['scroll', 'fixed'])) {
$aBgProperties['background-attachment'] = $mValue;
} elseif (in_array($mValue, ['repeat', 'no-repeat', 'repeat-x', 'repeat-y'])) {
$aBgProperties['background-repeat'] = $mValue;
} elseif (in_array($mValue, ['left', 'center', 'right', 'top', 'bottom']) || $mValue instanceof Size) {
if ($iNumBgPos == 0) {
$aBgProperties['background-position'][0] = $mValue;
$aBgProperties['background-position'][1] = 'center';
} else {
$aBgProperties['background-position'][$iNumBgPos] = $mValue;
}
$iNumBgPos++;
}
}
foreach ($aBgProperties as $sProperty => $mValue) {
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->setIsImportant($oRule->getIsImportant());
$oNewRule->addValue($mValue);
$this->addRule($oNewRule);
}
$this->removeRule('background');
}
/**
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function expandListStyleShorthand()
{
$aListProperties = ['list-style-type' => 'disc', 'list-style-position' => 'outside', 'list-style-image' => 'none'];
$aListStyleTypes = ['none', 'disc', 'circle', 'square', 'decimal-leading-zero', 'decimal', 'lower-roman', 'upper-roman', 'lower-greek', 'lower-alpha', 'lower-latin', 'upper-alpha', 'upper-latin', 'hebrew', 'armenian', 'georgian', 'cjk-ideographic', 'hiragana', 'hira-gana-iroha', 'katakana-iroha', 'katakana'];
$aListStylePositions = ['inside', 'outside'];
$aRules = $this->getRulesAssoc();
if (!isset($aRules['list-style'])) {
return;
}
$oRule = $aRules['list-style'];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
if (count($aValues) == 1 && $aValues[0] == 'inherit') {
foreach ($aListProperties as $sProperty => $mValue) {
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->addValue('inherit');
$oNewRule->setIsImportant($oRule->getIsImportant());
$this->addRule($oNewRule);
}
$this->removeRule('list-style');
return;
}
foreach ($aValues as $mValue) {
if (!$mValue instanceof Value) {
$mValue = mb_strtolower($mValue);
}
if ($mValue instanceof Url) {
$aListProperties['list-style-image'] = $mValue;
} elseif (in_array($mValue, $aListStyleTypes)) {
$aListProperties['list-style-types'] = $mValue;
} elseif (in_array($mValue, $aListStylePositions)) {
$aListProperties['list-style-position'] = $mValue;
}
}
foreach ($aListProperties as $sProperty => $mValue) {
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
$oNewRule->setIsImportant($oRule->getIsImportant());
$oNewRule->addValue($mValue);
$this->addRule($oNewRule);
}
$this->removeRule('list-style');
}
/**
* @param array<array-key, string> $aProperties
* @param string $sShorthand
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createShorthandProperties(array $aProperties, $sShorthand)
{
$aRules = $this->getRulesAssoc();
$oRule = null;
$aNewValues = [];
foreach ($aProperties as $sProperty) {
if (!isset($aRules[$sProperty])) {
continue;
}
$oRule = $aRules[$sProperty];
if (!$oRule->getIsImportant()) {
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
foreach ($aValues as $mValue) {
$aNewValues[] = $mValue;
}
$this->removeRule($sProperty);
}
}
if ($aNewValues !== [] && $oRule instanceof Rule) {
$oNewRule = new Rule($sShorthand, $oRule->getLineNo(), $oRule->getColNo());
foreach ($aNewValues as $mValue) {
$oNewRule->addValue($mValue);
}
$this->addRule($oNewRule);
}
}
/**
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createBackgroundShorthand()
{
$aProperties = ['background-color', 'background-image', 'background-repeat', 'background-position', 'background-attachment'];
$this->createShorthandProperties($aProperties, 'background');
}
/**
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createListStyleShorthand()
{
$aProperties = ['list-style-type', 'list-style-position', 'list-style-image'];
$this->createShorthandProperties($aProperties, 'list-style');
}
/**
* Combines `border-color`, `border-style` and `border-width` into `border`.
*
* Should be run after `create_dimensions_shorthand`!
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createBorderShorthand()
{
$aProperties = ['border-width', 'border-style', 'border-color'];
$this->createShorthandProperties($aProperties, 'border');
}
/**
* Looks for long format CSS dimensional properties
* (margin, padding, border-color, border-style and border-width)
* and converts them into shorthand CSS properties.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createDimensionsShorthand()
{
$aPositions = ['top', 'right', 'bottom', 'left'];
$aExpansions = ['margin' => 'margin-%s', 'padding' => 'padding-%s', 'border-color' => 'border-%s-color', 'border-style' => 'border-%s-style', 'border-width' => 'border-%s-width'];
$aRules = $this->getRulesAssoc();
foreach ($aExpansions as $sProperty => $sExpanded) {
$aFoldable = [];
foreach ($aRules as $sRuleName => $oRule) {
foreach ($aPositions as $sPosition) {
if ($sRuleName == sprintf($sExpanded, $sPosition)) {
$aFoldable[$sRuleName] = $oRule;
}
}
}
// All four dimensions must be present
if (count($aFoldable) == 4) {
$aValues = [];
foreach ($aPositions as $sPosition) {
$oRule = $aRules[sprintf($sExpanded, $sPosition)];
$mRuleValue = $oRule->getValue();
$aRuleValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aRuleValues[] = $mRuleValue;
} else {
$aRuleValues = $mRuleValue->getListComponents();
}
$aValues[$sPosition] = $aRuleValues;
}
$oNewRule = new Rule($sProperty, $oRule->getLineNo(), $oRule->getColNo());
if ((string) $aValues['left'][0] == (string) $aValues['right'][0]) {
if ((string) $aValues['top'][0] == (string) $aValues['bottom'][0]) {
if ((string) $aValues['top'][0] == (string) $aValues['left'][0]) {
// All 4 sides are equal
$oNewRule->addValue($aValues['top']);
} else {
// Top and bottom are equal, left and right are equal
$oNewRule->addValue($aValues['top']);
$oNewRule->addValue($aValues['left']);
}
} else {
// Only left and right are equal
$oNewRule->addValue($aValues['top']);
$oNewRule->addValue($aValues['left']);
$oNewRule->addValue($aValues['bottom']);
}
} else {
// No sides are equal
$oNewRule->addValue($aValues['top']);
$oNewRule->addValue($aValues['left']);
$oNewRule->addValue($aValues['bottom']);
$oNewRule->addValue($aValues['right']);
}
$this->addRule($oNewRule);
foreach ($aPositions as $sPosition) {
$this->removeRule(sprintf($sExpanded, $sPosition));
}
}
}
}
/**
* Looks for long format CSS font properties (e.g. `font-weight`) and
* tries to convert them into a shorthand CSS `font` property.
*
* At least `font-size` AND `font-family` must be present in order to create a shorthand declaration.
*
* @return void
*
* @deprecated since 8.7.0, will be removed without substitution in version 9.0 in #511
*/
public function createFontShorthand()
{
$aFontProperties = ['font-style', 'font-variant', 'font-weight', 'font-size', 'line-height', 'font-family'];
$aRules = $this->getRulesAssoc();
if (!isset($aRules['font-size']) || !isset($aRules['font-family'])) {
return;
}
$oOldRule = isset($aRules['font-size']) ? $aRules['font-size'] : $aRules['font-family'];
$oNewRule = new Rule('font', $oOldRule->getLineNo(), $oOldRule->getColNo());
unset($oOldRule);
foreach (['font-style', 'font-variant', 'font-weight'] as $sProperty) {
if (isset($aRules[$sProperty])) {
$oRule = $aRules[$sProperty];
$mRuleValue = $oRule->getValue();
$aValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aValues[] = $mRuleValue;
} else {
$aValues = $mRuleValue->getListComponents();
}
if ($aValues[0] !== 'normal') {
$oNewRule->addValue($aValues[0]);
}
}
}
// Get the font-size value
$oRule = $aRules['font-size'];
$mRuleValue = $oRule->getValue();
$aFSValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aFSValues[] = $mRuleValue;
} else {
$aFSValues = $mRuleValue->getListComponents();
}
// But wait to know if we have line-height to add it
if (isset($aRules['line-height'])) {
$oRule = $aRules['line-height'];
$mRuleValue = $oRule->getValue();
$aLHValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aLHValues[] = $mRuleValue;
} else {
$aLHValues = $mRuleValue->getListComponents();
}
if ($aLHValues[0] !== 'normal') {
$val = new RuleValueList('/', $this->iLineNo);
$val->addListComponent($aFSValues[0]);
$val->addListComponent($aLHValues[0]);
$oNewRule->addValue($val);
}
} else {
$oNewRule->addValue($aFSValues[0]);
}
$oRule = $aRules['font-family'];
$mRuleValue = $oRule->getValue();
$aFFValues = [];
if (!$mRuleValue instanceof RuleValueList) {
$aFFValues[] = $mRuleValue;
} else {
$aFFValues = $mRuleValue->getListComponents();
}
$oFFValue = new RuleValueList(',', $this->iLineNo);
$oFFValue->setListComponents($aFFValues);
$oNewRule->addValue($oFFValue);
$this->addRule($oNewRule);
foreach ($aFontProperties as $sProperty) {
$this->removeRule($sProperty);
}
}
/**
* @return string
*
* @throws OutputException
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*
* @throws OutputException
*/
public function render($oOutputFormat)
{
$sResult = $oOutputFormat->comments($this);
if (count($this->aSelectors) === 0) {
// If all the selectors have been removed, this declaration block becomes invalid
throw new OutputException("Attempt to print declaration block with missing selector", $this->iLineNo);
}
$sResult .= $oOutputFormat->sBeforeDeclarationBlock;
$sResult .= $oOutputFormat->implode($oOutputFormat->spaceBeforeSelectorSeparator() . ',' . $oOutputFormat->spaceAfterSelectorSeparator(), $this->aSelectors);
$sResult .= $oOutputFormat->sAfterDeclarationBlockSelectors;
$sResult .= $oOutputFormat->spaceBeforeOpeningBrace() . '{';
$sResult .= $this->renderRules($oOutputFormat);
$sResult .= '}';
$sResult .= $oOutputFormat->sAfterDeclarationBlock;
return $sResult;
}
}
@@ -0,0 +1,314 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\RuleSet;
use JooosiFonDeps\Sabberworm\CSS\Comment\Comment;
use JooosiFonDeps\Sabberworm\CSS\Comment\Commentable;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
use JooosiFonDeps\Sabberworm\CSS\Rule\Rule;
/**
* This class is a container for individual 'Rule's.
*
* The most common form of a rule set is one constrained by a selector, i.e., a `DeclarationBlock`.
* However, unknown `AtRule`s (like `@font-face`) are rule sets as well.
*
* If you want to manipulate a `RuleSet`, use the methods `addRule(Rule $rule)`, `getRules()` and `removeRule($rule)`
* (which accepts either a `Rule` or a rule name; optionally suffixed by a dash to remove all related rules).
*/
abstract class RuleSet implements Renderable, Commentable
{
/**
* the rules in this rule set, using the property name as the key,
* with potentially multiple rules per property name.
*
* @var array<string, array<int<0, max>, Rule>>
*/
private $aRules;
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @var array<array-key, Comment>
*
* @internal since 8.8.0
*/
protected $aComments;
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
$this->aRules = [];
$this->iLineNo = $iLineNo;
$this->aComments = [];
}
/**
* @return void
*
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parseRuleSet(ParserState $oParserState, RuleSet $oRuleSet)
{
while ($oParserState->comes(';')) {
$oParserState->consume(';');
}
while (\true) {
$commentsBeforeRule = $oParserState->consumeWhiteSpace();
if ($oParserState->comes('}')) {
break;
}
$oRule = null;
if ($oParserState->getSettings()->bLenientParsing) {
try {
$oRule = Rule::parse($oParserState, $commentsBeforeRule);
} catch (UnexpectedTokenException $e) {
try {
$sConsume = $oParserState->consumeUntil(["\n", ";", '}'], \true);
// We need to “unfind” the matches to the end of the ruleSet as this will be matched later
if ($oParserState->streql(substr($sConsume, -1), '}')) {
$oParserState->backtrack(1);
} else {
while ($oParserState->comes(';')) {
$oParserState->consume(';');
}
}
} catch (UnexpectedTokenException $e) {
// We’ve reached the end of the document. Just close the RuleSet.
return;
}
}
} else {
$oRule = Rule::parse($oParserState, $commentsBeforeRule);
}
if ($oRule) {
$oRuleSet->addRule($oRule);
}
}
$oParserState->consume('}');
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
/**
* @param Rule|null $oSibling
*
* @return void
*/
public function addRule(Rule $oRule, $oSibling = null)
{
$sRule = $oRule->getRule();
if (!isset($this->aRules[$sRule])) {
$this->aRules[$sRule] = [];
}
$iPosition = count($this->aRules[$sRule]);
if ($oSibling !== null) {
$iSiblingPos = array_search($oSibling, $this->aRules[$sRule], \true);
if ($iSiblingPos !== \false) {
$iPosition = $iSiblingPos;
$oRule->setPosition($oSibling->getLineNo(), $oSibling->getColNo() - 1);
}
}
if ($oRule->getLineNo() === 0 && $oRule->getColNo() === 0) {
//this node is added manually, give it the next best line
$rules = $this->getRules();
$pos = count($rules);
if ($pos > 0) {
$last = $rules[$pos - 1];
$oRule->setPosition($last->getLineNo() + 1, 0);
}
}
array_splice($this->aRules[$sRule], $iPosition, 0, [$oRule]);
}
/**
* Returns all rules matching the given rule name
*
* @example $oRuleSet->getRules('font') // returns array(0 => $oRule, …) or array().
*
* @example $oRuleSet->getRules('font-')
* //returns an array of all rules either beginning with font- or matching font.
*
* @param Rule|string|null $mRule
* Pattern to search for. If null, returns all rules.
* If the pattern ends with a dash, all rules starting with the pattern are returned
* as well as one matching the pattern with the dash excluded.
* Passing a Rule behaves like calling `getRules($mRule->getRule())`.
*
* @return array<int, Rule>
*/
public function getRules($mRule = null)
{
if ($mRule instanceof Rule) {
$mRule = $mRule->getRule();
}
/** @var array<int, Rule> $aResult */
$aResult = [];
foreach ($this->aRules as $sName => $aRules) {
// Either no search rule is given or the search rule matches the found rule exactly
// or the search rule ends in “-” and the found rule starts with the search rule.
if (!$mRule || $sName === $mRule || strrpos($mRule, '-') === strlen($mRule) - strlen('-') && (strpos($sName, $mRule) === 0 || $sName === substr($mRule, 0, -1))) {
$aResult = array_merge($aResult, $aRules);
}
}
usort($aResult, function (Rule $first, Rule $second) {
if ($first->getLineNo() === $second->getLineNo()) {
return $first->getColNo() - $second->getColNo();
}
return $first->getLineNo() - $second->getLineNo();
});
return $aResult;
}
/**
* Overrides all the rules of this set.
*
* @param array<array-key, Rule> $aRules The rules to override with.
*
* @return void
*/
public function setRules(array $aRules)
{
$this->aRules = [];
foreach ($aRules as $rule) {
$this->addRule($rule);
}
}
/**
* Returns all rules matching the given pattern and returns them in an associative array with the rule’s name
* as keys. This method exists mainly for backwards-compatibility and is really only partially useful.
*
* Note: This method loses some information: Calling this (with an argument of `background-`) on a declaration block
* like `{ background-color: green; background-color; rgba(0, 127, 0, 0.7); }` will only yield an associative array
* containing the rgba-valued rule while `getRules()` would yield an indexed array containing both.
*
* @param Rule|string|null $mRule $mRule
* Pattern to search for. If null, returns all rules. If the pattern ends with a dash,
* all rules starting with the pattern are returned as well as one matching the pattern with the dash
* excluded. Passing a Rule behaves like calling `getRules($mRule->getRule())`.
*
* @return array<string, Rule>
*/
public function getRulesAssoc($mRule = null)
{
/** @var array<string, Rule> $aResult */
$aResult = [];
foreach ($this->getRules($mRule) as $oRule) {
$aResult[$oRule->getRule()] = $oRule;
}
return $aResult;
}
/**
* Removes a rule from this RuleSet. This accepts all the possible values that `getRules()` accepts.
*
* If given a Rule, it will only remove this particular rule (by identity).
* If given a name, it will remove all rules by that name.
*
* Note: this is different from pre-v.2.0 behaviour of PHP-CSS-Parser, where passing a Rule instance would
* remove all rules with the same name. To get the old behaviour, use `removeRule($oRule->getRule())`.
*
* @param Rule|string|null $mRule
* pattern to remove. If $mRule is null, all rules are removed. If the pattern ends in a dash,
* all rules starting with the pattern are removed as well as one matching the pattern with the dash
* excluded. Passing a Rule behaves matches by identity.
*
* @return void
*/
public function removeRule($mRule)
{
if ($mRule instanceof Rule) {
$sRule = $mRule->getRule();
if (!isset($this->aRules[$sRule])) {
return;
}
foreach ($this->aRules[$sRule] as $iKey => $oRule) {
if ($oRule === $mRule) {
unset($this->aRules[$sRule][$iKey]);
}
}
} else {
foreach ($this->aRules as $sName => $aRules) {
// Either no search rule is given or the search rule matches the found rule exactly
// or the search rule ends in “-” and the found rule starts with the search rule or equals it
// (without the trailing dash).
if (!$mRule || $sName === $mRule || strrpos($mRule, '-') === strlen($mRule) - strlen('-') && (strpos($sName, $mRule) === 0 || $sName === substr($mRule, 0, -1))) {
unset($this->aRules[$sName]);
}
}
}
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @return string
*/
protected function renderRules(OutputFormat $oOutputFormat)
{
$sResult = '';
$bIsFirst = \true;
$oNextLevel = $oOutputFormat->nextLevel();
foreach ($this->getRules() as $oRule) {
$sRendered = $oNextLevel->safely(function () use ($oRule, $oNextLevel) {
return $oRule->render($oNextLevel);
});
if ($sRendered === null) {
continue;
}
if ($bIsFirst) {
$bIsFirst = \false;
$sResult .= $oNextLevel->spaceBeforeRules();
} else {
$sResult .= $oNextLevel->spaceBetweenRules();
}
$sResult .= $sRendered;
}
if (!$bIsFirst) {
// Had some output
$sResult .= $oOutputFormat->spaceAfterRules();
}
return $oOutputFormat->removeLastSemicolon($sResult);
}
/**
* @param array<string, Comment> $aComments
*
* @return void
*/
public function addComments(array $aComments)
{
$this->aComments = array_merge($this->aComments, $aComments);
}
/**
* @return array<string, Comment>
*/
public function getComments()
{
return $this->aComments;
}
/**
* @param array<string, Comment> $aComments
*
* @return void
*/
public function setComments(array $aComments)
{
$this->aComments = $aComments;
}
}
@@ -0,0 +1,98 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS;
/**
* Parser settings class.
*
* Configure parser behaviour here.
*/
class Settings
{
/**
* Multi-byte string support.
*
* If `true` (`mbstring` extension must be enabled), will use (slower) `mb_strlen`, `mb_convert_case`, `mb_substr`
* and `mb_strpos` functions. Otherwise, the normal (ASCII-Only) functions will be used.
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bMultibyteSupport;
/**
* The default charset for the CSS if no `@charset` declaration is found. Defaults to utf-8.
*
* @var string
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $sDefaultCharset = 'utf-8';
/**
* Whether the parser silently ignore invalid rules instead of choking on them.
*
* @var bool
*
* @internal since 8.8.0, will be made private in 9.0.0
*/
public $bLenientParsing = \true;
private function __construct()
{
$this->bMultibyteSupport = extension_loaded('mbstring');
}
/**
* @return self new instance
*/
public static function create()
{
return new Settings();
}
/**
* Enables/disables multi-byte string support.
*
* If `true` (`mbstring` extension must be enabled), will use (slower) `mb_strlen`, `mb_convert_case`, `mb_substr`
* and `mb_strpos` functions. Otherwise, the normal (ASCII-Only) functions will be used.
*
* @param bool $bMultibyteSupport
*
* @return self fluent interface
*/
public function withMultibyteSupport($bMultibyteSupport = \true)
{
$this->bMultibyteSupport = $bMultibyteSupport;
return $this;
}
/**
* Sets the charset to be used if the CSS does not contain an `@charset` declaration.
*
* @param string $sDefaultCharset
*
* @return self fluent interface
*/
public function withDefaultCharset($sDefaultCharset)
{
$this->sDefaultCharset = $sDefaultCharset;
return $this;
}
/**
* Configures whether the parser should silently ignore invalid rules.
*
* @param bool $bLenientParsing
*
* @return self fluent interface
*/
public function withLenientParsing($bLenientParsing = \true)
{
$this->bLenientParsing = $bLenientParsing;
return $this;
}
/**
* Configures the parser to choke on invalid rules.
*
* @return self fluent interface
*/
public function beStrict()
{
return $this->withLenientParsing(\false);
}
}
@@ -0,0 +1,101 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* A `CSSFunction` represents a special kind of value that also contains a function name and where the values are the
* function’s arguments. It also handles equals-sign-separated argument lists like `filter: alpha(opacity=90);`.
*/
class CSSFunction extends ValueList
{
/**
* @var string
*
* @internal since 8.8.0
*/
protected $sName;
/**
* @param string $sName
* @param RuleValueList|array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aArguments
* @param string $sSeparator
* @param int $iLineNo
*/
public function __construct($sName, $aArguments, $sSeparator = ',', $iLineNo = 0)
{
if ($aArguments instanceof RuleValueList) {
$sSeparator = $aArguments->getListSeparator();
$aArguments = $aArguments->getListComponents();
}
$this->sName = $sName;
$this->iLineNo = $iLineNo;
parent::__construct($aArguments, $sSeparator, $iLineNo);
}
/**
* @param ParserState $oParserState
* @param bool $bIgnoreCase
*
* @return CSSFunction
*
* @throws SourceException
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $bIgnoreCase = \false)
{
$mResult = $oParserState->parseIdentifier($bIgnoreCase);
$oParserState->consume('(');
$aArguments = Value::parseValue($oParserState, ['=', ' ', ',']);
$mResult = new CSSFunction($mResult, $aArguments, ',', $oParserState->currentLine());
$oParserState->consume(')');
return $mResult;
}
/**
* @return string
*/
public function getName()
{
return $this->sName;
}
/**
* @param string $sName
*
* @return void
*/
public function setName($sName)
{
$this->sName = $sName;
}
/**
* @return array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string>
*/
public function getArguments()
{
return $this->aComponents;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$aArguments = parent::render($oOutputFormat);
return "{$this->sName}({$aArguments})";
}
}
@@ -0,0 +1,106 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* This class is a wrapper for quoted strings to distinguish them from keywords.
*
* `CSSString`s always output with double quotes.
*/
class CSSString extends PrimitiveValue
{
/**
* @var string
*/
private $sString;
/**
* @param string $sString
* @param int $iLineNo
*/
public function __construct($sString, $iLineNo = 0)
{
$this->sString = $sString;
parent::__construct($iLineNo);
}
/**
* @return CSSString
*
* @throws SourceException
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState)
{
$sBegin = $oParserState->peek();
$sQuote = null;
if ($sBegin === "'") {
$sQuote = "'";
} elseif ($sBegin === '"') {
$sQuote = '"';
}
if ($sQuote !== null) {
$oParserState->consume($sQuote);
}
$sResult = "";
$sContent = null;
if ($sQuote === null) {
// Unquoted strings end in whitespace or with braces, brackets, parentheses
while (!preg_match('/[\s{}()<>\[\]]/isu', $oParserState->peek())) {
$sResult .= $oParserState->parseCharacter(\false);
}
} else {
while (!$oParserState->comes($sQuote)) {
$sContent = $oParserState->parseCharacter(\false);
if ($sContent === null) {
throw new SourceException("Non-well-formed quoted string {$oParserState->peek(3)}", $oParserState->currentLine());
}
$sResult .= $sContent;
}
$oParserState->consume($sQuote);
}
return new CSSString($sResult, $oParserState->currentLine());
}
/**
* @param string $sString
*
* @return void
*/
public function setString($sString)
{
$this->sString = $sString;
}
/**
* @return string
*/
public function getString()
{
return $this->sString;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$sString = addslashes($this->sString);
$sString = str_replace("\n", '\A', $sString);
return $oOutputFormat->getStringQuotingType() . $sString . $oOutputFormat->getStringQuotingType();
}
}
@@ -0,0 +1,91 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* Support for `-webkit-calc` and `-moz-calc` is deprecated in version 8.8.0, and will be removed in version 9.0.0.
*/
class CalcFunction extends CSSFunction
{
/**
* @var int
*
* @internal
*/
const T_OPERAND = 1;
/**
* @var int
*
* @internal
*/
const T_OPERATOR = 2;
/**
* @param ParserState $oParserState
* @param bool $bIgnoreCase
*
* @return CalcFunction
*
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $bIgnoreCase = \false)
{
$aOperators = ['+', '-', '*', '/'];
$sFunction = $oParserState->parseIdentifier();
if ($oParserState->peek() != '(') {
// Found ; or end of line before an opening bracket
throw new UnexpectedTokenException('(', $oParserState->peek(), 'literal', $oParserState->currentLine());
} elseif (!in_array($sFunction, ['calc', '-moz-calc', '-webkit-calc'])) {
// Found invalid calc definition. Example calc (...
throw new UnexpectedTokenException('calc', $sFunction, 'literal', $oParserState->currentLine());
}
$oParserState->consume('(');
$oCalcList = new CalcRuleValueList($oParserState->currentLine());
$oList = new RuleValueList(',', $oParserState->currentLine());
$iNestingLevel = 0;
$iLastComponentType = null;
while (!$oParserState->comes(')') || $iNestingLevel > 0) {
if ($oParserState->isEnd() && $iNestingLevel === 0) {
break;
}
$oParserState->consumeWhiteSpace();
if ($oParserState->comes('(')) {
$iNestingLevel++;
$oCalcList->addListComponent($oParserState->consume(1));
$oParserState->consumeWhiteSpace();
continue;
} elseif ($oParserState->comes(')')) {
$iNestingLevel--;
$oCalcList->addListComponent($oParserState->consume(1));
$oParserState->consumeWhiteSpace();
continue;
}
if ($iLastComponentType != CalcFunction::T_OPERAND) {
$oVal = Value::parsePrimitiveValue($oParserState);
$oCalcList->addListComponent($oVal);
$iLastComponentType = CalcFunction::T_OPERAND;
} else if (in_array($oParserState->peek(), $aOperators)) {
if ($oParserState->comes('-') || $oParserState->comes('+')) {
if ($oParserState->peek(1, -1) != ' ' || !($oParserState->comes('- ') || $oParserState->comes('+ '))) {
throw new UnexpectedTokenException(" {$oParserState->peek()} ", $oParserState->peek(1, -1) . $oParserState->peek(2), 'literal', $oParserState->currentLine());
}
}
$oCalcList->addListComponent($oParserState->consume(1));
$iLastComponentType = CalcFunction::T_OPERATOR;
} else {
throw new UnexpectedTokenException(sprintf('Next token was expected to be an operand of type %s. Instead "%s" was found.', implode(', ', $aOperators), $oParserState->peek()), '', 'custom', $oParserState->currentLine());
}
$oParserState->consumeWhiteSpace();
}
$oList->addListComponent($oCalcList);
if (!$oParserState->isEnd()) {
$oParserState->consume(')');
}
return new CalcFunction($sFunction, $oList, ',', $oParserState->currentLine());
}
}
@@ -0,0 +1,24 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
class CalcRuleValueList extends RuleValueList
{
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct(',', $iLineNo);
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return $oOutputFormat->implode(' ', $this->aComponents);
}
}
@@ -0,0 +1,147 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* `Color's can be input in the form #rrggbb, #rgb or schema(val1, val2, …) but are always stored as an array of
* ('s' => val1, 'c' => val2, 'h' => val3, …) and output in the second form.
*/
class Color extends CSSFunction
{
/**
* @param array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aColor
* @param int $iLineNo
*/
public function __construct(array $aColor, $iLineNo = 0)
{
parent::__construct(implode('', array_keys($aColor)), $aColor, ',', $iLineNo);
}
/**
* @param ParserState $oParserState
* @param bool $bIgnoreCase
*
* @return Color|CSSFunction
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $bIgnoreCase = \false)
{
$aColor = [];
if ($oParserState->comes('#')) {
$oParserState->consume('#');
$sValue = $oParserState->parseIdentifier(\false);
if ($oParserState->strlen($sValue) === 3) {
$sValue = $sValue[0] . $sValue[0] . $sValue[1] . $sValue[1] . $sValue[2] . $sValue[2];
} elseif ($oParserState->strlen($sValue) === 4) {
$sValue = $sValue[0] . $sValue[0] . $sValue[1] . $sValue[1] . $sValue[2] . $sValue[2] . $sValue[3] . $sValue[3];
}
if ($oParserState->strlen($sValue) === 8) {
$aColor = ['r' => new Size(intval($sValue[0] . $sValue[1], 16), null, \true, $oParserState->currentLine()), 'g' => new Size(intval($sValue[2] . $sValue[3], 16), null, \true, $oParserState->currentLine()), 'b' => new Size(intval($sValue[4] . $sValue[5], 16), null, \true, $oParserState->currentLine()), 'a' => new Size(round(self::mapRange(intval($sValue[6] . $sValue[7], 16), 0, 255, 0, 1), 2), null, \true, $oParserState->currentLine())];
} elseif ($oParserState->strlen($sValue) === 6) {
$aColor = ['r' => new Size(intval($sValue[0] . $sValue[1], 16), null, \true, $oParserState->currentLine()), 'g' => new Size(intval($sValue[2] . $sValue[3], 16), null, \true, $oParserState->currentLine()), 'b' => new Size(intval($sValue[4] . $sValue[5], 16), null, \true, $oParserState->currentLine())];
} else {
throw new UnexpectedTokenException('Invalid hex color value', $sValue, 'custom', $oParserState->currentLine());
}
} else {
$sColorMode = $oParserState->parseIdentifier(\true);
$oParserState->consumeWhiteSpace();
$oParserState->consume('(');
$bContainsVar = \false;
$iLength = $oParserState->strlen($sColorMode);
for ($i = 0; $i < $iLength; ++$i) {
$oParserState->consumeWhiteSpace();
if ($oParserState->comes('var')) {
$aColor[$sColorMode[$i]] = CSSFunction::parseIdentifierOrFunction($oParserState);
$bContainsVar = \true;
} else {
$aColor[$sColorMode[$i]] = Size::parse($oParserState, \true);
}
if ($bContainsVar && $oParserState->comes(')')) {
// With a var argument the function can have fewer arguments
break;
}
$oParserState->consumeWhiteSpace();
if ($i < $iLength - 1) {
$oParserState->consume(',');
}
}
$oParserState->consume(')');
if ($bContainsVar) {
return new CSSFunction($sColorMode, array_values($aColor), ',', $oParserState->currentLine());
}
}
return new Color($aColor, $oParserState->currentLine());
}
/**
* @param float $fVal
* @param float $fFromMin
* @param float $fFromMax
* @param float $fToMin
* @param float $fToMax
*
* @return float
*/
private static function mapRange($fVal, $fFromMin, $fFromMax, $fToMin, $fToMax)
{
$fFromRange = $fFromMax - $fFromMin;
$fToRange = $fToMax - $fToMin;
$fMultiplier = $fToRange / $fFromRange;
$fNewVal = $fVal - $fFromMin;
$fNewVal *= $fMultiplier;
return $fNewVal + $fToMin;
}
/**
* @return array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string>
*/
public function getColor()
{
return $this->aComponents;
}
/**
* @param array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aColor
*
* @return void
*/
public function setColor(array $aColor)
{
$this->setName(implode('', array_keys($aColor)));
$this->aComponents = $aColor;
}
/**
* @return string
*/
public function getColorDescription()
{
return $this->getName();
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
// Shorthand RGB color values
if ($oOutputFormat->getRGBHashNotation() && implode('', array_keys($this->aComponents)) === 'rgb') {
$sResult = sprintf('%02x%02x%02x', $this->aComponents['r']->getSize(), $this->aComponents['g']->getSize(), $this->aComponents['b']->getSize());
return '#' . ($sResult[0] == $sResult[1] && $sResult[2] == $sResult[3] && $sResult[4] == $sResult[5] ? "{$sResult[0]}{$sResult[2]}{$sResult[4]}" : $sResult);
}
return parent::render($oOutputFormat);
}
}
@@ -0,0 +1,67 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
class LineName extends ValueList
{
/**
* @param array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aComponents
* @param int $iLineNo
*/
public function __construct(array $aComponents = [], $iLineNo = 0)
{
parent::__construct($aComponents, ' ', $iLineNo);
}
/**
* @return LineName
*
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState)
{
$oParserState->consume('[');
$oParserState->consumeWhiteSpace();
$aNames = [];
do {
if ($oParserState->getSettings()->bLenientParsing) {
try {
$aNames[] = $oParserState->parseIdentifier();
} catch (UnexpectedTokenException $e) {
if (!$oParserState->comes(']')) {
throw $e;
}
}
} else {
$aNames[] = $oParserState->parseIdentifier();
}
$oParserState->consumeWhiteSpace();
} while (!$oParserState->comes(']'));
$oParserState->consume(']');
return new LineName($aNames, $oParserState->currentLine());
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return '[' . parent::render(OutputFormat::createCompact()) . ']';
}
}
@@ -0,0 +1,14 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
abstract class PrimitiveValue extends Value
{
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
parent::__construct($iLineNo);
}
}
@@ -0,0 +1,20 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
/**
* This class is used to represent all multivalued rules like `font: bold 12px/3 Helvetica, Verdana, sans-serif;`
* (where the value would be a whitespace-separated list of the primitive value `bold`, a slash-separated list
* and a comma-separated list).
*/
class RuleValueList extends ValueList
{
/**
* @param string $sSeparator
* @param int $iLineNo
*/
public function __construct($sSeparator = ',', $iLineNo = 0)
{
parent::__construct([], $sSeparator, $iLineNo);
}
}
@@ -0,0 +1,208 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* A `Size` consists of a numeric `size` value and a unit.
*/
class Size extends PrimitiveValue
{
/**
* vh/vw/vm(ax)/vmin/rem are absolute insofar as they don’t scale to the immediate parent (only the viewport)
*
* @var array<int, string>
*
* @internal
*/
const ABSOLUTE_SIZE_UNITS = ['px', 'pt', 'pc', 'cm', 'mm', 'mozmm', 'in', 'vh', 'dvh', 'svh', 'lvh', 'vw', 'vmin', 'vmax', 'rem'];
/**
* @var array<int, string>
*
* @internal
*/
const RELATIVE_SIZE_UNITS = ['%', 'em', 'ex', 'ch', 'fr'];
/**
* @var array<int, string>
*
* @internal
*/
const NON_SIZE_UNITS = ['deg', 'grad', 'rad', 's', 'ms', 'turn', 'Hz', 'kHz'];
/**
* @var array<int, array<string, string>>|null
*/
private static $SIZE_UNITS = null;
/**
* @var float
*/
private $fSize;
/**
* @var string|null
*/
private $sUnit;
/**
* @var bool
*/
private $bIsColorComponent;
/**
* @param float|int|string $fSize
* @param string|null $sUnit
* @param bool $bIsColorComponent
* @param int $iLineNo
*/
public function __construct($fSize, $sUnit = null, $bIsColorComponent = \false, $iLineNo = 0)
{
parent::__construct($iLineNo);
$this->fSize = (float) $fSize;
$this->sUnit = $sUnit;
$this->bIsColorComponent = $bIsColorComponent;
}
/**
* @param bool $bIsColorComponent
*
* @return Size
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState, $bIsColorComponent = \false)
{
$sSize = '';
if ($oParserState->comes('-')) {
$sSize .= $oParserState->consume('-');
}
while (is_numeric($oParserState->peek()) || $oParserState->comes('.') || $oParserState->comes('e', \true)) {
if ($oParserState->comes('.')) {
$sSize .= $oParserState->consume('.');
} elseif ($oParserState->comes('e', \true)) {
$sLookahead = $oParserState->peek(1, 1);
if (is_numeric($sLookahead) || $sLookahead === '+' || $sLookahead === '-') {
$sSize .= $oParserState->consume(2);
} else {
break;
// Reached the unit part of the number like "em" or "ex"
}
} else {
$sSize .= $oParserState->consume(1);
}
}
$sUnit = null;
$aSizeUnits = self::getSizeUnits();
foreach ($aSizeUnits as $iLength => &$aValues) {
$sKey = strtolower($oParserState->peek($iLength));
if (array_key_exists($sKey, $aValues)) {
if (($sUnit = $aValues[$sKey]) !== null) {
$oParserState->consume($iLength);
break;
}
}
}
return new Size((float) $sSize, $sUnit, $bIsColorComponent, $oParserState->currentLine());
}
/**
* @return array<int, array<string, string>>
*/
private static function getSizeUnits()
{
if (!is_array(self::$SIZE_UNITS)) {
self::$SIZE_UNITS = [];
foreach (array_merge(self::ABSOLUTE_SIZE_UNITS, self::RELATIVE_SIZE_UNITS, self::NON_SIZE_UNITS) as $val) {
$iSize = strlen($val);
if (!isset(self::$SIZE_UNITS[$iSize])) {
self::$SIZE_UNITS[$iSize] = [];
}
self::$SIZE_UNITS[$iSize][strtolower($val)] = $val;
}
krsort(self::$SIZE_UNITS, \SORT_NUMERIC);
}
return self::$SIZE_UNITS;
}
/**
* @param string $sUnit
*
* @return void
*/
public function setUnit($sUnit)
{
$this->sUnit = $sUnit;
}
/**
* @return string|null
*/
public function getUnit()
{
return $this->sUnit;
}
/**
* @param float|int|string $fSize
*/
public function setSize($fSize)
{
$this->fSize = (float) $fSize;
}
/**
* @return float
*/
public function getSize()
{
return $this->fSize;
}
/**
* @return bool
*/
public function isColorComponent()
{
return $this->bIsColorComponent;
}
/**
* Returns whether the number stored in this Size really represents a size (as in a length of something on screen).
*
* @return false if the unit an angle, a duration, a frequency or the number is a component in a Color object.
*/
public function isSize()
{
if (in_array($this->sUnit, self::NON_SIZE_UNITS, \true)) {
return \false;
}
return !$this->isColorComponent();
}
/**
* @return bool
*/
public function isRelative()
{
if (in_array($this->sUnit, self::RELATIVE_SIZE_UNITS, \true)) {
return \true;
}
if ($this->sUnit === null && $this->fSize != 0) {
return \true;
}
return \false;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
$l = localeconv();
$sPoint = preg_quote($l['decimal_point'], '/');
$sSize = preg_match("/[\\d\\.]+e[+-]?\\d+/i", (string) $this->fSize) ? preg_replace("/{$sPoint}?0+\$/", "", sprintf("%f", $this->fSize)) : (string) $this->fSize;
return preg_replace(["/{$sPoint}/", "/^(-?)0\\./"], ['.', '$1.'], $sSize) . ($this->sUnit === null ? '' : $this->sUnit);
}
}
@@ -0,0 +1,94 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
/**
* This class represents URLs in CSS. `URL`s always output in `URL("")` notation.
*/
class URL extends PrimitiveValue
{
/**
* @var CSSString
*/
private $oURL;
/**
* @param int $iLineNo
*/
public function __construct(CSSString $oURL, $iLineNo = 0)
{
parent::__construct($iLineNo);
$this->oURL = $oURL;
}
/**
* @return URL
*
* @throws SourceException
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parse(ParserState $oParserState)
{
$oAnchor = $oParserState->anchor();
$sIdentifier = '';
for ($i = 0; $i < 3; $i++) {
$sChar = $oParserState->parseCharacter(\true);
if ($sChar === null) {
break;
}
$sIdentifier .= $sChar;
}
$bUseUrl = $oParserState->streql($sIdentifier, 'url');
if ($bUseUrl) {
$oParserState->consumeWhiteSpace();
$oParserState->consume('(');
} else {
$oAnchor->backtrack();
}
$oParserState->consumeWhiteSpace();
$oResult = new URL(CSSString::parse($oParserState), $oParserState->currentLine());
if ($bUseUrl) {
$oParserState->consumeWhiteSpace();
$oParserState->consume(')');
}
return $oResult;
}
/**
* @return void
*/
public function setURL(CSSString $oURL)
{
$this->oURL = $oURL;
}
/**
* @return CSSString
*/
public function getURL()
{
return $this->oURL;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return "url({$this->oURL->render($oOutputFormat)})";
}
}
@@ -0,0 +1,203 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\Parsing\ParserState;
use JooosiFonDeps\Sabberworm\CSS\Parsing\SourceException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedEOFException;
use JooosiFonDeps\Sabberworm\CSS\Parsing\UnexpectedTokenException;
use JooosiFonDeps\Sabberworm\CSS\Renderable;
/**
* Abstract base class for specific classes of CSS values: `Size`, `Color`, `CSSString` and `URL`, and another
* abstract subclass `ValueList`.
*/
abstract class Value implements Renderable
{
/**
* @var int
*
* @internal since 8.8.0
*/
protected $iLineNo;
/**
* @param int $iLineNo
*/
public function __construct($iLineNo = 0)
{
$this->iLineNo = $iLineNo;
}
/**
* @param array<array-key, string> $aListDelimiters
*
* @return RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string
*
* @throws UnexpectedTokenException
* @throws UnexpectedEOFException
*
* @internal since V8.8.0
*/
public static function parseValue(ParserState $oParserState, array $aListDelimiters = [])
{
/** @var array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aStack */
$aStack = [];
$oParserState->consumeWhiteSpace();
//Build a list of delimiters and parsed values
while (!($oParserState->comes('}') || $oParserState->comes(';') || $oParserState->comes('!') || $oParserState->comes(')') || $oParserState->comes('\\') || $oParserState->isEnd())) {
if (count($aStack) > 0) {
$bFoundDelimiter = \false;
foreach ($aListDelimiters as $sDelimiter) {
if ($oParserState->comes($sDelimiter)) {
array_push($aStack, $oParserState->consume($sDelimiter));
$oParserState->consumeWhiteSpace();
$bFoundDelimiter = \true;
break;
}
}
if (!$bFoundDelimiter) {
//Whitespace was the list delimiter
array_push($aStack, ' ');
}
}
array_push($aStack, self::parsePrimitiveValue($oParserState));
$oParserState->consumeWhiteSpace();
}
// Convert the list to list objects
foreach ($aListDelimiters as $sDelimiter) {
$iStackLength = count($aStack);
if ($iStackLength === 1) {
return $aStack[0];
}
$aNewStack = [];
for ($iStartPosition = 0; $iStartPosition < $iStackLength; ++$iStartPosition) {
if ($iStartPosition === $iStackLength - 1 || $sDelimiter !== $aStack[$iStartPosition + 1]) {
$aNewStack[] = $aStack[$iStartPosition];
continue;
}
$iLength = 2;
//Number of elements to be joined
for ($i = $iStartPosition + 3; $i < $iStackLength; $i += 2, ++$iLength) {
if ($sDelimiter !== $aStack[$i]) {
break;
}
}
$oList = new RuleValueList($sDelimiter, $oParserState->currentLine());
for ($i = $iStartPosition; $i - $iStartPosition < $iLength * 2; $i += 2) {
$oList->addListComponent($aStack[$i]);
}
$aNewStack[] = $oList;
$iStartPosition += $iLength * 2 - 2;
}
$aStack = $aNewStack;
}
if (!isset($aStack[0])) {
throw new UnexpectedTokenException(" {$oParserState->peek()} ", $oParserState->peek(1, -1) . $oParserState->peek(2), 'literal', $oParserState->currentLine());
}
return $aStack[0];
}
/**
* @param bool $bIgnoreCase
*
* @return CSSFunction|string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*
* @internal since V8.8.0
*/
public static function parseIdentifierOrFunction(ParserState $oParserState, $bIgnoreCase = \false)
{
$oAnchor = $oParserState->anchor();
$mResult = $oParserState->parseIdentifier($bIgnoreCase);
if ($oParserState->comes('(')) {
$oAnchor->backtrack();
if ($oParserState->streql('url', $mResult)) {
$mResult = URL::parse($oParserState);
} elseif ($oParserState->streql('calc', $mResult) || $oParserState->streql('-webkit-calc', $mResult) || $oParserState->streql('-moz-calc', $mResult)) {
$mResult = CalcFunction::parse($oParserState);
} else {
$mResult = CSSFunction::parse($oParserState, $bIgnoreCase);
}
}
return $mResult;
}
/**
* @return CSSFunction|CSSString|LineName|Size|URL|string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
* @throws SourceException
*
* @internal since V8.8.0
*/
public static function parsePrimitiveValue(ParserState $oParserState)
{
$oValue = null;
$oParserState->consumeWhiteSpace();
if (is_numeric($oParserState->peek()) || $oParserState->comes('-.') && is_numeric($oParserState->peek(1, 2)) || ($oParserState->comes('-') || $oParserState->comes('.')) && is_numeric($oParserState->peek(1, 1))) {
$oValue = Size::parse($oParserState);
} elseif ($oParserState->comes('#') || $oParserState->comes('rgb', \true) || $oParserState->comes('hsl', \true)) {
$oValue = Color::parse($oParserState);
} elseif ($oParserState->comes("'") || $oParserState->comes('"')) {
$oValue = CSSString::parse($oParserState);
} elseif ($oParserState->comes("progid:") && $oParserState->getSettings()->bLenientParsing) {
$oValue = self::parseMicrosoftFilter($oParserState);
} elseif ($oParserState->comes("[")) {
$oValue = LineName::parse($oParserState);
} elseif ($oParserState->comes("U+")) {
$oValue = self::parseUnicodeRangeValue($oParserState);
} else {
$sNextChar = $oParserState->peek(1);
try {
$oValue = self::parseIdentifierOrFunction($oParserState);
} catch (UnexpectedTokenException $e) {
if (\in_array($sNextChar, ['+', '-', '*', '/'], \true)) {
$oValue = $oParserState->consume(1);
} else {
throw $e;
}
}
}
$oParserState->consumeWhiteSpace();
return $oValue;
}
/**
* @return CSSFunction
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
private static function parseMicrosoftFilter(ParserState $oParserState)
{
$sFunction = $oParserState->consumeUntil('(', \false, \true);
$aArguments = Value::parseValue($oParserState, [',', '=']);
return new CSSFunction($sFunction, $aArguments, ',', $oParserState->currentLine());
}
/**
* @return string
*
* @throws UnexpectedEOFException
* @throws UnexpectedTokenException
*/
private static function parseUnicodeRangeValue(ParserState $oParserState)
{
$iCodepointMaxLength = 6;
// Code points outside BMP can use up to six digits
$sRange = "";
$oParserState->consume("U+");
do {
if ($oParserState->comes('-')) {
$iCodepointMaxLength = 13;
// Max length is 2 six digit code points + the dash(-) between them
}
$sRange .= $oParserState->consume(1);
} while (strlen($sRange) < $iCodepointMaxLength && preg_match("/[A-Fa-f0-9\\?-]/", $oParserState->peek()));
return "U+{$sRange}";
}
/**
* @return int
*/
public function getLineNo()
{
return $this->iLineNo;
}
}
@@ -0,0 +1,100 @@
<?php
namespace JooosiFonDeps\Sabberworm\CSS\Value;
use JooosiFonDeps\Sabberworm\CSS\OutputFormat;
/**
* A `ValueList` represents a lists of `Value`s, separated by some separation character
* (mostly `,`, whitespace, or `/`).
*
* There are two types of `ValueList`s: `RuleValueList` and `CSSFunction`
*/
abstract class ValueList extends Value
{
/**
* @var array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string>
*
* @internal since 8.8.0
*/
protected $aComponents;
/**
* @var string
*
* @internal since 8.8.0
*/
protected $sSeparator;
/**
* phpcs:ignore Generic.Files.LineLength
* @param array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string>|RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string $aComponents
* @param string $sSeparator
* @param int $iLineNo
*/
public function __construct($aComponents = [], $sSeparator = ',', $iLineNo = 0)
{
parent::__construct($iLineNo);
if (!is_array($aComponents)) {
$aComponents = [$aComponents];
}
$this->aComponents = $aComponents;
$this->sSeparator = $sSeparator;
}
/**
* @param RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string $mComponent
*
* @return void
*/
public function addListComponent($mComponent)
{
$this->aComponents[] = $mComponent;
}
/**
* @return array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string>
*/
public function getListComponents()
{
return $this->aComponents;
}
/**
* @param array<int, RuleValueList|CSSFunction|CSSString|LineName|Size|URL|string> $aComponents
*
* @return void
*/
public function setListComponents(array $aComponents)
{
$this->aComponents = $aComponents;
}
/**
* @return string
*/
public function getListSeparator()
{
return $this->sSeparator;
}
/**
* @param string $sSeparator
*
* @return void
*/
public function setListSeparator($sSeparator)
{
$this->sSeparator = $sSeparator;
}
/**
* @return string
*
* @deprecated in V8.8.0, will be removed in V9.0.0. Use `render` instead.
*/
public function __toString()
{
return $this->render(new OutputFormat());
}
/**
* @param OutputFormat|null $oOutputFormat
*
* @return string
*/
public function render($oOutputFormat)
{
return $oOutputFormat->implode($oOutputFormat->spaceBeforeListArgumentSeparator($this->sSeparator) . $this->sSeparator . $oOutputFormat->spaceAfterListArgumentSeparator($this->sSeparator), $this->aComponents);
}
}
@@ -0,0 +1,120 @@
<?php
// scoper-autoload.php @generated by PhpScoper
$loader = (static function () {
// Backup the autoloaded Composer files
$existingComposerAutoloadFiles = isset($GLOBALS['__composer_autoload_files']) ? $GLOBALS['__composer_autoload_files'] : [];
$GLOBALS['__composer_autoload_files'] = $GLOBALS['__composer_autoload_files_jooosi_fon_deps'] ?? [];
$loader = require_once __DIR__.'/autoload.php';
// Ensure InstalledVersions is available
$installedVersionsPath = __DIR__.'/composer/InstalledVersions.php';
if (file_exists($installedVersionsPath)) require_once $installedVersionsPath;
$GLOBALS['__composer_autoload_files_jooosi_fon_deps'] = $GLOBALS['__composer_autoload_files'];
// Restore the backup and ensure the excluded files are properly marked as loaded
$GLOBALS['__composer_autoload_files'] = \array_merge(
$existingComposerAutoloadFiles,
\array_fill_keys(['320cde22f66dd4f5d3fd621d3e88b98f', '9eaa6b0f3f04e58e17ae5ecb754ea313', '8825ede83f2f289127722d4e842cf7e8', 'acbe0d033c55cd0a032b415e08d14f4c', 'e69f7f6ee287b969198c3c9d6777bd38', '36dfd6ed9dd74e8062aa61f09caf8554', '0e6d7bf4a5811bfa5cf40c5ccd6fae6a', '5928a00fa978807cf85d90ec3f4b0147', 'a4a119a56e50fbb293281d9a48007e0e', '54b9ab13bc86d8251a04a939888e357e', '18e965175c6bcd96deba6bc791a44373', '7bdb062931f6e7102434c3ad28423eb6', '7edcabe1b67fbb38f4972a722bbbb429', '51421aa3e5e8003b70a289762d146a2a', 'f49032536fdd06afd9df7191c3f21453'], true)
);
return $loader;
})();
// Class aliases. For more information see:
// https://github.com/humbug/php-scoper/blob/master/docs/further-reading.md#class-aliases
if (!function_exists('humbug_phpscoper_expose_class')) {
function humbug_phpscoper_expose_class($exposed, $prefixed) {
if (!class_exists($exposed, false) && !interface_exists($exposed, false) && !trait_exists($exposed, false)) {
spl_autoload_call($prefixed);
}
}
}
humbug_phpscoper_expose_class('JOOOSI_FON', 'JooosiFonDeps\JOOOSI_FON');
humbug_phpscoper_expose_class('Normalizer', 'JooosiFonDeps\Normalizer');
humbug_phpscoper_expose_class('Attribute', 'JooosiFonDeps\Attribute');
humbug_phpscoper_expose_class('PhpToken', 'JooosiFonDeps\PhpToken');
humbug_phpscoper_expose_class('Stringable', 'JooosiFonDeps\Stringable');
humbug_phpscoper_expose_class('UnhandledMatchError', 'JooosiFonDeps\UnhandledMatchError');
humbug_phpscoper_expose_class('ValueError', 'JooosiFonDeps\ValueError');
// Function aliases. For more information see:
// https://github.com/humbug/php-scoper/blob/master/docs/further-reading.md#function-aliases
if (!function_exists('ctype_alnum')) { function ctype_alnum() { return \JooosiFonDeps\ctype_alnum(...func_get_args()); } }
if (!function_exists('ctype_alpha')) { function ctype_alpha() { return \JooosiFonDeps\ctype_alpha(...func_get_args()); } }
if (!function_exists('ctype_cntrl')) { function ctype_cntrl() { return \JooosiFonDeps\ctype_cntrl(...func_get_args()); } }
if (!function_exists('ctype_digit')) { function ctype_digit() { return \JooosiFonDeps\ctype_digit(...func_get_args()); } }
if (!function_exists('ctype_graph')) { function ctype_graph() { return \JooosiFonDeps\ctype_graph(...func_get_args()); } }
if (!function_exists('ctype_lower')) { function ctype_lower() { return \JooosiFonDeps\ctype_lower(...func_get_args()); } }
if (!function_exists('ctype_print')) { function ctype_print() { return \JooosiFonDeps\ctype_print(...func_get_args()); } }
if (!function_exists('ctype_punct')) { function ctype_punct() { return \JooosiFonDeps\ctype_punct(...func_get_args()); } }
if (!function_exists('ctype_space')) { function ctype_space() { return \JooosiFonDeps\ctype_space(...func_get_args()); } }
if (!function_exists('ctype_upper')) { function ctype_upper() { return \JooosiFonDeps\ctype_upper(...func_get_args()); } }
if (!function_exists('ctype_xdigit')) { function ctype_xdigit() { return \JooosiFonDeps\ctype_xdigit(...func_get_args()); } }
if (!function_exists('fdiv')) { function fdiv() { return \JooosiFonDeps\fdiv(...func_get_args()); } }
if (!function_exists('get_debug_type')) { function get_debug_type() { return \JooosiFonDeps\get_debug_type(...func_get_args()); } }
if (!function_exists('get_resource_id')) { function get_resource_id() { return \JooosiFonDeps\get_resource_id(...func_get_args()); } }
if (!function_exists('grapheme_extract')) { function grapheme_extract() { return \JooosiFonDeps\grapheme_extract(...func_get_args()); } }
if (!function_exists('grapheme_stripos')) { function grapheme_stripos() { return \JooosiFonDeps\grapheme_stripos(...func_get_args()); } }
if (!function_exists('grapheme_stristr')) { function grapheme_stristr() { return \JooosiFonDeps\grapheme_stristr(...func_get_args()); } }
if (!function_exists('grapheme_strlen')) { function grapheme_strlen() { return \JooosiFonDeps\grapheme_strlen(...func_get_args()); } }
if (!function_exists('grapheme_strpos')) { function grapheme_strpos() { return \JooosiFonDeps\grapheme_strpos(...func_get_args()); } }
if (!function_exists('grapheme_strripos')) { function grapheme_strripos() { return \JooosiFonDeps\grapheme_strripos(...func_get_args()); } }
if (!function_exists('grapheme_strrpos')) { function grapheme_strrpos() { return \JooosiFonDeps\grapheme_strrpos(...func_get_args()); } }
if (!function_exists('grapheme_strstr')) { function grapheme_strstr() { return \JooosiFonDeps\grapheme_strstr(...func_get_args()); } }
if (!function_exists('grapheme_substr')) { function grapheme_substr() { return \JooosiFonDeps\grapheme_substr(...func_get_args()); } }
if (!function_exists('mb_check_encoding')) { function mb_check_encoding() { return \JooosiFonDeps\mb_check_encoding(...func_get_args()); } }
if (!function_exists('mb_chr')) { function mb_chr() { return \JooosiFonDeps\mb_chr(...func_get_args()); } }
if (!function_exists('mb_convert_case')) { function mb_convert_case() { return \JooosiFonDeps\mb_convert_case(...func_get_args()); } }
if (!function_exists('mb_convert_encoding')) { function mb_convert_encoding() { return \JooosiFonDeps\mb_convert_encoding(...func_get_args()); } }
if (!function_exists('mb_convert_variables')) { function mb_convert_variables() { return \JooosiFonDeps\mb_convert_variables(...func_get_args()); } }
if (!function_exists('mb_decode_mimeheader')) { function mb_decode_mimeheader() { return \JooosiFonDeps\mb_decode_mimeheader(...func_get_args()); } }
if (!function_exists('mb_decode_numericentity')) { function mb_decode_numericentity() { return \JooosiFonDeps\mb_decode_numericentity(...func_get_args()); } }
if (!function_exists('mb_detect_encoding')) { function mb_detect_encoding() { return \JooosiFonDeps\mb_detect_encoding(...func_get_args()); } }
if (!function_exists('mb_detect_order')) { function mb_detect_order() { return \JooosiFonDeps\mb_detect_order(...func_get_args()); } }
if (!function_exists('mb_encode_mimeheader')) { function mb_encode_mimeheader() { return \JooosiFonDeps\mb_encode_mimeheader(...func_get_args()); } }
if (!function_exists('mb_encode_numericentity')) { function mb_encode_numericentity() { return \JooosiFonDeps\mb_encode_numericentity(...func_get_args()); } }
if (!function_exists('mb_encoding_aliases')) { function mb_encoding_aliases() { return \JooosiFonDeps\mb_encoding_aliases(...func_get_args()); } }
if (!function_exists('mb_get_info')) { function mb_get_info() { return \JooosiFonDeps\mb_get_info(...func_get_args()); } }
if (!function_exists('mb_http_input')) { function mb_http_input() { return \JooosiFonDeps\mb_http_input(...func_get_args()); } }
if (!function_exists('mb_http_output')) { function mb_http_output() { return \JooosiFonDeps\mb_http_output(...func_get_args()); } }
if (!function_exists('mb_internal_encoding')) { function mb_internal_encoding() { return \JooosiFonDeps\mb_internal_encoding(...func_get_args()); } }
if (!function_exists('mb_language')) { function mb_language() { return \JooosiFonDeps\mb_language(...func_get_args()); } }
if (!function_exists('mb_lcfirst')) { function mb_lcfirst() { return \JooosiFonDeps\mb_lcfirst(...func_get_args()); } }
if (!function_exists('mb_list_encodings')) { function mb_list_encodings() { return \JooosiFonDeps\mb_list_encodings(...func_get_args()); } }
if (!function_exists('mb_ltrim')) { function mb_ltrim() { return \JooosiFonDeps\mb_ltrim(...func_get_args()); } }
if (!function_exists('mb_ord')) { function mb_ord() { return \JooosiFonDeps\mb_ord(...func_get_args()); } }
if (!function_exists('mb_output_handler')) { function mb_output_handler() { return \JooosiFonDeps\mb_output_handler(...func_get_args()); } }
if (!function_exists('mb_parse_str')) { function mb_parse_str() { return \JooosiFonDeps\mb_parse_str(...func_get_args()); } }
if (!function_exists('mb_rtrim')) { function mb_rtrim() { return \JooosiFonDeps\mb_rtrim(...func_get_args()); } }
if (!function_exists('mb_scrub')) { function mb_scrub() { return \JooosiFonDeps\mb_scrub(...func_get_args()); } }
if (!function_exists('mb_str_pad')) { function mb_str_pad() { return \JooosiFonDeps\mb_str_pad(...func_get_args()); } }
if (!function_exists('mb_str_split')) { function mb_str_split() { return \JooosiFonDeps\mb_str_split(...func_get_args()); } }
if (!function_exists('mb_stripos')) { function mb_stripos() { return \JooosiFonDeps\mb_stripos(...func_get_args()); } }
if (!function_exists('mb_stristr')) { function mb_stristr() { return \JooosiFonDeps\mb_stristr(...func_get_args()); } }
if (!function_exists('mb_strlen')) { function mb_strlen() { return \JooosiFonDeps\mb_strlen(...func_get_args()); } }
if (!function_exists('mb_strpos')) { function mb_strpos() { return \JooosiFonDeps\mb_strpos(...func_get_args()); } }
if (!function_exists('mb_strrchr')) { function mb_strrchr() { return \JooosiFonDeps\mb_strrchr(...func_get_args()); } }
if (!function_exists('mb_strrichr')) { function mb_strrichr() { return \JooosiFonDeps\mb_strrichr(...func_get_args()); } }
if (!function_exists('mb_strripos')) { function mb_strripos() { return \JooosiFonDeps\mb_strripos(...func_get_args()); } }
if (!function_exists('mb_strrpos')) { function mb_strrpos() { return \JooosiFonDeps\mb_strrpos(...func_get_args()); } }
if (!function_exists('mb_strstr')) { function mb_strstr() { return \JooosiFonDeps\mb_strstr(...func_get_args()); } }
if (!function_exists('mb_strtolower')) { function mb_strtolower() { return \JooosiFonDeps\mb_strtolower(...func_get_args()); } }
if (!function_exists('mb_strtoupper')) { function mb_strtoupper() { return \JooosiFonDeps\mb_strtoupper(...func_get_args()); } }
if (!function_exists('mb_strwidth')) { function mb_strwidth() { return \JooosiFonDeps\mb_strwidth(...func_get_args()); } }
if (!function_exists('mb_substitute_character')) { function mb_substitute_character() { return \JooosiFonDeps\mb_substitute_character(...func_get_args()); } }
if (!function_exists('mb_substr')) { function mb_substr() { return \JooosiFonDeps\mb_substr(...func_get_args()); } }
if (!function_exists('mb_substr_count')) { function mb_substr_count() { return \JooosiFonDeps\mb_substr_count(...func_get_args()); } }
if (!function_exists('mb_trim')) { function mb_trim() { return \JooosiFonDeps\mb_trim(...func_get_args()); } }
if (!function_exists('mb_ucfirst')) { function mb_ucfirst() { return \JooosiFonDeps\mb_ucfirst(...func_get_args()); } }
if (!function_exists('normalizer_is_normalized')) { function normalizer_is_normalized() { return \JooosiFonDeps\normalizer_is_normalized(...func_get_args()); } }
if (!function_exists('normalizer_normalize')) { function normalizer_normalize() { return \JooosiFonDeps\normalizer_normalize(...func_get_args()); } }
if (!function_exists('preg_last_error_msg')) { function preg_last_error_msg() { return \JooosiFonDeps\preg_last_error_msg(...func_get_args()); } }
if (!function_exists('str_contains')) { function str_contains() { return \JooosiFonDeps\str_contains(...func_get_args()); } }
if (!function_exists('str_ends_with')) { function str_ends_with() { return \JooosiFonDeps\str_ends_with(...func_get_args()); } }
if (!function_exists('str_starts_with')) { function str_starts_with() { return \JooosiFonDeps\str_starts_with(...func_get_args()); } }
return $loader;
@@ -0,0 +1,5 @@
CHANGELOG
=========
The changelog is maintained for all Symfony contracts at the following URL:
https://github.com/symfony/contracts/blob/main/CHANGELOG.md
@@ -0,0 +1,19 @@
Copyright (c) 2020-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,26 @@
Symfony Deprecation Contracts
=============================
A generic function and convention to trigger deprecation notices.
This package provides a single global function named `trigger_deprecation()` that triggers silenced deprecation notices.
By using a custom PHP error handler such as the one provided by the Symfony ErrorHandler component,
the triggered deprecations can be caught and logged for later discovery, both on dev and prod environments.
The function requires at least 3 arguments:
- the name of the Composer package that is triggering the deprecation
- the version of the package that introduced the deprecation
- the message of the deprecation
- more arguments can be provided: they will be inserted in the message using `printf()` formatting
Example:
```php
trigger_deprecation('symfony/blockchain', '8.9', 'Using "%s" is deprecated, use "%s" instead.', 'bitcoin', 'fabcoin');
```
This will generate the following message:
`Since symfony/blockchain 8.9: Using "bitcoin" is deprecated, use "fabcoin" instead.`
While not necessarily recommended, the deprecation notices can be completely ignored by declaring an empty
`function trigger_deprecation() {}` in your application.
@@ -0,0 +1,35 @@
{
"name": "symfony\/deprecation-contracts",
"type": "library",
"description": "A generic function and convention to trigger deprecation notices",
"homepage": "https:\/\/symfony.com",
"license": "MIT",
"authors": [
{
"name": "Nicolas Grekas",
"email": "p@tchwork.com"
},
{
"name": "Symfony Community",
"homepage": "https:\/\/symfony.com\/contributors"
}
],
"require": {
"php": ">=7.1"
},
"autoload": {
"files": [
"function.php"
]
},
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-main": "2.5-dev"
},
"thanks": {
"name": "symfony\/contracts",
"url": "https:\/\/github.com\/symfony\/contracts"
}
}
}
@@ -0,0 +1,28 @@
<?php
namespace JooosiFonDeps;
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (!\function_exists('JooosiFonDeps\trigger_deprecation')) {
/**
* Triggers a silenced deprecation notice.
*
* @param string $package The name of the Composer package that is triggering the deprecation
* @param string $version The version of the package that introduced the deprecation
* @param string $message The message of the deprecation
* @param mixed ...$args Values to insert in the message using printf() formatting
*
* @author Nicolas Grekas <p@tchwork.com>
*/
function trigger_deprecation(string $package, string $version, string $message, ...$args): void
{
@\trigger_error(($package || $version ? "Since {$package} {$version}: " : '') . ($args ? \vsprintf($message, $args) : $message), \E_USER_DEPRECATED);
}
}
@@ -0,0 +1,87 @@
CHANGELOG
=========
5.4.0
-----
* Deprecate `Comparator::setTarget()` and `Comparator::setOperator()`
* Add a constructor to `Comparator` that allows setting target and operator
* Finder's iterator has now `Symfony\Component\Finder\SplFileInfo` inner type specified
* Add recursive .gitignore files support
5.0.0
-----
* added `$useNaturalSort` argument to `Finder::sortByName()`
4.3.0
-----
* added Finder::ignoreVCSIgnored() to ignore files based on rules listed in .gitignore
4.2.0
-----
* added $useNaturalSort option to Finder::sortByName() method
* the `Finder::sortByName()` method will have a new `$useNaturalSort`
argument in version 5.0, not defining it is deprecated
* added `Finder::reverseSorting()` to reverse the sorting
4.0.0
-----
* removed `ExceptionInterface`
* removed `Symfony\Component\Finder\Iterator\FilterIterator`
3.4.0
-----
* deprecated `Symfony\Component\Finder\Iterator\FilterIterator`
* added Finder::hasResults() method to check if any results were found
3.3.0
-----
* added double-star matching to Glob::toRegex()
3.0.0
-----
* removed deprecated classes
2.8.0
-----
* deprecated adapters and related classes
2.5.0
-----
* added support for GLOB_BRACE in the paths passed to Finder::in()
2.3.0
-----
* added a way to ignore unreadable directories (via Finder::ignoreUnreadableDirs())
* unified the way subfolders that are not executable are handled by always throwing an AccessDeniedException exception
2.2.0
-----
* added Finder::path() and Finder::notPath() methods
* added finder adapters to improve performance on specific platforms
* added support for wildcard characters (glob patterns) in the paths passed
to Finder::in()
2.1.0
-----
* added Finder::sortByAccessedTime(), Finder::sortByChangedTime(), and
Finder::sortByModifiedTime()
* added Countable to Finder
* added support for an array of directories as an argument to
Finder::exclude()
* added searching based on the file content via Finder::contains() and
Finder::notContains()
* added support for the != operator in the Comparator
* [BC BREAK] filter expressions (used for file name and content) are no more
considered as regexps but glob patterns when they are enclosed in '*' or '?'
@@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Comparator;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class Comparator
{
private $target;
private $operator = '==';
public function __construct(?string $target = null, string $operator = '==')
{
if (null === $target) {
trigger_deprecation('symfony/finder', '5.4', 'Constructing a "%s" without setting "$target" is deprecated.', __CLASS__);
}
$this->target = $target;
$this->doSetOperator($operator);
}
/**
* Gets the target value.
*
* @return string
*/
public function getTarget()
{
if (null === $this->target) {
trigger_deprecation('symfony/finder', '5.4', 'Calling "%s" without initializing the target is deprecated.', __METHOD__);
}
return $this->target;
}
/**
* @deprecated set the target via the constructor instead
*/
public function setTarget(string $target)
{
trigger_deprecation('symfony/finder', '5.4', '"%s" is deprecated. Set the target via the constructor instead.', __METHOD__);
$this->target = $target;
}
/**
* Gets the comparison operator.
*
* @return string
*/
public function getOperator()
{
return $this->operator;
}
/**
* Sets the comparison operator.
*
* @throws \InvalidArgumentException
*
* @deprecated set the operator via the constructor instead
*/
public function setOperator(string $operator)
{
trigger_deprecation('symfony/finder', '5.4', '"%s" is deprecated. Set the operator via the constructor instead.', __METHOD__);
$this->doSetOperator('' === $operator ? '==' : $operator);
}
/**
* Tests against the target.
*
* @param mixed $test A test value
*
* @return bool
*/
public function test($test)
{
if (null === $this->target) {
trigger_deprecation('symfony/finder', '5.4', 'Calling "%s" without initializing the target is deprecated.', __METHOD__);
}
switch ($this->operator) {
case '>':
return $test > $this->target;
case '>=':
return $test >= $this->target;
case '<':
return $test < $this->target;
case '<=':
return $test <= $this->target;
case '!=':
return $test != $this->target;
}
return $test == $this->target;
}
private function doSetOperator(string $operator): void
{
if (!\in_array($operator, ['>', '<', '>=', '<=', '==', '!='])) {
throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator));
}
$this->operator = $operator;
}
}
@@ -0,0 +1,45 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Comparator;
/**
* DateCompare compiles date comparisons.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DateComparator extends Comparator
{
/**
* @param string $test A comparison string
*
* @throws \InvalidArgumentException If the test is not understood
*/
public function __construct(string $test)
{
if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test));
}
try {
$date = new \DateTime($matches[2]);
$target = $date->format('U');
} catch (\Exception $e) {
throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
}
$operator = $matches[1] ?? '==';
if ('since' === $operator || 'after' === $operator) {
$operator = '>';
}
if ('until' === $operator || 'before' === $operator) {
$operator = '<';
}
parent::__construct($target, $operator);
}
}
@@ -0,0 +1,75 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Comparator;
/**
* NumberComparator compiles a simple comparison to an anonymous
* subroutine, which you can call with a value to be tested again.
*
* Now this would be very pointless, if NumberCompare didn't understand
* magnitudes.
*
* The target value may use magnitudes of kilobytes (k, ki),
* megabytes (m, mi), or gigabytes (g, gi). Those suffixed
* with an i use the appropriate 2**n version in accordance with the
* IEC standard: http://physics.nist.gov/cuu/Units/binary.html
*
* Based on the Perl Number::Compare module.
*
* @author Fabien Potencier <fabien@symfony.com> PHP port
* @author Richard Clamp <richardc@unixbeard.net> Perl version
* @copyright 2004-2005 Fabien Potencier <fabien@symfony.com>
* @copyright 2002 Richard Clamp <richardc@unixbeard.net>
*
* @see http://physics.nist.gov/cuu/Units/binary.html
*/
class NumberComparator extends Comparator
{
/**
* @param string|null $test A comparison string or null
*
* @throws \InvalidArgumentException If the test is not understood
*/
public function __construct(?string $test)
{
if (null === $test || !preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test ?? 'null'));
}
$target = $matches[2];
if (!is_numeric($target)) {
throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target));
}
if (isset($matches[3])) {
// magnitude
switch (strtolower($matches[3])) {
case 'k':
$target *= 1000;
break;
case 'ki':
$target *= 1024;
break;
case 'm':
$target *= 1000000;
break;
case 'mi':
$target *= 1024 * 1024;
break;
case 'g':
$target *= 1000000000;
break;
case 'gi':
$target *= 1024 * 1024 * 1024;
break;
}
}
parent::__construct($target, $matches[1] ?: '==');
}
}
@@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Exception;
/**
* @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
*/
class AccessDeniedException extends \UnexpectedValueException
{
}
@@ -0,0 +1,18 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Exception;
/**
* @author Andreas Erhard <andreas.erhard@i-med.ac.at>
*/
class DirectoryNotFoundException extends \InvalidArgumentException
{
}
@@ -0,0 +1,707 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder;
use JooosiFonDeps\Symfony\Component\Finder\Comparator\DateComparator;
use JooosiFonDeps\Symfony\Component\Finder\Comparator\NumberComparator;
use JooosiFonDeps\Symfony\Component\Finder\Exception\DirectoryNotFoundException;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\CustomFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\FilenameFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\LazyIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
use JooosiFonDeps\Symfony\Component\Finder\Iterator\SortableIterator;
/**
* Finder allows to build rules to find files and directories.
*
* It is a thin wrapper around several specialized iterator classes.
*
* All rules may be invoked several times.
*
* All methods return the current Finder object to allow chaining:
*
* $finder = Finder::create()->files()->name('*.php')->in(__DIR__);
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @implements \IteratorAggregate<string, SplFileInfo>
*/
class Finder implements \IteratorAggregate, \Countable
{
public const IGNORE_VCS_FILES = 1;
public const IGNORE_DOT_FILES = 2;
public const IGNORE_VCS_IGNORED_FILES = 4;
private $mode = 0;
private $names = [];
private $notNames = [];
private $exclude = [];
private $filters = [];
private $depths = [];
private $sizes = [];
private $followLinks = \false;
private $reverseSorting = \false;
private $sort = \false;
private $ignore = 0;
private $dirs = [];
private $dates = [];
private $iterators = [];
private $contains = [];
private $notContains = [];
private $paths = [];
private $notPaths = [];
private $ignoreUnreadableDirs = \false;
private static $vcsPatterns = ['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg'];
public function __construct()
{
$this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
}
/**
* Creates a new Finder.
*
* @return static
*/
public static function create()
{
return new static();
}
/**
* Restricts the matching to directories only.
*
* @return $this
*/
public function directories()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
return $this;
}
/**
* Restricts the matching to files only.
*
* @return $this
*/
public function files()
{
$this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
return $this;
}
/**
* Adds tests for the directory depth.
*
* Usage:
*
* $finder->depth('> 1') // the Finder will start matching at level 1.
* $finder->depth('< 3') // the Finder will descend at most 3 levels of directories below the starting point.
* $finder->depth(['>= 1', '< 3'])
*
* @param string|int|string[]|int[] $levels The depth level expression or an array of depth levels
*
* @return $this
*
* @see DepthRangeFilterIterator
* @see NumberComparator
*/
public function depth($levels)
{
foreach ((array) $levels as $level) {
$this->depths[] = new Comparator\NumberComparator($level);
}
return $this;
}
/**
* Adds tests for file dates (last modified).
*
* The date must be something that strtotime() is able to parse:
*
* $finder->date('since yesterday');
* $finder->date('until 2 days ago');
* $finder->date('> now - 2 hours');
* $finder->date('>= 2005-10-15');
* $finder->date(['>= 2005-10-15', '<= 2006-05-27']);
*
* @param string|string[] $dates A date range string or an array of date ranges
*
* @return $this
*
* @see strtotime
* @see DateRangeFilterIterator
* @see DateComparator
*/
public function date($dates)
{
foreach ((array) $dates as $date) {
$this->dates[] = new Comparator\DateComparator($date);
}
return $this;
}
/**
* Adds rules that files must match.
*
* You can use patterns (delimited with / sign), globs or simple strings.
*
* $finder->name('/\.php$/')
* $finder->name('*.php') // same as above, without dot files
* $finder->name('test.php')
* $finder->name(['test.py', 'test.php'])
*
* @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
*
* @return $this
*
* @see FilenameFilterIterator
*/
public function name($patterns)
{
$this->names = array_merge($this->names, (array) $patterns);
return $this;
}
/**
* Adds rules that files must not match.
*
* @param string|string[] $patterns A pattern (a regexp, a glob, or a string) or an array of patterns
*
* @return $this
*
* @see FilenameFilterIterator
*/
public function notName($patterns)
{
$this->notNames = array_merge($this->notNames, (array) $patterns);
return $this;
}
/**
* Adds tests that file contents must match.
*
* Strings or PCRE patterns can be used:
*
* $finder->contains('Lorem ipsum')
* $finder->contains('/Lorem ipsum/i')
* $finder->contains(['dolor', '/ipsum/i'])
*
* @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
*
* @return $this
*
* @see FilecontentFilterIterator
*/
public function contains($patterns)
{
$this->contains = array_merge($this->contains, (array) $patterns);
return $this;
}
/**
* Adds tests that file contents must not match.
*
* Strings or PCRE patterns can be used:
*
* $finder->notContains('Lorem ipsum')
* $finder->notContains('/Lorem ipsum/i')
* $finder->notContains(['lorem', '/dolor/i'])
*
* @param string|string[] $patterns A pattern (string or regexp) or an array of patterns
*
* @return $this
*
* @see FilecontentFilterIterator
*/
public function notContains($patterns)
{
$this->notContains = array_merge($this->notContains, (array) $patterns);
return $this;
}
/**
* Adds rules that filenames must match.
*
* You can use patterns (delimited with / sign) or simple strings.
*
* $finder->path('some/special/dir')
* $finder->path('/some\/special\/dir/') // same as above
* $finder->path(['some dir', 'another/dir'])
*
* Use only / as dirname separator.
*
* @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
*
* @return $this
*
* @see FilenameFilterIterator
*/
public function path($patterns)
{
$this->paths = array_merge($this->paths, (array) $patterns);
return $this;
}
/**
* Adds rules that filenames must not match.
*
* You can use patterns (delimited with / sign) or simple strings.
*
* $finder->notPath('some/special/dir')
* $finder->notPath('/some\/special\/dir/') // same as above
* $finder->notPath(['some/file.txt', 'another/file.log'])
*
* Use only / as dirname separator.
*
* @param string|string[] $patterns A pattern (a regexp or a string) or an array of patterns
*
* @return $this
*
* @see FilenameFilterIterator
*/
public function notPath($patterns)
{
$this->notPaths = array_merge($this->notPaths, (array) $patterns);
return $this;
}
/**
* Adds tests for file sizes.
*
* $finder->size('> 10K');
* $finder->size('<= 1Ki');
* $finder->size(4);
* $finder->size(['> 10K', '< 20K'])
*
* @param string|int|string[]|int[] $sizes A size range string or an integer or an array of size ranges
*
* @return $this
*
* @see SizeRangeFilterIterator
* @see NumberComparator
*/
public function size($sizes)
{
foreach ((array) $sizes as $size) {
$this->sizes[] = new Comparator\NumberComparator($size);
}
return $this;
}
/**
* Excludes directories.
*
* Directories passed as argument must be relative to the ones defined with the `in()` method. For example:
*
* $finder->in(__DIR__)->exclude('ruby');
*
* @param string|array $dirs A directory path or an array of directories
*
* @return $this
*
* @see ExcludeDirectoryFilterIterator
*/
public function exclude($dirs)
{
$this->exclude = array_merge($this->exclude, (array) $dirs);
return $this;
}
/**
* Excludes "hidden" directories and files (starting with a dot).
*
* This option is enabled by default.
*
* @return $this
*
* @see ExcludeDirectoryFilterIterator
*/
public function ignoreDotFiles(bool $ignoreDotFiles)
{
if ($ignoreDotFiles) {
$this->ignore |= static::IGNORE_DOT_FILES;
} else {
$this->ignore &= ~static::IGNORE_DOT_FILES;
}
return $this;
}
/**
* Forces the finder to ignore version control directories.
*
* This option is enabled by default.
*
* @return $this
*
* @see ExcludeDirectoryFilterIterator
*/
public function ignoreVCS(bool $ignoreVCS)
{
if ($ignoreVCS) {
$this->ignore |= static::IGNORE_VCS_FILES;
} else {
$this->ignore &= ~static::IGNORE_VCS_FILES;
}
return $this;
}
/**
* Forces Finder to obey .gitignore and ignore files based on rules listed there.
*
* This option is disabled by default.
*
* @return $this
*/
public function ignoreVCSIgnored(bool $ignoreVCSIgnored)
{
if ($ignoreVCSIgnored) {
$this->ignore |= static::IGNORE_VCS_IGNORED_FILES;
} else {
$this->ignore &= ~static::IGNORE_VCS_IGNORED_FILES;
}
return $this;
}
/**
* Adds VCS patterns.
*
* @see ignoreVCS()
*
* @param string|string[] $pattern VCS patterns to ignore
*/
public static function addVCSPattern($pattern)
{
foreach ((array) $pattern as $p) {
self::$vcsPatterns[] = $p;
}
self::$vcsPatterns = array_unique(self::$vcsPatterns);
}
/**
* Sorts files and directories by an anonymous function.
*
* The anonymous function receives two \SplFileInfo instances to compare.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sort(\Closure $closure)
{
$this->sort = $closure;
return $this;
}
/**
* Sorts files and directories by name.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sortByName(bool $useNaturalSort = \false)
{
$this->sort = $useNaturalSort ? Iterator\SortableIterator::SORT_BY_NAME_NATURAL : Iterator\SortableIterator::SORT_BY_NAME;
return $this;
}
/**
* Sorts files and directories by type (directories before files), then by name.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sortByType()
{
$this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
return $this;
}
/**
* Sorts files and directories by the last accessed time.
*
* This is the time that the file was last accessed, read or written to.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sortByAccessedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
return $this;
}
/**
* Reverses the sorting.
*
* @return $this
*/
public function reverseSorting()
{
$this->reverseSorting = \true;
return $this;
}
/**
* Sorts files and directories by the last inode changed time.
*
* This is the time that the inode information was last modified (permissions, owner, group or other metadata).
*
* On Windows, since inode is not available, changed time is actually the file creation time.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sortByChangedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
return $this;
}
/**
* Sorts files and directories by the last modified time.
*
* This is the last time the actual contents of the file were last modified.
*
* This can be slow as all the matching files and directories must be retrieved for comparison.
*
* @return $this
*
* @see SortableIterator
*/
public function sortByModifiedTime()
{
$this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
return $this;
}
/**
* Filters the iterator with an anonymous function.
*
* The anonymous function receives a \SplFileInfo and must return false
* to remove files.
*
* @return $this
*
* @see CustomFilterIterator
*/
public function filter(\Closure $closure)
{
$this->filters[] = $closure;
return $this;
}
/**
* Forces the following of symlinks.
*
* @return $this
*/
public function followLinks()
{
$this->followLinks = \true;
return $this;
}
/**
* Tells finder to ignore unreadable directories.
*
* By default, scanning unreadable directories content throws an AccessDeniedException.
*
* @return $this
*/
public function ignoreUnreadableDirs(bool $ignore = \true)
{
$this->ignoreUnreadableDirs = $ignore;
return $this;
}
/**
* Searches files and directories which match defined rules.
*
* @param string|string[] $dirs A directory path or an array of directories
*
* @return $this
*
* @throws DirectoryNotFoundException if one of the directories does not exist
*/
public function in($dirs)
{
$resolvedDirs = [];
foreach ((array) $dirs as $dir) {
if (is_dir($dir)) {
$resolvedDirs[] = [$this->normalizeDir($dir)];
} elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? \GLOB_BRACE : 0) | \GLOB_ONLYDIR | \GLOB_NOSORT)) {
sort($glob);
$resolvedDirs[] = array_map([$this, 'normalizeDir'], $glob);
} else {
throw new DirectoryNotFoundException(sprintf('The "%s" directory does not exist.', $dir));
}
}
$this->dirs = array_merge($this->dirs, ...$resolvedDirs);
return $this;
}
/**
* Returns an Iterator for the current Finder configuration.
*
* This method implements the IteratorAggregate interface.
*
* @return \Iterator<string, SplFileInfo>
*
* @throws \LogicException if the in() method has not been called
*/
#[\ReturnTypeWillChange]
public function getIterator()
{
if (0 === \count($this->dirs) && 0 === \count($this->iterators)) {
throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
}
if (1 === \count($this->dirs) && 0 === \count($this->iterators)) {
$iterator = $this->searchInDirectory($this->dirs[0]);
if ($this->sort || $this->reverseSorting) {
$iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator();
}
return $iterator;
}
$iterator = new \AppendIterator();
foreach ($this->dirs as $dir) {
$iterator->append(new \IteratorIterator(new LazyIterator(function () use ($dir) {
return $this->searchInDirectory($dir);
})));
}
foreach ($this->iterators as $it) {
$iterator->append($it);
}
if ($this->sort || $this->reverseSorting) {
$iterator = (new Iterator\SortableIterator($iterator, $this->sort, $this->reverseSorting))->getIterator();
}
return $iterator;
}
/**
* Appends an existing set of files/directories to the finder.
*
* The set can be another Finder, an Iterator, an IteratorAggregate, or even a plain array.
*
* @return $this
*
* @throws \InvalidArgumentException when the given argument is not iterable
*/
public function append(iterable $iterator)
{
if ($iterator instanceof \IteratorAggregate) {
$this->iterators[] = $iterator->getIterator();
} elseif ($iterator instanceof \Iterator) {
$this->iterators[] = $iterator;
} elseif (is_iterable($iterator)) {
$it = new \ArrayIterator();
foreach ($iterator as $file) {
$file = $file instanceof \SplFileInfo ? $file : new \SplFileInfo($file);
$it[$file->getPathname()] = $file;
}
$this->iterators[] = $it;
} else {
throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
}
return $this;
}
/**
* Check if any results were found.
*
* @return bool
*/
public function hasResults()
{
foreach ($this->getIterator() as $_) {
return \true;
}
return \false;
}
/**
* Counts all the results collected by the iterators.
*
* @return int
*/
#[\ReturnTypeWillChange]
public function count()
{
return iterator_count($this->getIterator());
}
private function searchInDirectory(string $dir): \Iterator
{
$exclude = $this->exclude;
$notPaths = $this->notPaths;
if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
$exclude = array_merge($exclude, self::$vcsPatterns);
}
if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
$notPaths[] = '#(^|/)\..+(/|$)#';
}
$minDepth = 0;
$maxDepth = \PHP_INT_MAX;
foreach ($this->depths as $comparator) {
switch ($comparator->getOperator()) {
case '>':
$minDepth = $comparator->getTarget() + 1;
break;
case '>=':
$minDepth = $comparator->getTarget();
break;
case '<':
$maxDepth = $comparator->getTarget() - 1;
break;
case '<=':
$maxDepth = $comparator->getTarget();
break;
default:
$minDepth = $maxDepth = $comparator->getTarget();
}
}
$flags = \RecursiveDirectoryIterator::SKIP_DOTS;
if ($this->followLinks) {
$flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
}
$iterator = new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs);
if ($exclude) {
$iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $exclude);
}
$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::SELF_FIRST);
if ($minDepth > 0 || $maxDepth < \PHP_INT_MAX) {
$iterator = new Iterator\DepthRangeFilterIterator($iterator, $minDepth, $maxDepth);
}
if ($this->mode) {
$iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
}
if ($this->names || $this->notNames) {
$iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
}
if ($this->contains || $this->notContains) {
$iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
}
if ($this->sizes) {
$iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
}
if ($this->dates) {
$iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
}
if ($this->filters) {
$iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
}
if ($this->paths || $notPaths) {
$iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $notPaths);
}
if (static::IGNORE_VCS_IGNORED_FILES === (static::IGNORE_VCS_IGNORED_FILES & $this->ignore)) {
$iterator = new Iterator\VcsIgnoredFilterIterator($iterator, $dir);
}
return $iterator;
}
/**
* Normalizes given directory names by removing trailing slashes.
*
* Excluding: (s)ftp:// or ssh2.(s)ftp:// wrapper
*/
private function normalizeDir(string $dir): string
{
if ('/' === $dir) {
return $dir;
}
$dir = rtrim($dir, '/' . \DIRECTORY_SEPARATOR);
if (preg_match('#^(ssh2\.)?s?ftp://#', $dir)) {
$dir .= '/';
}
return $dir;
}
}
@@ -0,0 +1,81 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder;
/**
* Gitignore matches against text.
*
* @author Michael Voříšek <vorismi3@fel.cvut.cz>
* @author Ahmed Abdou <mail@ahmd.io>
*/
class Gitignore
{
/**
* Returns a regexp which is the equivalent of the gitignore pattern.
*
* Format specification: https://git-scm.com/docs/gitignore#_pattern_format
*/
public static function toRegex(string $gitignoreFileContent): string
{
return self::buildRegex($gitignoreFileContent, \false);
}
public static function toRegexMatchingNegatedPatterns(string $gitignoreFileContent): string
{
return self::buildRegex($gitignoreFileContent, \true);
}
private static function buildRegex(string $gitignoreFileContent, bool $inverted): string
{
$gitignoreFileContent = preg_replace('~(?<!\\\\)#[^\n\r]*~', '', $gitignoreFileContent);
$gitignoreLines = preg_split('~\r\n?|\n~', $gitignoreFileContent);
$res = self::lineToRegex('');
foreach ($gitignoreLines as $line) {
$line = preg_replace('~(?<!\\\\)[ \t]+$~', '', $line);
if ('!' === substr($line, 0, 1)) {
$line = substr($line, 1);
$isNegative = \true;
} else {
$isNegative = \false;
}
if ('' !== $line) {
if ($isNegative xor $inverted) {
$res = '(?!' . self::lineToRegex($line) . '$)' . $res;
} else {
$res = '(?:' . $res . '|' . self::lineToRegex($line) . ')';
}
}
}
return '~^(?:' . $res . ')~s';
}
private static function lineToRegex(string $gitignoreLine): string
{
if ('' === $gitignoreLine) {
return '$f';
// always false
}
$slashPos = strpos($gitignoreLine, '/');
if (\false !== $slashPos && \strlen($gitignoreLine) - 1 !== $slashPos) {
if (0 === $slashPos) {
$gitignoreLine = substr($gitignoreLine, 1);
}
$isAbsolute = \true;
} else {
$isAbsolute = \false;
}
$regex = preg_quote(str_replace('\\', '', $gitignoreLine), '~');
$regex = preg_replace_callback('~\\\\\\[((?:\\\\!)?)([^\[\]]*)\\\\\\]~', function (array $matches): string {
return '[' . ('' !== $matches[1] ? '^' : '') . str_replace('\-', '-', $matches[2]) . ']';
}, $regex);
$regex = preg_replace('~(?:(?:\\\\\\*){2,}(/?))+~', '(?:(?:(?!//).(?<!//))+$1)?', $regex);
$regex = preg_replace('~\\\\\\*~', '[^/]*', $regex);
$regex = preg_replace('~\\\\\\?~', '[^/]', $regex);
return ($isAbsolute ? '' : '(?:[^/]+/)*') . $regex . (!str_ends_with($gitignoreLine, '/') ? '(?:$|/)' : '');
}
}
@@ -0,0 +1,102 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder;
/**
* Glob matches globbing patterns against text.
*
* if match_glob("foo.*", "foo.bar") echo "matched\n";
*
* // prints foo.bar and foo.baz
* $regex = glob_to_regex("foo.*");
* for (['foo.bar', 'foo.baz', 'foo', 'bar'] as $t)
* {
* if (/$regex/) echo "matched: $car\n";
* }
*
* Glob implements glob(3) style matching that can be used to match
* against text, rather than fetching names from a filesystem.
*
* Based on the Perl Text::Glob module.
*
* @author Fabien Potencier <fabien@symfony.com> PHP port
* @author Richard Clamp <richardc@unixbeard.net> Perl version
* @copyright 2004-2005 Fabien Potencier <fabien@symfony.com>
* @copyright 2002 Richard Clamp <richardc@unixbeard.net>
*/
class Glob
{
/**
* Returns a regexp which is the equivalent of the glob pattern.
*
* @return string
*/
public static function toRegex(string $glob, bool $strictLeadingDot = \true, bool $strictWildcardSlash = \true, string $delimiter = '#')
{
$firstByte = \true;
$escaping = \false;
$inCurlies = 0;
$regex = '';
$sizeGlob = \strlen($glob);
for ($i = 0; $i < $sizeGlob; ++$i) {
$car = $glob[$i];
if ($firstByte && $strictLeadingDot && '.' !== $car) {
$regex .= '(?=[^\.])';
}
$firstByte = '/' === $car;
if ($firstByte && $strictWildcardSlash && isset($glob[$i + 2]) && '**' === $glob[$i + 1] . $glob[$i + 2] && (!isset($glob[$i + 3]) || '/' === $glob[$i + 3])) {
$car = '[^/]++/';
if (!isset($glob[$i + 3])) {
$car .= '?';
}
if ($strictLeadingDot) {
$car = '(?=[^\.])' . $car;
}
$car = '/(?:' . $car . ')*';
$i += 2 + isset($glob[$i + 3]);
if ('/' === $delimiter) {
$car = str_replace('/', '\/', $car);
}
}
if ($delimiter === $car || '.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
$regex .= "\\{$car}";
} elseif ('*' === $car) {
$regex .= $escaping ? '\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
} elseif ('?' === $car) {
$regex .= $escaping ? '\?' : ($strictWildcardSlash ? '[^/]' : '.');
} elseif ('{' === $car) {
$regex .= $escaping ? '\{' : '(';
if (!$escaping) {
++$inCurlies;
}
} elseif ('}' === $car && $inCurlies) {
$regex .= $escaping ? '}' : ')';
if (!$escaping) {
--$inCurlies;
}
} elseif (',' === $car && $inCurlies) {
$regex .= $escaping ? ',' : '|';
} elseif ('\\' === $car) {
if ($escaping) {
$regex .= '\\\\';
$escaping = \false;
} else {
$escaping = \true;
}
continue;
} else {
$regex .= $car;
}
$escaping = \false;
}
return $delimiter . '^' . $regex . '$' . $delimiter;
}
}
@@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace JooosiFonDeps\Symfony\Component\Finder\Iterator;
/**
* CustomFilterIterator filters files by applying anonymous functions.
*
* The anonymous function receives a \SplFileInfo and must return false
* to remove files.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @extends \FilterIterator<string, \SplFileInfo>
*/
class CustomFilterIterator extends \FilterIterator
{
private $filters = [];
/**
* @param \Iterator<string, \SplFileInfo> $iterator The Iterator to filter
* @param callable[] $filters An array of PHP callbacks
*
* @throws \InvalidArgumentException
*/
public function __construct(\Iterator $iterator, array $filters)
{
foreach ($filters as $filter) {
if (!\is_callable($filter)) {
throw new \InvalidArgumentException('Invalid PHP callback.');
}
}
$this->filters = $filters;
parent::__construct($iterator);
}
/**
* Filters the iterator values.
*
* @return bool
*/
#[\ReturnTypeWillChange]
public function accept()
{
$fileinfo = $this->current();
foreach ($this->filters as $filter) {
if (\false === $filter($fileinfo)) {
return \false;
}
}
return \true;
}
}

Some files were not shown because too many files have changed in this diff Show More