msd Backup hinzugefügt

This commit is contained in:
aschwarz
2023-07-25 19:16:12 +02:00
parent 50297c1d25
commit 1d3ed789b5
680 changed files with 103120 additions and 0 deletions

25
msd/vendor/autoload.php vendored Normal file
View File

@ -0,0 +1,25 @@
<?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;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit2352399418895b7bd82ed699298d379a::getLoader();

581
msd/vendor/composer/ClassLoader.php vendored Normal file
View File

@ -0,0 +1,581 @@
<?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 */
private $vendorDir;
// PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array();
// PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array();
/** @var ?string */
private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return string[]
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}
return array();
}
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap()
{
return $this->classMap;
}
/**
* @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @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 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)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $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 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)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $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] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $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 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 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)) {
(self::$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 indexed by their corresponding vendor directories.
*
* @return 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;
}
private static function initializeIncludeClosure(): void
{
if (self::$includeFile !== null) {
return;
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/
self::$includeFile = static function($file) {
include $file;
};
}
}

View File

@ -0,0 +1,352 @@
<?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;
use Composer\Autoload\ClassLoader;
use 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 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|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 || empty($installed['versions'][$packageName]['dev_requirement']);
}
}
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($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();
}
/**
* @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('Composer\Autoload\ClassLoader', 'getRegisteredLoaders');
}
$installed = array();
if (self::$canGetVendors) {
foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) {
if (isset(self::$installedByVendor[$vendorDir])) {
$installed[] = self::$installedByVendor[$vendorDir];
} elseif (is_file($vendorDir.'/composer/installed.php')) {
$installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php';
if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) {
self::$installed = $installed[count($installed) - 1];
}
}
}
}
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 = require __DIR__ . '/installed.php';
} else {
self::$installed = array();
}
}
$installed[] = self::$installed;
return $installed;
}
}

21
msd/vendor/composer/LICENSE vendored Normal file
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.

View File

@ -0,0 +1,10 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
);

10
msd/vendor/composer/autoload_files.php vendored Normal file
View File

@ -0,0 +1,10 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
);

View File

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
);

19
msd/vendor/composer/autoload_psr4.php vendored Normal file
View File

@ -0,0 +1,19 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'phpseclib\\' => array($vendorDir . '/phpseclib/phpseclib/phpseclib'),
'VisualAppeal\\' => array($vendorDir . '/visualappeal/php-auto-update/src'),
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'League\\MimeTypeDetection\\' => array($vendorDir . '/league/mime-type-detection/src'),
'League\\Flysystem\\PhpseclibV2\\' => array($vendorDir . '/league/flysystem-sftp'),
'League\\Flysystem\\' => array($vendorDir . '/league/flysystem/src'),
'Desarrolla2\\Cache\\' => array($vendorDir . '/desarrolla2/cache/src'),
'Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'),
);

50
msd/vendor/composer/autoload_real.php vendored Normal file
View File

@ -0,0 +1,50 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInit2352399418895b7bd82ed699298d379a
{
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('ComposerAutoloaderInit2352399418895b7bd82ed699298d379a', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
spl_autoload_unregister(array('ComposerAutoloaderInit2352399418895b7bd82ed699298d379a', 'loadClassLoader'));
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit2352399418895b7bd82ed699298d379a::getInitializer($loader));
$loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInit2352399418895b7bd82ed699298d379a::$files;
$requireFile = static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
};
foreach ($filesToLoad as $fileIdentifier => $file) {
($requireFile)($fileIdentifier, $file);
}
return $loader;
}
}

103
msd/vendor/composer/autoload_static.php vendored Normal file
View File

@ -0,0 +1,103 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInit2352399418895b7bd82ed699298d379a
{
public static $files = array (
'decc78cc4436b1292c6c0d151b19445c' => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
);
public static $prefixLengthsPsr4 = array (
'p' =>
array (
'phpseclib\\' => 10,
),
'V' =>
array (
'VisualAppeal\\' => 13,
),
'P' =>
array (
'Psr\\SimpleCache\\' => 16,
'Psr\\Log\\' => 8,
),
'M' =>
array (
'Monolog\\' => 8,
),
'L' =>
array (
'League\\MimeTypeDetection\\' => 25,
'League\\Flysystem\\PhpseclibV2\\' => 29,
'League\\Flysystem\\' => 17,
),
'D' =>
array (
'Desarrolla2\\Cache\\' => 18,
),
'C' =>
array (
'Composer\\Semver\\' => 16,
),
);
public static $prefixDirsPsr4 = array (
'phpseclib\\' =>
array (
0 => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib',
),
'VisualAppeal\\' =>
array (
0 => __DIR__ . '/..' . '/visualappeal/php-auto-update/src',
),
'Psr\\SimpleCache\\' =>
array (
0 => __DIR__ . '/..' . '/psr/simple-cache/src',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/Psr/Log',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'League\\MimeTypeDetection\\' =>
array (
0 => __DIR__ . '/..' . '/league/mime-type-detection/src',
),
'League\\Flysystem\\PhpseclibV2\\' =>
array (
0 => __DIR__ . '/..' . '/league/flysystem-sftp',
),
'League\\Flysystem\\' =>
array (
0 => __DIR__ . '/..' . '/league/flysystem/src',
),
'Desarrolla2\\Cache\\' =>
array (
0 => __DIR__ . '/..' . '/desarrolla2/cache/src',
),
'Composer\\Semver\\' =>
array (
0 => __DIR__ . '/..' . '/composer/semver/src',
),
);
public static $classMap = array (
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit2352399418895b7bd82ed699298d379a::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit2352399418895b7bd82ed699298d379a::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInit2352399418895b7bd82ed699298d379a::$classMap;
}, null, ClassLoader::class);
}
}

763
msd/vendor/composer/installed.json vendored Normal file
View File

@ -0,0 +1,763 @@
{
"packages": [
{
"name": "composer/semver",
"version": "3.3.2",
"version_normalized": "3.3.2.0",
"source": {
"type": "git",
"url": "https://github.com/composer/semver.git",
"reference": "3953f23262f2bff1919fc82183ad9acb13ff62c9"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/composer/semver/zipball/3953f23262f2bff1919fc82183ad9acb13ff62c9",
"reference": "3953f23262f2bff1919fc82183ad9acb13ff62c9",
"shasum": ""
},
"require": {
"php": "^5.3.2 || ^7.0 || ^8.0"
},
"require-dev": {
"phpstan/phpstan": "^1.4",
"symfony/phpunit-bridge": "^4.2 || ^5"
},
"time": "2022-04-01T19:23:25+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Composer\\Semver\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Nils Adermann",
"email": "naderman@naderman.de",
"homepage": "http://www.naderman.de"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
},
{
"name": "Rob Bast",
"email": "rob.bast@gmail.com",
"homepage": "http://robbast.nl"
}
],
"description": "Semver library that offers utilities, version constraint parsing and validation.",
"keywords": [
"semantic",
"semver",
"validation",
"versioning"
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/semver/issues",
"source": "https://github.com/composer/semver/tree/3.3.2"
},
"funding": [
{
"url": "https://packagist.com",
"type": "custom"
},
{
"url": "https://github.com/composer",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/composer/composer",
"type": "tidelift"
}
],
"install-path": "./semver"
},
{
"name": "desarrolla2/cache",
"version": "v3.0.2",
"version_normalized": "3.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/desarrolla2/Cache.git",
"reference": "0b8f985d09abfc04a2c1535943f6f07b7206161a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/desarrolla2/Cache/zipball/0b8f985d09abfc04a2c1535943f6f07b7206161a",
"reference": "0b8f985d09abfc04a2c1535943f6f07b7206161a",
"shasum": ""
},
"require": {
"php": ">=7.2.0",
"psr/simple-cache": "^1.0"
},
"provide": {
"psr/simple-cache-implementation": "1.0"
},
"require-dev": {
"cache/integration-tests": "dev-master",
"ext-apcu": "*",
"ext-json": "*",
"ext-memcached": "*",
"ext-mysqli": "*",
"mikey179/vfsstream": "v1.6.8",
"mongodb/mongodb": "^1.3",
"phpstan/phpstan": "^0.12.29",
"phpunit/phpunit": "^8.3 || ^9.0",
"predis/predis": "~1.0.0",
"symfony/phpunit-bridge": "^5.2"
},
"time": "2022-03-27T23:04:06+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Desarrolla2\\Cache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Daniel González",
"homepage": "http://desarrolla2.com/"
},
{
"name": "Arnold Daniels",
"homepage": "https://jasny.net/"
}
],
"description": "Provides an cache interface for several adapters Apc, Apcu, File, Mongo, Memcache, Memcached, Mysql, Mongo, Redis is supported.",
"homepage": "https://github.com/desarrolla2/Cache/",
"keywords": [
"apc",
"apcu",
"cache",
"file",
"memcache",
"memcached",
"mongo",
"mysql",
"psr-16",
"redis",
"simple-cache"
],
"support": {
"issues": "https://github.com/desarrolla2/Cache/issues",
"source": "https://github.com/desarrolla2/Cache/tree/v3.0.2"
},
"install-path": "../desarrolla2/cache"
},
{
"name": "league/flysystem",
"version": "2.5.0",
"version_normalized": "2.5.0.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem.git",
"reference": "8aaffb653c5777781b0f7f69a5d937baf7ab6cdb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem/zipball/8aaffb653c5777781b0f7f69a5d937baf7ab6cdb",
"reference": "8aaffb653c5777781b0f7f69a5d937baf7ab6cdb",
"shasum": ""
},
"require": {
"ext-json": "*",
"league/mime-type-detection": "^1.0.0",
"php": "^7.2 || ^8.0"
},
"conflict": {
"guzzlehttp/ringphp": "<1.1.1"
},
"require-dev": {
"async-aws/s3": "^1.5",
"async-aws/simple-s3": "^1.0",
"aws/aws-sdk-php": "^3.132.4",
"composer/semver": "^3.0",
"ext-fileinfo": "*",
"ext-ftp": "*",
"friendsofphp/php-cs-fixer": "^3.2",
"google/cloud-storage": "^1.23",
"phpseclib/phpseclib": "^2.0",
"phpstan/phpstan": "^0.12.26",
"phpunit/phpunit": "^8.5 || ^9.4",
"sabre/dav": "^4.1"
},
"time": "2022-09-17T21:02:32+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\Flysystem\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frankdejonge.nl"
}
],
"description": "File storage abstraction for PHP",
"keywords": [
"WebDAV",
"aws",
"cloud",
"file",
"files",
"filesystem",
"filesystems",
"ftp",
"s3",
"sftp",
"storage"
],
"support": {
"issues": "https://github.com/thephpleague/flysystem/issues",
"source": "https://github.com/thephpleague/flysystem/tree/2.5.0"
},
"funding": [
{
"url": "https://ecologi.com/frankdejonge",
"type": "custom"
},
{
"url": "https://github.com/frankdejonge",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/league/flysystem",
"type": "tidelift"
}
],
"install-path": "../league/flysystem"
},
{
"name": "league/flysystem-sftp",
"version": "2.5.0",
"version_normalized": "2.5.0.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/flysystem-sftp.git",
"reference": "e30acbc9be024bb7df6ee4b159f2c8db3efcb6a7"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/flysystem-sftp/zipball/e30acbc9be024bb7df6ee4b159f2c8db3efcb6a7",
"reference": "e30acbc9be024bb7df6ee4b159f2c8db3efcb6a7",
"shasum": ""
},
"require": {
"league/flysystem": "^2.0.0",
"league/mime-type-detection": "^1.0.0",
"php": "^7.2 || ^8.0",
"phpseclib/phpseclib": "^2.0"
},
"time": "2022-04-27T17:27:27+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\Flysystem\\PhpseclibV2\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frankdejonge.nl"
}
],
"description": "SFTP filesystem adapter for Flysystem.",
"keywords": [
"Flysystem",
"file",
"files",
"filesystem",
"sftp"
],
"support": {
"issues": "https://github.com/thephpleague/flysystem-sftp/issues",
"source": "https://github.com/thephpleague/flysystem-sftp/tree/2.5.0"
},
"funding": [
{
"url": "https://ecologi.com/frankdejonge",
"type": "custom"
},
{
"url": "https://github.com/frankdejonge",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/league/flysystem",
"type": "tidelift"
}
],
"abandoned": "league/flysystem-sftp-v3",
"install-path": "../league/flysystem-sftp"
},
{
"name": "league/mime-type-detection",
"version": "1.11.0",
"version_normalized": "1.11.0.0",
"source": {
"type": "git",
"url": "https://github.com/thephpleague/mime-type-detection.git",
"reference": "ff6248ea87a9f116e78edd6002e39e5128a0d4dd"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/thephpleague/mime-type-detection/zipball/ff6248ea87a9f116e78edd6002e39e5128a0d4dd",
"reference": "ff6248ea87a9f116e78edd6002e39e5128a0d4dd",
"shasum": ""
},
"require": {
"ext-fileinfo": "*",
"php": "^7.2 || ^8.0"
},
"require-dev": {
"friendsofphp/php-cs-fixer": "^3.2",
"phpstan/phpstan": "^0.12.68",
"phpunit/phpunit": "^8.5.8 || ^9.3"
},
"time": "2022-04-17T13:12:02+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"League\\MimeTypeDetection\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Frank de Jonge",
"email": "info@frankdejonge.nl"
}
],
"description": "Mime-type detection for Flysystem",
"support": {
"issues": "https://github.com/thephpleague/mime-type-detection/issues",
"source": "https://github.com/thephpleague/mime-type-detection/tree/1.11.0"
},
"funding": [
{
"url": "https://github.com/frankdejonge",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/league/flysystem",
"type": "tidelift"
}
],
"install-path": "../league/mime-type-detection"
},
{
"name": "monolog/monolog",
"version": "2.8.0",
"version_normalized": "2.8.0.0",
"source": {
"type": "git",
"url": "https://github.com/Seldaek/monolog.git",
"reference": "720488632c590286b88b80e62aa3d3d551ad4a50"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Seldaek/monolog/zipball/720488632c590286b88b80e62aa3d3d551ad4a50",
"reference": "720488632c590286b88b80e62aa3d3d551ad4a50",
"shasum": ""
},
"require": {
"php": ">=7.2",
"psr/log": "^1.0.1 || ^2.0 || ^3.0"
},
"provide": {
"psr/log-implementation": "1.0.0 || 2.0.0 || 3.0.0"
},
"require-dev": {
"aws/aws-sdk-php": "^2.4.9 || ^3.0",
"doctrine/couchdb": "~1.0@dev",
"elasticsearch/elasticsearch": "^7 || ^8",
"ext-json": "*",
"graylog2/gelf-php": "^1.4.2",
"guzzlehttp/guzzle": "^7.4",
"guzzlehttp/psr7": "^2.2",
"mongodb/mongodb": "^1.8",
"php-amqplib/php-amqplib": "~2.4 || ^3",
"phpspec/prophecy": "^1.15",
"phpstan/phpstan": "^0.12.91",
"phpunit/phpunit": "^8.5.14",
"predis/predis": "^1.1 || ^2.0",
"rollbar/rollbar": "^1.3 || ^2 || ^3",
"ruflin/elastica": "^7",
"swiftmailer/swiftmailer": "^5.3|^6.0",
"symfony/mailer": "^5.4 || ^6",
"symfony/mime": "^5.4 || ^6"
},
"suggest": {
"aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
"doctrine/couchdb": "Allow sending log messages to a CouchDB server",
"elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client",
"ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
"ext-curl": "Required to send log messages using the IFTTTHandler, the LogglyHandler, the SendGridHandler, the SlackWebhookHandler or the TelegramBotHandler",
"ext-mbstring": "Allow to work properly with unicode symbols",
"ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)",
"ext-openssl": "Required to send log messages using SSL",
"ext-sockets": "Allow sending log messages to a Syslog server (via UDP driver)",
"graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
"mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)",
"php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
"rollbar/rollbar": "Allow sending log messages to Rollbar",
"ruflin/elastica": "Allow sending log messages to an Elastic Search server"
},
"time": "2022-07-24T11:55:47+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-main": "2.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Monolog\\": "src/Monolog"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "https://seld.be"
}
],
"description": "Sends your logs to files, sockets, inboxes, databases and various web services",
"homepage": "https://github.com/Seldaek/monolog",
"keywords": [
"log",
"logging",
"psr-3"
],
"support": {
"issues": "https://github.com/Seldaek/monolog/issues",
"source": "https://github.com/Seldaek/monolog/tree/2.8.0"
},
"funding": [
{
"url": "https://github.com/Seldaek",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/monolog/monolog",
"type": "tidelift"
}
],
"install-path": "../monolog/monolog"
},
{
"name": "phpseclib/phpseclib",
"version": "2.0.41",
"version_normalized": "2.0.41.0",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "7e763c6f97ec1fcb37c46aa8ecfc20a2c71d9c1b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/7e763c6f97ec1fcb37c46aa8ecfc20a2c71d9c1b",
"reference": "7e763c6f97ec1fcb37c46aa8ecfc20a2c71d9c1b",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phing/phing": "~2.7",
"phpunit/phpunit": "^4.8.35|^5.7|^6.0|^9.4",
"squizlabs/php_codesniffer": "~2.0"
},
"suggest": {
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations.",
"ext-xml": "Install the XML extension to load XML formatted public keys."
},
"time": "2022-12-23T16:44:18+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"support": {
"issues": "https://github.com/phpseclib/phpseclib/issues",
"source": "https://github.com/phpseclib/phpseclib/tree/2.0.41"
},
"funding": [
{
"url": "https://github.com/terrafrost",
"type": "github"
},
{
"url": "https://www.patreon.com/phpseclib",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/phpseclib/phpseclib",
"type": "tidelift"
}
],
"install-path": "../phpseclib/phpseclib"
},
{
"name": "psr/log",
"version": "1.1.4",
"version_normalized": "1.1.4.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/log.git",
"reference": "d49695b909c3b7628b6289db5479a1c204601f11"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/log/zipball/d49695b909c3b7628b6289db5479a1c204601f11",
"reference": "d49695b909c3b7628b6289db5479a1c204601f11",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2021-05-03T11:20:27+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\Log\\": "Psr/Log/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for logging libraries",
"homepage": "https://github.com/php-fig/log",
"keywords": [
"log",
"psr",
"psr-3"
],
"support": {
"source": "https://github.com/php-fig/log/tree/1.1.4"
},
"install-path": "../psr/log"
},
{
"name": "psr/simple-cache",
"version": "1.0.1",
"version_normalized": "1.0.1.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/simple-cache.git",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/simple-cache/zipball/408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"reference": "408d5eafb83c57f6365a3ca330ff23aa4a5fa39b",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"time": "2017-10-23T01:57:42+00:00",
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"Psr\\SimpleCache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "http://www.php-fig.org/"
}
],
"description": "Common interfaces for simple caching",
"keywords": [
"cache",
"caching",
"psr",
"psr-16",
"simple-cache"
],
"support": {
"source": "https://github.com/php-fig/simple-cache/tree/master"
},
"install-path": "../psr/simple-cache"
},
{
"name": "visualappeal/php-auto-update",
"version": "1.0.2",
"version_normalized": "1.0.2.0",
"source": {
"type": "git",
"url": "https://github.com/VisualAppeal/PHP-Auto-Update.git",
"reference": "4454361a0fa346c7fb179deef11585c79715b645"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/VisualAppeal/PHP-Auto-Update/zipball/4454361a0fa346c7fb179deef11585c79715b645",
"reference": "4454361a0fa346c7fb179deef11585c79715b645",
"shasum": ""
},
"require": {
"composer/semver": "^3.0",
"desarrolla2/cache": "^3.0",
"ext-curl": "*",
"ext-json": "*",
"ext-zip": "*",
"monolog/monolog": "^2.1",
"php": ">=7.2.0",
"psr/log": "1.1.4"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"roave/security-advisories": "dev-master"
},
"time": "2021-11-27T22:39:05+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"VisualAppeal\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Tim Helfensdörfer",
"email": "tim@visualappeal.de"
}
],
"description": "Autoupdater for PHP",
"support": {
"issues": "https://github.com/VisualAppeal/PHP-Auto-Update/issues",
"source": "https://github.com/VisualAppeal/PHP-Auto-Update/tree/1.0.2"
},
"install-path": "../visualappeal/php-auto-update"
}
],
"dev": true,
"dev-package-names": []
}

125
msd/vendor/composer/installed.php vendored Normal file
View File

@ -0,0 +1,125 @@
<?php return array(
'root' => array(
'name' => '__root__',
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '36584e64258f869722dd8bc34b66b083a03b2369',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev' => true,
),
'versions' => array(
'__root__' => array(
'pretty_version' => 'dev-master',
'version' => 'dev-master',
'reference' => '36584e64258f869722dd8bc34b66b083a03b2369',
'type' => 'library',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'dev_requirement' => false,
),
'composer/semver' => array(
'pretty_version' => '3.3.2',
'version' => '3.3.2.0',
'reference' => '3953f23262f2bff1919fc82183ad9acb13ff62c9',
'type' => 'library',
'install_path' => __DIR__ . '/./semver',
'aliases' => array(),
'dev_requirement' => false,
),
'desarrolla2/cache' => array(
'pretty_version' => 'v3.0.2',
'version' => '3.0.2.0',
'reference' => '0b8f985d09abfc04a2c1535943f6f07b7206161a',
'type' => 'library',
'install_path' => __DIR__ . '/../desarrolla2/cache',
'aliases' => array(),
'dev_requirement' => false,
),
'league/flysystem' => array(
'pretty_version' => '2.5.0',
'version' => '2.5.0.0',
'reference' => '8aaffb653c5777781b0f7f69a5d937baf7ab6cdb',
'type' => 'library',
'install_path' => __DIR__ . '/../league/flysystem',
'aliases' => array(),
'dev_requirement' => false,
),
'league/flysystem-sftp' => array(
'pretty_version' => '2.5.0',
'version' => '2.5.0.0',
'reference' => 'e30acbc9be024bb7df6ee4b159f2c8db3efcb6a7',
'type' => 'library',
'install_path' => __DIR__ . '/../league/flysystem-sftp',
'aliases' => array(),
'dev_requirement' => false,
),
'league/mime-type-detection' => array(
'pretty_version' => '1.11.0',
'version' => '1.11.0.0',
'reference' => 'ff6248ea87a9f116e78edd6002e39e5128a0d4dd',
'type' => 'library',
'install_path' => __DIR__ . '/../league/mime-type-detection',
'aliases' => array(),
'dev_requirement' => false,
),
'monolog/monolog' => array(
'pretty_version' => '2.8.0',
'version' => '2.8.0.0',
'reference' => '720488632c590286b88b80e62aa3d3d551ad4a50',
'type' => 'library',
'install_path' => __DIR__ . '/../monolog/monolog',
'aliases' => array(),
'dev_requirement' => false,
),
'phpseclib/phpseclib' => array(
'pretty_version' => '2.0.41',
'version' => '2.0.41.0',
'reference' => '7e763c6f97ec1fcb37c46aa8ecfc20a2c71d9c1b',
'type' => 'library',
'install_path' => __DIR__ . '/../phpseclib/phpseclib',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/log' => array(
'pretty_version' => '1.1.4',
'version' => '1.1.4.0',
'reference' => 'd49695b909c3b7628b6289db5479a1c204601f11',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/log',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/log-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0.0 || 2.0.0 || 3.0.0',
),
),
'psr/simple-cache' => array(
'pretty_version' => '1.0.1',
'version' => '1.0.1.0',
'reference' => '408d5eafb83c57f6365a3ca330ff23aa4a5fa39b',
'type' => 'library',
'install_path' => __DIR__ . '/../psr/simple-cache',
'aliases' => array(),
'dev_requirement' => false,
),
'psr/simple-cache-implementation' => array(
'dev_requirement' => false,
'provided' => array(
0 => '1.0',
),
),
'visualappeal/php-auto-update' => array(
'pretty_version' => '1.0.2',
'version' => '1.0.2.0',
'reference' => '4454361a0fa346c7fb179deef11585c79715b645',
'type' => 'library',
'install_path' => __DIR__ . '/../visualappeal/php-auto-update',
'aliases' => array(),
'dev_requirement' => false,
),
),
);

26
msd/vendor/composer/platform_check.php vendored Normal file
View File

@ -0,0 +1,26 @@
<?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;
}
}
trigger_error(
'Composer detected issues in your platform: ' . implode(' ', $issues),
E_USER_ERROR
);
}

209
msd/vendor/composer/semver/CHANGELOG.md vendored Normal file
View File

@ -0,0 +1,209 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
### [3.3.2] 2022-04-01
* Fixed handling of non-string values (#134)
### [3.3.1] 2022-03-16
* Fixed possible cache key clash in the CompilingMatcher memoization (#132)
### [3.3.0] 2022-03-15
* Improved performance of CompilingMatcher by memoizing more (#131)
* Added CompilingMatcher::clear to clear all memoization caches
### [3.2.9] 2022-02-04
* Revert #129 (Fixed MultiConstraint with MatchAllConstraint) which caused regressions
### [3.2.8] 2022-02-04
* Updates to latest phpstan / CI by @Seldaek in https://github.com/composer/semver/pull/130
* Fixed MultiConstraint with MatchAllConstraint by @Toflar in https://github.com/composer/semver/pull/129
### [3.2.7] 2022-01-04
* Fixed: typo in type definition of Intervals class causing issues with Psalm scanning vendors
### [3.2.6] 2021-10-25
* Fixed: type improvements to parseStability
### [3.2.5] 2021-05-24
* Fixed: issue comparing disjunctive MultiConstraints to conjunctive ones (#127)
* Fixed: added complete type information using phpstan annotations
### [3.2.4] 2020-11-13
* Fixed: code clean-up
### [3.2.3] 2020-11-12
* Fixed: constraints in the form of `X || Y, >=Y.1` and other such complex constructs were in some cases being optimized into a more restrictive constraint
### [3.2.2] 2020-10-14
* Fixed: internal code cleanups
### [3.2.1] 2020-09-27
* Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases
* Fixed: normalization of beta0 and such which was dropping the 0
### [3.2.0] 2020-09-09
* Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0
* Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience
### [3.1.0] 2020-09-08
* Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 3.0.1
* Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package
### [3.0.1] 2020-09-08
* Fixed: handling of some invalid -dev versions which were seen as valid
### [3.0.0] 2020-05-26
* Break: Renamed `EmptyConstraint`, replace it with `MatchAllConstraint`
* Break: Unlikely to affect anyone but strictly speaking a breaking change, `*.*` and such variants will not match all `dev-*` versions anymore, only `*` does
* Break: ConstraintInterface is now considered internal/private and not meant to be implemented by third parties anymore
* Added `Intervals` class to check if a constraint is a subsets of another one, and allow compacting complex MultiConstraints into simpler ones
* Added `CompilingMatcher` class to speed up constraint matching against simple Constraint instances
* Added `MatchAllConstraint` and `MatchNoneConstraint` which match everything and nothing
* Added more advanced optimization of contiguous constraints inside MultiConstraint
* Added tentative support for PHP 8
* Fixed ConstraintInterface::matches to be commutative in all cases
### [2.0.0] 2020-04-21
* Break: `dev-master`, `dev-trunk` and `dev-default` now normalize to `dev-master`, `dev-trunk` and `dev-default` instead of `9999999-dev` in 1.x
* Break: Removed the deprecated `AbstractConstraint`
* Added `getUpperBound` and `getLowerBound` to ConstraintInterface. They return `Composer\Semver\Constraint\Bound` instances
* Added `MultiConstraint::create` to create the most-optimal form of ConstraintInterface from an array of constraint strings
### [1.7.2] 2020-12-03
* Fixed: Allow installing on php 8
### [1.7.1] 2020-09-27
* Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases
* Fixed: normalization of beta0 and such which was dropping the 0
### [1.7.0] 2020-09-09
* Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0
* Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience
### [1.6.0] 2020-09-08
* Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2
* Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package
### [1.5.2] 2020-09-08
* Fixed: handling of some invalid -dev versions which were seen as valid
* Fixed: some doctypes
### [1.5.1] 2020-01-13
* Fixed: Parsing of aliased version was not validating the alias to be a valid version
### [1.5.0] 2019-03-19
* Added: some support for date versions (e.g. 201903) in `~` operator
* Fixed: support for stabilities in `~` operator was inconsistent
### [1.4.2] 2016-08-30
* Fixed: collapsing of complex constraints lead to buggy constraints
### [1.4.1] 2016-06-02
* Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38).
### [1.4.0] 2016-03-30
* Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35).
### [1.3.0] 2016-02-25
* Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889).
* Changed: collapse contiguous constraints when possible.
### [1.2.0] 2015-11-10
* Changed: allow multiple numerical identifiers in 'pre-release' version part.
* Changed: add more 'v' prefix support.
### [1.1.0] 2015-11-03
* Changed: dropped redundant `test` namespace.
* Changed: minor adjustment in datetime parsing normalization.
* Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore.
* Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0.
* Changed: `Constraint` is now extensible.
### [1.0.0] 2015-09-21
* Break: `VersionConstraint` renamed to `Constraint`.
* Break: `SpecificConstraint` renamed to `AbstractConstraint`.
* Break: `LinkConstraintInterface` renamed to `ConstraintInterface`.
* Break: `VersionParser::parseNameVersionPairs` was removed.
* Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now.
* Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now.
* Changed: Fixed namespace(s) of test files.
* Changed: `Comparator::compare` no longer throws `InvalidArgumentException`.
* Changed: `Constraint` now throws `InvalidArgumentException`.
### [0.1.0] 2015-07-23
* Added: `Composer\Semver\Comparator`, various methods to compare versions.
* Added: various documents such as README.md, LICENSE, etc.
* Added: configuration files for Git, Travis, php-cs-fixer, phpunit.
* Break: the following namespaces were renamed:
- Namespace: `Composer\Package\Version` -> `Composer\Semver`
- Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint`
- Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver`
- Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint`
* Changed: code style using php-cs-fixer.
[3.3.2]: https://github.com/composer/semver/compare/3.3.1...3.3.2
[3.3.1]: https://github.com/composer/semver/compare/3.3.0...3.3.1
[3.3.0]: https://github.com/composer/semver/compare/3.2.9...3.3.0
[3.2.9]: https://github.com/composer/semver/compare/3.2.8...3.2.9
[3.2.8]: https://github.com/composer/semver/compare/3.2.7...3.2.8
[3.2.7]: https://github.com/composer/semver/compare/3.2.6...3.2.7
[3.2.6]: https://github.com/composer/semver/compare/3.2.5...3.2.6
[3.2.5]: https://github.com/composer/semver/compare/3.2.4...3.2.5
[3.2.4]: https://github.com/composer/semver/compare/3.2.3...3.2.4
[3.2.3]: https://github.com/composer/semver/compare/3.2.2...3.2.3
[3.2.2]: https://github.com/composer/semver/compare/3.2.1...3.2.2
[3.2.1]: https://github.com/composer/semver/compare/3.2.0...3.2.1
[3.2.0]: https://github.com/composer/semver/compare/3.1.0...3.2.0
[3.1.0]: https://github.com/composer/semver/compare/3.0.1...3.1.0
[3.0.1]: https://github.com/composer/semver/compare/3.0.0...3.0.1
[3.0.0]: https://github.com/composer/semver/compare/2.0.0...3.0.0
[2.0.0]: https://github.com/composer/semver/compare/1.5.1...2.0.0
[1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2
[1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1
[1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0
[1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0
[1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2
[1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1
[1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0
[1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2
[1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1
[1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0
[1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0
[1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0
[1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0
[1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0
[0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0

19
msd/vendor/composer/semver/LICENSE vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (C) 2015 Composer
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.

98
msd/vendor/composer/semver/README.md vendored Normal file
View File

@ -0,0 +1,98 @@
composer/semver
===============
Semver (Semantic Versioning) library that offers utilities, version constraint parsing and validation.
Originally written as part of [composer/composer](https://github.com/composer/composer),
now extracted and made available as a stand-alone library.
[![Continuous Integration](https://github.com/composer/semver/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/semver/actions)
Installation
------------
Install the latest version with:
```bash
$ composer require composer/semver
```
Requirements
------------
* PHP 5.3.2 is required but using the latest version of PHP is highly recommended.
Version Comparison
------------------
For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md)
article in the documentation section of the [getcomposer.org](https://getcomposer.org) website.
Basic usage
-----------
### Comparator
The [`Composer\Semver\Comparator`](https://github.com/composer/semver/blob/main/src/Comparator.php) class provides the following methods for comparing versions:
* greaterThan($v1, $v2)
* greaterThanOrEqualTo($v1, $v2)
* lessThan($v1, $v2)
* lessThanOrEqualTo($v1, $v2)
* equalTo($v1, $v2)
* notEqualTo($v1, $v2)
Each function takes two version strings as arguments and returns a boolean. For example:
```php
use Composer\Semver\Comparator;
Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0
```
### Semver
The [`Composer\Semver\Semver`](https://github.com/composer/semver/blob/main/src/Semver.php) class provides the following methods:
* satisfies($version, $constraints)
* satisfiedBy(array $versions, $constraint)
* sort($versions)
* rsort($versions)
### Intervals
The [`Composer\Semver\Intervals`](https://github.com/composer/semver/blob/main/src/Intervals.php) static class provides
a few utilities to work with complex constraints or read version intervals from a constraint:
```php
use Composer\Semver\Intervals;
// Checks whether $candidate is a subset of $constraint
Intervals::isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint);
// Checks whether $a and $b have any intersection, equivalent to $a->matches($b)
Intervals::haveIntersections(ConstraintInterface $a, ConstraintInterface $b);
// Optimizes a complex multi constraint by merging all intervals down to the smallest
// possible multi constraint. The drawbacks are this is not very fast, and the resulting
// multi constraint will have no human readable prettyConstraint configured on it
Intervals::compactConstraint(ConstraintInterface $constraint);
// Creates an array of numeric intervals and branch constraints representing a given constraint
Intervals::get(ConstraintInterface $constraint);
// Clears the memoization cache when you are done processing constraints
Intervals::clear()
```
See the class docblocks for more details.
License
-------
composer/semver is licensed under the MIT License, see the LICENSE file for details.

View File

@ -0,0 +1,59 @@
{
"name": "composer/semver",
"description": "Semver library that offers utilities, version constraint parsing and validation.",
"type": "library",
"license": "MIT",
"keywords": [
"semver",
"semantic",
"versioning",
"validation"
],
"authors": [
{
"name": "Nils Adermann",
"email": "naderman@naderman.de",
"homepage": "http://www.naderman.de"
},
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
},
{
"name": "Rob Bast",
"email": "rob.bast@gmail.com",
"homepage": "http://robbast.nl"
}
],
"support": {
"irc": "irc://irc.freenode.org/composer",
"issues": "https://github.com/composer/semver/issues"
},
"require": {
"php": "^5.3.2 || ^7.0 || ^8.0"
},
"require-dev": {
"symfony/phpunit-bridge": "^4.2 || ^5",
"phpstan/phpstan": "^1.4"
},
"autoload": {
"psr-4": {
"Composer\\Semver\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Composer\\Semver\\": "tests"
}
},
"extra": {
"branch-alias": {
"dev-main": "3.x-dev"
}
},
"scripts": {
"test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor/bin/simple-phpunit",
"phpstan": "@php vendor/bin/phpstan analyse"
}
}

View File

@ -0,0 +1,113 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Comparator
{
/**
* Evaluates the expression: $version1 > $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function greaterThan($version1, $version2)
{
return self::compare($version1, '>', $version2);
}
/**
* Evaluates the expression: $version1 >= $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function greaterThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '>=', $version2);
}
/**
* Evaluates the expression: $version1 < $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function lessThan($version1, $version2)
{
return self::compare($version1, '<', $version2);
}
/**
* Evaluates the expression: $version1 <= $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function lessThanOrEqualTo($version1, $version2)
{
return self::compare($version1, '<=', $version2);
}
/**
* Evaluates the expression: $version1 == $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function equalTo($version1, $version2)
{
return self::compare($version1, '==', $version2);
}
/**
* Evaluates the expression: $version1 != $version2.
*
* @param string $version1
* @param string $version2
*
* @return bool
*/
public static function notEqualTo($version1, $version2)
{
return self::compare($version1, '!=', $version2);
}
/**
* Evaluates the expression: $version1 $operator $version2.
*
* @param string $version1
* @param string $operator
* @param string $version2
*
* @return bool
*
* @phpstan-param Constraint::STR_OP_* $operator
*/
public static function compare($version1, $operator, $version2)
{
$constraint = new Constraint($operator, $version2);
return $constraint->matchSpecific(new Constraint('==', $version1), true);
}
}

View File

@ -0,0 +1,94 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
/**
* Helper class to evaluate constraint by compiling and reusing the code to evaluate
*/
class CompilingMatcher
{
/**
* @var array
* @phpstan-var array<string, callable>
*/
private static $compiledCheckerCache = array();
/**
* @var array
* @phpstan-var array<string, bool>
*/
private static $resultCache = array();
/** @var bool */
private static $enabled;
/**
* @phpstan-var array<Constraint::OP_*, Constraint::STR_OP_*>
*/
private static $transOpInt = array(
Constraint::OP_EQ => Constraint::STR_OP_EQ,
Constraint::OP_LT => Constraint::STR_OP_LT,
Constraint::OP_LE => Constraint::STR_OP_LE,
Constraint::OP_GT => Constraint::STR_OP_GT,
Constraint::OP_GE => Constraint::STR_OP_GE,
Constraint::OP_NE => Constraint::STR_OP_NE,
);
/**
* Clears the memoization cache once you are done
*
* @return void
*/
public static function clear()
{
self::$resultCache = array();
self::$compiledCheckerCache = array();
}
/**
* Evaluates the expression: $constraint match $operator $version
*
* @param ConstraintInterface $constraint
* @param int $operator
* @phpstan-param Constraint::OP_* $operator
* @param string $version
*
* @return mixed
*/
public static function match(ConstraintInterface $constraint, $operator, $version)
{
$resultCacheKey = $operator.$constraint.';'.$version;
if (isset(self::$resultCache[$resultCacheKey])) {
return self::$resultCache[$resultCacheKey];
}
if (self::$enabled === null) {
self::$enabled = !\in_array('eval', explode(',', (string) ini_get('disable_functions')), true);
}
if (!self::$enabled) {
return self::$resultCache[$resultCacheKey] = $constraint->matches(new Constraint(self::$transOpInt[$operator], $version));
}
$cacheKey = $operator.$constraint;
if (!isset(self::$compiledCheckerCache[$cacheKey])) {
$code = $constraint->compile($operator);
self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};');
} else {
$function = self::$compiledCheckerCache[$cacheKey];
}
return self::$resultCache[$resultCacheKey] = $function($version, strpos($version, 'dev-') === 0);
}
}

View File

@ -0,0 +1,122 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
class Bound
{
/**
* @var string
*/
private $version;
/**
* @var bool
*/
private $isInclusive;
/**
* @param string $version
* @param bool $isInclusive
*/
public function __construct($version, $isInclusive)
{
$this->version = $version;
$this->isInclusive = $isInclusive;
}
/**
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* @return bool
*/
public function isInclusive()
{
return $this->isInclusive;
}
/**
* @return bool
*/
public function isZero()
{
return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive();
}
/**
* @return bool
*/
public function isPositiveInfinity()
{
return $this->getVersion() === PHP_INT_MAX.'.0.0.0' && !$this->isInclusive();
}
/**
* Compares a bound to another with a given operator.
*
* @param Bound $other
* @param string $operator
*
* @return bool
*/
public function compareTo(Bound $other, $operator)
{
if (!\in_array($operator, array('<', '>'), true)) {
throw new \InvalidArgumentException('Does not support any other operator other than > or <.');
}
// If they are the same it doesn't matter
if ($this == $other) {
return false;
}
$compareResult = version_compare($this->getVersion(), $other->getVersion());
// Not the same version means we don't need to check if the bounds are inclusive or not
if (0 !== $compareResult) {
return (('>' === $operator) ? 1 : -1) === $compareResult;
}
// Question we're answering here is "am I higher than $other?"
return '>' === $operator ? $other->isInclusive() : !$other->isInclusive();
}
public function __toString()
{
return sprintf(
'%s [%s]',
$this->getVersion(),
$this->isInclusive() ? 'inclusive' : 'exclusive'
);
}
/**
* @return self
*/
public static function zero()
{
return new Bound('0.0.0.0-dev', true);
}
/**
* @return self
*/
public static function positiveInfinity()
{
return new Bound(PHP_INT_MAX.'.0.0.0', false);
}
}

View File

@ -0,0 +1,435 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines a constraint.
*/
class Constraint implements ConstraintInterface
{
/* operator integer values */
const OP_EQ = 0;
const OP_LT = 1;
const OP_LE = 2;
const OP_GT = 3;
const OP_GE = 4;
const OP_NE = 5;
/* operator string values */
const STR_OP_EQ = '==';
const STR_OP_EQ_ALT = '=';
const STR_OP_LT = '<';
const STR_OP_LE = '<=';
const STR_OP_GT = '>';
const STR_OP_GE = '>=';
const STR_OP_NE = '!=';
const STR_OP_NE_ALT = '<>';
/**
* Operator to integer translation table.
*
* @var array
* @phpstan-var array<self::STR_OP_*, self::OP_*>
*/
private static $transOpStr = array(
'=' => self::OP_EQ,
'==' => self::OP_EQ,
'<' => self::OP_LT,
'<=' => self::OP_LE,
'>' => self::OP_GT,
'>=' => self::OP_GE,
'<>' => self::OP_NE,
'!=' => self::OP_NE,
);
/**
* Integer to operator translation table.
*
* @var array
* @phpstan-var array<self::OP_*, self::STR_OP_*>
*/
private static $transOpInt = array(
self::OP_EQ => '==',
self::OP_LT => '<',
self::OP_LE => '<=',
self::OP_GT => '>',
self::OP_GE => '>=',
self::OP_NE => '!=',
);
/**
* @var int
* @phpstan-var self::OP_*
*/
protected $operator;
/** @var string */
protected $version;
/** @var string|null */
protected $prettyString;
/** @var Bound */
protected $lowerBound;
/** @var Bound */
protected $upperBound;
/**
* Sets operator and version to compare with.
*
* @param string $operator
* @param string $version
*
* @throws \InvalidArgumentException if invalid operator is given.
*
* @phpstan-param self::STR_OP_* $operator
*/
public function __construct($operator, $version)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$this->operator = self::$transOpStr[$operator];
$this->version = $version;
}
/**
* @return string
*/
public function getVersion()
{
return $this->version;
}
/**
* @return string
*
* @phpstan-return self::STR_OP_*
*/
public function getOperator()
{
return self::$transOpInt[$this->operator];
}
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
if ($provider instanceof self) {
return $this->matchSpecific($provider);
}
// turn matching around to find a match
return $provider->matches($this);
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return $this->__toString();
}
/**
* Get all supported comparison operators.
*
* @return array
*
* @phpstan-return list<self::STR_OP_*>
*/
public static function getSupportedOperators()
{
return array_keys(self::$transOpStr);
}
/**
* @param string $operator
* @return int
*
* @phpstan-param self::STR_OP_* $operator
* @phpstan-return self::OP_*
*/
public static function getOperatorConstant($operator)
{
return self::$transOpStr[$operator];
}
/**
* @param string $a
* @param string $b
* @param string $operator
* @param bool $compareBranches
*
* @throws \InvalidArgumentException if invalid operator is given.
*
* @return bool
*
* @phpstan-param self::STR_OP_* $operator
*/
public function versionCompare($a, $b, $operator, $compareBranches = false)
{
if (!isset(self::$transOpStr[$operator])) {
throw new \InvalidArgumentException(sprintf(
'Invalid operator "%s" given, expected one of: %s',
$operator,
implode(', ', self::getSupportedOperators())
));
}
$aIsBranch = strpos($a, 'dev-') === 0;
$bIsBranch = strpos($b, 'dev-') === 0;
if ($operator === '!=' && ($aIsBranch || $bIsBranch)) {
return $a !== $b;
}
if ($aIsBranch && $bIsBranch) {
return $operator === '==' && $a === $b;
}
// when branches are not comparable, we make sure dev branches never match anything
if (!$compareBranches && ($aIsBranch || $bIsBranch)) {
return false;
}
return \version_compare($a, $b, $operator);
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
if (strpos($this->version, 'dev-') === 0) {
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b && $v === %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
return 'false';
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('!$b || $v !== %s', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
return 'false';
}
if (self::OP_EQ === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('\version_compare($v, %s, \'==\')', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return sprintf('$b || \version_compare($v, %s, \'!=\')', \var_export($this->version, true));
}
return sprintf('!$b && \version_compare(%s, $v, \'%s\')', \var_export($this->version, true), self::$transOpInt[$otherOperator]);
}
if (self::OP_NE === $this->operator) {
if (self::OP_EQ === $otherOperator) {
return sprintf('$b || (!$b && \version_compare($v, %s, \'!=\'))', \var_export($this->version, true));
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
return '!$b';
}
if (self::OP_LT === $this->operator || self::OP_LE === $this->operator) {
if (self::OP_LT === $otherOperator || self::OP_LE === $otherOperator) {
return '!$b';
}
} else { // $this->operator must be self::OP_GT || self::OP_GE here
if (self::OP_GT === $otherOperator || self::OP_GE === $otherOperator) {
return '!$b';
}
}
if (self::OP_NE === $otherOperator) {
return 'true';
}
$codeComparison = sprintf('\version_compare($v, %s, \'%s\')', \var_export($this->version, true), self::$transOpInt[$this->operator]);
if ($this->operator === self::OP_LE) {
if ($otherOperator === self::OP_GT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
} elseif ($this->operator === self::OP_GE) {
if ($otherOperator === self::OP_LT) {
return sprintf('!$b && \version_compare($v, %s, \'!=\') && ', \var_export($this->version, true)) . $codeComparison;
}
}
return sprintf('!$b && %s', $codeComparison);
}
/**
* @param Constraint $provider
* @param bool $compareBranches
*
* @return bool
*/
public function matchSpecific(Constraint $provider, $compareBranches = false)
{
$noEqualOp = str_replace('=', '', self::$transOpInt[$this->operator]);
$providerNoEqualOp = str_replace('=', '', self::$transOpInt[$provider->operator]);
$isEqualOp = self::OP_EQ === $this->operator;
$isNonEqualOp = self::OP_NE === $this->operator;
$isProviderEqualOp = self::OP_EQ === $provider->operator;
$isProviderNonEqualOp = self::OP_NE === $provider->operator;
// '!=' operator is match when other operator is not '==' operator or version is not match
// these kinds of comparisons always have a solution
if ($isNonEqualOp || $isProviderNonEqualOp) {
if ($isNonEqualOp && !$isProviderNonEqualOp && !$isProviderEqualOp && strpos($provider->version, 'dev-') === 0) {
return false;
}
if ($isProviderNonEqualOp && !$isNonEqualOp && !$isEqualOp && strpos($this->version, 'dev-') === 0) {
return false;
}
if (!$isEqualOp && !$isProviderEqualOp) {
return true;
}
return $this->versionCompare($provider->version, $this->version, '!=', $compareBranches);
}
// an example for the condition is <= 2.0 & < 1.0
// these kinds of comparisons always have a solution
if ($this->operator !== self::OP_EQ && $noEqualOp === $providerNoEqualOp) {
return !(strpos($this->version, 'dev-') === 0 || strpos($provider->version, 'dev-') === 0);
}
$version1 = $isEqualOp ? $this->version : $provider->version;
$version2 = $isEqualOp ? $provider->version : $this->version;
$operator = $isEqualOp ? $provider->operator : $this->operator;
if ($this->versionCompare($version1, $version2, self::$transOpInt[$operator], $compareBranches)) {
// special case, e.g. require >= 1.0 and provide < 1.0
// 1.0 >= 1.0 but 1.0 is outside of the provided interval
return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp
&& self::$transOpInt[$this->operator] !== $noEqualOp
&& \version_compare($provider->version, $this->version, '=='));
}
return false;
}
/**
* @return string
*/
public function __toString()
{
return self::$transOpInt[$this->operator] . ' ' . $this->version;
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
$this->extractBounds();
return $this->lowerBound;
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
$this->extractBounds();
return $this->upperBound;
}
/**
* @return void
*/
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
// Branches
if (strpos($this->version, 'dev-') === 0) {
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
return;
}
switch ($this->operator) {
case self::OP_EQ:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_LT:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, false);
break;
case self::OP_LE:
$this->lowerBound = Bound::zero();
$this->upperBound = new Bound($this->version, true);
break;
case self::OP_GT:
$this->lowerBound = new Bound($this->version, false);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_GE:
$this->lowerBound = new Bound($this->version, true);
$this->upperBound = Bound::positiveInfinity();
break;
case self::OP_NE:
$this->lowerBound = Bound::zero();
$this->upperBound = Bound::positiveInfinity();
break;
}
}
}

View File

@ -0,0 +1,75 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* DO NOT IMPLEMENT this interface. It is only meant for usage as a type hint
* in libraries relying on composer/semver but creating your own constraint class
* that implements this interface is not a supported use case and will cause the
* composer/semver components to return unexpected results.
*/
interface ConstraintInterface
{
/**
* Checks whether the given constraint intersects in any way with this constraint
*
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider);
/**
* Provides a compiled version of the constraint for the given operator
* The compiled version must be a PHP expression.
* Executor of compile version must provide 2 variables:
* - $v = the string version to compare with
* - $b = whether or not the version is a non-comparable branch (starts with "dev-")
*
* @see Constraint::OP_* for the list of available operators.
* @example return '!$b && version_compare($v, '1.0', '>')';
*
* @param int $otherOperator one Constraint::OP_*
*
* @return string
*
* @phpstan-param Constraint::OP_* $otherOperator
*/
public function compile($otherOperator);
/**
* @return Bound
*/
public function getUpperBound();
/**
* @return Bound
*/
public function getLowerBound();
/**
* @return string
*/
public function getPrettyString();
/**
* @param string|null $prettyString
*
* @return void
*/
public function setPrettyString($prettyString);
/**
* @return string
*/
public function __toString();
}

View File

@ -0,0 +1,85 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines the absence of a constraint.
*
* This constraint matches everything.
*/
class MatchAllConstraint implements ConstraintInterface
{
/** @var string|null */
protected $prettyString;
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
return true;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
return 'true';
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
return '*';
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
return Bound::positiveInfinity();
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
return Bound::zero();
}
}

View File

@ -0,0 +1,83 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Blackhole of constraints, nothing escapes it
*/
class MatchNoneConstraint implements ConstraintInterface
{
/** @var string|null */
protected $prettyString;
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
return false;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
return 'false';
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
return '[]';
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
return new Bound('0.0.0.0-dev', false);
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
return new Bound('0.0.0.0-dev', false);
}
}

View File

@ -0,0 +1,325 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver\Constraint;
/**
* Defines a conjunctive or disjunctive set of constraints.
*/
class MultiConstraint implements ConstraintInterface
{
/**
* @var ConstraintInterface[]
* @phpstan-var non-empty-array<ConstraintInterface>
*/
protected $constraints;
/** @var string|null */
protected $prettyString;
/** @var string|null */
protected $string;
/** @var bool */
protected $conjunctive;
/** @var Bound|null */
protected $lowerBound;
/** @var Bound|null */
protected $upperBound;
/**
* @param ConstraintInterface[] $constraints A set of constraints
* @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive
*
* @throws \InvalidArgumentException If less than 2 constraints are passed
*/
public function __construct(array $constraints, $conjunctive = true)
{
if (\count($constraints) < 2) {
throw new \InvalidArgumentException(
'Must provide at least two constraints for a MultiConstraint. Use '.
'the regular Constraint class for one constraint only or MatchAllConstraint for none. You may use '.
'MultiConstraint::create() which optimizes and handles those cases automatically.'
);
}
$this->constraints = $constraints;
$this->conjunctive = $conjunctive;
}
/**
* @return ConstraintInterface[]
*/
public function getConstraints()
{
return $this->constraints;
}
/**
* @return bool
*/
public function isConjunctive()
{
return $this->conjunctive;
}
/**
* @return bool
*/
public function isDisjunctive()
{
return !$this->conjunctive;
}
/**
* {@inheritDoc}
*/
public function compile($otherOperator)
{
$parts = array();
foreach ($this->constraints as $constraint) {
$code = $constraint->compile($otherOperator);
if ($code === 'true') {
if (!$this->conjunctive) {
return 'true';
}
} elseif ($code === 'false') {
if ($this->conjunctive) {
return 'false';
}
} else {
$parts[] = '('.$code.')';
}
}
if (!$parts) {
return $this->conjunctive ? 'true' : 'false';
}
return $this->conjunctive ? implode('&&', $parts) : implode('||', $parts);
}
/**
* @param ConstraintInterface $provider
*
* @return bool
*/
public function matches(ConstraintInterface $provider)
{
if (false === $this->conjunctive) {
foreach ($this->constraints as $constraint) {
if ($provider->matches($constraint)) {
return true;
}
}
return false;
}
// when matching a conjunctive and a disjunctive multi constraint we have to iterate over the disjunctive one
// otherwise we'd return true if different parts of the disjunctive constraint match the conjunctive one
// which would lead to incorrect results, e.g. [>1 and <2] would match [<1 or >2] although they do not intersect
if ($provider instanceof MultiConstraint && $provider->isDisjunctive()) {
return $provider->matches($this);
}
foreach ($this->constraints as $constraint) {
if (!$provider->matches($constraint)) {
return false;
}
}
return true;
}
/**
* {@inheritDoc}
*/
public function setPrettyString($prettyString)
{
$this->prettyString = $prettyString;
}
/**
* {@inheritDoc}
*/
public function getPrettyString()
{
if ($this->prettyString) {
return $this->prettyString;
}
return (string) $this;
}
/**
* {@inheritDoc}
*/
public function __toString()
{
if ($this->string !== null) {
return $this->string;
}
$constraints = array();
foreach ($this->constraints as $constraint) {
$constraints[] = (string) $constraint;
}
return $this->string = '[' . implode($this->conjunctive ? ' ' : ' || ', $constraints) . ']';
}
/**
* {@inheritDoc}
*/
public function getLowerBound()
{
$this->extractBounds();
if (null === $this->lowerBound) {
throw new \LogicException('extractBounds should have populated the lowerBound property');
}
return $this->lowerBound;
}
/**
* {@inheritDoc}
*/
public function getUpperBound()
{
$this->extractBounds();
if (null === $this->upperBound) {
throw new \LogicException('extractBounds should have populated the upperBound property');
}
return $this->upperBound;
}
/**
* Tries to optimize the constraints as much as possible, meaning
* reducing/collapsing congruent constraints etc.
* Does not necessarily return a MultiConstraint instance if
* things can be reduced to a simple constraint
*
* @param ConstraintInterface[] $constraints A set of constraints
* @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive
*
* @return ConstraintInterface
*/
public static function create(array $constraints, $conjunctive = true)
{
if (0 === \count($constraints)) {
return new MatchAllConstraint();
}
if (1 === \count($constraints)) {
return $constraints[0];
}
$optimized = self::optimizeConstraints($constraints, $conjunctive);
if ($optimized !== null) {
list($constraints, $conjunctive) = $optimized;
if (\count($constraints) === 1) {
return $constraints[0];
}
}
return new self($constraints, $conjunctive);
}
/**
* @param ConstraintInterface[] $constraints
* @param bool $conjunctive
* @return ?array
*
* @phpstan-return array{0: list<ConstraintInterface>, 1: bool}|null
*/
private static function optimizeConstraints(array $constraints, $conjunctive)
{
// parse the two OR groups and if they are contiguous we collapse
// them into one constraint
// [>= 1 < 2] || [>= 2 < 3] || [>= 3 < 4] => [>= 1 < 4]
if (!$conjunctive) {
$left = $constraints[0];
$mergedConstraints = array();
$optimized = false;
for ($i = 1, $l = \count($constraints); $i < $l; $i++) {
$right = $constraints[$i];
if (
$left instanceof self
&& $left->conjunctive
&& $right instanceof self
&& $right->conjunctive
&& \count($left->constraints) === 2
&& \count($right->constraints) === 2
&& ($left0 = (string) $left->constraints[0])
&& $left0[0] === '>' && $left0[1] === '='
&& ($left1 = (string) $left->constraints[1])
&& $left1[0] === '<'
&& ($right0 = (string) $right->constraints[0])
&& $right0[0] === '>' && $right0[1] === '='
&& ($right1 = (string) $right->constraints[1])
&& $right1[0] === '<'
&& substr($left1, 2) === substr($right0, 3)
) {
$optimized = true;
$left = new MultiConstraint(
array(
$left->constraints[0],
$right->constraints[1],
),
true);
} else {
$mergedConstraints[] = $left;
$left = $right;
}
}
if ($optimized) {
$mergedConstraints[] = $left;
return array($mergedConstraints, false);
}
}
// TODO: Here's the place to put more optimizations
return null;
}
/**
* @return void
*/
private function extractBounds()
{
if (null !== $this->lowerBound) {
return;
}
foreach ($this->constraints as $constraint) {
if (null === $this->lowerBound || null === $this->upperBound) {
$this->lowerBound = $constraint->getLowerBound();
$this->upperBound = $constraint->getUpperBound();
continue;
}
if ($constraint->getLowerBound()->compareTo($this->lowerBound, $this->isConjunctive() ? '>' : '<')) {
$this->lowerBound = $constraint->getLowerBound();
}
if ($constraint->getUpperBound()->compareTo($this->upperBound, $this->isConjunctive() ? '<' : '>')) {
$this->upperBound = $constraint->getUpperBound();
}
}
}
}

View File

@ -0,0 +1,98 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Interval
{
/** @var Constraint */
private $start;
/** @var Constraint */
private $end;
public function __construct(Constraint $start, Constraint $end)
{
$this->start = $start;
$this->end = $end;
}
/**
* @return Constraint
*/
public function getStart()
{
return $this->start;
}
/**
* @return Constraint
*/
public function getEnd()
{
return $this->end;
}
/**
* @return Constraint
*/
public static function fromZero()
{
static $zero;
if (null === $zero) {
$zero = new Constraint('>=', '0.0.0.0-dev');
}
return $zero;
}
/**
* @return Constraint
*/
public static function untilPositiveInfinity()
{
static $positiveInfinity;
if (null === $positiveInfinity) {
$positiveInfinity = new Constraint('<', PHP_INT_MAX.'.0.0.0');
}
return $positiveInfinity;
}
/**
* @return self
*/
public static function any()
{
return new self(self::fromZero(), self::untilPositiveInfinity());
}
/**
* @return array{'names': string[], 'exclude': bool}
*/
public static function anyDev()
{
// any == exclude nothing
return array('names' => array(), 'exclude' => true);
}
/**
* @return array{'names': string[], 'exclude': bool}
*/
public static function noDev()
{
// nothing == no names included
return array('names' => array(), 'exclude' => false);
}
}

View File

@ -0,0 +1,478 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MatchNoneConstraint;
use Composer\Semver\Constraint\MultiConstraint;
/**
* Helper class generating intervals from constraints
*
* This contains utilities for:
*
* - compacting an existing constraint which can be used to combine several into one
* by creating a MultiConstraint out of the many constraints you have.
*
* - checking whether one subset is a subset of another.
*
* Note: You should call clear to free memoization memory usage when you are done using this class
*/
class Intervals
{
/**
* @phpstan-var array<string, array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}>
*/
private static $intervalsCache = array();
/**
* @phpstan-var array<string, int>
*/
private static $opSortOrder = array(
'>=' => -3,
'<' => -2,
'>' => 2,
'<=' => 3,
);
/**
* Clears the memoization cache once you are done
*
* @return void
*/
public static function clear()
{
self::$intervalsCache = array();
}
/**
* Checks whether $candidate is a subset of $constraint
*
* @return bool
*/
public static function isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint)
{
if ($constraint instanceof MatchAllConstraint) {
return true;
}
if ($candidate instanceof MatchNoneConstraint || $constraint instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::get(new MultiConstraint(array($candidate, $constraint), true));
$candidateIntervals = self::get($candidate);
if (\count($intersectionIntervals['numeric']) !== \count($candidateIntervals['numeric'])) {
return false;
}
foreach ($intersectionIntervals['numeric'] as $index => $interval) {
if (!isset($candidateIntervals['numeric'][$index])) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getStart() !== (string) $interval->getStart()) {
return false;
}
if ((string) $candidateIntervals['numeric'][$index]->getEnd() !== (string) $interval->getEnd()) {
return false;
}
}
if ($intersectionIntervals['branches']['exclude'] !== $candidateIntervals['branches']['exclude']) {
return false;
}
if (\count($intersectionIntervals['branches']['names']) !== \count($candidateIntervals['branches']['names'])) {
return false;
}
foreach ($intersectionIntervals['branches']['names'] as $index => $name) {
if ($name !== $candidateIntervals['branches']['names'][$index]) {
return false;
}
}
return true;
}
/**
* Checks whether $a and $b have any intersection, equivalent to $a->matches($b)
*
* @return bool
*/
public static function haveIntersections(ConstraintInterface $a, ConstraintInterface $b)
{
if ($a instanceof MatchAllConstraint || $b instanceof MatchAllConstraint) {
return true;
}
if ($a instanceof MatchNoneConstraint || $b instanceof MatchNoneConstraint) {
return false;
}
$intersectionIntervals = self::generateIntervals(new MultiConstraint(array($a, $b), true), true);
return \count($intersectionIntervals['numeric']) > 0 || $intersectionIntervals['branches']['exclude'] || \count($intersectionIntervals['branches']['names']) > 0;
}
/**
* Attempts to optimize a MultiConstraint
*
* When merging MultiConstraints together they can get very large, this will
* compact it by looking at the real intervals covered by all the constraints
* and then creates a new constraint containing only the smallest amount of rules
* to match the same intervals.
*
* @return ConstraintInterface
*/
public static function compactConstraint(ConstraintInterface $constraint)
{
if (!$constraint instanceof MultiConstraint) {
return $constraint;
}
$intervals = self::generateIntervals($constraint);
$constraints = array();
$hasNumericMatchAll = false;
if (\count($intervals['numeric']) === 1 && (string) $intervals['numeric'][0]->getStart() === (string) Interval::fromZero() && (string) $intervals['numeric'][0]->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $intervals['numeric'][0]->getStart();
$hasNumericMatchAll = true;
} else {
$unEqualConstraints = array();
for ($i = 0, $count = \count($intervals['numeric']); $i < $count; $i++) {
$interval = $intervals['numeric'][$i];
// if current interval ends with < N and next interval begins with > N we can swap this out for != N
// but this needs to happen as a conjunctive expression together with the start of the current interval
// and end of next interval, so [>=M, <N] || [>N, <P] => [>=M, !=N, <P] but M/P can be skipped if
// they are zero/+inf
if ($interval->getEnd()->getOperator() === '<' && $i+1 < $count) {
$nextInterval = $intervals['numeric'][$i+1];
if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') {
// only add a start if we didn't already do so, can be skipped if we're looking at second
// interval in [>=M, <N] || [>N, <P] || [>P, <Q] where unEqualConstraints currently contains
// [>=M, !=N] already and we only want to add !=P right now
if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) {
$unEqualConstraints[] = $interval->getStart();
}
$unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion());
continue;
}
}
if (\count($unEqualConstraints) > 0) {
// this is where the end of the following interval of a != constraint is added as explained above
if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) {
$unEqualConstraints[] = $interval->getEnd();
}
// count is 1 if entire constraint is just one != expression
if (\count($unEqualConstraints) > 1) {
$constraints[] = new MultiConstraint($unEqualConstraints, true);
} else {
$constraints[] = $unEqualConstraints[0];
}
$unEqualConstraints = array();
continue;
}
// convert back >= x - <= x intervals to == x
if ($interval->getStart()->getVersion() === $interval->getEnd()->getVersion() && $interval->getStart()->getOperator() === '>=' && $interval->getEnd()->getOperator() === '<=') {
$constraints[] = new Constraint('==', $interval->getStart()->getVersion());
continue;
}
if ((string) $interval->getStart() === (string) Interval::fromZero()) {
$constraints[] = $interval->getEnd();
} elseif ((string) $interval->getEnd() === (string) Interval::untilPositiveInfinity()) {
$constraints[] = $interval->getStart();
} else {
$constraints[] = new MultiConstraint(array($interval->getStart(), $interval->getEnd()), true);
}
}
}
$devConstraints = array();
if (0 === \count($intervals['branches']['names'])) {
if ($intervals['branches']['exclude']) {
if ($hasNumericMatchAll) {
return new MatchAllConstraint;
}
// otherwise constraint should contain a != operator and already cover this
}
} else {
foreach ($intervals['branches']['names'] as $branchName) {
if ($intervals['branches']['exclude']) {
$devConstraints[] = new Constraint('!=', $branchName);
} else {
$devConstraints[] = new Constraint('==', $branchName);
}
}
// excluded branches, e.g. != dev-foo are conjunctive with the interval, so
// > 2.0 != dev-foo must return a conjunctive constraint
if ($intervals['branches']['exclude']) {
if (\count($constraints) > 1) {
return new MultiConstraint(array_merge(
array(new MultiConstraint($constraints, false)),
$devConstraints
), true);
}
if (\count($constraints) === 1 && (string)$constraints[0] === (string)Interval::fromZero()) {
if (\count($devConstraints) > 1) {
return new MultiConstraint($devConstraints, true);
}
return $devConstraints[0];
}
return new MultiConstraint(array_merge($constraints, $devConstraints), true);
}
// otherwise devConstraints contains a list of == operators for branches which are disjunctive with the
// rest of the constraint
$constraints = array_merge($constraints, $devConstraints);
}
if (\count($constraints) > 1) {
return new MultiConstraint($constraints, false);
}
if (\count($constraints) === 1) {
return $constraints[0];
}
return new MatchNoneConstraint;
}
/**
* Creates an array of numeric intervals and branch constraints representing a given constraint
*
* if the returned numeric array is empty it means the constraint matches nothing in the numeric range (0 - +inf)
* if the returned branches array is empty it means no dev-* versions are matched
* if a constraint matches all possible dev-* versions, branches will contain Interval::anyDev()
*
* @return array
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
public static function get(ConstraintInterface $constraint)
{
$key = (string) $constraint;
if (!isset(self::$intervalsCache[$key])) {
self::$intervalsCache[$key] = self::generateIntervals($constraint);
}
return self::$intervalsCache[$key];
}
/**
* @param bool $stopOnFirstValidInterval
*
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
private static function generateIntervals(ConstraintInterface $constraint, $stopOnFirstValidInterval = false)
{
if ($constraint instanceof MatchAllConstraint) {
return array('numeric' => array(new Interval(Interval::fromZero(), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev());
}
if ($constraint instanceof MatchNoneConstraint) {
return array('numeric' => array(), 'branches' => array('names' => array(), 'exclude' => false));
}
if ($constraint instanceof Constraint) {
return self::generateSingleConstraintIntervals($constraint);
}
if (!$constraint instanceof MultiConstraint) {
throw new \UnexpectedValueException('The constraint passed in should be an MatchAllConstraint, Constraint or MultiConstraint instance, got '.\get_class($constraint).'.');
}
$constraints = $constraint->getConstraints();
$numericGroups = array();
$constraintBranches = array();
foreach ($constraints as $c) {
$res = self::get($c);
$numericGroups[] = $res['numeric'];
$constraintBranches[] = $res['branches'];
}
if ($constraint->isDisjunctive()) {
$branches = Interval::noDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
// disjunctive constraint, so only exclude what's excluded in all constraints
// !=a,!=b || !=b,!=c => !=b
$branches['names'] = array_intersect($branches['names'], $b['names']);
} else {
// disjunctive constraint so exclude all names which are not explicitly included in the alternative
// (==b || ==c) || !=a,!=b => !=a
$branches['exclude'] = true;
$branches['names'] = array_diff($b['names'], $branches['names']);
}
} else {
if ($branches['exclude']) {
// disjunctive constraint so exclude all names which are not explicitly included in the alternative
// !=a,!=b || (==b || ==c) => !=a
$branches['names'] = array_diff($branches['names'], $b['names']);
} else {
// disjunctive constraint, so just add all the other branches
// (==a || ==b) || ==c => ==a || ==b || ==c
$branches['names'] = array_merge($branches['names'], $b['names']);
}
}
}
} else {
$branches = Interval::anyDev();
foreach ($constraintBranches as $b) {
if ($b['exclude']) {
if ($branches['exclude']) {
// conjunctive, so just add all branch names to be excluded
// !=a && !=b => !=a,!=b
$branches['names'] = array_merge($branches['names'], $b['names']);
} else {
// conjunctive, so only keep included names which are not excluded
// (==a||==c) && !=a,!=b => ==c
$branches['names'] = array_diff($branches['names'], $b['names']);
}
} else {
if ($branches['exclude']) {
// conjunctive, so only keep included names which are not excluded
// !=a,!=b && (==a||==c) => ==c
$branches['names'] = array_diff($b['names'], $branches['names']);
$branches['exclude'] = false;
} else {
// conjunctive, so only keep names that are included in both
// (==a||==b) && (==a||==c) => ==a
$branches['names'] = array_intersect($branches['names'], $b['names']);
}
}
}
}
$branches['names'] = array_unique($branches['names']);
if (\count($numericGroups) === 1) {
return array('numeric' => $numericGroups[0], 'branches' => $branches);
}
$borders = array();
foreach ($numericGroups as $group) {
foreach ($group as $interval) {
$borders[] = array('version' => $interval->getStart()->getVersion(), 'operator' => $interval->getStart()->getOperator(), 'side' => 'start');
$borders[] = array('version' => $interval->getEnd()->getVersion(), 'operator' => $interval->getEnd()->getOperator(), 'side' => 'end');
}
}
$opSortOrder = self::$opSortOrder;
usort($borders, function ($a, $b) use ($opSortOrder) {
$order = version_compare($a['version'], $b['version']);
if ($order === 0) {
return $opSortOrder[$a['operator']] - $opSortOrder[$b['operator']];
}
return $order;
});
$activeIntervals = 0;
$intervals = array();
$index = 0;
$activationThreshold = $constraint->isConjunctive() ? \count($numericGroups) : 1;
$start = null;
foreach ($borders as $border) {
if ($border['side'] === 'start') {
$activeIntervals++;
} else {
$activeIntervals--;
}
if (!$start && $activeIntervals >= $activationThreshold) {
$start = new Constraint($border['operator'], $border['version']);
} elseif ($start && $activeIntervals < $activationThreshold) {
// filter out invalid intervals like > x - <= x, or >= x - < x
if (
version_compare($start->getVersion(), $border['version'], '=')
&& (
($start->getOperator() === '>' && $border['operator'] === '<=')
|| ($start->getOperator() === '>=' && $border['operator'] === '<')
)
) {
unset($intervals[$index]);
} else {
$intervals[$index] = new Interval($start, new Constraint($border['operator'], $border['version']));
$index++;
if ($stopOnFirstValidInterval) {
break;
}
}
$start = null;
}
}
return array('numeric' => $intervals, 'branches' => $branches);
}
/**
* @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}}
*/
private static function generateSingleConstraintIntervals(Constraint $constraint)
{
$op = $constraint->getOperator();
// handle branch constraints first
if (strpos($constraint->getVersion(), 'dev-') === 0) {
$intervals = array();
$branches = array('names' => array(), 'exclude' => false);
// != dev-foo means any numeric version may match, we treat >/< like != they are not really defined for branches
if ($op === '!=') {
$intervals[] = new Interval(Interval::fromZero(), Interval::untilPositiveInfinity());
$branches = array('names' => array($constraint->getVersion()), 'exclude' => true);
} elseif ($op === '==') {
$branches['names'][] = $constraint->getVersion();
}
return array(
'numeric' => $intervals,
'branches' => $branches,
);
}
if ($op[0] === '>') { // > & >=
return array('numeric' => array(new Interval($constraint, Interval::untilPositiveInfinity())), 'branches' => Interval::noDev());
}
if ($op[0] === '<') { // < & <=
return array('numeric' => array(new Interval(Interval::fromZero(), $constraint)), 'branches' => Interval::noDev());
}
if ($op === '!=') {
// convert !=x to intervals of 0 - <x && >x - +inf + dev*
return array('numeric' => array(
new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())),
new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity()),
), 'branches' => Interval::anyDev());
}
// convert ==x to an interval of >=x - <=x
return array('numeric' => array(
new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion())),
), 'branches' => Interval::noDev());
}
}

View File

@ -0,0 +1,129 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\Constraint;
class Semver
{
const SORT_ASC = 1;
const SORT_DESC = -1;
/** @var VersionParser */
private static $versionParser;
/**
* Determine if given version satisfies given constraints.
*
* @param string $version
* @param string $constraints
*
* @return bool
*/
public static function satisfies($version, $constraints)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$provider = new Constraint('==', $versionParser->normalize($version));
$parsedConstraints = $versionParser->parseConstraints($constraints);
return $parsedConstraints->matches($provider);
}
/**
* Return all versions that satisfy given constraints.
*
* @param string[] $versions
* @param string $constraints
*
* @return string[]
*/
public static function satisfiedBy(array $versions, $constraints)
{
$versions = array_filter($versions, function ($version) use ($constraints) {
return Semver::satisfies($version, $constraints);
});
return array_values($versions);
}
/**
* Sort given array of versions.
*
* @param string[] $versions
*
* @return string[]
*/
public static function sort(array $versions)
{
return self::usort($versions, self::SORT_ASC);
}
/**
* Sort given array of versions in reverse.
*
* @param string[] $versions
*
* @return string[]
*/
public static function rsort(array $versions)
{
return self::usort($versions, self::SORT_DESC);
}
/**
* @param string[] $versions
* @param int $direction
*
* @return string[]
*/
private static function usort(array $versions, $direction)
{
if (null === self::$versionParser) {
self::$versionParser = new VersionParser();
}
$versionParser = self::$versionParser;
$normalized = array();
// Normalize outside of usort() scope for minor performance increase.
// Creates an array of arrays: [[normalized, key], ...]
foreach ($versions as $key => $version) {
$normalizedVersion = $versionParser->normalize($version);
$normalizedVersion = $versionParser->normalizeDefaultBranch($normalizedVersion);
$normalized[] = array($normalizedVersion, $key);
}
usort($normalized, function (array $left, array $right) use ($direction) {
if ($left[0] === $right[0]) {
return 0;
}
if (Comparator::lessThan($left[0], $right[0])) {
return -$direction;
}
return $direction;
});
// Recreate input array, using the original indexes which are now in sorted order.
$sorted = array();
foreach ($normalized as $item) {
$sorted[] = $versions[$item[1]];
}
return $sorted;
}
}

View File

@ -0,0 +1,586 @@
<?php
/*
* This file is part of composer/semver.
*
* (c) Composer <https://github.com/composer>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Composer\Semver;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
use Composer\Semver\Constraint\Constraint;
/**
* Version parser.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class VersionParser
{
/**
* Regex to match pre-release data (sort of).
*
* Due to backwards compatibility:
* - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted.
* - Only stabilities as recognized by Composer are allowed to precede a numerical identifier.
* - Numerical-only pre-release identifiers are not supported, see tests.
*
* |--------------|
* [major].[minor].[patch] -[pre-release] +[build-metadata]
*
* @var string
*/
private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\d+)*+)?)?([.-]?dev)?';
/** @var string */
private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev';
/**
* Returns the stability of a version.
*
* @param string $version
*
* @return string
* @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev'
*/
public static function parseStability($version)
{
$version = (string) preg_replace('{#.+$}', '', (string) $version);
if (strpos($version, 'dev-') === 0 || '-dev' === substr($version, -4)) {
return 'dev';
}
preg_match('{' . self::$modifierRegex . '(?:\+.*)?$}i', strtolower($version), $match);
if (!empty($match[3])) {
return 'dev';
}
if (!empty($match[1])) {
if ('beta' === $match[1] || 'b' === $match[1]) {
return 'beta';
}
if ('alpha' === $match[1] || 'a' === $match[1]) {
return 'alpha';
}
if ('rc' === $match[1]) {
return 'RC';
}
}
return 'stable';
}
/**
* @param string $stability
*
* @return string
*/
public static function normalizeStability($stability)
{
$stability = strtolower((string) $stability);
return $stability === 'rc' ? 'RC' : $stability;
}
/**
* Normalizes a version string to be able to perform comparisons on it.
*
* @param string $version
* @param ?string $fullVersion optional complete version string to give more context
*
* @throws \UnexpectedValueException
*
* @return string
*/
public function normalize($version, $fullVersion = null)
{
$version = trim((string) $version);
$origVersion = $version;
if (null === $fullVersion) {
$fullVersion = $version;
}
// strip off aliasing
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $version, $match)) {
$version = $match[1];
}
// strip off stability flag
if (preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) {
$version = substr($version, 0, strlen($version) - strlen($match[0]));
}
// normalize master/trunk/default branches to dev-name for BC with 1.x as these used to be valid constraints
if (\in_array($version, array('master', 'trunk', 'default'), true)) {
$version = 'dev-' . $version;
}
// if requirement is branch-like, use full name
if (stripos($version, 'dev-') === 0) {
return 'dev-' . substr($version, 4);
}
// strip off build metadata
if (preg_match('{^([^,\s+]++)\+[^\s]++$}', $version, $match)) {
$version = $match[1];
}
// match classical versioning
if (preg_match('{^v?(\d{1,5})(\.\d++)?(\.\d++)?(\.\d++)?' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = $matches[1]
. (!empty($matches[2]) ? $matches[2] : '.0')
. (!empty($matches[3]) ? $matches[3] : '.0')
. (!empty($matches[4]) ? $matches[4] : '.0');
$index = 5;
// match date(time) based versioning
} elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) {
$version = preg_replace('{\D}', '.', $matches[1]);
$index = 2;
}
// add version modifiers if a version was matched
if (isset($index)) {
if (!empty($matches[$index])) {
if ('stable' === $matches[$index]) {
return $version;
}
$version .= '-' . $this->expandStability($matches[$index]) . (isset($matches[$index + 1]) && '' !== $matches[$index + 1] ? ltrim($matches[$index + 1], '.-') : '');
}
if (!empty($matches[$index + 2])) {
$version .= '-dev';
}
return $version;
}
// match dev branches
if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
try {
$normalized = $this->normalizeBranch($match[1]);
// a branch ending with -dev is only valid if it is numeric
// if it gets prefixed with dev- it means the branch name should
// have had a dev- prefix already when passed to normalize
if (strpos($normalized, 'dev-') === false) {
return $normalized;
}
} catch (\Exception $e) {
}
}
$extraMessage = '';
if (preg_match('{ +as +' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))?$}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias must be an exact version';
} elseif (preg_match('{^' . preg_quote($version) . '(?:@(?:'.self::$stabilitiesRegex.'))? +as +}', $fullVersion)) {
$extraMessage = ' in "' . $fullVersion . '", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
}
throw new \UnexpectedValueException('Invalid version string "' . $origVersion . '"' . $extraMessage);
}
/**
* Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison.
*
* @param string $branch Branch name (e.g. 2.1.x-dev)
*
* @return string|false Numeric prefix if present (e.g. 2.1.) or false
*/
public function parseNumericAliasPrefix($branch)
{
if (preg_match('{^(?P<version>(\d++\\.)*\d++)(?:\.x)?-dev$}i', (string) $branch, $matches)) {
return $matches['version'] . '.';
}
return false;
}
/**
* Normalizes a branch name to be able to perform comparisons on it.
*
* @param string $name
*
* @return string
*/
public function normalizeBranch($name)
{
$name = trim((string) $name);
if (preg_match('{^v?(\d++)(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?(\.(?:\d++|[xX*]))?$}i', $name, $matches)) {
$version = '';
for ($i = 1; $i < 5; ++$i) {
$version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
}
return str_replace('x', '9999999', $version) . '-dev';
}
return 'dev-' . $name;
}
/**
* Normalizes a default branch name (i.e. master on git) to 9999999-dev.
*
* @param string $name
*
* @return string
*
* @deprecated No need to use this anymore in theory, Composer 2 does not normalize any branch names to 9999999-dev anymore
*/
public function normalizeDefaultBranch($name)
{
if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') {
return '9999999-dev';
}
return (string) $name;
}
/**
* Parses a constraint string into MultiConstraint and/or Constraint objects.
*
* @param string $constraints
*
* @return ConstraintInterface
*/
public function parseConstraints($constraints)
{
$prettyConstraint = (string) $constraints;
$orConstraints = preg_split('{\s*\|\|?\s*}', trim((string) $constraints));
if (false === $orConstraints) {
throw new \RuntimeException('Failed to preg_split string: '.$constraints);
}
$orGroups = array();
foreach ($orConstraints as $constraints) {
$andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
if (false === $andConstraints) {
throw new \RuntimeException('Failed to preg_split string: '.$constraints);
}
if (\count($andConstraints) > 1) {
$constraintObjects = array();
foreach ($andConstraints as $constraint) {
foreach ($this->parseConstraint($constraint) as $parsedConstraint) {
$constraintObjects[] = $parsedConstraint;
}
}
} else {
$constraintObjects = $this->parseConstraint($andConstraints[0]);
}
if (1 === \count($constraintObjects)) {
$constraint = $constraintObjects[0];
} else {
$constraint = new MultiConstraint($constraintObjects);
}
$orGroups[] = $constraint;
}
$constraint = MultiConstraint::create($orGroups, false);
$constraint->setPrettyString($prettyConstraint);
return $constraint;
}
/**
* @param string $constraint
*
* @throws \UnexpectedValueException
*
* @return array
*
* @phpstan-return non-empty-array<ConstraintInterface>
*/
private function parseConstraint($constraint)
{
// strip off aliasing
if (preg_match('{^([^,\s]++) ++as ++([^,\s]++)$}', $constraint, $match)) {
$constraint = $match[1];
}
// strip @stability flags, and keep it for later use
if (preg_match('{^([^,\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) {
$constraint = '' !== $match[1] ? $match[1] : '*';
if ($match[2] !== 'stable') {
$stabilityModifier = $match[2];
}
}
// get rid of #refs as those are used by composer only
if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraint, $match)) {
$constraint = $match[1];
}
if (preg_match('{^(v)?[xX*](\.[xX*])*$}i', $constraint, $match)) {
if (!empty($match[1]) || !empty($match[2])) {
return array(new Constraint('>=', '0.0.0.0-dev'));
}
return array(new MatchAllConstraint());
}
$versionRegex = 'v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.(\d++))?(?:' . self::$modifierRegex . '|\.([xX*][.-]?dev))(?:\+[^\s]+)?';
// Tilde Range
//
// Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous
// version, to ensure that unstable instances of the current version are allowed. However, if a stability
// suffix is added to the constraint, then a >= match on the current version is used instead.
if (preg_match('{^~>?' . $versionRegex . '$}i', $constraint, $matches)) {
if (strpos($constraint, '~>') === 0) {
throw new \UnexpectedValueException(
'Could not parse version constraint ' . $constraint . ': ' .
'Invalid operator "~>", you probably meant to use the "~" operator'
);
}
// Work out which position in the version we are operating at
if (isset($matches[4]) && '' !== $matches[4] && null !== $matches[4]) {
$position = 4;
} elseif (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
// when matching 2.x-dev or 3.0.x-dev we have to shift the second or third number, despite no second/third number matching above
if (!empty($matches[8])) {
$position++;
}
// Calculate the stability suffix
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
// For upper bound, we increment the position of one more significance,
// but highPosition = 0 would be illegal
$highPosition = max(1, $position - 1);
$highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
// Caret Range
//
// Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple.
// In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for
// versions 0.X >=0.1.0, and no updates for versions 0.0.X
if (preg_match('{^\^' . $versionRegex . '($)}i', $constraint, $matches)) {
// Work out which position in the version we are operating at
if ('0' !== $matches[1] || '' === $matches[2] || null === $matches[2]) {
$position = 1;
} elseif ('0' !== $matches[2] || '' === $matches[3] || null === $matches[3]) {
$position = 2;
} else {
$position = 3;
}
// Calculate the stability suffix
$stabilitySuffix = '';
if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) {
$stabilitySuffix .= '-dev';
}
$lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
$lowerBound = new Constraint('>=', $lowVersion);
// For upper bound, we increment the position of one more significance,
// but highPosition = 0 would be illegal
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
return array(
$lowerBound,
$upperBound,
);
}
// X Range
//
// Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple.
// A partial version range is treated as an X-Range, so the special character is in fact optional.
if (preg_match('{^v?(\d++)(?:\.(\d++))?(?:\.(\d++))?(?:\.[xX*])++$}', $constraint, $matches)) {
if (isset($matches[3]) && '' !== $matches[3] && null !== $matches[3]) {
$position = 3;
} elseif (isset($matches[2]) && '' !== $matches[2] && null !== $matches[2]) {
$position = 2;
} else {
$position = 1;
}
$lowVersion = $this->manipulateVersionString($matches, $position) . '-dev';
$highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
if ($lowVersion === '0.0.0.0-dev') {
return array(new Constraint('<', $highVersion));
}
return array(
new Constraint('>=', $lowVersion),
new Constraint('<', $highVersion),
);
}
// Hyphen Range
//
// Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range,
// then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in
// the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but
// nothing that would be greater than the provided tuple parts.
if (preg_match('{^(?P<from>' . $versionRegex . ') +- +(?P<to>' . $versionRegex . ')($)}i', $constraint, $matches)) {
// Calculate the stability suffix
$lowStabilitySuffix = '';
if (empty($matches[6]) && empty($matches[8]) && empty($matches[9])) {
$lowStabilitySuffix = '-dev';
}
$lowVersion = $this->normalize($matches['from']);
$lowerBound = new Constraint('>=', $lowVersion . $lowStabilitySuffix);
$empty = function ($x) {
return ($x === 0 || $x === '0') ? false : empty($x);
};
if ((!$empty($matches[12]) && !$empty($matches[13])) || !empty($matches[15]) || !empty($matches[17]) || !empty($matches[18])) {
$highVersion = $this->normalize($matches['to']);
$upperBound = new Constraint('<=', $highVersion);
} else {
$highMatch = array('', $matches[11], $matches[12], $matches[13], $matches[14]);
// validate to version
$this->normalize($matches['to']);
$highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev';
$upperBound = new Constraint('<', $highVersion);
}
return array(
$lowerBound,
$upperBound,
);
}
// Basic Comparators
if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
try {
try {
$version = $this->normalize($matches[2]);
} catch (\UnexpectedValueException $e) {
// recover from an invalid constraint like foobar-dev which should be dev-foobar
// except if the constraint uses a known operator, in which case it must be a parse error
if (substr($matches[2], -4) === '-dev' && preg_match('{^[0-9a-zA-Z-./]+$}', $matches[2])) {
$version = $this->normalize('dev-'.substr($matches[2], 0, -4));
} else {
throw $e;
}
}
$op = $matches[1] ?: '=';
if ($op !== '==' && $op !== '=' && !empty($stabilityModifier) && self::parseStability($version) === 'stable') {
$version .= '-' . $stabilityModifier;
} elseif ('<' === $op || '>=' === $op) {
if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
if (strpos($matches[2], 'dev-') !== 0) {
$version .= '-dev';
}
}
}
return array(new Constraint($matches[1] ?: '=', $version));
} catch (\Exception $e) {
}
}
$message = 'Could not parse version constraint ' . $constraint;
if (isset($e)) {
$message .= ': ' . $e->getMessage();
}
throw new \UnexpectedValueException($message);
}
/**
* Increment, decrement, or simply pad a version number.
*
* Support function for {@link parseConstraint()}
*
* @param array $matches Array with version parts in array indexes 1,2,3,4
* @param int $position 1,2,3,4 - which segment of the version to increment/decrement
* @param int $increment
* @param string $pad The string to pad version parts after $position
*
* @return string|null The new version
*
* @phpstan-param string[] $matches
*/
private function manipulateVersionString(array $matches, $position, $increment = 0, $pad = '0')
{
for ($i = 4; $i > 0; --$i) {
if ($i > $position) {
$matches[$i] = $pad;
} elseif ($i === $position && $increment) {
$matches[$i] += $increment;
// If $matches[$i] was 0, carry the decrement
if ($matches[$i] < 0) {
$matches[$i] = $pad;
--$position;
// Return null on a carry overflow
if ($i === 1) {
return null;
}
}
}
}
return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
}
/**
* Expand shorthand stability string to long version.
*
* @param string $stability
*
* @return string
*/
private function expandStability($stability)
{
$stability = strtolower($stability);
switch ($stability) {
case 'a':
return 'alpha';
case 'b':
return 'beta';
case 'p':
case 'pl':
return 'patch';
case 'rc':
return 'RC';
default:
return $stability;
}
}
}

View File

@ -0,0 +1,18 @@
use-sort:
group:
- _main
group-type: each
sort-type: alph
sort-direction: asc
header: |
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/

View File

@ -0,0 +1,73 @@
name: PHP
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
run:
runs-on: ubuntu-latest
services:
mysql:
image: mysql:5.7
ports:
- 3306:3306
env:
MYSQL_ALLOW_EMPTY_PASSWORD: yes
redis:
image: redis:6.0
ports:
- 6379:6379
mongo:
image: mongo:4.2-bionic
ports:
- 27017:27017
memcached:
image: memcached:1.6
ports:
- 11211:11211
strategy:
fail-fast: false
matrix:
include:
- php: 7.2
composer: '--prefer-lowest'
desc: "Lowest versions"
- php: 7.4
composer: '--prefer-lowest'
desc: "Lowest versions"
- php: 7.2
- php: 7.3
- php: 7.4
coverage: '--coverage-clover /tmp/clover.xml'
- php: 8.0
name: PHP ${{ matrix.php }} ${{ matrix.desc }}
steps:
- uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: xdebug
extensions: apcu, mongodb, memcached
ini-values: apc.enable_cli=1,mysqli.default_host=127.0.0.1,mysqli.default_port=3306,mysqli.default_user=root
- name: Validate composer.json and composer.lock
run: composer validate
- name: Install dependencies
run: composer update --prefer-dist --no-progress ${{ matrix.composer }}
- name: Run PHPUnit
run: vendor/bin/phpunit ${{ matrix.coverage }}
- name: Upload coverage to Scrutinizer
if: ${{ matrix.coverage }}
run: >
wget https://scrutinizer-ci.com/ocular.phar -O "/tmp/ocular.phar" &&
php "/tmp/ocular.phar" code-coverage:upload --format=php-clover /tmp/clover.xml

View File

@ -0,0 +1,9 @@
/build
/composer.lock
/tests/config.json
/vendor
/.idea
/TODO.md
*~
*.swp
/.phpunit.result.cache

View File

@ -0,0 +1,31 @@
#language: php
checks:
php: true
filter:
excluded_paths:
- tests
build:
nodes:
analysis:
environment:
php:
version: 7.4
pecl_extensions:
- apcu
- mongodb
- memcached
mysql: false
postgresql: false
redis: false
mongodb: false
tests:
override:
- phpcs-run src
-
command: vendor/bin/phpstan analyze --error-format=checkstyle | sed '/^\s*$/d' > phpstan-checkstyle.xml
analysis:
file: phpstan-checkstyle.xml
format: 'general-checkstyle'
- php-scrutinizer-run
tools:
external_code_coverage: true

19
msd/vendor/desarrolla2/cache/LICENSE vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2012-2013 Desarrolla2 - http://desarrolla2.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.

174
msd/vendor/desarrolla2/cache/README.md vendored Normal file
View File

@ -0,0 +1,174 @@
# Desarolla2 Cache
A **simple cache** library, implementing the [PSR-16](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md) standard using **immutable** objects.
![life-is-hard-cache-is](https://user-images.githubusercontent.com/100821/41566888-ecd60cde-735d-11e8-893f-da42b2cd65e7.jpg)
Caching is typically used throughout an applicatiton. Immutability ensure that modifying the cache behaviour in one
location doesn't result in unexpected behaviour due to changes in unrelated code.
_Desarolla2 Cache aims to be the most complete, correct and best performing PSR-16 implementation available._
[![Latest version][ico-version]][link-packagist]
[![Latest version][ico-pre-release]][link-packagist]
[![Software License][ico-license]][link-license]
[![Build Status][ico-github-actions]][link-github-actions]
[![Coverage Status][ico-coverage]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-scrutinizer]
[![Total Downloads][ico-downloads]][link-downloads]
[![Today Downloads][ico-today-downloads]][link-downloads]
[![Gitter][ico-gitter]][link-gitter]
## Installation
```
composer require desarrolla2/cache
```
## Usage
``` php
use Desarrolla2\Cache\Memory as Cache;
$cache = new Cache();
$value = $cache->get('key');
if (!isset($value)) {
$value = do_something();
$cache->set('key', $value, 3600);
}
echo $value;
```
## Adapters
* [Apcu](docs/implementations/apcu.md)
* [File](docs/implementations/file.md)
* [Memcached](docs/implementations/memcached.md)
* [Memory](docs/implementations/memory.md)
* [MongoDB](docs/implementations/mongodb.md)
* [Mysqli](docs/implementations/mysqli.md)
* [NotCache](docs/implementations/notcache.md)
* [PhpFile](docs/implementations/phpfile.md)
* [Predis](docs/implementations/predis.md)
The following implementation allows you to combine cache adapters.
* [Chain](docs/implementations/chain.md)
[Other implementations][todo-implementations] are planned. Please vote or
provide a PR to speed up the process of adding the to this library.
[todo-implementations]: https://github.com/desarrolla2/Cache/issues?q=is%3Aissue+is%3Aopen+label%3Aadapter
### Options
You can set options for cache using the `withOption` or `withOptions` method.
Note that all cache objects are immutable, setting an option creates a new
object.
#### TTL
All cache implementations support the `ttl` option. This sets the default
time (in seconds) that cache will survive. It defaults to one hour (3600
seconds).
Setting the TTL to 0 or a negative number, means the cache should live forever.
## Methods
Each cache implementation has the following `Psr\SimpleCache\CacheInterface`
methods:
##### `get(string $key [, mixed $default])`
Retrieve the value corresponding to a provided key
##### `has(string $key)`
Retrieve the if value corresponding to a provided key exist
##### `set(string $key, mixed $value [, int $ttl])`
Add a value to the cache under a unique key
##### `delete(string $key)`
Delete a value from the cache
##### `clear()`
Clear all cache
##### `getMultiple(array $keys)`
Obtains multiple cache items by their unique keys
##### `setMultiple(array $values [, int $ttl])`
Persists a set of key => value pairs in the cache
##### `deleteMultiple(array $keys)`
Deletes multiple cache items in a single operation
.
The `Desarrolla2\Cache\CacheInterface` also has the following methods:
##### `withOption(string $key, string $value)`
Set option for implementation. Creates a new instance.
##### `withOptions(array $options)`
Set multiple options for implementation. Creates a new instance.
##### `getOption(string $key)`
Get option for implementation.
## Packers
Cache objects typically hold a `Desarrolla2\Cache\Packer\PackerInterface`
object. By default, packing is done using `serialize` and `unserialize`.
Available packers are:
* `SerializePacker` using `serialize` and `unserialize`
* `JsonPacker` using `json_encode` and `json_decode`
* `NopPacker` does no packing
* `MongoDBBinaryPacker` using `serialize` and `unserialize` to store as [BSON Binary](http://php.net/manual/en/class.mongodb-bson-binary.php)
#### PSR-16 incompatible packers
The `JsonPacker` does not fully comply with PSR-16, as packing and
unpacking an object will probably not result in an object of the same class.
The `NopPacker` is intended when caching string data only (like HTML output) or
if the caching backend supports structured data. Using it when storing objects
will might give unexpected results.
## Contributors
[![Daniel González](https://avatars1.githubusercontent.com/u/661529?v=3&s=80)](https://github.com/desarrolla2)
Twitter: [@desarrolla2](https://twitter.com/desarrolla2)\
[![Arnold Daniels](https://avatars3.githubusercontent.com/u/100821?v=3&s=80)](https://github.com/jasny)
Twitter: [@ArnoldDaniels](https://twitter.com/ArnoldDaniels)
[ico-version]: https://img.shields.io/packagist/v/desarrolla2/Cache.svg?style=flat-square
[ico-pre-release]: https://img.shields.io/packagist/vpre/desarrolla2/Cache.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/desarrolla2/Cache/master.svg?style=flat-square
[ico-coveralls]: https://img.shields.io/coveralls/desarrolla2/Cache/master.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/desarrolla2/cache.svg?style=flat-square
[ico-coverage]: https://scrutinizer-ci.com/g/desarrolla2/Cache/badges/coverage.png?b=master
[ico-sensiolabs]: https://img.shields.io/sensiolabs/i/5f139261-1ac1-4559-846a-723e09319a88.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/desarrolla2/cache.svg?style=flat-square
[ico-today-downloads]: https://img.shields.io/packagist/dd/desarrolla2/cache.svg?style=flat-square
[ico-gitter]: https://img.shields.io/badge/GITTER-JOIN%20CHAT%20%E2%86%92-brightgreen.svg?style=flat-square
[ico-github-actions]: https://github.com/desarrolla2/Cache/workflows/PHP/badge.svg
[link-packagist]: https://packagist.org/packages/desarrolla2/cache
[link-license]: http://hassankhan.mit-license.org
[link-travis]: https://travis-ci.org/desarrolla2/Cache
[link-github-actions]: https://github.com/desarrolla2/Cache/actions
[link-coveralls]: https://coveralls.io/github/desarrolla2/Cache
[link-scrutinizer]: https://scrutinizer-ci.com/g/desarrolla2/cache
[link-sensiolabs]: https://insight.sensiolabs.com/projects/5f139261-1ac1-4559-846a-723e09319a88
[link-downloads]: https://packagist.org/packages/desarrolla2/cache
[link-gitter]: https://gitter.im/desarrolla2/Cache?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge

100
msd/vendor/desarrolla2/cache/build.xml vendored Normal file
View File

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="Cache" default="build">
<target name="install" depends="composer"
description="Prepare for execution"/>
<target name="build" depends="install, init"
description="Run all tests and build everything"/>
<target name="metrics" depends="build, phpunit, phpdoc, pdepend, phpcs, phpmd"
description="Generate Metrics"/>
<target name="clean"
description="Cleanup build artifacts">
<delete dir="cache"/>
<delete dir="build"/>
</target>
<target name="init" depends="clean"
description="Prepare for build">
<mkdir dir="cache/htmlpurifier"/>
<mkdir dir="build/api"/>
<mkdir dir="build/coverage"/>
<mkdir dir="build/pdepend"/>
<mkdir dir="build/phpcs"/>
<mkdir dir="build/phpmd"/>
</target>
<target name="composer"
description="Composer install">
<exec executable="composer">
<arg value="install"/>
</exec>
</target>
<target name="phpdoc"
description="Generate API documentation using PHPDocumentor">
<exec executable="phpdoc">
<arg value="-d"/>
<arg value="src"/>
<arg value="-t"/>
<arg value="build/api/"/>
</exec>
</target>
<target name="phpunit"
description="Run unit tests using PHPUnit">
<exec executable="phpunit">
<arg value="-c"/>
<arg value="phpunit.xml"/>
</exec>
</target>
<target name="pdepend"
description="Generate software metrics charts using PHP_Depend">
<exec executable="pdepend">
<arg value="--jdepend-chart=build/pdepend/dependencies.svg"/>
<arg value="--overview-pyramid=build/pdepend/overview-pyramid.svg"/>
<arg value="src"/>
</exec>
</target>
<target name="phpcs"
description="Generate coding standard metrics using PHPCS">
<exec executable="phpcs">
<arg value="--standard=PSR2"/>
<arg value="--report-full=build/phpcs/full.txt"/>
<arg value="--report-summary=build/phpcs/sumary.txt"/>
<arg value="src"/>
<arg value="tests"/>
</exec>
</target>
<target name="phpmd"
description="Generate coding metrics for mess code using PHPMD">
<exec executable="phpmd">
<arg value="src"/>
<arg value="text"/>
<arg value="codesize,unusedcode,naming,design,controversial"/>
<arg value="--reportfile"/>
<arg value="build/phpmd/report.txt"/>
</exec>
</target>
<target name="cs" description="">
<parallel>
<exec executable="php-cs-fixer">
<arg line="fix src"/>
</exec>
<exec executable="php-formatter">
<arg line="formatter:header:fix src"/>
</exec>
<exec executable="php-formatter">
<arg line="formatter:use:sort src"/>
</exec>
</parallel>
</target>
</project>

View File

@ -0,0 +1,67 @@
{
"name": "desarrolla2/cache",
"description": "Provides an cache interface for several adapters Apc, Apcu, File, Mongo, Memcache, Memcached, Mysql, Mongo, Redis is supported.",
"keywords": [
"cache",
"simple-cache",
"psr-16",
"apc",
"apcu",
"file",
"memcached",
"memcache",
"mysql",
"mongo",
"redis"
],
"type": "library",
"license": "MIT",
"homepage": "https://github.com/desarrolla2/Cache/",
"authors": [
{
"name": "Daniel González",
"homepage": "http://desarrolla2.com/"
},
{
"name": "Arnold Daniels",
"homepage": "https://jasny.net/"
}
],
"provide": {
"psr/simple-cache-implementation": "1.0"
},
"require": {
"php": ">=7.2.0",
"psr/simple-cache": "^1.0"
},
"require-dev": {
"ext-apcu": "*",
"ext-json": "*",
"ext-mysqli": "*",
"ext-memcached": "*",
"predis/predis": "~1.0.0",
"mongodb/mongodb": "^1.3",
"cache/integration-tests": "dev-master",
"phpunit/phpunit": "^8.3 || ^9.0",
"phpstan/phpstan": "^0.12.29",
"symfony/phpunit-bridge": "^5.2",
"mikey179/vfsstream": "v1.6.8"
},
"autoload": {
"psr-4": {
"Desarrolla2\\Cache\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Desarrolla2\\Test\\Cache\\": "tests/"
}
},
"scripts": {
"test": [
"phpstan analyse",
"phpunit --colors=always",
"phpcs -p src"
]
}
}

View File

@ -0,0 +1,25 @@
# Apcu
Use [APCu cache](http://php.net/manual/en/book.apcu.php) to cache to shared
memory.
``` php
use Desarrolla2\Cache\Apcu as ApcuCache;
$cache = new ApcuCache();
```
_Note: by default APCu uses the time at the beginning of a request for ttl. In
some cases, like with a long running script, this can be a problem. You can
change this behaviour `ini_set('apc.use_request_time', false)`._
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
### Packer
By default the [`NopPacker`](../packers/nop.md) is used.

View File

@ -0,0 +1,37 @@
# Chain
The Cache chain allows you to use multiple implementations to store cache. For
instance, you can use both fast volatile (in-memory) storage and slower
non-volatile (disk) storage. Alternatively you can have a local storage
as well as a shared storage service.
``` php
use Desarrolla2\Cache\Chain as CacheChain;
use Desarrolla2\Cache\Memory as MemoryCache;
use Desarrolla2\Cache\Predis as PredisCache;
$cache = new CacheChain([
(new MemoryCache())->withOption('ttl', 3600),
(new PredisCache())->withOption('ttl', 10800)
]);
```
The Chain cache implementation doesn't use any option. It uses the `Nop` packer
by default.
Typically it's useful to specify a maximum `ttl` for each implementation. This
means that the volatile memory only holds items that are used often.
The following actions propogate to all cache adapters in the chain
* `set`
* `setMultiple`
* `delete`
* `deleteMultiple`
* `clear`
For the following actions all nodes are tried in sequence
* `has`
* `get`
* `getMultiple`

View File

@ -0,0 +1,82 @@
# File
Save the cache as file to on the filesystem.
You must pass a cache directory to the constructor.
``` php
use Desarrolla2\Cache\File as FileCache;
$cache = new FileCache(sys_get_temp_dir() . '/cache');
```
### Options
| name | type | default | |
| ------------ | --------------------------------- | -------------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| ttl-strategy | string ('embed', 'file', 'mtime') | "embed" | Strategy to store the TTL |
| prefix | string | "" | Key prefix |
| filename | string or callable | "%s.php.cache" | Filename as sprintf format |
#### TTL strategy option
The ttl strategy determines how the TTL is stored. Typical filesystems don't
allow custom file properties, so we'll have to use one of these strategies:
| strategy | |
| -------- | ----------------------------------------------- |
| embed | Embed the TTL as first line of the file |
| file | Create a TTL file in addition to the cache file |
| mtime | Use [mtime][] + max ttl |
The 'mtime' strategy is not PSR-16 compliant, as the TTL passed to the `set()`
method is ignored. Only the `ttl` option for is used on `get()` and `has()`.
[mtime]: https://www.unixtutorial.org/2008/04/atime-ctime-mtime-in-unix-filesystems/
#### Filename option
The `filename` will be parsed using `sprintf` where '%s' is substituted with
the key. The default extension is automatically determined based on the
packer.
Instead of a string, `filename` may also be set to a callable, like a callable
object or closure. In that case the callable will be called to create a
filename as
$filename = $callable($key);
##### BasicFilename
The library comes with invokable object as callable for the filename. The
`BasicFilename` object works as described above.
##### TrieFilename
The `TrieFilename` object will create a prefix tree directory structure. This
is useful where a lot of cache files would cause to many files in a directory.
Specify the `sprintf` format and the directory level to the constructor when
creating a `TrieFilename` object.
``` php
use Desarrolla2\Cache\File as FileCache;
use Desarrolla2\Cache\File\TrieFilename;
$callback = new TrieFilename('%s.php.cache', 2);
$cache = (new FileCache(sys_get_temp_dir() . '/cache'))
->withOption('filename', $callback);
```
In this case, adding an item with key `foobar` would be create a file at
/tmp/cache/f/fo/foobar.php.cache
### Packer
By default the [`SerializePacker`](../packers/serialize.md) is used. The
[`NopPacker`](../packers/nop.md) can be used if the values are strings.
Other packers, like the [`JsonPacker`](../packers/json.md) are also
useful with file cache.

View File

@ -0,0 +1,28 @@
# Memcached
Store cache to [Memcached](https://memcached.org/). Memcached is a high
performance distributed caching system.
``` php
use Desarrolla2\Cache\Memcached as MemcachedCache;
use Memcached;
$server = new Memcached();
// configure it here
$cache = new MemcachedCache($server);
```
This implementation uses the [memcached](https://php.net/memcached) php
extension. The (alternative) memcache extension is not supported.
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
### Packer
By default the [`NopPacker`](../packers/nop.md) is used.

View File

@ -0,0 +1,23 @@
# Memory
Store the cache in process memory _(in other words in an array)_. Cache Memory
is removed when the PHP process exist. Also it is not shared between different
processes.
``` php
use Desarrolla2\Cache\Memory as MemoryCache;
$cache = new MemoryCache();
```
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| limit | int | null | Maximum items in cache |
| prefix | string | "" | Key prefix |
### Packer
By default the [`SerializePacker`](../packers/serialize.md) is used.

View File

@ -0,0 +1,45 @@
# Mongo
Use it to store the cache in a Mongo database. Requires the mongodb extension
and the [mongodb/mongodb](https://github.com/mongodb/mongo-php-library)
library.
You must pass a `MongoDB\Collection` object to the cache constructor.
``` php
<?php
use Desarrolla2\Cache\Mongo as MongoCache;
use MongoDB\Client;
$client = new Client('mongodb://localhost:27017');
$database = $client->selectDatabase('mycache');
$collection = $database->selectCollection('cache');
$cache = new MongoCache($collection);
```
MonoDB will always automatically create the database and collection if needed.
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| initialize | bool | true | Enable auto-initialize |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
#### Initialize option
If `initialize` is enabled, the cache implementation will automatically create
a [ttl index](https://docs.mongodb.com/manual/core/index-ttl/). In production
it's better to disable auto-initialization and create the ttl index explicitly
when setting up the database. This prevents a `createIndex()` call on each
request.
### Packer
By default the [`MongoDBBinaryPacker`](../packers/mongodbbinary.md) is used. It
serializes the data and stores it in a [Binary BSON variable](http://php.net/manual/en/class.mongodb-bson-binary.php).
If the data is a UTF-8 string of simple array or stdClass object, it may be
useful to use the [`NopPacker`](../packers/nop.md) instead.

View File

@ -0,0 +1,47 @@
# Mysqli
Cache to a [MySQL database](https://www.mysql.com/) using the
[mysqli](http://php.net/manual/en/book.mysqli.php) PHP extension.
You must pass a `mysqli` connection object to the constructor.
``` php
<?php
use Desarrolla2\Cache\Mysqli as MysqliCache;
$db = new mysqli('localhost');
$cache = new MysqliCache($db);
```
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| initialize | bool | true | Enable auto-initialize |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
#### Initialize option
If `initialize` is enabled, the cache implementation will automatically create
a [scheduled event](https://dev.mysql.com/doc/refman/5.7/en/event-scheduler.html).
```
DELIMITER ;;
CREATE TABLE IF NOT EXISTS `cache` (`key` VARCHAR(255), `value` TEXT, `ttl` INT UNSIGNED, PRIMARY KEY (`key`));;
CREATE EVENT `apply_ttl_cache` ON SCHEDULE 1 HOUR
DO BEGIN
DELETE FROM `cache` WHERE `ttl` < NOW();
END;;
```
In production it's better to disable auto-initialization and create the event
explicitly when setting up the database. This prevents a `CREATE TABLE` and
`CREATE EVENT` query on each request.
### Packer
By default the [`SerializePacker`](../packers/serialize.md) is used.

View File

@ -0,0 +1,13 @@
# NotCache
A [Null object](https://sourcemaking.com/design_patterns/null_object) that
correctly implements the PSR-16 interface, but does not actually cache
anything.
``` php
use Desarrolla2\Cache\NotCache;
$cache = new NotCache();
```
It doesn't use any options or packers.

View File

@ -0,0 +1,74 @@
# PhpFile
Save the cache as PHP script to on the filesystem using
[`var_export`](http://php.net/manual/en/function.var-export.php) when storing
cache and [`include`](http://php.net/manual/en/function.include.php) when
loading cache.
The implementation leverages the PHP engines in-memory file caching (opcache)
to cache application data in addition to code. This method is particularly fast
in PHP7.2+ due to opcode cache optimizations.
PHP file caching should primarily be used for arrays and objects. There is no
performance benefit over APCu for storing strings.
[read more][]
``` php
use Desarrolla2\Cache\PhpFile as PhpFileCache;
$cache = new PhpFileCache();
```
### Options
| name | type | default | |
| --------- | ------------------ | -------------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
| filename | string or callable | "%s.php" | Filename as sprintf format |
#### Filename option
The `filename` will be parsed using `sprintf` where '%s' is substituted with
the key.
Instead of a string, `filename` may also be set to a callable, like a callable
object or closure. In that case the callable will be called to create a
filename as
$filename = $callable($key);
##### BasicFilename
The library comes with invokable object as callable for the filename. The
`BasicFilename` object works as described above.
##### TrieFilename
The `TrieFilename` object will create a prefix tree directory structure. This
is useful where a lot of cache files would cause to many files in a directory.
Specify the `sprintf` format and the directory level to the constructor when
creating a `TrieFilename` object.
``` php
use Desarrolla2\Cache\File as FileCache;
use Desarrolla2\Cache\File\TrieFilename;
$callback = new TrieFilename('%s.php', 2);
$cache = (new FileCache(sys_get_temp_dir() . '/cache'))
->withOption('filename', $callback);
```
In this case, adding an item with key `foobar` would be create a file at
/tmp/cache/f/fo/foobar.php
### Packer
By default the [`NopPacker`](../packers/nop.md) is used. Other packers should
not be used.
[read more]: https://medium.com/@dylanwenzlau/500x-faster-caching-than-redis-memcache-apc-in-php-hhvm-dcd26e8447ad

View File

@ -0,0 +1,31 @@
# Predis
Cache using a [redis server](https://redis.io/). Redis is an open source,
in-memory data structure store, used as a database, cache and message broker.
You must provide a `Predis\Client` object to the constructor.
```php
use Desarrolla2\Cache\Predis as PredisCache;
use Predis\Client as PredisClient;
$client = new PredisClient('tcp://localhost:6379');
$cache = new PredisCache($client);
```
### Installation
Requires the [`predis`](https://github.com/nrk/predis/wiki) library.
composer require predis/predis
### Options
| name | type | default | |
| --------- | ---- | ------- | ------------------------------------- |
| ttl | int | null | Maximum time to live in seconds |
| prefix | string | "" | Key prefix |
### Packer
By default the [`SerializePacker`](../packers/serialize.md) is used.

View File

@ -0,0 +1,40 @@
# Performance test
Here are my performance tests, you can view the results ordered from faster to slower.
| Adapter | 10.000 set | 10.000 has | 10.000 get |
| :-------------- | -----------: | -----------: | ---------: |
| NoCache | 0.0637 | 0.0482 | 0.0488 |
| Apcu | 0.0961 | 0.0556 | 0.0770 |
| File | 0.6881 | 0.3426 | 0.3107 |
| Mongo | 13.8144 | 30.0203 | 24.4214 |
## how i run the test?
The test its the same for all Adapters and look like this.
``` php
<?php
$timer = new Timer();
for ($i = 1; $i <= 10000; $i++) {
$cache->set(md5($i), md5($i), 3600);
}
$timer->mark('10.000 set');
for ($i = 1; $i <= 10000; $i++) {
$cache->has(md5($i));
}
$timer->mark('10.000 has');
for ($i = 1; $i <= 10000; $i++) {
$cache->get(md5($i));
}
$timer->mark('10.000 get');
```
if you want run the tests them execute.
``` sh
php test/performance/AdapterName.php
```

View File

@ -0,0 +1,8 @@
<?xml version="1.0"?>
<ruleset name="PSR">
<!-- Include the whole PSR-1 standard -->
<rule ref="PSR1"/>
<!-- Include the whole PSR-2 standard -->
<rule ref="PSR2"/>
</ruleset>

View File

@ -0,0 +1,8 @@
parameters:
level: 3
paths:
- src
reportUnmatchedIgnoredErrors: false
ignoreErrors:
- /^Variable property access/

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
bootstrap="./vendor/autoload.php"
convertWarningsToExceptions="true"
convertNoticesToExceptions="true"
convertErrorsToExceptions="true"
backupStaticAttributes="false"
processIsolation="false"
stopOnFailure="false"
backupGlobals="false"
colors="true"
>
<testsuites>
<testsuite name="Desarrolla2 Cache test suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./src</directory>
</whitelist>
</filter>
<php>
<!--ini name="mysqli.default_host" value="localhost" /-->
<!--ini name="mysqli.default_user" value="root" /-->
<!--ini name="mysqli.default_pw" value=""/-->
<const name="CACHE_TESTS_MYSQLI_DATABASE" value="cache_tests" />
<const name="CACHE_TESTS_MONGO_DSN" value="mongodb://localhost:27017" />
<const name="CACHE_TESTS_MONGO_DATABASE" value="cache_tests" />
<const name="CACHE_TESTS_MEMCACHED_SERVER" value="localhost:11211" />
<const name="CACHE_TESTS_PREDIS_DSN" value="tcp://localhost:6379" />
</php>
</phpunit>

View File

@ -0,0 +1,296 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Option\PrefixTrait as PrefixOption;
use Desarrolla2\Cache\Option\TtlTrait as TtlOption;
use Desarrolla2\Cache\Packer\PackingTrait as Packing;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use DateTimeImmutable;
use DateInterval;
use Traversable;
/**
* AbstractAdapter
*/
abstract class AbstractCache implements CacheInterface
{
use PrefixOption;
use TtlOption;
use Packing;
/**
* Make a clone of this object.
*
* @return static
*/
protected function cloneSelf(): self
{
return clone $this;
}
/**
* {@inheritdoc}
*/
public function withOption(string $key, $value): self
{
return $this->withOptions([$key => $value]);
}
/**
* {@inheritdoc}
*/
public function withOptions(array $options): self
{
$cache = $this->cloneSelf();
foreach ($options as $key => $value) {
$method = "set" . str_replace('-', '', $key) . "Option";
if (empty($key) || !method_exists($cache, $method)) {
throw new InvalidArgumentException("unknown option '$key'");
}
$cache->$method($value);
}
return $cache;
}
/**
* {@inheritdoc}
*/
public function getOption($key)
{
$method = "get" . str_replace('-', '', $key) . "Option";
if (empty($key) || !method_exists($this, $method)) {
throw new InvalidArgumentException("unknown option '$key'");
}
return $this->$method();
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
if (!is_string($key)) {
$type = (is_object($key) ? get_class($key) . ' ' : '') . gettype($key);
throw new InvalidArgumentException("Expected key to be a string, not $type");
}
if ($key === '' || preg_match('~[{}()/\\\\@:]~', $key)) {
throw new InvalidArgumentException("Invalid key '$key'");
}
}
/**
* Assert that the keys are an array or traversable
*
* @param iterable $subject
* @param string $msg
* @return void
* @throws InvalidArgumentException if subject are not iterable
*/
protected function assertIterable($subject, $msg): void
{
$iterable = function_exists('is_iterable')
? is_iterable($subject)
: is_array($subject) || $subject instanceof Traversable;
if (!$iterable) {
throw new InvalidArgumentException($msg);
}
}
/**
* Turn the key into a cache identifier
*
* @param string $key
* @return string
* @throws InvalidArgumentException
*/
protected function keyToId($key): string
{
$this->assertKey($key);
return sprintf('%s%s', $this->prefix, $key);
}
/**
* Create a map with keys and ids
*
* @param iterable $keys
* @return array
* @throws InvalidArgumentException
*/
protected function mapKeysToIds($keys): array
{
$this->assertIterable($keys, 'keys not iterable');
$map = [];
foreach ($keys as $key) {
$id = $this->keyToId($key);
$map[$id] = $key;
}
return $map;
}
/**
* Pack all values and turn keys into ids
*
* @param iterable $values
* @return array
*/
protected function packValues(iterable $values): array
{
$packed = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$packed[$id] = $this->pack($value);
}
return $packed;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys not iterable');
$result = [];
foreach ($keys as $key) {
$result[$key] = $this->get($key, $default);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$success = true;
foreach ($values as $key => $value) {
$success = $this->set(is_int($key) ? (string)$key : $key, $value, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$this->assertIterable($keys, 'keys not iterable');
$success = true;
foreach ($keys as $key) {
$success = $this->delete($key) && $success;
}
return $success;
}
/**
* Get the current time.
*
* @return int
*/
protected function currentTimestamp(): int
{
return time();
}
/**
* Convert TTL to seconds from now
*
* @param null|int|DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToSeconds($ttl): ?int
{
if (!isset($ttl)) {
return $this->ttl;
}
if ($ttl instanceof DateInterval) {
$reference = new DateTimeImmutable();
$endTime = $reference->add($ttl);
$ttl = $endTime->getTimestamp() - $reference->getTimestamp();
}
if (!is_int($ttl)) {
$type = (is_object($ttl) ? get_class($ttl) . ' ' : '') . gettype($ttl);
throw new InvalidArgumentException("ttl should be of type int or DateInterval, not $type");
}
return isset($this->ttl) ? min($ttl, $this->ttl) : $ttl;
}
/**
* Convert TTL to epoch timestamp
*
* @param null|int|DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToTimestamp($ttl): ?int
{
if (!isset($ttl)) {
return isset($this->ttl) ? time() + $this->ttl : null;
}
if (is_int($ttl)) {
return time() + (isset($this->ttl) ? min($ttl, $this->ttl) : $ttl);
}
if ($ttl instanceof DateInterval) {
$timestamp = (new DateTimeImmutable())->add($ttl)->getTimestamp();
return isset($this->ttl) ? min($timestamp, time() + $this->ttl) : $timestamp;
}
$type = (is_object($ttl) ? get_class($ttl) . ' ' : '') . gettype($ttl);
throw new InvalidArgumentException("ttl should be of type int or DateInterval, not $type");
}
}

View File

@ -0,0 +1,216 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Option\FilenameTrait as FilenameOption;
/**
* Abstract class for using files as cache.
*
* @package Desarrolla2\Cache
*/
abstract class AbstractFile extends AbstractCache
{
use FilenameOption;
/**
* @var string
*/
protected $cacheDir;
/**
* Class constructor
*
* @param string|null $cacheDir
*/
public function __construct(?string $cacheDir = null)
{
if (!$cacheDir) {
$cacheDir = realpath(sys_get_temp_dir()) . DIRECTORY_SEPARATOR . 'cache';
if(!is_dir($cacheDir)) {
mkdir($cacheDir, 0777, true);
}
}
$this->cacheDir = rtrim($cacheDir, '/');
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
parent::assertKey($key);
if (strpos($key, '*')) {
throw new InvalidArgumentException("Key may not contain the character '*'");
}
}
/**
* Get the contents of the cache file.
*
* @param string $cacheFile
* @return string
*/
protected function readFile(string $cacheFile): string
{
return file_get_contents($cacheFile);
}
/**
* Read the first line of the cache file.
*
* @param string $cacheFile
* @return string
*/
protected function readLine(string $cacheFile): string
{
$fp = fopen($cacheFile, 'r');
$line = fgets($fp);
fclose($fp);
return $line;
}
/**
* Create a cache file
*
* @param string $cacheFile
* @param string $contents
* @return bool
*/
protected function writeFile(string $cacheFile, string $contents): bool
{
$dir = dirname($cacheFile);
if ($dir !== $this->cacheDir && !is_dir($dir)) {
mkdir($dir, 0775, true);
}
return (bool)file_put_contents($cacheFile, $contents);
}
/**
* Delete a cache file
*
* @param string $file
* @return bool
*/
protected function deleteFile(string $file): bool
{
return !is_file($file) || unlink($file);
}
/**
* Remove all files from a directory.
*/
protected function removeFiles(string $dir): bool
{
$success = true;
$generator = $this->getFilenameOption();
$objects = $this->streamSafeGlob($dir, $generator('*'));
foreach ($objects as $object) {
$success = $this->deleteFile($object) && $success;
}
return $success;
}
/**
* Recursive delete an empty directory.
*
* @param string $dir
*/
protected function removeRecursively(string $dir): bool
{
$success = $this->removeFiles($dir);
$objects = $this->streamSafeGlob($dir, '*');
foreach ($objects as $object) {
if (!is_dir($object)) {
continue;
}
if (is_link($object)) {
unlink($object);
} else {
$success = $this->removeRecursively($object) && $success;
rmdir($object);
}
}
return $success;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$cacheFile = $this->getFilename($key);
return $this->deleteFile($cacheFile);
}
/**
* Delete cache directory.
*
* {@inheritdoc}
*/
public function clear()
{
$this->removeRecursively($this->cacheDir);
return true;
}
/**
* Glob that is safe with streams (vfs for example)
*
* @param string $directory
* @param string $filePattern
* @return array
*/
protected function streamSafeGlob(string $directory, string $filePattern): array
{
$filePattern = basename($filePattern);
$files = scandir($directory);
$found = [];
foreach ($files as $filename) {
if (in_array($filename, ['.', '..'])) {
continue;
}
if (fnmatch($filePattern, $filename) || fnmatch($filePattern . '.ttl', $filename)) {
$found[] = "{$directory}/{$filename}";
}
}
return $found;
}
}

View File

@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\CacheException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
/**
* Apcu
*/
class Apcu extends AbstractCache
{
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->delete($key);
}
return apcu_store($this->keyToId($key), $this->pack($value), $ttlSeconds ?? 0);
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$packed = apcu_fetch($this->keyToId($key), $success);
return $success ? $this->unpack($packed) : $default;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return apcu_exists($this->keyToId($key));
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
return apcu_delete($id) || !apcu_exists($id);
}
/**
* {@inheritdoc}
*/
public function clear()
{
return apcu_clear_cache();
}
}

View File

@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Psr\SimpleCache\CacheInterface as PsrCacheInterface;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\KeyMaker\KeyMakerInterface;
/**
* CacheInterface
*/
interface CacheInterface extends PsrCacheInterface
{
/**
* Set option for cache
*
* @param string $key
* @param mixed $value
* @return static
*/
public function withOption(string $key, $value);
/**
* Set multiple options for cache
*
* @param array $options
* @return static
*/
public function withOptions(array $options);
/**
* Get option for cache
*
* @param string $key
* @return mixed
*/
public function getOption($key);
/**
* Set the packer
*
* @param PackerInterface $packer
* @return static
*/
public function withPacker(PackerInterface $packer);
}

View File

@ -0,0 +1,192 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\NopPacker;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Use multiple cache adapters.
*/
class Chain extends AbstractCache
{
/**
* @var CacheInterface[]
*/
protected $adapters;
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* Chain constructor.
*
* @param CacheInterface[] $adapters Fastest to slowest
*/
public function __construct(array $adapters)
{
foreach ($adapters as $adapter) {
if (!$adapter instanceof CacheInterface) {
throw new InvalidArgumentException("All adapters should be a cache implementation");
}
}
$this->adapters = $adapters;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->set($key, $value, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->setMultiple($values, $ttl) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
foreach ($this->adapters as $adapter) {
$result = $adapter->get($key); // Not using $default as we want to get null if the adapter doesn't have it
if (isset($result)) {
return $result;
}
}
return $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys are not iterable');
$missing = [];
$values = [];
foreach ($keys as $key) {
$this->assertKey($key);
$missing[] = $key;
$values[$key] = $default;
}
foreach ($this->adapters as $adapter) {
if (empty($missing)) {
break;
}
$found = [];
foreach ($adapter->getMultiple($missing) as $key => $value) {
if (isset($value)) {
$found[$key] = $value;
}
}
$values = array_merge($values, $found);
$missing = array_values(array_diff($missing, array_keys($found)));
}
return $values;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
foreach ($this->adapters as $adapter) {
if ($adapter->has($key)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->delete($key) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->deleteMultiple($keys) && $success;
}
return $success;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$success = true;
foreach ($this->adapters as $adapter) {
$success = $adapter->clear() && $success;
}
return $success;
}
}

View File

@ -0,0 +1,25 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Exception bad method calls
*/
class BadMethodCallException extends \BadMethodCallException implements PsrCacheException
{
}

View File

@ -0,0 +1,25 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Interface used for all types of exceptions thrown by the implementing library.
*/
class CacheException extends \RuntimeException implements PsrCacheException
{
}

View File

@ -0,0 +1,25 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\InvalidArgumentException as PsrInvalidArgumentException;
/**
* Exception for invalid cache arguments.
*/
class InvalidArgumentException extends \InvalidArgumentException implements PsrInvalidArgumentException
{
}

View File

@ -0,0 +1,25 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Exception;
use Psr\SimpleCache\CacheException as PsrCacheException;
/**
* Exception for unexpected values when reading from cache.
*/
class UnexpectedValueException extends \UnexpectedValueException implements PsrCacheException
{
}

View File

@ -0,0 +1,175 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Exception\UnexpectedValueException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Cache file.
*/
class File extends AbstractFile
{
/**
* @var string 'embed', 'file', 'mtime'
*/
protected $ttlStrategy = 'embed';
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Set TTL strategy
*
* @param string $strategy
*/
protected function setTtlStrategyOption($strategy)
{
if (!in_array($strategy, ['embed', 'file', 'mtime'])) {
throw new InvalidArgumentException("Unknown strategy '$strategy', should be 'embed', 'file' or 'mtime'");
}
$this->ttlStrategy = $strategy;
}
/**
* Get TTL strategy
*
* @return string
*/
protected function getTtlStrategyOption(): string
{
return $this->ttlStrategy;
}
/**
* Get the TTL using one of the strategies
*
* @param string $cacheFile
* @return int
*/
protected function getTtl(string $cacheFile)
{
switch ($this->ttlStrategy) {
case 'embed':
return (int)$this->readLine($cacheFile);
case 'file':
return file_exists("$cacheFile.ttl")
? (int)file_get_contents("$cacheFile.ttl")
: PHP_INT_MAX;
case 'mtime':
return $this->getTtl($cacheFile) > 0 ? filemtime($cacheFile) + $this->ttl : PHP_INT_MAX;
}
throw new \InvalidArgumentException("Invalid TTL strategy '{$this->ttlStrategy}'");
}
/**
* Set the TTL using one of the strategies
*
* @param int|null $expiration
* @param string $contents
* @param string $cacheFile
* @return string The (modified) contents
*/
protected function setTtl($expiration, $contents, $cacheFile)
{
switch ($this->ttlStrategy) {
case 'embed':
$contents = ($expiration ?? PHP_INT_MAX) . "\n" . $contents;
break;
case 'file':
if ($expiration !== null) {
file_put_contents("$cacheFile.ttl", $expiration);
}
break;
case 'mtime':
// nothing
break;
}
return $contents;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
if (!$this->has($key)) {
return $default;
}
$cacheFile = $this->getFilename($key);
$packed = $this->readFile($cacheFile);
if ($this->ttlStrategy === 'embed') {
$packed = substr($packed, strpos($packed, "\n") + 1);
}
return $this->unpack($packed);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$cacheFile = $this->getFilename($key);
if (!file_exists($cacheFile)) {
return false;
}
$ttl = $this->getTtl($cacheFile);
if ($ttl <= time()) {
$this->deleteFile($cacheFile);
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$cacheFile = $this->getFilename($key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data to be cached to file");
}
$contents = $this->setTtl($this->ttlToTimestamp($ttl), $packed, $cacheFile);
return $this->writeFile($cacheFile, $contents);
}
}

View File

@ -0,0 +1,68 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\File;
/**
* Create a path for a key
*/
class BasicFilename
{
/**
* @var string
*/
protected $format;
/**
* BasicFilename constructor.
*
* @param string $format
*/
public function __construct(string $format)
{
$this->format = $format;
}
/**
* Get the format
*
* @return string
*/
public function getFormat(): string
{
return $this->format;
}
/**
* Create the path for a key
*
* @param string $key
* @return string
*/
public function __invoke(string $key): string
{
return sprintf($this->format, $key ?: '*');
}
/**
* Cast to string
*
* @return string
*/
public function __toString(): string
{
return $this->getFormat();
}
}

View File

@ -0,0 +1,121 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\File;
/**
* Create a path for a key as prefix tree directory structure.
*
* @see https://en.wikipedia.org/wiki/Trie
*/
class TrieFilename
{
/**
* @var string
*/
protected $format;
/**
* @var int
*/
protected $levels;
/**
* @var bool
*/
protected $hash;
/**
* TrieFilename constructor.
*
* @param string $format
* @param int $levels The depth of the structure
* @param bool $hash MD5 hash the key to get a better spread
*/
public function __construct(string $format, int $levels = 1, bool $hash = false)
{
$this->format = $format;
$this->levels = $levels;
$this->hash = $hash;
}
/**
* Get the format
*
* @return string
*/
public function getFormat(): string
{
return $this->format;
}
/**
* Get the depth of the structure
*
* @return int
*/
public function getLevels(): int
{
return $this->levels;
}
/**
* Will the key be hashed to create the trie.
*
* @return bool
*/
public function isHashed(): bool
{
return $this->hash;
}
/**
* Create the path for a key
*
* @param string $key
* @return string
*/
public function __invoke(string $key): string
{
if (empty($key)) {
return $this->wildcardPath();
}
$dirname = $this->hash ? base_convert(md5($key), 16, 36) : $key;
$filename = sprintf($this->format, $key);
$path = '';
for ($length = 1; $length <= $this->levels; $length++) {
$path .= substr($dirname, 0, $length) . DIRECTORY_SEPARATOR;
}
return $path . $filename;
}
/**
* Get a path for all files (using glob)
*
* @return string
*/
protected function wildcardPath(): string
{
$filename = sprintf($this->format, '*');
return str_repeat('*' . DIRECTORY_SEPARATOR, $this->levels) . $filename;
}
}

View File

@ -0,0 +1,218 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
use Memcached as MemcachedServer;
/**
* Memcached
*/
class Memcached extends AbstractCache
{
/**
* @var MemcachedServer
*/
protected $server;
/**
* @param MemcachedServer $server
*/
public function __construct(MemcachedServer $server)
{
$this->server = $server;
}
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* Validate the key
*
* @param string $key
* @return void
* @throws InvalidArgumentException
*/
protected function assertKey($key): void
{
parent::assertKey($key);
if (strlen($key) > 250) {
throw new InvalidArgumentException("Key to long, max 250 characters");
}
}
/**
* Pack all values and turn keys into ids
*
* @param iterable $values
* @return array
*/
protected function packValues(iterable $values): array
{
$packed = [];
foreach ($values as $key => $value) {
$this->assertKey(is_int($key) ? (string)$key : $key);
$packed[$key] = $this->pack($value);
}
return $packed;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$this->assertKey($key);
$data = $this->server->get($key);
if ($this->server->getResultCode() !== MemcachedServer::RES_SUCCESS) {
return $default;
}
return $this->unpack($data);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$this->assertKey($key);
$this->server->get($key);
$result = $this->server->getResultCode();
return $result === MemcachedServer::RES_SUCCESS;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->assertKey($key);
$packed = $this->pack($value);
$ttlTime = $this->ttlToMemcachedTime($ttl);
if ($ttlTime === false) {
return $this->delete($key);
}
$success = $this->server->set($key, $packed, $ttlTime);
return $success;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$this->server->delete($this->keyToId($key));
$result = $this->server->getResultCode();
return $result === MemcachedServer::RES_SUCCESS || $result === MemcachedServer::RES_NOTFOUND;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$this->assertIterable($keys, 'keys not iterable');
$keysArr = is_array($keys) ? $keys : iterator_to_array($keys, false);
array_walk($keysArr, [$this, 'assertKey']);
$result = $this->server->getMulti($keysArr);
if ($result === false) {
return false;
}
$items = array_fill_keys($keysArr, $default);
foreach ($result as $key => $value) {
$items[$key] = $this->unpack($value);
}
return $items;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$packed = $this->packValues($values);
$ttlTime = $this->ttlToMemcachedTime($ttl);
if ($ttlTime === false) {
return $this->server->deleteMulti(array_keys($packed));
}
return $this->server->setMulti($packed, $ttlTime);
}
/**
* {@inheritdoc}
*/
public function clear()
{
return $this->server->flush();
}
/**
* Convert ttl to timestamp or seconds.
*
* @see http://php.net/manual/en/memcached.expiration.php
*
* @param null|int|\DateInterval $ttl
* @return int|null
* @throws InvalidArgumentException
*/
protected function ttlToMemcachedTime($ttl)
{
$seconds = $this->ttlToSeconds($ttl);
if ($seconds <= 0) {
return isset($seconds) ? false : 0;
}
/* 2592000 seconds = 30 days */
return $seconds <= 2592000 ? $seconds : $this->ttlToTimestamp($ttl);
}
}

View File

@ -0,0 +1,165 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Memory
*/
class Memory extends AbstractCache
{
/**
* Limit the amount of entries
* @var int
*/
protected $limit = PHP_INT_MAX;
/**
* @var array
*/
protected $cache = [];
/**
* @var array
*/
protected $cacheTtl = [];
/**
* Create the default packer for this cache implementation.
* {@internal NopPacker might fail PSR-16, as cached objects would change}
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Make a clone of this object.
* Set by cache reference, thus using the same pool.
*
* @return static
*/
protected function cloneSelf(): AbstractCache
{
$clone = clone $this;
$clone->cache =& $this->cache;
$clone->cacheTtl =& $this->cacheTtl;
return $clone;
}
/**
* Set the max number of items
*
* @param int $limit
*/
protected function setLimitOption($limit)
{
$this->limit = (int)$limit ?: PHP_INT_MAX;
}
/**
* Get the max number of items
*
* @return int
*/
protected function getLimitOption()
{
return $this->limit;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
if (!$this->has($key)) {
return $default;
}
$id = $this->keyToId($key);
return $this->unpack($this->cache[$id]);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$id = $this->keyToId($key);
if (!isset($this->cacheTtl[$id])) {
return false;
}
if ($this->cacheTtl[$id] <= time()) {
unset($this->cache[$id], $this->cacheTtl[$id]);
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
if (count($this->cache) >= $this->limit) {
$deleteKey = key($this->cache);
unset($this->cache[$deleteKey], $this->cacheTtl[$deleteKey]);
}
$id = $this->keyToId($key);
$this->cache[$id] = $this->pack($value);
$this->cacheTtl[$id] = $this->ttlToTimestamp($ttl) ?? PHP_INT_MAX;
return true;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
unset($this->cache[$id], $this->cacheTtl[$id]);
return true;
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->cache = [];
$this->cacheTtl = [];
return true;
}
}

View File

@ -0,0 +1,273 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\MongoDBBinaryPacker;
use Desarrolla2\Cache\Option\InitializeTrait as InitializeOption;
use MongoDB\Collection;
use MongoDB\BSON\UTCDatetime as BSONUTCDateTime;
use MongoDB\Driver\Exception\RuntimeException as MongoDBRuntimeException;
/**
* MongoDB cache implementation
*/
class MongoDB extends AbstractCache
{
use InitializeOption;
/**
* @var Collection
*/
protected $collection;
/**
* Class constructor
*
* @param Collection $collection
*/
public function __construct(Collection $collection)
{
$this->collection = $collection;
}
/**
* Initialize the DB collection.
* Set TTL index.
*/
protected function initialize(): void
{
$this->collection->createIndex(['ttl' => 1], ['expireAfterSeconds' => 0]);
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new MongoDBBinaryPacker();
}
/**
* Get filter for key and ttl.
*
* @param string|iterable $key
* @return array
*/
protected function filter($key)
{
if (is_array($key)) {
$key = ['$in' => $key];
}
return [
'_id' => $key,
'$or' => [
['ttl' => ['$gt' => new BSONUTCDateTime($this->currentTimestamp() * 1000)]],
['ttl' => null]
]
];
}
/**
* {@inheritdoc }
*/
public function get($key, $default = null)
{
$filter = $this->filter($this->keyToId($key));
try {
$data = $this->collection->findOne($filter);
} catch (MongoDBRuntimeException $e) {
return $default;
}
return isset($data) ? $this->unpack($data['value']) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return [];
}
$filter = $this->filter(array_keys($idKeyPairs));
$items = array_fill_keys(array_values($idKeyPairs), $default);
try {
$rows = $this->collection->find($filter);
} catch (MongoDBRuntimeException $e) {
return $items;
}
foreach ($rows as $row) {
$id = $row['_id'];
$key = $idKeyPairs[$id];
$items[$key] = $this->unpack($row['value']);
}
return $items;
}
/**
* {@inheritdoc }
*/
public function has($key)
{
$filter = $this->filter($this->keyToId($key));
try {
$count = $this->collection->count($filter);
} catch (MongoDBRuntimeException $e) {
return false;
}
return $count > 0;
}
/**
* {@inheritdoc }
*/
public function set($key, $value, $ttl = null)
{
$id = $this->keyToId($key);
$item = [
'_id' => $id,
'ttl' => $this->getTtlBSON($ttl),
'value' => $this->pack($value)
];
try {
$this->collection->replaceOne(['_id' => $id], $item, ['upsert' => true]);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
if (empty($values)) {
return true;
}
$bsonTtl = $this->getTtlBSON($ttl);
$items = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$items[] = [
'replaceOne' => [
['_id' => $id],
[
'_id' => $id,
'ttl' => $bsonTtl,
'value' => $this->pack($value)
],
[ 'upsert' => true ]
]
];
}
try {
$this->collection->bulkWrite($items);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
try {
$this->collection->deleteOne(['_id' => $id]);
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$idKeyPairs = $this->mapKeysToIds($keys);
try {
if (!empty($idKeyPairs)) {
$this->collection->deleteMany(['_id' => ['$in' => array_keys($idKeyPairs)]]);
}
} catch (MongoDBRuntimeException $e) {
return false;
}
return true;
}
/**
* {@inheritdoc}
*/
public function clear()
{
try {
$this->collection->drop();
} catch (MongoDBRuntimeException $e) {
return false;
}
$this->requireInitialization();
return true;
}
/**
* Get TTL as Date type BSON object
*
* @param null|int|\DateInterval $ttl
* @return BSONUTCDatetime|null
*/
protected function getTtlBSON($ttl): ?BSONUTCDatetime
{
return isset($ttl) ? new BSONUTCDateTime($this->ttlToTimestamp($ttl) * 1000) : null;
}
}

View File

@ -0,0 +1,312 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\Option\InitializeTrait;
use mysqli as Server;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
/**
* Mysqli cache adapter.
*
* Errors are silently ignored but exceptions are **not** caught. Beware when using `mysqli_report()` to throw a
* `mysqli_sql_exception` on error.
*/
class Mysqli extends AbstractCache
{
use InitializeTrait;
/**
* @var Server
*/
protected $server;
/**
* @var string
*/
protected $table = 'cache';
/**
* Class constructor
*
* @param Server $server
*/
public function __construct(Server $server)
{
$this->server = $server;
}
/**
* Initialize table.
* Automatically delete old cache.
*/
protected function initialize(): void
{
if ($this->initialized !== false) {
return;
}
$this->query(
"CREATE TABLE IF NOT EXISTS `{table}` "
. "( `key` VARCHAR(255), `value` BLOB, `ttl` BIGINT UNSIGNED, PRIMARY KEY (`key`) )"
);
$this->query(
"CREATE EVENT IF NOT EXISTS `apply_ttl_{$this->table}` ON SCHEDULE EVERY 1 HOUR DO BEGIN"
. " DELETE FROM {table} WHERE `ttl` < UNIX_TIMESTAMP();"
. " END"
);
$this->initialized = true;
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Set the table name
*
* @param string $table
*/
public function setTableOption(string $table)
{
$this->table = $table;
$this->requireInitialization();
}
/**
* Get the table name
*
* @return string
*/
public function getTableOption(): string
{
return $this->table;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$this->initialize();
$result = $this->query(
'SELECT `value` FROM {table} WHERE `key` = ? AND (`ttl` > ? OR `ttl` IS NULL) LIMIT 1',
'si',
$this->keyToId($key),
$this->currentTimestamp()
);
$row = $result !== false ? $result->fetch_row() : null;
return $row ? $this->unpack($row[0]) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return [];
}
$this->initialize();
$values = array_fill_keys(array_values($idKeyPairs), $default);
$placeholders = rtrim(str_repeat('?, ', count($idKeyPairs)), ', ');
$paramTypes = str_repeat('s', count($idKeyPairs)) . 'i';
$params = array_keys($idKeyPairs);
$params[] = $this->currentTimestamp();
$result = $this->query(
"SELECT `key`, `value` FROM {table} WHERE `key` IN ($placeholders) AND (`ttl` > ? OR `ttl` IS NULL)",
$paramTypes,
...$params
);
while (([$id, $value] = $result->fetch_row())) {
$key = $idKeyPairs[$id];
$values[$key] = $this->unpack($value);
}
return $values;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
$this->initialize();
$result = $this->query(
'SELECT COUNT(`key`) FROM {table} WHERE `key` = ? AND (`ttl` > ? OR `ttl` IS NULL) LIMIT 1',
'si',
$this->keyToId($key),
$this->currentTimestamp()
);
[$count] = $result ? $result->fetch_row() : [null];
return isset($count) && $count > 0;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$this->initialize();
$result = $this->query(
'REPLACE INTO {table} (`key`, `value`, `ttl`) VALUES (?, ?, ?)',
'ssi',
$this->keyToId($key),
$this->pack($value),
$this->ttlToTimestamp($ttl)
);
return $result !== false;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
if (empty($values)) {
return true;
}
$this->initialize();
$count = 0;
$params = [];
$timeTtl = $this->ttlToTimestamp($ttl);
foreach ($values as $key => $value) {
$count++;
$params[] = $this->keyToId(is_int($key) ? (string)$key : $key);
$params[] = $this->pack($value);
$params[] = $timeTtl;
}
$query = 'REPLACE INTO {table} (`key`, `value`, `ttl`) VALUES '
. rtrim(str_repeat('(?, ?, ?), ', $count), ', ');
return (bool)$this->query($query, str_repeat('ssi', $count), ...$params);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$this->initialize();
return (bool)$this->query(
'DELETE FROM {table} WHERE `key` = ?',
's',
$this->keyToId($key)
);
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$idKeyPairs = $this->mapKeysToIds($keys);
if (empty($idKeyPairs)) {
return true;
}
$this->initialize();
$placeholders = rtrim(str_repeat('?, ', count($idKeyPairs)), ', ');
$paramTypes = str_repeat('s', count($idKeyPairs));
return (bool)$this->query(
"DELETE FROM {table} WHERE `key` IN ($placeholders)",
$paramTypes,
...array_keys($idKeyPairs)
);
}
/**
* {@inheritdoc}
*/
public function clear()
{
$this->initialize();
return (bool)$this->query('TRUNCATE {table}');
}
/**
* Query the MySQL server
*
* @param string $query
* @param string $types
* @param mixed[] $params
* @return \mysqli_result|bool
*/
protected function query($query, $types = '', ...$params)
{
$sql = str_replace('{table}', $this->table, $query);
if ($params === []) {
$ret = $this->server->query($sql);
} else {
$statement = $this->server->prepare($sql);
if ($statement !== false) {
$statement->bind_param($types, ...$params);
$ret = $statement->execute();
$ret = $ret ? ($statement->get_result() ?: true) : false;
} else {
$ret = false;
}
}
if ($this->server->error) {
trigger_error($this->server->error . " $sql", E_USER_NOTICE);
}
return $ret;
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractCache;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\NopPacker;
/**
* Dummy cache handler
*/
class NotCache extends AbstractCache
{
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new NopPacker();
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
return true;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return false;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
return false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
return true;
}
}

View File

@ -0,0 +1,91 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
use TypeError;
use Desarrolla2\Cache\File\BasicFilename;
/**
* Use filename generator
*/
trait FilenameTrait
{
/**
* @var callable
*/
protected $filename;
/**
* Filename format or callable.
* The filename format will be applied using sprintf, replacing `%s` with the key.
*
* @param string|callable $filename
* @return void
*/
protected function setFilenameOption($filename): void
{
if (is_string($filename)) {
$filename = new BasicFilename($filename);
}
if (!is_callable($filename)) {
throw new TypeError("Filename should be a string or callable");
}
$this->filename = $filename;
}
/**
* Get the filename callable
*
* @return callable
*/
protected function getFilenameOption(): callable
{
if (!isset($this->filename)) {
$this->filename = new BasicFilename('%s.' . $this->getPacker()->getType());
}
return $this->filename;
}
/**
* Create a filename based on the key
*
* @param string|mixed $key
* @return string
*/
protected function getFilename($key): string
{
$id = $this->keyToId($key);
$generator = $this->getFilenameOption();
return $this->cacheDir . DIRECTORY_SEPARATOR . $generator($id);
}
/**
* Get a wildcard for all files
*
* @return string
*/
protected function getWildcard(): string
{
$generator = $this->getFilenameOption();
return $this->cacheDir . DIRECTORY_SEPARATOR . $generator('');
}
}

View File

@ -0,0 +1,65 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
/**
* Auto initialize the cache
*/
trait InitializeTrait
{
/**
* Is cache initialized
* @var bool|null
*/
protected $initialized = false;
/**
* Enable/disable initialization
*
* @param bool $enabled
*/
public function setInitializeOption(bool $enabled)
{
$this->initialized = $enabled ? (bool)$this->initialized : null;
}
/**
* Should initialize
*
* @return bool
*/
protected function getInitializeOption(): bool
{
return $this->initialized !== null;
}
/**
* Mark as initialization required (if enabled)
*/
protected function requireInitialization()
{
$this->initialized = isset($this->initialized) ? false : null;
}
/**
* Initialize
*
* @return void
*/
abstract protected function initialize(): void;
}

View File

@ -0,0 +1,49 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
/**
* Prefix option
*/
trait PrefixTrait
{
/**
* @var string
*/
protected $prefix = '';
/**
* Set the key prefix
*
* @param string $prefix
* @return void
*/
protected function setPrefixOption(string $prefix): void
{
$this->prefix = $prefix;
}
/**
* Get the key prefix
*
* @return string
*/
protected function getPrefixOption(): string
{
return $this->prefix;
}
}

View File

@ -0,0 +1,54 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Option;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* TTL option
*/
trait TtlTrait
{
/**
* @var int|null
*/
protected $ttl = null;
/**
* Set the maximum time to live (ttl)
*
* @param int|null $value Seconds or null to live forever
* @throws InvalidArgumentException
*/
protected function setTtlOption(?int $value): void
{
if (isset($value) && $value < 1) {
throw new InvalidArgumentException('ttl cant be lower than 1');
}
$this->ttl = $value;
}
/**
* Get the maximum time to live (ttl)
*
* @return int|null
*/
protected function getTtlOption(): ?int
{
return $this->ttl;
}
}

View File

@ -0,0 +1,69 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Pack value through serialization
*/
class JsonPacker implements PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'json';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return json_encode($value);
}
/**
* Unpack the value
*
* @param string $packed
* @return mixed
* @throws InvalidArgumentException
*/
public function unpack($packed)
{
if (!is_string($packed)) {
throw new InvalidArgumentException("packed value should be a string");
}
$ret = json_decode($packed);
if (!isset($ret) && json_last_error()) {
throw new \UnexpectedValueException("packed value is not a valid JSON string");
}
return $ret;
}
}

View File

@ -0,0 +1,77 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use MongoDB\BSON\Binary;
/**
* Pack as BSON binary
*
* @todo Don't use serialize when packer chain is here.
*/
class MongoDBBinaryPacker implements PackerInterface
{
/**
* @var array
*/
protected $options;
/**
* SerializePacker constructor
*
* @param array $options Any options to be provided to unserialize()
*/
public function __construct(array $options = ['allowed_classes' => true])
{
$this->options = $options;
}
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'bson';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return new Binary(serialize($value), Binary::TYPE_GENERIC);
}
/**
* Unpack the value
*
* @param string $packed
* @return string
* @throws \UnexpectedValueException if he value can't be unpacked
*/
public function unpack($packed)
{
if (!$packed instanceof Binary) {
throw new \InvalidArgumentException("packed value should be BSON binary");
}
return unserialize((string)$packed, $this->options);
}
}

View File

@ -0,0 +1,57 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
/**
* Don't pack, just straight passthrough
*/
class NopPacker implements PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'data';
}
/**
* Pack the value
*
* @param mixed $value
* @return mixed
*/
public function pack($value)
{
return $value;
}
/**
* Unpack the value
*
* @param mixed $packed
* @return mixed
*/
public function unpack($packed)
{
return $packed;
}
}

View File

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
/**
* Interface for packer / unpacker
*/
interface PackerInterface
{
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType();
/**
* Pack the value
*
* @param mixed $value
* @return string|mixed
*/
public function pack($value);
/**
* Unpack the value
*
* @param string|mixed $packed
* @return string
* @throws \UnexpectedValueException if the value can't be unpacked
*/
public function unpack($packed);
}

View File

@ -0,0 +1,86 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
/**
* Support packing for Caching adapter
*/
trait PackingTrait
{
/**
* @var PackerInterface
*/
protected $packer;
/**
* Create the default packer for this cache implementation
*
* @return PackerInterface
*/
abstract protected static function createDefaultPacker(): PackerInterface;
/**
* Set a packer to pack (serialialize) and unpack (unserialize) the data.
*
* @param PackerInterface $packer
* @return static
*/
public function withPacker(PackerInterface $packer)
{
$cache = $this->cloneSelf();
$cache->packer = $packer;
return $cache;
}
/**
* Get the packer
*
* @return PackerInterface
*/
protected function getPacker(): PackerInterface
{
if (!isset($this->packer)) {
$this->packer = static::createDefaultPacker();
}
return $this->packer;
}
/**
* Pack the value
*
* @param mixed $value
* @return string|mixed
*/
protected function pack($value)
{
return $this->getPacker()->pack($value);
}
/**
* Unpack the data to retrieve the value
*
* @param string|mixed $packed
* @return mixed
* @throws \UnexpectedValueException
*/
protected function unpack($packed)
{
return $this->getPacker()->unpack($packed);
}
}

View File

@ -0,0 +1,78 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache\Packer;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* Pack value through serialization
*/
class SerializePacker implements PackerInterface
{
/**
* @var array
*/
protected $options;
/**
* SerializePacker constructor
*
* @param array $options Any options to be provided to unserialize()
*/
public function __construct(array $options = ['allowed_classes' => true])
{
$this->options = $options;
}
/**
* Get cache type (might be used as file extension)
*
* @return string
*/
public function getType()
{
return 'php.cache';
}
/**
* Pack the value
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return serialize($value);
}
/**
* Unpack the value
*
* @param string $packed
* @return string
* @throws \UnexpectedValueException if he value can't be unpacked
*/
public function unpack($packed)
{
if (!is_string($packed)) {
throw new InvalidArgumentException("packed value should be a string");
}
return unserialize($packed, $this->options);
}
}

View File

@ -0,0 +1,111 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractFile;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
use Desarrolla2\Cache\File\BasicFilename;
/**
* Cache file as PHP script.
*/
class PhpFile extends AbstractFile
{
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Get the filename callable
*
* @return callable
*/
protected function getFilenameOption(): callable
{
if (!isset($this->filename)) {
$this->filename = new BasicFilename('%s.php');
}
return $this->filename;
}
/**
* Create a PHP script returning the cached value
*
* @param mixed $value
* @param int|null $ttl
* @return string
*/
public function createScript($value, ?int $ttl): string
{
$macro = var_export($value, true);
if (strpos($macro, 'stdClass::__set_state') !== false) {
$macro = preg_replace_callback("/('([^'\\\\]++|''\\.)')|stdClass::__set_state/", $macro, function($match) {
return empty($match[1]) ? '(object)' : $match[1];
});
}
return $ttl !== null
? "<?php return time() < {$ttl} ? {$macro} : false;"
: "<?php return {$macro};";
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$cacheFile = $this->getFilename($key);
if (!file_exists($cacheFile)) {
return $default;
}
$packed = include $cacheFile;
return $packed === false ? $default : $this->unpack($packed);
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return $this->get($key) !== null;
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$cacheFile = $this->getFilename($key);
$packed = $this->pack($value);
$script = $this->createScript($packed, $this->ttlToTimestamp($ttl));
return $this->writeFile($cacheFile, $script);
}
}

View File

@ -0,0 +1,245 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
declare(strict_types=1);
namespace Desarrolla2\Cache;
use Desarrolla2\Cache\AbstractCache;
use Desarrolla2\Cache\Exception\UnexpectedValueException;
use Desarrolla2\Cache\Packer\PackerInterface;
use Desarrolla2\Cache\Packer\SerializePacker;
use Predis\Client;
use Predis\Response\ServerException;
use Predis\Response\Status;
use Predis\Response\ErrorInterface;
/**
* Predis cache adapter.
*
* Errors are silently ignored but ServerExceptions are **not** caught. To PSR-16 compliant disable the `exception`
* option.
*/
class Predis extends AbstractCache
{
/**
* @var Client
*/
protected $predis;
/**
* Class constructor
* @see predis documentation about how know your configuration https://github.com/nrk/predis
*
* @param Client $client
*/
public function __construct(Client $client)
{
$this->predis = $client;
}
/**
* Create the default packer for this cache implementation.
*
* @return PackerInterface
*/
protected static function createDefaultPacker(): PackerInterface
{
return new SerializePacker();
}
/**
* Run a predis command.
*
* @param string $cmd
* @param mixed ...$args
* @return mixed|bool
*/
protected function execCommand(string $cmd, ...$args)
{
$command = $this->predis->createCommand($cmd, $args);
$response = $this->predis->executeCommand($command);
if ($response instanceof ErrorInterface) {
return false;
}
if ($response instanceof Status) {
return $response->getPayload() === 'OK';
}
return $response;
}
/**
* Set multiple (mset) with expire
*
* @param array $dictionary
* @param int|null $ttlSeconds
* @return bool
*/
protected function msetExpire(array $dictionary, ?int $ttlSeconds): bool
{
if (empty($dictionary)) {
return true;
}
if (!isset($ttlSeconds)) {
return $this->execCommand('MSET', $dictionary);
}
$transaction = $this->predis->transaction();
foreach ($dictionary as $key => $value) {
$transaction->set($key, $value, 'EX', $ttlSeconds);
}
try {
$responses = $transaction->execute();
} catch (ServerException $e) {
return false;
}
$ok = array_reduce($responses, function($ok, $response) {
return $ok && $response instanceof Status && $response->getPayload() === 'OK';
}, true);
return $ok;
}
/**
* {@inheritdoc}
*/
public function get($key, $default = null)
{
$id = $this->keyToId($key);
$response = $this->execCommand('GET', $id);
return !empty($response) ? $this->unpack($response) : $default;
}
/**
* {@inheritdoc}
*/
public function getMultiple($keys, $default = null)
{
$idKeyPairs = $this->mapKeysToIds($keys);
$ids = array_keys($idKeyPairs);
$response = $this->execCommand('MGET', $ids);
if ($response === false) {
return false;
}
$items = [];
$packedItems = array_combine(array_values($idKeyPairs), $response);
foreach ($packedItems as $key => $packed) {
$items[$key] = isset($packed) ? $this->unpack($packed) : $default;
}
return $items;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return $this->execCommand('EXISTS', $this->keyToId($key));
}
/**
* {@inheritdoc}
*/
public function set($key, $value, $ttl = null)
{
$id = $this->keyToId($key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->execCommand('DEL', [$id]);
}
return !isset($ttlSeconds)
? $this->execCommand('SET', $id, $packed)
: $this->execCommand('SETEX', $id, $ttlSeconds, $packed);
}
/**
* {@inheritdoc}
*/
public function setMultiple($values, $ttl = null)
{
$this->assertIterable($values, 'values not iterable');
$dictionary = [];
foreach ($values as $key => $value) {
$id = $this->keyToId(is_int($key) ? (string)$key : $key);
$packed = $this->pack($value);
if (!is_string($packed)) {
throw new UnexpectedValueException("Packer must create a string for the data");
}
$dictionary[$id] = $packed;
}
$ttlSeconds = $this->ttlToSeconds($ttl);
if (isset($ttlSeconds) && $ttlSeconds <= 0) {
return $this->execCommand('DEL', array_keys($dictionary));
}
return $this->msetExpire($dictionary, $ttlSeconds);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
$id = $this->keyToId($key);
return $this->execCommand('DEL', [$id]) !== false;
}
/**
* {@inheritdoc}
*/
public function deleteMultiple($keys)
{
$ids = array_keys($this->mapKeysToIds($keys));
return empty($ids) || $this->execCommand('DEL', $ids) !== false;
}
/**
* {@inheritdoc}
*/
public function clear()
{
return $this->execCommand('FLUSHDB');
}
}

View File

@ -0,0 +1,93 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Cache\IntegrationTests\SimpleCacheTest;
use Desarrolla2\Cache\Exception\InvalidArgumentException;
/**
* AbstractCacheTest
*/
abstract class AbstractCacheTest extends SimpleCacheTest
{
/**
* @return array
*/
public function dataProviderForOptions()
{
return [
['ttl', 100],
['prefix', 'test']
];
}
/**
* @dataProvider dataProviderForOptions
*
* @param string $key
* @param mixed $value
*/
public function testWithOption($key, $value)
{
$cache = $this->cache->withOption($key, $value);
$this->assertEquals($value, $cache->getOption($key));
// Check immutability
$this->assertNotSame($this->cache, $cache);
$this->assertNotEquals($value, $this->cache->getOption($key));
}
public function testWithOptions()
{
$data = $this->dataProviderForOptions();
$options = array_combine(array_column($data, 0), array_column($data, 1));
$cache = $this->cache->withOptions($options);
foreach ($options as $key => $value) {
$this->assertEquals($value, $cache->getOption($key));
}
// Check immutability
$this->assertNotSame($this->cache, $cache);
foreach ($options as $key => $value) {
$this->assertNotEquals($value, $this->cache->getOption($key));
}
}
/**
* @return array
*/
public function dataProviderForOptionsException()
{
return [
['ttl', 0, InvalidArgumentException::class],
['foo', 'bar', InvalidArgumentException::class]
];
}
/**
* @dataProvider dataProviderForOptionsException
*
* @param string $key
* @param mixed $value
* @param string $expectedException
*/
public function testWithOptionException($key, $value, $expectedException)
{
$this->expectException($expectedException);
$this->createSimpleCache()->withOption($key, $value);
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Apcu as ApcuCache;
/**
* ApcuCacheTest
*/
class ApcuCacheTest extends AbstractCacheTest
{
public static function setUpBeforeClass(): void
{
// Required to check the TTL for new entries
ini_set('apc.use_request_time', false);
}
public function createSimpleCache()
{
if (!extension_loaded('apcu')) {
$this->markTestSkipped(
'The APCu extension is not available.'
);
}
if (!ini_get('apc.enable_cli')) {
$this->markTestSkipped(
'You need to enable apc.enable_cli'
);
}
return new ApcuCache();
}
}

View File

@ -0,0 +1,216 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Chain as CacheChain;
use Desarrolla2\Cache\Memory as MemoryCache;
/**
* ChainTest
*/
class ChainTest extends AbstractCacheTest
{
public function createSimpleCache()
{
$adapters = [new MemoryCache()]; // For the general PSR-16 tests, we don't need more than 1 adapter
return new CacheChain($adapters);
}
public function tearDown(): void
{
// No need to clear cache, as the adapters don't persist between tests.
}
public function testChainSet()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('set')->with("foo", "bar", 300);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('set')->with("foo", "bar", 300);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->set("foo", "bar", 300);
}
public function testChainSetMultiple()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('setMultiple')->with(["foo" => 1, "bar" => 2], 300);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('setMultiple')->with(["foo" => 1, "bar" => 2], 300);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->setMultiple(["foo" => 1, "bar" => 2], 300);
}
public function testChainGetFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn("bar");
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('get');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals("bar", $cache->get("foo", 42));
}
public function testChainGetSecond()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn(null);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('get')->with("foo")->willReturn("car");
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals("car", $cache->get("foo", 42));
}
public function testChainGetNone()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('get')->with("foo")->willReturn(null);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('get')->with("foo")->willReturn(null);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals(42, $cache->get("foo", 42));
}
public function testChainGetMultipleFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('getMultiple')->with(["foo", "bar"])
->willReturn(["foo" => 1, "bar" => 2]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('getMultiple');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertEquals(["foo" => 1, "bar" => 2], $cache->getMultiple(["foo", "bar"]));
}
public function testChainGetMultipleMixed()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('getMultiple')
->with($this->equalTo(["foo", "bar", "wux", "lot"]))
->willReturn(["foo" => null, "bar" => 2, "wux" => null, "lot" => null]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('getMultiple')
->with($this->equalTo(["foo", "wux", "lot"]))
->willReturn(["foo" => 11, "wux" => 15, "lot" => null]);
$cache = new CacheChain([$adapter1, $adapter2]);
$expected = ["foo" => 11, "bar" => 2, "wux" => 15, "lot" => 42];
$this->assertEquals($expected, $cache->getMultiple(["foo", "bar", "wux", "lot"], 42));
}
public function testChainHasFirst()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(true);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->never())->method('has');
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertTrue($cache->has("foo"));
}
public function testChainHasSecond()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(false);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('has')->with("foo")->willReturn(true);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertTrue($cache->has("foo"));
}
public function testChainHasNone()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('has')->with("foo")->willReturn(false);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('has')->with("foo")->willReturn(false);
$cache = new CacheChain([$adapter1, $adapter2]);
$this->assertFalse($cache->has("foo"));
}
public function testChainDelete()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('delete')->with("foo");
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('delete')->with("foo");
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->delete("foo");
}
public function testChainDeleteMultiple()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('deleteMultiple')->with(["foo", "bar"]);
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('deleteMultiple')->with(["foo", "bar"]);
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->deleteMultiple(["foo", "bar"]);
}
public function testChainClear()
{
$adapter1 = $this->createMock(MemoryCache::class);
$adapter1->expects($this->once())->method('clear');
$adapter2 = $this->createMock(MemoryCache::class);
$adapter2->expects($this->once())->method('clear');
$cache = new CacheChain([$adapter1, $adapter2]);
$cache->clear();
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest
*/
class FileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return new FileCache(vfsStream::url('cache'));
}
}

View File

@ -0,0 +1,43 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use Desarrolla2\Cache\File\TrieFilename;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest with Trie structure
*/
class FileTrieTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return (new FileCache(vfsStream::url('cache')))
->withOption('filename', new TrieFilename('%s.php.cache',4));
}
}

View File

@ -0,0 +1,42 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
* @author Arnold Daniels <arnold@jasny.net>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\File as FileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest
*/
class FileTtlFileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return (new FileCache(vfsStream::url('cache')))
->withOption('ttl-strategy', 'file');
}
}

View File

@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Memcached as MemcachedCache;
use Memcached;
/**
* MemcachedTest
*/
class MemcachedTest extends AbstractCacheTest
{
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 250 bytes'
];
public function createSimpleCache()
{
if (!extension_loaded('memcached') || !class_exists('\Memcached')) {
$this->markTestSkipped(
'The Memcached extension is not available.'
);
}
list($host, $port) = explode(':', CACHE_TESTS_MEMCACHED_SERVER) + [1 => 11211];
$adapter = new Memcached();
$adapter->addServer($host, (int)$port);
if (!$adapter->flush()) {
$this->markTestSkipped("Unable to flush Memcached; not running?");
}
return new MemcachedCache($adapter);
}
}

View File

@ -0,0 +1,44 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Memory as MemoryCache;
/**
* MemoryTest
*/
class MemoryTest extends AbstractCacheTest
{
public function createSimpleCache()
{
return new MemoryCache();
}
public function tearDown(): void
{
// No need to clear cache, as the adapters don't persist between tests.
}
public function testExceededLimit()
{
$cache = $this->createSimpleCache()->withOption('limit', 1);
$cache->set('foo', 1);
$this->assertTrue($cache->has('foo'));
$cache->set('bar', 1);
$this->assertFalse($cache->has('foo'));
$this->assertTrue($cache->has('bar'));
}
}

View File

@ -0,0 +1,53 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\MongoDB as MongoDBCache;
use MongoDB\Client;
/**
* MongoDBTest
*/
class MongoDBTest extends AbstractCacheTest
{
/**
* @var Client
*/
protected static $client;
/**
* Use one client per test, as the MongoDB extension leaves connections open
*/
public static function setUpBeforeClass(): void
{
if (!extension_loaded('mongodb')) {
return;
}
self::$client = new Client(CACHE_TESTS_MONGO_DSN);
self::$client->listDatabases(); // Fail if unable to connect
}
public function createSimpleCache()
{
if (!isset(self::$client)) {
$this->markTestSkipped('The mongodb extension is not available');
}
$collection = self::$client->selectCollection(CACHE_TESTS_MONGO_DATABASE, 'cache');
return (new MongoDBCache($collection))
->withOption('initialize', false);
}
}

View File

@ -0,0 +1,75 @@
<?php
/**
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Mysqli as MysqliCache;
/**
* MysqliTest
*/
class MysqliTest extends AbstractCacheTest
{
/**
* @var \mysqli
*/
protected static $mysqli;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 255 bytes'
];
public static function setUpBeforeClass(): void
{
if (class_exists('mysqli')) {
static::$mysqli = new \mysqli(
ini_get('mysqli.default_host') ?: 'localhost',
ini_get('mysqli.default_user') ?: 'root'
);
}
}
public function init(): void
{
if (!class_exists('mysqli')) {
$this->markTestSkipped("mysqli extension not loaded");
}
try {
static::$mysqli->query('CREATE DATABASE IF NOT EXISTS `' . CACHE_TESTS_MYSQLI_DATABASE . '`');
static::$mysqli->select_db(CACHE_TESTS_MYSQLI_DATABASE);
static::$mysqli->query("CREATE TABLE IF NOT EXISTS `cache` "
."( `key` VARCHAR(255), `value` BLOB, `ttl` INT UNSIGNED, PRIMARY KEY (`key`) )");
} catch (\Exception $e) {
$this->markTestSkipped("skipping mysqli test; " . $e->getMessage());
}
if (static::$mysqli->error) {
$this->markTestSkipped(static::$mysqli->error);
}
}
public function createSimpleCache()
{
$this->init();
return (new MysqliCache(static::$mysqli))
->withOption('initialize', false);
}
public static function tearDownAfterClass(): void
{
static::$mysqli->query('DROP DATABASE IF EXISTS `' . CACHE_TESTS_MYSQLI_DATABASE . '`');
static::$mysqli->close();
}
}

View File

@ -0,0 +1,88 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\NotCache as NotCache;
use PHPUnit\Framework\TestCase;
/**
* NotCacheTest
*/
class NotCacheTest extends TestCase
{
/**
* @var \Desarrolla2\Cache\NotCache
*/
protected $cache;
public function setUp(): void
{
$this->cache = new NotCache();
}
/**
* @return array
*/
public function dataProvider()
{
return array(
array(),
);
}
/**
* @dataProvider dataProvider
*/
public function testHas()
{
$this->cache->set('key', 'value');
$this->assertFalse($this->cache->has('key'));
}
/**
* @dataProvider dataProvider
*/
public function testGet()
{
$this->cache->set('key', 'value');
$this->assertFalse($this->cache->get('key', false));
}
/**
* @dataProvider dataProvider
*/
public function testSet()
{
$this->assertFalse($this->cache->set('key', 'value'));
}
/**
* @dataProvider dataProvider
*/
public function testDelete()
{
$this->assertTrue($this->cache->delete('key'));
}
/**
* @dataProvider dataProvider
*/
public function testWithOption()
{
$cache = $this->cache->withOption('ttl', 3600);
$this->assertSame(3600, $cache->getOption('ttl'));
$this->assertNotSame($this->cache, $cache);
}
}

View File

@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\PhpFile as PhpFileCache;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
/**
* FileTest with PhpPacker
*/
class PhpFileTest extends AbstractCacheTest
{
/**
* @var vfsStreamDirectory
*/
private $root;
protected $skippedTests = [
'testBasicUsageWithLongKey' => 'Only support keys up to 64 bytes'
];
public function createSimpleCache()
{
$this->root = vfsStream::setup('cache');
return new PhpFileCache(vfsStream::url('cache'));
}
}

View File

@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
namespace Desarrolla2\Test\Cache;
use Desarrolla2\Cache\Predis as PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;
/**
* PredisTest
*/
class PredisTest extends AbstractCacheTest
{
/**
* @var Client
*/
protected $client;
public function createSimpleCache()
{
if (!class_exists('Predis\Client')) {
$this->markTestSkipped('The predis library is not available');
}
try {
$this->client = new Client(CACHE_TESTS_PREDIS_DSN, ['exceptions' => false]);
$this->client->connect();
} catch (ConnectionException $e) {
$this->markTestSkipped($e->getMessage());
}
return new PredisCache($this->client);
}
public function tearDown(): void
{
parent::tearDown();
$this->client->disconnect();
}
}

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\Apcu;
$cache = new Cache(new Apcu());
require_once __DIR__.'/common.php';

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\File;
$cache = new Cache(new File('/tmp'));
require_once __DIR__.'/common.php';

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\Mongo;
$cache = new Cache(new Mongo('mongodb://localhost:27017'));
require_once __DIR__.'/common.php';

View File

@ -0,0 +1,21 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
require_once __DIR__.'/../bootstrap.php';
use Desarrolla2\Cache\Cache;
use Desarrolla2\Cache\Adapter\NotCache;
$cache = new Cache(new NotCache());
require_once __DIR__.'/common.php';

View File

@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Cache package.
*
* Copyright (c) Daniel González
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Daniel González <daniel@desarrolla2.com>
*/
//build test data outside of timing loop
$data = [];
for ($i = 1; $i <= 10000; $i++) {
$data[$i] = md5($i);
}
$timer = new \Desarrolla2\Timer\Timer(new \Desarrolla2\Timer\Formatter\Human());
for ($i = 1; $i <= 10000; $i++) {
$cache->set($data[$i], $data[$i], 3600);
}
$timer->mark('10.000 set');
for ($i = 1; $i <= 10000; $i++) {
$cache->has($data[$i]);
}
$timer->mark('10.000 has');
for ($i = 1; $i <= 10000; $i++) {
$cache->get($data[$i]);
}
$timer->mark('10.000 get');
for ($i = 1; $i <= 10000; $i++) {
$cache->has($data[$i]);
$cache->get($data[$i]);
}
$timer->mark('10.000 has+get combos');
$benchmarks = $timer->getAll();
foreach ($benchmarks as $benchmark) {
ld($benchmark);
}

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
interface ConnectionProvider
{
public function provideConnection(): SFTP;
}

View File

@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace League\Flysystem\PhpseclibV2;
use phpseclib\Net\SFTP;
interface ConnectivityChecker
{
public function isConnected(SFTP $connection): bool;
}

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