PK 髏PK8%
LICENSE.mdnu W+A Copyright (c) 2020 Laminas Project a Series of LF Projects, LLC.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Laminas Foundation nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
PK 髏PF[ [ COPYRIGHT.mdnu W+A Copyright (c) 2020 Laminas Project a Series of LF Projects, LLC. (https://getlaminas.org/)
PK 髏PyG\ .travis.ymlnu W+A language: php
cache:
directories:
- $HOME/.composer/cache
env:
global:
- COMPOSER_ARGS="--no-interaction"
- COVERAGE_DEPS="php-coveralls/php-coveralls"
matrix:
fast_finish: true
include:
- php: 5.6
env:
- DEPS=lowest
- REMOVE_DEV_DEPS="psr/http-factory"
- php: 5.6
env:
- DEPS=latest
- REMOVE_DEV_DEPS="psr/http-factory"
- php: 7
env:
- DEPS=lowest
- php: 7
env:
- DEPS=latest
- php: 7.1
env:
- DEPS=lowest
- php: 7.1
env:
- DEPS=latest
- CS_CHECK=true
- TEST_COVERAGE=true
- php: 7.2
env:
- DEPS=lowest
- php: 7.2
env:
- DEPS=latest
before_install:
- if [[ $TEST_COVERAGE != 'true' ]]; then phpenv config-rm xdebug.ini || return 0 ; fi
- if [[ $REMOVE_DEV_DEPS != '' ]]; then travis_retry composer remove $COMPOSER_ARGS --dev --no-update $REMOVE_DEV_DEPS ; fi
install:
- travis_retry composer install $COMPOSER_ARGS --ignore-platform-reqs
- if [[ $LEGACY_DEPS != '' ]]; then travis_retry composer update $COMPOSER_ARGS --with-dependencies $LEGACY_DEPS ; fi
- if [[ $DEPS == 'latest' ]]; then travis_retry composer update $COMPOSER_ARGS ; fi
- if [[ $DEPS == 'lowest' ]]; then travis_retry composer update --prefer-lowest --prefer-stable $COMPOSER_ARGS ; fi
- if [[ $TEST_COVERAGE == 'true' ]]; then travis_retry composer require --dev $COMPOSER_ARGS $COVERAGE_DEPS ; fi
- stty cols 120 && composer show
script:
- if [[ $TEST_COVERAGE == 'true' ]]; then composer test-coverage ; else composer test ; fi
- if [[ $CS_CHECK == 'true' ]]; then composer cs-check ; fi
after_script:
- if [[ $TEST_COVERAGE == 'true' ]]; then vendor/bin/php-coveralls -v ; fi
notifications:
email: false
PK 髏Px= = .coveralls.ymlnu W+A coverage_clover: clover.xml
json_path: coveralls-upload.json
PK 髏P}CC phpcs.xmlnu W+A
src
test
PK 髏P README.mdnu W+A # laminas-filter
[![Build Status](https://travis-ci.com/laminas/laminas-filter.svg?branch=master)](https://travis-ci.com/laminas/laminas-filter)
[![Coverage Status](https://coveralls.io/repos/github/laminas/laminas-filter/badge.svg?branch=master)](https://coveralls.io/github/laminas/laminas-filter?branch=master)
The `Laminas\Filter` component provides a set of commonly needed data filters. It
also provides a simple filter chaining mechanism by which multiple filters may
be applied to a single datum in a user-defined order.
- File issues at https://github.com/laminas/laminas-filter/issues
- Documentation is at https://docs.laminas.dev/laminas-filter/
PK 髏P@ݫ
.gitignorenu W+A /clover.xml
/composer.lock
/coveralls-upload.json
/docs/html/
/laminas-mkdoc-theme.tgz
/laminas-mkdoc-theme/
/phpunit.xml
/vendor/
PK 髏Pys " src/FilterPluginManagerFactory.phpnu W+A has('ServiceListener')) {
return $pluginManager;
}
// If we do not have a config service, nothing more to do
if (! $container->has('config')) {
return $pluginManager;
}
$config = $container->get('config');
// If we do not have filters configuration, nothing more to do
if (! isset($config['filters']) || ! is_array($config['filters'])) {
return $pluginManager;
}
// Wire service configuration for validators
(new Config($config['filters']))->configureServiceManager($pluginManager);
return $pluginManager;
}
/**
* {@inheritDoc}
*
* @return FilterPluginManager
*/
public function createService(ServiceLocatorInterface $container, $name = null, $requestedName = null)
{
return $this($container, $requestedName ?: FilterPluginManager::class, $this->creationOptions);
}
/**
* laminas-servicemanager v2 support for invocation options.
*
* @param array $options
* @return void
*/
public function setCreationOptions(array $options)
{
$this->creationOptions = $options;
}
}
PK 髏Pp src/Int.phpnu W+A null,
'replacement' => '',
];
/**
* Constructor
* Supported options are
* 'pattern' => matching pattern
* 'replacement' => replace with this
*
* @param array|Traversable|string|null $options
*/
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = iterator_to_array($options);
}
if (! is_array($options) || (! isset($options['pattern']) && ! isset($options['replacement']))) {
$args = func_get_args();
if (isset($args[0])) {
$this->setPattern($args[0]);
}
if (isset($args[1])) {
$this->setReplacement($args[1]);
}
} else {
$this->setOptions($options);
}
}
/**
* Set the regex pattern to search for
* @see preg_replace()
*
* @param string|array $pattern - same as the first argument of preg_replace
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setPattern($pattern)
{
if (! is_array($pattern) && ! is_string($pattern)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects pattern to be array or string; received "%s"',
__METHOD__,
(is_object($pattern) ? get_class($pattern) : gettype($pattern))
));
}
if (is_array($pattern)) {
foreach ($pattern as $p) {
$this->validatePattern($p);
}
}
if (is_string($pattern)) {
$this->validatePattern($pattern);
}
$this->options['pattern'] = $pattern;
return $this;
}
/**
* Get currently set match pattern
*
* @return string|array
*/
public function getPattern()
{
return $this->options['pattern'];
}
/**
* Set the replacement array/string
* @see preg_replace()
*
* @param array|string $replacement - same as the second argument of preg_replace
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setReplacement($replacement)
{
if (! is_array($replacement) && ! is_string($replacement)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects replacement to be array or string; received "%s"',
__METHOD__,
(is_object($replacement) ? get_class($replacement) : gettype($replacement))
));
}
$this->options['replacement'] = $replacement;
return $this;
}
/**
* Get currently set replacement value
*
* @return string|array
*/
public function getReplacement()
{
return $this->options['replacement'];
}
/**
* Perform regexp replacement as filter
*
* @param mixed $value
* @return mixed
* @throws Exception\RuntimeException
*/
public function filter($value)
{
if (! is_scalar($value) && ! is_array($value)) {
return $value;
}
if ($this->options['pattern'] === null) {
throw new Exception\RuntimeException(sprintf(
'Filter %s does not have a valid pattern set',
get_class($this)
));
}
return preg_replace($this->options['pattern'], $this->options['replacement'], $value);
}
/**
* Validate a pattern and ensure it does not contain the "e" modifier
*
* @param string $pattern
* @return bool
* @throws Exception\InvalidArgumentException
*/
protected function validatePattern($pattern)
{
if (! preg_match('/(?[imsxeADSUXJu]+)$/', $pattern, $matches)) {
return true;
}
if (false !== strpos($matches['modifier'], 'e')) {
throw new Exception\InvalidArgumentException(sprintf(
'Pattern for a PregReplace filter may not contain the "e" pattern modifier; received "%s"',
$pattern
));
}
}
}
PK 髏P(Hw w src/FilterChain.phpnu W+A filters = new PriorityQueue();
if (null !== $options) {
$this->setOptions($options);
}
}
/**
* @param array|Traversable $options
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setOptions($options)
{
if (! is_array($options) && ! $options instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'Expected array or Traversable; received "%s"',
(is_object($options) ? get_class($options) : gettype($options))
));
}
foreach ($options as $key => $value) {
switch (strtolower($key)) {
case 'callbacks':
foreach ($value as $spec) {
$callback = isset($spec['callback']) ? $spec['callback'] : false;
$priority = isset($spec['priority']) ? $spec['priority'] : static::DEFAULT_PRIORITY;
if ($callback) {
$this->attach($callback, $priority);
}
}
break;
case 'filters':
foreach ($value as $spec) {
$name = isset($spec['name']) ? $spec['name'] : false;
$options = isset($spec['options']) ? $spec['options'] : [];
$priority = isset($spec['priority']) ? $spec['priority'] : static::DEFAULT_PRIORITY;
if ($name) {
$this->attachByName($name, $options, $priority);
}
}
break;
default:
// ignore other options
break;
}
}
return $this;
}
/**
* Return the count of attached filters
*
* @return int
*/
public function count()
{
return count($this->filters);
}
/**
* Get plugin manager instance
*
* @return FilterPluginManager
*/
public function getPluginManager()
{
if (! $this->plugins) {
$this->setPluginManager(new FilterPluginManager(new ServiceManager()));
}
return $this->plugins;
}
/**
* Set plugin manager instance
*
* @param FilterPluginManager $plugins
* @return self
*/
public function setPluginManager(FilterPluginManager $plugins)
{
$this->plugins = $plugins;
return $this;
}
/**
* Retrieve a filter plugin by name
*
* @param mixed $name
* @param array $options
* @return FilterInterface
*/
public function plugin($name, array $options = [])
{
$plugins = $this->getPluginManager();
return $plugins->get($name, $options);
}
/**
* Attach a filter to the chain
*
* @param callable|FilterInterface $callback A Filter implementation or valid PHP callback
* @param int $priority Priority at which to enqueue filter; defaults to 1000 (higher executes earlier)
* @throws Exception\InvalidArgumentException
* @return self
*/
public function attach($callback, $priority = self::DEFAULT_PRIORITY)
{
if (! is_callable($callback)) {
if (! $callback instanceof FilterInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'Expected a valid PHP callback; received "%s"',
(is_object($callback) ? get_class($callback) : gettype($callback))
));
}
$callback = [$callback, 'filter'];
}
$this->filters->insert($callback, $priority);
return $this;
}
/**
* Attach a filter to the chain using a short name
*
* Retrieves the filter from the attached plugin manager, and then calls attach()
* with the retrieved instance.
*
* @param string $name
* @param mixed $options
* @param int $priority Priority at which to enqueue filter; defaults to 1000 (higher executes earlier)
* @return self
*/
public function attachByName($name, $options = [], $priority = self::DEFAULT_PRIORITY)
{
if (! is_array($options)) {
$options = (array) $options;
} elseif (empty($options)) {
$options = null;
}
$filter = $this->getPluginManager()->get($name, $options);
return $this->attach($filter, $priority);
}
/**
* Merge the filter chain with the one given in parameter
*
* @param FilterChain $filterChain
* @return self
*/
public function merge(FilterChain $filterChain)
{
foreach ($filterChain->filters->toArray(PriorityQueue::EXTR_BOTH) as $item) {
$this->attach($item['data'], $item['priority']);
}
return $this;
}
/**
* Get all the filters
*
* @return PriorityQueue
*/
public function getFilters()
{
return $this->filters;
}
/**
* Returns $value filtered through each filter in the chain
*
* Filters are run in the order in which they were added to the chain (FIFO)
*
* @param mixed $value
* @return mixed
*/
public function filter($value)
{
$chain = clone $this->filters;
$valueFiltered = $value;
foreach ($chain as $filter) {
$valueFiltered = call_user_func($filter, $valueFiltered);
}
return $valueFiltered;
}
/**
* Clone filters
*/
public function __clone()
{
$this->filters = clone $this->filters;
}
/**
* Prepare filter chain for serialization
*
* Plugin manager (property 'plugins') cannot
* be serialized. On wakeup the property remains unset
* and next invocation to getPluginManager() sets
* the default plugin manager instance (FilterPluginManager).
*/
public function __sleep()
{
return ['filters'];
}
}
PK 髏PN N src/StaticFilter.phpnu W+A get($classBaseName, $args);
return $filter->filter($value);
}
}
PK 髏PίѢ src/StringPrefix.phpnu W+A
*/
protected $options = [
'prefix' => null,
];
/**
* @param string|array|Traversable $options
*/
public function __construct($options = null)
{
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Set the prefix string
*
* @param string $prefix
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setPrefix($prefix)
{
if (! is_string($prefix)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects "prefix" to be string; received "%s"',
__METHOD__,
is_object($prefix) ? get_class($prefix) : gettype($prefix)
));
}
$this->options['prefix'] = $prefix;
return $this;
}
/**
* Returns the prefix string, which is appended at the beginning of the input value
*
* @return string
*/
public function getPrefix()
{
if (! isset($this->options['prefix'])) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects a "prefix" option; none given',
__CLASS__
));
}
return $this->options['prefix'];
}
/**
* {@inheritdoc}
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
return $this->getPrefix() . $value;
}
}
PK 髏P$Ა` ` src/UriNormalize.phpnu W+A setOptions($options);
}
}
/**
* Set the default scheme to use when parsing scheme-less URIs
*
* The scheme used when parsing URIs may affect the specific object used to
* normalize the URI and thus may affect the resulting normalize URI.
*
* @param string $defaultScheme
* @return self
*/
public function setDefaultScheme($defaultScheme)
{
$this->defaultScheme = $defaultScheme;
return $this;
}
/**
* Set a URI scheme to enforce on schemeless URIs
*
* This allows forcing input values such as 'www.example.com/foo' into
* 'http://www.example.com/foo'.
*
* This should be used with caution, as a standard-compliant URI parser
* would regard 'www.example.com' in the above input URI to be the path and
* not host part of the URI. While this option can assist in solving
* real-world user mishaps, it may yield unexpected results at times.
*
* @param string $enforcedScheme
* @return self
*/
public function setEnforcedScheme($enforcedScheme)
{
$this->enforcedScheme = $enforcedScheme;
return $this;
}
/**
* Filter the URL by normalizing it and applying a default scheme if set
*
* @param string $value
* @return string
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
$defaultScheme = $this->defaultScheme ?: $this->enforcedScheme;
// Reset default scheme if it is not a known scheme
if (! UriFactory::getRegisteredSchemeClass($defaultScheme)) {
$defaultScheme = null;
}
try {
$uri = UriFactory::factory($value, $defaultScheme);
if ($this->enforcedScheme && ! $uri->getScheme()) {
$this->enforceScheme($uri);
}
} catch (UriException $ex) {
// We are unable to parse / enfore scheme with the given config and input
return $value;
}
$uri->normalize();
if (! $uri->isValid()) {
return $value;
}
return $uri->toString();
}
/**
* Enforce the defined scheme on the URI
*
* This will also adjust the host and path parts of the URI as expected in
* the case of scheme-less network URIs
*
* @param Uri $uri
*/
protected function enforceScheme(Uri $uri)
{
$path = $uri->getPath();
if (strpos($path, '/') !== false) {
list($host, $path) = explode('/', $path, 2);
$path = '/' . $path;
} else {
$host = $path;
$path = '';
}
// We have nothing to do if we have no host
if (! $host) {
return;
}
$uri->setScheme($this->enforcedScheme)
->setHost($host)
->setPath($path);
}
}
PK 髏PE_ " src/Exception/RuntimeException.phpnu W+A null,
];
/**
* Constructor
*
* @param string|array|Traversable $encodingOrOptions OPTIONAL
*/
public function __construct($encodingOrOptions = null)
{
if ($encodingOrOptions !== null) {
if (! static::isOptions($encodingOrOptions)) {
$this->setEncoding($encodingOrOptions);
} else {
$this->setOptions($encodingOrOptions);
}
}
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns the string $value, converting characters to uppercase as necessary
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
if (null !== $this->getEncoding()) {
return mb_strtoupper($value, $this->options['encoding']);
}
return strtoupper($value);
}
}
PK 髏P5Y; ; src/FilterInterface.phpnu W+A true
];
/**
* Class constructor
*
* @param bool|Traversable $existsOrOptions Options to set
*/
public function __construct($existsOrOptions = true)
{
if ($existsOrOptions !== null) {
if (! static::isOptions($existsOrOptions)) {
$this->setExists($existsOrOptions);
} else {
$this->setOptions($existsOrOptions);
}
}
}
/**
* Sets if the path has to exist
* TRUE when the path must exist
* FALSE when not existing paths can be given
*
* @param bool $flag Path must exist
* @return self
*/
public function setExists($flag = true)
{
$this->options['exists'] = (bool) $flag;
return $this;
}
/**
* Returns true if the filtered path must exist
*
* @return bool
*/
public function getExists()
{
return $this->options['exists'];
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns realpath($value)
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_string($value)) {
return $value;
}
$path = (string) $value;
if ($this->options['exists']) {
return realpath($path);
}
ErrorHandler::start();
$realpath = realpath($path);
ErrorHandler::stop();
if ($realpath) {
return $realpath;
}
$drive = '';
if (stripos(PHP_OS, 'WIN') === 0) {
$path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path);
if (preg_match('/([a-zA-Z]\:)(.*)/', $path, $matches)) {
list(, $drive, $path) = $matches;
} else {
$cwd = getcwd();
$drive = substr($cwd, 0, 2);
if (strpos($path, DIRECTORY_SEPARATOR) !== 0) {
$path = substr($cwd, 3) . DIRECTORY_SEPARATOR . $path;
}
}
} elseif (strpos($path, DIRECTORY_SEPARATOR) !== 0) {
$path = getcwd() . DIRECTORY_SEPARATOR . $path;
}
$stack = [];
$parts = explode(DIRECTORY_SEPARATOR, $path);
foreach ($parts as $dir) {
if ($dir !== '' && $dir !== '.') {
if ($dir === '..') {
array_pop($stack);
} else {
$stack[] = $dir;
}
}
}
return $drive . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $stack);
}
}
PK 髏P(U U src/ToNull.phpnu W+A 'boolean',
self::TYPE_INTEGER => 'integer',
self::TYPE_EMPTY_ARRAY => 'array',
self::TYPE_STRING => 'string',
self::TYPE_ZERO_STRING => 'zero',
self::TYPE_FLOAT => 'float',
self::TYPE_ALL => 'all',
];
/**
* @var array
*/
protected $options = [
'type' => self::TYPE_ALL,
];
/**
* Constructor
*
* @param int|string|array|Traversable|null $typeOrOptions
*/
public function __construct($typeOrOptions = null)
{
if ($typeOrOptions !== null) {
if ($typeOrOptions instanceof Traversable) {
$typeOrOptions = iterator_to_array($typeOrOptions);
}
if (is_array($typeOrOptions)) {
if (isset($typeOrOptions['type'])) {
$this->setOptions($typeOrOptions);
} else {
$this->setType($typeOrOptions);
}
} else {
$this->setType($typeOrOptions);
}
}
}
/**
* Set boolean types
*
* @param int|string|array $type
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setType($type = null)
{
if (is_array($type)) {
$detected = 0;
foreach ($type as $value) {
if (is_int($value)) {
$detected |= $value;
} elseif (($found = array_search($value, $this->constants, true)) !== false) {
$detected |= $found;
}
}
$type = $detected;
} elseif (is_string($type) && ($found = array_search($type, $this->constants, true)) !== false) {
$type = $found;
}
if (! is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) {
throw new Exception\InvalidArgumentException(sprintf(
'Unknown type value "%s" (%s)',
$type,
gettype($type)
));
}
$this->options['type'] = $type;
return $this;
}
/**
* Returns defined boolean types
*
* @return int
*/
public function getType()
{
return $this->options['type'];
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns null representation of $value, if value is empty and matches
* types that should be considered null.
*
* @param null|array|bool|float|int|string $value
* @return null|mixed
*/
public function filter($value)
{
$type = $this->getType();
// FLOAT (0.0)
if ($type & self::TYPE_FLOAT) {
if (is_float($value) && $value === 0.0) {
return null;
}
}
// STRING ZERO ('0')
if ($type & self::TYPE_ZERO_STRING) {
if (is_string($value) && $value === '0') {
return null;
}
}
// STRING ('')
if ($type & self::TYPE_STRING) {
if (is_string($value) && $value === '') {
return null;
}
}
// EMPTY_ARRAY (array())
if ($type & self::TYPE_EMPTY_ARRAY) {
if (is_array($value) && $value === []) {
return null;
}
}
// INTEGER (0)
if ($type & self::TYPE_INTEGER) {
if (is_int($value) && $value === 0) {
return null;
}
}
// BOOLEAN (false)
if ($type & self::TYPE_BOOLEAN) {
if (is_bool($value) && $value === false) {
return null;
}
}
return $value;
}
}
PK 髏P86 src/Dir.phpnu W+A setAdapter($options);
} elseif ($options instanceof Compress\CompressionAlgorithmInterface) {
$this->setAdapter($options);
} elseif (is_array($options)) {
$this->setOptions($options);
}
}
/**
* Set filter setate
*
* @param array $options
* @throws Exception\InvalidArgumentException if options is not an array or Traversable
* @return self
*/
public function setOptions($options)
{
if (! is_array($options) && ! $options instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'"%s" expects an array or Traversable; received "%s"',
__METHOD__,
(is_object($options) ? get_class($options) : gettype($options))
));
}
foreach ($options as $key => $value) {
if ($key === 'options') {
$key = 'adapterOptions';
}
$method = 'set' . ucfirst($key);
if (method_exists($this, $method)) {
$this->$method($value);
}
}
return $this;
}
/**
* Returns the current adapter, instantiating it if necessary
*
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
* @return Compress\CompressionAlgorithmInterface
*/
public function getAdapter()
{
if ($this->adapter instanceof Compress\CompressionAlgorithmInterface) {
return $this->adapter;
}
$adapter = $this->adapter;
$options = $this->getAdapterOptions();
if (! class_exists($adapter)) {
$adapter = 'Laminas\\Filter\\Compress\\' . ucfirst($adapter);
if (! class_exists($adapter)) {
throw new Exception\RuntimeException(sprintf(
'%s unable to load adapter; class "%s" not found',
__METHOD__,
$this->adapter
));
}
}
$this->adapter = new $adapter($options);
if (! $this->adapter instanceof Compress\CompressionAlgorithmInterface) {
throw new Exception\InvalidArgumentException(
"Compression adapter '" . $adapter
. "' does not implement Laminas\\Filter\\Compress\\CompressionAlgorithmInterface"
);
}
return $this->adapter;
}
/**
* Retrieve adapter name
*
* @return string
*/
public function getAdapterName()
{
return $this->getAdapter()->toString();
}
/**
* Sets compression adapter
*
* @param string|Compress\CompressionAlgorithmInterface $adapter Adapter to use
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setAdapter($adapter)
{
if ($adapter instanceof Compress\CompressionAlgorithmInterface) {
$this->adapter = $adapter;
return $this;
}
if (! is_string($adapter)) {
throw new Exception\InvalidArgumentException(
'Invalid adapter provided; must be string or instance of '
. 'Laminas\\Filter\\Compress\\CompressionAlgorithmInterface'
);
}
$this->adapter = $adapter;
return $this;
}
/**
* Retrieve adapter options
*
* @return array
*/
public function getAdapterOptions()
{
return $this->adapterOptions;
}
/**
* Set adapter options
*
* @param array $options
* @return self
*/
public function setAdapterOptions(array $options)
{
$this->adapterOptions = $options;
return $this;
}
/**
* Get individual or all options from underlying adapter
*
* @param null|string $option
* @return mixed
*/
public function getOptions($option = null)
{
$adapter = $this->getAdapter();
return $adapter->getOptions($option);
}
/**
* Calls adapter methods
*
* @param string $method Method to call
* @param string|array $options Options for this method
* @return mixed
* @throws Exception\BadMethodCallException
*/
public function __call($method, $options)
{
$adapter = $this->getAdapter();
if (! method_exists($adapter, $method)) {
throw new Exception\BadMethodCallException("Unknown method '{$method}'");
}
return call_user_func_array([$adapter, $method], $options);
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Compresses the content $value with the defined settings
*
* @param string $value Content to compress
* @return string The compressed content
*/
public function filter($value)
{
if (! is_string($value)) {
return $value;
}
return $this->getAdapter()->compress($value);
}
}
PK 髏P*X%% % src/StripTags.phpnu W+A Tags which are allowed
* 'allowAttribs' => Attributes which are allowed
* 'allowComments' => Are comments allowed ?
*
* @param string|array|Traversable $options
*/
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if ((! is_array($options)) || (is_array($options) && ! array_key_exists('allowTags', $options) &&
! array_key_exists('allowAttribs', $options) && ! array_key_exists('allowComments', $options))) {
$options = func_get_args();
$temp['allowTags'] = array_shift($options);
if (! empty($options)) {
$temp['allowAttribs'] = array_shift($options);
}
if (! empty($options)) {
$temp['allowComments'] = array_shift($options);
}
$options = $temp;
}
if (array_key_exists('allowTags', $options)) {
$this->setTagsAllowed($options['allowTags']);
}
if (array_key_exists('allowAttribs', $options)) {
$this->setAttributesAllowed($options['allowAttribs']);
}
}
/**
* Returns the tagsAllowed option
*
* @return array
*/
public function getTagsAllowed()
{
return $this->tagsAllowed;
}
/**
* Sets the tagsAllowed option
*
* @param array|string $tagsAllowed
* @return self Provides a fluent interface
*/
public function setTagsAllowed($tagsAllowed)
{
if (! is_array($tagsAllowed)) {
$tagsAllowed = [$tagsAllowed];
}
foreach ($tagsAllowed as $index => $element) {
// If the tag was provided without attributes
if (is_int($index) && is_string($element)) {
// Canonicalize the tag name
$tagName = strtolower($element);
// Store the tag as allowed with no attributes
$this->tagsAllowed[$tagName] = [];
} elseif (is_string($index) && (is_array($element) || is_string($element))) {
// Otherwise, if a tag was provided with attributes
// Canonicalize the tag name
$tagName = strtolower($index);
// Canonicalize the attributes
if (is_string($element)) {
$element = [$element];
}
// Store the tag as allowed with the provided attributes
$this->tagsAllowed[$tagName] = [];
foreach ($element as $attribute) {
if (is_string($attribute)) {
// Canonicalize the attribute name
$attributeName = strtolower($attribute);
$this->tagsAllowed[$tagName][$attributeName] = null;
}
}
}
}
return $this;
}
/**
* Returns the attributesAllowed option
*
* @return array
*/
public function getAttributesAllowed()
{
return $this->attributesAllowed;
}
/**
* Sets the attributesAllowed option
*
* @param array|string $attributesAllowed
* @return self Provides a fluent interface
*/
public function setAttributesAllowed($attributesAllowed)
{
if (! is_array($attributesAllowed)) {
$attributesAllowed = [$attributesAllowed];
}
// Store each attribute as allowed
foreach ($attributesAllowed as $attribute) {
if (is_string($attribute)) {
// Canonicalize the attribute name
$attributeName = strtolower($attribute);
$this->attributesAllowed[$attributeName] = null;
}
}
return $this;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @todo improve docblock descriptions
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
// Strip HTML comments first
$open = '';
$closeLen = strlen($close);
while (($start = strpos($value, $open)) !== false) {
$end = strpos($value, $close, $start + $openLen);
if ($end === false) {
$value = substr($value, 0, $start);
} else {
$value = substr($value, 0, $start) . substr($value, $end + $closeLen);
}
}
// Initialize accumulator for filtered data
$dataFiltered = '';
// Parse the input data iteratively as regular pre-tag text followed by a
// tag; either may be empty strings
preg_match_all('/([^<]*)([^>]*>?)/', (string) $value, $matches);
// Iterate over each set of matches
foreach ($matches[1] as $index => $preTag) {
// If the pre-tag text is non-empty, strip any ">" characters from it
if (strlen($preTag)) {
$preTag = str_replace('>', '', $preTag);
}
// If a tag exists in this match, then filter the tag
$tag = $matches[2][$index];
if (strlen($tag)) {
$tagFiltered = $this->_filterTag($tag);
} else {
$tagFiltered = '';
}
// Add the filtered pre-tag text and filtered tag to the data buffer
$dataFiltered .= $preTag . $tagFiltered;
}
// Return the filtered data
return $dataFiltered;
}
/**
* Filters a single tag against the current option settings
*
* @param string $tag
* @return string
*/
// @codingStandardsIgnoreStart
protected function _filterTag($tag)
{
// @codingStandardsIgnoreEnd
// Parse the tag into:
// 1. a starting delimiter (mandatory)
// 2. a tag name (if available)
// 3. a string of attributes (if available)
// 4. an ending delimiter (if available)
$isMatch = preg_match('~(?)(\w*)((/(?!>)|[^/>])*)(/?>)~', $tag, $matches);
// If the tag does not match, then strip the tag entirely
if (! $isMatch) {
return '';
}
// Save the matches to more meaningfully named variables
$tagStart = $matches[1];
$tagName = strtolower($matches[2]);
$tagAttributes = $matches[3];
$tagEnd = $matches[5];
// If the tag is not an allowed tag, then remove the tag entirely
if (! isset($this->tagsAllowed[$tagName])) {
return '';
}
// Trim the attribute string of whitespace at the ends
$tagAttributes = trim($tagAttributes);
// If there are non-whitespace characters in the attribute string
if (strlen($tagAttributes)) {
// Parse iteratively for well-formed attributes
preg_match_all('/([\w-]+)\s*=\s*(?:(")(.*?)"|(\')(.*?)\')/s', $tagAttributes, $matches);
// Initialize valid attribute accumulator
$tagAttributes = '';
// Iterate over each matched attribute
foreach ($matches[1] as $index => $attributeName) {
$attributeName = strtolower($attributeName);
$attributeDelimiter = empty($matches[2][$index]) ? $matches[4][$index] : $matches[2][$index];
$attributeValue = $matches[3][$index] === '' ? $matches[5][$index] : $matches[3][$index];
// If the attribute is not allowed, then remove it entirely
if (! array_key_exists($attributeName, $this->tagsAllowed[$tagName])
&& ! array_key_exists($attributeName, $this->attributesAllowed)) {
continue;
}
// Add the attribute to the accumulator
$tagAttributes .= " $attributeName=" . $attributeDelimiter
. $attributeValue . $attributeDelimiter;
}
}
// Reconstruct tags ending with "/>" as backwards-compatible XHTML tag
if (strpos($tagEnd, '/') !== false) {
$tagEnd = " $tagEnd";
}
// Return the filtered tag
return $tagStart . $tagName . $tagAttributes . $tagEnd;
}
}
PK 髏PajV V src/DateTimeSelect.phpnu W+A isNullOnEmpty()
&& (
empty($value['year'])
|| empty($value['month'])
|| empty($value['day'])
|| empty($value['hour'])
|| empty($value['minute'])
|| (isset($value['second']) && empty($value['second']))
)
) {
return;
}
if ($this->isNullOnAllEmpty()
&& (
empty($value['year'])
&& empty($value['month'])
&& empty($value['day'])
&& empty($value['hour'])
&& empty($value['minute'])
&& (! isset($value['second']) || empty($value['second']))
)
) {
// Cannot handle this value
return;
}
if (! isset($value['second'])) {
$value['second'] = '00';
}
$this->filterable($value);
ksort($value);
$value = vsprintf($this->format, $value);
return $value;
}
}
PK 髏PEf src/Word/DashToUnderscore.phpnu W+A setSearchSeparator($searchSeparator);
$this->setReplacementSeparator($replacementSeparator);
}
/**
* Sets a new separator to search for
*
* @param string $separator Separator to search for
* @return self
*/
public function setSearchSeparator($separator)
{
$this->searchSeparator = $separator;
return $this;
}
/**
* Returns the actual set separator to search for
*
* @return string
*/
public function getSearchSeparator()
{
return $this->searchSeparator;
}
/**
* Sets a new separator which replaces the searched one
*
* @param string $separator Separator which replaces the searched one
* @return self
*/
public function setReplacementSeparator($separator)
{
$this->replacementSeparator = $separator;
return $this;
}
/**
* Returns the actual set separator which replaces the searched one
*
* @return string
*/
public function getReplacementSeparator()
{
return $this->replacementSeparator;
}
/**
* Defined by Laminas\Filter\Filter
*
* Returns the string $value, replacing the searched separators with the defined ones
*
* @param string|array $value
* @return string|array
*/
public function filter($value)
{
if (! is_scalar($value) && ! is_array($value)) {
return $value;
}
if ($this->searchSeparator === null) {
throw new Exception\RuntimeException('You must provide a search separator for this filter to work.');
}
$pattern = '#' . preg_quote($this->searchSeparator, '#') . '#';
return preg_replace($pattern, $this->replacementSeparator, $value);
}
}
PK 髏P*3 # src/Word/UnderscoreToStudlyCase.phpnu W+A separator . '\1', $this->separator . '\1'];
} else {
$pattern = ['#(?<=(?:[A-Z]))([A-Z]+)([A-Z][a-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#'];
$replacement = ['\1' . $this->separator . '\2', $this->separator . '\1'];
}
return preg_replace($pattern, $replacement, $value);
}
}
PK 髏PN src/Word/CamelCaseToDash.phpnu W+A separator, '#');
if (StringUtils::hasPcreUnicodeSupport()) {
$patterns = [
'#(' . $pregQuotedSeparator.')(\P{Z}{1})#u',
'#(^\P{Z}{1})#u',
];
if (! extension_loaded('mbstring')) {
$replacements = [
// @codingStandardsIgnoreStart
static function ($matches) {
return strtoupper($matches[2]);
},
static function ($matches) {
return strtoupper($matches[1]);
},
// @codingStandardsIgnoreEnd
];
} else {
$replacements = [
// @codingStandardsIgnoreStart
static function ($matches) {
return mb_strtoupper($matches[2], 'UTF-8');
},
static function ($matches) {
return mb_strtoupper($matches[1], 'UTF-8');
},
// @codingStandardsIgnoreEnd
];
}
} else {
$patterns = [
'#(' . $pregQuotedSeparator.')([\S]{1})#',
'#(^[\S]{1})#',
];
$replacements = [
// @codingStandardsIgnoreStart
static function ($matches) {
return strtoupper($matches[2]);
},
static function ($matches) {
return strtoupper($matches[1]);
},
// @codingStandardsIgnoreEnd
];
}
$filtered = $value;
foreach ($patterns as $index => $pattern) {
$filtered = preg_replace_callback($pattern, $replacements[$index], $filtered);
}
return $filtered;
}
}
PK 髏Px6b b " src/Word/UnderscoreToSeparator.phpnu W+A separator, $value);
}
}
PK 髏Pg$E E 0 src/Word/Service/SeparatorToSeparatorFactory.phpnu W+A creationOptions = $creationOptions;
}
/**
* {@inheritDoc}
*/
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
return new SeparatorToSeparator(
isset($options['search_separator']) ? $options['search_separator'] : ' ',
isset($options['replacement_separator']) ? $options['replacement_separator'] : '-'
);
}
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $this($serviceLocator, self::class, $this->creationOptions);
}
public function setCreationOptions(array $options)
{
$this->creationOptions = $options;
}
}
PK 髏PBS src/Word/AbstractSeparator.phpnu W+A setSeparator($separator);
}
/**
* Sets a new separator
*
* @param string $separator Separator
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setSeparator($separator)
{
if (! is_string($separator)) {
throw new Exception\InvalidArgumentException('"' . $separator . '" is not a valid separator.');
}
$this->separator = $separator;
return $this;
}
/**
* Returns the actual set separator
*
* @return string
*/
public function getSeparator()
{
return $this->separator;
}
}
PK 髏P " src/Word/UnderscoreToCamelCase.phpnu W+A encryption key string
* 'key_iteration' => the number of iterations for the PBKDF2 key generation
* 'algorithm => cipher algorithm to use
* 'hash' => algorithm to use for the authentication
* 'vector' => initialization vector
* )
*/
protected $encryption = [
'key_iteration' => 5000,
'algorithm' => 'aes',
'hash' => 'sha256',
];
/**
* BlockCipher
*
* @var BlockCipher
*/
protected $blockCipher;
/**
* Internal compression
*
* @var array
*/
protected $compression;
/**
* Class constructor
*
* @param string|array|Traversable $options Encryption Options
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
*/
public function __construct($options)
{
$cipherPluginManager = CryptBlockCipher::getSymmetricPluginManager();
$cipherType = $cipherPluginManager->has('openssl') ? 'openssl' : 'mcrypt';
try {
$this->blockCipher = CryptBlockCipher::factory($cipherType, $this->encryption);
} catch (SymmetricException\RuntimeException $e) {
throw new Exception\RuntimeException(sprintf(
'The BlockCipher cannot be used without the %s extension',
$cipherType
));
}
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif (is_string($options)) {
$options = ['key' => $options];
} elseif (! is_array($options)) {
throw new Exception\InvalidArgumentException('Invalid options argument provided to filter');
}
if (array_key_exists('compression', $options)) {
$this->setCompression($options['compression']);
unset($options['compress']);
}
$this->setEncryption($options);
}
/**
* Returns the set encryption options
*
* @return array
*/
public function getEncryption()
{
return $this->encryption;
}
/**
* Sets new encryption options
*
* @param string|array $options Encryption options
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setEncryption($options)
{
if (is_string($options)) {
$this->blockCipher->setKey($options);
$this->encryption['key'] = $options;
return $this;
}
if (! is_array($options)) {
throw new Exception\InvalidArgumentException('Invalid options argument provided to filter');
}
$options += $this->encryption;
if (isset($options['key'])) {
$this->blockCipher->setKey($options['key']);
}
if (isset($options['algorithm'])) {
try {
$this->blockCipher->setCipherAlgorithm($options['algorithm']);
} catch (CryptException\InvalidArgumentException $e) {
throw new Exception\InvalidArgumentException(
"The algorithm '{$options['algorithm']}' is not supported"
);
}
}
if (isset($options['hash'])) {
try {
$this->blockCipher->setHashAlgorithm($options['hash']);
} catch (CryptException\InvalidArgumentException $e) {
throw new Exception\InvalidArgumentException("The algorithm '{$options['hash']}' is not supported");
}
}
if (isset($options['vector'])) {
$this->setVector($options['vector']);
}
if (isset($options['key_iteration'])) {
$this->blockCipher->setKeyIteration($options['key_iteration']);
}
$this->encryption = $options;
return $this;
}
/**
* Returns the initialization vector
*
* @return string
*/
public function getVector()
{
return $this->encryption['vector'];
}
/**
* Set the inizialization vector
*
* @param string $vector
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setVector($vector)
{
try {
$this->blockCipher->setSalt($vector);
} catch (CryptException\InvalidArgumentException $e) {
throw new Exception\InvalidArgumentException($e->getMessage());
}
$this->encryption['vector'] = $vector;
return $this;
}
/**
* Set the encryption key
*
* @param string $key
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setKey($key)
{
try {
$this->blockCipher->setKey($key);
} catch (CryptException\InvalidArgumentException $e) {
throw new Exception\InvalidArgumentException($e->getMessage());
}
$this->encryption['key'] = $key;
return $this;
}
/**
* Get the encryption key
*
* @return string
*/
public function getKey()
{
return $this->encryption['key'];
}
/**
* Returns the compression
*
* @return array
*/
public function getCompression()
{
return $this->compression;
}
/**
* Sets an internal compression for values to encrypt
*
* @param string|array $compression
* @return self
*/
public function setCompression($compression)
{
if (is_string($this->compression)) {
$compression = ['adapter' => $compression];
}
$this->compression = $compression;
return $this;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Encrypts $value with the defined settings
*
* @param string $value The content to encrypt
* @throws Exception\InvalidArgumentException
* @return string The encrypted content
*/
public function encrypt($value)
{
// compress prior to encryption
if (! empty($this->compression)) {
$compress = new Compress($this->compression);
$value = $compress($value);
}
try {
$encrypted = $this->blockCipher->encrypt($value);
} catch (CryptException\InvalidArgumentException $e) {
throw new Exception\InvalidArgumentException($e->getMessage());
}
return $encrypted;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Decrypts $value with the defined settings
*
* @param string $value Content to decrypt
* @return string The decrypted content
*/
public function decrypt($value)
{
$decrypted = $this->blockCipher->decrypt($value);
// decompress after decryption
if (! empty($this->compression)) {
$decompress = new Decompress($this->compression);
$decrypted = $decompress($decrypted);
}
return $decrypted;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'BlockCipher';
}
}
PK 髏Pilr0 0 src/Encrypt/Openssl.phpnu W+A public keys
* 'private' => private keys
* 'envelope' => resulting envelope keys
* )
*/
protected $keys = [
'public' => [],
'private' => [],
'envelope' => [],
];
/**
* Internal passphrase
*
* @var string
*/
protected $passphrase;
/**
* Internal compression
*
* @var array
*/
protected $compression;
/**
* Internal create package
*
* @var bool
*/
protected $package = false;
/**
* Class constructor
* Available options
* 'public' => public key
* 'private' => private key
* 'envelope' => envelope key
* 'passphrase' => passphrase
* 'compression' => compress value with this compression adapter
* 'package' => pack envelope keys into encrypted string, simplifies decryption
*
* @param string|array|Traversable $options Options for this adapter
* @throws Exception\ExtensionNotLoadedException
*/
public function __construct($options = [])
{
if (! extension_loaded('openssl')) {
throw new Exception\ExtensionNotLoadedException('This filter needs the openssl extension');
}
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (! is_array($options)) {
$options = ['public' => $options];
}
if (array_key_exists('passphrase', $options)) {
$this->setPassphrase($options['passphrase']);
unset($options['passphrase']);
}
if (array_key_exists('compression', $options)) {
$this->setCompression($options['compression']);
unset($options['compression']);
}
if (array_key_exists('package', $options)) {
$this->setPackage($options['package']);
unset($options['package']);
}
$this->_setKeys($options);
}
/**
* Sets the encryption keys
*
* @param string|array $keys Key with type association
* @return self
* @throws Exception\InvalidArgumentException
*/
// @codingStandardsIgnoreStart
protected function _setKeys($keys)
{
// @codingStandardsIgnoreEnd
if (! is_array($keys)) {
throw new Exception\InvalidArgumentException('Invalid options argument provided to filter');
}
foreach ($keys as $type => $key) {
if (is_file($key) && is_readable($key)) {
$file = fopen($key, 'r');
$cert = fread($file, 8192);
fclose($file);
} else {
$cert = $key;
$key = count($this->keys[$type]);
}
switch ($type) {
case 'public':
$test = openssl_pkey_get_public($cert);
if ($test === false) {
throw new Exception\InvalidArgumentException("Public key '{$cert}' not valid");
}
openssl_free_key($test);
$this->keys['public'][$key] = $cert;
break;
case 'private':
$test = openssl_pkey_get_private($cert, $this->passphrase);
if ($test === false) {
throw new Exception\InvalidArgumentException("Private key '{$cert}' not valid");
}
openssl_free_key($test);
$this->keys['private'][$key] = $cert;
break;
case 'envelope':
$this->keys['envelope'][$key] = $cert;
break;
default:
break;
}
}
return $this;
}
/**
* Returns all public keys
*
* @return array
*/
public function getPublicKey()
{
return $this->keys['public'];
}
/**
* Sets public keys
*
* @param string|array $key Public keys
* @return self
*/
public function setPublicKey($key)
{
if (is_array($key)) {
foreach ($key as $type => $option) {
if ($type !== 'public') {
$key['public'] = $option;
unset($key[$type]);
}
}
} else {
$key = ['public' => $key];
}
return $this->_setKeys($key);
}
/**
* Returns all private keys
*
* @return array
*/
public function getPrivateKey()
{
return $this->keys['private'];
}
/**
* Sets private keys
*
* @param string|array $key Private key
* @param string|null $passphrase
* @return self
*/
public function setPrivateKey($key, $passphrase = null)
{
if (is_array($key)) {
foreach ($key as $type => $option) {
if ($type !== 'private') {
$key['private'] = $option;
unset($key[$type]);
}
}
} else {
$key = ['private' => $key];
}
if ($passphrase !== null) {
$this->setPassphrase($passphrase);
}
return $this->_setKeys($key);
}
/**
* Returns all envelope keys
*
* @return array
*/
public function getEnvelopeKey()
{
return $this->keys['envelope'];
}
/**
* Sets envelope keys
*
* @param string|array $key Envelope keys
* @return self
*/
public function setEnvelopeKey($key)
{
if (is_array($key)) {
foreach ($key as $type => $option) {
if ($type !== 'envelope') {
$key['envelope'] = $option;
unset($key[$type]);
}
}
} else {
$key = ['envelope' => $key];
}
return $this->_setKeys($key);
}
/**
* Returns the passphrase
*
* @return string
*/
public function getPassphrase()
{
return $this->passphrase;
}
/**
* Sets a new passphrase
*
* @param string $passphrase
* @return self
*/
public function setPassphrase($passphrase)
{
$this->passphrase = $passphrase;
return $this;
}
/**
* Returns the compression
*
* @return array
*/
public function getCompression()
{
return $this->compression;
}
/**
* Sets an internal compression for values to encrypt
*
* @param string|array $compression
* @return self
*/
public function setCompression($compression)
{
if (is_string($this->compression)) {
$compression = ['adapter' => $compression];
}
$this->compression = $compression;
return $this;
}
/**
* Returns if header should be packaged
*
* @return bool
*/
public function getPackage()
{
return $this->package;
}
/**
* Sets if the envelope keys should be included in the encrypted value
*
* @param bool $package
* @return self
*/
public function setPackage($package)
{
$this->package = (bool) $package;
return $this;
}
/**
* Encrypts $value with the defined settings
* Note that you also need the "encrypted" keys to be able to decrypt
*
* @param string $value Content to encrypt
* @return string The encrypted content
* @throws Exception\RuntimeException
*/
public function encrypt($value)
{
$encrypted = [];
$encryptedkeys = [];
if (! $this->keys['public']) {
throw new Exception\RuntimeException('Openssl can not encrypt without public keys');
}
$keys = [];
$fingerprints = [];
$count = -1;
foreach ($this->keys['public'] as $key => $cert) {
$keys[$key] = openssl_pkey_get_public($cert);
if ($this->package) {
$details = openssl_pkey_get_details($keys[$key]);
if ($details === false) {
$details = ['key' => 'Laminas'];
}
++$count;
$fingerprints[$count] = md5($details['key']);
}
}
// compress prior to encryption
if (! empty($this->compression)) {
$compress = new Compress($this->compression);
$value = $compress($value);
}
$crypt = openssl_seal($value, $encrypted, $encryptedkeys, $keys);
foreach ($keys as $key) {
openssl_free_key($key);
}
if ($crypt === false) {
throw new Exception\RuntimeException('Openssl was not able to encrypt your content with the given options');
}
$this->keys['envelope'] = $encryptedkeys;
// Pack data and envelope keys into single string
if ($this->package) {
$header = pack('n', count($this->keys['envelope']));
foreach ($this->keys['envelope'] as $key => $envKey) {
$header .= pack('H32n', $fingerprints[$key], strlen($envKey)) . $envKey;
}
$encrypted = $header . $encrypted;
}
return $encrypted;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Decrypts $value with the defined settings
*
* @param string $value Content to decrypt
* @return string The decrypted content
* @throws Exception\RuntimeException
*/
public function decrypt($value)
{
$decrypted = '';
$envelope = current($this->getEnvelopeKey());
if (count($this->keys['private']) !== 1) {
throw new Exception\RuntimeException('Please give a private key for decryption with Openssl');
}
if (! $this->package && empty($envelope)) {
throw new Exception\RuntimeException('Please give an envelope key for decryption with Openssl');
}
foreach ($this->keys['private'] as $cert) {
$keys = openssl_pkey_get_private($cert, $this->getPassphrase());
}
if ($this->package) {
$details = openssl_pkey_get_details($keys);
if ($details !== false) {
$fingerprint = md5($details['key']);
} else {
$fingerprint = md5("Laminas");
}
$count = unpack('ncount', $value);
$count = $count['count'];
$length = 2;
for ($i = $count; $i > 0; --$i) {
$header = unpack('H32print/nsize', substr($value, $length, 18));
$length += 18;
if ($header['print'] === $fingerprint) {
$envelope = substr($value, $length, $header['size']);
}
$length += $header['size'];
}
// remainder of string is the value to decrypt
$value = substr($value, $length);
}
$crypt = openssl_open($value, $decrypted, $envelope, $keys);
openssl_free_key($keys);
if ($crypt === false) {
throw new Exception\RuntimeException('Openssl was not able to decrypt you content with the given options');
}
// decompress after decryption
if (! empty($this->compression)) {
$decompress = new Decompress($this->compression);
$decrypted = $decompress($decrypted);
}
return $decrypted;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Openssl';
}
}
PK 髏Py~ ~ , src/Encrypt/EncryptionAlgorithmInterface.phpnu W+A setOptions($options);
}
}
/**
* @param bool $nullOnAllEmpty
* @return self
*/
public function setNullOnAllEmpty($nullOnAllEmpty)
{
$this->nullOnAllEmpty = $nullOnAllEmpty;
return $this;
}
/**
* @return bool
*/
public function isNullOnAllEmpty()
{
return $this->nullOnAllEmpty;
}
/**
* @param bool $nullOnEmpty
* @return self
*/
public function setNullOnEmpty($nullOnEmpty)
{
$this->nullOnEmpty = $nullOnEmpty;
return $this;
}
/**
* @return bool
*/
public function isNullOnEmpty()
{
return $this->nullOnEmpty;
}
/**
* Attempts to filter an array of date/time information to a formatted
* string.
*
* @param mixed $value
* @return mixed
* @throws Exception\RuntimeException If filtering $value is impossible
*/
public function filter($value)
{
if (! is_array($value)) {
// nothing to do
return $value;
}
// Convert the date to a specific format
if ($this->isNullOnEmpty()
&& array_reduce($value, __CLASS__ . '::reduce', false)
) {
return null;
}
if ($this->isNullOnAllEmpty()
&& array_reduce($value, __CLASS__ . '::reduce', true)
) {
return null;
}
$this->filterable($value);
ksort($value);
$value = vsprintf($this->format, $value);
return $value;
}
/**
* Ensures there are enough inputs in the array to properly format the date.
*
* @param $value
* @throws Exception\RuntimeException
*/
protected function filterable($value)
{
if (count($value) !== $this->expectedInputs) {
throw new Exception\RuntimeException(
sprintf(
'There are not enough values in the array to filter this date (Required: %d, Received: %d)',
$this->expectedInputs,
count($value)
)
);
}
}
/**
* Reduce to a single value
*
* @param string $soFar
* @param string $value
* @return bool
*/
public static function reduce($soFar, $value)
{
return $soFar || empty($value);
}
}
PK 髏Ps
& src/Whitelist.phpnu W+A setOptions($options);
}
}
/**
* Determine whether the in_array() call should be "strict" or not. See in_array docs.
*
* @param bool $strict
*/
public function setStrict($strict = true)
{
$this->strict = (bool) $strict;
}
/**
* Returns whether the in_array() call should be "strict" or not. See in_array docs.
*
* @return boolean
*/
public function getStrict()
{
return $this->strict;
}
/**
* Set the list of items to white-list.
*
* @param array|Traversable $list
*/
public function setList($list = [])
{
if (! is_array($list)) {
$list = ArrayUtils::iteratorToArray($list);
}
$this->list = $list;
}
/**
* Get the list of items to white-list
*
* @return array
*/
public function getList()
{
return $this->list;
}
/**
* {@inheritDoc}
*
* Will return $value if its present in the white-list. If $value is rejected then it will return null.
*/
public function filter($value)
{
return in_array($value, $this->getList(), $this->getStrict()) ? $value : null;
}
}
PK 髏P` src/DateSelect.phpnu W+A null
];
/**
* Constructor
*
* @param string|array|\Traversable $encodingOrOptions OPTIONAL
*/
public function __construct($encodingOrOptions = null)
{
if ($encodingOrOptions !== null) {
if (static::isOptions($encodingOrOptions)) {
$this->setOptions($encodingOrOptions);
} else {
$this->setEncoding($encodingOrOptions);
}
}
}
/**
* {@inheritDoc}
*
* Returns the string $value, converting words to have an uppercase first character as necessary
*
* If the value provided is not a string, the value will remain unfiltered
*
* @param string|mixed $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_string($value)) {
return $value;
}
$value = (string) $value;
if ($this->options['encoding'] !== null) {
return mb_convert_case($value, MB_CASE_TITLE, $this->options['encoding']);
}
return ucwords(strtolower($value));
}
}
PK 髏P+K K src/DataUnitFormatter.phpnu W+A ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'],
// decimal SI units:
self::MODE_DECIMAL => ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
];
/**
* Default options:
*
* @var array
*/
protected $options = [
'mode' => self::MODE_DECIMAL,
'unit' => '',
'precision' => 2,
'prefixes' => [],
];
/**
* @param array $options
*/
public function __construct($options = [])
{
if (! static::isOptions($options)) {
throw new InvalidArgumentException('The unit filter needs options to work.');
}
if (! isset($options['unit'])) {
throw new InvalidArgumentException('The unit filter needs a unit to work with.');
}
$this->setOptions($options);
}
/**
* Define the mode of the filter. Possible values can be fount at self::$modes.
*
* @param string $mode
*
* @throws InvalidArgumentException
*/
protected function setMode($mode)
{
$mode = strtolower($mode);
if (! in_array($mode, self::$modes, true)) {
throw new InvalidArgumentException(sprintf('Invalid binary mode: %s', $mode));
}
$this->options['mode'] = $mode;
}
/**
* Get current filter mode
*
* @return string
*/
protected function getMode()
{
return $this->options['mode'];
}
/**
* Find out if the filter is in decimal mode.
*
* @return bool
*/
protected function isDecimalMode()
{
return $this->getMode() === self::MODE_DECIMAL;
}
/**
* Find out if the filter is in binary mode.
*
* @return bool
*/
protected function isBinaryMode()
{
return $this->getMode() === self::MODE_BINARY;
}
/**
* Define the unit of the filter. Possible values can be fount at self::$types.
*
* @param string $unit
*/
protected function setUnit($unit)
{
$this->options['unit'] = (string) $unit;
}
/**
* Get current filter type
*
* @return string
*/
protected function getUnit()
{
return $this->options['unit'];
}
/**
* Set the precision of the filtered result.
*
* @param $precision
*/
protected function setPrecision($precision)
{
$this->options['precision'] = (int) $precision;
}
/**
* Get the precision of the filtered result.
*
* @return int
*/
protected function getPrecision()
{
return $this->options['precision'];
}
/**
* Set the precision of the result.
*
* @param array $prefixes
*/
protected function setPrefixes(array $prefixes)
{
$this->options['prefixes'] = $prefixes;
}
/**
* Get the predefined prefixes or use the build-in standardized lists of prefixes.
*
* @return array
*/
protected function getPrefixes()
{
$prefixes = $this->options['prefixes'];
if ($prefixes) {
return $prefixes;
}
return self::$standardizedPrefixes[$this->getMode()];
}
/**
* Find the prefix at a specific location in the prefixes array.
*
* @param $index
*
* @return string|null
*/
protected function getPrefixAt($index)
{
$prefixes = $this->getPrefixes();
return isset($prefixes[$index]) ? $prefixes[$index] : null;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns a human readable format of the amount of bits or bytes.
*
* If the value provided is not numeric, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_numeric($value)) {
return $value;
}
// Parse to float and check if value is not zero
$amount = (float) $value;
if ($amount === 0.0) {
return $this->formatAmount($amount);
}
// Calculate the correct size and prefix:
$base = $this->isBinaryMode() ? self::BASE_BINARY : self::BASE_DECIMAL;
$power = floor(log($amount, $base));
$prefix = $this->getPrefixAt((int)$power);
// When the amount is too big, no prefix can be found:
if ($prefix === null) {
return $this->formatAmount($amount);
}
// return formatted value:
$result = ($amount / pow($base, $power));
$formatted = number_format($result, $this->getPrecision());
return $this->formatAmount($formatted, $prefix);
}
/**
* @param $amount
* @param null $prefix
*
* @return string
*/
protected function formatAmount($amount, $prefix = null)
{
return sprintf('%s %s%s', $amount, $prefix, $this->getUnit());
}
}
PK 髏P`R@ src/StringTrim.phpnu W+A null,
];
/**
* Sets filter options
*
* @param string|array|Traversable $charlistOrOptions
*/
public function __construct($charlistOrOptions = null)
{
if ($charlistOrOptions !== null) {
if (! is_array($charlistOrOptions) && ! $charlistOrOptions instanceof Traversable) {
$this->setCharList($charlistOrOptions);
} else {
$this->setOptions($charlistOrOptions);
}
}
}
/**
* Sets the charList option
*
* @param string $charList
* @return self Provides a fluent interface
*/
public function setCharList($charList)
{
if (! strlen($charList)) {
$charList = null;
}
$this->options['charlist'] = $charList;
return $this;
}
/**
* Returns the charList option
*
* @return string|null
*/
public function getCharList()
{
return $this->options['charlist'];
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns the string $value with characters stripped from the beginning and end
*
* @param string $value
* @return string
*/
public function filter($value)
{
if (! is_string($value)) {
return $value;
}
$value = (string) $value;
if (null === $this->options['charlist']) {
return $this->unicodeTrim($value);
}
return $this->unicodeTrim($value, $this->options['charlist']);
}
/**
* Unicode aware trim method
* Fixes a PHP problem
*
* @param string $value
* @param string $charlist
* @return string
*/
protected function unicodeTrim($value, $charlist = '\\\\s')
{
$chars = preg_replace(
['/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'],
['\\\\\\0', '\\', '\/'],
$charlist
);
$pattern = '/^[' . $chars . ']+|[' . $chars . ']+$/usSD';
return preg_replace($pattern, '', $value);
}
}
PK 髏P Lo o src/FilterPluginManager.phpnu W+A ToInt::class,
'Int' => ToInt::class,
'null' => ToNull::class,
'Null' => ToNull::class,
// I18n filters
'alnum' => Alnum::class,
'Alnum' => Alnum::class,
'alpha' => Alpha::class,
'Alpha' => Alpha::class,
'numberformat' => NumberFormat::class,
'numberFormat' => NumberFormat::class,
'NumberFormat' => NumberFormat::class,
'numberparse' => NumberParse::class,
'numberParse' => NumberParse::class,
'NumberParse' => NumberParse::class,
// Standard filters
'basename' => BaseName::class,
'Basename' => BaseName::class,
'blacklist' => Blacklist::class,
'Blacklist' => Blacklist::class,
'boolean' => Boolean::class,
'Boolean' => Boolean::class,
'callback' => Callback::class,
'Callback' => Callback::class,
'compress' => Compress::class,
'Compress' => Compress::class,
'dataunitformatter' => DataUnitFormatter::class,
'dataUnitFormatter' => DataUnitFormatter::class,
'DataUnitFormatter' => DataUnitFormatter::class,
'dateselect' => DateSelect::class,
'dateSelect' => DateSelect::class,
'DateSelect' => DateSelect::class,
'datetimeformatter' => DateTimeFormatter::class,
'datetimeFormatter' => DateTimeFormatter::class,
'DatetimeFormatter' => DateTimeFormatter::class,
'dateTimeFormatter' => DateTimeFormatter::class,
'DateTimeFormatter' => DateTimeFormatter::class,
'datetimeselect' => DateTimeSelect::class,
'datetimeSelect' => DateTimeSelect::class,
'DatetimeSelect' => DateTimeSelect::class,
'dateTimeSelect' => DateTimeSelect::class,
'DateTimeSelect' => DateTimeSelect::class,
'decompress' => Decompress::class,
'Decompress' => Decompress::class,
'decrypt' => Decrypt::class,
'Decrypt' => Decrypt::class,
'digits' => Digits::class,
'Digits' => Digits::class,
'dir' => Dir::class,
'Dir' => Dir::class,
'encrypt' => Encrypt::class,
'Encrypt' => Encrypt::class,
'filedecrypt' => File\Decrypt::class,
'fileDecrypt' => File\Decrypt::class,
'FileDecrypt' => File\Decrypt::class,
'fileencrypt' => File\Encrypt::class,
'fileEncrypt' => File\Encrypt::class,
'FileEncrypt' => File\Encrypt::class,
'filelowercase' => File\LowerCase::class,
'fileLowercase' => File\LowerCase::class,
'FileLowercase' => File\LowerCase::class,
'fileLowerCase' => File\LowerCase::class,
'FileLowerCase' => File\LowerCase::class,
'filerename' => File\Rename::class,
'fileRename' => File\Rename::class,
'FileRename' => File\Rename::class,
'filerenameupload' => File\RenameUpload::class,
'fileRenameUpload' => File\RenameUpload::class,
'FileRenameUpload' => File\RenameUpload::class,
'fileuppercase' => File\UpperCase::class,
'fileUppercase' => File\UpperCase::class,
'FileUppercase' => File\UpperCase::class,
'fileUpperCase' => File\UpperCase::class,
'FileUpperCase' => File\UpperCase::class,
'htmlentities' => HtmlEntities::class,
'htmlEntities' => HtmlEntities::class,
'HtmlEntities' => HtmlEntities::class,
'inflector' => Inflector::class,
'Inflector' => Inflector::class,
'monthselect' => MonthSelect::class,
'monthSelect' => MonthSelect::class,
'MonthSelect' => MonthSelect::class,
'pregreplace' => PregReplace::class,
'pregReplace' => PregReplace::class,
'PregReplace' => PregReplace::class,
'realpath' => RealPath::class,
'realPath' => RealPath::class,
'RealPath' => RealPath::class,
'stringprefix' => StringPrefix::class,
'stringPrefix' => StringPrefix::class,
'StringPrefix' => StringPrefix::class,
'stringsuffix' => StringSuffix::class,
'stringSuffix' => StringSuffix::class,
'StringSuffix' => StringSuffix::class,
'stringtolower' => StringToLower::class,
'stringToLower' => StringToLower::class,
'StringToLower' => StringToLower::class,
'stringtoupper' => StringToUpper::class,
'stringToUpper' => StringToUpper::class,
'StringToUpper' => StringToUpper::class,
'stringtrim' => StringTrim::class,
'stringTrim' => StringTrim::class,
'StringTrim' => StringTrim::class,
'stripnewlines' => StripNewlines::class,
'stripNewlines' => StripNewlines::class,
'StripNewlines' => StripNewlines::class,
'striptags' => StripTags::class,
'stripTags' => StripTags::class,
'StripTags' => StripTags::class,
'toint' => ToInt::class,
'toInt' => ToInt::class,
'ToInt' => ToInt::class,
'tofloat' => ToFloat::class,
'toFloat' => ToFloat::class,
'ToFloat' => ToFloat::class,
'tonull' => ToNull::class,
'toNull' => ToNull::class,
'ToNull' => ToNull::class,
'uppercasewords' => UpperCaseWords::class,
'upperCaseWords' => UpperCaseWords::class,
'UpperCaseWords' => UpperCaseWords::class,
'urinormalize' => UriNormalize::class,
'uriNormalize' => UriNormalize::class,
'UriNormalize' => UriNormalize::class,
'whitelist' => Whitelist::class,
'Whitelist' => Whitelist::class,
'wordcamelcasetodash' => Word\CamelCaseToDash::class,
'wordCamelCaseToDash' => Word\CamelCaseToDash::class,
'WordCamelCaseToDash' => Word\CamelCaseToDash::class,
'wordcamelcasetoseparator' => Word\CamelCaseToSeparator::class,
'wordCamelCaseToSeparator' => Word\CamelCaseToSeparator::class,
'WordCamelCaseToSeparator' => Word\CamelCaseToSeparator::class,
'wordcamelcasetounderscore' => Word\CamelCaseToUnderscore::class,
'wordCamelCaseToUnderscore' => Word\CamelCaseToUnderscore::class,
'WordCamelCaseToUnderscore' => Word\CamelCaseToUnderscore::class,
'worddashtocamelcase' => Word\DashToCamelCase::class,
'wordDashToCamelCase' => Word\DashToCamelCase::class,
'WordDashToCamelCase' => Word\DashToCamelCase::class,
'worddashtoseparator' => Word\DashToSeparator::class,
'wordDashToSeparator' => Word\DashToSeparator::class,
'WordDashToSeparator' => Word\DashToSeparator::class,
'worddashtounderscore' => Word\DashToUnderscore::class,
'wordDashToUnderscore' => Word\DashToUnderscore::class,
'WordDashToUnderscore' => Word\DashToUnderscore::class,
'wordseparatortocamelcase' => Word\SeparatorToCamelCase::class,
'wordSeparatorToCamelCase' => Word\SeparatorToCamelCase::class,
'WordSeparatorToCamelCase' => Word\SeparatorToCamelCase::class,
'wordseparatortodash' => Word\SeparatorToDash::class,
'wordSeparatorToDash' => Word\SeparatorToDash::class,
'WordSeparatorToDash' => Word\SeparatorToDash::class,
'wordseparatortoseparator' => Word\SeparatorToSeparator::class,
'wordSeparatorToSeparator' => Word\SeparatorToSeparator::class,
'WordSeparatorToSeparator' => Word\SeparatorToSeparator::class,
'wordunderscoretocamelcase' => Word\UnderscoreToCamelCase::class,
'wordUnderscoreToCamelCase' => Word\UnderscoreToCamelCase::class,
'WordUnderscoreToCamelCase' => Word\UnderscoreToCamelCase::class,
'wordunderscoretostudlycase' => Word\UnderscoreToStudlyCase::class,
'wordUnderscoreToStudlyCase' => Word\UnderscoreToStudlyCase::class,
'WordUnderscoreToStudlyCase' => Word\UnderscoreToStudlyCase::class,
'wordunderscoretodash' => Word\UnderscoreToDash::class,
'wordUnderscoreToDash' => Word\UnderscoreToDash::class,
'WordUnderscoreToDash' => Word\UnderscoreToDash::class,
'wordunderscoretoseparator' => Word\UnderscoreToSeparator::class,
'wordUnderscoreToSeparator' => Word\UnderscoreToSeparator::class,
'WordUnderscoreToSeparator' => Word\UnderscoreToSeparator::class,
// Legacy Zend Framework aliases
\Zend\I18n\Filter\Alnum::class => Alnum::class,
\Zend\I18n\Filter\Alpha::class => Alpha::class,
\Zend\I18n\Filter\NumberFormat::class => NumberFormat::class,
\Zend\I18n\Filter\NumberParse::class => NumberParse::class,
\Zend\Filter\BaseName::class => BaseName::class,
\Zend\Filter\Blacklist::class => Blacklist::class,
\Zend\Filter\Boolean::class => Boolean::class,
\Zend\Filter\Callback::class => Callback::class,
\Zend\Filter\Compress::class => Compress::class,
\Zend\Filter\DataUnitFormatter::class => DataUnitFormatter::class,
\Zend\Filter\DateSelect::class => DateSelect::class,
\Zend\Filter\DateTimeFormatter::class => DateTimeFormatter::class,
\Zend\Filter\DateTimeSelect::class => DateTimeSelect::class,
\Zend\Filter\Decompress::class => Decompress::class,
\Zend\Filter\Decrypt::class => Decrypt::class,
\Zend\Filter\Digits::class => Digits::class,
\Zend\Filter\Dir::class => Dir::class,
\Zend\Filter\Encrypt::class => Encrypt::class,
\Zend\Filter\File\Decrypt::class => File\Decrypt::class,
\Zend\Filter\File\Encrypt::class => File\Encrypt::class,
\Zend\Filter\File\LowerCase::class => File\LowerCase::class,
\Zend\Filter\File\Rename::class => File\Rename::class,
\Zend\Filter\File\RenameUpload::class => File\RenameUpload::class,
\Zend\Filter\File\UpperCase::class => File\UpperCase::class,
\Zend\Filter\HtmlEntities::class => HtmlEntities::class,
\Zend\Filter\Inflector::class => Inflector::class,
\Zend\Filter\ToInt::class => ToInt::class,
\Zend\Filter\ToFloat::class => ToFloat::class,
\Zend\Filter\MonthSelect::class => MonthSelect::class,
\Zend\Filter\ToNull::class => ToNull::class,
\Zend\Filter\UpperCaseWords::class => UpperCaseWords::class,
\Zend\Filter\PregReplace::class => PregReplace::class,
\Zend\Filter\RealPath::class => RealPath::class,
\Zend\Filter\StringPrefix::class => StringPrefix::class,
\Zend\Filter\StringSuffix::class => StringSuffix::class,
\Zend\Filter\StringToLower::class => StringToLower::class,
\Zend\Filter\StringToUpper::class => StringToUpper::class,
\Zend\Filter\StringTrim::class => StringTrim::class,
\Zend\Filter\StripNewlines::class => StripNewlines::class,
\Zend\Filter\StripTags::class => StripTags::class,
\Zend\Filter\UriNormalize::class => UriNormalize::class,
\Zend\Filter\Whitelist::class => Whitelist::class,
\Zend\Filter\Word\CamelCaseToDash::class => Word\CamelCaseToDash::class,
\Zend\Filter\Word\CamelCaseToSeparator::class => Word\CamelCaseToSeparator::class,
\Zend\Filter\Word\CamelCaseToUnderscore::class => Word\CamelCaseToUnderscore::class,
\Zend\Filter\Word\DashToCamelCase::class => Word\DashToCamelCase::class,
\Zend\Filter\Word\DashToSeparator::class => Word\DashToSeparator::class,
\Zend\Filter\Word\DashToUnderscore::class => Word\DashToUnderscore::class,
\Zend\Filter\Word\SeparatorToCamelCase::class => Word\SeparatorToCamelCase::class,
\Zend\Filter\Word\SeparatorToDash::class => Word\SeparatorToDash::class,
\Zend\Filter\Word\SeparatorToSeparator::class => Word\SeparatorToSeparator::class,
\Zend\Filter\Word\UnderscoreToCamelCase::class => Word\UnderscoreToCamelCase::class,
\Zend\Filter\Word\UnderscoreToStudlyCase::class => Word\UnderscoreToStudlyCase::class,
\Zend\Filter\Word\UnderscoreToDash::class => Word\UnderscoreToDash::class,
\Zend\Filter\Word\UnderscoreToSeparator::class => Word\UnderscoreToSeparator::class,
// v2 normalized FQCNs
'zendfiltertoint' => ToInt::class,
'zendfiltertofloat' => ToFloat::class,
'zendfiltertonull' => ToNull::class,
'zendi18nfilteralnum' => Alnum::class,
'zendi18nfilteralpha' => Alpha::class,
'zendi18nfilternumberformat' => NumberFormat::class,
'zendi18nfilternumberparse' => NumberParse::class,
'zendfilterbasename' => BaseName::class,
'zendfilterblacklist' => Blacklist::class,
'zendfilterboolean' => Boolean::class,
'zendfiltercallback' => Callback::class,
'zendfiltercompress' => Compress::class,
'zendfilterdataunitformatter' => DataUnitFormatter::class,
'zendfilterdateselect' => DateSelect::class,
'zendfilterdatetimeformatter' => DateTimeFormatter::class,
'zendfilterdatetimeselect' => DateTimeSelect::class,
'zendfilterdecompress' => Decompress::class,
'zendfilterdecrypt' => Decrypt::class,
'zendfilterdigits' => Digits::class,
'zendfilterdir' => Dir::class,
'zendfilterencrypt' => Encrypt::class,
'zendfilterfiledecrypt' => File\Decrypt::class,
'zendfilterfileencrypt' => File\Encrypt::class,
'zendfilterfilelowercase' => File\LowerCase::class,
'zendfilterfilerename' => File\Rename::class,
'zendfilterfilerenameupload' => File\RenameUpload::class,
'zendfilterfileuppercase' => File\UpperCase::class,
'zendfilterhtmlentities' => HtmlEntities::class,
'zendfilterinflector' => Inflector::class,
'zendfiltermonthselect' => MonthSelect::class,
'zendfilterpregreplace' => PregReplace::class,
'zendfilterrealpath' => RealPath::class,
'zendfilterstringprefix' => StringPrefix::class,
'zendfilterstringsuffix' => StringSuffix::class,
'zendfilterstringtolower' => StringToLower::class,
'zendfilterstringtoupper' => StringToUpper::class,
'zendfilterstringtrim' => StringTrim::class,
'zendfilterstripnewlines' => StripNewlines::class,
'zendfilterstriptags' => StripTags::class,
'zendfilteruppercasewords' => UpperCaseWords::class,
'zendfilterurinormalize' => UriNormalize::class,
'zendfilterwhitelist' => Whitelist::class,
'zendfilterwordcamelcasetodash' => Word\CamelCaseToDash::class,
'zendfilterwordcamelcasetoseparator' => Word\CamelCaseToSeparator::class,
'zendfilterwordcamelcasetounderscore' => Word\CamelCaseToUnderscore::class,
'zendfilterworddashtocamelcase' => Word\DashToCamelCase::class,
'zendfilterworddashtoseparator' => Word\DashToSeparator::class,
'zendfilterworddashtounderscore' => Word\DashToUnderscore::class,
'zendfilterwordseparatortocamelcase' => Word\SeparatorToCamelCase::class,
'zendfilterwordseparatortodash' => Word\SeparatorToDash::class,
'zendfilterwordseparatortoseparator' => Word\SeparatorToSeparator::class,
'zendfilterwordunderscoretocamelcase' => Word\UnderscoreToCamelCase::class,
'zendfilterwordunderscoretostudlycase' => Word\UnderscoreToStudlyCase::class,
'zendfilterwordunderscoretodash' => Word\UnderscoreToDash::class,
'zendfilterwordunderscoretoseparator' => Word\UnderscoreToSeparator::class,
];
/**
* Default set of plugins factories
*
* @var array
*/
protected $factories = [
// I18n filters
Alnum::class => InvokableFactory::class,
Alpha::class => InvokableFactory::class,
NumberFormat::class => InvokableFactory::class,
NumberParse::class => InvokableFactory::class,
// Standard filters
BaseName::class => InvokableFactory::class,
Blacklist::class => InvokableFactory::class,
Boolean::class => InvokableFactory::class,
Callback::class => InvokableFactory::class,
Compress::class => InvokableFactory::class,
DataUnitFormatter::class => InvokableFactory::class,
DateSelect::class => InvokableFactory::class,
DateTimeFormatter::class => InvokableFactory::class,
DateTimeSelect::class => InvokableFactory::class,
Decompress::class => InvokableFactory::class,
Decrypt::class => InvokableFactory::class,
Digits::class => InvokableFactory::class,
Dir::class => InvokableFactory::class,
Encrypt::class => InvokableFactory::class,
File\Decrypt::class => InvokableFactory::class,
File\Encrypt::class => InvokableFactory::class,
File\LowerCase::class => InvokableFactory::class,
File\Rename::class => InvokableFactory::class,
File\RenameUpload::class => InvokableFactory::class,
File\UpperCase::class => InvokableFactory::class,
HtmlEntities::class => InvokableFactory::class,
Inflector::class => InvokableFactory::class,
ToInt::class => InvokableFactory::class,
ToFloat::class => InvokableFactory::class,
MonthSelect::class => InvokableFactory::class,
ToNull::class => InvokableFactory::class,
UpperCaseWords::class => InvokableFactory::class,
PregReplace::class => InvokableFactory::class,
RealPath::class => InvokableFactory::class,
StringPrefix::class => InvokableFactory::class,
StringSuffix::class => InvokableFactory::class,
StringToLower::class => InvokableFactory::class,
StringToUpper::class => InvokableFactory::class,
StringTrim::class => InvokableFactory::class,
StripNewlines::class => InvokableFactory::class,
StripTags::class => InvokableFactory::class,
ToInt::class => InvokableFactory::class,
ToNull::class => InvokableFactory::class,
UriNormalize::class => InvokableFactory::class,
Whitelist::class => InvokableFactory::class,
Word\CamelCaseToDash::class => InvokableFactory::class,
Word\CamelCaseToSeparator::class => InvokableFactory::class,
Word\CamelCaseToUnderscore::class => InvokableFactory::class,
Word\DashToCamelCase::class => InvokableFactory::class,
Word\DashToSeparator::class => InvokableFactory::class,
Word\DashToUnderscore::class => InvokableFactory::class,
Word\SeparatorToCamelCase::class => InvokableFactory::class,
Word\SeparatorToDash::class => InvokableFactory::class,
Word\SeparatorToSeparator::class => Word\Service\SeparatorToSeparatorFactory::class,
Word\UnderscoreToCamelCase::class => InvokableFactory::class,
Word\UnderscoreToStudlyCase::class => InvokableFactory::class,
Word\UnderscoreToDash::class => InvokableFactory::class,
Word\UnderscoreToSeparator::class => InvokableFactory::class,
// v2 canonical FQCNs
'laminasfiltertoint' => InvokableFactory::class,
'laminasfiltertofloat' => InvokableFactory::class,
'laminasfiltertonull' => InvokableFactory::class,
'laminasi18nfilteralnum' => InvokableFactory::class,
'laminasi18nfilteralpha' => InvokableFactory::class,
'laminasi18nfilternumberformat' => InvokableFactory::class,
'laminasi18nfilternumberparse' => InvokableFactory::class,
'laminasfilterbasename' => InvokableFactory::class,
'laminasfilterblacklist' => InvokableFactory::class,
'laminasfilterboolean' => InvokableFactory::class,
'laminasfiltercallback' => InvokableFactory::class,
'laminasfiltercompress' => InvokableFactory::class,
'laminasfilterdataunitformatter' => InvokableFactory::class,
'laminasfilterdateselect' => InvokableFactory::class,
'laminasfilterdatetimeformatter' => InvokableFactory::class,
'laminasfilterdatetimeselect' => InvokableFactory::class,
'laminasfilterdecompress' => InvokableFactory::class,
'laminasfilterdecrypt' => InvokableFactory::class,
'laminasfilterdigits' => InvokableFactory::class,
'laminasfilterdir' => InvokableFactory::class,
'laminasfilterencrypt' => InvokableFactory::class,
'laminasfilterfiledecrypt' => InvokableFactory::class,
'laminasfilterfileencrypt' => InvokableFactory::class,
'laminasfilterfilelowercase' => InvokableFactory::class,
'laminasfilterfilerename' => InvokableFactory::class,
'laminasfilterfilerenameupload' => InvokableFactory::class,
'laminasfilterfileuppercase' => InvokableFactory::class,
'laminasfilterhtmlentities' => InvokableFactory::class,
'laminasfilterinflector' => InvokableFactory::class,
'laminasfiltermonthselect' => InvokableFactory::class,
'laminasfilterpregreplace' => InvokableFactory::class,
'laminasfilterrealpath' => InvokableFactory::class,
'laminasfilterstringprefix' => InvokableFactory::class,
'laminasfilterstringsuffix' => InvokableFactory::class,
'laminasfilterstringtolower' => InvokableFactory::class,
'laminasfilterstringtoupper' => InvokableFactory::class,
'laminasfilterstringtrim' => InvokableFactory::class,
'laminasfilterstripnewlines' => InvokableFactory::class,
'laminasfilterstriptags' => InvokableFactory::class,
'laminasfilteruppercasewords' => InvokableFactory::class,
'laminasfilterurinormalize' => InvokableFactory::class,
'laminasfilterwhitelist' => InvokableFactory::class,
'laminasfilterwordcamelcasetodash' => InvokableFactory::class,
'laminasfilterwordcamelcasetoseparator' => InvokableFactory::class,
'laminasfilterwordcamelcasetounderscore' => InvokableFactory::class,
'laminasfilterworddashtocamelcase' => InvokableFactory::class,
'laminasfilterworddashtoseparator' => InvokableFactory::class,
'laminasfilterworddashtounderscore' => InvokableFactory::class,
'laminasfilterwordseparatortocamelcase' => InvokableFactory::class,
'laminasfilterwordseparatortodash' => InvokableFactory::class,
'laminasfilterwordseparatortoseparator' => Word\Service\SeparatorToSeparatorFactory::class,
'laminasfilterwordunderscoretocamelcase' => InvokableFactory::class,
'laminasfilterwordunderscoretostudlycase' => InvokableFactory::class,
'laminasfilterwordunderscoretodash' => InvokableFactory::class,
'laminasfilterwordunderscoretoseparator' => InvokableFactory::class,
];
protected $instanceOf = FilterInterface::class;
/**
* Whether or not to share by default; default to false (v2)
*
* @var bool
*/
protected $shareByDefault = false;
/**
* Whether or not to share by default; default to false (v3)
*
* @var bool
*/
protected $sharedByDefault = false;
/**
* {@inheritdoc}
*/
public function validate($plugin)
{
if ($plugin instanceof $this->instanceOf) {
// we're okay
return;
}
if (is_callable($plugin)) {
// also okay
return;
}
throw new InvalidServiceException(sprintf(
'Plugin of type %s is invalid; must implement %s\FilterInterface or be callable',
(is_object($plugin) ? get_class($plugin) : gettype($plugin)),
__NAMESPACE__
));
}
/**
* Validate the plugin (v2)
*
* Checks that the filter loaded is either a valid callback or an instance
* of FilterInterface.
*
* @param mixed $plugin
* @return void
* @throws Exception\RuntimeException if invalid
*/
public function validatePlugin($plugin)
{
try {
$this->validate($plugin);
} catch (InvalidServiceException $e) {
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
}
}
PK 髏PX9<$
$
src/Callback.phpnu W+A null,
'callback_params' => []
];
/**
* @param callable|array|string|Traversable $callbackOrOptions
* @param array $callbackParams
*/
public function __construct($callbackOrOptions = [], $callbackParams = [])
{
if (is_callable($callbackOrOptions) || is_string($callbackOrOptions)) {
$this->setCallback($callbackOrOptions);
$this->setCallbackParams($callbackParams);
} else {
$this->setOptions($callbackOrOptions);
}
}
/**
* Sets a new callback for this filter
*
* @param callable $callback
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setCallback($callback)
{
if (is_string($callback) && class_exists($callback)) {
$callback = new $callback();
}
if (! is_callable($callback)) {
throw new Exception\InvalidArgumentException(
'Invalid parameter for callback: must be callable'
);
}
$this->options['callback'] = $callback;
return $this;
}
/**
* Returns the set callback
*
* @return callable
*/
public function getCallback()
{
return $this->options['callback'];
}
/**
* Sets parameters for the callback
*
* @param array $params
* @return self
*/
public function setCallbackParams($params)
{
$this->options['callback_params'] = (array) $params;
return $this;
}
/**
* Get parameters for the callback
*
* @return array
*/
public function getCallbackParams()
{
return $this->options['callback_params'];
}
/**
* Calls the filter per callback
*
* @param mixed $value Options for the set callable
* @return mixed Result from the filter which was called
*/
public function filter($value)
{
$params = (array) $this->options['callback_params'];
array_unshift($params, $value);
return call_user_func_array($this->options['callback'], $params);
}
}
PK 髏Pz
$ src/StringToLower.phpnu W+A null,
];
/**
* Constructor
*
* @param string|array|Traversable $encodingOrOptions OPTIONAL
*/
public function __construct($encodingOrOptions = null)
{
if ($encodingOrOptions !== null) {
if (! static::isOptions($encodingOrOptions)) {
$this->setEncoding($encodingOrOptions);
} else {
$this->setOptions($encodingOrOptions);
}
}
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns the string $value, converting characters to lowercase as necessary
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
if (null !== $this->getEncoding()) {
return mb_strtolower($value, $this->options['encoding']);
}
return strtolower($value);
}
}
PK 髏P> src/Decrypt.phpnu W+A adapter->decrypt($value);
}
}
PK 髏P src/File/LowerCase.phpnu W+A null,
'use_upload_name' => false,
'use_upload_extension' => false,
'overwrite' => false,
'randomize' => false,
'stream_factory' => null,
'upload_file_factory' => null,
];
/**
* Store already filtered values, so we can filter multiple
* times the same file without being block by move_uploaded_file
* internal checks
*
* @var array
*/
protected $alreadyFiltered = [];
/**
* Constructor
*
* @param array|string $targetOrOptions The target file path or an options array
*/
public function __construct($targetOrOptions = [])
{
if (is_array($targetOrOptions)) {
$this->setOptions($targetOrOptions);
} else {
$this->setTarget($targetOrOptions);
}
}
/**
* @param StreamFactoryInterface $factory Factory to use to produce a PSR-7
* stream with which to seed a PSR-7 UploadedFileInterface.
* @return self
*/
public function setStreamFactory(StreamFactoryInterface $factory)
{
$this->options['stream_factory'] = $factory;
return $this;
}
/**
* @return null|StreamFactoryInterface
*/
public function getStreamFactory()
{
return $this->options['stream_factory'];
}
/**
* @param string $target Target file path or directory
* @return self
*/
public function setTarget($target)
{
if (! is_string($target)) {
throw new Exception\InvalidArgumentException(
'Invalid target, must be a string'
);
}
$this->options['target'] = $target;
return $this;
}
/**
* @return string Target file path or directory
*/
public function getTarget()
{
return $this->options['target'];
}
/**
* @param UploadedFileFactoryInterface $factory Factory to use to produce
* filtered PSR-7 UploadedFileInterface instances.
* @return self
*/
public function setUploadFileFactory(UploadedFileFactoryInterface $factory)
{
$this->options['upload_file_factory'] = $factory;
return $this;
}
/**
* @return null|UploadedFileFactoryInterface
*/
public function getUploadFileFactory()
{
return $this->options['upload_file_factory'];
}
/**
* @param bool $flag When true, this filter will use the $_FILES['name']
* as the target filename.
* Otherwise, it uses the default 'target' rules.
* @return self
*/
public function setUseUploadName($flag = true)
{
$this->options['use_upload_name'] = (bool) $flag;
return $this;
}
/**
* @return bool
*/
public function getUseUploadName()
{
return $this->options['use_upload_name'];
}
/**
* @param bool $flag When true, this filter will use the original file
* extension for the target filename
* @return self
*/
public function setUseUploadExtension($flag = true)
{
$this->options['use_upload_extension'] = (bool) $flag;
return $this;
}
/**
* @return bool
*/
public function getUseUploadExtension()
{
return $this->options['use_upload_extension'];
}
/**
* @param bool $flag Shall existing files be overwritten?
* @return self
*/
public function setOverwrite($flag = true)
{
$this->options['overwrite'] = (bool) $flag;
return $this;
}
/**
* @return bool
*/
public function getOverwrite()
{
return $this->options['overwrite'];
}
/**
* @param bool $flag Shall target files have a random postfix attached?
* @return self
*/
public function setRandomize($flag = true)
{
$this->options['randomize'] = (bool) $flag;
return $this;
}
/**
* @return bool
*/
public function getRandomize()
{
return $this->options['randomize'];
}
/**
* Defined by Laminas\Filter\Filter
*
* Renames the file $value to the new name set before
* Returns the file $value, removing all but digit characters
*
* @param string|array|UploadedFileInterface $value Full path of file to
* change; $_FILES data array; or UploadedFileInterface instance.
* @return string|array|UploadedFileInterface Returns one of the following:
* - New filename, for string $value
* - Array with tmp_name and name keys for array $value
* - UploadedFileInterface for UploadedFileInterface $value
* @throws Exception\RuntimeException
*/
public function filter($value)
{
// PSR-7 uploaded file
if ($value instanceof UploadedFileInterface) {
return $this->filterPsr7UploadedFile($value);
}
// File upload via traditional SAPI
if (is_array($value) && isset($value['tmp_name'])) {
return $this->filterSapiUploadedFile($value);
}
// String filename
if (is_string($value)) {
return $this->filterStringFilename($value);
}
// Unrecognized; return verbatim
return $value;
}
/**
* @param string $sourceFile Source file path
* @param string $targetFile Target file path
* @throws Exception\RuntimeException
* @return bool
*/
protected function moveUploadedFile($sourceFile, $targetFile)
{
ErrorHandler::start();
$result = move_uploaded_file($sourceFile, $targetFile);
$warningException = ErrorHandler::stop();
if (! $result || null !== $warningException) {
throw new Exception\RuntimeException(
sprintf("File '%s' could not be renamed. An error occurred while processing the file.", $sourceFile),
0,
$warningException
);
}
return $result;
}
/**
* @param string $targetFile Target file path
* @return void
* @throws Exception\InvalidArgumentException
*/
protected function checkFileExists($targetFile)
{
if (! file_exists($targetFile)) {
return;
}
if (! $this->getOverwrite()) {
throw new Exception\InvalidArgumentException(
sprintf("File '%s' could not be renamed. It already exists.", $targetFile)
);
}
unlink($targetFile);
}
/**
* @param $source
* @param $clientFileName
*
* @return string
*/
protected function getFinalTarget($source, $clientFileName)
{
$target = $this->getTarget();
if ($target === null || $target === '*') {
$target = $source;
}
// Get the target directory
if (is_dir($target)) {
$targetDir = $target;
$last = $target[strlen($target) - 1];
if (($last !== '/') && ($last !== '\\')) {
$targetDir .= DIRECTORY_SEPARATOR;
}
} else {
$info = pathinfo($target);
$targetDir = $info['dirname'] . DIRECTORY_SEPARATOR;
}
// Get the target filename
if ($this->getUseUploadName()) {
$targetFile = basename($clientFileName);
} elseif (! is_dir($target)) {
$targetFile = basename($target);
if ($this->getUseUploadExtension() && ! $this->getRandomize()) {
$targetInfo = pathinfo($targetFile);
$sourceinfo = pathinfo($clientFileName);
if (isset($sourceinfo['extension'])) {
$targetFile = $targetInfo['filename'] . '.' . $sourceinfo['extension'];
}
}
} else {
$targetFile = basename($source);
}
if ($this->getRandomize()) {
$targetFile = $this->applyRandomToFilename($clientFileName, $targetFile);
}
return $targetDir . $targetFile;
}
/**
* @param string $source
* @param string $filename
* @return string
*/
protected function applyRandomToFilename($source, $filename)
{
$info = pathinfo($filename);
$filename = $info['filename'] . str_replace('.', '_', uniqid('_', true));
$sourceinfo = pathinfo($source);
$extension = '';
if ($this->getUseUploadExtension() === true && isset($sourceinfo['extension'])) {
$extension .= '.' . $sourceinfo['extension'];
} elseif (isset($info['extension'])) {
$extension .= '.' . $info['extension'];
}
return $filename . $extension;
}
/**
* @param string $fileName
* @return string
*/
private function filterStringFilename($fileName)
{
if (isset($this->alreadyFiltered[$fileName])) {
return $this->alreadyFiltered[$fileName];
}
$targetFile = $this->getFinalTarget($fileName, $fileName);
if ($fileName === $targetFile || ! file_exists($fileName)) {
return $fileName;
}
$this->checkFileExists($targetFile);
$this->moveUploadedFile($fileName, $targetFile);
$this->alreadyFiltered[$fileName] = $targetFile;
return $this->alreadyFiltered[$fileName];
}
/**
* @param array $fileData
* @return array
*/
private function filterSapiUploadedFile(array $fileData)
{
$sourceFile = $fileData['tmp_name'];
if (isset($this->alreadyFiltered[$sourceFile])) {
return $this->alreadyFiltered[$sourceFile];
}
$clientFilename = $fileData['name'];
$targetFile = $this->getFinalTarget($sourceFile, $clientFilename);
if ($sourceFile === $targetFile || ! file_exists($sourceFile)) {
return $fileData;
}
$this->checkFileExists($targetFile);
$this->moveUploadedFile($sourceFile, $targetFile);
$this->alreadyFiltered[$sourceFile] = $fileData;
$this->alreadyFiltered[$sourceFile]['tmp_name'] = $targetFile;
return $this->alreadyFiltered[$sourceFile];
}
/**
* @param UploadedFileInterface $uploadedFile
* @return UploadedFileInterface
* @throws Exception\RuntimeException if no stream factory is composed in the filter.
* @throws Exception\RuntimeException if no uploaded file factory is composed in the filter.
*/
private function filterPsr7UploadedFile(UploadedFileInterface $uploadedFile)
{
$sourceFile = $uploadedFile->getStream()->getMetadata('uri');
if (isset($this->alreadyFiltered[$sourceFile])) {
return $this->alreadyFiltered[$sourceFile];
}
$clientFilename = $uploadedFile->getClientFilename();
$targetFile = $this->getFinalTarget($sourceFile, $clientFilename);
if ($sourceFile === $targetFile || ! file_exists($sourceFile)) {
return $uploadedFile;
}
$this->checkFileExists($targetFile);
$uploadedFile->moveTo($targetFile);
$streamFactory = $this->getStreamFactory();
if (! $streamFactory) {
throw new Exception\RuntimeException(sprintf(
'No PSR-17 %s present; cannot filter file. Please pass the stream_file_factory'
. ' option with a %s instance when creating the filter for use with PSR-7.',
StreamFactoryInterface::class,
StreamFactoryInterface::class
));
}
$stream = $streamFactory->createStreamFromFile($targetFile);
$uploadedFileFactory = $this->getUploadFileFactory();
if (! $uploadedFileFactory) {
throw new Exception\RuntimeException(sprintf(
'No PSR-17 %s present; cannot filter file. Please pass the upload_file_factory'
. ' option with a %s instance when creating the filter for use with PSR-7.',
UploadedFileFactoryInterface::class,
UploadedFileFactoryInterface::class
));
}
$this->alreadyFiltered[$sourceFile] = $uploadedFileFactory->createUploadedFile(
$stream,
filesize($targetFile),
UPLOAD_ERR_OK,
$uploadedFile->getClientFilename(),
$uploadedFile->getClientMediaType()
);
return $this->alreadyFiltered[$sourceFile];
}
}
PK 髏PVtK K src/File/Decrypt.phpnu W+A filename;
}
/**
* Sets the new filename where the content will be stored
*
* @param string $filename (Optional) New filename to set
* @return self
*/
public function setFilename($filename = null)
{
$this->filename = $filename;
return $this;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Decrypts the file $value with the defined settings
*
* @param string|array $value Full path of file to change or $_FILES data array
* @return string|array The filename which has been set
* @throws Exception\InvalidArgumentException
* @throws Exception\RuntimeException
*/
public function filter($value)
{
if (! is_scalar($value) && ! is_array($value)) {
return $value;
}
// An uploaded file? Retrieve the 'tmp_name'
$isFileUpload = false;
if (is_array($value)) {
if (! isset($value['tmp_name'])) {
return $value;
}
$isFileUpload = true;
$uploadData = $value;
$value = $value['tmp_name'];
}
if (! file_exists($value)) {
throw new Exception\InvalidArgumentException("File '$value' not found");
}
if (! isset($this->filename)) {
$this->filename = $value;
}
if (file_exists($this->filename) && ! is_writable($this->filename)) {
throw new Exception\RuntimeException("File '{$this->filename}' is not writable");
}
$content = file_get_contents($value);
if (! $content) {
throw new Exception\RuntimeException("Problem while reading file '$value'");
}
$decrypted = parent::filter($content);
$result = file_put_contents($this->filename, $decrypted);
if (! $result) {
throw new Exception\RuntimeException("Problem while writing file '{$this->filename}'");
}
if ($isFileUpload) {
$uploadData['tmp_name'] = $this->filename;
return $uploadData;
}
return $this->filename;
}
}
PK 髏PUc c src/File/Encrypt.phpnu W+A filename;
}
/**
* Sets the new filename where the content will be stored
*
* @param string $filename (Optional) New filename to set
* @return self
*/
public function setFilename($filename = null)
{
$this->filename = $filename;
return $this;
}
/**
* Defined by Laminas\Filter\Filter
*
* Encrypts the file $value with the defined settings
*
* @param string|array $value Full path of file to change or $_FILES data array
* @return string|array The filename which has been set, or false when there were errors
* @throws Exception\InvalidArgumentException
* @throws Exception\RuntimeException
*/
public function filter($value)
{
if (! is_scalar($value) && ! is_array($value)) {
return $value;
}
// An uploaded file? Retrieve the 'tmp_name'
$isFileUpload = false;
if (is_array($value)) {
if (! isset($value['tmp_name'])) {
return $value;
}
$isFileUpload = true;
$uploadData = $value;
$value = $value['tmp_name'];
}
if (! file_exists($value)) {
throw new Exception\InvalidArgumentException("File '$value' not found");
}
if (! isset($this->filename)) {
$this->filename = $value;
}
if (file_exists($this->filename) && ! is_writable($this->filename)) {
throw new Exception\RuntimeException("File '{$this->filename}' is not writable");
}
$content = file_get_contents($value);
if (! $content) {
throw new Exception\RuntimeException("Problem while reading file '$value'");
}
$encrypted = parent::filter($content);
$result = file_put_contents($this->filename, $encrypted);
if (! $result) {
throw new Exception\RuntimeException("Problem while writing file '{$this->filename}'");
}
if ($isFileUpload) {
$uploadData['tmp_name'] = $this->filename;
return $uploadData;
}
return $this->filename;
}
}
PK 髏Pc src/File/UpperCase.phpnu W+A Source filename or directory which will be renamed
* 'target' => Target filename or directory, the new name of the source file
* 'overwrite' => Shall existing files be overwritten ?
* 'randomize' => Shall target files have a random postfix attached?
*
* @param string|array|Traversable $options Target file or directory to be renamed
* @throws Exception\InvalidArgumentException
*/
public function __construct($options = [])
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif (is_string($options)) {
$options = ['target' => $options];
} elseif (! is_array($options)) {
throw new Exception\InvalidArgumentException(
'Invalid options argument provided to filter'
);
}
$this->setFile($options);
}
/**
* Returns the files to rename and their new name and location
*
* @return array
*/
public function getFile()
{
return $this->files;
}
/**
* Sets a new file or directory as target, deleting existing ones
*
* Array accepts the following keys:
* 'source' => Source filename or directory which will be renamed
* 'target' => Target filename or directory, the new name of the sourcefile
* 'overwrite' => Shall existing files be overwritten?
* 'randomize' => Shall target files have a random postfix attached?
*
* @param string|array $options Old file or directory to be rewritten
* @return self
*/
public function setFile($options)
{
$this->files = [];
$this->addFile($options);
return $this;
}
/**
* Adds a new file or directory as target to the existing ones
*
* Array accepts the following keys:
* 'source' => Source filename or directory which will be renamed
* 'target' => Target filename or directory, the new name of the sourcefile
* 'overwrite' => Shall existing files be overwritten?
* 'randomize' => Shall target files have a random postfix attached?
*
* @param string|array $options Old file or directory to be rewritten
* @return Rename
* @throws Exception\InvalidArgumentException
*/
public function addFile($options)
{
if (is_string($options)) {
$options = ['target' => $options];
} elseif (! is_array($options)) {
throw new Exception\InvalidArgumentException(
'Invalid options to rename filter provided'
);
}
$this->_convertOptions($options);
return $this;
}
/**
* Returns only the new filename without moving it
* But existing files will be erased when the overwrite option is true
*
* @param string $value Full path of file to change
* @param bool $source Return internal information
* @return string The new filename which has been set
* @throws Exception\InvalidArgumentException If the target file already exists.
*/
public function getNewName($value, $source = false)
{
$file = $this->_getFileName($value);
if (! is_array($file)) {
return $file;
}
if ($file['source'] === $file['target']) {
return $value;
}
if (! file_exists($file['source'])) {
return $value;
}
if ($file['overwrite'] && file_exists($file['target'])) {
unlink($file['target']);
}
if (file_exists($file['target'])) {
throw new Exception\InvalidArgumentException(sprintf(
'"File "%s" could not be renamed to "%s"; target file already exists',
$value,
realpath($file['target'])
));
}
if ($source) {
return $file;
}
return $file['target'];
}
/**
* Defined by Laminas\Filter\Filter
*
* Renames the file $value to the new name set before
* Returns the file $value, removing all but digit characters
*
* @param string|array $value Full path of file to change or $_FILES data array
* @throws Exception\RuntimeException
* @return string|array The new filename which has been set
*/
public function filter($value)
{
if (! is_scalar($value) && ! is_array($value)) {
return $value;
}
// An uploaded file? Retrieve the 'tmp_name'
$isFileUpload = false;
if (is_array($value)) {
if (! isset($value['tmp_name'])) {
return $value;
}
$isFileUpload = true;
$uploadData = $value;
$value = $value['tmp_name'];
}
$file = $this->getNewName($value, true);
if (is_string($file)) {
if ($isFileUpload) {
return $uploadData;
} else {
return $file;
}
}
$result = rename($file['source'], $file['target']);
if ($result !== true) {
throw new Exception\RuntimeException(
sprintf(
"File '%s' could not be renamed. " .
"An error occurred while processing the file.",
$value
)
);
}
if ($isFileUpload) {
$uploadData['tmp_name'] = $file['target'];
return $uploadData;
}
return $file['target'];
}
/**
* Internal method for creating the file array
* Supports single and nested arrays
*
* @param array $options
* @return array
*/
// @codingStandardsIgnoreStart
protected function _convertOptions($options)
{
// @codingStandardsIgnoreEnd
$files = [];
foreach ($options as $key => $value) {
if (is_array($value)) {
$this->_convertOptions($value);
continue;
}
switch ($key) {
case "source":
$files['source'] = (string) $value;
break;
case 'target':
$files['target'] = (string) $value;
break;
case 'overwrite':
$files['overwrite'] = (bool) $value;
break;
case 'randomize':
$files['randomize'] = (bool) $value;
break;
default:
break;
}
}
if (empty($files)) {
return $this;
}
if (empty($files['source'])) {
$files['source'] = '*';
}
if (empty($files['target'])) {
$files['target'] = '*';
}
if (empty($files['overwrite'])) {
$files['overwrite'] = false;
}
if (empty($files['randomize'])) {
$files['randomize'] = false;
}
$found = false;
foreach ($this->files as $key => $value) {
if ($value['source'] === $files['source']) {
$this->files[$key] = $files;
$found = true;
}
}
if (! $found) {
$count = count($this->files);
$this->files[$count] = $files;
}
return $this;
}
/**
* Internal method to resolve the requested source
* and return all other related parameters
*
* @param string $file Filename to get the information for
* @return array|string
*/
// @codingStandardsIgnoreStart
protected function _getFileName($file)
{
// @codingStandardsIgnoreEnd
$rename = [];
foreach ($this->files as $value) {
if ($value['source'] === '*') {
if (! isset($rename['source'])) {
$rename = $value;
$rename['source'] = $file;
}
}
if ($value['source'] === $file) {
$rename = $value;
break;
}
}
if (! isset($rename['source'])) {
return $file;
}
if (! isset($rename['target']) || $rename['target'] === '*') {
$rename['target'] = $rename['source'];
}
if (is_dir($rename['target'])) {
$name = basename($rename['source']);
$last = $rename['target'][strlen($rename['target']) - 1];
if ($last !== '/' && $last !== '\\') {
$rename['target'] .= DIRECTORY_SEPARATOR;
}
$rename['target'] .= $name;
}
if ($rename['randomize']) {
$info = pathinfo($rename['target']);
$newTarget = $info['dirname'] . DIRECTORY_SEPARATOR .
$info['filename'] . uniqid('_', false);
if (isset($info['extension'])) {
$newTarget .= '.' . $info['extension'];
}
$rename['target'] = $newTarget;
}
return $rename;
}
}
PK 髏P@ɒ% % src/DateTimeFormatter.phpnu W+A setOptions($options);
}
}
/**
* Set the format string accepted by date() to use when formatting a string
*
* @param string $format
* @return self
*/
public function setFormat($format)
{
$this->format = $format;
return $this;
}
/**
* Filter a datetime string by normalizing it to the filters specified format
*
* @param DateTime|string|integer $value
* @throws Exception\InvalidArgumentException
* @return string
*/
public function filter($value)
{
try {
$result = $this->normalizeDateTime($value);
} catch (\Exception $e) {
// DateTime threw an exception, an invalid date string was provided
throw new Exception\InvalidArgumentException('Invalid date string provided', $e->getCode(), $e);
}
if ($result === false) {
return $value;
}
return $result;
}
/**
* Normalize the provided value to a formatted string
*
* @param string|int|DateTime $value
* @return string
*/
protected function normalizeDateTime($value)
{
if ($value === '' || $value === null) {
return $value;
}
if (! is_string($value) && ! is_int($value) && ! $value instanceof DateTime) {
return $value;
}
if (is_int($value)) {
//timestamp
$value = new DateTime('@' . $value);
} elseif (! $value instanceof DateTime) {
$value = new DateTime($value);
}
return $value->format($this->format);
}
}
PK 髏PU[3 3 src/Null.phpnu W+A
*/
protected $options = [
'suffix' => null,
];
/**
* @param string|array|Traversable $options
*/
public function __construct($options = null)
{
if ($options !== null) {
$this->setOptions($options);
}
}
/**
* Set the suffix string
*
* @param string $suffix
*
* @return self
* @throws Exception\InvalidArgumentException
*/
public function setSuffix($suffix)
{
if (! is_string($suffix)) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects "suffix" to be string; received "%s"',
__METHOD__,
is_object($suffix) ? get_class($suffix) : gettype($suffix)
));
}
$this->options['suffix'] = $suffix;
return $this;
}
/**
* Returns the suffix string, which is appended at the end of the input value
*
* @return string
* @throws Exception\InvalidArgumentException
*/
public function getSuffix()
{
if (! isset($this->options['suffix'])) {
throw new Exception\InvalidArgumentException(sprintf(
'%s expects a "suffix" option; none given',
__CLASS__
));
}
return $this->options['suffix'];
}
/**
* {@inheritdoc}
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
return $value . $this->getSuffix();
}
}
PK 髏PnW src/Blacklist.phpnu W+A setOptions($options);
}
}
/**
* Determine whether the in_array() call should be "strict" or not. See in_array docs.
*
* @param bool $strict
*/
public function setStrict($strict = true)
{
$this->strict = (bool) $strict;
}
/**
* Returns whether the in_array() call should be "strict" or not. See in_array docs.
*
* @return boolean
*/
public function getStrict()
{
return $this->strict;
}
/**
* Set the list of items to black-list.
*
* @param array|Traversable $list
*/
public function setList($list = [])
{
if (! is_array($list)) {
$list = ArrayUtils::iteratorToArray($list);
}
$this->list = $list;
}
/**
* Get the list of items to black-list
*
* @return array
*/
public function getList()
{
return $this->list;
}
/**
* {@inheritDoc}
*
* Will return null if $value is present in the black-list. If $value is NOT present then it will return $value.
*/
public function filter($value)
{
return in_array($value, $this->getList(), $this->getStrict()) ? null : $value;
}
}
PK 髏Pts}J J src/HtmlEntities.phpnu W+A setQuoteStyle($options['quotestyle']);
$this->setEncoding($options['encoding']);
$this->setDoubleQuote($options['doublequote']);
}
/**
* Returns the quoteStyle option
*
* @return int
*/
public function getQuoteStyle()
{
return $this->quoteStyle;
}
/**
* Sets the quoteStyle option
*
* @param int $quoteStyle
* @return self Provides a fluent interface
*/
public function setQuoteStyle($quoteStyle)
{
$this->quoteStyle = $quoteStyle;
return $this;
}
/**
* Get encoding
*
* @return string
*/
public function getEncoding()
{
return $this->encoding;
}
/**
* Set encoding
*
* @param string $value
* @return self
*/
public function setEncoding($value)
{
$this->encoding = (string) $value;
return $this;
}
/**
* Returns the charSet option
*
* Proxies to {@link getEncoding()}
*
* @return string
*/
public function getCharSet()
{
return $this->getEncoding();
}
/**
* Sets the charSet option
*
* Proxies to {@link setEncoding()}
*
* @param string $charSet
* @return self Provides a fluent interface
*/
public function setCharSet($charSet)
{
return $this->setEncoding($charSet);
}
/**
* Returns the doubleQuote option
*
* @return bool
*/
public function getDoubleQuote()
{
return $this->doubleQuote;
}
/**
* Sets the doubleQuote option
*
* @param bool $doubleQuote
* @return self Provides a fluent interface
*/
public function setDoubleQuote($doubleQuote)
{
$this->doubleQuote = (bool) $doubleQuote;
return $this;
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns the string $value, converting characters to their corresponding HTML entity
* equivalents where they exist
*
* If the value provided is non-scalar, the value will remain unfiltered
*
* @param string $value
* @return string|mixed
* @throws Exception\DomainException on encoding mismatches
*/
public function filter($value)
{
if (! is_scalar($value)) {
return $value;
}
$value = (string) $value;
$filtered = htmlentities($value, $this->getQuoteStyle(), $this->getEncoding(), $this->getDoubleQuote());
if (strlen($value) && ! strlen($filtered)) {
if (! function_exists('iconv')) {
throw new Exception\DomainException('Encoding mismatch has resulted in htmlentities errors');
}
$enc = $this->getEncoding();
$value = iconv('', $this->getEncoding() . '//IGNORE', $value);
$filtered = htmlentities($value, $this->getQuoteStyle(), $enc, $this->getDoubleQuote());
if (! strlen($filtered)) {
throw new Exception\DomainException('Encoding mismatch has resulted in htmlentities errors');
}
}
return $filtered;
}
}
PK 髏P~ src/Encrypt.phpnu W+A setAdapter($options);
}
/**
* Returns the adapter instance
*
* @throws Exception\RuntimeException
* @throws Exception\InvalidArgumentException
* @return Encrypt\EncryptionAlgorithmInterface
*/
public function getAdapterInstance()
{
if ($this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) {
return $this->adapter;
}
$adapter = $this->adapter;
$options = $this->getOptions();
if (! class_exists($adapter)) {
$adapter = __CLASS__ . '\\' . ucfirst($adapter);
if (! class_exists($adapter)) {
throw new Exception\RuntimeException(sprintf(
'%s unable to load adapter; class "%s" not found',
__METHOD__,
$this->adapter
));
}
}
$this->adapter = new $adapter($options);
if (! $this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) {
throw new Exception\InvalidArgumentException(sprintf(
'Encryption adapter "%s" does not implement %s\\EncryptionAlgorithmInterface',
$adapter,
__CLASS__
));
}
return $this->adapter;
}
/**
* Returns the name of the set adapter
*
* @return string
*/
public function getAdapter()
{
return $this->adapter->toString();
}
/**
* Sets new encryption options
*
* @param string|array $options (Optional) Encryption options
* @return self
* @throws Exception\DomainException
* @throws Exception\InvalidArgumentException
*/
public function setAdapter($options = null)
{
if (is_string($options)) {
$adapter = $options;
} elseif (isset($options['adapter'])) {
$adapter = $options['adapter'];
unset($options['adapter']);
} else {
$adapter = 'BlockCipher';
}
if (! is_array($options)) {
$options = [];
}
if (class_exists('Laminas\Filter\Encrypt\\' . ucfirst($adapter))) {
$adapter = 'Laminas\Filter\Encrypt\\' . ucfirst($adapter);
} elseif (! class_exists($adapter)) {
throw new Exception\DomainException(
sprintf(
'%s expects a valid registry class name; received "%s", which did not resolve',
__METHOD__,
$adapter
)
);
}
$this->adapter = new $adapter($options);
if (! $this->adapter instanceof Encrypt\EncryptionAlgorithmInterface) {
throw new Exception\InvalidArgumentException(
"Encoding adapter '" . $adapter
. "' does not implement Laminas\\Filter\\Encrypt\\EncryptionAlgorithmInterface"
);
}
return $this;
}
/**
* Calls adapter methods
*
* @param string $method Method to call
* @param string|array $options Options for this method
* @return mixed
* @throws Exception\BadMethodCallException
*/
public function __call($method, $options)
{
$part = substr($method, 0, 3);
if (($part !== 'get' && $part !== 'set') || ! method_exists($this->adapter, $method)) {
throw new Exception\BadMethodCallException("Unknown method '{$method}'");
}
return call_user_func_array([$this->adapter, $method], $options);
}
/**
* Defined by Laminas\Filter\Filter
*
* Encrypts the content $value with the defined settings
*
* @param string $value Content to encrypt
* @return string The encrypted content
*/
public function filter($value)
{
if (! is_string($value) && ! is_numeric($value)) {
return $value;
}
return $this->adapter->encrypt($value);
}
}
PK 髏Pj~ ~ src/FilterProviderInterface.phpnu W+A setOptions($options);
}
/**
* Retrieve plugin manager
*
* @return FilterPluginManager
*/
public function getPluginManager()
{
if (! $this->pluginManager instanceof FilterPluginManager) {
$this->setPluginManager(new FilterPluginManager(new ServiceManager()));
}
return $this->pluginManager;
}
/**
* Set plugin manager
*
* @param FilterPluginManager $manager
* @return self
*/
public function setPluginManager(FilterPluginManager $manager)
{
$this->pluginManager = $manager;
return $this;
}
/**
* Set options
*
* @param array|Traversable $options
* @return self
*/
public function setOptions($options)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
// Set plugin manager
if (array_key_exists('pluginManager', $options)) {
if (is_scalar($options['pluginManager']) && class_exists($options['pluginManager'])) {
$options['pluginManager'] = new $options['pluginManager'];
}
$this->setPluginManager($options['pluginManager']);
}
if (array_key_exists('throwTargetExceptionsOn', $options)) {
$this->setThrowTargetExceptionsOn($options['throwTargetExceptionsOn']);
}
if (array_key_exists('targetReplacementIdentifier', $options)) {
$this->setTargetReplacementIdentifier($options['targetReplacementIdentifier']);
}
if (array_key_exists('target', $options)) {
$this->setTarget($options['target']);
}
if (array_key_exists('rules', $options)) {
$this->addRules($options['rules']);
}
return $this;
}
/**
* Set Whether or not the inflector should throw an exception when a replacement
* identifier is still found within an inflected target.
*
* @param bool $throwTargetExceptionsOn
* @return self
*/
public function setThrowTargetExceptionsOn($throwTargetExceptionsOn)
{
$this->throwTargetExceptionsOn = (bool) $throwTargetExceptionsOn;
return $this;
}
/**
* Will exceptions be thrown?
*
* @return bool
*/
public function isThrowTargetExceptionsOn()
{
return $this->throwTargetExceptionsOn;
}
/**
* Set the Target Replacement Identifier, by default ':'
*
* @param string $targetReplacementIdentifier
* @return self
*/
public function setTargetReplacementIdentifier($targetReplacementIdentifier)
{
if ($targetReplacementIdentifier) {
$this->targetReplacementIdentifier = (string) $targetReplacementIdentifier;
}
return $this;
}
/**
* Get Target Replacement Identifier
*
* @return string
*/
public function getTargetReplacementIdentifier()
{
return $this->targetReplacementIdentifier;
}
/**
* Set a Target
* ex: 'scripts/:controller/:action.:suffix'
*
* @param string $target
* @return self
*/
public function setTarget($target)
{
$this->target = (string) $target;
return $this;
}
/**
* Retrieve target
*
* @return string
*/
public function getTarget()
{
return $this->target;
}
/**
* Set Target Reference
*
* @param string $target
* @return self
*/
public function setTargetReference(&$target)
{
$this->target =& $target;
return $this;
}
/**
* Is the same as calling addRules() with the exception that it
* clears the rules before adding them.
*
* @param array $rules
* @return self
*/
public function setRules(array $rules)
{
$this->clearRules();
$this->addRules($rules);
return $this;
}
/**
* Multi-call to setting filter rules.
*
* If prefixed with a ":" (colon), a filter rule will be added. If not
* prefixed, a static replacement will be added.
*
* ex:
* array(
* ':controller' => array('CamelCaseToUnderscore', 'StringToLower'),
* ':action' => array('CamelCaseToUnderscore', 'StringToLower'),
* 'suffix' => 'phtml'
* );
*
* @param array $rules
* @return self
*/
public function addRules(array $rules)
{
$keys = array_keys($rules);
foreach ($keys as $spec) {
if ($spec[0] === ':') {
$this->addFilterRule($spec, $rules[$spec]);
} else {
$this->setStaticRule($spec, $rules[$spec]);
}
}
return $this;
}
/**
* Get rules
*
* By default, returns all rules. If a $spec is provided, will return those
* rules if found, false otherwise.
*
* @param string $spec
* @return array|false
*/
public function getRules($spec = null)
{
if (null !== $spec) {
$spec = $this->_normalizeSpec($spec);
if (isset($this->rules[$spec])) {
return $this->rules[$spec];
}
return false;
}
return $this->rules;
}
/**
* Returns a rule set by setFilterRule(), a numeric index must be provided
*
* @param string $spec
* @param int $index
* @return FilterInterface|false
*/
public function getRule($spec, $index)
{
$spec = $this->_normalizeSpec($spec);
if (isset($this->rules[$spec]) && is_array($this->rules[$spec])) {
if (isset($this->rules[$spec][$index])) {
return $this->rules[$spec][$index];
}
}
return false;
}
/**
* Clears the rules currently in the inflector
*
* @return self
*/
public function clearRules()
{
$this->rules = [];
return $this;
}
/**
* Set a filtering rule for a spec. $ruleSet can be a string, Filter object
* or an array of strings or filter objects.
*
* @param string $spec
* @param array|string|\Laminas\Filter\FilterInterface $ruleSet
* @return self
*/
public function setFilterRule($spec, $ruleSet)
{
$spec = $this->_normalizeSpec($spec);
$this->rules[$spec] = [];
return $this->addFilterRule($spec, $ruleSet);
}
/**
* Add a filter rule for a spec
*
* @param mixed $spec
* @param mixed $ruleSet
* @return self
*/
public function addFilterRule($spec, $ruleSet)
{
$spec = $this->_normalizeSpec($spec);
if (! isset($this->rules[$spec])) {
$this->rules[$spec] = [];
}
if (! is_array($ruleSet)) {
$ruleSet = [$ruleSet];
}
if (is_string($this->rules[$spec])) {
$temp = $this->rules[$spec];
$this->rules[$spec] = [];
$this->rules[$spec][] = $temp;
}
foreach ($ruleSet as $rule) {
$this->rules[$spec][] = $this->_getRule($rule);
}
return $this;
}
/**
* Set a static rule for a spec. This is a single string value
*
* @param string $name
* @param string $value
* @return self
*/
public function setStaticRule($name, $value)
{
$name = $this->_normalizeSpec($name);
$this->rules[$name] = (string) $value;
return $this;
}
/**
* Set Static Rule Reference.
*
* This allows a consuming class to pass a property or variable
* in to be referenced when its time to build the output string from the
* target.
*
* @param string $name
* @param mixed $reference
* @return self
*/
public function setStaticRuleReference($name, &$reference)
{
$name = $this->_normalizeSpec($name);
$this->rules[$name] =& $reference;
return $this;
}
/**
* Inflect
*
* @param string|array $source
* @throws Exception\RuntimeException
* @return string
*/
public function filter($source)
{
// clean source
foreach ((array) $source as $sourceName => $sourceValue) {
$source[ltrim($sourceName, ':')] = $sourceValue;
}
$pregQuotedTargetReplacementIdentifier = preg_quote($this->targetReplacementIdentifier, '#');
$processedParts = [];
foreach ($this->rules as $ruleName => $ruleValue) {
if (isset($source[$ruleName])) {
if (is_string($ruleValue)) {
// overriding the set rule
$processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace(
'\\',
'\\\\',
$source[$ruleName]
);
} elseif (is_array($ruleValue)) {
$processedPart = $source[$ruleName];
foreach ($ruleValue as $ruleFilter) {
$processedPart = $ruleFilter($processedPart);
}
$processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace(
'\\',
'\\\\',
$processedPart
);
}
} elseif (is_string($ruleValue)) {
$processedParts['#' . $pregQuotedTargetReplacementIdentifier . $ruleName . '#'] = str_replace(
'\\',
'\\\\',
$ruleValue
);
}
}
// all of the values of processedParts would have been str_replace('\\', '\\\\', ..)'d
// to disable preg_replace backreferences
$inflectedTarget = preg_replace(array_keys($processedParts), array_values($processedParts), $this->target);
if ($this->throwTargetExceptionsOn
&& preg_match('#(?=' . $pregQuotedTargetReplacementIdentifier.'[A-Za-z]{1})#', $inflectedTarget)
) {
throw new Exception\RuntimeException(
'A replacement identifier ' . $this->targetReplacementIdentifier
. ' was found inside the inflected target, perhaps a rule was not satisfied with a target source? '
. 'Unsatisfied inflected target: ' . $inflectedTarget
);
}
return $inflectedTarget;
}
/**
* Normalize spec string
*
* @param string $spec
* @return string
*/
// @codingStandardsIgnoreStart
protected function _normalizeSpec($spec)
{
// @codingStandardsIgnoreEnd
return ltrim((string) $spec, ':&');
}
/**
* Resolve named filters and convert them to filter objects.
*
* @param string $rule
* @return FilterInterface
*/
// @codingStandardsIgnoreStart
protected function _getRule($rule)
{
// @codingStandardsIgnoreEnd
if ($rule instanceof FilterInterface) {
return $rule;
}
$rule = (string) $rule;
return $this->getPluginManager()->get($rule);
}
}
PK 髏Pat src/Boolean.phpnu W+A 'boolean',
self::TYPE_INTEGER => 'integer',
self::TYPE_FLOAT => 'float',
self::TYPE_STRING => 'string',
self::TYPE_ZERO_STRING => 'zero',
self::TYPE_EMPTY_ARRAY => 'array',
self::TYPE_NULL => 'null',
self::TYPE_PHP => 'php',
self::TYPE_FALSE_STRING => 'false',
self::TYPE_LOCALIZED => 'localized',
self::TYPE_ALL => 'all',
];
/**
* @var array
*/
protected $options = [
'type' => self::TYPE_PHP,
'casting' => true,
'translations' => [],
];
/**
* Constructor
*
* @param int|string|array|Traversable|null $typeOrOptions
* @param bool $casting
* @param array $translations
*/
public function __construct($typeOrOptions = null, $casting = true, $translations = [])
{
if ($typeOrOptions !== null) {
if ($typeOrOptions instanceof Traversable) {
$typeOrOptions = ArrayUtils::iteratorToArray($typeOrOptions);
}
if (is_array($typeOrOptions)) {
if (isset($typeOrOptions['type'])
|| isset($typeOrOptions['casting'])
|| isset($typeOrOptions['translations'])
) {
$this->setOptions($typeOrOptions);
} else {
$this->setType($typeOrOptions);
$this->setCasting($casting);
$this->setTranslations($translations);
}
} else {
$this->setType($typeOrOptions);
$this->setCasting($casting);
$this->setTranslations($translations);
}
}
}
/**
* Set boolean types
*
* @param int|string|array $type
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setType($type = null)
{
if (is_array($type)) {
$detected = 0;
foreach ($type as $value) {
if (is_int($value)) {
$detected |= $value;
} elseif (($found = array_search($value, $this->constants, true)) !== false) {
$detected |= $found;
}
}
$type = $detected;
} elseif (is_string($type) && ($found = array_search($type, $this->constants, true)) !== false) {
$type = $found;
}
if (! is_int($type) || ($type < 0) || ($type > self::TYPE_ALL)) {
throw new Exception\InvalidArgumentException(sprintf(
'Unknown type value "%s" (%s)',
$type,
gettype($type)
));
}
$this->options['type'] = $type;
return $this;
}
/**
* Returns defined boolean types
*
* @return int
*/
public function getType()
{
return $this->options['type'];
}
/**
* Set the working mode
*
* @param bool $flag When true this filter works like cast
* When false it recognises only true and false
* and all other values are returned as is
* @return self
*/
public function setCasting($flag = true)
{
$this->options['casting'] = (bool) $flag;
return $this;
}
/**
* Returns the casting option
*
* @return bool
*/
public function getCasting()
{
return $this->options['casting'];
}
/**
* @param array|Traversable $translations
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setTranslations($translations)
{
if (! is_array($translations) && ! $translations instanceof Traversable) {
throw new Exception\InvalidArgumentException(sprintf(
'"%s" expects an array or Traversable; received "%s"',
__METHOD__,
(is_object($translations) ? get_class($translations) : gettype($translations))
));
}
foreach ($translations as $message => $flag) {
$this->options['translations'][$message] = (bool) $flag;
}
return $this;
}
/**
* @return array
*/
public function getTranslations()
{
return $this->options['translations'];
}
/**
* Defined by Laminas\Filter\FilterInterface
*
* Returns a boolean representation of $value
*
* @param null|array|bool|float|int|string $value
* @return bool|mixed
*/
public function filter($value)
{
$type = $this->getType();
$casting = $this->getCasting();
// LOCALIZED
if ($type & self::TYPE_LOCALIZED) {
if (is_string($value)) {
if (isset($this->options['translations'][$value])) {
return (bool) $this->options['translations'][$value];
}
}
}
// FALSE_STRING ('false')
if ($type & self::TYPE_FALSE_STRING) {
if (is_string($value) && strtolower($value) === 'false') {
return false;
}
if (! $casting && is_string($value) && strtolower($value) === 'true') {
return true;
}
}
// NULL (null)
if ($type & self::TYPE_NULL) {
if ($value === null) {
return false;
}
}
// EMPTY_ARRAY (array())
if ($type & self::TYPE_EMPTY_ARRAY) {
if (is_array($value) && $value === []) {
return false;
}
}
// ZERO_STRING ('0')
if ($type & self::TYPE_ZERO_STRING) {
if (is_string($value) && $value === '0') {
return false;
}
if (! $casting && is_string($value) && $value === '1') {
return true;
}
}
// STRING ('')
if ($type & self::TYPE_STRING) {
if (is_string($value) && $value === '') {
return false;
}
}
// FLOAT (0.0)
if ($type & self::TYPE_FLOAT) {
if (is_float($value) && $value === 0.0) {
return false;
}
if (! $casting && is_float($value) && $value === 1.0) {
return true;
}
}
// INTEGER (0)
if ($type & self::TYPE_INTEGER) {
if (is_int($value) && $value === 0) {
return false;
}
if (! $casting && is_int($value) && $value === 1) {
return true;
}
}
// BOOLEAN (false)
if ($type & self::TYPE_BOOLEAN) {
if (is_bool($value)) {
return $value;
}
}
if ($casting) {
return true;
}
return $value;
}
}
PK 髏P-_ src/AbstractUnicode.phpnu W+A options['encoding'] = $encoding;
return $this;
}
/**
* Returns the set encoding
*
* @return string
*/
public function getEncoding()
{
if ($this->options['encoding'] === null && function_exists('mb_internal_encoding')) {
$this->options['encoding'] = mb_internal_encoding();
}
return $this->options['encoding'];
}
}
PK 髏P[
[
src/AbstractFilter.phpnu W+A $value) {
$setter = 'set' . str_replace(' ', '', ucwords(str_replace('_', ' ', $key)));
if (method_exists($this, $setter)) {
$this->{$setter}($value);
} elseif (array_key_exists($key, $this->options)) {
$this->options[$key] = $value;
} else {
throw new Exception\InvalidArgumentException(
sprintf(
'The option "%s" does not have a matching %s setter method or options[%s] array key',
$key,
$setter,
$key
)
);
}
}
return $this;
}
/**
* Retrieve options representing object state
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Invoke filter as a command
*
* Proxies to {@link filter()}
*
* @param mixed $value
* @throws Exception\ExceptionInterface If filtering $value is impossible
* @return mixed
*/
public function __invoke($value)
{
return $this->filter($value);
}
/**
* @param mixed $options
* @return bool
*/
protected static function isOptions($options)
{
return (is_array($options) || $options instanceof Traversable);
}
}
PK 髏P3e` ` src/Decompress.phpnu W+A filter($value);
}
/**
* Defined by FilterInterface
*
* Decompresses the content $value with the defined settings
*
* @param string $value Content to decompress
* @return string The decompressed content
*/
public function filter($value)
{
if (! is_string($value) && $value !== null) {
return $value;
}
return $this->getAdapter()->decompress($value);
}
}
PK 髏Pڋ . src/Compress/CompressionAlgorithmInterface.phpnu W+A Archive to use
* 'password' => Password to use
* 'target' => Target to write the files to
* )
*
* @var array
*/
protected $options = [
'archive' => null,
'target' => null,
];
/**
* Class constructor
*
* @param null|array|\Traversable $options (Optional) Options to set
* @throws Exception\ExtensionNotLoadedException if zip extension not loaded
*/
public function __construct($options = null)
{
if (! extension_loaded('zip')) {
throw new Exception\ExtensionNotLoadedException('This filter needs the zip extension');
}
parent::__construct($options);
}
/**
* Returns the set archive
*
* @return string
*/
public function getArchive()
{
return $this->options['archive'];
}
/**
* Sets the archive to use for de-/compression
*
* @param string $archive Archive to use
* @return self
*/
public function setArchive($archive)
{
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, (string) $archive);
$this->options['archive'] = $archive;
return $this;
}
/**
* Returns the set targetpath
*
* @return string
*/
public function getTarget()
{
return $this->options['target'];
}
/**
* Sets the target to use
*
* @param string $target
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setTarget($target)
{
if (! file_exists(dirname($target))) {
throw new Exception\InvalidArgumentException("The directory '$target' does not exist");
}
$target = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, (string) $target);
$this->options['target'] = $target;
return $this;
}
/**
* Compresses the given content
*
* @param string $content
* @return string Compressed archive
* @throws Exception\RuntimeException if unable to open zip archive, or error during compression
*/
public function compress($content)
{
$zip = new ZipArchive();
$res = $zip->open($this->getArchive(), ZipArchive::CREATE | ZipArchive::OVERWRITE);
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
if (file_exists($content)) {
$content = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));
$basename = substr($content, strrpos($content, DIRECTORY_SEPARATOR) + 1);
if (is_dir($content)) {
$index = strrpos($content, DIRECTORY_SEPARATOR) + 1;
$content .= DIRECTORY_SEPARATOR;
$stack = [$content];
while (! empty($stack)) {
$current = array_pop($stack);
$files = [];
$dir = dir($current);
while (false !== ($node = $dir->read())) {
if ($node === '.' || $node === '..') {
continue;
}
if (is_dir($current . $node)) {
$stack[] = $current . $node . DIRECTORY_SEPARATOR;
}
if (is_file($current . $node)) {
$files[] = $node;
}
}
$local = substr($current, $index);
$zip->addEmptyDir(substr($local, 0, -1));
foreach ($files as $file) {
$zip->addFile($current . $file, $local . $file);
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
}
}
} else {
$res = $zip->addFile($content, $basename);
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
}
} else {
$file = $this->getTarget();
if (! is_dir($file)) {
$file = basename($file);
} else {
$file = 'zip.tmp';
}
$res = $zip->addFromString($file, $content);
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
}
$zip->close();
return $this->options['archive'];
}
/**
* Decompresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException If archive file not found, target directory not found,
* or error during decompression
*/
public function decompress($content)
{
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));
if (empty($archive) || ! file_exists($archive)) {
throw new Exception\RuntimeException('ZIP Archive not found');
}
$zip = new ZipArchive();
$res = $zip->open($archive);
$target = $this->getTarget();
if (! empty($target) && ! is_dir($target)) {
$target = dirname($target);
}
if (! empty($target)) {
$target = rtrim($target, '/\\') . DIRECTORY_SEPARATOR;
}
if (empty($target) || ! is_dir($target)) {
throw new Exception\RuntimeException('No target for ZIP decompression set');
}
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
$res = $zip->extractTo($target);
if ($res !== true) {
throw new Exception\RuntimeException($this->errorString($res));
}
$zip->close();
return $target;
}
/**
* Returns the proper string based on the given error constant
*
* @param string $error
* @return string
*/
public function errorString($error)
{
switch ($error) {
case ZipArchive::ER_MULTIDISK:
return 'Multidisk ZIP Archives not supported';
case ZipArchive::ER_RENAME:
return 'Failed to rename the temporary file for ZIP';
case ZipArchive::ER_CLOSE:
return 'Failed to close the ZIP Archive';
case ZipArchive::ER_SEEK:
return 'Failure while seeking the ZIP Archive';
case ZipArchive::ER_READ:
return 'Failure while reading the ZIP Archive';
case ZipArchive::ER_WRITE:
return 'Failure while writing the ZIP Archive';
case ZipArchive::ER_CRC:
return 'CRC failure within the ZIP Archive';
case ZipArchive::ER_ZIPCLOSED:
return 'ZIP Archive already closed';
case ZipArchive::ER_NOENT:
return 'No such file within the ZIP Archive';
case ZipArchive::ER_EXISTS:
return 'ZIP Archive already exists';
case ZipArchive::ER_OPEN:
return 'Can not open ZIP Archive';
case ZipArchive::ER_TMPOPEN:
return 'Failure creating temporary ZIP Archive';
case ZipArchive::ER_ZLIB:
return 'ZLib Problem';
case ZipArchive::ER_MEMORY:
return 'Memory allocation problem while working on a ZIP Archive';
case ZipArchive::ER_CHANGED:
return 'ZIP Entry has been changed';
case ZipArchive::ER_COMPNOTSUPP:
return 'Compression method not supported within ZLib';
case ZipArchive::ER_EOF:
return 'Premature EOF within ZIP Archive';
case ZipArchive::ER_INVAL:
return 'Invalid argument for ZLIB';
case ZipArchive::ER_NOZIP:
return 'Given file is no zip archive';
case ZipArchive::ER_INTERNAL:
return 'Internal error while working on a ZIP Archive';
case ZipArchive::ER_INCONS:
return 'Inconsistent ZIP archive';
case ZipArchive::ER_REMOVE:
return 'Can not remove ZIP Archive';
case ZipArchive::ER_DELETED:
return 'ZIP Entry has been deleted';
default:
return 'Unknown error within ZIP Archive';
}
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Zip';
}
}
PK 髏PC
# - src/Compress/AbstractCompressionAlgorithm.phpnu W+A setOptions($options);
}
}
/**
* Returns one or all set options
*
* @param string|null $option Option to return
* @return mixed
*/
public function getOptions($option = null)
{
if ($option === null) {
return $this->options;
}
if (! isset($this->options[$option])) {
return null;
}
return $this->options[$option];
}
/**
* Sets all or one option
*
* @param array $options
* @return self
*/
public function setOptions(array $options)
{
foreach ($options as $key => $option) {
$method = 'set' . $key;
if (method_exists($this, $method)) {
$this->$method($option);
}
}
return $this;
}
}
PK 髏P5_ _ src/Compress/Rar.phpnu W+A Callback for compression
* 'archive' => Archive to use
* 'password' => Password to use
* 'target' => Target to write the files to
* )
*
* @var array
*/
protected $options = [
'callback' => null,
'archive' => null,
'password' => null,
'target' => '.',
];
/**
* Class constructor
*
* @param array $options (Optional) Options to set
* @throws Exception\ExtensionNotLoadedException if rar extension not loaded
*/
public function __construct($options = null)
{
if (! extension_loaded('rar')) {
throw new Exception\ExtensionNotLoadedException('This filter needs the rar extension');
}
parent::__construct($options);
}
/**
* Returns the set callback for compression
*
* @return string
*/
public function getCallback()
{
return $this->options['callback'];
}
/**
* Sets the callback to use
*
* @param string $callback
* @return self
* @throws Exception\InvalidArgumentException if invalid callback provided
*/
public function setCallback($callback)
{
if (! is_callable($callback)) {
throw new Exception\InvalidArgumentException('Invalid callback provided');
}
$this->options['callback'] = $callback;
return $this;
}
/**
* Returns the set archive
*
* @return string
*/
public function getArchive()
{
return $this->options['archive'];
}
/**
* Sets the archive to use for de-/compression
*
* @param string $archive Archive to use
* @return self
*/
public function setArchive($archive)
{
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $archive);
$this->options['archive'] = (string) $archive;
return $this;
}
/**
* Returns the set password
*
* @return string
*/
public function getPassword()
{
return $this->options['password'];
}
/**
* Sets the password to use
*
* @param string $password
* @return self
*/
public function setPassword($password)
{
$this->options['password'] = (string) $password;
return $this;
}
/**
* Returns the set targetpath
*
* @return string
*/
public function getTarget()
{
return $this->options['target'];
}
/**
* Sets the targetpath to use
*
* @param string $target
* @return self
* @throws Exception\InvalidArgumentException if specified target directory does not exist
*/
public function setTarget($target)
{
if (! file_exists(dirname($target))) {
throw new Exception\InvalidArgumentException("The directory '$target' does not exist");
}
$target = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, (string) $target);
$this->options['target'] = $target;
return $this;
}
/**
* Compresses the given content
*
* @param string|array $content
* @return string
* @throws Exception\RuntimeException if no callback available, or error during compression
*/
public function compress($content)
{
$callback = $this->getCallback();
if ($callback === null) {
throw new Exception\RuntimeException('No compression callback available');
}
$options = $this->getOptions();
unset($options['callback']);
$result = $callback($options, $content);
if ($result !== true) {
throw new Exception\RuntimeException('Error compressing the RAR Archive');
}
return $this->getArchive();
}
/**
* Decompresses the given content
*
* @param string $content
* @return bool
* @throws Exception\RuntimeException if archive not found, cannot be opened,
* or error during decompression
*/
public function decompress($content)
{
if (! file_exists($content)) {
throw new Exception\RuntimeException('RAR Archive not found');
}
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));
$password = $this->getPassword();
if ($password !== null) {
$archive = rar_open($archive, $password);
} else {
$archive = rar_open($archive);
}
if (! $archive) {
throw new Exception\RuntimeException('Error opening the RAR Archive');
}
$target = $this->getTarget();
if (! is_dir($target)) {
$target = dirname($target);
}
$filelist = rar_list($archive);
if (! $filelist) {
throw new Exception\RuntimeException("Error reading the RAR Archive");
}
foreach ($filelist as $file) {
$file->extract($target);
}
rar_close($archive);
return true;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Rar';
}
}
PK 髏P^ src/Compress/Snappy.phpnu W+A Compression level 0-9
* 'mode' => Compression mode, can be 'compress', 'deflate'
* 'archive' => Archive to use
* )
*
* @var array
*/
protected $options = [
'level' => 9,
'mode' => 'compress',
'archive' => null,
];
/**
* Class constructor
*
* @param null|array|\Traversable $options (Optional) Options to set
* @throws Exception\ExtensionNotLoadedException if zlib extension not loaded
*/
public function __construct($options = null)
{
if (! extension_loaded('zlib')) {
throw new Exception\ExtensionNotLoadedException('This filter needs the zlib extension');
}
parent::__construct($options);
}
/**
* Returns the set compression level
*
* @return int
*/
public function getLevel()
{
return $this->options['level'];
}
/**
* Sets a new compression level
*
* @param int $level
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setLevel($level)
{
if (($level < 0) || ($level > 9)) {
throw new Exception\InvalidArgumentException('Level must be between 0 and 9');
}
$this->options['level'] = (int) $level;
return $this;
}
/**
* Returns the set compression mode
*
* @return string
*/
public function getMode()
{
return $this->options['mode'];
}
/**
* Sets a new compression mode
*
* @param string $mode Supported are 'compress', 'deflate' and 'file'
* @return self
* @throws Exception\InvalidArgumentException for invalid $mode value
*/
public function setMode($mode)
{
if ($mode !== 'compress' && $mode !== 'deflate') {
throw new Exception\InvalidArgumentException('Given compression mode not supported');
}
$this->options['mode'] = $mode;
return $this;
}
/**
* Returns the set archive
*
* @return string
*/
public function getArchive()
{
return $this->options['archive'];
}
/**
* Sets the archive to use for de-/compression
*
* @param string $archive Archive to use
* @return self
*/
public function setArchive($archive)
{
$this->options['archive'] = (string) $archive;
return $this;
}
/**
* Compresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException if unable to open archive or error during decompression
*/
public function compress($content)
{
$archive = $this->getArchive();
if (! empty($archive)) {
$file = gzopen($archive, 'w' . $this->getLevel());
if (! $file) {
throw new Exception\RuntimeException("Error opening the archive '" . $this->options['archive'] . "'");
}
gzwrite($file, $content);
gzclose($file);
$compressed = true;
} elseif ($this->options['mode'] === 'deflate') {
$compressed = gzdeflate($content, $this->getLevel());
} else {
$compressed = gzcompress($content, $this->getLevel());
}
if (! $compressed) {
throw new Exception\RuntimeException('Error during compression');
}
return $compressed;
}
/**
* Decompresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException if unable to open archive or error during decompression
*/
public function decompress($content)
{
$archive = $this->getArchive();
$mode = $this->getMode();
//check if there are null byte characters before doing a file_exists check
if (false === strpos($content, "\0") && file_exists($content)) {
$archive = $content;
}
if (file_exists($archive)) {
$handler = fopen($archive, 'rb');
if (! $handler) {
throw new Exception\RuntimeException("Error opening the archive '" . $archive . "'");
}
fseek($handler, -4, SEEK_END);
$packet = fread($handler, 4);
$bytes = unpack('V', $packet);
$size = end($bytes);
fclose($handler);
$file = gzopen($archive, 'r');
$compressed = gzread($file, $size);
gzclose($file);
} elseif ($mode === 'deflate') {
$compressed = gzinflate($content);
} else {
$compressed = gzuncompress($content);
}
if ($compressed === false) {
throw new Exception\RuntimeException('Error during decompression');
}
return $compressed;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Gz';
}
}
PK 髏Pmhw w src/Compress/Tar.phpnu W+A Archive to use
* 'target' => Target to write the files to
* )
*
* @var array
*/
protected $options = [
'archive' => null,
'target' => '.',
'mode' => null,
];
/**
* Class constructor
*
* @param array $options (Optional) Options to set
* @throws Exception\ExtensionNotLoadedException if Archive_Tar component not available
*/
public function __construct($options = null)
{
if (! class_exists('Archive_Tar')) {
throw new Exception\ExtensionNotLoadedException(
'This filter needs PEAR\'s Archive_Tar component. '
. 'Ensure loading Archive_Tar (registering autoload or require_once)'
);
}
parent::__construct($options);
}
/**
* Returns the set archive
*
* @return string
*/
public function getArchive()
{
return $this->options['archive'];
}
/**
* Sets the archive to use for de-/compression
*
* @param string $archive Archive to use
* @return self
*/
public function setArchive($archive)
{
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, (string) $archive);
$this->options['archive'] = $archive;
return $this;
}
/**
* Returns the set target path
*
* @return string
*/
public function getTarget()
{
return $this->options['target'];
}
/**
* Sets the target path to use
*
* @param string $target
* @return self
* @throws Exception\InvalidArgumentException if target path does not exist
*/
public function setTarget($target)
{
if (! file_exists(dirname($target))) {
throw new Exception\InvalidArgumentException("The directory '$target' does not exist");
}
$target = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, (string) $target);
$this->options['target'] = $target;
return $this;
}
/**
* Returns the set compression mode
*
* @return string
*/
public function getMode()
{
return $this->options['mode'];
}
/**
* Compression mode to use
*
* Either Gz or Bz2.
*
* @param string $mode
* @return self
* @throws Exception\InvalidArgumentException for invalid $mode values
* @throws Exception\ExtensionNotLoadedException if bz2 mode selected but extension not loaded
* @throws Exception\ExtensionNotLoadedException if gz mode selected but extension not loaded
*/
public function setMode($mode)
{
$mode = strtolower($mode);
if ($mode !== 'bz2' && $mode !== 'gz') {
throw new Exception\InvalidArgumentException("The mode '$mode' is unknown");
}
if ($mode === 'bz2' && ! extension_loaded('bz2')) {
throw new Exception\ExtensionNotLoadedException('This mode needs the bz2 extension');
}
if ($mode === 'gz' && ! extension_loaded('zlib')) {
throw new Exception\ExtensionNotLoadedException('This mode needs the zlib extension');
}
$this->options['mode'] = $mode;
return $this;
}
/**
* Compresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException if unable to create temporary file
* @throws Exception\RuntimeException if unable to create archive
*/
public function compress($content)
{
$archive = new Archive_Tar($this->getArchive(), $this->getMode());
if (! file_exists($content)) {
$file = $this->getTarget();
if (is_dir($file)) {
$file .= DIRECTORY_SEPARATOR . 'tar.tmp';
}
$result = file_put_contents($file, $content);
if ($result === false) {
throw new Exception\RuntimeException('Error creating the temporary file');
}
$content = $file;
}
if (is_dir($content)) {
// collect all file infos
foreach (new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($content, RecursiveDirectoryIterator::KEY_AS_PATHNAME),
RecursiveIteratorIterator::SELF_FIRST
) as $directory => $info) {
if ($info->isFile()) {
$file[] = $directory;
}
}
$content = $file;
}
$result = $archive->create($content);
if ($result === false) {
throw new Exception\RuntimeException('Error creating the Tar archive');
}
return $this->getArchive();
}
/**
* Decompresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException if unable to find archive
* @throws Exception\RuntimeException if error occurs decompressing archive
*/
public function decompress($content)
{
$archive = $this->getArchive();
if (file_exists($content)) {
$archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));
} elseif (empty($archive) || ! file_exists($archive)) {
throw new Exception\RuntimeException('Tar Archive not found');
}
$archive = new Archive_Tar($archive, $this->getMode());
$target = $this->getTarget();
if (! is_dir($target)) {
$target = dirname($target) . DIRECTORY_SEPARATOR;
}
$result = $archive->extract($target);
if ($result === false) {
throw new Exception\RuntimeException('Error while extracting the Tar archive');
}
return $target;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Tar';
}
}
PK 髏P;: ' ' src/Compress/Lzf.phpnu W+A Blocksize to use from 0-9
* 'archive' => Archive to use
* )
*
* @var array
*/
protected $options = [
'blocksize' => 4,
'archive' => null,
];
/**
* Class constructor
*
* @param null|array|\Traversable $options (Optional) Options to set
* @throws Exception\ExtensionNotLoadedException if bz2 extension not loaded
*/
public function __construct($options = null)
{
if (! extension_loaded('bz2')) {
throw new Exception\ExtensionNotLoadedException('This filter needs the bz2 extension');
}
parent::__construct($options);
}
/**
* Returns the set blocksize
*
* @return int
*/
public function getBlocksize()
{
return $this->options['blocksize'];
}
/**
* Sets a new blocksize
*
* @param int $blocksize
* @throws Exception\InvalidArgumentException
* @return self
*/
public function setBlocksize($blocksize)
{
if (($blocksize < 0) || ($blocksize > 9)) {
throw new Exception\InvalidArgumentException('Blocksize must be between 0 and 9');
}
$this->options['blocksize'] = (int) $blocksize;
return $this;
}
/**
* Returns the set archive
*
* @return string
*/
public function getArchive()
{
return $this->options['archive'];
}
/**
* Sets the archive to use for de-/compression
*
* @param string $archive Archive to use
* @return self
*/
public function setArchive($archive)
{
$this->options['archive'] = (string) $archive;
return $this;
}
/**
* Compresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException
*/
public function compress($content)
{
$archive = $this->getArchive();
if (! empty($archive)) {
$file = bzopen($archive, 'w');
if (! $file) {
throw new Exception\RuntimeException("Error opening the archive '" . $archive . "'");
}
bzwrite($file, $content);
bzclose($file);
$compressed = true;
} else {
$compressed = bzcompress($content, $this->getBlocksize());
}
if (is_int($compressed)) {
throw new Exception\RuntimeException('Error during compression');
}
return $compressed;
}
/**
* Decompresses the given content
*
* @param string $content
* @return string
* @throws Exception\RuntimeException
*/
public function decompress($content)
{
$archive = $this->getArchive();
//check if there are null byte characters before doing a file_exists check
if (false === strpos($content, "\0") && file_exists($content)) {
$archive = $content;
}
if (file_exists($archive)) {
$file = bzopen($archive, 'r');
if (! $file) {
throw new Exception\RuntimeException("Error opening the archive '" . $content . "'");
}
$compressed = bzread($file);
bzclose($file);
} else {
$compressed = bzdecompress($content);
}
if (is_int($compressed)) {
throw new Exception\RuntimeException('Error during decompression');
}
return $compressed;
}
/**
* Returns the adapter name
*
* @return string
*/
public function toString()
{
return 'Bz2';
}
}
PK 髏PzvS S src/ConfigProvider.phpnu W+A $this->getDependencyConfig(),
];
}
/**
* Return dependency mappings for this component.
*
* @return array
*/
public function getDependencyConfig()
{
return [
'aliases' => [
'FilterManager' => FilterPluginManager::class,
// Legacy Zend Framework aliases
\Zend\Filter\FilterPluginManager::class => FilterPluginManager::class,
],
'factories' => [
FilterPluginManager::class => FilterPluginManagerFactory::class,
],
];
}
}
PK 髏P src/ToFloat.phpnu W+A $provider->getDependencyConfig(),
];
}
/**
* Register a specification for the FilterManager with the ServiceListener.
*
* @param \Laminas\ModuleManager\ModuleManager $moduleManager
* @return void
*/
public function init($moduleManager)
{
$event = $moduleManager->getEvent();
$container = $event->getParam('ServiceManager');
$serviceListener = $container->get('ServiceListener');
$serviceListener->addServiceManager(
'FilterManager',
'filters',
FilterProviderInterface::class,
'getFilterConfig'
);
}
}
PK 髏Pr_E E
mkdocs.ymlnu W+A docs_dir: docs/book
site_dir: docs/html
nav:
- Home: index.md
- Introduction: intro.md
- Reference:
- 'Standard Filters': standard-filters.md
- 'Word Filters': word.md
- 'File Filters': file.md
- 'Filter Chains': filter-chains.md
- 'String Inflection': inflector.md
- 'Static Filter': static-filter.md
- 'Writing Filters': writing-filters.md
site_name: laminas-filter
site_description: "Programmatically filter and normalize data and files."
repo_url: 'https://github.com/laminas/laminas-filter'
extra:
project: Components
PK 髏P;bJ J .github/workflows/docs-build.ymlnu W+A name: docs-build
on:
push:
branches:
- master
repository_dispatch:
types: docs-build
jobs:
build-deploy:
runs-on: ubuntu-latest
steps:
- name: Build Docs
uses: laminas/documentation-theme/github-actions/docs@master
env:
DOCS_DEPLOY_KEY: ${{ secrets.DOCS_DEPLOY_KEY }}
PK 髏PRa .gitattributesnu W+A /.coveralls.yml export-ignore
/.gitattributes export-ignore
/.github/ export-ignore
/.gitignore export-ignore
/.travis.yml export-ignore
/docs/ export-ignore
/mkdocs.yml export-ignore
/phpcs.xml export-ignore
/phpunit.xml.dist export-ignore
/test/ export-ignore
PK 髏Pi
test/DataUnitFormatterTest.phpnu W+A DataUnitFormatterFilter::MODE_DECIMAL,
'unit' => 'B'
]);
$this->assertEquals($expected, $filter->filter($value));
}
/**
* @param float $value
* @param string $expected
* @dataProvider binaryBytesTestProvider
*/
public function testBinaryBytes($value, $expected)
{
$filter = new DataUnitFormatterFilter([
'mode' => DataUnitFormatterFilter::MODE_BINARY,
'unit' => 'B'
]);
$this->assertEquals($expected, $filter->filter($value));
}
public function testPrecision()
{
$filter = new DataUnitFormatterFilter([
'unit' => 'B',
'precision' => 3,
]);
$this->assertEquals('1.500 kB', $filter->filter(1500));
}
public function testCustomPrefixes()
{
$filter = new DataUnitFormatterFilter([
'unit' => 'B',
'prefixes' => ['', 'kilos'],
]);
$this->assertEquals('1.50 kilosB', $filter->filter(1500));
}
public function testSettingNoOptions()
{
$this->expectException(Exception\InvalidArgumentException::class);
$filter = new DataUnitFormatterFilter();
}
public function testSettingNoUnit()
{
$this->expectException(Exception\InvalidArgumentException::class);
$filter = new DataUnitFormatterFilter([]);
}
public function testSettingFalseMode()
{
$this->expectException(Exception\InvalidArgumentException::class);
$filter = new DataUnitFormatterFilter([
'unit' => 'B',
'mode' => 'invalid',
]);
}
public static function decimalBytesTestProvider()
{
return [
[0, '0 B'],
[1, '1.00 B'],
[pow(1000, 1), '1.00 kB'],
[pow(1500, 1), '1.50 kB'],
[pow(1000, 2), '1.00 MB'],
[pow(1000, 3), '1.00 GB'],
[pow(1000, 4), '1.00 TB'],
[pow(1000, 5), '1.00 PB'],
[pow(1000, 6), '1.00 EB'],
[pow(1000, 7), '1.00 ZB'],
[pow(1000, 8), '1.00 YB'],
[pow(1000, 9), (pow(1000, 9) . ' B')],
];
}
public static function binaryBytesTestProvider()
{
return [
[0, '0 B'],
[1, '1.00 B'],
[pow(1024, 1), '1.00 KiB'],
[pow(1536, 1), '1.50 KiB'],
[pow(1024, 2), '1.00 MiB'],
[pow(1024, 3), '1.00 GiB'],
[pow(1024, 4), '1.00 TiB'],
[pow(1024, 5), '1.00 PiB'],
[pow(1024, 6), '1.00 EiB'],
[pow(1024, 7), '1.00 ZiB'],
[pow(1024, 8), '1.00 YiB'],
[pow(1024, 9), (pow(1024, 9) . ' B')],
];
}
}
PK 髏P;h^K test/CompressTest.phpnu W+A markTestSkipped('This filter is tested with the bz2 extension');
}
$this->tmpDir = sprintf('%s/%s', sys_get_temp_dir(), uniqid('laminasilter'));
mkdir($this->tmpDir, 0775, true);
}
public function tearDown()
{
if (is_dir($this->tmpDir)) {
if (file_exists($this->tmpDir . '/compressed.bz2')) {
unlink($this->tmpDir . '/compressed.bz2');
}
rmdir($this->tmpDir);
}
}
/**
* Basic usage
*
* @return void
*/
public function testBasicUsage()
{
$filter = new CompressFilter('bz2');
$text = 'compress me';
$compressed = $filter($text);
$this->assertNotEquals($text, $compressed);
$decompressed = $filter->decompress($compressed);
$this->assertEquals($text, $decompressed);
}
/**
* Setting Options
*
* @return void
*/
public function testGetSetAdapterOptionsInConstructor()
{
$filter = new CompressFilter([
'adapter' => 'bz2',
'options' => [
'blocksize' => 6,
'archive' => 'test.txt',
]
]);
$this->assertEquals(
['blocksize' => 6, 'archive' => 'test.txt'],
$filter->getAdapterOptions()
);
$adapter = $filter->getAdapter();
$this->assertEquals(6, $adapter->getBlocksize());
$this->assertEquals('test.txt', $adapter->getArchive());
}
/**
* Setting Options through constructor
*
* @return void
*/
public function testGetSetAdapterOptions()
{
$filter = new CompressFilter('bz2');
$filter->setAdapterOptions([
'blocksize' => 6,
'archive' => 'test.txt',
]);
$this->assertEquals(
['blocksize' => 6, 'archive' => 'test.txt'],
$filter->getAdapterOptions()
);
$adapter = $filter->getAdapter();
$this->assertEquals(6, $adapter->getBlocksize());
$this->assertEquals('test.txt', $adapter->getArchive());
}
/**
* Setting Blocksize
*
* @return void
*/
public function testGetSetBlocksize()
{
$filter = new CompressFilter('bz2');
$this->assertEquals(4, $filter->getBlocksize());
$filter->setBlocksize(6);
$this->assertEquals(6, $filter->getOptions('blocksize'));
$this->expectException(Exception\InvalidArgumentException::class);
$this->expectExceptionMessage('must be between');
$filter->setBlocksize(15);
}
/**
* Setting Archive
*
* @return void
*/
public function testGetSetArchive()
{
$filter = new CompressFilter('bz2');
$this->assertEquals(null, $filter->getArchive());
$filter->setArchive('Testfile.txt');
$this->assertEquals('Testfile.txt', $filter->getArchive());
$this->assertEquals('Testfile.txt', $filter->getOptions('archive'));
}
/**
* Setting Archive
*
* @return void
*/
public function testCompressToFile()
{
$filter = new CompressFilter('bz2');
$archive = $this->tmpDir . '/compressed.bz2';
$filter->setArchive($archive);
$content = $filter('compress me');
$this->assertTrue($content);
$filter2 = new CompressFilter('bz2');
$content2 = $filter2->decompress($archive);
$this->assertEquals('compress me', $content2);
$filter3 = new CompressFilter('bz2');
$filter3->setArchive($archive);
$content3 = $filter3->decompress(null);
$this->assertEquals('compress me', $content3);
}
/**
* testing toString
*
* @return void
*/
public function testToString()
{
$filter = new CompressFilter('bz2');
$this->assertEquals('Bz2', $filter->toString());
}
/**
* testing getAdapter
*
* @return void
*/
public function testGetAdapter()
{
$filter = new CompressFilter('bz2');
$adapter = $filter->getAdapter();
$this->assertInstanceOf('Laminas\Filter\Compress\CompressionAlgorithmInterface', $adapter);
$this->assertEquals('Bz2', $filter->getAdapterName());
}
/**
* Setting Adapter
*
* @return void
*/
public function testSetAdapter()
{
if (! extension_loaded('zlib')) {
$this->markTestSkipped('This filter is tested with the zlib extension');
}
$filter = new CompressFilter();
$this->assertEquals('Gz', $filter->getAdapterName());
$filter->setAdapter('\Laminas\Filter\Boolean');
$this->expectException(Exception\InvalidArgumentException::class);
$this->expectExceptionMessage('does not implement');
$adapter = $filter->getAdapter();
}
/**
* Decompress archiv
*
* @return void
*/
public function testDecompressArchive()
{
$filter = new CompressFilter('bz2');
$archive = $this->tmpDir . '/compressed.bz2';
$filter->setArchive($archive);
$content = $filter('compress me');
$this->assertTrue($content);
$filter2 = new CompressFilter('bz2');
$content2 = $filter2->decompress($archive);
$this->assertEquals('compress me', $content2);
}
/**
* Setting invalid method
*
* @return void
*/
public function testInvalidMethod()
{
$filter = new CompressFilter();
$this->expectException(Exception\BadMethodCallException::class);
$this->expectExceptionMessage('Unknown method');
$filter->invalidMethod();
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
[[
'compress me',
'compress me too, please'
]]
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$filter = new CompressFilter('bz2');
$this->assertEquals($input, $filter($input));
}
}
PK 髏P1G
test/DecompressTest.phpnu W+A markTestSkipped('This filter is tested with the bz2 extension');
}
$this->tmpDir = sprintf('%s/%s', sys_get_temp_dir(), uniqid('laminasilter'));
mkdir($this->tmpDir, 0775, true);
}
public function tearDown()
{
if (is_dir($this->tmpDir)) {
if (file_exists($this->tmpDir . '/compressed.bz2')) {
unlink($this->tmpDir . '/compressed.bz2');
}
rmdir($this->tmpDir);
}
}
/**
* Basic usage
*
* @return void
*/
public function testBasicUsage()
{
$filter = new DecompressFilter('bz2');
$text = 'compress me';
$compressed = $filter->compress($text);
$this->assertNotEquals($text, $compressed);
$decompressed = $filter($compressed);
$this->assertEquals($text, $decompressed);
}
/**
* Setting Archive
*
* @return void
*/
public function testCompressToFile()
{
$filter = new DecompressFilter('bz2');
$archive = $this->tmpDir . '/compressed.bz2';
$filter->setArchive($archive);
$content = $filter->compress('compress me');
$this->assertTrue($content);
$filter2 = new DecompressFilter('bz2');
$content2 = $filter2($archive);
$this->assertEquals('compress me', $content2);
$filter3 = new DecompressFilter('bz2');
$filter3->setArchive($archive);
$content3 = $filter3(null);
$this->assertEquals('compress me', $content3);
}
/**
* Basic usage
*
* @return void
*/
public function testDecompressArchive()
{
$filter = new DecompressFilter('bz2');
$archive = $this->tmpDir . '/compressed.bz2';
$filter->setArchive($archive);
$content = $filter->compress('compress me');
$this->assertTrue($content);
$filter2 = new DecompressFilter('bz2');
$content2 = $filter2($archive);
$this->assertEquals('compress me', $content2);
}
public function testFilterMethodProxiesToDecompress()
{
$filter = new DecompressFilter('bz2');
$archive = $this->tmpDir . '/compressed.bz2';
$filter->setArchive($archive);
$content = $filter->compress('compress me');
$this->assertTrue($content);
$filter2 = new DecompressFilter('bz2');
$content2 = $filter2->filter($archive);
$this->assertEquals('compress me', $content2);
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
[[
'decompress me',
'decompress me too, please'
]]
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$filter = new DecompressFilter('bz2');
$this->assertEquals($input, $filter($input));
}
}
PK 髏P)$U, test/MonthSelectTest.phpnu W+A setOptions($options);
$this->assertEquals($expected, $sut->filter($input));
}
public function provideFilter()
{
return [
[[], ['year' => '2014', 'month' => '10'], '2014-10'],
[['nullOnEmpty' => true], ['year' => null, 'month' => '10'], null],
[['null_on_empty' => true], ['year' => null, 'month' => '10'], null],
[['nullOnAllEmpty' => true], ['year' => null, 'month' => null], null],
[['null_on_all_empty' => true], ['year' => null, 'month' => null], null],
];
}
/**
* @expectedException \Laminas\Filter\Exception\RuntimeException
*/
public function testInvalidInput()
{
$sut = new MonthSelectFilter();
$sut->filter(['year' => '2120']);
}
}
PK 髏P>YPN N ' test/FilterPluginManagerFactoryTest.phpnu W+A prophesize(ContainerInterface::class)->reveal();
$factory = new FilterPluginManagerFactory();
$filters = $factory($container, FilterPluginManagerFactory::class);
$this->assertInstanceOf(FilterPluginManager::class, $filters);
if (method_exists($filters, 'configure')) {
// laminas-servicemanager v3
$this->assertAttributeSame($container, 'creationContext', $filters);
} else {
// laminas-servicemanager v2
$this->assertSame($container, $filters->getServiceLocator());
}
}
/**
* @depends testFactoryReturnsPluginManager
*/
public function testFactoryConfiguresPluginManagerUnderContainerInterop()
{
$container = $this->prophesize(ContainerInterface::class)->reveal();
$filter = function ($value) {
return $value;
};
$factory = new FilterPluginManagerFactory();
$filters = $factory($container, FilterPluginManagerFactory::class, [
'services' => [
'test' => $filter,
],
]);
$this->assertSame($filter, $filters->get('test'));
}
/**
* @depends testFactoryReturnsPluginManager
*/
public function testFactoryConfiguresPluginManagerUnderServiceManagerV2()
{
$container = $this->prophesize(ServiceLocatorInterface::class);
$container->willImplement(ContainerInterface::class);
$filter = function ($value) {
return $value;
};
$factory = new FilterPluginManagerFactory();
$factory->setCreationOptions([
'services' => [
'test' => $filter,
],
]);
$filters = $factory->createService($container->reveal());
$this->assertSame($filter, $filters->get('test'));
}
public function testConfiguresFilterServicesWhenFound()
{
$filter = $this->prophesize(FilterInterface::class)->reveal();
$config = [
'filters' => [
'aliases' => [
'test' => Boolean::class,
],
'factories' => [
'test-too' => function ($container) use ($filter) {
return $filter;
},
],
],
];
$container = $this->prophesize(ServiceLocatorInterface::class);
$container->willImplement(ContainerInterface::class);
$container->has('ServiceListener')->willReturn(false);
$container->has('config')->willReturn(true);
$container->get('config')->willReturn($config);
$factory = new FilterPluginManagerFactory();
$filters = $factory($container->reveal(), 'FilterManager');
$this->assertInstanceOf(FilterPluginManager::class, $filters);
$this->assertTrue($filters->has('test'));
$this->assertInstanceOf(Boolean::class, $filters->get('test'));
$this->assertTrue($filters->has('test-too'));
$this->assertSame($filter, $filters->get('test-too'));
}
public function testDoesNotConfigureFilterServicesWhenServiceListenerPresent()
{
$filter = $this->prophesize(FilterInterface::class)->reveal();
$config = [
'filters' => [
'aliases' => [
'test' => Boolean::class,
],
'factories' => [
'test-too' => function ($container) use ($filter) {
return $filter;
},
],
],
];
$container = $this->prophesize(ServiceLocatorInterface::class);
$container->willImplement(ContainerInterface::class);
$container->has('ServiceListener')->willReturn(true);
$container->has('config')->shouldNotBeCalled();
$container->get('config')->shouldNotBeCalled();
$factory = new FilterPluginManagerFactory();
$filters = $factory($container->reveal(), 'FilterManager');
$this->assertInstanceOf(FilterPluginManager::class, $filters);
$this->assertFalse($filters->has('test'));
$this->assertFalse($filters->has('test-too'));
}
public function testDoesNotConfigureFilterServicesWhenConfigServiceNotPresent()
{
$container = $this->prophesize(ServiceLocatorInterface::class);
$container->willImplement(ContainerInterface::class);
$container->has('ServiceListener')->willReturn(false);
$container->has('config')->willReturn(false);
$container->get('config')->shouldNotBeCalled();
$factory = new FilterPluginManagerFactory();
$filters = $factory($container->reveal(), 'FilterManager');
$this->assertInstanceOf(FilterPluginManager::class, $filters);
}
public function testDoesNotConfigureFilterServicesWhenConfigServiceDoesNotContainFiltersConfig()
{
$container = $this->prophesize(ServiceLocatorInterface::class);
$container->willImplement(ContainerInterface::class);
$container->has('ServiceListener')->willReturn(false);
$container->has('config')->willReturn(true);
$container->get('config')->willReturn(['foo' => 'bar']);
$factory = new FilterPluginManagerFactory();
$filters = $factory($container->reveal(), 'FilterManager');
$this->assertInstanceOf(FilterPluginManager::class, $filters);
$this->assertFalse($filters->has('foo'));
}
}
PK 髏Pa a test/BaseNameTest.phpnu W+A 'filename',
'/path/to/filename.ext' => 'filename.ext'
];
foreach ($valuesExpected as $input => $output) {
$this->assertEquals($output, $filter($input));
}
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
[[
'/path/to/filename',
'/path/to/filename.ext'
]]
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$filter = new BaseNameFilter();
$this->assertEquals($input, $filter($input));
}
}
PK 髏Pn% test/TestAsset/LowerCase.phpnu W+A 0,
'1' => 1,
'-1' => -1,
'1.1' => 1,
'-1.1' => -1,
'0.9' => 0,
'-0.9' => 0
];
foreach ($valuesExpected as $input => $output) {
$this->assertEquals($output, $filter($input));
}
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
[[
'1',
-1
]]
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$filter = new ToIntFilter();
$this->assertEquals($input, $filter($input));
}
}
PK 髏Pܚׇ - test/FilterPluginManagerCompatibilityTest.phpnu W+A getPluginManager();
$r = new ReflectionProperty($pluginManager, 'aliases');
$r->setAccessible(true);
$aliases = $r->getValue($pluginManager);
foreach ($aliases as $alias => $target) {
// Skipping as laminas-i18n is not required by this package
if (strpos($target, '\\I18n\\')) {
continue;
}
// Skipping as it has required options
if (strpos($target, 'DataUnitFormatter')) {
continue;
}
yield $alias => [$alias, $target];
}
}
}
PK 髏P9& & test/DigitsTest.phpnu W+A '123',
'C 4.5B 6' => '456',
'9壱8@7.6,5#4' => '987654',
'789' => '789'
];
} else {
// POSIX named classes are not supported, use alternative 0-9 match
// Or filter for the value without mbstring
$valuesExpected = [
'abc123' => '123',
'abc 123' => '123',
'abcxyz' => '',
'AZ@#4.3' => '43',
'1.23' => '123',
'0x9f' => '09'
];
}
foreach ($valuesExpected as $input => $output) {
$this->assertEquals(
$output,
$result = $filter($input),
"Expected '$input' to filter to '$output', but received '$result' instead"
);
}
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
[[
'abc123',
'abc 123'
]],
[true],
[false],
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$filter = new DigitsFilter();
$this->assertSame($input, $filter($input));
}
}
PK 髏Pn-: : test/DecryptTest.phpnu W+A markTestSkipped('This filter needs the mcrypt or openssl extension');
}
}
/**
* Ensures that the filter follows expected behavior
*
* @return void
*/
public function testBasicMcrypt()
{
$filter = new DecryptFilter(['adapter' => 'BlockCipher']);
$valuesExpected = [
'STRING' => 'STRING',
'ABC1@3' => 'ABC1@3',
'A b C' => 'A B C'
];
$enc = $filter->getEncryption();
$filter->setKey('1234567890123456');
foreach ($valuesExpected as $input => $output) {
$this->assertNotEquals($output, $filter($input));
}
}
/**
* Ensures that the encryption works fine
*/
public function testDecryptBlockCipher()
{
$decrypt = new DecryptFilter(['adapter' => 'BlockCipher', 'key' => 'testkey']);
$decrypt->setVector('1234567890123456890');
// @codingStandardsIgnoreStart
$decrypted = $decrypt->filter('ec133eb7460682b0020b736ad6d2ef14c35de0f1e5976330ae1dd096ef3b4cb7MTIzNDU2Nzg5MDEyMzQ1NoZvxY1JkeL6TnQP3ug5F0k=');
// @codingStandardsIgnoreEnd
$this->assertEquals($decrypted, 'test');
}
/**
* Ensures that the filter follows expected behavior
*
* @return void
*/
public function testBasicOpenssl()
{
if (! extension_loaded('openssl')) {
$this->markTestSkipped('Openssl extension not installed');
}
$filter = new DecryptFilter(['adapter' => 'Openssl']);
$filter->setPassphrase('zPUp9mCzIrM7xQOEnPJZiDkBwPBV9UlITY0Xd3v4bfIwzJ12yPQCAkcR5BsePGVw
RK6GS5RwXSLrJu9Qj8+fk0wPj6IPY5HvA9Dgwh+dptPlXppeBm3JZJ+92l0DqR2M
ccL43V3Z4JN9OXRAfGWXyrBJNmwURkq7a2EyFElBBWK03OLYVMevQyRJcMKY0ai+
tmnFUSkH2zwnkXQfPUxg9aV7TmGQv/3TkK1SziyDyNm7GwtyIlfcigCCRz3uc77U
Izcez5wgmkpNElg/D7/VCd9E+grTfPYNmuTVccGOes+n8ISJJdW0vYX1xwWv5l
bK22CwD/l7SMBOz4M9XH0Jb0OhNxLza4XMDu0ANMIpnkn1KOcmQ4gB8fmAbBt');
$filter->setPrivateKey(__DIR__ . '/_files/privatekey.pem');
$key = $filter->getPrivateKey();
$this->assertEquals(
[__DIR__ . '/_files/privatekey.pem' =>
'-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDKTIp7FntJt1BioBZ0lmWBE8CyzngeGCHNMcAC4JLbi1Y0LwT4
CSaQarbvAqBRmc+joHX+rcURm89wOibRaThrrZcvgl2pomzu7shJc0ObiRZC8H7p
xTkZ1HHjN8cRSQlOHkcdtE9yoiSGSO+zZ9K5ReU1DOsFFDD4V7XpcNU63QIDAQAB
AoGBALr0XY4/SpTnmpxqwhXg39GYBZ+5e/yj5KkTbxW5oT7P2EzFn1vyaPdSB9l+
ndaLxP68zg8dXGBXlC9tLm6dRQtocGupUPB1HOEQbUIlQdiKF/W7/8w6uzLNXdid
qCSLrSJ4cfkYKtS29Xi6qooRw2DOvUFngXy/ELtmTeiBcihpAkEA8+oUesTET+TO
IYM0+l5JrTOpCPZt+aY4JPmWoKz9bshJT/DP2KPgmqd8/Vy+i23yIfOwUxbpwbna
aKzNPi/uywJBANRSl7RNL7jh1BJRQC7+mvUVTE8iQwbyGtIipcLC7bxwhNQzuPKS
P4o/a1+HEVB9Nv1Em7DqKTwBnlkJvaFZ3/cCQQCcvx0SGEkgHqXpG2x8SQOH7t7+
B399I7iI6mxGLWVgQA389YBcdFPujxvfpi49ZBZqgzQY8WyfNlSJWCM9h4gpAkAu
qxzHN7QGmjSn9g36hmH+/rhwKGK9MxfsGkt+/KOOqNi5X8kGIFkxBPGP5LtMisk8
cAkcoMuBcgWhIn/46C1PAkEAzLK/ibrdMQLOdO4SuDgj/2nc53NZ3agl61ew8Os6
d/fxzPfuO/bLpADozTAnYT9Hu3wPrQVLeAfCp0ojqH7DYg==
-----END RSA PRIVATE KEY-----
'],
$key
);
}
/**
* @return void
*/
public function testSettingAdapterManually()
{
if (! extension_loaded('openssl')) {
$this->markTestSkipped('Openssl extension not installed');
}
$filter = new DecryptFilter();
$filter->setAdapter('Openssl');
$this->assertEquals('Openssl', $filter->getAdapter());
$this->assertInstanceOf('Laminas\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance());
$filter->setAdapter('BlockCipher');
$this->assertEquals('BlockCipher', $filter->getAdapter());
$this->assertInstanceOf('Laminas\Filter\Encrypt\EncryptionAlgorithmInterface', $filter->getAdapterInstance());
$this->expectException(Exception\InvalidArgumentException::class);
$this->expectExceptionMessage('does not implement');
$filter->setAdapter('\stdClass');
}
/**
* @return void
*/
public function testCallingUnknownMethod()
{
$this->expectException(Exception\BadMethodCallException::class);
$this->expectExceptionMessage('Unknown method');
$filter = new DecryptFilter();
$filter->getUnknownMethod();
}
public function returnUnfilteredDataProvider()
{
return [
[null],
[new \stdClass()],
// @codingStandardsIgnoreStart
[[
'ec133eb7460682b0020b736ad6d2ef14c35de0f1e5976330ae1dd096ef3b4cb7MTIzNDU2Nzg5MDEyMzQ1NoZvxY1JkeL6TnQP3ug5F0k=',
'decrypt me too, please'
]]
// @codingStandardsIgnoreEnd
];
}
/**
* @dataProvider returnUnfilteredDataProvider
* @return void
*/
public function testReturnUnfiltered($input)
{
$decrypt = new DecryptFilter(['adapter' => 'BlockCipher', 'key' => 'testkey']);
$decrypt->setVector('1234567890123456890');
$decrypted = $decrypt->filter($input);
$this->assertEquals($input, $decrypted);
}
}
PK 髏P<* * ' test/Word/CamelCaseToUnderscoreTest.phpnu W+A assertNotEquals($string, $filtered);
$this->assertEquals('Camel_Cased_Words', $filtered);
}
public function testFilterSeperatingNumbersToUnterscore()
{
$string = 'PaTitle';
$filter = new CamelCaseToUnderscoreFilter();
$filtered = $filter($string);
$this->assertNotEquals($string, $filtered);
$this->assertEquals('Pa_Title', $filtered);
$string = 'Pa2Title';
$filter = new CamelCaseToUnderscoreFilter();
$filtered = $filter($string);
$this->assertNotEquals($string, $filtered);
$this->assertEquals('Pa2_Title', $filtered);
$string = 'Pa2aTitle';
$filter = new CamelCaseToUnderscoreFilter();
$filtered = $filter($string);
$this->assertNotEquals($string, $filtered);
$this->assertEquals('Pa2a_Title', $filtered);
}
}
PK 髏P
! test/Word/CamelCaseToDashTest.phpnu W+A assertNotEquals($string, $filtered);
$this->assertEquals('Camel-Cased-Words', $filtered);
}
}
PK 髏Pﺆ &