diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/autoload.php b/modules/addons/NFEioServiceInvoices/lib/vendor/autoload.php new file mode 100644 index 0000000..67095af --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/autoload.php @@ -0,0 +1,7 @@ + $stream, callable $callback, int $read_write = STREAM_FILTER_ALL): resource` function can be used to +append a filter callback to the given stream. + +Each stream can have a list of filters attached. +This function appends a filter to the end of this list. + +If the given filter can not be added, it throws an `Exception`. + +The `$stream` can be any valid stream resource, such as: + +```php +$stream = fopen('demo.txt', 'w+'); +``` + +The `$callback` should be a valid callable function which accepts +an individual chunk of data and should return the updated chunk: + +```php +$filter = Filter\append($stream, function ($chunk) { + // will be called each time you read or write a $chunk to/from the stream + return $chunk; +}); +``` + +As such, you can also use native PHP functions or any other `callable`: + +```php +Filter\append($stream, 'strtoupper'); + +// will write "HELLO" to the underlying stream +fwrite($stream, 'hello'); +``` + +If the `$callback` accepts invocation without parameters, +then this signature will be invoked once ending (flushing) the filter: + +```php +Filter\append($stream, function ($chunk = null) { + if ($chunk === null) { + // will be called once ending the filter + return 'end'; + } + // will be called each time you read or write a $chunk to/from the stream + return $chunk; +}); + +fclose($stream); +``` + +> Note: Legacy PHP versions (PHP < 5.4) do not support passing additional data +from the end signal handler if the stream is being closed. + +If your callback throws an `Exception`, then the filter process will be aborted. +In order to play nice with PHP's stream handling, +the `Exception` will be transformed to a PHP warning instead: + +```php +Filter\append($stream, function ($chunk) { + throw new \RuntimeException('Unexpected chunk'); +}); + +// raises an E_USER_WARNING with "Error invoking filter: Unexpected chunk" +fwrite($stream, 'hello'); +``` + +The optional `$read_write` parameter can be used to only invoke the `$callback` +when either writing to the stream or only when reading from the stream: + +```php +Filter\append($stream, function ($chunk) { + // will be called each time you write to the stream + return $chunk; +}, STREAM_FILTER_WRITE); + +Filter\append($stream, function ($chunk) { + // will be called each time you read from the stream + return $chunk; +}, STREAM_FILTER_READ); +``` + +This function returns a filter resource which can be passed to [`remove()`](#remove). + +> Note that once a filter has been added to stream, the stream can no longer be passed to +> [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) +> (and family). +> +> > Warning: stream_select(): cannot cast a filtered stream on this system in {file} on line {line} +> +> This is due to limitations of PHP's stream filter support, as it can no longer reliably +> tell when the underlying stream resource is actually ready. +> As an alternative, consider calling `stream_select()` on the unfiltered stream and +> then pass the unfiltered data through the [`fun()`](#fun) function. + +### prepend() + +The `prepend(resource $stream, callable $callback, int $read_write = STREAM_FILTER_ALL): resource` function can be used to +prepend a filter callback to the given stream. + +Each stream can have a list of filters attached. +This function prepends a filter to the start of this list. + +If the given filter can not be added, it throws an `Exception`. + +```php +$filter = Filter\prepend($stream, function ($chunk) { + // will be called each time you read or write a $chunk to/from the stream + return $chunk; +}); +``` + +This function returns a filter resource which can be passed to [`remove()`](#remove). + +Except for the position in the list of filters, this function behaves exactly +like the [`append()`](#append) function. +For more details about its behavior, see also the [`append()`](#append) function. + +### fun() + +The `fun(string $filter, mixed $parameters = null): callable` function can be used to +create a filter function which uses the given built-in `$filter`. + +PHP comes with a useful set of [built-in filters](https://www.php.net/manual/en/filters.php). +Using `fun()` makes accessing these as easy as passing an input string to filter +and getting the filtered output string. + +```php +$fun = Filter\fun('string.rot13'); + +assert('grfg' === $fun('test')); +assert('test' === $fun($fun('test')); +``` + +Please note that not all filter functions may be available depending +on installed PHP extensions and the PHP version in use. +In particular, [HHVM](https://hhvm.com/) may not offer the same filter functions +or parameters as Zend PHP. +Accessing an unknown filter function will result in a `RuntimeException`: + +```php +Filter\fun('unknown'); // throws RuntimeException +``` + +Some filters may accept or require additional filter parameters – most +filters do not require filter parameters. +If given, the optional `$parameters` argument will be passed to the +underlying filter handler as-is. +In particular, note how *not passing* this parameter at all differs from +explicitly passing a `null` value (which many filters do not accept). +Please refer to the individual filter definition for more details. +For example, the `string.strip_tags` filter can be invoked like this: + +```php +$fun = Filter\fun('string.strip_tags', ''); + +$ret = $fun('h
i
'); +assert('hi' === $ret); +``` + +Under the hood, this function allocates a temporary memory stream, so it's +recommended to clean up the filter function after use. +Also, some filter functions (in particular the +[zlib compression filters](https://www.php.net/manual/en/filters.compression.php)) +may use internal buffers and may emit a final data chunk on close. +The filter function can be closed by invoking without any arguments: + +```php +$fun = Filter\fun('zlib.deflate'); + +$ret = $fun('hello') . $fun('world') . $fun(); +assert('helloworld' === gzinflate($ret)); +``` + +The filter function must not be used anymore after it has been closed. +Doing so will result in a `RuntimeException`: + +```php +$fun = Filter\fun('string.rot13'); +$fun(); + +$fun('test'); // throws RuntimeException +``` + +> Note: If you're using the zlib compression filters, then you should be wary +about engine inconsistencies between different PHP versions and HHVM. +These inconsistencies exist in the underlying PHP engines and there's little we +can do about this in this library. +[Our test suite](tests/) contains several test cases that exhibit these issues. +If you feel some test case is missing or outdated, we're happy to accept PRs! :) + +### remove() + +The `remove(resource $filter): bool` function can be used to +remove a filter previously added via [`append()`](#append) or [`prepend()`](#prepend). + +```php +$filter = Filter\append($stream, function () { + // … +}); +Filter\remove($filter); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require clue/stream-filter:^1.5 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 7+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. +Older PHP versions may suffer from a number of inconsistencies documented above. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +## License + +This project is released under the permissive [MIT license](LICENSE). + +> Did you know that I offer custom development services and issuing invoices for + sponsorships of releases and for contributions? Contact me (@clue) for details. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/composer.json new file mode 100644 index 0000000..797fb53 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/composer.json @@ -0,0 +1,26 @@ +{ + "name": "clue/stream-filter", + "description": "A simple and modern approach to stream filtering in PHP", + "keywords": ["stream", "callback", "filter", "php_user_filter", "stream_filter_append", "stream_filter_register", "bucket brigade"], + "homepage": "https://github.com/clue/php-stream-filter", + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.36" + }, + "autoload": { + "psr-4": { "Clue\\StreamFilter\\": "src/" }, + "files": [ "src/functions_include.php" ] + }, + "autoload-dev": { + "psr-4": { "Clue\\Tests\\StreamFilter\\": "tests/" } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/CallbackFilter.php b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/CallbackFilter.php new file mode 100644 index 0000000..1ca074b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/CallbackFilter.php @@ -0,0 +1,114 @@ +closed = false; + + if (!\is_callable($this->params)) { + throw new \InvalidArgumentException('No valid callback parameter given to stream_filter_(append|prepend)'); + } + $this->callback = $this->params; + + // callback supports end event if it accepts invocation without arguments + $ref = new \ReflectionFunction($this->callback); + $this->supportsClose = ($ref->getNumberOfRequiredParameters() === 0); + + return true; + } + + public function onClose() + { + $this->closed = true; + + // callback supports closing and is not already closed + if ($this->supportsClose) { + $this->supportsClose = false; + // invoke without argument to signal end and discard resulting buffer + try { + \call_user_func($this->callback); + } catch (\Exception $ignored) { + // this might be called during engine shutdown, so it's not safe + // to raise any errors or exceptions here + // trigger_error('Error closing filter: ' . $ignored->getMessage(), E_USER_WARNING); + } + } + + $this->callback = null; + } + + public function filter($in, $out, &$consumed, $closing) + { + // concatenate whole buffer from input brigade + $data = ''; + while ($bucket = \stream_bucket_make_writeable($in)) { + $consumed += $bucket->datalen; + $data .= $bucket->data; + } + + // skip processing callback that already ended + if ($this->closed) { + return \PSFS_FEED_ME; + } + + // only invoke filter function if buffer is not empty + // this may skip flushing a closing filter + if ($data !== '') { + try { + $data = \call_user_func($this->callback, $data); + } catch (\Exception $e) { + // exception should mark filter as closed + $this->onClose(); + \trigger_error('Error invoking filter: ' . $e->getMessage(), \E_USER_WARNING); + + return \PSFS_ERR_FATAL; + } + } + + // mark filter as closed after processing closing chunk + if ($closing) { + $this->closed = true; + + // callback supports closing and is not already closed + if ($this->supportsClose) { + $this->supportsClose = false; + + // invoke without argument to signal end and append resulting buffer + try { + $data .= \call_user_func($this->callback); + } catch (\Exception $e) { + \trigger_error('Error ending filter: ' . $e->getMessage(), \E_USER_WARNING); + + return \PSFS_ERR_FATAL; + } + } + } + + if ($data !== '') { + // create a new bucket for writing the resulting buffer to the output brigade + // reusing an existing bucket turned out to be bugged in some environments (ancient PHP versions and HHVM) + $bucket = @\stream_bucket_new($this->stream, $data); + + // legacy PHP versions (PHP < 5.4) do not support passing data from the event signal handler + // because closing the stream invalidates the stream and its stream bucket brigade before + // invoking the filter close handler. + if ($bucket !== false) { + \stream_bucket_append($out, $bucket); + } + } + + return \PSFS_PASS_ON; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions.php new file mode 100644 index 0000000..4746d88 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions.php @@ -0,0 +1,327 @@ + Note: Legacy PHP versions (PHP < 5.4) do not support passing additional data + * from the end signal handler if the stream is being closed. + * + * If your callback throws an `Exception`, then the filter process will be aborted. + * In order to play nice with PHP's stream handling, + * the `Exception` will be transformed to a PHP warning instead: + * + * ```php + * Filter\append($stream, function ($chunk) { + * throw new \RuntimeException('Unexpected chunk'); + * }); + * + * // raises an E_USER_WARNING with "Error invoking filter: Unexpected chunk" + * fwrite($stream, 'hello'); + * ``` + * + * The optional `$read_write` parameter can be used to only invoke the `$callback` + * when either writing to the stream or only when reading from the stream: + * + * ```php + * Filter\append($stream, function ($chunk) { + * // will be called each time you write to the stream + * return $chunk; + * }, STREAM_FILTER_WRITE); + * + * Filter\append($stream, function ($chunk) { + * // will be called each time you read from the stream + * return $chunk; + * }, STREAM_FILTER_READ); + * ``` + * + * This function returns a filter resource which can be passed to [`remove()`](#remove). + * + * > Note that once a filter has been added to stream, the stream can no longer be passed to + * > [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) + * > (and family). + * > + * > > Warning: stream_select(): cannot cast a filtered stream on this system in {file} on line {line} + * > + * > This is due to limitations of PHP's stream filter support, as it can no longer reliably + * > tell when the underlying stream resource is actually ready. + * > As an alternative, consider calling `stream_select()` on the unfiltered stream and + * > then pass the unfiltered data through the [`fun()`](#fun) function. + * + * @param resource $stream + * @param callable $callback + * @param int $read_write + * @return resource filter resource which can be used for `remove()` + * @throws \Exception on error + * @uses stream_filter_append() + */ +function append($stream, $callback, $read_write = STREAM_FILTER_ALL) +{ + $ret = @\stream_filter_append($stream, register(), $read_write, $callback); + + // PHP 8 throws above on type errors, older PHP and memory issues can throw here + // @codeCoverageIgnoreStart + if ($ret === false) { + $error = \error_get_last() + array('message' => ''); + throw new \RuntimeException('Unable to append filter: ' . $error['message']); + } + // @codeCoverageIgnoreEnd + + return $ret; +} + +/** + * Prepend a filter callback to the given stream. + * + * Each stream can have a list of filters attached. + * This function prepends a filter to the start of this list. + * + * If the given filter can not be added, it throws an `Exception`. + * + * ```php + * $filter = Filter\prepend($stream, function ($chunk) { + * // will be called each time you read or write a $chunk to/from the stream + * return $chunk; + * }); + * ``` + * + * This function returns a filter resource which can be passed to [`remove()`](#remove). + * + * Except for the position in the list of filters, this function behaves exactly + * like the [`append()`](#append) function. + * For more details about its behavior, see also the [`append()`](#append) function. + * + * @param resource $stream + * @param callable $callback + * @param int $read_write + * @return resource filter resource which can be used for `remove()` + * @throws \Exception on error + * @uses stream_filter_prepend() + */ +function prepend($stream, $callback, $read_write = STREAM_FILTER_ALL) +{ + $ret = @\stream_filter_prepend($stream, register(), $read_write, $callback); + + // PHP 8 throws above on type errors, older PHP and memory issues can throw here + // @codeCoverageIgnoreStart + if ($ret === false) { + $error = \error_get_last() + array('message' => ''); + throw new \RuntimeException('Unable to prepend filter: ' . $error['message']); + } + // @codeCoverageIgnoreEnd + + return $ret; +} + +/** + * Create a filter function which uses the given built-in `$filter`. + * + * PHP comes with a useful set of [built-in filters](https://www.php.net/manual/en/filters.php). + * Using `fun()` makes accessing these as easy as passing an input string to filter + * and getting the filtered output string. + * + * ```php + * $fun = Filter\fun('string.rot13'); + * + * assert('grfg' === $fun('test')); + * assert('test' === $fun($fun('test')); + * ``` + * + * Please note that not all filter functions may be available depending + * on installed PHP extensions and the PHP version in use. + * In particular, [HHVM](https://hhvm.com/) may not offer the same filter functions + * or parameters as Zend PHP. + * Accessing an unknown filter function will result in a `RuntimeException`: + * + * ```php + * Filter\fun('unknown'); // throws RuntimeException + * ``` + * + * Some filters may accept or require additional filter parameters – most + * filters do not require filter parameters. + * If given, the optional `$parameters` argument will be passed to the + * underlying filter handler as-is. + * In particular, note how *not passing* this parameter at all differs from + * explicitly passing a `null` value (which many filters do not accept). + * Please refer to the individual filter definition for more details. + * For example, the `string.strip_tags` filter can be invoked like this: + * + * ```php + * $fun = Filter\fun('string.strip_tags', '
'); + * + * $ret = $fun('h
i
'); + * assert('hi' === $ret); + * ``` + * + * Under the hood, this function allocates a temporary memory stream, so it's + * recommended to clean up the filter function after use. + * Also, some filter functions (in particular the + * [zlib compression filters](https://www.php.net/manual/en/filters.compression.php)) + * may use internal buffers and may emit a final data chunk on close. + * The filter function can be closed by invoking without any arguments: + * + * ```php + * $fun = Filter\fun('zlib.deflate'); + * + * $ret = $fun('hello') . $fun('world') . $fun(); + * assert('helloworld' === gzinflate($ret)); + * ``` + * + * The filter function must not be used anymore after it has been closed. + * Doing so will result in a `RuntimeException`: + * + * ```php + * $fun = Filter\fun('string.rot13'); + * $fun(); + * + * $fun('test'); // throws RuntimeException + * ``` + * + * > Note: If you're using the zlib compression filters, then you should be wary + * about engine inconsistencies between different PHP versions and HHVM. + * These inconsistencies exist in the underlying PHP engines and there's little we + * can do about this in this library. + * [Our test suite](tests/) contains several test cases that exhibit these issues. + * If you feel some test case is missing or outdated, we're happy to accept PRs! :) + * + * @param string $filter built-in filter name. See stream_get_filters() or http://php.net/manual/en/filters.php + * @param mixed $parameters (optional) parameters to pass to the built-in filter as-is + * @return callable a filter callback which can be append()'ed or prepend()'ed + * @throws \RuntimeException on error + * @link http://php.net/manual/en/filters.php + * @see stream_get_filters() + * @see append() + */ +function fun($filter, $parameters = null) +{ + $fp = \fopen('php://memory', 'w'); + if (\func_num_args() === 1) { + $filter = @\stream_filter_append($fp, $filter, \STREAM_FILTER_WRITE); + } else { + $filter = @\stream_filter_append($fp, $filter, \STREAM_FILTER_WRITE, $parameters); + } + + if ($filter === false) { + \fclose($fp); + $error = \error_get_last() + array('message' => ''); + throw new \RuntimeException('Unable to access built-in filter: ' . $error['message']); + } + + // append filter function which buffers internally + $buffer = ''; + append($fp, function ($chunk) use (&$buffer) { + $buffer .= $chunk; + + // always return empty string in order to skip actually writing to stream resource + return ''; + }, \STREAM_FILTER_WRITE); + + $closed = false; + + return function ($chunk = null) use ($fp, $filter, &$buffer, &$closed) { + if ($closed) { + throw new \RuntimeException('Unable to perform operation on closed stream'); + } + if ($chunk === null) { + $closed = true; + $buffer = ''; + \fclose($fp); + return $buffer; + } + // initialize buffer and invoke filters by attempting to write to stream + $buffer = ''; + \fwrite($fp, $chunk); + + // buffer now contains everything the filter function returned + return $buffer; + }; +} + +/** + * Remove a filter previously added via `append()` or `prepend()`. + * + * ```php + * $filter = Filter\append($stream, function () { + * // … + * }); + * Filter\remove($filter); + * ``` + * + * @param resource $filter + * @return bool true on success or false on error + * @throws \RuntimeException on error + * @uses stream_filter_remove() + */ +function remove($filter) +{ + if (@\stream_filter_remove($filter) === false) { + // PHP 8 throws above on type errors, older PHP and memory issues can throw here + $error = \error_get_last(); + throw new \RuntimeException('Unable to remove filter: ' . $error['message']); + } +} + +/** + * Registers the callback filter and returns the resulting filter name + * + * There should be little reason to call this function manually. + * + * @return string filter name + * @uses CallbackFilter + */ +function register() +{ + static $registered = null; + if ($registered === null) { + $registered = 'stream-callback'; + \stream_filter_register($registered, __NAMESPACE__ . '\CallbackFilter'); + } + return $registered; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions_include.php new file mode 100644 index 0000000..4b315ae --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/clue/stream-filter/src/functions_include.php @@ -0,0 +1,6 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var ?string */ + private $vendorDir; + + // PSR-4 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array[] + * @psalm-var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * @var array[] + * @psalm-var array> + */ + private $prefixesPsr0 = array(); + /** + * @var array[] + * @psalm-var array + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var string[] + * @psalm-var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var bool[] + * @psalm-var array + */ + private $missingClasses = array(); + + /** @var ?string */ + private $apcuPrefix; + + /** + * @var self[] + */ + private static $registeredLoaders = array(); + + /** + * @param ?string $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + } + + /** + * @return string[] + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array[] + * @psalm-return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return array[] + * @psalm-return array + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return string[] Array of classname => path + * @psalm-var array + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param string[] $classMap Class to filename map + * @psalm-param array $classMap + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param string[]|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param string[]|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders indexed by their corresponding vendor directories. + * + * @return self[] + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + * @private + */ +function includeFile($file) +{ + include $file; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/InstalledVersions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/InstalledVersions.php new file mode 100644 index 0000000..7c5502c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/InstalledVersions.php @@ -0,0 +1,337 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Autoload\ClassLoader; +use Composer\Semver\VersionParser; + +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + */ +class InstalledVersions +{ + private static $installed; + private static $canGetVendors; + private static $installedByVendor = array(); + + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = array_keys($installed['versions']); + } + + if (1 === \count($packages)) { + return $packages[0]; + } + + return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); + } + + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + + return $packagesByType; + } + + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || empty($installed['versions'][$packageName]['dev_requirement']); + } + } + + return false; + } + + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints($constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + + return $provided->matches($constraint); + } + + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + + return implode(' || ', $ranges); + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + + return $installed['versions'][$packageName]['version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + + return $installed['versions'][$packageName]['pretty_version']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + + return $installed['versions'][$packageName]['reference']; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + + /** + * @return array + * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + + return $installed[0]['root']; + } + + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} + */ + public static function getRawData() + { + @trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', E_USER_DEPRECATED); + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = include __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + + return self::$installed; + } + + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[], dev: bool, install_path: string, type: string}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); + } + + $installed = array(); + + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (is_file($vendorDir.'/composer/installed.php')) { + $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; + if (null === self::$installed && strtr($vendorDir.'/composer', '\\', '/') === strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[count($installed) - 1]; + } + } + } + } + + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (substr(__DIR__, -8, 1) !== 'C') { + self::$installed = require __DIR__ . '/installed.php'; + } else { + self::$installed = array(); + } + } + $installed[] = self::$installed; + + return $installed; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_classmap.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..5d4cd1d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_classmap.php @@ -0,0 +1,274 @@ + $vendorDir . '/clue/stream-filter/src/CallbackFilter.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'Evenement\\EventEmitter' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitter.php', + 'Evenement\\EventEmitterInterface' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitterInterface.php', + 'Evenement\\EventEmitterTrait' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitterTrait.php', + 'GuzzleHttp\\Psr7\\AppendStream' => $vendorDir . '/guzzlehttp/psr7/src/AppendStream.php', + 'GuzzleHttp\\Psr7\\BufferStream' => $vendorDir . '/guzzlehttp/psr7/src/BufferStream.php', + 'GuzzleHttp\\Psr7\\CachingStream' => $vendorDir . '/guzzlehttp/psr7/src/CachingStream.php', + 'GuzzleHttp\\Psr7\\DroppingStream' => $vendorDir . '/guzzlehttp/psr7/src/DroppingStream.php', + 'GuzzleHttp\\Psr7\\FnStream' => $vendorDir . '/guzzlehttp/psr7/src/FnStream.php', + 'GuzzleHttp\\Psr7\\Header' => $vendorDir . '/guzzlehttp/psr7/src/Header.php', + 'GuzzleHttp\\Psr7\\InflateStream' => $vendorDir . '/guzzlehttp/psr7/src/InflateStream.php', + 'GuzzleHttp\\Psr7\\LazyOpenStream' => $vendorDir . '/guzzlehttp/psr7/src/LazyOpenStream.php', + 'GuzzleHttp\\Psr7\\LimitStream' => $vendorDir . '/guzzlehttp/psr7/src/LimitStream.php', + 'GuzzleHttp\\Psr7\\Message' => $vendorDir . '/guzzlehttp/psr7/src/Message.php', + 'GuzzleHttp\\Psr7\\MessageTrait' => $vendorDir . '/guzzlehttp/psr7/src/MessageTrait.php', + 'GuzzleHttp\\Psr7\\MimeType' => $vendorDir . '/guzzlehttp/psr7/src/MimeType.php', + 'GuzzleHttp\\Psr7\\MultipartStream' => $vendorDir . '/guzzlehttp/psr7/src/MultipartStream.php', + 'GuzzleHttp\\Psr7\\NoSeekStream' => $vendorDir . '/guzzlehttp/psr7/src/NoSeekStream.php', + 'GuzzleHttp\\Psr7\\PumpStream' => $vendorDir . '/guzzlehttp/psr7/src/PumpStream.php', + 'GuzzleHttp\\Psr7\\Query' => $vendorDir . '/guzzlehttp/psr7/src/Query.php', + 'GuzzleHttp\\Psr7\\Request' => $vendorDir . '/guzzlehttp/psr7/src/Request.php', + 'GuzzleHttp\\Psr7\\Response' => $vendorDir . '/guzzlehttp/psr7/src/Response.php', + 'GuzzleHttp\\Psr7\\Rfc7230' => $vendorDir . '/guzzlehttp/psr7/src/Rfc7230.php', + 'GuzzleHttp\\Psr7\\ServerRequest' => $vendorDir . '/guzzlehttp/psr7/src/ServerRequest.php', + 'GuzzleHttp\\Psr7\\Stream' => $vendorDir . '/guzzlehttp/psr7/src/Stream.php', + 'GuzzleHttp\\Psr7\\StreamDecoratorTrait' => $vendorDir . '/guzzlehttp/psr7/src/StreamDecoratorTrait.php', + 'GuzzleHttp\\Psr7\\StreamWrapper' => $vendorDir . '/guzzlehttp/psr7/src/StreamWrapper.php', + 'GuzzleHttp\\Psr7\\UploadedFile' => $vendorDir . '/guzzlehttp/psr7/src/UploadedFile.php', + 'GuzzleHttp\\Psr7\\Uri' => $vendorDir . '/guzzlehttp/psr7/src/Uri.php', + 'GuzzleHttp\\Psr7\\UriNormalizer' => $vendorDir . '/guzzlehttp/psr7/src/UriNormalizer.php', + 'GuzzleHttp\\Psr7\\UriResolver' => $vendorDir . '/guzzlehttp/psr7/src/UriResolver.php', + 'GuzzleHttp\\Psr7\\Utils' => $vendorDir . '/guzzlehttp/psr7/src/Utils.php', + 'Http\\Message\\Authentication' => $vendorDir . '/php-http/message/src/Authentication.php', + 'Http\\Message\\Authentication\\AutoBasicAuth' => $vendorDir . '/php-http/message/src/Authentication/AutoBasicAuth.php', + 'Http\\Message\\Authentication\\BasicAuth' => $vendorDir . '/php-http/message/src/Authentication/BasicAuth.php', + 'Http\\Message\\Authentication\\Bearer' => $vendorDir . '/php-http/message/src/Authentication/Bearer.php', + 'Http\\Message\\Authentication\\Chain' => $vendorDir . '/php-http/message/src/Authentication/Chain.php', + 'Http\\Message\\Authentication\\Header' => $vendorDir . '/php-http/message/src/Authentication/Header.php', + 'Http\\Message\\Authentication\\Matching' => $vendorDir . '/php-http/message/src/Authentication/Matching.php', + 'Http\\Message\\Authentication\\QueryParam' => $vendorDir . '/php-http/message/src/Authentication/QueryParam.php', + 'Http\\Message\\Authentication\\RequestConditional' => $vendorDir . '/php-http/message/src/Authentication/RequestConditional.php', + 'Http\\Message\\Authentication\\Wsse' => $vendorDir . '/php-http/message/src/Authentication/Wsse.php', + 'Http\\Message\\Builder\\ResponseBuilder' => $vendorDir . '/php-http/message/src/Builder/ResponseBuilder.php', + 'Http\\Message\\Cookie' => $vendorDir . '/php-http/message/src/Cookie.php', + 'Http\\Message\\CookieJar' => $vendorDir . '/php-http/message/src/CookieJar.php', + 'Http\\Message\\CookieUtil' => $vendorDir . '/php-http/message/src/CookieUtil.php', + 'Http\\Message\\Decorator\\MessageDecorator' => $vendorDir . '/php-http/message/src/Decorator/MessageDecorator.php', + 'Http\\Message\\Decorator\\RequestDecorator' => $vendorDir . '/php-http/message/src/Decorator/RequestDecorator.php', + 'Http\\Message\\Decorator\\ResponseDecorator' => $vendorDir . '/php-http/message/src/Decorator/ResponseDecorator.php', + 'Http\\Message\\Decorator\\StreamDecorator' => $vendorDir . '/php-http/message/src/Decorator/StreamDecorator.php', + 'Http\\Message\\Encoding\\ChunkStream' => $vendorDir . '/php-http/message/src/Encoding/ChunkStream.php', + 'Http\\Message\\Encoding\\CompressStream' => $vendorDir . '/php-http/message/src/Encoding/CompressStream.php', + 'Http\\Message\\Encoding\\DechunkStream' => $vendorDir . '/php-http/message/src/Encoding/DechunkStream.php', + 'Http\\Message\\Encoding\\DecompressStream' => $vendorDir . '/php-http/message/src/Encoding/DecompressStream.php', + 'Http\\Message\\Encoding\\DeflateStream' => $vendorDir . '/php-http/message/src/Encoding/DeflateStream.php', + 'Http\\Message\\Encoding\\Filter\\Chunk' => $vendorDir . '/php-http/message/src/Encoding/Filter/Chunk.php', + 'Http\\Message\\Encoding\\FilteredStream' => $vendorDir . '/php-http/message/src/Encoding/FilteredStream.php', + 'Http\\Message\\Encoding\\GzipDecodeStream' => $vendorDir . '/php-http/message/src/Encoding/GzipDecodeStream.php', + 'Http\\Message\\Encoding\\GzipEncodeStream' => $vendorDir . '/php-http/message/src/Encoding/GzipEncodeStream.php', + 'Http\\Message\\Encoding\\InflateStream' => $vendorDir . '/php-http/message/src/Encoding/InflateStream.php', + 'Http\\Message\\Exception' => $vendorDir . '/php-http/message/src/Exception.php', + 'Http\\Message\\Exception\\UnexpectedValueException' => $vendorDir . '/php-http/message/src/Exception/UnexpectedValueException.php', + 'Http\\Message\\Formatter' => $vendorDir . '/php-http/message/src/Formatter.php', + 'Http\\Message\\Formatter\\CurlCommandFormatter' => $vendorDir . '/php-http/message/src/Formatter/CurlCommandFormatter.php', + 'Http\\Message\\Formatter\\FullHttpMessageFormatter' => $vendorDir . '/php-http/message/src/Formatter/FullHttpMessageFormatter.php', + 'Http\\Message\\Formatter\\SimpleFormatter' => $vendorDir . '/php-http/message/src/Formatter/SimpleFormatter.php', + 'Http\\Message\\MessageFactory' => $vendorDir . '/php-http/message-factory/src/MessageFactory.php', + 'Http\\Message\\MessageFactory\\DiactorosMessageFactory' => $vendorDir . '/php-http/message/src/MessageFactory/DiactorosMessageFactory.php', + 'Http\\Message\\MessageFactory\\GuzzleMessageFactory' => $vendorDir . '/php-http/message/src/MessageFactory/GuzzleMessageFactory.php', + 'Http\\Message\\MessageFactory\\SlimMessageFactory' => $vendorDir . '/php-http/message/src/MessageFactory/SlimMessageFactory.php', + 'Http\\Message\\RequestFactory' => $vendorDir . '/php-http/message-factory/src/RequestFactory.php', + 'Http\\Message\\RequestMatcher' => $vendorDir . '/php-http/message/src/RequestMatcher.php', + 'Http\\Message\\RequestMatcher\\CallbackRequestMatcher' => $vendorDir . '/php-http/message/src/RequestMatcher/CallbackRequestMatcher.php', + 'Http\\Message\\RequestMatcher\\RegexRequestMatcher' => $vendorDir . '/php-http/message/src/RequestMatcher/RegexRequestMatcher.php', + 'Http\\Message\\RequestMatcher\\RequestMatcher' => $vendorDir . '/php-http/message/src/RequestMatcher/RequestMatcher.php', + 'Http\\Message\\ResponseFactory' => $vendorDir . '/php-http/message-factory/src/ResponseFactory.php', + 'Http\\Message\\StreamFactory' => $vendorDir . '/php-http/message-factory/src/StreamFactory.php', + 'Http\\Message\\StreamFactory\\DiactorosStreamFactory' => $vendorDir . '/php-http/message/src/StreamFactory/DiactorosStreamFactory.php', + 'Http\\Message\\StreamFactory\\GuzzleStreamFactory' => $vendorDir . '/php-http/message/src/StreamFactory/GuzzleStreamFactory.php', + 'Http\\Message\\StreamFactory\\SlimStreamFactory' => $vendorDir . '/php-http/message/src/StreamFactory/SlimStreamFactory.php', + 'Http\\Message\\Stream\\BufferedStream' => $vendorDir . '/php-http/message/src/Stream/BufferedStream.php', + 'Http\\Message\\UriFactory' => $vendorDir . '/php-http/message-factory/src/UriFactory.php', + 'Http\\Message\\UriFactory\\DiactorosUriFactory' => $vendorDir . '/php-http/message/src/UriFactory/DiactorosUriFactory.php', + 'Http\\Message\\UriFactory\\GuzzleUriFactory' => $vendorDir . '/php-http/message/src/UriFactory/GuzzleUriFactory.php', + 'Http\\Message\\UriFactory\\SlimUriFactory' => $vendorDir . '/php-http/message/src/UriFactory/SlimUriFactory.php', + 'NFEioServiceInvoices\\Addon' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Addon.php', + 'NFEioServiceInvoices\\Admin\\AdminDispatcher' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Admin/AdminDispatcher.php', + 'NFEioServiceInvoices\\Admin\\Controller' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Admin/Controller.php', + 'NFEioServiceInvoices\\Client\\ClientDispatcher' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Client/ClientDispatcher.php', + 'NFEioServiceInvoices\\Client\\Controller' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Client/Controller.php', + 'NFEioServiceInvoices\\Configuration' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Configuration.php', + 'NFEioServiceInvoices\\CustomFields' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/CustomFields.php', + 'NFEioServiceInvoices\\Helpers\\Versions' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Helpers/Versions.php', + 'NFEioServiceInvoices\\Legacy\\Functions' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Legacy/Functions.php', + 'NFEioServiceInvoices\\Legacy\\Hooks' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Legacy/Hooks.php', + 'NFEioServiceInvoices\\Migrations\\Migrations' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Migrations/Migrations.php', + 'NFEioServiceInvoices\\Models\\ClientConfiguration\\Repository' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Models/ClientConfiguration/Repository.php', + 'NFEioServiceInvoices\\Models\\ModuleConfiguration\\Repository' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Models/ModuleConfiguration/Repository.php', + 'NFEioServiceInvoices\\Models\\ProductCode\\Repository' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Models/ProductCode/Repository.php', + 'NFEioServiceInvoices\\Models\\ServiceInvoices\\Repository' => $baseDir . '/modules/addons/NFEioServiceInvoices/lib/Models/ServiceInvoices/Repository.php', + 'Plasticbrain\\FlashMessages\\FlashMessages' => $vendorDir . '/plasticbrain/php-flash-messages/src/FlashMessages.php', + 'Psr\\Http\\Message\\MessageInterface' => $vendorDir . '/psr/http-message/src/MessageInterface.php', + 'Psr\\Http\\Message\\RequestInterface' => $vendorDir . '/psr/http-message/src/RequestInterface.php', + 'Psr\\Http\\Message\\ResponseInterface' => $vendorDir . '/psr/http-message/src/ResponseInterface.php', + 'Psr\\Http\\Message\\ServerRequestInterface' => $vendorDir . '/psr/http-message/src/ServerRequestInterface.php', + 'Psr\\Http\\Message\\StreamInterface' => $vendorDir . '/psr/http-message/src/StreamInterface.php', + 'Psr\\Http\\Message\\UploadedFileInterface' => $vendorDir . '/psr/http-message/src/UploadedFileInterface.php', + 'Psr\\Http\\Message\\UriInterface' => $vendorDir . '/psr/http-message/src/UriInterface.php', + 'React\\Cache\\ArrayCache' => $vendorDir . '/react/cache/src/ArrayCache.php', + 'React\\Cache\\CacheInterface' => $vendorDir . '/react/cache/src/CacheInterface.php', + 'React\\Dns\\BadServerException' => $vendorDir . '/react/dns/src/BadServerException.php', + 'React\\Dns\\Config\\Config' => $vendorDir . '/react/dns/src/Config/Config.php', + 'React\\Dns\\Config\\HostsFile' => $vendorDir . '/react/dns/src/Config/HostsFile.php', + 'React\\Dns\\Model\\Message' => $vendorDir . '/react/dns/src/Model/Message.php', + 'React\\Dns\\Model\\Record' => $vendorDir . '/react/dns/src/Model/Record.php', + 'React\\Dns\\Protocol\\BinaryDumper' => $vendorDir . '/react/dns/src/Protocol/BinaryDumper.php', + 'React\\Dns\\Protocol\\Parser' => $vendorDir . '/react/dns/src/Protocol/Parser.php', + 'React\\Dns\\Query\\CachingExecutor' => $vendorDir . '/react/dns/src/Query/CachingExecutor.php', + 'React\\Dns\\Query\\CancellationException' => $vendorDir . '/react/dns/src/Query/CancellationException.php', + 'React\\Dns\\Query\\CoopExecutor' => $vendorDir . '/react/dns/src/Query/CoopExecutor.php', + 'React\\Dns\\Query\\ExecutorInterface' => $vendorDir . '/react/dns/src/Query/ExecutorInterface.php', + 'React\\Dns\\Query\\FallbackExecutor' => $vendorDir . '/react/dns/src/Query/FallbackExecutor.php', + 'React\\Dns\\Query\\HostsFileExecutor' => $vendorDir . '/react/dns/src/Query/HostsFileExecutor.php', + 'React\\Dns\\Query\\Query' => $vendorDir . '/react/dns/src/Query/Query.php', + 'React\\Dns\\Query\\RetryExecutor' => $vendorDir . '/react/dns/src/Query/RetryExecutor.php', + 'React\\Dns\\Query\\SelectiveTransportExecutor' => $vendorDir . '/react/dns/src/Query/SelectiveTransportExecutor.php', + 'React\\Dns\\Query\\TcpTransportExecutor' => $vendorDir . '/react/dns/src/Query/TcpTransportExecutor.php', + 'React\\Dns\\Query\\TimeoutException' => $vendorDir . '/react/dns/src/Query/TimeoutException.php', + 'React\\Dns\\Query\\TimeoutExecutor' => $vendorDir . '/react/dns/src/Query/TimeoutExecutor.php', + 'React\\Dns\\Query\\UdpTransportExecutor' => $vendorDir . '/react/dns/src/Query/UdpTransportExecutor.php', + 'React\\Dns\\RecordNotFoundException' => $vendorDir . '/react/dns/src/RecordNotFoundException.php', + 'React\\Dns\\Resolver\\Factory' => $vendorDir . '/react/dns/src/Resolver/Factory.php', + 'React\\Dns\\Resolver\\Resolver' => $vendorDir . '/react/dns/src/Resolver/Resolver.php', + 'React\\Dns\\Resolver\\ResolverInterface' => $vendorDir . '/react/dns/src/Resolver/ResolverInterface.php', + 'React\\EventLoop\\ExtEvLoop' => $vendorDir . '/react/event-loop/src/ExtEvLoop.php', + 'React\\EventLoop\\ExtEventLoop' => $vendorDir . '/react/event-loop/src/ExtEventLoop.php', + 'React\\EventLoop\\ExtLibevLoop' => $vendorDir . '/react/event-loop/src/ExtLibevLoop.php', + 'React\\EventLoop\\ExtLibeventLoop' => $vendorDir . '/react/event-loop/src/ExtLibeventLoop.php', + 'React\\EventLoop\\ExtUvLoop' => $vendorDir . '/react/event-loop/src/ExtUvLoop.php', + 'React\\EventLoop\\Factory' => $vendorDir . '/react/event-loop/src/Factory.php', + 'React\\EventLoop\\Loop' => $vendorDir . '/react/event-loop/src/Loop.php', + 'React\\EventLoop\\LoopInterface' => $vendorDir . '/react/event-loop/src/LoopInterface.php', + 'React\\EventLoop\\SignalsHandler' => $vendorDir . '/react/event-loop/src/SignalsHandler.php', + 'React\\EventLoop\\StreamSelectLoop' => $vendorDir . '/react/event-loop/src/StreamSelectLoop.php', + 'React\\EventLoop\\Tick\\FutureTickQueue' => $vendorDir . '/react/event-loop/src/Tick/FutureTickQueue.php', + 'React\\EventLoop\\TimerInterface' => $vendorDir . '/react/event-loop/src/TimerInterface.php', + 'React\\EventLoop\\Timer\\Timer' => $vendorDir . '/react/event-loop/src/Timer/Timer.php', + 'React\\EventLoop\\Timer\\Timers' => $vendorDir . '/react/event-loop/src/Timer/Timers.php', + 'React\\Http\\Browser' => $vendorDir . '/react/http/src/Browser.php', + 'React\\Http\\Client\\Client' => $vendorDir . '/react/http/src/Client/Client.php', + 'React\\Http\\Client\\Request' => $vendorDir . '/react/http/src/Client/Request.php', + 'React\\Http\\Client\\RequestData' => $vendorDir . '/react/http/src/Client/RequestData.php', + 'React\\Http\\HttpServer' => $vendorDir . '/react/http/src/HttpServer.php', + 'React\\Http\\Io\\BufferedBody' => $vendorDir . '/react/http/src/Io/BufferedBody.php', + 'React\\Http\\Io\\ChunkedDecoder' => $vendorDir . '/react/http/src/Io/ChunkedDecoder.php', + 'React\\Http\\Io\\ChunkedEncoder' => $vendorDir . '/react/http/src/Io/ChunkedEncoder.php', + 'React\\Http\\Io\\CloseProtectionStream' => $vendorDir . '/react/http/src/Io/CloseProtectionStream.php', + 'React\\Http\\Io\\EmptyBodyStream' => $vendorDir . '/react/http/src/Io/EmptyBodyStream.php', + 'React\\Http\\Io\\HttpBodyStream' => $vendorDir . '/react/http/src/Io/HttpBodyStream.php', + 'React\\Http\\Io\\IniUtil' => $vendorDir . '/react/http/src/Io/IniUtil.php', + 'React\\Http\\Io\\LengthLimitedStream' => $vendorDir . '/react/http/src/Io/LengthLimitedStream.php', + 'React\\Http\\Io\\MiddlewareRunner' => $vendorDir . '/react/http/src/Io/MiddlewareRunner.php', + 'React\\Http\\Io\\MultipartParser' => $vendorDir . '/react/http/src/Io/MultipartParser.php', + 'React\\Http\\Io\\PauseBufferStream' => $vendorDir . '/react/http/src/Io/PauseBufferStream.php', + 'React\\Http\\Io\\ReadableBodyStream' => $vendorDir . '/react/http/src/Io/ReadableBodyStream.php', + 'React\\Http\\Io\\RequestHeaderParser' => $vendorDir . '/react/http/src/Io/RequestHeaderParser.php', + 'React\\Http\\Io\\Sender' => $vendorDir . '/react/http/src/Io/Sender.php', + 'React\\Http\\Io\\StreamingServer' => $vendorDir . '/react/http/src/Io/StreamingServer.php', + 'React\\Http\\Io\\Transaction' => $vendorDir . '/react/http/src/Io/Transaction.php', + 'React\\Http\\Io\\UploadedFile' => $vendorDir . '/react/http/src/Io/UploadedFile.php', + 'React\\Http\\Message\\Response' => $vendorDir . '/react/http/src/Message/Response.php', + 'React\\Http\\Message\\ResponseException' => $vendorDir . '/react/http/src/Message/ResponseException.php', + 'React\\Http\\Message\\ServerRequest' => $vendorDir . '/react/http/src/Message/ServerRequest.php', + 'React\\Http\\Middleware\\LimitConcurrentRequestsMiddleware' => $vendorDir . '/react/http/src/Middleware/LimitConcurrentRequestsMiddleware.php', + 'React\\Http\\Middleware\\RequestBodyBufferMiddleware' => $vendorDir . '/react/http/src/Middleware/RequestBodyBufferMiddleware.php', + 'React\\Http\\Middleware\\RequestBodyParserMiddleware' => $vendorDir . '/react/http/src/Middleware/RequestBodyParserMiddleware.php', + 'React\\Http\\Middleware\\StreamingRequestMiddleware' => $vendorDir . '/react/http/src/Middleware/StreamingRequestMiddleware.php', + 'React\\Http\\Server' => $vendorDir . '/react/http/src/Server.php', + 'React\\Promise\\CancellablePromiseInterface' => $vendorDir . '/react/promise/src/CancellablePromiseInterface.php', + 'React\\Promise\\CancellationQueue' => $vendorDir . '/react/promise/src/CancellationQueue.php', + 'React\\Promise\\Deferred' => $vendorDir . '/react/promise/src/Deferred.php', + 'React\\Promise\\Exception\\LengthException' => $vendorDir . '/react/promise/src/Exception/LengthException.php', + 'React\\Promise\\ExtendedPromiseInterface' => $vendorDir . '/react/promise/src/ExtendedPromiseInterface.php', + 'React\\Promise\\FulfilledPromise' => $vendorDir . '/react/promise/src/FulfilledPromise.php', + 'React\\Promise\\LazyPromise' => $vendorDir . '/react/promise/src/LazyPromise.php', + 'React\\Promise\\Promise' => $vendorDir . '/react/promise/src/Promise.php', + 'React\\Promise\\PromiseInterface' => $vendorDir . '/react/promise/src/PromiseInterface.php', + 'React\\Promise\\PromisorInterface' => $vendorDir . '/react/promise/src/PromisorInterface.php', + 'React\\Promise\\RejectedPromise' => $vendorDir . '/react/promise/src/RejectedPromise.php', + 'React\\Promise\\Stream\\UnwrapReadableStream' => $vendorDir . '/react/promise-stream/src/UnwrapReadableStream.php', + 'React\\Promise\\Stream\\UnwrapWritableStream' => $vendorDir . '/react/promise-stream/src/UnwrapWritableStream.php', + 'React\\Promise\\Timer\\TimeoutException' => $vendorDir . '/react/promise-timer/src/TimeoutException.php', + 'React\\Promise\\UnhandledRejectionException' => $vendorDir . '/react/promise/src/UnhandledRejectionException.php', + 'React\\Socket\\Connection' => $vendorDir . '/react/socket/src/Connection.php', + 'React\\Socket\\ConnectionInterface' => $vendorDir . '/react/socket/src/ConnectionInterface.php', + 'React\\Socket\\Connector' => $vendorDir . '/react/socket/src/Connector.php', + 'React\\Socket\\ConnectorInterface' => $vendorDir . '/react/socket/src/ConnectorInterface.php', + 'React\\Socket\\DnsConnector' => $vendorDir . '/react/socket/src/DnsConnector.php', + 'React\\Socket\\FixedUriConnector' => $vendorDir . '/react/socket/src/FixedUriConnector.php', + 'React\\Socket\\HappyEyeBallsConnectionBuilder' => $vendorDir . '/react/socket/src/HappyEyeBallsConnectionBuilder.php', + 'React\\Socket\\HappyEyeBallsConnector' => $vendorDir . '/react/socket/src/HappyEyeBallsConnector.php', + 'React\\Socket\\LimitingServer' => $vendorDir . '/react/socket/src/LimitingServer.php', + 'React\\Socket\\SecureConnector' => $vendorDir . '/react/socket/src/SecureConnector.php', + 'React\\Socket\\SecureServer' => $vendorDir . '/react/socket/src/SecureServer.php', + 'React\\Socket\\Server' => $vendorDir . '/react/socket/src/Server.php', + 'React\\Socket\\ServerInterface' => $vendorDir . '/react/socket/src/ServerInterface.php', + 'React\\Socket\\SocketServer' => $vendorDir . '/react/socket/src/SocketServer.php', + 'React\\Socket\\StreamEncryption' => $vendorDir . '/react/socket/src/StreamEncryption.php', + 'React\\Socket\\TcpConnector' => $vendorDir . '/react/socket/src/TcpConnector.php', + 'React\\Socket\\TcpServer' => $vendorDir . '/react/socket/src/TcpServer.php', + 'React\\Socket\\TimeoutConnector' => $vendorDir . '/react/socket/src/TimeoutConnector.php', + 'React\\Socket\\UnixConnector' => $vendorDir . '/react/socket/src/UnixConnector.php', + 'React\\Socket\\UnixServer' => $vendorDir . '/react/socket/src/UnixServer.php', + 'React\\Stream\\CompositeStream' => $vendorDir . '/react/stream/src/CompositeStream.php', + 'React\\Stream\\DuplexResourceStream' => $vendorDir . '/react/stream/src/DuplexResourceStream.php', + 'React\\Stream\\DuplexStreamInterface' => $vendorDir . '/react/stream/src/DuplexStreamInterface.php', + 'React\\Stream\\ReadableResourceStream' => $vendorDir . '/react/stream/src/ReadableResourceStream.php', + 'React\\Stream\\ReadableStreamInterface' => $vendorDir . '/react/stream/src/ReadableStreamInterface.php', + 'React\\Stream\\ThroughStream' => $vendorDir . '/react/stream/src/ThroughStream.php', + 'React\\Stream\\Util' => $vendorDir . '/react/stream/src/Util.php', + 'React\\Stream\\WritableResourceStream' => $vendorDir . '/react/stream/src/WritableResourceStream.php', + 'React\\Stream\\WritableStreamInterface' => $vendorDir . '/react/stream/src/WritableStreamInterface.php', + 'RingCentral\\Psr7\\AppendStream' => $vendorDir . '/ringcentral/psr7/src/AppendStream.php', + 'RingCentral\\Psr7\\BufferStream' => $vendorDir . '/ringcentral/psr7/src/BufferStream.php', + 'RingCentral\\Psr7\\CachingStream' => $vendorDir . '/ringcentral/psr7/src/CachingStream.php', + 'RingCentral\\Psr7\\DroppingStream' => $vendorDir . '/ringcentral/psr7/src/DroppingStream.php', + 'RingCentral\\Psr7\\FnStream' => $vendorDir . '/ringcentral/psr7/src/FnStream.php', + 'RingCentral\\Psr7\\InflateStream' => $vendorDir . '/ringcentral/psr7/src/InflateStream.php', + 'RingCentral\\Psr7\\LazyOpenStream' => $vendorDir . '/ringcentral/psr7/src/LazyOpenStream.php', + 'RingCentral\\Psr7\\LimitStream' => $vendorDir . '/ringcentral/psr7/src/LimitStream.php', + 'RingCentral\\Psr7\\MessageTrait' => $vendorDir . '/ringcentral/psr7/src/MessageTrait.php', + 'RingCentral\\Psr7\\MultipartStream' => $vendorDir . '/ringcentral/psr7/src/MultipartStream.php', + 'RingCentral\\Psr7\\NoSeekStream' => $vendorDir . '/ringcentral/psr7/src/NoSeekStream.php', + 'RingCentral\\Psr7\\PumpStream' => $vendorDir . '/ringcentral/psr7/src/PumpStream.php', + 'RingCentral\\Psr7\\Request' => $vendorDir . '/ringcentral/psr7/src/Request.php', + 'RingCentral\\Psr7\\Response' => $vendorDir . '/ringcentral/psr7/src/Response.php', + 'RingCentral\\Psr7\\ServerRequest' => $vendorDir . '/ringcentral/psr7/src/ServerRequest.php', + 'RingCentral\\Psr7\\Stream' => $vendorDir . '/ringcentral/psr7/src/Stream.php', + 'RingCentral\\Psr7\\StreamDecoratorTrait' => $vendorDir . '/ringcentral/psr7/src/StreamDecoratorTrait.php', + 'RingCentral\\Psr7\\StreamWrapper' => $vendorDir . '/ringcentral/psr7/src/StreamWrapper.php', + 'RingCentral\\Psr7\\Uri' => $vendorDir . '/ringcentral/psr7/src/Uri.php', + 'WHMCSExpert\\Addon\\Storage' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Addon/Storage.php', + 'WHMCSExpert\\Gateway\\GatewayStorage' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Gateway/GatewayStorage.php', + 'WHMCSExpert\\Helper\\Helper' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Helper/Helper.php', + 'WHMCSExpert\\Template\\Template' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Template/Template.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Exception' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Exception.php', + 'WHMCSExpert\\mtLibs\\MySQL\\PdoWrapper' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/PdoWrapper.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Query' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Query.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Result' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Result.php', + 'WHMCSExpert\\mtLibs\\Smarty' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/Smarty.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Base' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Base.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Codes' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Codes.php', + 'WHMCSExpert\\mtLibs\\exceptions\\SyntaxError' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/SyntaxError.php', + 'WHMCSExpert\\mtLibs\\exceptions\\System' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/System.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Validation' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Validation.php', + 'WHMCSExpert\\mtLibs\\exceptions\\WhmcsAPI' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/WhmcsAPI.php', + 'WHMCSExpert\\mtLibs\\models\\Base' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Base.php', + 'WHMCSExpert\\mtLibs\\models\\Orm' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Orm.php', + 'WHMCSExpert\\mtLibs\\models\\Repository' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Repository.php', + 'WHMCSExpert\\mtLibs\\models\\TableConstructor' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/TableConstructor.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractConfiguration' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractConfiguration.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractController' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractController.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractMainDriver' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractMainDriver.php', + 'WHMCSExpert\\mtLibs\\process\\MainInstance' => $vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/MainInstance.php', +); diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_files.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_files.php new file mode 100644 index 0000000..8e40486 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_files.php @@ -0,0 +1,17 @@ + $vendorDir . '/react/promise/src/functions_include.php', + '9c67151ae59aff4788964ce8eb2a0f43' => $vendorDir . '/clue/stream-filter/src/functions_include.php', + '972fda704d680a3a53c68e34e193cb22' => $vendorDir . '/react/promise-timer/src/functions_include.php', + 'cea474b4340aa9fa53661e887a21a316' => $vendorDir . '/react/promise-stream/src/functions_include.php', + '7b11c4dc42b3b3023073cb14e519683c' => $vendorDir . '/ralouphie/getallheaders/src/getallheaders.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => $vendorDir . '/guzzlehttp/psr7/src/functions_include.php', + 'ebf8799635f67b5d7248946fe2154f4a' => $vendorDir . '/ringcentral/psr7/src/functions_include.php', + '8cff32064859f4559445b89279f3199c' => $vendorDir . '/php-http/message/src/filters.php', +); diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_namespaces.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..f61e7a7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_namespaces.php @@ -0,0 +1,10 @@ + array($vendorDir . '/evenement/evenement/src'), +); diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_psr4.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_psr4.php new file mode 100644 index 0000000..512379c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_psr4.php @@ -0,0 +1,26 @@ + array($vendorDir . '/whmcsexpert/whmcsexpert/src/WHMCSExpert'), + 'RingCentral\\Psr7\\' => array($vendorDir . '/ringcentral/psr7/src'), + 'React\\Stream\\' => array($vendorDir . '/react/stream/src'), + 'React\\Socket\\' => array($vendorDir . '/react/socket/src'), + 'React\\Promise\\Timer\\' => array($vendorDir . '/react/promise-timer/src'), + 'React\\Promise\\Stream\\' => array($vendorDir . '/react/promise-stream/src'), + 'React\\Promise\\' => array($vendorDir . '/react/promise/src'), + 'React\\Http\\' => array($vendorDir . '/react/http/src'), + 'React\\EventLoop\\' => array($vendorDir . '/react/event-loop/src'), + 'React\\Dns\\' => array($vendorDir . '/react/dns/src'), + 'React\\Cache\\' => array($vendorDir . '/react/cache/src'), + 'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src'), + 'Plasticbrain\\FlashMessages\\' => array($vendorDir . '/plasticbrain/php-flash-messages/src'), + 'NFEioServiceInvoices\\' => array($baseDir . '/modules/addons/NFEioServiceInvoices/lib'), + 'Http\\Message\\' => array($vendorDir . '/php-http/message-factory/src', $vendorDir . '/php-http/message/src'), + 'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'), + 'Clue\\StreamFilter\\' => array($vendorDir . '/clue/stream-filter/src'), +); diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_real.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_real.php new file mode 100644 index 0000000..5340eec --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_real.php @@ -0,0 +1,75 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInit86e02c580f8e6930f39d749d3a111004::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInit86e02c580f8e6930f39d749d3a111004::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequire86e02c580f8e6930f39d749d3a111004($fileIdentifier, $file); + } + + return $loader; + } +} + +function composerRequire86e02c580f8e6930f39d749d3a111004($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_static.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_static.php new file mode 100644 index 0000000..8c15d7e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/autoload_static.php @@ -0,0 +1,421 @@ + __DIR__ . '/..' . '/react/promise/src/functions_include.php', + '9c67151ae59aff4788964ce8eb2a0f43' => __DIR__ . '/..' . '/clue/stream-filter/src/functions_include.php', + '972fda704d680a3a53c68e34e193cb22' => __DIR__ . '/..' . '/react/promise-timer/src/functions_include.php', + 'cea474b4340aa9fa53661e887a21a316' => __DIR__ . '/..' . '/react/promise-stream/src/functions_include.php', + '7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php', + 'a0edc8309cc5e1d60e3047b5df6b7052' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/functions_include.php', + 'ebf8799635f67b5d7248946fe2154f4a' => __DIR__ . '/..' . '/ringcentral/psr7/src/functions_include.php', + '8cff32064859f4559445b89279f3199c' => __DIR__ . '/..' . '/php-http/message/src/filters.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'W' => + array ( + 'WHMCSExpert\\' => 12, + ), + 'R' => + array ( + 'RingCentral\\Psr7\\' => 17, + 'React\\Stream\\' => 13, + 'React\\Socket\\' => 13, + 'React\\Promise\\Timer\\' => 20, + 'React\\Promise\\Stream\\' => 21, + 'React\\Promise\\' => 14, + 'React\\Http\\' => 11, + 'React\\EventLoop\\' => 16, + 'React\\Dns\\' => 10, + 'React\\Cache\\' => 12, + ), + 'P' => + array ( + 'Psr\\Http\\Message\\' => 17, + 'Plasticbrain\\FlashMessages\\' => 27, + ), + 'N' => + array ( + 'NFEioServiceInvoices\\' => 21, + ), + 'H' => + array ( + 'Http\\Message\\' => 13, + ), + 'G' => + array ( + 'GuzzleHttp\\Psr7\\' => 16, + ), + 'C' => + array ( + 'Clue\\StreamFilter\\' => 18, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'WHMCSExpert\\' => + array ( + 0 => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert', + ), + 'RingCentral\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/ringcentral/psr7/src', + ), + 'React\\Stream\\' => + array ( + 0 => __DIR__ . '/..' . '/react/stream/src', + ), + 'React\\Socket\\' => + array ( + 0 => __DIR__ . '/..' . '/react/socket/src', + ), + 'React\\Promise\\Timer\\' => + array ( + 0 => __DIR__ . '/..' . '/react/promise-timer/src', + ), + 'React\\Promise\\Stream\\' => + array ( + 0 => __DIR__ . '/..' . '/react/promise-stream/src', + ), + 'React\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/react/promise/src', + ), + 'React\\Http\\' => + array ( + 0 => __DIR__ . '/..' . '/react/http/src', + ), + 'React\\EventLoop\\' => + array ( + 0 => __DIR__ . '/..' . '/react/event-loop/src', + ), + 'React\\Dns\\' => + array ( + 0 => __DIR__ . '/..' . '/react/dns/src', + ), + 'React\\Cache\\' => + array ( + 0 => __DIR__ . '/..' . '/react/cache/src', + ), + 'Psr\\Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/http-message/src', + ), + 'Plasticbrain\\FlashMessages\\' => + array ( + 0 => __DIR__ . '/..' . '/plasticbrain/php-flash-messages/src', + ), + 'NFEioServiceInvoices\\' => + array ( + 0 => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib', + ), + 'Http\\Message\\' => + array ( + 0 => __DIR__ . '/..' . '/php-http/message-factory/src', + 1 => __DIR__ . '/..' . '/php-http/message/src', + ), + 'GuzzleHttp\\Psr7\\' => + array ( + 0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src', + ), + 'Clue\\StreamFilter\\' => + array ( + 0 => __DIR__ . '/..' . '/clue/stream-filter/src', + ), + ); + + public static $prefixesPsr0 = array ( + 'E' => + array ( + 'Evenement' => + array ( + 0 => __DIR__ . '/..' . '/evenement/evenement/src', + ), + ), + ); + + public static $classMap = array ( + 'Clue\\StreamFilter\\CallbackFilter' => __DIR__ . '/..' . '/clue/stream-filter/src/CallbackFilter.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'Evenement\\EventEmitter' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitter.php', + 'Evenement\\EventEmitterInterface' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitterInterface.php', + 'Evenement\\EventEmitterTrait' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitterTrait.php', + 'GuzzleHttp\\Psr7\\AppendStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/AppendStream.php', + 'GuzzleHttp\\Psr7\\BufferStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/BufferStream.php', + 'GuzzleHttp\\Psr7\\CachingStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/CachingStream.php', + 'GuzzleHttp\\Psr7\\DroppingStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/DroppingStream.php', + 'GuzzleHttp\\Psr7\\FnStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/FnStream.php', + 'GuzzleHttp\\Psr7\\Header' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Header.php', + 'GuzzleHttp\\Psr7\\InflateStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/InflateStream.php', + 'GuzzleHttp\\Psr7\\LazyOpenStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/LazyOpenStream.php', + 'GuzzleHttp\\Psr7\\LimitStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/LimitStream.php', + 'GuzzleHttp\\Psr7\\Message' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Message.php', + 'GuzzleHttp\\Psr7\\MessageTrait' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/MessageTrait.php', + 'GuzzleHttp\\Psr7\\MimeType' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/MimeType.php', + 'GuzzleHttp\\Psr7\\MultipartStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/MultipartStream.php', + 'GuzzleHttp\\Psr7\\NoSeekStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/NoSeekStream.php', + 'GuzzleHttp\\Psr7\\PumpStream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/PumpStream.php', + 'GuzzleHttp\\Psr7\\Query' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Query.php', + 'GuzzleHttp\\Psr7\\Request' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Request.php', + 'GuzzleHttp\\Psr7\\Response' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Response.php', + 'GuzzleHttp\\Psr7\\Rfc7230' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Rfc7230.php', + 'GuzzleHttp\\Psr7\\ServerRequest' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/ServerRequest.php', + 'GuzzleHttp\\Psr7\\Stream' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Stream.php', + 'GuzzleHttp\\Psr7\\StreamDecoratorTrait' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/StreamDecoratorTrait.php', + 'GuzzleHttp\\Psr7\\StreamWrapper' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/StreamWrapper.php', + 'GuzzleHttp\\Psr7\\UploadedFile' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UploadedFile.php', + 'GuzzleHttp\\Psr7\\Uri' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Uri.php', + 'GuzzleHttp\\Psr7\\UriNormalizer' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UriNormalizer.php', + 'GuzzleHttp\\Psr7\\UriResolver' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/UriResolver.php', + 'GuzzleHttp\\Psr7\\Utils' => __DIR__ . '/..' . '/guzzlehttp/psr7/src/Utils.php', + 'Http\\Message\\Authentication' => __DIR__ . '/..' . '/php-http/message/src/Authentication.php', + 'Http\\Message\\Authentication\\AutoBasicAuth' => __DIR__ . '/..' . '/php-http/message/src/Authentication/AutoBasicAuth.php', + 'Http\\Message\\Authentication\\BasicAuth' => __DIR__ . '/..' . '/php-http/message/src/Authentication/BasicAuth.php', + 'Http\\Message\\Authentication\\Bearer' => __DIR__ . '/..' . '/php-http/message/src/Authentication/Bearer.php', + 'Http\\Message\\Authentication\\Chain' => __DIR__ . '/..' . '/php-http/message/src/Authentication/Chain.php', + 'Http\\Message\\Authentication\\Header' => __DIR__ . '/..' . '/php-http/message/src/Authentication/Header.php', + 'Http\\Message\\Authentication\\Matching' => __DIR__ . '/..' . '/php-http/message/src/Authentication/Matching.php', + 'Http\\Message\\Authentication\\QueryParam' => __DIR__ . '/..' . '/php-http/message/src/Authentication/QueryParam.php', + 'Http\\Message\\Authentication\\RequestConditional' => __DIR__ . '/..' . '/php-http/message/src/Authentication/RequestConditional.php', + 'Http\\Message\\Authentication\\Wsse' => __DIR__ . '/..' . '/php-http/message/src/Authentication/Wsse.php', + 'Http\\Message\\Builder\\ResponseBuilder' => __DIR__ . '/..' . '/php-http/message/src/Builder/ResponseBuilder.php', + 'Http\\Message\\Cookie' => __DIR__ . '/..' . '/php-http/message/src/Cookie.php', + 'Http\\Message\\CookieJar' => __DIR__ . '/..' . '/php-http/message/src/CookieJar.php', + 'Http\\Message\\CookieUtil' => __DIR__ . '/..' . '/php-http/message/src/CookieUtil.php', + 'Http\\Message\\Decorator\\MessageDecorator' => __DIR__ . '/..' . '/php-http/message/src/Decorator/MessageDecorator.php', + 'Http\\Message\\Decorator\\RequestDecorator' => __DIR__ . '/..' . '/php-http/message/src/Decorator/RequestDecorator.php', + 'Http\\Message\\Decorator\\ResponseDecorator' => __DIR__ . '/..' . '/php-http/message/src/Decorator/ResponseDecorator.php', + 'Http\\Message\\Decorator\\StreamDecorator' => __DIR__ . '/..' . '/php-http/message/src/Decorator/StreamDecorator.php', + 'Http\\Message\\Encoding\\ChunkStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/ChunkStream.php', + 'Http\\Message\\Encoding\\CompressStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/CompressStream.php', + 'Http\\Message\\Encoding\\DechunkStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/DechunkStream.php', + 'Http\\Message\\Encoding\\DecompressStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/DecompressStream.php', + 'Http\\Message\\Encoding\\DeflateStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/DeflateStream.php', + 'Http\\Message\\Encoding\\Filter\\Chunk' => __DIR__ . '/..' . '/php-http/message/src/Encoding/Filter/Chunk.php', + 'Http\\Message\\Encoding\\FilteredStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/FilteredStream.php', + 'Http\\Message\\Encoding\\GzipDecodeStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/GzipDecodeStream.php', + 'Http\\Message\\Encoding\\GzipEncodeStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/GzipEncodeStream.php', + 'Http\\Message\\Encoding\\InflateStream' => __DIR__ . '/..' . '/php-http/message/src/Encoding/InflateStream.php', + 'Http\\Message\\Exception' => __DIR__ . '/..' . '/php-http/message/src/Exception.php', + 'Http\\Message\\Exception\\UnexpectedValueException' => __DIR__ . '/..' . '/php-http/message/src/Exception/UnexpectedValueException.php', + 'Http\\Message\\Formatter' => __DIR__ . '/..' . '/php-http/message/src/Formatter.php', + 'Http\\Message\\Formatter\\CurlCommandFormatter' => __DIR__ . '/..' . '/php-http/message/src/Formatter/CurlCommandFormatter.php', + 'Http\\Message\\Formatter\\FullHttpMessageFormatter' => __DIR__ . '/..' . '/php-http/message/src/Formatter/FullHttpMessageFormatter.php', + 'Http\\Message\\Formatter\\SimpleFormatter' => __DIR__ . '/..' . '/php-http/message/src/Formatter/SimpleFormatter.php', + 'Http\\Message\\MessageFactory' => __DIR__ . '/..' . '/php-http/message-factory/src/MessageFactory.php', + 'Http\\Message\\MessageFactory\\DiactorosMessageFactory' => __DIR__ . '/..' . '/php-http/message/src/MessageFactory/DiactorosMessageFactory.php', + 'Http\\Message\\MessageFactory\\GuzzleMessageFactory' => __DIR__ . '/..' . '/php-http/message/src/MessageFactory/GuzzleMessageFactory.php', + 'Http\\Message\\MessageFactory\\SlimMessageFactory' => __DIR__ . '/..' . '/php-http/message/src/MessageFactory/SlimMessageFactory.php', + 'Http\\Message\\RequestFactory' => __DIR__ . '/..' . '/php-http/message-factory/src/RequestFactory.php', + 'Http\\Message\\RequestMatcher' => __DIR__ . '/..' . '/php-http/message/src/RequestMatcher.php', + 'Http\\Message\\RequestMatcher\\CallbackRequestMatcher' => __DIR__ . '/..' . '/php-http/message/src/RequestMatcher/CallbackRequestMatcher.php', + 'Http\\Message\\RequestMatcher\\RegexRequestMatcher' => __DIR__ . '/..' . '/php-http/message/src/RequestMatcher/RegexRequestMatcher.php', + 'Http\\Message\\RequestMatcher\\RequestMatcher' => __DIR__ . '/..' . '/php-http/message/src/RequestMatcher/RequestMatcher.php', + 'Http\\Message\\ResponseFactory' => __DIR__ . '/..' . '/php-http/message-factory/src/ResponseFactory.php', + 'Http\\Message\\StreamFactory' => __DIR__ . '/..' . '/php-http/message-factory/src/StreamFactory.php', + 'Http\\Message\\StreamFactory\\DiactorosStreamFactory' => __DIR__ . '/..' . '/php-http/message/src/StreamFactory/DiactorosStreamFactory.php', + 'Http\\Message\\StreamFactory\\GuzzleStreamFactory' => __DIR__ . '/..' . '/php-http/message/src/StreamFactory/GuzzleStreamFactory.php', + 'Http\\Message\\StreamFactory\\SlimStreamFactory' => __DIR__ . '/..' . '/php-http/message/src/StreamFactory/SlimStreamFactory.php', + 'Http\\Message\\Stream\\BufferedStream' => __DIR__ . '/..' . '/php-http/message/src/Stream/BufferedStream.php', + 'Http\\Message\\UriFactory' => __DIR__ . '/..' . '/php-http/message-factory/src/UriFactory.php', + 'Http\\Message\\UriFactory\\DiactorosUriFactory' => __DIR__ . '/..' . '/php-http/message/src/UriFactory/DiactorosUriFactory.php', + 'Http\\Message\\UriFactory\\GuzzleUriFactory' => __DIR__ . '/..' . '/php-http/message/src/UriFactory/GuzzleUriFactory.php', + 'Http\\Message\\UriFactory\\SlimUriFactory' => __DIR__ . '/..' . '/php-http/message/src/UriFactory/SlimUriFactory.php', + 'NFEioServiceInvoices\\Addon' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Addon.php', + 'NFEioServiceInvoices\\Admin\\AdminDispatcher' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Admin/AdminDispatcher.php', + 'NFEioServiceInvoices\\Admin\\Controller' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Admin/Controller.php', + 'NFEioServiceInvoices\\Client\\ClientDispatcher' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Client/ClientDispatcher.php', + 'NFEioServiceInvoices\\Client\\Controller' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Client/Controller.php', + 'NFEioServiceInvoices\\Configuration' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Configuration.php', + 'NFEioServiceInvoices\\CustomFields' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/CustomFields.php', + 'NFEioServiceInvoices\\Helpers\\Versions' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Helpers/Versions.php', + 'NFEioServiceInvoices\\Legacy\\Functions' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Legacy/Functions.php', + 'NFEioServiceInvoices\\Legacy\\Hooks' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Legacy/Hooks.php', + 'NFEioServiceInvoices\\Migrations\\Migrations' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Migrations/Migrations.php', + 'NFEioServiceInvoices\\Models\\ClientConfiguration\\Repository' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Models/ClientConfiguration/Repository.php', + 'NFEioServiceInvoices\\Models\\ModuleConfiguration\\Repository' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Models/ModuleConfiguration/Repository.php', + 'NFEioServiceInvoices\\Models\\ProductCode\\Repository' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Models/ProductCode/Repository.php', + 'NFEioServiceInvoices\\Models\\ServiceInvoices\\Repository' => __DIR__ . '/../../../../../..' . '/modules/addons/NFEioServiceInvoices/lib/Models/ServiceInvoices/Repository.php', + 'Plasticbrain\\FlashMessages\\FlashMessages' => __DIR__ . '/..' . '/plasticbrain/php-flash-messages/src/FlashMessages.php', + 'Psr\\Http\\Message\\MessageInterface' => __DIR__ . '/..' . '/psr/http-message/src/MessageInterface.php', + 'Psr\\Http\\Message\\RequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/RequestInterface.php', + 'Psr\\Http\\Message\\ResponseInterface' => __DIR__ . '/..' . '/psr/http-message/src/ResponseInterface.php', + 'Psr\\Http\\Message\\ServerRequestInterface' => __DIR__ . '/..' . '/psr/http-message/src/ServerRequestInterface.php', + 'Psr\\Http\\Message\\StreamInterface' => __DIR__ . '/..' . '/psr/http-message/src/StreamInterface.php', + 'Psr\\Http\\Message\\UploadedFileInterface' => __DIR__ . '/..' . '/psr/http-message/src/UploadedFileInterface.php', + 'Psr\\Http\\Message\\UriInterface' => __DIR__ . '/..' . '/psr/http-message/src/UriInterface.php', + 'React\\Cache\\ArrayCache' => __DIR__ . '/..' . '/react/cache/src/ArrayCache.php', + 'React\\Cache\\CacheInterface' => __DIR__ . '/..' . '/react/cache/src/CacheInterface.php', + 'React\\Dns\\BadServerException' => __DIR__ . '/..' . '/react/dns/src/BadServerException.php', + 'React\\Dns\\Config\\Config' => __DIR__ . '/..' . '/react/dns/src/Config/Config.php', + 'React\\Dns\\Config\\HostsFile' => __DIR__ . '/..' . '/react/dns/src/Config/HostsFile.php', + 'React\\Dns\\Model\\Message' => __DIR__ . '/..' . '/react/dns/src/Model/Message.php', + 'React\\Dns\\Model\\Record' => __DIR__ . '/..' . '/react/dns/src/Model/Record.php', + 'React\\Dns\\Protocol\\BinaryDumper' => __DIR__ . '/..' . '/react/dns/src/Protocol/BinaryDumper.php', + 'React\\Dns\\Protocol\\Parser' => __DIR__ . '/..' . '/react/dns/src/Protocol/Parser.php', + 'React\\Dns\\Query\\CachingExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/CachingExecutor.php', + 'React\\Dns\\Query\\CancellationException' => __DIR__ . '/..' . '/react/dns/src/Query/CancellationException.php', + 'React\\Dns\\Query\\CoopExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/CoopExecutor.php', + 'React\\Dns\\Query\\ExecutorInterface' => __DIR__ . '/..' . '/react/dns/src/Query/ExecutorInterface.php', + 'React\\Dns\\Query\\FallbackExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/FallbackExecutor.php', + 'React\\Dns\\Query\\HostsFileExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/HostsFileExecutor.php', + 'React\\Dns\\Query\\Query' => __DIR__ . '/..' . '/react/dns/src/Query/Query.php', + 'React\\Dns\\Query\\RetryExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/RetryExecutor.php', + 'React\\Dns\\Query\\SelectiveTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/SelectiveTransportExecutor.php', + 'React\\Dns\\Query\\TcpTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/TcpTransportExecutor.php', + 'React\\Dns\\Query\\TimeoutException' => __DIR__ . '/..' . '/react/dns/src/Query/TimeoutException.php', + 'React\\Dns\\Query\\TimeoutExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/TimeoutExecutor.php', + 'React\\Dns\\Query\\UdpTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/UdpTransportExecutor.php', + 'React\\Dns\\RecordNotFoundException' => __DIR__ . '/..' . '/react/dns/src/RecordNotFoundException.php', + 'React\\Dns\\Resolver\\Factory' => __DIR__ . '/..' . '/react/dns/src/Resolver/Factory.php', + 'React\\Dns\\Resolver\\Resolver' => __DIR__ . '/..' . '/react/dns/src/Resolver/Resolver.php', + 'React\\Dns\\Resolver\\ResolverInterface' => __DIR__ . '/..' . '/react/dns/src/Resolver/ResolverInterface.php', + 'React\\EventLoop\\ExtEvLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtEvLoop.php', + 'React\\EventLoop\\ExtEventLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtEventLoop.php', + 'React\\EventLoop\\ExtLibevLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtLibevLoop.php', + 'React\\EventLoop\\ExtLibeventLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtLibeventLoop.php', + 'React\\EventLoop\\ExtUvLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtUvLoop.php', + 'React\\EventLoop\\Factory' => __DIR__ . '/..' . '/react/event-loop/src/Factory.php', + 'React\\EventLoop\\Loop' => __DIR__ . '/..' . '/react/event-loop/src/Loop.php', + 'React\\EventLoop\\LoopInterface' => __DIR__ . '/..' . '/react/event-loop/src/LoopInterface.php', + 'React\\EventLoop\\SignalsHandler' => __DIR__ . '/..' . '/react/event-loop/src/SignalsHandler.php', + 'React\\EventLoop\\StreamSelectLoop' => __DIR__ . '/..' . '/react/event-loop/src/StreamSelectLoop.php', + 'React\\EventLoop\\Tick\\FutureTickQueue' => __DIR__ . '/..' . '/react/event-loop/src/Tick/FutureTickQueue.php', + 'React\\EventLoop\\TimerInterface' => __DIR__ . '/..' . '/react/event-loop/src/TimerInterface.php', + 'React\\EventLoop\\Timer\\Timer' => __DIR__ . '/..' . '/react/event-loop/src/Timer/Timer.php', + 'React\\EventLoop\\Timer\\Timers' => __DIR__ . '/..' . '/react/event-loop/src/Timer/Timers.php', + 'React\\Http\\Browser' => __DIR__ . '/..' . '/react/http/src/Browser.php', + 'React\\Http\\Client\\Client' => __DIR__ . '/..' . '/react/http/src/Client/Client.php', + 'React\\Http\\Client\\Request' => __DIR__ . '/..' . '/react/http/src/Client/Request.php', + 'React\\Http\\Client\\RequestData' => __DIR__ . '/..' . '/react/http/src/Client/RequestData.php', + 'React\\Http\\HttpServer' => __DIR__ . '/..' . '/react/http/src/HttpServer.php', + 'React\\Http\\Io\\BufferedBody' => __DIR__ . '/..' . '/react/http/src/Io/BufferedBody.php', + 'React\\Http\\Io\\ChunkedDecoder' => __DIR__ . '/..' . '/react/http/src/Io/ChunkedDecoder.php', + 'React\\Http\\Io\\ChunkedEncoder' => __DIR__ . '/..' . '/react/http/src/Io/ChunkedEncoder.php', + 'React\\Http\\Io\\CloseProtectionStream' => __DIR__ . '/..' . '/react/http/src/Io/CloseProtectionStream.php', + 'React\\Http\\Io\\EmptyBodyStream' => __DIR__ . '/..' . '/react/http/src/Io/EmptyBodyStream.php', + 'React\\Http\\Io\\HttpBodyStream' => __DIR__ . '/..' . '/react/http/src/Io/HttpBodyStream.php', + 'React\\Http\\Io\\IniUtil' => __DIR__ . '/..' . '/react/http/src/Io/IniUtil.php', + 'React\\Http\\Io\\LengthLimitedStream' => __DIR__ . '/..' . '/react/http/src/Io/LengthLimitedStream.php', + 'React\\Http\\Io\\MiddlewareRunner' => __DIR__ . '/..' . '/react/http/src/Io/MiddlewareRunner.php', + 'React\\Http\\Io\\MultipartParser' => __DIR__ . '/..' . '/react/http/src/Io/MultipartParser.php', + 'React\\Http\\Io\\PauseBufferStream' => __DIR__ . '/..' . '/react/http/src/Io/PauseBufferStream.php', + 'React\\Http\\Io\\ReadableBodyStream' => __DIR__ . '/..' . '/react/http/src/Io/ReadableBodyStream.php', + 'React\\Http\\Io\\RequestHeaderParser' => __DIR__ . '/..' . '/react/http/src/Io/RequestHeaderParser.php', + 'React\\Http\\Io\\Sender' => __DIR__ . '/..' . '/react/http/src/Io/Sender.php', + 'React\\Http\\Io\\StreamingServer' => __DIR__ . '/..' . '/react/http/src/Io/StreamingServer.php', + 'React\\Http\\Io\\Transaction' => __DIR__ . '/..' . '/react/http/src/Io/Transaction.php', + 'React\\Http\\Io\\UploadedFile' => __DIR__ . '/..' . '/react/http/src/Io/UploadedFile.php', + 'React\\Http\\Message\\Response' => __DIR__ . '/..' . '/react/http/src/Message/Response.php', + 'React\\Http\\Message\\ResponseException' => __DIR__ . '/..' . '/react/http/src/Message/ResponseException.php', + 'React\\Http\\Message\\ServerRequest' => __DIR__ . '/..' . '/react/http/src/Message/ServerRequest.php', + 'React\\Http\\Middleware\\LimitConcurrentRequestsMiddleware' => __DIR__ . '/..' . '/react/http/src/Middleware/LimitConcurrentRequestsMiddleware.php', + 'React\\Http\\Middleware\\RequestBodyBufferMiddleware' => __DIR__ . '/..' . '/react/http/src/Middleware/RequestBodyBufferMiddleware.php', + 'React\\Http\\Middleware\\RequestBodyParserMiddleware' => __DIR__ . '/..' . '/react/http/src/Middleware/RequestBodyParserMiddleware.php', + 'React\\Http\\Middleware\\StreamingRequestMiddleware' => __DIR__ . '/..' . '/react/http/src/Middleware/StreamingRequestMiddleware.php', + 'React\\Http\\Server' => __DIR__ . '/..' . '/react/http/src/Server.php', + 'React\\Promise\\CancellablePromiseInterface' => __DIR__ . '/..' . '/react/promise/src/CancellablePromiseInterface.php', + 'React\\Promise\\CancellationQueue' => __DIR__ . '/..' . '/react/promise/src/CancellationQueue.php', + 'React\\Promise\\Deferred' => __DIR__ . '/..' . '/react/promise/src/Deferred.php', + 'React\\Promise\\Exception\\LengthException' => __DIR__ . '/..' . '/react/promise/src/Exception/LengthException.php', + 'React\\Promise\\ExtendedPromiseInterface' => __DIR__ . '/..' . '/react/promise/src/ExtendedPromiseInterface.php', + 'React\\Promise\\FulfilledPromise' => __DIR__ . '/..' . '/react/promise/src/FulfilledPromise.php', + 'React\\Promise\\LazyPromise' => __DIR__ . '/..' . '/react/promise/src/LazyPromise.php', + 'React\\Promise\\Promise' => __DIR__ . '/..' . '/react/promise/src/Promise.php', + 'React\\Promise\\PromiseInterface' => __DIR__ . '/..' . '/react/promise/src/PromiseInterface.php', + 'React\\Promise\\PromisorInterface' => __DIR__ . '/..' . '/react/promise/src/PromisorInterface.php', + 'React\\Promise\\RejectedPromise' => __DIR__ . '/..' . '/react/promise/src/RejectedPromise.php', + 'React\\Promise\\Stream\\UnwrapReadableStream' => __DIR__ . '/..' . '/react/promise-stream/src/UnwrapReadableStream.php', + 'React\\Promise\\Stream\\UnwrapWritableStream' => __DIR__ . '/..' . '/react/promise-stream/src/UnwrapWritableStream.php', + 'React\\Promise\\Timer\\TimeoutException' => __DIR__ . '/..' . '/react/promise-timer/src/TimeoutException.php', + 'React\\Promise\\UnhandledRejectionException' => __DIR__ . '/..' . '/react/promise/src/UnhandledRejectionException.php', + 'React\\Socket\\Connection' => __DIR__ . '/..' . '/react/socket/src/Connection.php', + 'React\\Socket\\ConnectionInterface' => __DIR__ . '/..' . '/react/socket/src/ConnectionInterface.php', + 'React\\Socket\\Connector' => __DIR__ . '/..' . '/react/socket/src/Connector.php', + 'React\\Socket\\ConnectorInterface' => __DIR__ . '/..' . '/react/socket/src/ConnectorInterface.php', + 'React\\Socket\\DnsConnector' => __DIR__ . '/..' . '/react/socket/src/DnsConnector.php', + 'React\\Socket\\FixedUriConnector' => __DIR__ . '/..' . '/react/socket/src/FixedUriConnector.php', + 'React\\Socket\\HappyEyeBallsConnectionBuilder' => __DIR__ . '/..' . '/react/socket/src/HappyEyeBallsConnectionBuilder.php', + 'React\\Socket\\HappyEyeBallsConnector' => __DIR__ . '/..' . '/react/socket/src/HappyEyeBallsConnector.php', + 'React\\Socket\\LimitingServer' => __DIR__ . '/..' . '/react/socket/src/LimitingServer.php', + 'React\\Socket\\SecureConnector' => __DIR__ . '/..' . '/react/socket/src/SecureConnector.php', + 'React\\Socket\\SecureServer' => __DIR__ . '/..' . '/react/socket/src/SecureServer.php', + 'React\\Socket\\Server' => __DIR__ . '/..' . '/react/socket/src/Server.php', + 'React\\Socket\\ServerInterface' => __DIR__ . '/..' . '/react/socket/src/ServerInterface.php', + 'React\\Socket\\SocketServer' => __DIR__ . '/..' . '/react/socket/src/SocketServer.php', + 'React\\Socket\\StreamEncryption' => __DIR__ . '/..' . '/react/socket/src/StreamEncryption.php', + 'React\\Socket\\TcpConnector' => __DIR__ . '/..' . '/react/socket/src/TcpConnector.php', + 'React\\Socket\\TcpServer' => __DIR__ . '/..' . '/react/socket/src/TcpServer.php', + 'React\\Socket\\TimeoutConnector' => __DIR__ . '/..' . '/react/socket/src/TimeoutConnector.php', + 'React\\Socket\\UnixConnector' => __DIR__ . '/..' . '/react/socket/src/UnixConnector.php', + 'React\\Socket\\UnixServer' => __DIR__ . '/..' . '/react/socket/src/UnixServer.php', + 'React\\Stream\\CompositeStream' => __DIR__ . '/..' . '/react/stream/src/CompositeStream.php', + 'React\\Stream\\DuplexResourceStream' => __DIR__ . '/..' . '/react/stream/src/DuplexResourceStream.php', + 'React\\Stream\\DuplexStreamInterface' => __DIR__ . '/..' . '/react/stream/src/DuplexStreamInterface.php', + 'React\\Stream\\ReadableResourceStream' => __DIR__ . '/..' . '/react/stream/src/ReadableResourceStream.php', + 'React\\Stream\\ReadableStreamInterface' => __DIR__ . '/..' . '/react/stream/src/ReadableStreamInterface.php', + 'React\\Stream\\ThroughStream' => __DIR__ . '/..' . '/react/stream/src/ThroughStream.php', + 'React\\Stream\\Util' => __DIR__ . '/..' . '/react/stream/src/Util.php', + 'React\\Stream\\WritableResourceStream' => __DIR__ . '/..' . '/react/stream/src/WritableResourceStream.php', + 'React\\Stream\\WritableStreamInterface' => __DIR__ . '/..' . '/react/stream/src/WritableStreamInterface.php', + 'RingCentral\\Psr7\\AppendStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/AppendStream.php', + 'RingCentral\\Psr7\\BufferStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/BufferStream.php', + 'RingCentral\\Psr7\\CachingStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/CachingStream.php', + 'RingCentral\\Psr7\\DroppingStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/DroppingStream.php', + 'RingCentral\\Psr7\\FnStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/FnStream.php', + 'RingCentral\\Psr7\\InflateStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/InflateStream.php', + 'RingCentral\\Psr7\\LazyOpenStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/LazyOpenStream.php', + 'RingCentral\\Psr7\\LimitStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/LimitStream.php', + 'RingCentral\\Psr7\\MessageTrait' => __DIR__ . '/..' . '/ringcentral/psr7/src/MessageTrait.php', + 'RingCentral\\Psr7\\MultipartStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/MultipartStream.php', + 'RingCentral\\Psr7\\NoSeekStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/NoSeekStream.php', + 'RingCentral\\Psr7\\PumpStream' => __DIR__ . '/..' . '/ringcentral/psr7/src/PumpStream.php', + 'RingCentral\\Psr7\\Request' => __DIR__ . '/..' . '/ringcentral/psr7/src/Request.php', + 'RingCentral\\Psr7\\Response' => __DIR__ . '/..' . '/ringcentral/psr7/src/Response.php', + 'RingCentral\\Psr7\\ServerRequest' => __DIR__ . '/..' . '/ringcentral/psr7/src/ServerRequest.php', + 'RingCentral\\Psr7\\Stream' => __DIR__ . '/..' . '/ringcentral/psr7/src/Stream.php', + 'RingCentral\\Psr7\\StreamDecoratorTrait' => __DIR__ . '/..' . '/ringcentral/psr7/src/StreamDecoratorTrait.php', + 'RingCentral\\Psr7\\StreamWrapper' => __DIR__ . '/..' . '/ringcentral/psr7/src/StreamWrapper.php', + 'RingCentral\\Psr7\\Uri' => __DIR__ . '/..' . '/ringcentral/psr7/src/Uri.php', + 'WHMCSExpert\\Addon\\Storage' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Addon/Storage.php', + 'WHMCSExpert\\Gateway\\GatewayStorage' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Gateway/GatewayStorage.php', + 'WHMCSExpert\\Helper\\Helper' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Helper/Helper.php', + 'WHMCSExpert\\Template\\Template' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/Template/Template.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Exception' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Exception.php', + 'WHMCSExpert\\mtLibs\\MySQL\\PdoWrapper' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/PdoWrapper.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Query' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Query.php', + 'WHMCSExpert\\mtLibs\\MySQL\\Result' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Result.php', + 'WHMCSExpert\\mtLibs\\Smarty' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/Smarty.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Base' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Base.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Codes' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Codes.php', + 'WHMCSExpert\\mtLibs\\exceptions\\SyntaxError' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/SyntaxError.php', + 'WHMCSExpert\\mtLibs\\exceptions\\System' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/System.php', + 'WHMCSExpert\\mtLibs\\exceptions\\Validation' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Validation.php', + 'WHMCSExpert\\mtLibs\\exceptions\\WhmcsAPI' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/WhmcsAPI.php', + 'WHMCSExpert\\mtLibs\\models\\Base' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Base.php', + 'WHMCSExpert\\mtLibs\\models\\Orm' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Orm.php', + 'WHMCSExpert\\mtLibs\\models\\Repository' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Repository.php', + 'WHMCSExpert\\mtLibs\\models\\TableConstructor' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/TableConstructor.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractConfiguration' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractConfiguration.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractController' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractController.php', + 'WHMCSExpert\\mtLibs\\process\\AbstractMainDriver' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractMainDriver.php', + 'WHMCSExpert\\mtLibs\\process\\MainInstance' => __DIR__ . '/..' . '/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/MainInstance.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit86e02c580f8e6930f39d749d3a111004::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit86e02c580f8e6930f39d749d3a111004::$prefixDirsPsr4; + $loader->prefixesPsr0 = ComposerStaticInit86e02c580f8e6930f39d749d3a111004::$prefixesPsr0; + $loader->classMap = ComposerStaticInit86e02c580f8e6930f39d749d3a111004::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.json b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.json new file mode 100644 index 0000000..6ee1645 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.json @@ -0,0 +1,1347 @@ +{ + "packages": [ + { + "name": "clue/stream-filter", + "version": "v1.5.0", + "version_normalized": "1.5.0.0", + "source": { + "type": "git", + "url": "https://github.com/clue/stream-filter.git", + "reference": "aeb7d8ea49c7963d3b581378955dbf5bc49aa320" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/clue/stream-filter/zipball/aeb7d8ea49c7963d3b581378955dbf5bc49aa320", + "reference": "aeb7d8ea49c7963d3b581378955dbf5bc49aa320", + "shasum": "" + }, + "require": { + "php": ">=5.3" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.36" + }, + "time": "2020-10-02T12:38:20+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Clue\\StreamFilter\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering" + } + ], + "description": "A simple and modern approach to stream filtering in PHP", + "homepage": "https://github.com/clue/php-stream-filter", + "keywords": [ + "bucket brigade", + "callback", + "filter", + "php_user_filter", + "stream", + "stream_filter_append", + "stream_filter_register" + ], + "support": { + "issues": "https://github.com/clue/stream-filter/issues", + "source": "https://github.com/clue/stream-filter/tree/v1.5.0" + }, + "funding": [ + { + "url": "https://clue.engineering/support", + "type": "custom" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../clue/stream-filter" + }, + { + "name": "evenement/evenement", + "version": "v3.0.1", + "version_normalized": "3.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/igorw/evenement.git", + "reference": "531bfb9d15f8aa57454f5f0285b18bec903b8fb7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/igorw/evenement/zipball/531bfb9d15f8aa57454f5f0285b18bec903b8fb7", + "reference": "531bfb9d15f8aa57454f5f0285b18bec903b8fb7", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "time": "2017-07-23T21:35:13+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Evenement": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https://github.com/igorw/evenement/issues", + "source": "https://github.com/igorw/evenement/tree/master" + }, + "install-path": "../evenement/evenement" + }, + { + "name": "guzzlehttp/psr7", + "version": "1.8.3", + "version_normalized": "1.8.3.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "1afdd860a2566ed3c2b0b4a3de6e23434a79ec85" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/1afdd860a2566ed3c2b0b4a3de6e23434a79ec85", + "reference": "1afdd860a2566ed3c2b0b4a3de6e23434a79ec85", + "shasum": "" + }, + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "time": "2021-10-05T13:56:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.7-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/1.8.3" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "install-path": "../guzzlehttp/psr7" + }, + { + "name": "php-http/message", + "version": "1.12.0", + "version_normalized": "1.12.0.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/message.git", + "reference": "39eb7548be982a81085fe5a6e2a44268cd586291" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/message/zipball/39eb7548be982a81085fe5a6e2a44268cd586291", + "reference": "39eb7548be982a81085fe5a6e2a44268cd586291", + "shasum": "" + }, + "require": { + "clue/stream-filter": "^1.5", + "php": "^7.1 || ^8.0", + "php-http/message-factory": "^1.0.2", + "psr/http-message": "^1.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0" + }, + "require-dev": { + "ergebnis/composer-normalize": "^2.6", + "ext-zlib": "*", + "guzzlehttp/psr7": "^1.0", + "laminas/laminas-diactoros": "^2.0", + "phpspec/phpspec": "^5.1 || ^6.3", + "slim/slim": "^3.0" + }, + "suggest": { + "ext-zlib": "Used with compressor/decompressor streams", + "guzzlehttp/psr7": "Used with Guzzle PSR-7 Factories", + "laminas/laminas-diactoros": "Used with Diactoros Factories", + "slim/slim": "Used with Slim Framework PSR-7 implementation" + }, + "time": "2021-08-29T09:13:12+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Http\\Message\\": "src/" + }, + "files": [ + "src/filters.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "HTTP Message related tools", + "homepage": "http://php-http.org", + "keywords": [ + "http", + "message", + "psr-7" + ], + "support": { + "issues": "https://github.com/php-http/message/issues", + "source": "https://github.com/php-http/message/tree/1.12.0" + }, + "install-path": "../php-http/message" + }, + { + "name": "php-http/message-factory", + "version": "v1.0.2", + "version_normalized": "1.0.2.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/message-factory.git", + "reference": "a478cb11f66a6ac48d8954216cfed9aa06a501a1" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/message-factory/zipball/a478cb11f66a6ac48d8954216cfed9aa06a501a1", + "reference": "a478cb11f66a6ac48d8954216cfed9aa06a501a1", + "shasum": "" + }, + "require": { + "php": ">=5.4", + "psr/http-message": "^1.0" + }, + "time": "2015-12-19T14:08:53+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Factory interfaces for PSR-7 HTTP Message", + "homepage": "http://php-http.org", + "keywords": [ + "factory", + "http", + "message", + "stream", + "uri" + ], + "support": { + "issues": "https://github.com/php-http/message-factory/issues", + "source": "https://github.com/php-http/message-factory/tree/master" + }, + "install-path": "../php-http/message-factory" + }, + { + "name": "plasticbrain/php-flash-messages", + "version": "v1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/plasticbrain/PhpFlashMessages.git", + "reference": "b565762619342057ce561de20d0f2f6e14f9aa77" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/plasticbrain/PhpFlashMessages/zipball/b565762619342057ce561de20d0f2f6e14f9aa77", + "reference": "b565762619342057ce561de20d0f2f6e14f9aa77", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "time": "2016-04-01T08:39:38+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Plasticbrain\\FlashMessages\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mike Everhart", + "email": "mike@plasticbrain.net" + } + ], + "description": "A modern take on PHP session-based flash messages", + "keywords": [ + "bootstrap", + "flash", + "messages", + "session" + ], + "support": { + "issues": "https://github.com/plasticbrain/PhpFlashMessages/issues", + "source": "https://github.com/plasticbrain/PhpFlashMessages/tree/master" + }, + "install-path": "../plasticbrain/php-flash-messages" + }, + { + "name": "psr/http-message", + "version": "1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/f6561bf28d520154e4b0ec72be95418abe6d9363", + "reference": "f6561bf28d520154e4b0ec72be95418abe6d9363", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "time": "2016-08-06T14:39:51+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/master" + }, + "install-path": "../psr/http-message" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "time": "2019-03-08T08:55:37+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "install-path": "../ralouphie/getallheaders" + }, + { + "name": "react/cache", + "version": "v1.1.1", + "version_normalized": "1.1.1.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/cache.git", + "reference": "4bf736a2cccec7298bdf745db77585966fc2ca7e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/cache/zipball/4bf736a2cccec7298bdf745db77585966fc2ca7e", + "reference": "4bf736a2cccec7298bdf745db77585966fc2ca7e", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "time": "2021-02-02T06:47:52+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Cache\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/cache/issues", + "source": "https://github.com/reactphp/cache/tree/v1.1.1" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/cache" + }, + { + "name": "react/dns", + "version": "v1.8.0", + "version_normalized": "1.8.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/dns.git", + "reference": "2a5a74ab751e53863b45fb87e1d3913884f88248" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/dns/zipball/2a5a74ab751e53863b45fb87e1d3913884f88248", + "reference": "2a5a74ab751e53863b45fb87e1d3913884f88248", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.0 || ^2.7 || ^1.2.1", + "react/promise-timer": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.2", + "phpunit/phpunit": "^9.3 || ^4.8.35" + }, + "time": "2021-07-11T12:40:34+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Dns\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https://github.com/reactphp/dns/issues", + "source": "https://github.com/reactphp/dns/tree/v1.8.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/dns" + }, + { + "name": "react/event-loop", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/event-loop.git", + "reference": "be6dee480fc4692cec0504e65eb486e3be1aa6f2" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/event-loop/zipball/be6dee480fc4692cec0504e65eb486e3be1aa6f2", + "reference": "be6dee480fc4692cec0504e65eb486e3be1aa6f2", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "suggest": { + "ext-event": "~1.0 for ExtEventLoop", + "ext-pcntl": "For signal handling support when using the StreamSelectLoop", + "ext-uv": "* for ExtUvLoop" + }, + "time": "2021-07-11T12:31:24+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https://github.com/reactphp/event-loop/issues", + "source": "https://github.com/reactphp/event-loop/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/event-loop" + }, + { + "name": "react/http", + "version": "v1.5.0", + "version_normalized": "1.5.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/http.git", + "reference": "8a0fd7c0aa74f0db3008b1e47ca86c613cbb040e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/http/zipball/8a0fd7c0aa74f0db3008b1e47ca86c613cbb040e", + "reference": "8a0fd7c0aa74f0db3008b1e47ca86c613cbb040e", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "psr/http-message": "^1.0", + "react/event-loop": "^1.2", + "react/promise": "^2.3 || ^1.2.1", + "react/promise-stream": "^1.1", + "react/socket": "^1.9", + "react/stream": "^1.2", + "ringcentral/psr7": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.1", + "clue/http-proxy-react": "^1.3", + "clue/reactphp-ssh-proxy": "^1.0", + "clue/socks-react": "^1.0", + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "time": "2021-08-04T12:24:55+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Http\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven, streaming HTTP client and server implementation for ReactPHP", + "keywords": [ + "async", + "client", + "event-driven", + "http", + "http client", + "http server", + "https", + "psr-7", + "reactphp", + "server", + "streaming" + ], + "support": { + "issues": "https://github.com/reactphp/http/issues", + "source": "https://github.com/reactphp/http/tree/v1.5.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/http" + }, + { + "name": "react/promise", + "version": "v2.8.0", + "version_normalized": "2.8.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise.git", + "reference": "f3cff96a19736714524ca0dd1d4130de73dbbbc4" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise/zipball/f3cff96a19736714524ca0dd1d4130de73dbbbc4", + "reference": "f3cff96a19736714524ca0dd1d4130de73dbbbc4", + "shasum": "" + }, + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.0 || ^6.5 || ^5.7 || ^4.8.36" + }, + "time": "2020-05-12T15:16:56+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Promise\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com" + } + ], + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https://github.com/reactphp/promise/issues", + "source": "https://github.com/reactphp/promise/tree/v2.8.0" + }, + "install-path": "../react/promise" + }, + { + "name": "react/promise-stream", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise-stream.git", + "reference": "6384d8b76cf7dcc44b0bf3343fb2b2928412d1fe" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise-stream/zipball/6384d8b76cf7dcc44b0bf3343fb2b2928412d1fe", + "reference": "6384d8b76cf7dcc44b0bf3343fb2b2928412d1fe", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/promise": "^2.1 || ^1.2", + "react/stream": "^1.0 || ^0.7 || ^0.6 || ^0.5 || ^0.4.6" + }, + "require-dev": { + "clue/block-react": "^1.0", + "phpunit/phpunit": "^7.0 || ^6.4 || ^5.7 || ^4.8.35", + "react/event-loop": "^1.0 || ^0.5 || ^0.4 || ^0.3", + "react/promise-timer": "^1.0" + }, + "time": "2019-07-03T12:29:10+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Promise\\Stream\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@lueck.tv" + } + ], + "description": "The missing link between Promise-land and Stream-land for ReactPHP", + "homepage": "https://github.com/reactphp/promise-stream", + "keywords": [ + "Buffer", + "async", + "promise", + "reactphp", + "stream", + "unwrap" + ], + "support": { + "issues": "https://github.com/reactphp/promise-stream/issues", + "source": "https://github.com/reactphp/promise-stream/tree/v1.2.0" + }, + "install-path": "../react/promise-stream" + }, + { + "name": "react/promise-timer", + "version": "v1.7.0", + "version_normalized": "1.7.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/promise-timer.git", + "reference": "607dd79990e32fcb402cb0a176b4a4be12f97e7c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/promise-timer/zipball/607dd79990e32fcb402cb0a176b4a4be12f97e7c", + "reference": "607dd79990e32fcb402cb0a176b4a4be12f97e7c", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react/event-loop": "^1.2", + "react/promise": "^3.0 || ^2.7.0 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "time": "2021-07-11T13:08:51+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Promise\\Timer\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "A trivial implementation of timeouts for Promises, built on top of ReactPHP.", + "homepage": "https://github.com/reactphp/promise-timer", + "keywords": [ + "async", + "event-loop", + "promise", + "reactphp", + "timeout", + "timer" + ], + "support": { + "issues": "https://github.com/reactphp/promise-timer/issues", + "source": "https://github.com/reactphp/promise-timer/tree/v1.7.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/promise-timer" + }, + { + "name": "react/socket", + "version": "v1.9.0", + "version_normalized": "1.9.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/socket.git", + "reference": "aa6e3f8ebcd6dec3ad1ee92a449b4cc341994001" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/socket/zipball/aa6e3f8ebcd6dec3ad1ee92a449b4cc341994001", + "reference": "aa6e3f8ebcd6dec3ad1ee92a449b4cc341994001", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react/dns": "^1.8", + "react/event-loop": "^1.2", + "react/promise": "^2.6.0 || ^1.2.1", + "react/promise-timer": "^1.4.0", + "react/stream": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.2", + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35", + "react/promise-stream": "^1.2" + }, + "time": "2021-08-03T12:37:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Socket\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https://github.com/reactphp/socket/issues", + "source": "https://github.com/reactphp/socket/tree/v1.9.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/socket" + }, + { + "name": "react/stream", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https://github.com/reactphp/stream.git", + "reference": "7a423506ee1903e89f1e08ec5f0ed430ff784ae9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/reactphp/stream/zipball/7a423506ee1903e89f1e08ec5f0ed430ff784ae9", + "reference": "7a423506ee1903e89f1e08ec5f0ed430ff784ae9", + "shasum": "" + }, + "require": { + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react/event-loop": "^1.2" + }, + "require-dev": { + "clue/stream-filter": "~1.2", + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "time": "2021-07-11T12:37:55+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "React\\Stream\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian Lück", + "email": "christian@clue.engineering", + "homepage": "https://clue.engineering/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https://wyrihaximus.net/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https://sorgalla.com/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https://cboden.dev/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https://github.com/reactphp/stream/issues", + "source": "https://github.com/reactphp/stream/tree/v1.2.0" + }, + "funding": [ + { + "url": "https://github.com/WyriHaximus", + "type": "github" + }, + { + "url": "https://github.com/clue", + "type": "github" + } + ], + "install-path": "../react/stream" + }, + { + "name": "ringcentral/psr7", + "version": "1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https://github.com/ringcentral/psr7.git", + "reference": "360faaec4b563958b673fb52bbe94e37f14bc686" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ringcentral/psr7/zipball/360faaec4b563958b673fb52bbe94e37f14bc686", + "reference": "360faaec4b563958b673fb52bbe94e37f14bc686", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "psr/http-message": "~1.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "time": "2018-05-29T20:21:04+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "RingCentral\\Psr7\\": "src/" + }, + "files": [ + "src/functions_include.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "description": "PSR-7 message implementation", + "keywords": [ + "http", + "message", + "stream", + "uri" + ], + "support": { + "source": "https://github.com/ringcentral/psr7/tree/master" + }, + "install-path": "../ringcentral/psr7" + }, + { + "name": "whmcsexpert/whmcsexpert", + "version": "dev-dev", + "version_normalized": "dev-dev", + "source": { + "type": "git", + "url": "https://github.com/whmcsexpert/whmcsexpert.git", + "reference": "2ab629648dcb7133d24defe305b8b5f74a0d3953" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/whmcsexpert/whmcsexpert/zipball/2ab629648dcb7133d24defe305b8b5f74a0d3953", + "reference": "2ab629648dcb7133d24defe305b8b5f74a0d3953", + "shasum": "" + }, + "require-dev": { + "illuminate/database": "v5.8.36", + "phpdocumentor/phpdocumentor": "2.*", + "phpunit/phpunit": "@stable" + }, + "time": "2021-10-16T22:00:59+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "WHMCSExpert\\": "src/WHMCSExpert/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Andre Bellafronte", + "email": "andre@eunarede.com" + } + ], + "description": "WHMCS Expert Library", + "support": { + "issues": "https://github.com/whmcsexpert/whmcsexpert/issues", + "source": "https://github.com/whmcsexpert/whmcsexpert/tree/dev" + }, + "install-path": "../whmcsexpert/whmcsexpert" + } + ], + "dev": false, + "dev-package-names": [] +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.php new file mode 100644 index 0000000..dfe6c7c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/installed.php @@ -0,0 +1,206 @@ + array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../../../../../', + 'aliases' => array(), + 'reference' => 'ac330ed6578aa9572539f5fc71c3cf6a1942f1d0', + 'name' => '__root__', + 'dev' => false, + ), + 'versions' => array( + '__root__' => array( + 'pretty_version' => 'dev-master', + 'version' => 'dev-master', + 'type' => 'library', + 'install_path' => __DIR__ . '/../../../../../../', + 'aliases' => array(), + 'reference' => 'ac330ed6578aa9572539f5fc71c3cf6a1942f1d0', + 'dev_requirement' => false, + ), + 'clue/stream-filter' => array( + 'pretty_version' => 'v1.5.0', + 'version' => '1.5.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../clue/stream-filter', + 'aliases' => array(), + 'reference' => 'aeb7d8ea49c7963d3b581378955dbf5bc49aa320', + 'dev_requirement' => false, + ), + 'evenement/evenement' => array( + 'pretty_version' => 'v3.0.1', + 'version' => '3.0.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../evenement/evenement', + 'aliases' => array(), + 'reference' => '531bfb9d15f8aa57454f5f0285b18bec903b8fb7', + 'dev_requirement' => false, + ), + 'guzzlehttp/psr7' => array( + 'pretty_version' => '1.8.3', + 'version' => '1.8.3.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../guzzlehttp/psr7', + 'aliases' => array(), + 'reference' => '1afdd860a2566ed3c2b0b4a3de6e23434a79ec85', + 'dev_requirement' => false, + ), + 'php-http/message' => array( + 'pretty_version' => '1.12.0', + 'version' => '1.12.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../php-http/message', + 'aliases' => array(), + 'reference' => '39eb7548be982a81085fe5a6e2a44268cd586291', + 'dev_requirement' => false, + ), + 'php-http/message-factory' => array( + 'pretty_version' => 'v1.0.2', + 'version' => '1.0.2.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../php-http/message-factory', + 'aliases' => array(), + 'reference' => 'a478cb11f66a6ac48d8954216cfed9aa06a501a1', + 'dev_requirement' => false, + ), + 'php-http/message-factory-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'plasticbrain/php-flash-messages' => array( + 'pretty_version' => 'v1.0.1', + 'version' => '1.0.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../plasticbrain/php-flash-messages', + 'aliases' => array(), + 'reference' => 'b565762619342057ce561de20d0f2f6e14f9aa77', + 'dev_requirement' => false, + ), + 'psr/http-message' => array( + 'pretty_version' => '1.0.1', + 'version' => '1.0.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../psr/http-message', + 'aliases' => array(), + 'reference' => 'f6561bf28d520154e4b0ec72be95418abe6d9363', + 'dev_requirement' => false, + ), + 'psr/http-message-implementation' => array( + 'dev_requirement' => false, + 'provided' => array( + 0 => '1.0', + ), + ), + 'ralouphie/getallheaders' => array( + 'pretty_version' => '3.0.3', + 'version' => '3.0.3.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ralouphie/getallheaders', + 'aliases' => array(), + 'reference' => '120b605dfeb996808c31b6477290a714d356e822', + 'dev_requirement' => false, + ), + 'react/cache' => array( + 'pretty_version' => 'v1.1.1', + 'version' => '1.1.1.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/cache', + 'aliases' => array(), + 'reference' => '4bf736a2cccec7298bdf745db77585966fc2ca7e', + 'dev_requirement' => false, + ), + 'react/dns' => array( + 'pretty_version' => 'v1.8.0', + 'version' => '1.8.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/dns', + 'aliases' => array(), + 'reference' => '2a5a74ab751e53863b45fb87e1d3913884f88248', + 'dev_requirement' => false, + ), + 'react/event-loop' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/event-loop', + 'aliases' => array(), + 'reference' => 'be6dee480fc4692cec0504e65eb486e3be1aa6f2', + 'dev_requirement' => false, + ), + 'react/http' => array( + 'pretty_version' => 'v1.5.0', + 'version' => '1.5.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/http', + 'aliases' => array(), + 'reference' => '8a0fd7c0aa74f0db3008b1e47ca86c613cbb040e', + 'dev_requirement' => false, + ), + 'react/promise' => array( + 'pretty_version' => 'v2.8.0', + 'version' => '2.8.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/promise', + 'aliases' => array(), + 'reference' => 'f3cff96a19736714524ca0dd1d4130de73dbbbc4', + 'dev_requirement' => false, + ), + 'react/promise-stream' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/promise-stream', + 'aliases' => array(), + 'reference' => '6384d8b76cf7dcc44b0bf3343fb2b2928412d1fe', + 'dev_requirement' => false, + ), + 'react/promise-timer' => array( + 'pretty_version' => 'v1.7.0', + 'version' => '1.7.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/promise-timer', + 'aliases' => array(), + 'reference' => '607dd79990e32fcb402cb0a176b4a4be12f97e7c', + 'dev_requirement' => false, + ), + 'react/socket' => array( + 'pretty_version' => 'v1.9.0', + 'version' => '1.9.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/socket', + 'aliases' => array(), + 'reference' => 'aa6e3f8ebcd6dec3ad1ee92a449b4cc341994001', + 'dev_requirement' => false, + ), + 'react/stream' => array( + 'pretty_version' => 'v1.2.0', + 'version' => '1.2.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../react/stream', + 'aliases' => array(), + 'reference' => '7a423506ee1903e89f1e08ec5f0ed430ff784ae9', + 'dev_requirement' => false, + ), + 'ringcentral/psr7' => array( + 'pretty_version' => '1.3.0', + 'version' => '1.3.0.0', + 'type' => 'library', + 'install_path' => __DIR__ . '/../ringcentral/psr7', + 'aliases' => array(), + 'reference' => '360faaec4b563958b673fb52bbe94e37f14bc686', + 'dev_requirement' => false, + ), + 'whmcsexpert/whmcsexpert' => array( + 'pretty_version' => 'dev-dev', + 'version' => 'dev-dev', + 'type' => 'library', + 'install_path' => __DIR__ . '/../whmcsexpert/whmcsexpert', + 'aliases' => array(), + 'reference' => '2ab629648dcb7133d24defe305b8b5f74a0d3953', + 'dev_requirement' => false, + ), + ), +); diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/composer/platform_check.php b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/platform_check.php new file mode 100644 index 0000000..6d3407d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/composer/platform_check.php @@ -0,0 +1,26 @@ += 70100)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 7.1.0". You are running ' . PHP_VERSION . '.'; +} + +if ($issues) { + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + if (!ini_get('display_errors')) { + if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { + fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); + } elseif (!headers_sent()) { + echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; + } + } + trigger_error( + 'Composer detected issues in your platform: ' . implode(' ', $issues), + E_USER_ERROR + ); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.gitignore b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.gitignore new file mode 100644 index 0000000..987e2a2 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.gitignore @@ -0,0 +1,2 @@ +composer.lock +vendor diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.travis.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.travis.yml new file mode 100644 index 0000000..65ba0ce --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/.travis.yml @@ -0,0 +1,24 @@ +language: php + +php: + - 7.0 + - 7.1 + - hhvm + - nightly + +matrix: + allow_failures: + - php: hhvm + - php: nightly + +before_script: + - wget http://getcomposer.org/composer.phar + - php composer.phar install + +script: + - ./vendor/bin/phpunit --coverage-text + - php -n examples/benchmark-emit-no-arguments.php + - php -n examples/benchmark-emit-one-argument.php + - php -n examples/benchmark-emit.php + - php -n examples/benchmark-emit-once.php + - php -n examples/benchmark-remove-listener-once.php diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/CHANGELOG.md new file mode 100644 index 0000000..568f229 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/CHANGELOG.md @@ -0,0 +1,35 @@ +CHANGELOG +========= + + +* v3.0.1 (2017-07-23) + + * Resolved regression introduced in once listeners in v3.0.0 [#49](https://github.com/igorw/evenement/pull/49) + +* v3.0.0 (2017-07-23) + + * Passing null as event name throw exception [#46](https://github.com/igorw/evenement/pull/46), and [#47](https://github.com/igorw/evenement/pull/47) + * Performance improvements [#39](https://github.com/igorw/evenement/pull/39), and [#45](https://github.com/igorw/evenement/pull/45) + * Remove once listeners [#44](https://github.com/igorw/evenement/pull/44), [#45](https://github.com/igorw/evenement/pull/45) + +* v2.1.0 (2017-07-17) + + * Chaining for "on" method [#30](https://github.com/igorw/evenement/pull/30) + * Unit tests (on Travis) improvements [#33](https://github.com/igorw/evenement/pull/33), [#36](https://github.com/igorw/evenement/pull/36), and [#37](https://github.com/igorw/evenement/pull/37) + * Benchmarks added [#35](https://github.com/igorw/evenement/pull/35), and [#40](https://github.com/igorw/evenement/pull/40) + * Minor performance improvements [#42](https://github.com/igorw/evenement/pull/42), and [#38](https://github.com/igorw/evenement/pull/38) + +* v2.0.0 (2012-11-02) + + * Require PHP >=5.4.0 + * Added EventEmitterTrait + * Removed EventEmitter2 + +* v1.1.0 (2017-07-17) + + * Chaining for "on" method [#29](https://github.com/igorw/evenement/pull/29) + * Minor performance improvements [#43](https://github.com/igorw/evenement/pull/43) + +* v1.0.0 (2012-05-30) + + * Inital stable release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/LICENSE new file mode 100644 index 0000000..d9a37d0 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/README.md new file mode 100644 index 0000000..9443011 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/README.md @@ -0,0 +1,83 @@ +# Événement + +Événement is a very simple event dispatching library for PHP. + +It has the same design goals as [Silex](http://silex-project.org) and +[Pimple](http://pimple-project.org), to empower the user while staying concise +and simple. + +It is very strongly inspired by the EventEmitter API found in +[node.js](http://nodejs.org). + +[![Build Status](https://secure.travis-ci.org/igorw/evenement.png?branch=master)](http://travis-ci.org/igorw/evenement) + +## Fetch + +The recommended way to install Événement is [through composer](http://getcomposer.org). + +Just create a composer.json file for your project: + +```JSON +{ + "require": { + "evenement/evenement": "^3.0 || ^2.0" + } +} +``` + +**Note:** The `3.x` version of Événement requires PHP 7 and the `2.x` version requires PHP 5.4. If you are +using PHP 5.3, please use the `1.x` version: + +```JSON +{ + "require": { + "evenement/evenement": "^1.0" + } +} +``` + +And run these two commands to install it: + + $ curl -s http://getcomposer.org/installer | php + $ php composer.phar install + +Now you can add the autoloader, and you will have access to the library: + +```php +on('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +### Emitting Events + +```php +emit('user.created', [$user]); +``` + +Tests +----- + + $ ./vendor/bin/phpunit + +License +------- +MIT, see LICENSE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/composer.json new file mode 100644 index 0000000..cbb4827 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/composer.json @@ -0,0 +1,29 @@ +{ + "name": "evenement/evenement", + "description": "Événement is a very simple event dispatching library for PHP", + "keywords": ["event-dispatcher", "event-emitter"], + "license": "MIT", + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit/phpunit": "^6.0" + }, + "autoload": { + "psr-0": { + "Evenement": "src" + } + }, + "autoload-dev": { + "psr-0": { + "Evenement": "tests" + }, + "files": ["tests/Evenement/Tests/functions.php"] + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/00-intro.md b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/00-intro.md new file mode 100644 index 0000000..6c28a2a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/00-intro.md @@ -0,0 +1,28 @@ +# Introduction + +Événement is is French and means "event". The événement library aims to +provide a simple way of subscribing to events and notifying those subscribers +whenever an event occurs. + +The API that it exposes is almost a direct port of the EventEmitter API found +in node.js. It also includes an "EventEmitter". There are some minor +differences however. + +The EventEmitter is an implementation of the publish-subscribe pattern, which +is a generalized version of the observer pattern. The observer pattern +specifies an observable subject, which observers can register themselves to. +Once something interesting happens, the subject notifies its observers. + +Pub/sub takes the same idea but encapsulates the observation logic inside a +separate object which manages all of its subscribers or listeners. Subscribers +are bound to an event name, and will only receive notifications of the events +they subscribed to. + +**TLDR: What does evenement do, in short? It provides a mapping from event +names to a list of listener functions and triggers each listener for a given +event when it is emitted.** + +Why do we do this, you ask? To achieve decoupling. + +It allows you to design a system where the core will emit events, and modules +are able to subscribe to these events. And respond to them. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/01-api.md b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/01-api.md new file mode 100644 index 0000000..17ba333 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/01-api.md @@ -0,0 +1,91 @@ +# API + +The API that événement exposes is defined by the +`Evenement\EventEmitterInterface`. The interface is useful if you want to +define an interface that extends the emitter and implicitly defines certain +events to be emitted, or if you want to type hint an `EventEmitter` to be +passed to a method without coupling to the specific implementation. + +## on($event, callable $listener) + +Allows you to subscribe to an event. + +Example: + +```php +$emitter->on('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +Since the listener can be any callable, you could also use an instance method +instead of the anonymous function: + +```php +$loggerSubscriber = new LoggerSubscriber($logger); +$emitter->on('user.created', array($loggerSubscriber, 'onUserCreated')); +``` + +This has the benefit that listener does not even need to know that the emitter +exists. + +You can also accept more than one parameter for the listener: + +```php +$emitter->on('numbers_added', function ($result, $a, $b) {}); +``` + +## once($event, callable $listener) + +Convenience method that adds a listener which is guaranteed to only be called +once. + +Example: + +```php +$conn->once('connected', function () use ($conn, $data) { + $conn->send($data); +}); +``` + +## emit($event, array $arguments = []) + +Emit an event, which will call all listeners. + +Example: + +```php +$conn->emit('data', [$data]); +``` + +The second argument to emit is an array of listener arguments. This is how you +specify more args: + +```php +$result = $a + $b; +$emitter->emit('numbers_added', [$result, $a, $b]); +``` + +## listeners($event) + +Allows you to inspect the listeners attached to an event. Particularly useful +to check if there are any listeners at all. + +Example: + +```php +$e = new \RuntimeException('Everything is broken!'); +if (0 === count($emitter->listeners('error'))) { + throw $e; +} +``` + +## removeListener($event, callable $listener) + +Remove a specific listener for a specific event. + +## removeAllListeners($event = null) + +Remove all listeners for a specific event or all listeners all together. This +is useful for long-running processes, where you want to remove listeners in +order to allow them to get garbage collected. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/02-plugin-system.md b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/02-plugin-system.md new file mode 100644 index 0000000..6a08371 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/doc/02-plugin-system.md @@ -0,0 +1,155 @@ +# Example: Plugin system + +In this example I will show you how to create a generic plugin system with +événement where plugins can alter the behaviour of the app. The app is a blog. +Boring, I know. By using the EventEmitter it will be easy to extend this blog +with additional functionality without modifying the core system. + +The blog is quite basic. Users are able to create blog posts when they log in. +The users are stored in a static config file, so there is no sign up process. +Once logged in they get a "new post" link which gives them a form where they +can create a new blog post with plain HTML. That will store the post in a +document database. The index lists all blog post titles by date descending. +Clicking on the post title will take you to the full post. + +## Plugin structure + +The goal of the plugin system is to allow features to be added to the blog +without modifying any core files of the blog. + +The plugins are managed through a config file, `plugins.json`. This JSON file +contains a JSON-encoded list of class-names for plugin classes. This allows +you to enable and disable plugins in a central location. The initial +`plugins.json` is just an empty array: +```json +[] +``` + +A plugin class must implement the `PluginInterface`: +```php +interface PluginInterface +{ + function attachEvents(EventEmitterInterface $emitter); +} +``` + +The `attachEvents` method allows the plugin to attach any events to the +emitter. For example: +```php +class FooPlugin implements PluginInterface +{ + public function attachEvents(EventEmitterInterface $emitter) + { + $emitter->on('foo', function () { + echo 'bar!'; + }); + } +} +``` + +The blog system creates an emitter instance and loads the plugins: +```php +$emitter = new EventEmitter(); + +$pluginClasses = json_decode(file_get_contents('plugins.json'), true); +foreach ($pluginClasses as $pluginClass) { + $plugin = new $pluginClass(); + $pluginClass->attachEvents($emitter); +} +``` + +This is the base system. There are no plugins yet, and there are no events yet +either. That's because I don't know which extension points will be needed. I +will add them on demand. + +## Feature: Markdown + +Writing blog posts in HTML sucks! Wouldn't it be great if I could write them +in a nice format such as markdown, and have that be converted to HTML for me? + +This feature will need two extension points. I need to be able to mark posts +as markdown, and I need to be able to hook into the rendering of the post body +and convert it from markdown to HTML. So the blog needs two new events: +`post.create` and `post.render`. + +In the code that creates the post, I'll insert the `post.create` event: +```php +class PostEvent +{ + public $post; + + public function __construct(array $post) + { + $this->post = $post; + } +} + +$post = createPostFromRequest($_POST); + +$event = new PostEvent($post); +$emitter->emit('post.create', [$event]); +$post = $event->post; + +$db->save('post', $post); +``` + +This shows that you can wrap a value in an event object to make it mutable, +allowing listeners to change it. + +The same thing for the `post.render` event: +```php +public function renderPostBody(array $post) +{ + $emitter = $this->emitter; + + $event = new PostEvent($post); + $emitter->emit('post.render', [$event]); + $post = $event->post; + + return $post['body']; +} + +

+

+``` + +Ok, the events are in place. It's time to create the first plugin, woohoo! I +will call this the `MarkdownPlugin`, so here's `plugins.json`: +```json +[ + "MarkdownPlugin" +] +``` + +The `MarkdownPlugin` class will be autoloaded, so I don't have to worry about +including any files. I just have to worry about implementing the plugin class. +The `markdown` function represents a markdown to HTML converter. +```php +class MarkdownPlugin implements PluginInterface +{ + public function attachEvents(EventEmitterInterface $emitter) + { + $emitter->on('post.create', function (PostEvent $event) { + $event->post['format'] = 'markdown'; + }); + + $emitter->on('post.render', function (PostEvent $event) { + if (isset($event->post['format']) && 'markdown' === $event->post['format']) { + $event->post['body'] = markdown($event->post['body']); + } + }); + } +} +``` + +There you go, the blog now renders posts as markdown. But all of the previous +posts before the addition of the markdown plugin are still rendered correctly +as raw HTML. + +## Feature: Comments + +TODO + +## Feature: Comment spam control + +TODO diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php new file mode 100644 index 0000000..53d7f4b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +const ITERATIONS = 10000000; + +use Evenement\EventEmitter; + +require __DIR__.'/../vendor/autoload.php'; + +$emitter = new EventEmitter(); + +$emitter->on('event', function () {}); + +$start = microtime(true); +for ($i = 0; $i < ITERATIONS; $i++) { + $emitter->emit('event'); +} +$time = microtime(true) - $start; + +echo 'Emitting ', number_format(ITERATIONS), ' events took: ', number_format($time, 2), 's', PHP_EOL; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-once.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-once.php new file mode 100644 index 0000000..74f4d17 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-once.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +ini_set('memory_limit', '512M'); + +const ITERATIONS = 100000; + +use Evenement\EventEmitter; + +require __DIR__.'/../vendor/autoload.php'; + +$emitter = new EventEmitter(); + +for ($i = 0; $i < ITERATIONS; $i++) { + $emitter->once('event', function ($a, $b, $c) {}); +} + +$start = microtime(true); +$emitter->emit('event', [1, 2, 3]); +$time = microtime(true) - $start; + +echo 'Emitting one event to ', number_format(ITERATIONS), ' once listeners took: ', number_format($time, 2), 's', PHP_EOL; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php new file mode 100644 index 0000000..39fc4ba --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +const ITERATIONS = 10000000; + +use Evenement\EventEmitter; + +require __DIR__.'/../vendor/autoload.php'; + +$emitter = new EventEmitter(); + +$emitter->on('event', function ($a) {}); + +$start = microtime(true); +for ($i = 0; $i < ITERATIONS; $i++) { + $emitter->emit('event', [1]); +} +$time = microtime(true) - $start; + +echo 'Emitting ', number_format(ITERATIONS), ' events took: ', number_format($time, 2), 's', PHP_EOL; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit.php new file mode 100644 index 0000000..3ab639e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-emit.php @@ -0,0 +1,28 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +const ITERATIONS = 10000000; + +use Evenement\EventEmitter; + +require __DIR__.'/../vendor/autoload.php'; + +$emitter = new EventEmitter(); + +$emitter->on('event', function ($a, $b, $c) {}); + +$start = microtime(true); +for ($i = 0; $i < ITERATIONS; $i++) { + $emitter->emit('event', [1, 2, 3]); +} +$time = microtime(true) - $start; + +echo 'Emitting ', number_format(ITERATIONS), ' events took: ', number_format($time, 2), 's', PHP_EOL; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php new file mode 100644 index 0000000..414be3b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +ini_set('memory_limit', '512M'); + +const ITERATIONS = 100000; + +use Evenement\EventEmitter; + +require __DIR__.'/../vendor/autoload.php'; + +$emitter = new EventEmitter(); + +$listeners = []; +for ($i = 0; $i < ITERATIONS; $i++) { + $listeners[] = function ($a, $b, $c) {}; +} + +$start = microtime(true); +foreach ($listeners as $listener) { + $emitter->once('event', $listener); +} +$time = microtime(true) - $start; +echo 'Adding ', number_format(ITERATIONS), ' once listeners took: ', number_format($time, 2), 's', PHP_EOL; + +$start = microtime(true); +foreach ($listeners as $listener) { + $emitter->removeListener('event', $listener); +} +$time = microtime(true) - $start; +echo 'Removing ', number_format(ITERATIONS), ' once listeners took: ', number_format($time, 2), 's', PHP_EOL; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/phpunit.xml.dist b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/phpunit.xml.dist new file mode 100644 index 0000000..70bc693 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/phpunit.xml.dist @@ -0,0 +1,24 @@ + + + + + + ./tests/Evenement/ + + + + + + ./src/ + + + diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitter.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitter.php new file mode 100644 index 0000000..db189b9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitter.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +class EventEmitter implements EventEmitterInterface +{ + use EventEmitterTrait; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php new file mode 100644 index 0000000..310631a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +interface EventEmitterInterface +{ + public function on($event, callable $listener); + public function once($event, callable $listener); + public function removeListener($event, callable $listener); + public function removeAllListeners($event = null); + public function listeners($event = null); + public function emit($event, array $arguments = []); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php new file mode 100644 index 0000000..a78e65c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php @@ -0,0 +1,135 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement; + +use InvalidArgumentException; + +trait EventEmitterTrait +{ + protected $listeners = []; + protected $onceListeners = []; + + public function on($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (!isset($this->listeners[$event])) { + $this->listeners[$event] = []; + } + + $this->listeners[$event][] = $listener; + + return $this; + } + + public function once($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (!isset($this->onceListeners[$event])) { + $this->onceListeners[$event] = []; + } + + $this->onceListeners[$event][] = $listener; + + return $this; + } + + public function removeListener($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (isset($this->listeners[$event])) { + $index = \array_search($listener, $this->listeners[$event], true); + if (false !== $index) { + unset($this->listeners[$event][$index]); + if (\count($this->listeners[$event]) === 0) { + unset($this->listeners[$event]); + } + } + } + + if (isset($this->onceListeners[$event])) { + $index = \array_search($listener, $this->onceListeners[$event], true); + if (false !== $index) { + unset($this->onceListeners[$event][$index]); + if (\count($this->onceListeners[$event]) === 0) { + unset($this->onceListeners[$event]); + } + } + } + } + + public function removeAllListeners($event = null) + { + if ($event !== null) { + unset($this->listeners[$event]); + } else { + $this->listeners = []; + } + + if ($event !== null) { + unset($this->onceListeners[$event]); + } else { + $this->onceListeners = []; + } + } + + public function listeners($event = null): array + { + if ($event === null) { + $events = []; + $eventNames = \array_unique( + \array_merge(\array_keys($this->listeners), \array_keys($this->onceListeners)) + ); + foreach ($eventNames as $eventName) { + $events[$eventName] = \array_merge( + isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : [], + isset($this->onceListeners[$eventName]) ? $this->onceListeners[$eventName] : [] + ); + } + return $events; + } + + return \array_merge( + isset($this->listeners[$event]) ? $this->listeners[$event] : [], + isset($this->onceListeners[$event]) ? $this->onceListeners[$event] : [] + ); + } + + public function emit($event, array $arguments = []) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + + if (isset($this->listeners[$event])) { + foreach ($this->listeners[$event] as $listener) { + $listener(...$arguments); + } + } + + if (isset($this->onceListeners[$event])) { + $listeners = $this->onceListeners[$event]; + unset($this->onceListeners[$event]); + foreach ($listeners as $listener) { + $listener(...$arguments); + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php new file mode 100644 index 0000000..28f3011 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php @@ -0,0 +1,438 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement\Tests; + +use Evenement\EventEmitter; +use InvalidArgumentException; +use PHPUnit\Framework\TestCase; + +class EventEmitterTest extends TestCase +{ + private $emitter; + + public function setUp() + { + $this->emitter = new EventEmitter(); + } + + public function testAddListenerWithLambda() + { + $this->emitter->on('foo', function () {}); + } + + public function testAddListenerWithMethod() + { + $listener = new Listener(); + $this->emitter->on('foo', [$listener, 'onFoo']); + } + + public function testAddListenerWithStaticMethod() + { + $this->emitter->on('bar', ['Evenement\Tests\Listener', 'onBar']); + } + + public function testAddListenerWithInvalidListener() + { + try { + $this->emitter->on('foo', 'not a callable'); + $this->fail(); + } catch (\Exception $e) { + } catch (\TypeError $e) { + } + } + + public function testOnce() + { + $listenerCalled = 0; + + $this->emitter->once('foo', function () use (&$listenerCalled) { + $listenerCalled++; + }); + + $this->assertSame(0, $listenerCalled); + + $this->emitter->emit('foo'); + + $this->assertSame(1, $listenerCalled); + + $this->emitter->emit('foo'); + + $this->assertSame(1, $listenerCalled); + } + + public function testOnceWithArguments() + { + $capturedArgs = []; + + $this->emitter->once('foo', function ($a, $b) use (&$capturedArgs) { + $capturedArgs = array($a, $b); + }); + + $this->emitter->emit('foo', array('a', 'b')); + + $this->assertSame(array('a', 'b'), $capturedArgs); + } + + public function testEmitWithoutArguments() + { + $listenerCalled = false; + + $this->emitter->on('foo', function () use (&$listenerCalled) { + $listenerCalled = true; + }); + + $this->assertSame(false, $listenerCalled); + $this->emitter->emit('foo'); + $this->assertSame(true, $listenerCalled); + } + + public function testEmitWithOneArgument() + { + $test = $this; + + $listenerCalled = false; + + $this->emitter->on('foo', function ($value) use (&$listenerCalled, $test) { + $listenerCalled = true; + + $test->assertSame('bar', $value); + }); + + $this->assertSame(false, $listenerCalled); + $this->emitter->emit('foo', ['bar']); + $this->assertSame(true, $listenerCalled); + } + + public function testEmitWithTwoArguments() + { + $test = $this; + + $listenerCalled = false; + + $this->emitter->on('foo', function ($arg1, $arg2) use (&$listenerCalled, $test) { + $listenerCalled = true; + + $test->assertSame('bar', $arg1); + $test->assertSame('baz', $arg2); + }); + + $this->assertSame(false, $listenerCalled); + $this->emitter->emit('foo', ['bar', 'baz']); + $this->assertSame(true, $listenerCalled); + } + + public function testEmitWithNoListeners() + { + $this->emitter->emit('foo'); + $this->emitter->emit('foo', ['bar']); + $this->emitter->emit('foo', ['bar', 'baz']); + } + + public function testEmitWithTwoListeners() + { + $listenersCalled = 0; + + $this->emitter->on('foo', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->emitter->on('foo', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(2, $listenersCalled); + } + + public function testRemoveListenerMatching() + { + $listenersCalled = 0; + + $listener = function () use (&$listenersCalled) { + $listenersCalled++; + }; + + $this->emitter->on('foo', $listener); + $this->emitter->removeListener('foo', $listener); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(0, $listenersCalled); + } + + public function testRemoveListenerNotMatching() + { + $listenersCalled = 0; + + $listener = function () use (&$listenersCalled) { + $listenersCalled++; + }; + + $this->emitter->on('foo', $listener); + $this->emitter->removeListener('bar', $listener); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenersCalled); + } + + public function testRemoveAllListenersMatching() + { + $listenersCalled = 0; + + $this->emitter->on('foo', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->emitter->removeAllListeners('foo'); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(0, $listenersCalled); + } + + public function testRemoveAllListenersNotMatching() + { + $listenersCalled = 0; + + $this->emitter->on('foo', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->emitter->removeAllListeners('bar'); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenersCalled); + } + + public function testRemoveAllListenersWithoutArguments() + { + $listenersCalled = 0; + + $this->emitter->on('foo', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->emitter->on('bar', function () use (&$listenersCalled) { + $listenersCalled++; + }); + + $this->emitter->removeAllListeners(); + + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->emitter->emit('bar'); + $this->assertSame(0, $listenersCalled); + } + + public function testCallablesClosure() + { + $calledWith = null; + + $this->emitter->on('foo', function ($data) use (&$calledWith) { + $calledWith = $data; + }); + + $this->emitter->emit('foo', ['bar']); + + self::assertSame('bar', $calledWith); + } + + public function testCallablesClass() + { + $listener = new Listener(); + $this->emitter->on('foo', [$listener, 'onFoo']); + + $this->emitter->emit('foo', ['bar']); + + self::assertSame(['bar'], $listener->getData()); + } + + + public function testCallablesClassInvoke() + { + $listener = new Listener(); + $this->emitter->on('foo', $listener); + + $this->emitter->emit('foo', ['bar']); + + self::assertSame(['bar'], $listener->getMagicData()); + } + + public function testCallablesStaticClass() + { + $this->emitter->on('foo', '\Evenement\Tests\Listener::onBar'); + + $this->emitter->emit('foo', ['bar']); + + self::assertSame(['bar'], Listener::getStaticData()); + } + + public function testCallablesFunction() + { + $this->emitter->on('foo', '\Evenement\Tests\setGlobalTestData'); + + $this->emitter->emit('foo', ['bar']); + + self::assertSame('bar', $GLOBALS['evenement-evenement-test-data']); + + unset($GLOBALS['evenement-evenement-test-data']); + } + + public function testListeners() + { + $onA = function () {}; + $onB = function () {}; + $onC = function () {}; + $onceA = function () {}; + $onceB = function () {}; + $onceC = function () {}; + + self::assertCount(0, $this->emitter->listeners('event')); + $this->emitter->on('event', $onA); + self::assertCount(1, $this->emitter->listeners('event')); + self::assertSame([$onA], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceA); + self::assertCount(2, $this->emitter->listeners('event')); + self::assertSame([$onA, $onceA], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceB); + self::assertCount(3, $this->emitter->listeners('event')); + self::assertSame([$onA, $onceA, $onceB], $this->emitter->listeners('event')); + $this->emitter->on('event', $onB); + self::assertCount(4, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceA, $onceB], $this->emitter->listeners('event')); + $this->emitter->removeListener('event', $onceA); + self::assertCount(3, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceB], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceC); + self::assertCount(4, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceB, $onceC], $this->emitter->listeners('event')); + $this->emitter->on('event', $onC); + self::assertCount(5, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onC, $onceB, $onceC], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceA); + self::assertCount(6, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onC, $onceB, $onceC, $onceA], $this->emitter->listeners('event')); + $this->emitter->removeListener('event', $onB); + self::assertCount(5, $this->emitter->listeners('event')); + self::assertSame([$onA, $onC, $onceB, $onceC, $onceA], $this->emitter->listeners('event')); + $this->emitter->emit('event'); + self::assertCount(2, $this->emitter->listeners('event')); + self::assertSame([$onA, $onC], $this->emitter->listeners('event')); + } + + public function testOnceCallIsNotRemovedWhenWorkingOverOnceListeners() + { + $aCalled = false; + $aCallable = function () use (&$aCalled) { + $aCalled = true; + }; + $bCalled = false; + $bCallable = function () use (&$bCalled, $aCallable) { + $bCalled = true; + $this->emitter->once('event', $aCallable); + }; + $this->emitter->once('event', $bCallable); + + self::assertFalse($aCalled); + self::assertFalse($bCalled); + $this->emitter->emit('event'); + + self::assertFalse($aCalled); + self::assertTrue($bCalled); + $this->emitter->emit('event'); + + self::assertTrue($aCalled); + self::assertTrue($bCalled); + } + + public function testEventNameMustBeStringOn() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + + $this->emitter->on(null, function () {}); + } + + public function testEventNameMustBeStringOnce() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + + $this->emitter->once(null, function () {}); + } + + public function testEventNameMustBeStringRemoveListener() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + + $this->emitter->removeListener(null, function () {}); + } + + public function testEventNameMustBeStringEmit() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + + $this->emitter->emit(null); + } + + public function testListenersGetAll() + { + $a = function () {}; + $b = function () {}; + $c = function () {}; + $d = function () {}; + + $this->emitter->once('event2', $c); + $this->emitter->on('event', $a); + $this->emitter->once('event', $b); + $this->emitter->on('event', $c); + $this->emitter->once('event', $d); + + self::assertSame( + [ + 'event' => [ + $a, + $c, + $b, + $d, + ], + 'event2' => [ + $c, + ], + ], + $this->emitter->listeners() + ); + } + + public function testOnceNestedCallRegression() + { + $first = 0; + $second = 0; + + $this->emitter->once('event', function () use (&$first, &$second) { + $first++; + $this->emitter->once('event', function () use (&$second) { + $second++; + }); + $this->emitter->emit('event'); + }); + $this->emitter->emit('event'); + + self::assertSame(1, $first); + self::assertSame(1, $second); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php new file mode 100644 index 0000000..df17424 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php @@ -0,0 +1,51 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement\Tests; + +class Listener +{ + private $data = []; + + private $magicData = []; + + private static $staticData = []; + + public function onFoo($data) + { + $this->data[] = $data; + } + + public function __invoke($data) + { + $this->magicData[] = $data; + } + + public static function onBar($data) + { + self::$staticData[] = $data; + } + + public function getData() + { + return $this->data; + } + + public function getMagicData() + { + return $this->magicData; + } + + public static function getStaticData() + { + return self::$staticData; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/functions.php new file mode 100644 index 0000000..7f11f5b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/evenement/evenement/tests/Evenement/Tests/functions.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Evenement\Tests; + +function setGlobalTestData($data) +{ + $GLOBALS['evenement-evenement-test-data'] = $data; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/FUNDING.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/FUNDING.yml new file mode 100644 index 0000000..7d222c5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: [Nyholm, GrahamCampbell] +tidelift: "packagist/guzzlehttp/psr7" diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/stale.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/stale.yml new file mode 100644 index 0000000..53faa71 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/stale.yml @@ -0,0 +1,14 @@ +daysUntilStale: 120 +daysUntilClose: 14 +exemptLabels: + - lifecycle/keep-open + - lifecycle/ready-for-merge +# Label to use when marking an issue as stale +staleLabel: lifecycle/stale +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed after 2 weeks if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/ci.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/ci.yml new file mode 100644 index 0000000..eda7dce --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: CI + +on: + pull_request: + +jobs: + build: + name: Build + runs-on: ubuntu-latest + strategy: + max-parallel: 10 + matrix: + php: ['5.5', '5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1'] + + steps: + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: 'none' + extensions: mbstring + + - name: Checkout code + uses: actions/checkout@v2 + + - name: Mimic PHP 8.0 + run: composer config platform.php 8.0.999 + if: matrix.php > 8 + + - name: Install dependencies + run: composer update --no-interaction --no-progress + + - name: Run tests + run: make test diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/integration.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/integration.yml new file mode 100644 index 0000000..3c31f9e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/integration.yml @@ -0,0 +1,37 @@ +name: Integration + +on: + pull_request: + +jobs: + + build: + name: Test + runs-on: ubuntu-latest + strategy: + max-parallel: 10 + matrix: + php: ['7.2', '7.3', '7.4', '8.0'] + + steps: + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + + - name: Checkout code + uses: actions/checkout@v2 + + - name: Download dependencies + uses: ramsey/composer-install@v1 + with: + composer-options: --no-interaction --optimize-autoloader + + - name: Start server + run: php -S 127.0.0.1:10002 tests/Integration/server.php & + + - name: Run tests + env: + TEST_SERVER: 127.0.0.1:10002 + run: ./vendor/bin/phpunit --testsuite Integration diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/static.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/static.yml new file mode 100644 index 0000000..ab4d68b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.github/workflows/static.yml @@ -0,0 +1,29 @@ +name: Static analysis + +on: + pull_request: + +jobs: + php-cs-fixer: + name: PHP-CS-Fixer + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '7.4' + coverage: none + extensions: mbstring + + - name: Download dependencies + run: composer update --no-interaction --no-progress + + - name: Download PHP CS Fixer + run: composer require "friendsofphp/php-cs-fixer:2.18.4" + + - name: Execute PHP CS Fixer + run: vendor/bin/php-cs-fixer fix --diff-format udiff --dry-run diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.php_cs.dist b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.php_cs.dist new file mode 100644 index 0000000..e4f0bd5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/.php_cs.dist @@ -0,0 +1,56 @@ +setRiskyAllowed(true) + ->setRules([ + '@PSR2' => true, + 'array_syntax' => ['syntax' => 'short'], + 'concat_space' => ['spacing' => 'one'], + 'declare_strict_types' => false, + 'final_static_access' => true, + 'fully_qualified_strict_types' => true, + 'header_comment' => false, + 'is_null' => ['use_yoda_style' => true], + 'list_syntax' => ['syntax' => 'long'], + 'lowercase_cast' => true, + 'magic_method_casing' => true, + 'modernize_types_casting' => true, + 'multiline_comment_opening_closing' => true, + 'no_alias_functions' => true, + 'no_alternative_syntax' => true, + 'no_blank_lines_after_phpdoc' => true, + 'no_empty_comment' => true, + 'no_empty_phpdoc' => true, + 'no_empty_statement' => true, + 'no_extra_blank_lines' => true, + 'no_leading_import_slash' => true, + 'no_trailing_comma_in_singleline_array' => true, + 'no_unset_cast' => true, + 'no_unused_imports' => true, + 'no_whitespace_in_blank_line' => true, + 'ordered_imports' => true, + 'php_unit_ordered_covers' => true, + 'php_unit_test_annotation' => ['style' => 'prefix'], + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'phpdoc_align' => ['align' => 'vertical'], + 'phpdoc_no_useless_inheritdoc' => true, + 'phpdoc_scalar' => true, + 'phpdoc_separation' => true, + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_trim' => true, + 'phpdoc_trim_consecutive_blank_line_separation' => true, + 'phpdoc_types' => true, + 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], + 'phpdoc_var_without_name' => true, + 'single_trait_insert_per_statement' => true, + 'standardize_not_equals' => true, + ]) + ->setFinder( + PhpCsFixer\Finder::create() + ->in(__DIR__.'/src') + ->in(__DIR__.'/tests') + ->name('*.php') + ) +; + +return $config; diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/CHANGELOG.md new file mode 100644 index 0000000..f40736c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/CHANGELOG.md @@ -0,0 +1,300 @@ +# Change Log + + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + + +## Unreleased + +## 1.8.3 - 2021-10-05 + +### Fixed + +- Return `null` in caching stream size if remote size is `null` + +## 1.8.2 - 2021-04-26 + +### Fixed + +- Handle possibly unset `url` in `stream_get_meta_data` + +## 1.8.1 - 2021-03-21 + +### Fixed + +- Issue parsing IPv6 URLs +- Issue modifying ServerRequest lost all its attributes + +## 1.8.0 - 2021-03-21 + +### Added + +- Locale independent URL parsing +- Most classes got a `@final` annotation to prepare for 2.0 + +### Fixed + +- Issue when creating stream from `php://input` and curl-ext is not installed +- Broken `Utils::tryFopen()` on PHP 8 + +## 1.7.0 - 2020-09-30 + +### Added + +- Replaced functions by static methods + +### Fixed + +- Converting a non-seekable stream to a string +- Handle multiple Set-Cookie correctly +- Ignore array keys in header values when merging +- Allow multibyte characters to be parsed in `Message:bodySummary()` + +### Changed + +- Restored partial HHVM 3 support + + +## [1.6.1] - 2019-07-02 + +### Fixed + +- Accept null and bool header values again + + +## [1.6.0] - 2019-06-30 + +### Added + +- Allowed version `^3.0` of `ralouphie/getallheaders` dependency (#244) +- Added MIME type for WEBP image format (#246) +- Added more validation of values according to PSR-7 and RFC standards, e.g. status code range (#250, #272) + +### Changed + +- Tests don't pass with HHVM 4.0, so HHVM support got dropped. Other libraries like composer have done the same. (#262) +- Accept port number 0 to be valid (#270) + +### Fixed + +- Fixed subsequent reads from `php://input` in ServerRequest (#247) +- Fixed readable/writable detection for certain stream modes (#248) +- Fixed encoding of special characters in the `userInfo` component of an URI (#253) + + +## [1.5.2] - 2018-12-04 + +### Fixed + +- Check body size when getting the message summary + + +## [1.5.1] - 2018-12-04 + +### Fixed + +- Get the summary of a body only if it is readable + + +## [1.5.0] - 2018-12-03 + +### Added + +- Response first-line to response string exception (fixes #145) +- A test for #129 behavior +- `get_message_body_summary` function in order to get the message summary +- `3gp` and `mkv` mime types + +### Changed + +- Clarify exception message when stream is detached + +### Deprecated + +- Deprecated parsing folded header lines as per RFC 7230 + +### Fixed + +- Fix `AppendStream::detach` to not close streams +- `InflateStream` preserves `isSeekable` attribute of the underlying stream +- `ServerRequest::getUriFromGlobals` to support URLs in query parameters + + +Several other fixes and improvements. + + +## [1.4.2] - 2017-03-20 + +### Fixed + +- Reverted BC break to `Uri::resolve` and `Uri::removeDotSegments` by removing + calls to `trigger_error` when deprecated methods are invoked. + + +## [1.4.1] - 2017-02-27 + +### Added + +- Rriggering of silenced deprecation warnings. + +### Fixed + +- Reverted BC break by reintroducing behavior to automagically fix a URI with a + relative path and an authority by adding a leading slash to the path. It's only + deprecated now. + + +## [1.4.0] - 2017-02-21 + +### Added + +- Added common URI utility methods based on RFC 3986 (see documentation in the readme): + - `Uri::isDefaultPort` + - `Uri::isAbsolute` + - `Uri::isNetworkPathReference` + - `Uri::isAbsolutePathReference` + - `Uri::isRelativePathReference` + - `Uri::isSameDocumentReference` + - `Uri::composeComponents` + - `UriNormalizer::normalize` + - `UriNormalizer::isEquivalent` + - `UriResolver::relativize` + +### Changed + +- Ensure `ServerRequest::getUriFromGlobals` returns a URI in absolute form. +- Allow `parse_response` to parse a response without delimiting space and reason. +- Ensure each URI modification results in a valid URI according to PSR-7 discussions. + Invalid modifications will throw an exception instead of returning a wrong URI or + doing some magic. + - `(new Uri)->withPath('foo')->withHost('example.com')` will throw an exception + because the path of a URI with an authority must start with a slash "/" or be empty + - `(new Uri())->withScheme('http')` will return `'http://localhost'` + +### Deprecated + +- `Uri::resolve` in favor of `UriResolver::resolve` +- `Uri::removeDotSegments` in favor of `UriResolver::removeDotSegments` + +### Fixed + +- `Stream::read` when length parameter <= 0. +- `copy_to_stream` reads bytes in chunks instead of `maxLen` into memory. +- `ServerRequest::getUriFromGlobals` when `Host` header contains port. +- Compatibility of URIs with `file` scheme and empty host. + + +## [1.3.1] - 2016-06-25 + +### Fixed + +- `Uri::__toString` for network path references, e.g. `//example.org`. +- Missing lowercase normalization for host. +- Handling of URI components in case they are `'0'` in a lot of places, + e.g. as a user info password. +- `Uri::withAddedHeader` to correctly merge headers with different case. +- Trimming of header values in `Uri::withAddedHeader`. Header values may + be surrounded by whitespace which should be ignored according to RFC 7230 + Section 3.2.4. This does not apply to header names. +- `Uri::withAddedHeader` with an array of header values. +- `Uri::resolve` when base path has no slash and handling of fragment. +- Handling of encoding in `Uri::with(out)QueryValue` so one can pass the + key/value both in encoded as well as decoded form to those methods. This is + consistent with withPath, withQuery etc. +- `ServerRequest::withoutAttribute` when attribute value is null. + + +## [1.3.0] - 2016-04-13 + +### Added + +- Remaining interfaces needed for full PSR7 compatibility + (ServerRequestInterface, UploadedFileInterface, etc.). +- Support for stream_for from scalars. + +### Changed + +- Can now extend Uri. + +### Fixed +- A bug in validating request methods by making it more permissive. + + +## [1.2.3] - 2016-02-18 + +### Fixed + +- Support in `GuzzleHttp\Psr7\CachingStream` for seeking forward on remote + streams, which can sometimes return fewer bytes than requested with `fread`. +- Handling of gzipped responses with FNAME headers. + + +## [1.2.2] - 2016-01-22 + +### Added + +- Support for URIs without any authority. +- Support for HTTP 451 'Unavailable For Legal Reasons.' +- Support for using '0' as a filename. +- Support for including non-standard ports in Host headers. + + +## [1.2.1] - 2015-11-02 + +### Changes + +- Now supporting negative offsets when seeking to SEEK_END. + + +## [1.2.0] - 2015-08-15 + +### Changed + +- Body as `"0"` is now properly added to a response. +- Now allowing forward seeking in CachingStream. +- Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +- functions.php is now conditionally required. +- user-info is no longer dropped when resolving URIs. + + +## [1.1.0] - 2015-06-24 + +### Changed + +- URIs can now be relative. +- `multipart/form-data` headers are now overridden case-insensitively. +- URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +- A port is no longer added to a URI when the scheme is missing and no port is + present. + + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` + + + +[1.6.0]: https://github.com/guzzle/psr7/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/guzzle/psr7/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/guzzle/psr7/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/guzzle/psr7/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/guzzle/psr7/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/guzzle/psr7/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/guzzle/psr7/compare/1.3.1...1.4.0 +[1.3.1]: https://github.com/guzzle/psr7/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/guzzle/psr7/compare/1.2.3...1.3.0 +[1.2.3]: https://github.com/guzzle/psr7/compare/1.2.2...1.2.3 +[1.2.2]: https://github.com/guzzle/psr7/compare/1.2.1...1.2.2 +[1.2.1]: https://github.com/guzzle/psr7/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/guzzle/psr7/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/guzzle/psr7/compare/1.0.0...1.1.0 diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/LICENSE new file mode 100644 index 0000000..51c7ec8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/LICENSE @@ -0,0 +1,26 @@ +The MIT License (MIT) + +Copyright (c) 2015 Michael Dowling +Copyright (c) 2015 Márk Sági-Kazár +Copyright (c) 2015 Graham Campbell +Copyright (c) 2016 Tobias Schultze +Copyright (c) 2016 George Mponos +Copyright (c) 2018 Tobias Nyholm + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/README.md new file mode 100644 index 0000000..464cae4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/README.md @@ -0,0 +1,824 @@ +# PSR-7 Message Implementation + +This repository contains a full [PSR-7](http://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. + + +[![Build Status](https://travis-ci.org/guzzle/psr7.svg?branch=master)](https://travis-ci.org/guzzle/psr7) + + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`GuzzleHttp\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use GuzzleHttp\Psr7; + +$a = Psr7\Utils::streamFor('abc, '); +$b = Psr7\Utils::streamFor('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\Utils::streamFor(' Above all listen to me')); + +echo $composed; // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`GuzzleHttp\Psr7\BufferStream` + +Provides a buffer stream that can be written to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use GuzzleHttp\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`GuzzleHttp\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use GuzzleHttp\Psr7; + +// Create an empty stream +$stream = Psr7\Utils::streamFor(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$dropping->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`GuzzleHttp\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing +to create a concrete class for a simple extension point. + +```php + +use GuzzleHttp\Psr7; + +$stream = Psr7\Utils::streamFor('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`GuzzleHttp\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate deflate or gzipped content. + +This stream decorator skips the first 10 bytes of the given stream to remove +the gzip header, converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`GuzzleHttp\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use GuzzleHttp\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`GuzzleHttp\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`GuzzleHttp\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`GuzzleHttp\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`GuzzleHttp\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`GuzzleHttp\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use GuzzleHttp\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use GuzzleHttp\Psr7; + +$original = Psr7\Utils::streamFor('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `GuzzleHttp\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `GuzzleHttp\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use GuzzleHttp\Psr7\StreamWrapper; + +$stream = GuzzleHttp\Psr7\Utils::streamFor('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Static API + +There are various static methods available under the `GuzzleHttp\Psr7` namespace. + + +## `GuzzleHttp\Psr7\Message::toString` + +`public static function toString(MessageInterface $message): string` + +Returns the string representation of an HTTP message. + +```php +$request = new GuzzleHttp\Psr7\Request('GET', 'http://example.com'); +echo GuzzleHttp\Psr7\Message::toString($request); +``` + + +## `GuzzleHttp\Psr7\Message::bodySummary` + +`public static function bodySummary(MessageInterface $message, int $truncateAt = 120): string|null` + +Get a short summary of the message body. + +Will return `null` if the response is not printable. + + +## `GuzzleHttp\Psr7\Message::rewindBody` + +`public static function rewindBody(MessageInterface $message): void` + +Attempts to rewind a message body and throws an exception on failure. + +The body of the message will only be rewound if a call to `tell()` +returns a value other than `0`. + + +## `GuzzleHttp\Psr7\Message::parseMessage` + +`public static function parseMessage(string $message): array` + +Parses an HTTP message into an associative array. + +The array contains the "start-line" key containing the start line of +the message, "headers" key containing an associative array of header +array values, and a "body" key containing the body of the message. + + +## `GuzzleHttp\Psr7\Message::parseRequestUri` + +`public static function parseRequestUri(string $path, array $headers): string` + +Constructs a URI for an HTTP request message. + + +## `GuzzleHttp\Psr7\Message::parseRequest` + +`public static function parseRequest(string $message): Request` + +Parses a request message string into a request object. + + +## `GuzzleHttp\Psr7\Message::parseResponse` + +`public static function parseResponse(string $message): Response` + +Parses a response message string into a response object. + + +## `GuzzleHttp\Psr7\Header::parse` + +`public static function parse(string|array $header): array` + +Parse an array of header values containing ";" separated data into an +array of associative arrays representing the header key value pair data +of the header. When a parameter does not contain a value, but just +contains a key, this function will inject a key with a '' string value. + + +## `GuzzleHttp\Psr7\Header::normalize` + +`public static function normalize(string|array $header): array` + +Converts an array of header values that may contain comma separated +headers into an array of headers with no comma separated values. + + +## `GuzzleHttp\Psr7\Query::parse` + +`public static function parse(string $str, int|bool $urlEncoding = true): array` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key +value pair will become an array. This function does not parse nested +PHP style arrays into an associative array (e.g., `foo[a]=1&foo[b]=2` +will be parsed into `['foo[a]' => '1', 'foo[b]' => '2'])`. + + +## `GuzzleHttp\Psr7\Query::build` + +`public static function build(array $params, int|false $encoding = PHP_QUERY_RFC3986): string` + +Build a query string from an array of key value pairs. + +This function can use the return value of `parse()` to build a query +string. This function does not modify the provided keys when an array is +encountered (like `http_build_query()` would). + + +## `GuzzleHttp\Psr7\Utils::caselessRemove` + +`public static function caselessRemove(iterable $keys, $keys, array $data): array` + +Remove the items given by the keys, case insensitively from the data. + + +## `GuzzleHttp\Psr7\Utils::copyToStream` + +`public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void` + +Copy the contents of a stream into another stream until the given number +of bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::copyToString` + +`public static function copyToString(StreamInterface $stream, int $maxLen = -1): string` + +Copy the contents of a stream into a string until the given number of +bytes have been read. + + +## `GuzzleHttp\Psr7\Utils::hash` + +`public static function hash(StreamInterface $stream, string $algo, bool $rawOutput = false): string` + +Calculate a hash of a stream. + +This method reads the entire stream to calculate a rolling hash, based on +PHP's `hash_init` functions. + + +## `GuzzleHttp\Psr7\Utils::modifyRequest` + +`public static function modifyRequest(RequestInterface $request, array $changes): RequestInterface` + +Clone and modify a request with the given changes. + +This method is useful for reducing the number of clones needed to mutate +a message. + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `GuzzleHttp\Psr7\Utils::readLine` + +`public static function readLine(StreamInterface $stream, int $maxLength = null): string` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `GuzzleHttp\Psr7\Utils::streamFor` + +`public static function streamFor(resource|string|null|int|float|bool|StreamInterface|callable|\Iterator $resource = '', array $options = []): StreamInterface` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +- metadata: Array of custom metadata. +- size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = GuzzleHttp\Psr7\Utils::streamFor('foo'); +$stream = GuzzleHttp\Psr7\Utils::streamFor(fopen('/path/to/file', 'r')); + +$generator = function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = GuzzleHttp\Psr7\Utils::streamFor($generator(100)); +``` + + +## `GuzzleHttp\Psr7\Utils::tryFopen` + +`public static function tryFopen(string $filename, string $mode): resource` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an +error handler that checks for errors and throws an exception instead. + + +## `GuzzleHttp\Psr7\Utils::uriFor` + +`public static function uriFor(string|UriInterface $uri): UriInterface` + +Returns a UriInterface for the given value. + +This function accepts a string or UriInterface and returns a +UriInterface for the given value. If the value is already a +UriInterface, it is returned as-is. + + +## `GuzzleHttp\Psr7\MimeType::fromFilename` + +`public static function fromFilename(string $filename): string|null` + +Determines the mimetype of a file by looking at its extension. + + +## `GuzzleHttp\Psr7\MimeType::fromExtension` + +`public static function fromExtension(string $extension): string|null` + +Maps a file extensions to a mimetype. + + +## Upgrading from Function API + +The static API was first introduced in 1.7.0, in order to mitigate problems with functions conflicting between global and local copies of the package. The function API will be removed in 2.0.0. A migration table has been provided here for your convenience: + +| Original Function | Replacement Method | +|----------------|----------------| +| `str` | `Message::toString` | +| `uri_for` | `Utils::uriFor` | +| `stream_for` | `Utils::streamFor` | +| `parse_header` | `Header::parse` | +| `normalize_header` | `Header::normalize` | +| `modify_request` | `Utils::modifyRequest` | +| `rewind_body` | `Message::rewindBody` | +| `try_fopen` | `Utils::tryFopen` | +| `copy_to_string` | `Utils::copyToString` | +| `copy_to_stream` | `Utils::copyToStream` | +| `hash` | `Utils::hash` | +| `readline` | `Utils::readLine` | +| `parse_request` | `Message::parseRequest` | +| `parse_response` | `Message::parseResponse` | +| `parse_query` | `Query::parse` | +| `build_query` | `Query::build` | +| `mimetype_from_filename` | `MimeType::fromFilename` | +| `mimetype_from_extension` | `MimeType::fromExtension` | +| `_parse_message` | `Message::parseMessage` | +| `_parse_request_uri` | `Message::parseRequestUri` | +| `get_message_body_summary` | `Message::bodySummary` | +| `_caseless_remove` | `Utils::caselessRemove` | + + +# Additional URI Methods + +Aside from the standard `Psr\Http\Message\UriInterface` implementation in form of the `GuzzleHttp\Psr7\Uri` class, +this library also provides additional functionality when working with URIs as static methods. + +## URI Types + +An instance of `Psr\Http\Message\UriInterface` can either be an absolute URI or a relative reference. +An absolute URI has a scheme. A relative reference is used to express a URI relative to another URI, +the base URI. Relative references can be divided into several forms according to +[RFC 3986 Section 4.2](https://tools.ietf.org/html/rfc3986#section-4.2): + +- network-path references, e.g. `//example.com/path` +- absolute-path references, e.g. `/path` +- relative-path references, e.g. `subpath` + +The following methods can be used to identify the type of the URI. + +### `GuzzleHttp\Psr7\Uri::isAbsolute` + +`public static function isAbsolute(UriInterface $uri): bool` + +Whether the URI is absolute, i.e. it has a scheme. + +### `GuzzleHttp\Psr7\Uri::isNetworkPathReference` + +`public static function isNetworkPathReference(UriInterface $uri): bool` + +Whether the URI is a network-path reference. A relative reference that begins with two slash characters is +termed an network-path reference. + +### `GuzzleHttp\Psr7\Uri::isAbsolutePathReference` + +`public static function isAbsolutePathReference(UriInterface $uri): bool` + +Whether the URI is a absolute-path reference. A relative reference that begins with a single slash character is +termed an absolute-path reference. + +### `GuzzleHttp\Psr7\Uri::isRelativePathReference` + +`public static function isRelativePathReference(UriInterface $uri): bool` + +Whether the URI is a relative-path reference. A relative reference that does not begin with a slash character is +termed a relative-path reference. + +### `GuzzleHttp\Psr7\Uri::isSameDocumentReference` + +`public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null): bool` + +Whether the URI is a same-document reference. A same-document reference refers to a URI that is, aside from its +fragment component, identical to the base URI. When no base URI is given, only an empty URI reference +(apart from its fragment) is considered a same-document reference. + +## URI Components + +Additional methods to work with URI components. + +### `GuzzleHttp\Psr7\Uri::isDefaultPort` + +`public static function isDefaultPort(UriInterface $uri): bool` + +Whether the URI has the default port of the current scheme. `Psr\Http\Message\UriInterface::getPort` may return null +or the standard port. This method can be used independently of the implementation. + +### `GuzzleHttp\Psr7\Uri::composeComponents` + +`public static function composeComponents($scheme, $authority, $path, $query, $fragment): string` + +Composes a URI reference string from its various components according to +[RFC 3986 Section 5.3](https://tools.ietf.org/html/rfc3986#section-5.3). Usually this method does not need to be called +manually but instead is used indirectly via `Psr\Http\Message\UriInterface::__toString`. + +### `GuzzleHttp\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts): UriInterface` + +Creates a URI from a hash of [`parse_url`](http://php.net/manual/en/function.parse-url.php) components. + + +### `GuzzleHttp\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value): UriInterface` + +Creates a new URI with a specific query string value. Any existing query string values that exactly match the +provided key are removed and replaced with the given key value pair. A value of null will set the query string +key without a value, e.g. "key" instead of "key=value". + +### `GuzzleHttp\Psr7\Uri::withQueryValues` + +`public static function withQueryValues(UriInterface $uri, array $keyValueArray): UriInterface` + +Creates a new URI with multiple query string values. It has the same behavior as `withQueryValue()` but for an +associative array of key => value. + +### `GuzzleHttp\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key): UriInterface` + +Creates a new URI with a specific query string value removed. Any existing query string values that exactly match the +provided key are removed. + +## Reference Resolution + +`GuzzleHttp\Psr7\UriResolver` provides methods to resolve a URI reference in the context of a base URI according +to [RFC 3986 Section 5](https://tools.ietf.org/html/rfc3986#section-5). This is for example also what web browsers +do when resolving a link in a website based on the current request URI. + +### `GuzzleHttp\Psr7\UriResolver::resolve` + +`public static function resolve(UriInterface $base, UriInterface $rel): UriInterface` + +Converts the relative URI into a new URI that is resolved against the base URI. + +### `GuzzleHttp\Psr7\UriResolver::removeDotSegments` + +`public static function removeDotSegments(string $path): string` + +Removes dot segments from a path and returns the new path according to +[RFC 3986 Section 5.2.4](https://tools.ietf.org/html/rfc3986#section-5.2.4). + +### `GuzzleHttp\Psr7\UriResolver::relativize` + +`public static function relativize(UriInterface $base, UriInterface $target): UriInterface` + +Returns the target URI as a relative reference from the base URI. This method is the counterpart to resolve(): + +```php +(string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) +``` + +One use-case is to use the current request URI as base URI and then generate relative links in your documents +to reduce the document size or offer self-contained downloadable document archives. + +```php +$base = new Uri('http://example.com/a/b/'); +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. +echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. +echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. +``` + +## Normalization and Comparison + +`GuzzleHttp\Psr7\UriNormalizer` provides methods to normalize and compare URIs according to +[RFC 3986 Section 6](https://tools.ietf.org/html/rfc3986#section-6). + +### `GuzzleHttp\Psr7\UriNormalizer::normalize` + +`public static function normalize(UriInterface $uri, $flags = self::PRESERVING_NORMALIZATIONS): UriInterface` + +Returns a normalized URI. The scheme and host component are already normalized to lowercase per PSR-7 UriInterface. +This methods adds additional normalizations that can be configured with the `$flags` parameter which is a bitmask +of normalizations to apply. The following normalizations are available: + +- `UriNormalizer::PRESERVING_NORMALIZATIONS` + + Default normalizations which only include the ones that preserve semantics. + +- `UriNormalizer::CAPITALIZE_PERCENT_ENCODING` + + All letters within a percent-encoding triplet (e.g., "%3A") are case-insensitive, and should be capitalized. + + Example: `http://example.org/a%c2%b1b` → `http://example.org/a%C2%B1b` + +- `UriNormalizer::DECODE_UNRESERVED_CHARACTERS` + + Decodes percent-encoded octets of unreserved characters. For consistency, percent-encoded octets in the ranges of + ALPHA (%41–%5A and %61–%7A), DIGIT (%30–%39), hyphen (%2D), period (%2E), underscore (%5F), or tilde (%7E) should + not be created by URI producers and, when found in a URI, should be decoded to their corresponding unreserved + characters by URI normalizers. + + Example: `http://example.org/%7Eusern%61me/` → `http://example.org/~username/` + +- `UriNormalizer::CONVERT_EMPTY_PATH` + + Converts the empty path to "/" for http and https URIs. + + Example: `http://example.org` → `http://example.org/` + +- `UriNormalizer::REMOVE_DEFAULT_HOST` + + Removes the default host of the given URI scheme from the URI. Only the "file" scheme defines the default host + "localhost". All of `file:/myfile`, `file:///myfile`, and `file://localhost/myfile` are equivalent according to + RFC 3986. + + Example: `file://localhost/myfile` → `file:///myfile` + +- `UriNormalizer::REMOVE_DEFAULT_PORT` + + Removes the default port of the given URI scheme from the URI. + + Example: `http://example.org:80/` → `http://example.org/` + +- `UriNormalizer::REMOVE_DOT_SEGMENTS` + + Removes unnecessary dot-segments. Dot-segments in relative-path references are not removed as it would + change the semantics of the URI reference. + + Example: `http://example.org/../a/b/../c/./d.html` → `http://example.org/a/c/d.html` + +- `UriNormalizer::REMOVE_DUPLICATE_SLASHES` + + Paths which include two or more adjacent slashes are converted to one. Webservers usually ignore duplicate slashes + and treat those URIs equivalent. But in theory those URIs do not need to be equivalent. So this normalization + may change the semantics. Encoded slashes (%2F) are not removed. + + Example: `http://example.org//foo///bar.html` → `http://example.org/foo/bar.html` + +- `UriNormalizer::SORT_QUERY_PARAMETERS` + + Sort query parameters with their values in alphabetical order. However, the order of parameters in a URI may be + significant (this is not defined by the standard). So this normalization is not safe and may change the semantics + of the URI. + + Example: `?lang=en&article=fred` → `?article=fred&lang=en` + +### `GuzzleHttp\Psr7\UriNormalizer::isEquivalent` + +`public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS): bool` + +Whether two URIs can be considered equivalent. Both URIs are normalized automatically before comparison with the given +`$normalizations` bitmask. The method also accepts relative URI references and returns true when they are equivalent. +This of course assumes they will be resolved against the same base URI. If this is not the case, determination of +equivalence or difference of relative references does not mean anything. + + +## Security + +If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/psr7/security/policy) for more information. + +## License + +Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information. + +## For Enterprise + +Available as part of the Tidelift Subscription + +The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-psr7?utm_source=packagist-guzzlehttp-psr7&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/composer.json new file mode 100644 index 0000000..bfa7cfd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/composer.json @@ -0,0 +1,73 @@ +{ + "name": "guzzlehttp/psr7", + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": ["request", "response", "message", "stream", "http", "uri", "url", "psr-7"], + "license": "MIT", + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "require": { + "php": ">=5.4.0", + "psr/http-message": "~1.0", + "ralouphie/getallheaders": "^2.0.5 || ^3.0.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.8.36 || ^5.7.27 || ^6.5.14 || ^7.5.20 || ^8.5.8 || ^9.3.10", + "ext-zlib": "*" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "autoload-dev": { + "psr-4": { + "GuzzleHttp\\Tests\\Psr7\\": "tests/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.7-dev" + } + }, + "config": { + "preferred-install": "dist", + "sort-packages": true + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/AppendStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/AppendStream.php new file mode 100644 index 0000000..fa9153d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/AppendStream.php @@ -0,0 +1,246 @@ +addStream($stream); + } + } + + public function __toString() + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Exception $e) { + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream) + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents() + { + return Utils::copyToString($this); + } + + /** + * Closes each attached stream. + * + * {@inheritdoc} + */ + public function close() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = []; + } + + /** + * Detaches each attached stream. + * + * Returns null as it's not clear which underlying stream resource to return. + * + * {@inheritdoc} + */ + public function detach() + { + $this->pos = $this->current = 0; + $this->seekable = true; + + foreach ($this->streams as $stream) { + $stream->detach(); + } + + $this->streams = []; + + return null; + } + + public function tell() + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + * + * {@inheritdoc} + */ + public function getSize() + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof() + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind() + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + * + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + * + * {@inheritdoc} + */ + public function read($length) + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + // Using a loose comparison here to match on '', false, and null + if ($result == null) { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return false; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + public function getMetadata($key = null) + { + return $key ? null : []; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/BufferStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/BufferStream.php new file mode 100644 index 0000000..783859c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/BufferStream.php @@ -0,0 +1,142 @@ +hwm = $hwm; + } + + public function __toString() + { + return $this->getContents(); + } + + public function getContents() + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close() + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize() + { + return strlen($this->buffer); + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return true; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof() + { + return strlen($this->buffer) === 0; + } + + public function tell() + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length) + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string) + { + $this->buffer .= $string; + + // TODO: What should happen here? + if (strlen($this->buffer) >= $this->hwm) { + return false; + } + + return strlen($string); + } + + public function getMetadata($key = null) + { + if ($key == 'hwm') { + return $this->hwm; + } + + return $key ? null : []; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/CachingStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/CachingStream.php new file mode 100644 index 0000000..febade9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/CachingStream.php @@ -0,0 +1,147 @@ +remoteStream = $stream; + $this->stream = $target ?: new Stream(Utils::tryFopen('php://temp', 'r+')); + } + + public function getSize() + { + $remoteSize = $this->remoteStream->getSize(); + + if (null === $remoteSize) { + return null; + } + + return max($this->stream->getSize(), $remoteSize); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + if ($whence == SEEK_SET) { + $byte = $offset; + } elseif ($whence == SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence == SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + $byte = $size + $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // Read the remoteStream until we have read in at least the amount + // of bytes requested, or we reach the end of the file. + while ($diff > 0 && !$this->remoteStream->eof()) { + $this->read($diff); + $diff = $byte - $this->stream->getSize(); + } + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length) + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string) + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof() + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close() + { + $this->remoteStream->close() && $this->stream->close(); + } + + private function cacheEntireStream() + { + $target = new FnStream(['write' => 'strlen']); + Utils::copyToStream($this, $target); + + return $this->tell(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php new file mode 100644 index 0000000..9f7420c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/DroppingStream.php @@ -0,0 +1,45 @@ +stream = $stream; + $this->maxLength = $maxLength; + } + + public function write($string) + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/FnStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/FnStream.php new file mode 100644 index 0000000..76a8cc7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/FnStream.php @@ -0,0 +1,163 @@ +methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * + * @throws \BadMethodCallException + */ + public function __get($name) + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * An unserialize would allow the __destruct to run when the unserialized value goes out of scope. + * + * @throws \LogicException + */ + public function __wakeup() + { + throw new \LogicException('FnStream should never be unserialized'); + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::$slots, array_keys($methods)) as $diff) { + $methods[$diff] = [$stream, $diff]; + } + + return new self($methods); + } + + public function __toString() + { + return call_user_func($this->_fn___toString); + } + + public function close() + { + return call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize() + { + return call_user_func($this->_fn_getSize); + } + + public function tell() + { + return call_user_func($this->_fn_tell); + } + + public function eof() + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable() + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind() + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET) + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable() + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string) + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable() + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length) + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents() + { + return call_user_func($this->_fn_getContents); + } + + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Header.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Header.php new file mode 100644 index 0000000..865d742 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Header.php @@ -0,0 +1,71 @@ +]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + + return $params; + } + + /** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @return array Returns the normalized header field values. + */ + public static function normalize($header) + { + if (!is_array($header)) { + return array_map('trim', explode(',', $header)); + } + + $result = []; + foreach ($header as $value) { + foreach ((array) $value as $v) { + if (strpos($v, ',') === false) { + $result[] = $v; + continue; + } + foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { + $result[] = trim($vv); + } + } + } + + return $result; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/InflateStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/InflateStream.php new file mode 100644 index 0000000..0cbd2cc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/InflateStream.php @@ -0,0 +1,56 @@ +read(10); + $filenameHeaderLength = $this->getLengthOfPossibleFilenameHeader($stream, $header); + // Skip the header, that is 10 + length of filename + 1 (nil) bytes + $stream = new LimitStream($stream, -1, 10 + $filenameHeaderLength); + $resource = StreamWrapper::getResource($stream); + stream_filter_append($resource, 'zlib.inflate', STREAM_FILTER_READ); + $this->stream = $stream->isSeekable() ? new Stream($resource) : new NoSeekStream(new Stream($resource)); + } + + /** + * @param StreamInterface $stream + * @param $header + * + * @return int + */ + private function getLengthOfPossibleFilenameHeader(StreamInterface $stream, $header) + { + $filename_header_length = 0; + + if (substr(bin2hex($header), 6, 2) === '08') { + // we have a filename, read until nil + $filename_header_length = 1; + while ($stream->read(1) !== chr(0)) { + $filename_header_length++; + } + } + + return $filename_header_length; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php new file mode 100644 index 0000000..911e127 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LazyOpenStream.php @@ -0,0 +1,42 @@ +filename = $filename; + $this->mode = $mode; + } + + /** + * Creates the underlying stream lazily when required. + * + * @return StreamInterface + */ + protected function createStream() + { + return Utils::streamFor(Utils::tryFopen($this->filename, $this->mode)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LimitStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LimitStream.php new file mode 100644 index 0000000..1173ec4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/LimitStream.php @@ -0,0 +1,157 @@ +stream = $stream; + $this->setLimit($limit); + $this->setOffset($offset); + } + + public function eof() + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit == -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + * {@inheritdoc} + */ + public function getSize() + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit == -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset %s with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + * {@inheritdoc} + */ + public function tell() + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset($offset) + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit($limit) + { + $this->limit = $limit; + } + + public function read($length) + { + if ($this->limit == -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Message.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Message.php new file mode 100644 index 0000000..516d1cb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Message.php @@ -0,0 +1,252 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + if (strtolower($name) === 'set-cookie') { + foreach ($values as $value) { + $msg .= "\r\n{$name}: " . $value; + } + } else { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + } + + return "{$msg}\r\n\r\n" . $message->getBody(); + } + + /** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + * + * @return string|null + */ + public static function bodySummary(MessageInterface $message, $truncateAt = 120) + { + $body = $message->getBody(); + + if (!$body->isSeekable() || !$body->isReadable()) { + return null; + } + + $size = $body->getSize(); + + if ($size === 0) { + return null; + } + + $summary = $body->read($truncateAt); + $body->rewind(); + + if ($size > $truncateAt) { + $summary .= ' (truncated...)'; + } + + // Matches any printable character, including unicode characters: + // letters, marks, numbers, punctuation, spacing, and separators. + if (preg_match('/[^\pL\pM\pN\pP\pS\pZ\n\r\t]/u', $summary)) { + return null; + } + + return $summary; + } + + /** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` + * returns a value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ + public static function rewindBody(MessageInterface $message) + { + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } + } + + /** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + * + * @return array + */ + public static function parseMessage($message) + { + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + $message = ltrim($message, "\r\n"); + + $messageParts = preg_split("/\r?\n\r?\n/", $message, 2); + + if ($messageParts === false || count($messageParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing header delimiter'); + } + + list($rawHeaders, $body) = $messageParts; + $rawHeaders .= "\r\n"; // Put back the delimiter we split previously + $headerParts = preg_split("/\r?\n/", $rawHeaders, 2); + + if ($headerParts === false || count($headerParts) !== 2) { + throw new \InvalidArgumentException('Invalid message: Missing status line'); + } + + list($startLine, $rawHeaders) = $headerParts; + + if (preg_match("/(?:^HTTP\/|^[A-Z]+ \S+ HTTP\/)(\d+(?:\.\d+)?)/i", $startLine, $matches) && $matches[1] === '1.0') { + // Header folding is deprecated for HTTP/1.1, but allowed in HTTP/1.0 + $rawHeaders = preg_replace(Rfc7230::HEADER_FOLD_REGEX, ' ', $rawHeaders); + } + + /** @var array[] $headerLines */ + $count = preg_match_all(Rfc7230::HEADER_REGEX, $rawHeaders, $headerLines, PREG_SET_ORDER); + + // If these aren't the same, then one line didn't match and there's an invalid header. + if ($count !== substr_count($rawHeaders, "\n")) { + // Folding is deprecated, see https://tools.ietf.org/html/rfc7230#section-3.2.4 + if (preg_match(Rfc7230::HEADER_FOLD_REGEX, $rawHeaders)) { + throw new \InvalidArgumentException('Invalid header syntax: Obsolete line folding'); + } + + throw new \InvalidArgumentException('Invalid header syntax'); + } + + $headers = []; + + foreach ($headerLines as $headerLine) { + $headers[$headerLine[1]][] = $headerLine[2]; + } + + return [ + 'start-line' => $startLine, + 'headers' => $headers, + 'body' => $body, + ]; + } + + /** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + * + * @return string + */ + public static function parseRequestUri($path, array $headers) + { + $hostKey = array_filter(array_keys($headers), function ($k) { + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); + } + + /** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + * + * @return Request + */ + public static function parseRequest($message) + { + $data = self::parseMessage($message); + $matches = []; + if (!preg_match('/^[\S]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $version = isset($parts[2]) ? explode('/', $parts[2])[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? self::parseRequestUri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); + } + + /** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + * + * @return Response + */ + public static function parseResponse($message) + { + $data = self::parseMessage($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string: ' . $data['start-line']); + } + $parts = explode(' ', $data['start-line'], 3); + + return new Response( + (int) $parts[1], + $data['headers'], + $data['body'], + explode('/', $parts[0])[1], + isset($parts[2]) ? $parts[2] : null + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php new file mode 100644 index 0000000..99203bb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MessageTrait.php @@ -0,0 +1,214 @@ + array of values */ + private $headers = []; + + /** @var array Map of lowercase header name => original name at registration */ + private $headerNames = []; + + /** @var string */ + private $protocol = '1.1'; + + /** @var StreamInterface|null */ + private $stream; + + public function getProtocolVersion() + { + return $this->protocol; + } + + public function withProtocolVersion($version) + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders() + { + return $this->headers; + } + + public function hasHeader($header) + { + return isset($this->headerNames[strtolower($header)]); + } + + public function getHeader($header) + { + $header = strtolower($header); + + if (!isset($this->headerNames[$header])) { + return []; + } + + $header = $this->headerNames[$header]; + + return $this->headers[$header]; + } + + public function getHeaderLine($header) + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value) + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + unset($new->headers[$new->headerNames[$normalized]]); + } + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + + return $new; + } + + public function withAddedHeader($header, $value) + { + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + + $new = clone $this; + if (isset($new->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $new->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $new->headerNames[$normalized] = $header; + $new->headers[$header] = $value; + } + + return $new; + } + + public function withoutHeader($header) + { + $normalized = strtolower($header); + + if (!isset($this->headerNames[$normalized])) { + return $this; + } + + $header = $this->headerNames[$normalized]; + + $new = clone $this; + unset($new->headers[$header], $new->headerNames[$normalized]); + + return $new; + } + + public function getBody() + { + if (!$this->stream) { + $this->stream = Utils::streamFor(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body) + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + private function setHeaders(array $headers) + { + $this->headerNames = $this->headers = []; + foreach ($headers as $header => $value) { + if (is_int($header)) { + // Numeric array keys are converted to int by PHP but having a header name '123' is not forbidden by the spec + // and also allowed in withHeader(). So we need to cast it to string again for the following assertion to pass. + $header = (string) $header; + } + $this->assertHeader($header); + $value = $this->normalizeHeaderValue($value); + $normalized = strtolower($header); + if (isset($this->headerNames[$normalized])) { + $header = $this->headerNames[$normalized]; + $this->headers[$header] = array_merge($this->headers[$header], $value); + } else { + $this->headerNames[$normalized] = $header; + $this->headers[$header] = $value; + } + } + } + + private function normalizeHeaderValue($value) + { + if (!is_array($value)) { + return $this->trimHeaderValues([$value]); + } + + if (count($value) === 0) { + throw new \InvalidArgumentException('Header value can not be an empty array.'); + } + + return $this->trimHeaderValues($value); + } + + /** + * Trims whitespace from the header values. + * + * Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field. + * + * header-field = field-name ":" OWS field-value OWS + * OWS = *( SP / HTAB ) + * + * @param string[] $values Header values + * + * @return string[] Trimmed header values + * + * @see https://tools.ietf.org/html/rfc7230#section-3.2.4 + */ + private function trimHeaderValues(array $values) + { + return array_map(function ($value) { + if (!is_scalar($value) && null !== $value) { + throw new \InvalidArgumentException(sprintf( + 'Header value must be scalar or null but %s provided.', + is_object($value) ? get_class($value) : gettype($value) + )); + } + + return trim((string) $value, " \t"); + }, array_values($values)); + } + + private function assertHeader($header) + { + if (!is_string($header)) { + throw new \InvalidArgumentException(sprintf( + 'Header name must be a string but %s provided.', + is_object($header) ? get_class($header) : gettype($header) + )); + } + + if ($header === '') { + throw new \InvalidArgumentException('Header name can not be empty.'); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MimeType.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MimeType.php new file mode 100644 index 0000000..205c7b1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MimeType.php @@ -0,0 +1,140 @@ + 'video/3gpp', + '7z' => 'application/x-7z-compressed', + 'aac' => 'audio/x-aac', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'asc' => 'text/plain', + 'asf' => 'video/x-ms-asf', + 'atom' => 'application/atom+xml', + 'avi' => 'video/x-msvideo', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bzip2', + 'cer' => 'application/pkix-cert', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'css' => 'text/css', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'deb' => 'application/x-debian-package', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dvi' => 'application/x-dvi', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'etx' => 'text/x-setext', + 'flac' => 'audio/flac', + 'flv' => 'video/x-flv', + 'gif' => 'image/gif', + 'gz' => 'application/gzip', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ini' => 'text/plain', + 'iso' => 'application/x-iso9660-image', + 'jar' => 'application/java-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'latex' => 'application/x-latex', + 'log' => 'text/plain', + 'm4a' => 'audio/mp4', + 'm4v' => 'video/mp4', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mkv' => 'video/x-matroska', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4v' => 'video/mp4', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'pbm' => 'image/x-portable-bitmap', + 'pdf' => 'application/pdf', + 'pgm' => 'image/x-portable-graymap', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'ppm' => 'image/x-portable-pixmap', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'qt' => 'video/quicktime', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'svg' => 'image/svg+xml', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'torrent' => 'application/x-bittorrent', + 'ttf' => 'application/x-font-ttf', + 'txt' => 'text/plain', + 'wav' => 'audio/x-wav', + 'webm' => 'video/webm', + 'webp' => 'image/webp', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'video/x-ms-wmv', + 'woff' => 'application/x-font-woff', + 'wsdl' => 'application/wsdl+xml', + 'xbm' => 'image/x-xbitmap', + 'xls' => 'application/vnd.ms-excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'yaml' => 'text/yaml', + 'yml' => 'text/yaml', + 'zip' => 'application/zip', + ]; + + $extension = strtolower($extension); + + return isset($mimetypes[$extension]) + ? $mimetypes[$extension] + : null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php new file mode 100644 index 0000000..5a6079a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/MultipartStream.php @@ -0,0 +1,158 @@ +boundary = $boundary ?: sha1(uniqid('', true)); + $this->stream = $this->createStream($elements); + } + + /** + * Get the boundary + * + * @return string + */ + public function getBoundary() + { + return $this->boundary; + } + + public function isWritable() + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + */ + private function getHeaders(array $headers) + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements) + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(Utils::streamFor("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element) + { + foreach (['contents', 'name'] as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = Utils::streamFor($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if (substr($uri, 0, 6) !== 'php://') { + $element['filename'] = $uri; + } + } + + list($body, $headers) = $this->createElement( + $element['name'], + $element['contents'], + isset($element['filename']) ? $element['filename'] : null, + isset($element['headers']) ? $element['headers'] : [] + ); + + $stream->addStream(Utils::streamFor($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(Utils::streamFor("\r\n")); + } + + /** + * @return array + */ + private function createElement($name, StreamInterface $stream, $filename, array $headers) + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = ($filename === '0' || $filename) + ? sprintf( + 'form-data; name="%s"; filename="%s"', + $name, + basename($filename) + ) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && ($filename === '0' || $filename)) { + if ($type = MimeType::fromFilename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return [$stream, $headers]; + } + + private function getHeader(array $headers, $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..d66bdde --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/NoSeekStream.php @@ -0,0 +1,25 @@ +source = $source; + $this->size = isset($options['size']) ? $options['size'] : null; + $this->metadata = isset($options['metadata']) ? $options['metadata'] : []; + $this->buffer = new BufferStream(); + } + + public function __toString() + { + try { + return Utils::copyToString($this); + } catch (\Exception $e) { + return ''; + } + } + + public function close() + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = false; + $this->source = null; + + return null; + } + + public function getSize() + { + return $this->size; + } + + public function tell() + { + return $this->tellPos; + } + + public function eof() + { + return !$this->source; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable() + { + return false; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable() + { + return true; + } + + public function read($length) + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents() + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return isset($this->metadata[$key]) ? $this->metadata[$key] : null; + } + + private function pump($length) + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Query.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Query.php new file mode 100644 index 0000000..5a7cc03 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Query.php @@ -0,0 +1,113 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + * + * @return array + */ + public static function parse($str, $urlEncoding = true) + { + $result = []; + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', $value)); + }; + } elseif ($urlEncoding === PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding === PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { + return $str; + }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!isset($result[$key])) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = [$result[$key]]; + } + $result[$key][] = $value; + } + } + + return $result; + } + + /** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + * + * @return string + */ + public static function build(array $params, $encoding = PHP_QUERY_RFC3986) + { + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function ($str) { + return $str; + }; + } elseif ($encoding === PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding === PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder($k); + if (!is_array($v)) { + $qs .= $k; + if ($v !== null) { + $qs .= '=' . $encoder($v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + if ($vv !== null) { + $qs .= '=' . $encoder($vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Request.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Request.php new file mode 100644 index 0000000..c1cdaeb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Request.php @@ -0,0 +1,152 @@ +assertMethod($method); + if (!($uri instanceof UriInterface)) { + $uri = new Uri($uri); + } + + $this->method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $version; + + if (!isset($this->headerNames['host'])) { + $this->updateHostFromUri(); + } + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + } + + public function getRequestTarget() + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target == '') { + $target = '/'; + } + if ($this->uri->getQuery() != '') { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget) + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod() + { + return $this->method; + } + + public function withMethod($method) + { + $this->assertMethod($method); + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri() + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false) + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost || !isset($this->headerNames['host'])) { + $new->updateHostFromUri(); + } + + return $new; + } + + private function updateHostFromUri() + { + $host = $this->uri->getHost(); + + if ($host == '') { + return; + } + + if (($port = $this->uri->getPort()) !== null) { + $host .= ':' . $port; + } + + if (isset($this->headerNames['host'])) { + $header = $this->headerNames['host']; + } else { + $header = 'Host'; + $this->headerNames['host'] = 'Host'; + } + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + $this->headers = [$header => [$host]] + $this->headers; + } + + private function assertMethod($method) + { + if (!is_string($method) || $method === '') { + throw new \InvalidArgumentException('Method must be a non-empty string.'); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Response.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Response.php new file mode 100644 index 0000000..8c01a0f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Response.php @@ -0,0 +1,155 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 451 => 'Unavailable For Legal Reasons', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 511 => 'Network Authentication Required', + ]; + + /** @var string */ + private $reasonPhrase = ''; + + /** @var int */ + private $statusCode = 200; + + /** + * @param int $status Status code + * @param array $headers Response headers + * @param string|resource|StreamInterface|null $body Response body + * @param string $version Protocol version + * @param string|null $reason Reason phrase (when empty a default will be used based on the status code) + */ + public function __construct( + $status = 200, + array $headers = [], + $body = null, + $version = '1.1', + $reason = null + ) { + $this->assertStatusCodeIsInteger($status); + $status = (int) $status; + $this->assertStatusCodeRange($status); + + $this->statusCode = $status; + + if ($body !== '' && $body !== null) { + $this->stream = Utils::streamFor($body); + } + + $this->setHeaders($headers); + if ($reason == '' && isset(self::$phrases[$this->statusCode])) { + $this->reasonPhrase = self::$phrases[$this->statusCode]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode() + { + return $this->statusCode; + } + + public function getReasonPhrase() + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = '') + { + $this->assertStatusCodeIsInteger($code); + $code = (int) $code; + $this->assertStatusCodeRange($code); + + $new = clone $this; + $new->statusCode = $code; + if ($reasonPhrase == '' && isset(self::$phrases[$new->statusCode])) { + $reasonPhrase = self::$phrases[$new->statusCode]; + } + $new->reasonPhrase = (string) $reasonPhrase; + return $new; + } + + private function assertStatusCodeIsInteger($statusCode) + { + if (filter_var($statusCode, FILTER_VALIDATE_INT) === false) { + throw new \InvalidArgumentException('Status code must be an integer value.'); + } + } + + private function assertStatusCodeRange($statusCode) + { + if ($statusCode < 100 || $statusCode >= 600) { + throw new \InvalidArgumentException('Status code must be an integer value between 1xx and 5xx.'); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php new file mode 100644 index 0000000..51b571f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Rfc7230.php @@ -0,0 +1,19 @@ +@,;:\\\"/[\]?={}\x01-\x20\x7F]++):[ \t]*+((?:[ \t]*+[\x21-\x7E\x80-\xFF]++)*+)[ \t]*+\r?\n)m"; + const HEADER_FOLD_REGEX = "(\r?\n[ \t]++)"; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php new file mode 100644 index 0000000..e6d26f5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/ServerRequest.php @@ -0,0 +1,379 @@ +serverParams = $serverParams; + + parent::__construct($method, $uri, $headers, $body, $version); + } + + /** + * Return an UploadedFile instance array. + * + * @param array $files A array which respect $_FILES structure + * + * @return array + * + * @throws InvalidArgumentException for unrecognized values + */ + public static function normalizeFiles(array $files) + { + $normalized = []; + + foreach ($files as $key => $value) { + if ($value instanceof UploadedFileInterface) { + $normalized[$key] = $value; + } elseif (is_array($value) && isset($value['tmp_name'])) { + $normalized[$key] = self::createUploadedFileFromSpec($value); + } elseif (is_array($value)) { + $normalized[$key] = self::normalizeFiles($value); + continue; + } else { + throw new InvalidArgumentException('Invalid value in files specification'); + } + } + + return $normalized; + } + + /** + * Create and return an UploadedFile instance from a $_FILES specification. + * + * If the specification represents an array of values, this method will + * delegate to normalizeNestedFileSpec() and return that return value. + * + * @param array $value $_FILES struct + * + * @return array|UploadedFileInterface + */ + private static function createUploadedFileFromSpec(array $value) + { + if (is_array($value['tmp_name'])) { + return self::normalizeNestedFileSpec($value); + } + + return new UploadedFile( + $value['tmp_name'], + (int) $value['size'], + (int) $value['error'], + $value['name'], + $value['type'] + ); + } + + /** + * Normalize an array of file specifications. + * + * Loops through all nested files and returns a normalized array of + * UploadedFileInterface instances. + * + * @param array $files + * + * @return UploadedFileInterface[] + */ + private static function normalizeNestedFileSpec(array $files = []) + { + $normalizedFiles = []; + + foreach (array_keys($files['tmp_name']) as $key) { + $spec = [ + 'tmp_name' => $files['tmp_name'][$key], + 'size' => $files['size'][$key], + 'error' => $files['error'][$key], + 'name' => $files['name'][$key], + 'type' => $files['type'][$key], + ]; + $normalizedFiles[$key] = self::createUploadedFileFromSpec($spec); + } + + return $normalizedFiles; + } + + /** + * Return a ServerRequest populated with superglobals: + * $_GET + * $_POST + * $_COOKIE + * $_FILES + * $_SERVER + * + * @return ServerRequestInterface + */ + public static function fromGlobals() + { + $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; + $headers = getallheaders(); + $uri = self::getUriFromGlobals(); + $body = new CachingStream(new LazyOpenStream('php://input', 'r+')); + $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? str_replace('HTTP/', '', $_SERVER['SERVER_PROTOCOL']) : '1.1'; + + $serverRequest = new ServerRequest($method, $uri, $headers, $body, $protocol, $_SERVER); + + return $serverRequest + ->withCookieParams($_COOKIE) + ->withQueryParams($_GET) + ->withParsedBody($_POST) + ->withUploadedFiles(self::normalizeFiles($_FILES)); + } + + private static function extractHostAndPortFromAuthority($authority) + { + $uri = 'http://' . $authority; + $parts = parse_url($uri); + if (false === $parts) { + return [null, null]; + } + + $host = isset($parts['host']) ? $parts['host'] : null; + $port = isset($parts['port']) ? $parts['port'] : null; + + return [$host, $port]; + } + + /** + * Get a Uri populated with values from $_SERVER. + * + * @return UriInterface + */ + public static function getUriFromGlobals() + { + $uri = new Uri(''); + + $uri = $uri->withScheme(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http'); + + $hasPort = false; + if (isset($_SERVER['HTTP_HOST'])) { + list($host, $port) = self::extractHostAndPortFromAuthority($_SERVER['HTTP_HOST']); + if ($host !== null) { + $uri = $uri->withHost($host); + } + + if ($port !== null) { + $hasPort = true; + $uri = $uri->withPort($port); + } + } elseif (isset($_SERVER['SERVER_NAME'])) { + $uri = $uri->withHost($_SERVER['SERVER_NAME']); + } elseif (isset($_SERVER['SERVER_ADDR'])) { + $uri = $uri->withHost($_SERVER['SERVER_ADDR']); + } + + if (!$hasPort && isset($_SERVER['SERVER_PORT'])) { + $uri = $uri->withPort($_SERVER['SERVER_PORT']); + } + + $hasQuery = false; + if (isset($_SERVER['REQUEST_URI'])) { + $requestUriParts = explode('?', $_SERVER['REQUEST_URI'], 2); + $uri = $uri->withPath($requestUriParts[0]); + if (isset($requestUriParts[1])) { + $hasQuery = true; + $uri = $uri->withQuery($requestUriParts[1]); + } + } + + if (!$hasQuery && isset($_SERVER['QUERY_STRING'])) { + $uri = $uri->withQuery($_SERVER['QUERY_STRING']); + } + + return $uri; + } + + /** + * {@inheritdoc} + */ + public function getServerParams() + { + return $this->serverParams; + } + + /** + * {@inheritdoc} + */ + public function getUploadedFiles() + { + return $this->uploadedFiles; + } + + /** + * {@inheritdoc} + */ + public function withUploadedFiles(array $uploadedFiles) + { + $new = clone $this; + $new->uploadedFiles = $uploadedFiles; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getCookieParams() + { + return $this->cookieParams; + } + + /** + * {@inheritdoc} + */ + public function withCookieParams(array $cookies) + { + $new = clone $this; + $new->cookieParams = $cookies; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getQueryParams() + { + return $this->queryParams; + } + + /** + * {@inheritdoc} + */ + public function withQueryParams(array $query) + { + $new = clone $this; + $new->queryParams = $query; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getParsedBody() + { + return $this->parsedBody; + } + + /** + * {@inheritdoc} + */ + public function withParsedBody($data) + { + $new = clone $this; + $new->parsedBody = $data; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * {@inheritdoc} + */ + public function getAttribute($attribute, $default = null) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $default; + } + + return $this->attributes[$attribute]; + } + + /** + * {@inheritdoc} + */ + public function withAttribute($attribute, $value) + { + $new = clone $this; + $new->attributes[$attribute] = $value; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function withoutAttribute($attribute) + { + if (false === array_key_exists($attribute, $this->attributes)) { + return $this; + } + + $new = clone $this; + unset($new->attributes[$attribute]); + + return $new; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Stream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Stream.php new file mode 100644 index 0000000..3865d6d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Stream.php @@ -0,0 +1,270 @@ +size = $options['size']; + } + + $this->customMetadata = isset($options['metadata']) + ? $options['metadata'] + : []; + + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); + $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); + $this->uri = $this->getMetadata('uri'); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString() + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Exception $e) { + return ''; + } + } + + public function getContents() + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $contents = stream_get_contents($this->stream); + + if ($contents === false) { + throw new \RuntimeException('Unable to read stream contents'); + } + + return $contents; + } + + public function close() + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize() + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function eof() + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + return feof($this->stream); + } + + public function tell() + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + $whence = (int) $whence; + + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } + if (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length) + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + if ($length < 0) { + throw new \RuntimeException('Length parameter cannot be negative'); + } + + if (0 === $length) { + return ''; + } + + $string = fread($this->stream, $length); + if (false === $string) { + throw new \RuntimeException('Unable to read from stream'); + } + + return $string; + } + + public function write($string) + { + if (!isset($this->stream)) { + throw new \RuntimeException('Stream is detached'); + } + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : []; + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return isset($meta[$key]) ? $meta[$key] : null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..5025dd6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,152 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @param string $name Name of the property (allows "stream" only). + * + * @return StreamInterface + */ + public function __get($name) + { + if ($name == 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString() + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Exception $e) { + // Really, PHP? https://bugs.php.net/bug.php?id=53648 + trigger_error('StreamDecorator::__toString exception: ' + . (string) $e, E_USER_ERROR); + return ''; + } + } + + public function getContents() + { + return Utils::copyToString($this); + } + + /** + * Allow decorators to implement custom methods + * + * @param string $method Missing method name + * @param array $args Method arguments + * + * @return mixed + */ + public function __call($method, array $args) + { + $result = call_user_func_array([$this->stream, $method], $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close() + { + $this->stream->close(); + } + + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize() + { + return $this->stream->getSize(); + } + + public function eof() + { + return $this->stream->eof(); + } + + public function tell() + { + return $this->stream->tell(); + } + + public function isReadable() + { + return $this->stream->isReadable(); + } + + public function isWritable() + { + return $this->stream->isWritable(); + } + + public function isSeekable() + { + return $this->stream->isSeekable(); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + $this->stream->seek($offset, $whence); + } + + public function read($length) + { + return $this->stream->read($length); + } + + public function write($string) + { + return $this->stream->write($string); + } + + /** + * Implement in subclasses to dynamically create streams when requested. + * + * @return StreamInterface + * + * @throws \BadMethodCallException + */ + protected function createStream() + { + throw new \BadMethodCallException('Not implemented'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..fc7cb96 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/StreamWrapper.php @@ -0,0 +1,165 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, null, self::createStreamContext($stream)); + } + + /** + * Creates a stream context that can be used to open a stream as a php stream resource. + * + * @param StreamInterface $stream + * + * @return resource + */ + public static function createStreamContext(StreamInterface $stream) + { + return stream_context_create([ + 'guzzle' => ['stream' => $stream] + ]); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register() + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open($path, $mode, $options, &$opened_path) + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read($count) + { + return $this->stream->read($count); + } + + public function stream_write($data) + { + return (int) $this->stream->write($data); + } + + public function stream_tell() + { + return $this->stream->tell(); + } + + public function stream_eof() + { + return $this->stream->eof(); + } + + public function stream_seek($offset, $whence) + { + $this->stream->seek($offset, $whence); + + return true; + } + + public function stream_cast($cast_as) + { + $stream = clone($this->stream); + + return $stream->detach(); + } + + public function stream_stat() + { + static $modeMap = [ + 'r' => 33060, + 'rb' => 33060, + 'r+' => 33206, + 'w' => 33188, + 'wb' => 33188 + ]; + + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } + + public function url_stat($path, $flags) + { + return [ + 'dev' => 0, + 'ino' => 0, + 'mode' => 0, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ]; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php new file mode 100644 index 0000000..bf342c4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UploadedFile.php @@ -0,0 +1,328 @@ +setError($errorStatus); + $this->setSize($size); + $this->setClientFilename($clientFilename); + $this->setClientMediaType($clientMediaType); + + if ($this->isOk()) { + $this->setStreamOrFile($streamOrFile); + } + } + + /** + * Depending on the value set file or stream variable + * + * @param mixed $streamOrFile + * + * @throws InvalidArgumentException + */ + private function setStreamOrFile($streamOrFile) + { + if (is_string($streamOrFile)) { + $this->file = $streamOrFile; + } elseif (is_resource($streamOrFile)) { + $this->stream = new Stream($streamOrFile); + } elseif ($streamOrFile instanceof StreamInterface) { + $this->stream = $streamOrFile; + } else { + throw new InvalidArgumentException( + 'Invalid stream or file provided for UploadedFile' + ); + } + } + + /** + * @param int $error + * + * @throws InvalidArgumentException + */ + private function setError($error) + { + if (false === is_int($error)) { + throw new InvalidArgumentException( + 'Upload file error status must be an integer' + ); + } + + if (false === in_array($error, UploadedFile::$errors)) { + throw new InvalidArgumentException( + 'Invalid error status for UploadedFile' + ); + } + + $this->error = $error; + } + + /** + * @param int $size + * + * @throws InvalidArgumentException + */ + private function setSize($size) + { + if (false === is_int($size)) { + throw new InvalidArgumentException( + 'Upload file size must be an integer' + ); + } + + $this->size = $size; + } + + /** + * @param mixed $param + * + * @return bool + */ + private function isStringOrNull($param) + { + return in_array(gettype($param), ['string', 'NULL']); + } + + /** + * @param mixed $param + * + * @return bool + */ + private function isStringNotEmpty($param) + { + return is_string($param) && false === empty($param); + } + + /** + * @param string|null $clientFilename + * + * @throws InvalidArgumentException + */ + private function setClientFilename($clientFilename) + { + if (false === $this->isStringOrNull($clientFilename)) { + throw new InvalidArgumentException( + 'Upload file client filename must be a string or null' + ); + } + + $this->clientFilename = $clientFilename; + } + + /** + * @param string|null $clientMediaType + * + * @throws InvalidArgumentException + */ + private function setClientMediaType($clientMediaType) + { + if (false === $this->isStringOrNull($clientMediaType)) { + throw new InvalidArgumentException( + 'Upload file client media type must be a string or null' + ); + } + + $this->clientMediaType = $clientMediaType; + } + + /** + * Return true if there is no upload error + * + * @return bool + */ + private function isOk() + { + return $this->error === UPLOAD_ERR_OK; + } + + /** + * @return bool + */ + public function isMoved() + { + return $this->moved; + } + + /** + * @throws RuntimeException if is moved or not ok + */ + private function validateActive() + { + if (false === $this->isOk()) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + if ($this->isMoved()) { + throw new RuntimeException('Cannot retrieve stream after it has already been moved'); + } + } + + /** + * {@inheritdoc} + * + * @throws RuntimeException if the upload was not successful. + */ + public function getStream() + { + $this->validateActive(); + + if ($this->stream instanceof StreamInterface) { + return $this->stream; + } + + return new LazyOpenStream($this->file, 'r+'); + } + + /** + * {@inheritdoc} + * + * @see http://php.net/is_uploaded_file + * @see http://php.net/move_uploaded_file + * + * @param string $targetPath Path to which to move the uploaded file. + * + * @throws RuntimeException if the upload was not successful. + * @throws InvalidArgumentException if the $path specified is invalid. + * @throws RuntimeException on any error during the move operation, or on + * the second or subsequent call to the method. + */ + public function moveTo($targetPath) + { + $this->validateActive(); + + if (false === $this->isStringNotEmpty($targetPath)) { + throw new InvalidArgumentException( + 'Invalid path provided for move operation; must be a non-empty string' + ); + } + + if ($this->file) { + $this->moved = php_sapi_name() == 'cli' + ? rename($this->file, $targetPath) + : move_uploaded_file($this->file, $targetPath); + } else { + Utils::copyToStream( + $this->getStream(), + new LazyOpenStream($targetPath, 'w') + ); + + $this->moved = true; + } + + if (false === $this->moved) { + throw new RuntimeException( + sprintf('Uploaded file could not be moved to %s', $targetPath) + ); + } + } + + /** + * {@inheritdoc} + * + * @return int|null The file size in bytes or null if unknown. + */ + public function getSize() + { + return $this->size; + } + + /** + * {@inheritdoc} + * + * @see http://php.net/manual/en/features.file-upload.errors.php + * + * @return int One of PHP's UPLOAD_ERR_XXX constants. + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + * + * @return string|null The filename sent by the client or null if none + * was provided. + */ + public function getClientFilename() + { + return $this->clientFilename; + } + + /** + * {@inheritdoc} + */ + public function getClientMediaType() + { + return $this->clientMediaType; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Uri.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Uri.php new file mode 100644 index 0000000..0f9f020 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Uri.php @@ -0,0 +1,810 @@ + 80, + 'https' => 443, + 'ftp' => 21, + 'gopher' => 70, + 'nntp' => 119, + 'news' => 119, + 'telnet' => 23, + 'tn3270' => 23, + 'imap' => 143, + 'pop' => 110, + 'ldap' => 389, + ]; + + private static $charUnreserved = 'a-zA-Z0-9_\-\.~'; + private static $charSubDelims = '!\$&\'\(\)\*\+,;='; + private static $replaceQuery = ['=' => '%3D', '&' => '%26']; + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** + * @param string $uri URI to parse + */ + public function __construct($uri = '') + { + // weak type check to also accept null until we can add scalar type hints + if ($uri != '') { + $parts = self::parse($uri); + if ($parts === false) { + throw new \InvalidArgumentException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + + /** + * UTF-8 aware \parse_url() replacement. + * + * The internal function produces broken output for non ASCII domain names + * (IDN) when used with locales other than "C". + * + * On the other hand, cURL understands IDN correctly only when UTF-8 locale + * is configured ("C.UTF-8", "en_US.UTF-8", etc.). + * + * @see https://bugs.php.net/bug.php?id=52923 + * @see https://www.php.net/manual/en/function.parse-url.php#114817 + * @see https://curl.haxx.se/libcurl/c/CURLOPT_URL.html#ENCODING + * + * @param string $url + * + * @return array|false + */ + private static function parse($url) + { + // If IPv6 + $prefix = ''; + if (preg_match('%^(.*://\[[0-9:a-f]+\])(.*?)$%', $url, $matches)) { + $prefix = $matches[1]; + $url = $matches[2]; + } + + $encodedUrl = preg_replace_callback( + '%[^:/@?&=#]+%usD', + static function ($matches) { + return urlencode($matches[0]); + }, + $url + ); + + $result = parse_url($prefix . $encodedUrl); + + if ($result === false) { + return false; + } + + return array_map('urldecode', $result); + } + + public function __toString() + { + return self::composeComponents( + $this->scheme, + $this->getAuthority(), + $this->path, + $this->query, + $this->fragment + ); + } + + /** + * Composes a URI reference string from its various components. + * + * Usually this method does not need to be called manually but instead is used indirectly via + * `Psr\Http\Message\UriInterface::__toString`. + * + * PSR-7 UriInterface treats an empty component the same as a missing component as + * getQuery(), getFragment() etc. always return a string. This explains the slight + * difference to RFC 3986 Section 5.3. + * + * Another adjustment is that the authority separator is added even when the authority is missing/empty + * for the "file" scheme. This is because PHP stream functions like `file_get_contents` only work with + * `file:///myfile` but not with `file:/myfile` although they are equivalent according to RFC 3986. But + * `file:///` is the more common syntax for the file scheme anyway (Chrome for example redirects to + * that format). + * + * @param string $scheme + * @param string $authority + * @param string $path + * @param string $query + * @param string $fragment + * + * @return string + * + * @link https://tools.ietf.org/html/rfc3986#section-5.3 + */ + public static function composeComponents($scheme, $authority, $path, $query, $fragment) + { + $uri = ''; + + // weak type checks to also accept null until we can add scalar type hints + if ($scheme != '') { + $uri .= $scheme . ':'; + } + + if ($authority != ''|| $scheme === 'file') { + $uri .= '//' . $authority; + } + + $uri .= $path; + + if ($query != '') { + $uri .= '?' . $query; + } + + if ($fragment != '') { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Whether the URI has the default port of the current scheme. + * + * `Psr\Http\Message\UriInterface::getPort` may return null or the standard port. This method can be used + * independently of the implementation. + * + * @param UriInterface $uri + * + * @return bool + */ + public static function isDefaultPort(UriInterface $uri) + { + return $uri->getPort() === null + || (isset(self::$defaultPorts[$uri->getScheme()]) && $uri->getPort() === self::$defaultPorts[$uri->getScheme()]); + } + + /** + * Whether the URI is absolute, i.e. it has a scheme. + * + * An instance of UriInterface can either be an absolute URI or a relative reference. This method returns true + * if it is the former. An absolute URI has a scheme. A relative reference is used to express a URI relative + * to another URI, the base URI. Relative references can be divided into several forms: + * - network-path references, e.g. '//example.com/path' + * - absolute-path references, e.g. '/path' + * - relative-path references, e.g. 'subpath' + * + * @param UriInterface $uri + * + * @return bool + * + * @see Uri::isNetworkPathReference + * @see Uri::isAbsolutePathReference + * @see Uri::isRelativePathReference + * @link https://tools.ietf.org/html/rfc3986#section-4 + */ + public static function isAbsolute(UriInterface $uri) + { + return $uri->getScheme() !== ''; + } + + /** + * Whether the URI is a network-path reference. + * + * A relative reference that begins with two slash characters is termed an network-path reference. + * + * @param UriInterface $uri + * + * @return bool + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isNetworkPathReference(UriInterface $uri) + { + return $uri->getScheme() === '' && $uri->getAuthority() !== ''; + } + + /** + * Whether the URI is a absolute-path reference. + * + * A relative reference that begins with a single slash character is termed an absolute-path reference. + * + * @param UriInterface $uri + * + * @return bool + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isAbsolutePathReference(UriInterface $uri) + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && isset($uri->getPath()[0]) + && $uri->getPath()[0] === '/'; + } + + /** + * Whether the URI is a relative-path reference. + * + * A relative reference that does not begin with a slash character is termed a relative-path reference. + * + * @param UriInterface $uri + * + * @return bool + * + * @link https://tools.ietf.org/html/rfc3986#section-4.2 + */ + public static function isRelativePathReference(UriInterface $uri) + { + return $uri->getScheme() === '' + && $uri->getAuthority() === '' + && (!isset($uri->getPath()[0]) || $uri->getPath()[0] !== '/'); + } + + /** + * Whether the URI is a same-document reference. + * + * A same-document reference refers to a URI that is, aside from its fragment + * component, identical to the base URI. When no base URI is given, only an empty + * URI reference (apart from its fragment) is considered a same-document reference. + * + * @param UriInterface $uri The URI to check + * @param UriInterface|null $base An optional base URI to compare against + * + * @return bool + * + * @link https://tools.ietf.org/html/rfc3986#section-4.4 + */ + public static function isSameDocumentReference(UriInterface $uri, UriInterface $base = null) + { + if ($base !== null) { + $uri = UriResolver::resolve($base, $uri); + + return ($uri->getScheme() === $base->getScheme()) + && ($uri->getAuthority() === $base->getAuthority()) + && ($uri->getPath() === $base->getPath()) + && ($uri->getQuery() === $base->getQuery()); + } + + return $uri->getScheme() === '' && $uri->getAuthority() === '' && $uri->getPath() === '' && $uri->getQuery() === ''; + } + + /** + * Removes dot segments from a path and returns the new path. + * + * @param string $path + * + * @return string + * + * @deprecated since version 1.4. Use UriResolver::removeDotSegments instead. + * @see UriResolver::removeDotSegments + */ + public static function removeDotSegments($path) + { + return UriResolver::removeDotSegments($path); + } + + /** + * Converts the relative URI into a new URI that is resolved against the base URI. + * + * @param UriInterface $base Base URI + * @param string|UriInterface $rel Relative URI + * + * @return UriInterface + * + * @deprecated since version 1.4. Use UriResolver::resolve instead. + * @see UriResolver::resolve + */ + public static function resolve(UriInterface $base, $rel) + { + if (!($rel instanceof UriInterface)) { + $rel = new self($rel); + } + + return UriResolver::resolve($base, $rel); + } + + /** + * Creates a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key to remove. + * + * @return UriInterface + */ + public static function withoutQueryValue(UriInterface $uri, $key) + { + $result = self::getFilteredQueryString($uri, [$key]); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * A value of null will set the query string key without a value, e.g. "key" + * instead of "key=value". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string|null $value Value to set + * + * @return UriInterface + */ + public static function withQueryValue(UriInterface $uri, $key, $value) + { + $result = self::getFilteredQueryString($uri, [$key]); + + $result[] = self::generateQueryString($key, $value); + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a new URI with multiple specific query string values. + * + * It has the same behavior as withQueryValue() but for an associative array of key => value. + * + * @param UriInterface $uri URI to use as a base. + * @param array $keyValueArray Associative array of key and values + * + * @return UriInterface + */ + public static function withQueryValues(UriInterface $uri, array $keyValueArray) + { + $result = self::getFilteredQueryString($uri, array_keys($keyValueArray)); + + foreach ($keyValueArray as $key => $value) { + $result[] = self::generateQueryString($key, $value); + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Creates a URI from a hash of `parse_url` components. + * + * @param array $parts + * + * @return UriInterface + * + * @link http://php.net/manual/en/function.parse-url.php + * + * @throws \InvalidArgumentException If the components do not form a valid URI. + */ + public static function fromParts(array $parts) + { + $uri = new self(); + $uri->applyParts($parts); + $uri->validateState(); + + return $uri; + } + + public function getScheme() + { + return $this->scheme; + } + + public function getAuthority() + { + $authority = $this->host; + if ($this->userInfo !== '') { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->port !== null) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo() + { + return $this->userInfo; + } + + public function getHost() + { + return $this->host; + } + + public function getPort() + { + return $this->port; + } + + public function getPath() + { + return $this->path; + } + + public function getQuery() + { + return $this->query; + } + + public function getFragment() + { + return $this->fragment; + } + + public function withScheme($scheme) + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withUserInfo($user, $password = null) + { + $info = $this->filterUserInfoComponent($user); + if ($password !== null) { + $info .= ':' . $this->filterUserInfoComponent($password); + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + $new->validateState(); + + return $new; + } + + public function withHost($host) + { + $host = $this->filterHost($host); + + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + $new->validateState(); + + return $new; + } + + public function withPort($port) + { + $port = $this->filterPort($port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + $new->removeDefaultPort(); + $new->validateState(); + + return $new; + } + + public function withPath($path) + { + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + $new->validateState(); + + return $new; + } + + public function withQuery($query) + { + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + + return $new; + } + + public function withFragment($fragment) + { + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + + return $new; + } + + /** + * Apply parse_url parts to a URI. + * + * @param array $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts) + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) + ? $this->filterUserInfoComponent($parts['user']) + : ''; + $this->host = isset($parts['host']) + ? $this->filterHost($parts['host']) + : ''; + $this->port = isset($parts['port']) + ? $this->filterPort($parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $this->filterUserInfoComponent($parts['pass']); + } + + $this->removeDefaultPort(); + } + + /** + * @param string $scheme + * + * @return string + * + * @throws \InvalidArgumentException If the scheme is invalid. + */ + private function filterScheme($scheme) + { + if (!is_string($scheme)) { + throw new \InvalidArgumentException('Scheme must be a string'); + } + + return \strtr($scheme, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param string $component + * + * @return string + * + * @throws \InvalidArgumentException If the user info is invalid. + */ + private function filterUserInfoComponent($component) + { + if (!is_string($component)) { + throw new \InvalidArgumentException('User info must be a string'); + } + + return preg_replace_callback( + '/(?:[^%' . self::$charUnreserved . self::$charSubDelims . ']+|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $component + ); + } + + /** + * @param string $host + * + * @return string + * + * @throws \InvalidArgumentException If the host is invalid. + */ + private function filterHost($host) + { + if (!is_string($host)) { + throw new \InvalidArgumentException('Host must be a string'); + } + + return \strtr($host, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); + } + + /** + * @param int|null $port + * + * @return int|null + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($port) + { + if ($port === null) { + return null; + } + + $port = (int) $port; + if (0 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 0 and 65535', $port) + ); + } + + return $port; + } + + /** + * @param UriInterface $uri + * @param array $keys + * + * @return array + */ + private static function getFilteredQueryString(UriInterface $uri, array $keys) + { + $current = $uri->getQuery(); + + if ($current === '') { + return []; + } + + $decodedKeys = array_map('rawurldecode', $keys); + + return array_filter(explode('&', $current), function ($part) use ($decodedKeys) { + return !in_array(rawurldecode(explode('=', $part)[0]), $decodedKeys, true); + }); + } + + /** + * @param string $key + * @param string|null $value + * + * @return string + */ + private static function generateQueryString($key, $value) + { + // Query string separators ("=", "&") within the key or value need to be encoded + // (while preventing double-encoding) before setting the query string. All other + // chars that need percent-encoding will be encoded by withQuery(). + $queryString = strtr($key, self::$replaceQuery); + + if ($value !== null) { + $queryString .= '=' . strtr($value, self::$replaceQuery); + } + + return $queryString; + } + + private function removeDefaultPort() + { + if ($this->port !== null && self::isDefaultPort($this)) { + $this->port = null; + } + } + + /** + * Filters the path of a URI + * + * @param string $path + * + * @return string + * + * @throws \InvalidArgumentException If the path is invalid. + */ + private function filterPath($path) + { + if (!is_string($path)) { + throw new \InvalidArgumentException('Path must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param string $str + * + * @return string + * + * @throws \InvalidArgumentException If the query or fragment is invalid. + */ + private function filterQueryAndFragment($str) + { + if (!is_string($str)) { + throw new \InvalidArgumentException('Query and fragment must be a string'); + } + + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]++|%(?![A-Fa-f0-9]{2}))/', + [$this, 'rawurlencodeMatchZero'], + $str + ); + } + + private function rawurlencodeMatchZero(array $match) + { + return rawurlencode($match[0]); + } + + private function validateState() + { + if ($this->host === '' && ($this->scheme === 'http' || $this->scheme === 'https')) { + $this->host = self::HTTP_DEFAULT_HOST; + } + + if ($this->getAuthority() === '') { + if (0 === strpos($this->path, '//')) { + throw new \InvalidArgumentException('The path of a URI without an authority must not start with two slashes "//"'); + } + if ($this->scheme === '' && false !== strpos(explode('/', $this->path, 2)[0], ':')) { + throw new \InvalidArgumentException('A relative URI must not have a path beginning with a segment containing a colon'); + } + } elseif (isset($this->path[0]) && $this->path[0] !== '/') { + @trigger_error( + 'The path of a URI with an authority must start with a slash "/" or be empty. Automagically fixing the URI ' . + 'by adding a leading slash to the path is deprecated since version 1.4 and will throw an exception instead.', + E_USER_DEPRECATED + ); + $this->path = '/' . $this->path; + //throw new \InvalidArgumentException('The path of a URI with an authority must start with a slash "/" or be empty'); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php new file mode 100644 index 0000000..81419ea --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriNormalizer.php @@ -0,0 +1,219 @@ +getPath() === '' && + ($uri->getScheme() === 'http' || $uri->getScheme() === 'https') + ) { + $uri = $uri->withPath('/'); + } + + if ($flags & self::REMOVE_DEFAULT_HOST && $uri->getScheme() === 'file' && $uri->getHost() === 'localhost') { + $uri = $uri->withHost(''); + } + + if ($flags & self::REMOVE_DEFAULT_PORT && $uri->getPort() !== null && Uri::isDefaultPort($uri)) { + $uri = $uri->withPort(null); + } + + if ($flags & self::REMOVE_DOT_SEGMENTS && !Uri::isRelativePathReference($uri)) { + $uri = $uri->withPath(UriResolver::removeDotSegments($uri->getPath())); + } + + if ($flags & self::REMOVE_DUPLICATE_SLASHES) { + $uri = $uri->withPath(preg_replace('#//++#', '/', $uri->getPath())); + } + + if ($flags & self::SORT_QUERY_PARAMETERS && $uri->getQuery() !== '') { + $queryKeyValues = explode('&', $uri->getQuery()); + sort($queryKeyValues); + $uri = $uri->withQuery(implode('&', $queryKeyValues)); + } + + return $uri; + } + + /** + * Whether two URIs can be considered equivalent. + * + * Both URIs are normalized automatically before comparison with the given $normalizations bitmask. The method also + * accepts relative URI references and returns true when they are equivalent. This of course assumes they will be + * resolved against the same base URI. If this is not the case, determination of equivalence or difference of + * relative references does not mean anything. + * + * @param UriInterface $uri1 An URI to compare + * @param UriInterface $uri2 An URI to compare + * @param int $normalizations A bitmask of normalizations to apply, see constants + * + * @return bool + * + * @link https://tools.ietf.org/html/rfc3986#section-6.1 + */ + public static function isEquivalent(UriInterface $uri1, UriInterface $uri2, $normalizations = self::PRESERVING_NORMALIZATIONS) + { + return (string) self::normalize($uri1, $normalizations) === (string) self::normalize($uri2, $normalizations); + } + + private static function capitalizePercentEncoding(UriInterface $uri) + { + $regex = '/(?:%[A-Fa-f0-9]{2})++/'; + + $callback = function (array $match) { + return strtoupper($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private static function decodeUnreservedCharacters(UriInterface $uri) + { + $regex = '/%(?:2D|2E|5F|7E|3[0-9]|[46][1-9A-F]|[57][0-9A])/i'; + + $callback = function (array $match) { + return rawurldecode($match[0]); + }; + + return + $uri->withPath( + preg_replace_callback($regex, $callback, $uri->getPath()) + )->withQuery( + preg_replace_callback($regex, $callback, $uri->getQuery()) + ); + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriResolver.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriResolver.php new file mode 100644 index 0000000..a3cb15d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/UriResolver.php @@ -0,0 +1,222 @@ +getScheme() != '') { + return $rel->withPath(self::removeDotSegments($rel->getPath())); + } + + if ($rel->getAuthority() != '') { + $targetAuthority = $rel->getAuthority(); + $targetPath = self::removeDotSegments($rel->getPath()); + $targetQuery = $rel->getQuery(); + } else { + $targetAuthority = $base->getAuthority(); + if ($rel->getPath() === '') { + $targetPath = $base->getPath(); + $targetQuery = $rel->getQuery() != '' ? $rel->getQuery() : $base->getQuery(); + } else { + if ($rel->getPath()[0] === '/') { + $targetPath = $rel->getPath(); + } else { + if ($targetAuthority != '' && $base->getPath() === '') { + $targetPath = '/' . $rel->getPath(); + } else { + $lastSlashPos = strrpos($base->getPath(), '/'); + if ($lastSlashPos === false) { + $targetPath = $rel->getPath(); + } else { + $targetPath = substr($base->getPath(), 0, $lastSlashPos + 1) . $rel->getPath(); + } + } + } + $targetPath = self::removeDotSegments($targetPath); + $targetQuery = $rel->getQuery(); + } + } + + return new Uri(Uri::composeComponents( + $base->getScheme(), + $targetAuthority, + $targetPath, + $targetQuery, + $rel->getFragment() + )); + } + + /** + * Returns the target URI as a relative reference from the base URI. + * + * This method is the counterpart to resolve(): + * + * (string) $target === (string) UriResolver::resolve($base, UriResolver::relativize($base, $target)) + * + * One use-case is to use the current request URI as base URI and then generate relative links in your documents + * to reduce the document size or offer self-contained downloadable document archives. + * + * $base = new Uri('http://example.com/a/b/'); + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/c')); // prints 'c'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/x/y')); // prints '../x/y'. + * echo UriResolver::relativize($base, new Uri('http://example.com/a/b/?q')); // prints '?q'. + * echo UriResolver::relativize($base, new Uri('http://example.org/a/b/')); // prints '//example.org/a/b/'. + * + * This method also accepts a target that is already relative and will try to relativize it further. Only a + * relative-path reference will be returned as-is. + * + * echo UriResolver::relativize($base, new Uri('/a/b/c')); // prints 'c' as well + * + * @param UriInterface $base Base URI + * @param UriInterface $target Target URI + * + * @return UriInterface The relative URI reference + */ + public static function relativize(UriInterface $base, UriInterface $target) + { + if ($target->getScheme() !== '' && + ($base->getScheme() !== $target->getScheme() || $target->getAuthority() === '' && $base->getAuthority() !== '') + ) { + return $target; + } + + if (Uri::isRelativePathReference($target)) { + // As the target is already highly relative we return it as-is. It would be possible to resolve + // the target with `$target = self::resolve($base, $target);` and then try make it more relative + // by removing a duplicate query. But let's not do that automatically. + return $target; + } + + if ($target->getAuthority() !== '' && $base->getAuthority() !== $target->getAuthority()) { + return $target->withScheme(''); + } + + // We must remove the path before removing the authority because if the path starts with two slashes, the URI + // would turn invalid. And we also cannot set a relative path before removing the authority, as that is also + // invalid. + $emptyPathUri = $target->withScheme('')->withPath('')->withUserInfo('')->withPort(null)->withHost(''); + + if ($base->getPath() !== $target->getPath()) { + return $emptyPathUri->withPath(self::getRelativePath($base, $target)); + } + + if ($base->getQuery() === $target->getQuery()) { + // Only the target fragment is left. And it must be returned even if base and target fragment are the same. + return $emptyPathUri->withQuery(''); + } + + // If the base URI has a query but the target has none, we cannot return an empty path reference as it would + // inherit the base query component when resolving. + if ($target->getQuery() === '') { + $segments = explode('/', $target->getPath()); + $lastSegment = end($segments); + + return $emptyPathUri->withPath($lastSegment === '' ? './' : $lastSegment); + } + + return $emptyPathUri; + } + + private static function getRelativePath(UriInterface $base, UriInterface $target) + { + $sourceSegments = explode('/', $base->getPath()); + $targetSegments = explode('/', $target->getPath()); + array_pop($sourceSegments); + $targetLastSegment = array_pop($targetSegments); + foreach ($sourceSegments as $i => $segment) { + if (isset($targetSegments[$i]) && $segment === $targetSegments[$i]) { + unset($sourceSegments[$i], $targetSegments[$i]); + } else { + break; + } + } + $targetSegments[] = $targetLastSegment; + $relativePath = str_repeat('../', count($sourceSegments)) . implode('/', $targetSegments); + + // A reference to am empty last segment or an empty first sub-segment must be prefixed with "./". + // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used + // as the first segment of a relative-path reference, as it would be mistaken for a scheme name. + if ('' === $relativePath || false !== strpos(explode('/', $relativePath, 2)[0], ':')) { + $relativePath = "./$relativePath"; + } elseif ('/' === $relativePath[0]) { + if ($base->getAuthority() != '' && $base->getPath() === '') { + // In this case an extra slash is added by resolve() automatically. So we must not add one here. + $relativePath = ".$relativePath"; + } else { + $relativePath = "./$relativePath"; + } + } + + return $relativePath; + } + + private function __construct() + { + // cannot be instantiated + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Utils.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Utils.php new file mode 100644 index 0000000..6b6c8cc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/Utils.php @@ -0,0 +1,428 @@ + $keys + * + * @return array + */ + public static function caselessRemove($keys, array $data) + { + $result = []; + + foreach ($keys as &$key) { + $key = strtolower($key); + } + + foreach ($data as $k => $v) { + if (!in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; + } + + /** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ + public static function copyToStream(StreamInterface $source, StreamInterface $dest, $maxLen = -1) + { + $bufferSize = 8192; + + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read($bufferSize))) { + break; + } + } + } else { + $remaining = $maxLen; + while ($remaining > 0 && !$source->eof()) { + $buf = $source->read(min($bufferSize, $remaining)); + $len = strlen($buf); + if (!$len) { + break; + } + $remaining -= $len; + $dest->write($buf); + } + } + } + + /** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @return string + * + * @throws \RuntimeException on error. + */ + public static function copyToString(StreamInterface $stream, $maxLen = -1) + { + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; + } + + /** + * Calculate a hash of a stream. + * + * This method reads the entire stream to calculate a rolling hash, based + * on PHP's `hash_init` functions. + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @return string Returns the hash of the stream + * + * @throws \RuntimeException on error. + */ + public static function hash(StreamInterface $stream, $algo, $rawOutput = false) + { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, (bool) $rawOutput); + $stream->seek($pos); + + return $out; + } + + /** + * Clone and modify a request with the given changes. + * + * This method is useful for reducing the number of clones needed to mutate + * a message. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + * + * @return RequestInterface + */ + public static function modifyRequest(RequestInterface $request, array $changes) + { + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + + if ($port = $changes['uri']->getPort()) { + $standardPorts = ['http' => 80, 'https' => 443]; + $scheme = $changes['uri']->getScheme(); + if (isset($standardPorts[$scheme]) && $port != $standardPorts[$scheme]) { + $changes['set_headers']['Host'] .= ':' . $port; + } + } + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = self::caselessRemove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = self::caselessRemove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + if ($request instanceof ServerRequestInterface) { + $new = (new ServerRequest( + isset($changes['method']) ? $changes['method'] : $request->getMethod(), + $uri, + $headers, + isset($changes['body']) ? $changes['body'] : $request->getBody(), + isset($changes['version']) + ? $changes['version'] + : $request->getProtocolVersion(), + $request->getServerParams() + )) + ->withParsedBody($request->getParsedBody()) + ->withQueryParams($request->getQueryParams()) + ->withCookieParams($request->getCookieParams()) + ->withUploadedFiles($request->getUploadedFiles()); + + foreach ($request->getAttributes() as $key => $value) { + $new = $new->withAttribute($key, $value); + } + + return $new; + } + + return new Request( + isset($changes['method']) ? $changes['method'] : $request->getMethod(), + $uri, + $headers, + isset($changes['body']) ? $changes['body'] : $request->getBody(), + isset($changes['version']) + ? $changes['version'] + : $request->getProtocolVersion() + ); + } + + /** + * Read a line from the stream up to the maximum allowed buffer length. + * + * @param StreamInterface $stream Stream to read from + * @param int|null $maxLength Maximum buffer length + * + * @return string + */ + public static function readLine(StreamInterface $stream, $maxLength = null) + { + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + // Using a loose equality here to match on '' and false. + if (null == ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte === "\n" || ++$size === $maxLength - 1) { + break; + } + } + + return $buffer; + } + + /** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * This method accepts the following `$resource` types: + * - `Psr\Http\Message\StreamInterface`: Returns the value as-is. + * - `string`: Creates a stream object that uses the given string as the contents. + * - `resource`: Creates a stream object that wraps the given PHP stream resource. + * - `Iterator`: If the provided value implements `Iterator`, then a read-only + * stream object will be created that wraps the given iterable. Each time the + * stream is read from, data from the iterator will fill a buffer and will be + * continuously called until the buffer is equal to the requested read size. + * Subsequent read calls will first read from the buffer and then call `next` + * on the underlying iterator until it is exhausted. + * - `object` with `__toString()`: If the object has the `__toString()` method, + * the object will be cast to a string and then a stream will be returned that + * uses the string value. + * - `NULL`: When `null` is passed, an empty stream object is returned. + * - `callable` When a callable is passed, a read-only stream object will be + * created that invokes the given callable. The callable is invoked with the + * number of suggested bytes to read. The callable can return any number of + * bytes, but MUST return `false` when there is no more data to return. The + * stream object that wraps the callable will invoke the callable until the + * number of requested bytes are available. Any additional bytes will be + * buffered and used in subsequent reads. + * + * @param resource|string|int|float|bool|StreamInterface|callable|\Iterator|null $resource Entity body data + * @param array $options Additional options + * + * @return StreamInterface + * + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ + public static function streamFor($resource = '', array $options = []) + { + if (is_scalar($resource)) { + $stream = self::tryFopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + } + + switch (gettype($resource)) { + case 'resource': + /* + * The 'php://input' is a special stream with quirks and inconsistencies. + * We avoid using that stream by reading it into php://temp + */ + $metaData = \stream_get_meta_data($resource); + if (isset($metaData['uri']) && $metaData['uri'] === 'php://input') { + $stream = self::tryFopen('php://temp', 'w+'); + fwrite($stream, stream_get_contents($resource)); + fseek($stream, 0); + $resource = $stream; + } + return new Stream($resource, $options); + case 'object': + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return Utils::streamFor((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(self::tryFopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); + } + + /** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * + * @throws \RuntimeException if the file cannot be opened + */ + public static function tryFopen($filename, $mode) + { + $ex = null; + set_error_handler(function () use ($filename, $mode, &$ex) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + func_get_args()[1] + )); + + return true; + }); + + try { + $handle = fopen($filename, $mode); + } catch (\Throwable $e) { + $ex = new \RuntimeException(sprintf( + 'Unable to open "%s" using mode "%s": %s', + $filename, + $mode, + $e->getMessage() + ), 0, $e); + } + + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; + } + + /** + * Returns a UriInterface for the given value. + * + * This function accepts a string or UriInterface and returns a + * UriInterface for the given value. If the value is already a + * UriInterface, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @return UriInterface + * + * @throws \InvalidArgumentException + */ + public static function uriFor($uri) + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions.php new file mode 100644 index 0000000..b0901fa --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions.php @@ -0,0 +1,422 @@ + '1', 'foo[b]' => '2'])`. + * + * @param string $str Query string to parse + * @param int|bool $urlEncoding How the query string is encoded + * + * @return array + * + * @deprecated parse_query will be removed in guzzlehttp/psr7:2.0. Use Query::parse instead. + */ +function parse_query($str, $urlEncoding = true) +{ + return Query::parse($str, $urlEncoding); +} + +/** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of `parse_query()` to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like `http_build_query()` would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + * + * @return string + * + * @deprecated build_query will be removed in guzzlehttp/psr7:2.0. Use Query::build instead. + */ +function build_query(array $params, $encoding = PHP_QUERY_RFC3986) +{ + return Query::build($params, $encoding); +} + +/** + * Determines the mimetype of a file by looking at its extension. + * + * @param string $filename + * + * @return string|null + * + * @deprecated mimetype_from_filename will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromFilename instead. + */ +function mimetype_from_filename($filename) +{ + return MimeType::fromFilename($filename); +} + +/** + * Maps a file extensions to a mimetype. + * + * @param $extension string The file extension. + * + * @return string|null + * + * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types + * @deprecated mimetype_from_extension will be removed in guzzlehttp/psr7:2.0. Use MimeType::fromExtension instead. + */ +function mimetype_from_extension($extension) +{ + return MimeType::fromExtension($extension); +} + +/** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + * + * @return array + * + * @internal + * + * @deprecated _parse_message will be removed in guzzlehttp/psr7:2.0. Use Message::parseMessage instead. + */ +function _parse_message($message) +{ + return Message::parseMessage($message); +} + +/** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + * + * @return string + * + * @internal + * + * @deprecated _parse_request_uri will be removed in guzzlehttp/psr7:2.0. Use Message::parseRequestUri instead. + */ +function _parse_request_uri($path, array $headers) +{ + return Message::parseRequestUri($path, $headers); +} + +/** + * Get a short summary of the message body. + * + * Will return `null` if the response is not printable. + * + * @param MessageInterface $message The message to get the body summary + * @param int $truncateAt The maximum allowed size of the summary + * + * @return string|null + * + * @deprecated get_message_body_summary will be removed in guzzlehttp/psr7:2.0. Use Message::bodySummary instead. + */ +function get_message_body_summary(MessageInterface $message, $truncateAt = 120) +{ + return Message::bodySummary($message, $truncateAt); +} + +/** + * Remove the items given by the keys, case insensitively from the data. + * + * @param iterable $keys + * + * @return array + * + * @internal + * + * @deprecated _caseless_remove will be removed in guzzlehttp/psr7:2.0. Use Utils::caselessRemove instead. + */ +function _caseless_remove($keys, array $data) +{ + return Utils::caselessRemove($keys, $data); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions_include.php new file mode 100644 index 0000000..96a4a83 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/guzzlehttp/psr7/src/functions_include.php @@ -0,0 +1,6 @@ + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/README.md new file mode 100644 index 0000000..4654495 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/README.md @@ -0,0 +1,36 @@ +# PSR-7 Message Factory + +[![Latest Version](https://img.shields.io/github/release/php-http/message-factory.svg?style=flat-square)](https://github.com/php-http/message-factory/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) +[![Total Downloads](https://img.shields.io/packagist/dt/php-http/message-factory.svg?style=flat-square)](https://packagist.org/packages/php-http/message-factory) + +**Factory interfaces for PSR-7 HTTP Message.** + + +## Install + +Via Composer + +``` bash +$ composer require php-http/message-factory +``` + + +## Documentation + +Please see the [official documentation](http://php-http.readthedocs.org/en/latest/message-factory/). + + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details. + + +## Security + +If you discover any security related issues, please contact us at [security@php-http.org](mailto:security@php-http.org). + + +## License + +The MIT License (MIT). Please see [License File](LICENSE) for more information. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/composer.json new file mode 100644 index 0000000..7c72feb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/composer.json @@ -0,0 +1,27 @@ +{ + "name": "php-http/message-factory", + "description": "Factory interfaces for PSR-7 HTTP Message", + "license": "MIT", + "keywords": ["http", "factory", "message", "stream", "uri"], + "homepage": "http://php-http.org", + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "require": { + "php": ">=5.4", + "psr/http-message": "^1.0" + }, + "autoload": { + "psr-4": { + "Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/puli.json b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/puli.json new file mode 100644 index 0000000..08d3762 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/puli.json @@ -0,0 +1,43 @@ +{ + "version": "1.0", + "binding-types": { + "Http\\Message\\MessageFactory": { + "description": "PSR-7 Message Factory", + "parameters": { + "depends": { + "description": "Optional class dependency which can be checked by consumers" + } + } + }, + "Http\\Message\\RequestFactory": { + "parameters": { + "depends": { + "description": "Optional class dependency which can be checked by consumers" + } + } + }, + "Http\\Message\\ResponseFactory": { + "parameters": { + "depends": { + "description": "Optional class dependency which can be checked by consumers" + } + } + }, + "Http\\Message\\StreamFactory": { + "description": "PSR-7 Stream Factory", + "parameters": { + "depends": { + "description": "Optional class dependency which can be checked by consumers" + } + } + }, + "Http\\Message\\UriFactory": { + "description": "PSR-7 URI Factory", + "parameters": { + "depends": { + "description": "Optional class dependency which can be checked by consumers" + } + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/MessageFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/MessageFactory.php new file mode 100644 index 0000000..965aaa8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/MessageFactory.php @@ -0,0 +1,12 @@ + + */ +interface MessageFactory extends RequestFactory, ResponseFactory +{ +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/RequestFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/RequestFactory.php new file mode 100644 index 0000000..624e82f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/RequestFactory.php @@ -0,0 +1,34 @@ + + */ +interface RequestFactory +{ + /** + * Creates a new PSR-7 request. + * + * @param string $method + * @param string|UriInterface $uri + * @param array $headers + * @param resource|string|StreamInterface|null $body + * @param string $protocolVersion + * + * @return RequestInterface + */ + public function createRequest( + $method, + $uri, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/ResponseFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/ResponseFactory.php new file mode 100644 index 0000000..2411ed3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/ResponseFactory.php @@ -0,0 +1,35 @@ + + */ +interface ResponseFactory +{ + /** + * Creates a new PSR-7 response. + * + * @param int $statusCode + * @param string|null $reasonPhrase + * @param array $headers + * @param resource|string|StreamInterface|null $body + * @param string $protocolVersion + * + * @return ResponseInterface + */ + public function createResponse( + $statusCode = 200, + $reasonPhrase = null, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/StreamFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/StreamFactory.php new file mode 100644 index 0000000..327a902 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/StreamFactory.php @@ -0,0 +1,25 @@ + + */ +interface StreamFactory +{ + /** + * Creates a new PSR-7 stream. + * + * @param string|resource|StreamInterface|null $body + * + * @return StreamInterface + * + * @throws \InvalidArgumentException If the stream body is invalid. + * @throws \RuntimeException If creating the stream from $body fails. + */ + public function createStream($body = null); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/UriFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/UriFactory.php new file mode 100644 index 0000000..f05e625 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message-factory/src/UriFactory.php @@ -0,0 +1,24 @@ + + */ +interface UriFactory +{ + /** + * Creates an PSR-7 URI. + * + * @param string|UriInterface $uri + * + * @return UriInterface + * + * @throws \InvalidArgumentException If the $uri argument can not be converted into a valid URI. + */ + public function createUri($uri); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/CHANGELOG.md new file mode 100644 index 0000000..d3eb840 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/CHANGELOG.md @@ -0,0 +1,249 @@ +# Change Log + + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [1.12.0] - 2021-08-29 + +- Added support for adjusting binary detection regex in FullHttpMessageFormatter + +## [1.11.2] - 2021-08-03 + +- Support GuzzleHttp/Psr7 version 2.0 in the (deprecated) GuzzleStreamFactory. + +## [1.11.1] - 2021-05-24 + +- Support GuzzleHttp/Psr7 version 2.0 in the (deprecated) GuzzleUriFactory. + +## [1.11.0] - 2020-02-01 + +- Migrated from `zendframework/zend-diactoros` to `laminas/laminas-diactoros`. + Users are encouraged to update their dependencies by simply replacing the Zend package with the Laminas package. + Due to the [laminas-zendframework-brige](https://github.com/laminas/laminas-zendframework-bridge), BC changes + are not expected and legacy code does not need to be refactored (though it is + [recommended and simple](https://docs.laminas.dev/migration/)). +- The diactoros factories of `php-http/message` will return objects from the `Laminas\Diactoros\` namespace, if + the respective classes are available via autoloading, but continue to return objects from `Zend\Diactoros\` + namespace otherwise. + +- Allow to specify the hashing algorithm for WSSE authentication. + +## [1.10.0] - 2020-11-11 + +- Added support for PHP 8.0. + +## [1.9.1] - 2020-10-13 + +- Improved detection of binary stream to not consider newlines, carriage return or tabs as binary. + +## [1.9.0] - 2020-08-17 + +- Omitted binary body in FullHttpMessageFormatter and CurlCommandFormatter. + `[binary stream omitted]` will be shown instead. + +### Added + +- New Header authentication method for arbitrary header authentication. + +## [1.8.0] - 2019-08-05 + +### Changed + +- Raised minimum PHP version to 7.1 + +### Fixed + +- Fatal error on `CurlCommandFormatter` when body is larger than `escapeshellarg` allowed length. +- Do not read stream in message formatter if stream is not seekable. + +## [1.7.2] - 2018-10-30 + +### Fixed + +- FilteredStream uses `@trigger_error` instead of throwing exceptions to not + break careless users. You still need to fix your stream code to respect + `isSeekable`. Seeking does not work as expected, and we will add exceptions + in version 2. + +## [1.7.1] - 2018-10-29 + +### Fixed + +- FilteredStream is not actually seekable + + +## [1.7.0] - 2018-08-15 + +### Fixed + +- Fix CurlCommandFormatter for binary request payloads +- Fix QueryParam authentication to assemble proper URL regardless of PHP `arg_separator.output` directive +- Do not pass `null` parameters to `Clue\StreamFilter\fun` + +### Changed + +- Dropped tests on HHVM + + +## [1.6.0] - 2017-07-05 + +### Added + +- CookieUtil::parseDate to create a date from cookie date string + +### Fixed + +- Fix curl command of CurlFormatter when there is an user-agent header + + +## [1.5.0] - 2017-02-14 + +### Added + +- Check for empty string in Stream factories +- Cookie::createWithoutValidation Static constructor to create a cookie. Will not perform any attribute validation during instantiation. +- Cookie::isValid Method to check if cookie attributes are valid. + +### Fixed + +- FilteredStream::getSize returns null because the contents size is unknown. +- Stream factories does not rewinds streams. The previous behavior was not coherent between factories and inputs. + +### Deprecated + +- FilteredStream::getReadFilter The read filter is internal and should never be used by consuming code. +- FilteredStream::getWriteFilter We did not implement writing to the streams at all. And if we do, the filter is an internal information and should not be used by consuming code. + + +## [1.4.1] - 2016-12-16 + +### Fixed + +- Cookie::matchPath Cookie with root path (`/`) will not match sub path (e.g. `/cookie`). + + +## [1.4.0] - 2016-10-20 + +### Added + +- Message, stream and URI factories for [Slim Framework](https://github.com/slimphp/Slim) +- BufferedStream that allow you to decorate a non-seekable stream with a seekable one. +- cUrlFormatter to be able to redo the request with a cURL command + + +## [1.3.1] - 2016-07-15 + +### Fixed + +- FullHttpMessageFormatter will not read from streams that you cannot rewind (non-seekable) +- FullHttpMessageFormatter will not read from the stream if $maxBodyLength is zero +- FullHttpMessageFormatter rewinds streams after they are read + + +## [1.3.0] - 2016-07-14 + +### Added + +- FullHttpMessageFormatter to include headers and body in the formatted message + +### Fixed + +- #41: Response builder broke header value + + +## [1.2.0] - 2016-03-29 + +### Added + +- The RequestMatcher is built after the Symfony RequestMatcher and separates + scheme, host and path expressions and provides an option to filter on the + method +- New RequestConditional authentication method using request matchers +- Add automatic basic auth info detection based on the URL + +### Changed + +- Improved ResponseBuilder + +### Deprecated + +- RegexRequestMatcher, use RequestMatcher instead +- Matching authenitcation method, use RequestConditional instead + + +## [1.1.0] - 2016-02-25 + +### Added + + - Add a request matcher interface and regex implementation + - Add a callback request matcher implementation + - Add a ResponseBuilder, to create PSR7 Response from a string + +### Fixed + + - Fix casting string on a FilteredStream not filtering the output + + +## [1.0.0] - 2016-01-27 + + +## [0.2.0] - 2015-12-29 + +### Added + +- Autoregistration of stream filters using Composer autoload +- Cookie +- [Apigen](http://www.apigen.org/) configuration + + +## [0.1.2] - 2015-12-26 + +### Added + +- Request and response factory bindings + +### Fixed + +- Chunk filter namespace in Dechunk stream + + +## [0.1.1] - 2015-12-25 + +### Added + +- Formatter + + +## 0.1.0 - 2015-12-24 + +### Added + +- Authentication +- Encoding +- Message decorator +- Message factory (Guzzle, Diactoros) + + +[Unreleased]: https://github.com/php-http/message/compare/1.10.0...HEAD +[1.10.0]: https://github.com/php-http/message/compare/1.9.1...1.10.0 +[1.9.1]: https://github.com/php-http/message/compare/1.9.0...1.9.1 +[1.9.0]: https://github.com/php-http/message/compare/1.8.0...1.9.0 +[1.8.0]: https://github.com/php-http/message/compare/1.7.2...1.8.0 +[1.7.2]: https://github.com/php-http/message/compare/v1.7.1...1.7.2 +[1.7.1]: https://github.com/php-http/message/compare/1.7.0...v1.7.1 +[1.7.0]: https://github.com/php-http/message/compare/1.6.0...1.7.0 +[1.6.0]: https://github.com/php-http/message/compare/1.5.0...1.6.0 +[1.5.0]: https://github.com/php-http/message/compare/v1.4.1...1.5.0 +[1.4.1]: https://github.com/php-http/message/compare/v1.4.0...v1.4.1 +[1.4.0]: https://github.com/php-http/message/compare/v1.3.1...v1.4.0 +[1.3.1]: https://github.com/php-http/message/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/php-http/message/compare/v1.2.0...v1.3.0 +[1.2.0]: https://github.com/php-http/message/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/php-http/message/compare/v1.0.0...v1.1.0 +[1.0.0]: https://github.com/php-http/message/compare/0.2.0...v1.0.0 +[0.2.0]: https://github.com/php-http/message/compare/v0.1.2...0.2.0 +[0.1.2]: https://github.com/php-http/message/compare/v0.1.1...v0.1.2 +[0.1.1]: https://github.com/php-http/message/compare/v0.1.0...v0.1.1 diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/LICENSE new file mode 100644 index 0000000..4558d6f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015-2016 PHP HTTP Team + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/README.md new file mode 100644 index 0000000..df1a7d5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/README.md @@ -0,0 +1,51 @@ +# HTTP Message + +[![Latest Version](https://img.shields.io/github/release/php-http/message.svg?style=flat-square)](https://github.com/php-http/message/releases) +[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE) +[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/php-http/message/CI?style=flat-square)](https://github.com/php-http/message/actions?query=workflow%3ACI+branch%3Amaster) +[![Total Downloads](https://img.shields.io/packagist/dt/php-http/message.svg?style=flat-square)](https://packagist.org/packages/php-http/message) + +**HTTP Message related tools.** + + +## Install + +Via Composer + +``` bash +$ composer require php-http/message +``` + + +## Intro + +This package contains various PSR-7 tools which might be useful in an HTTP workflow: + +- Authentication method implementations +- Various Stream encoding tools +- Message decorators +- Message factory implementations for Guzzle PSR-7 and Diactoros +- Cookie implementation +- Request matchers + + +## Documentation + +Please see the [official documentation](http://docs.php-http.org/en/latest/message.html). + + +## Testing + +``` bash +$ composer test +``` + + +## Credits + +Thanks to [Cuzzle](https://github.com/namshi/cuzzle) for inpiration for the `CurlCommandFormatter`. + + +## License + +The MIT License (MIT). Please see [License File](LICENSE) for more information. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/apigen.neon b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/apigen.neon new file mode 100644 index 0000000..0ba1a18 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/apigen.neon @@ -0,0 +1,6 @@ +source: + - src/ + +destination: build/api/ + +templateTheme: bootstrap diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/composer.json new file mode 100644 index 0000000..fc67cd0 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/composer.json @@ -0,0 +1,65 @@ +{ + "name": "php-http/message", + "description": "HTTP Message related tools", + "keywords": [ + "message", + "http", + "psr-7" + ], + "homepage": "http://php-http.org", + "license": "MIT", + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "require": { + "php": "^7.1 || ^8.0", + "clue/stream-filter": "^1.5", + "php-http/message-factory": "^1.0.2", + "psr/http-message": "^1.0" + }, + "provide": { + "php-http/message-factory-implementation": "1.0" + }, + "require-dev": { + "ext-zlib": "*", + "ergebnis/composer-normalize": "^2.6", + "guzzlehttp/psr7": "^1.0", + "phpspec/phpspec": "^5.1 || ^6.3", + "slim/slim": "^3.0", + "laminas/laminas-diactoros": "^2.0" + }, + "suggest": { + "ext-zlib": "Used with compressor/decompressor streams", + "guzzlehttp/psr7": "Used with Guzzle PSR-7 Factories", + "laminas/laminas-diactoros": "Used with Diactoros Factories", + "slim/slim": "Used with Slim Framework PSR-7 implementation" + }, + "config": { + "sort-packages": true + }, + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "autoload": { + "psr-4": { + "Http\\Message\\": "src/" + }, + "files": [ + "src/filters.php" + ] + }, + "autoload-dev": { + "psr-4": { + "spec\\Http\\Message\\": "spec/" + } + }, + "scripts": { + "test": "vendor/bin/phpspec run", + "test-ci": "vendor/bin/phpspec run -c phpspec.ci.yml" + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/puli.json b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/puli.json new file mode 100644 index 0000000..024a85d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/puli.json @@ -0,0 +1,111 @@ +{ + "version": "1.0", + "name": "php-http/message", + "bindings": { + "064d003d-78a1-48c4-8f3b-1f92ff25da69": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\DiactorosMessageFactory", + "type": "Http\\Message\\MessageFactory", + "parameters": { + "depends": "Zend\\Diactoros\\Request" + } + }, + "0836751e-6558-4d1b-8993-4a52012947c3": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\SlimMessageFactory", + "type": "Http\\Message\\ResponseFactory" + }, + "1d127622-dc61-4bfa-b9da-d221548d72c3": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\SlimMessageFactory", + "type": "Http\\Message\\RequestFactory" + }, + "2438c2d0-0658-441f-8855-ddaf0f87d54d": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\GuzzleMessageFactory", + "type": "Http\\Message\\MessageFactory", + "parameters": { + "depends": "GuzzleHttp\\Psr7\\Request" + } + }, + "253aa08c-d705-46e7-b1d2-e28c97eef792": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\GuzzleMessageFactory", + "type": "Http\\Message\\RequestFactory", + "parameters": { + "depends": "GuzzleHttp\\Psr7\\Request" + } + }, + "273a34f9-62f4-4ba1-9801-b1284d49ff89": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\StreamFactory\\GuzzleStreamFactory", + "type": "Http\\Message\\StreamFactory", + "parameters": { + "depends": "GuzzleHttp\\Psr7\\Stream" + } + }, + "304b83db-b594-4d83-ae75-1f633adf92f7": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\UriFactory\\GuzzleUriFactory", + "type": "Http\\Message\\UriFactory", + "parameters": { + "depends": "GuzzleHttp\\Psr7\\Uri" + } + }, + "3f4bc1cd-aa95-4702-9fa7-65408e471691": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\UriFactory\\DiactorosUriFactory", + "type": "Http\\Message\\UriFactory", + "parameters": { + "depends": "Zend\\Diactoros\\Uri" + } + }, + "4672a6ee-ad9e-4109-a5d1-b7d46f26c7a1": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\SlimMessageFactory", + "type": "Http\\Message\\MessageFactory" + }, + "6234e947-d3bd-43eb-97d5-7f9e22e6bb1b": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\DiactorosMessageFactory", + "type": "Http\\Message\\ResponseFactory", + "parameters": { + "depends": "Zend\\Diactoros\\Response" + } + }, + "6a9ad6ce-d82c-470f-8e30-60f21d9d95bf": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\UriFactory\\SlimUriFactory", + "type": "Http\\Message\\UriFactory" + }, + "72c2afa0-ea56-4d03-adb6-a9f241a8a734": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\StreamFactory\\SlimStreamFactory", + "type": "Http\\Message\\StreamFactory" + }, + "95c1be8f-39fe-4abd-8351-92cb14379a75": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\StreamFactory\\DiactorosStreamFactory", + "type": "Http\\Message\\StreamFactory", + "parameters": { + "depends": "Zend\\Diactoros\\Stream" + } + }, + "a018af27-7590-4dcf-83a1-497f95604cd6": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\GuzzleMessageFactory", + "type": "Http\\Message\\ResponseFactory", + "parameters": { + "depends": "GuzzleHttp\\Psr7\\Response" + } + }, + "c07955b1-de46-43db-923b-d07fae9382cb": { + "_class": "Puli\\Discovery\\Binding\\ClassBinding", + "class": "Http\\Message\\MessageFactory\\DiactorosMessageFactory", + "type": "Http\\Message\\RequestFactory", + "parameters": { + "depends": "Zend\\Diactoros\\Request" + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication.php new file mode 100644 index 0000000..0fe0cb3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication.php @@ -0,0 +1,25 @@ + + */ +interface Authentication +{ + /** + * Alter the request to add the authentication credentials. + * + * To do that, the implementation might use pre-stored credentials or do + * separate HTTP requests to obtain a valid token. + * + * @param RequestInterface $request The request without authentication information + * + * @return RequestInterface The request with added authentication information + */ + public function authenticate(RequestInterface $request); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/AutoBasicAuth.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/AutoBasicAuth.php new file mode 100644 index 0000000..7b6a429 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/AutoBasicAuth.php @@ -0,0 +1,48 @@ + + */ +final class AutoBasicAuth implements Authentication +{ + /** + * Whether user info should be removed from the URI. + * + * @var bool + */ + private $shouldRemoveUserInfo; + + /** + * @param bool|true $shouldRremoveUserInfo + */ + public function __construct($shouldRremoveUserInfo = true) + { + $this->shouldRemoveUserInfo = (bool) $shouldRremoveUserInfo; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + $uri = $request->getUri(); + $userInfo = $uri->getUserInfo(); + + if (!empty($userInfo)) { + if ($this->shouldRemoveUserInfo) { + $request = $request->withUri($uri->withUserInfo('')); + } + + $request = $request->withHeader('Authorization', sprintf('Basic %s', base64_encode($userInfo))); + } + + return $request; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/BasicAuth.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/BasicAuth.php new file mode 100644 index 0000000..23618a5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/BasicAuth.php @@ -0,0 +1,44 @@ + + */ +final class BasicAuth implements Authentication +{ + /** + * @var string + */ + private $username; + + /** + * @var string + */ + private $password; + + /** + * @param string $username + * @param string $password + */ + public function __construct($username, $password) + { + $this->username = $username; + $this->password = $password; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + $header = sprintf('Basic %s', base64_encode(sprintf('%s:%s', $this->username, $this->password))); + + return $request->withHeader('Authorization', $header); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Bearer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Bearer.php new file mode 100644 index 0000000..a8fb21a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Bearer.php @@ -0,0 +1,37 @@ + + */ +final class Bearer implements Authentication +{ + /** + * @var string + */ + private $token; + + /** + * @param string $token + */ + public function __construct($token) + { + $this->token = $token; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + $header = sprintf('Bearer %s', $this->token); + + return $request->withHeader('Authorization', $header); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Chain.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Chain.php new file mode 100644 index 0000000..71002bb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Chain.php @@ -0,0 +1,47 @@ + + */ +final class Chain implements Authentication +{ + /** + * @var Authentication[] + */ + private $authenticationChain = []; + + /** + * @param Authentication[] $authenticationChain + */ + public function __construct(array $authenticationChain = []) + { + foreach ($authenticationChain as $authentication) { + if (!$authentication instanceof Authentication) { + throw new \InvalidArgumentException( + 'Members of the authentication chain must be of type Http\Message\Authentication' + ); + } + } + + $this->authenticationChain = $authenticationChain; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + foreach ($this->authenticationChain as $authentication) { + $request = $authentication->authenticate($request); + } + + return $request; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Header.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Header.php new file mode 100644 index 0000000..97a04dd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Header.php @@ -0,0 +1,33 @@ +name = $name; + $this->value = $value; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + return $request->withHeader($this->name, $this->value); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Matching.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Matching.php new file mode 100644 index 0000000..7a5c247 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Matching.php @@ -0,0 +1,69 @@ + + * + * @deprecated since since version 1.2, and will be removed in 2.0. Use {@link RequestConditional} instead. + */ +final class Matching implements Authentication +{ + /** + * @var Authentication + */ + private $authentication; + + /** + * @var CallbackRequestMatcher + */ + private $matcher; + + public function __construct(Authentication $authentication, callable $matcher = null) + { + if (is_null($matcher)) { + $matcher = function () { + return true; + }; + } + + $this->authentication = $authentication; + $this->matcher = new CallbackRequestMatcher($matcher); + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + if ($this->matcher->matches($request)) { + return $this->authentication->authenticate($request); + } + + return $request; + } + + /** + * Creates a matching authentication for an URL. + * + * @param string $url + * + * @return self + */ + public static function createUrlMatcher(Authentication $authentication, $url) + { + $matcher = function (RequestInterface $request) use ($url) { + return preg_match($url, $request->getRequestTarget()); + }; + + return new static($authentication, $matcher); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/QueryParam.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/QueryParam.php new file mode 100644 index 0000000..243efef --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/QueryParam.php @@ -0,0 +1,47 @@ + + */ +final class QueryParam implements Authentication +{ + /** + * @var array + */ + private $params = []; + + public function __construct(array $params) + { + $this->params = $params; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + $uri = $request->getUri(); + $query = $uri->getQuery(); + $params = []; + + parse_str($query, $params); + + $params = array_merge($params, $this->params); + + $query = http_build_query($params, '', '&'); + + $uri = $uri->withQuery($query); + + return $request->withUri($uri); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/RequestConditional.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/RequestConditional.php new file mode 100644 index 0000000..01062cf --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/RequestConditional.php @@ -0,0 +1,43 @@ + + */ +final class RequestConditional implements Authentication +{ + /** + * @var RequestMatcher + */ + private $requestMatcher; + + /** + * @var Authentication + */ + private $authentication; + + public function __construct(RequestMatcher $requestMatcher, Authentication $authentication) + { + $this->requestMatcher = $requestMatcher; + $this->authentication = $authentication; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + if ($this->requestMatcher->matches($request)) { + return $this->authentication->authenticate($request); + } + + return $request; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Wsse.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Wsse.php new file mode 100644 index 0000000..f343633 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Authentication/Wsse.php @@ -0,0 +1,68 @@ + + */ +final class Wsse implements Authentication +{ + /** + * @var string + */ + private $username; + + /** + * @var string + */ + private $password; + + /** + * @var string + */ + private $hashAlgorithm; + + /** + * @param string $username + * @param string $password + * @param string $hashAlgorithm To use a better hashing algorithm than the weak sha1, pass the algorithm to use, e.g. "sha512" + */ + public function __construct($username, $password, $hashAlgorithm = 'sha1') + { + $this->username = $username; + $this->password = $password; + if (false === in_array($hashAlgorithm, hash_algos())) { + throw new InvalidArgumentException(sprintf('Unaccepted hashing algorithm: %s', $hashAlgorithm)); + } + $this->hashAlgorithm = $hashAlgorithm; + } + + /** + * {@inheritdoc} + */ + public function authenticate(RequestInterface $request) + { + $nonce = substr(md5(uniqid(uniqid().'_', true)), 0, 16); + $created = date('c'); + $digest = base64_encode(hash($this->hashAlgorithm, base64_decode($nonce).$created.$this->password, true)); + + $wsse = sprintf( + 'UsernameToken Username="%s", PasswordDigest="%s", Nonce="%s", Created="%s"', + $this->username, + $digest, + $nonce, + $created + ); + + return $request + ->withHeader('Authorization', 'WSSE profile="UsernameToken"') + ->withHeader('X-WSSE', $wsse) + ; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Builder/ResponseBuilder.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Builder/ResponseBuilder.php new file mode 100644 index 0000000..4c3ecfc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Builder/ResponseBuilder.php @@ -0,0 +1,146 @@ +response = $response; + } + + /** + * Return response. + * + * @return ResponseInterface + */ + public function getResponse() + { + return $this->response; + } + + /** + * Add headers represented by an array of header lines. + * + * @param string[] $headers response headers as array of header lines + * + * @return $this + * + * @throws \UnexpectedValueException for invalid header values + * @throws \InvalidArgumentException for invalid status code arguments + */ + public function setHeadersFromArray(array $headers) + { + $status = array_shift($headers); + $this->setStatus($status); + + foreach ($headers as $headerLine) { + $headerLine = trim($headerLine); + if ('' === $headerLine) { + continue; + } + + $this->addHeader($headerLine); + } + + return $this; + } + + /** + * Add headers represented by a single string. + * + * @param string $headers response headers as single string + * + * @return $this + * + * @throws \InvalidArgumentException if $headers is not a string on object with __toString() + * @throws \UnexpectedValueException for invalid header values + */ + public function setHeadersFromString($headers) + { + if (!(is_string($headers) + || (is_object($headers) && method_exists($headers, '__toString'))) + ) { + throw new \InvalidArgumentException( + sprintf( + '%s expects parameter 1 to be a string, %s given', + __METHOD__, + is_object($headers) ? get_class($headers) : gettype($headers) + ) + ); + } + + $this->setHeadersFromArray(explode("\r\n", $headers)); + + return $this; + } + + /** + * Set response status from a status string. + * + * @param string $statusLine response status as a string + * + * @return $this + * + * @throws \InvalidArgumentException for invalid status line + */ + public function setStatus($statusLine) + { + $parts = explode(' ', $statusLine, 3); + if (count($parts) < 2 || 0 !== strpos(strtolower($parts[0]), 'http/')) { + throw new \InvalidArgumentException( + sprintf('"%s" is not a valid HTTP status line', $statusLine) + ); + } + + $reasonPhrase = count($parts) > 2 ? $parts[2] : ''; + $this->response = $this->response + ->withStatus((int) $parts[1], $reasonPhrase) + ->withProtocolVersion(substr($parts[0], 5)); + + return $this; + } + + /** + * Add header represented by a string. + * + * @param string $headerLine response header as a string + * + * @return $this + * + * @throws \InvalidArgumentException for invalid header names or values + */ + public function addHeader($headerLine) + { + $parts = explode(':', $headerLine, 2); + if (2 !== count($parts)) { + throw new \InvalidArgumentException( + sprintf('"%s" is not a valid HTTP header line', $headerLine) + ); + } + $name = trim($parts[0]); + $value = trim($parts[1]); + if ($this->response->hasHeader($name)) { + $this->response = $this->response->withAddedHeader($name, $value); + } else { + $this->response = $this->response->withHeader($name, $value); + } + + return $this; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Cookie.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Cookie.php new file mode 100644 index 0000000..0cc2d43 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Cookie.php @@ -0,0 +1,524 @@ + + * + * @see http://tools.ietf.org/search/rfc6265 + */ +final class Cookie +{ + /** + * @var string + */ + private $name; + + /** + * @var string|null + */ + private $value; + + /** + * @var int|null + */ + private $maxAge; + + /** + * @var string|null + */ + private $domain; + + /** + * @var string + */ + private $path; + + /** + * @var bool + */ + private $secure; + + /** + * @var bool + */ + private $httpOnly; + + /** + * Expires attribute is HTTP 1.0 only and should be avoided. + * + * @var \DateTime|null + */ + private $expires; + + /** + * @param string $name + * @param string|null $value + * @param int|null $maxAge + * @param string|null $domain + * @param string|null $path + * @param bool $secure + * @param bool $httpOnly + * @param \DateTime|null $expires Expires attribute is HTTP 1.0 only and should be avoided. + * + * @throws \InvalidArgumentException if name, value or max age is not valid + */ + public function __construct( + $name, + $value = null, + $maxAge = null, + $domain = null, + $path = null, + $secure = false, + $httpOnly = false, + \DateTime $expires = null + ) { + $this->validateName($name); + $this->validateValue($value); + $this->validateMaxAge($maxAge); + + $this->name = $name; + $this->value = $value; + $this->maxAge = $maxAge; + $this->expires = $expires; + $this->domain = $this->normalizeDomain($domain); + $this->path = $this->normalizePath($path); + $this->secure = (bool) $secure; + $this->httpOnly = (bool) $httpOnly; + } + + /** + * Creates a new cookie without any attribute validation. + * + * @param string $name + * @param string|null $value + * @param int $maxAge + * @param string|null $domain + * @param string|null $path + * @param bool $secure + * @param bool $httpOnly + * @param \DateTime|null $expires Expires attribute is HTTP 1.0 only and should be avoided. + */ + public static function createWithoutValidation( + $name, + $value = null, + $maxAge = null, + $domain = null, + $path = null, + $secure = false, + $httpOnly = false, + \DateTime $expires = null + ) { + $cookie = new self('name', null, null, $domain, $path, $secure, $httpOnly, $expires); + $cookie->name = $name; + $cookie->value = $value; + $cookie->maxAge = $maxAge; + + return $cookie; + } + + /** + * Returns the name. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Returns the value. + * + * @return string|null + */ + public function getValue() + { + return $this->value; + } + + /** + * Checks if there is a value. + * + * @return bool + */ + public function hasValue() + { + return isset($this->value); + } + + /** + * Sets the value. + * + * @param string|null $value + * + * @return Cookie + */ + public function withValue($value) + { + $this->validateValue($value); + + $new = clone $this; + $new->value = $value; + + return $new; + } + + /** + * Returns the max age. + * + * @return int|null + */ + public function getMaxAge() + { + return $this->maxAge; + } + + /** + * Checks if there is a max age. + * + * @return bool + */ + public function hasMaxAge() + { + return isset($this->maxAge); + } + + /** + * Sets the max age. + * + * @param int|null $maxAge + * + * @return Cookie + */ + public function withMaxAge($maxAge) + { + $this->validateMaxAge($maxAge); + + $new = clone $this; + $new->maxAge = $maxAge; + + return $new; + } + + /** + * Returns the expiration time. + * + * @return \DateTime|null + */ + public function getExpires() + { + return $this->expires; + } + + /** + * Checks if there is an expiration time. + * + * @return bool + */ + public function hasExpires() + { + return isset($this->expires); + } + + /** + * Sets the expires. + * + * @return Cookie + */ + public function withExpires(\DateTime $expires = null) + { + $new = clone $this; + $new->expires = $expires; + + return $new; + } + + /** + * Checks if the cookie is expired. + * + * @return bool + */ + public function isExpired() + { + return isset($this->expires) and $this->expires < new \DateTime(); + } + + /** + * Returns the domain. + * + * @return string|null + */ + public function getDomain() + { + return $this->domain; + } + + /** + * Checks if there is a domain. + * + * @return bool + */ + public function hasDomain() + { + return isset($this->domain); + } + + /** + * Sets the domain. + * + * @param string|null $domain + * + * @return Cookie + */ + public function withDomain($domain) + { + $new = clone $this; + $new->domain = $this->normalizeDomain($domain); + + return $new; + } + + /** + * Checks whether this cookie is meant for this domain. + * + * @see http://tools.ietf.org/html/rfc6265#section-5.1.3 + * + * @param string $domain + * + * @return bool + */ + public function matchDomain($domain) + { + // Domain is not set or exact match + if (!$this->hasDomain() || 0 === strcasecmp($domain, $this->domain)) { + return true; + } + + // Domain is not an IP address + if (filter_var($domain, FILTER_VALIDATE_IP)) { + return false; + } + + return (bool) preg_match(sprintf('/\b%s$/i', preg_quote($this->domain)), $domain); + } + + /** + * Returns the path. + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Sets the path. + * + * @param string|null $path + * + * @return Cookie + */ + public function withPath($path) + { + $new = clone $this; + $new->path = $this->normalizePath($path); + + return $new; + } + + /** + * Checks whether this cookie is meant for this path. + * + * @see http://tools.ietf.org/html/rfc6265#section-5.1.4 + * + * @param string $path + * + * @return bool + */ + public function matchPath($path) + { + return $this->path === $path || (0 === strpos($path, rtrim($this->path, '/').'/')); + } + + /** + * Checks whether this cookie may only be sent over HTTPS. + * + * @return bool + */ + public function isSecure() + { + return $this->secure; + } + + /** + * Sets whether this cookie should only be sent over HTTPS. + * + * @param bool $secure + * + * @return Cookie + */ + public function withSecure($secure) + { + $new = clone $this; + $new->secure = (bool) $secure; + + return $new; + } + + /** + * Check whether this cookie may not be accessed through Javascript. + * + * @return bool + */ + public function isHttpOnly() + { + return $this->httpOnly; + } + + /** + * Sets whether this cookie may not be accessed through Javascript. + * + * @param bool $httpOnly + * + * @return Cookie + */ + public function withHttpOnly($httpOnly) + { + $new = clone $this; + $new->httpOnly = (bool) $httpOnly; + + return $new; + } + + /** + * Checks if this cookie represents the same cookie as $cookie. + * + * This does not compare the values, only name, domain and path. + * + * @param Cookie $cookie + * + * @return bool + */ + public function match(self $cookie) + { + return $this->name === $cookie->name && $this->domain === $cookie->domain and $this->path === $cookie->path; + } + + /** + * Validates cookie attributes. + * + * @return bool + */ + public function isValid() + { + try { + $this->validateName($this->name); + $this->validateValue($this->value); + $this->validateMaxAge($this->maxAge); + } catch (\InvalidArgumentException $e) { + return false; + } + + return true; + } + + /** + * Validates the name attribute. + * + * @see http://tools.ietf.org/search/rfc2616#section-2.2 + * + * @param string $name + * + * @throws \InvalidArgumentException if the name is empty or contains invalid characters + */ + private function validateName($name) + { + if (strlen($name) < 1) { + throw new \InvalidArgumentException('The name cannot be empty'); + } + + // Name attribute is a token as per spec in RFC 2616 + if (preg_match('/[\x00-\x20\x22\x28-\x29\x2C\x2F\x3A-\x40\x5B-\x5D\x7B\x7D\x7F]/', $name)) { + throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name)); + } + } + + /** + * Validates a value. + * + * @see http://tools.ietf.org/html/rfc6265#section-4.1.1 + * + * @param string|null $value + * + * @throws \InvalidArgumentException if the value contains invalid characters + */ + private function validateValue($value) + { + if (isset($value)) { + if (preg_match('/[^\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/', $value)) { + throw new \InvalidArgumentException(sprintf('The cookie value "%s" contains invalid characters.', $value)); + } + } + } + + /** + * Validates a Max-Age attribute. + * + * @param int|null $maxAge + * + * @throws \InvalidArgumentException if the Max-Age is not an empty or integer value + */ + private function validateMaxAge($maxAge) + { + if (isset($maxAge)) { + if (!is_int($maxAge)) { + throw new \InvalidArgumentException('Max-Age must be integer'); + } + } + } + + /** + * Remove the leading '.' and lowercase the domain as per spec in RFC 6265. + * + * @see http://tools.ietf.org/html/rfc6265#section-4.1.2.3 + * @see http://tools.ietf.org/html/rfc6265#section-5.1.3 + * @see http://tools.ietf.org/html/rfc6265#section-5.2.3 + * + * @param string|null $domain + * + * @return string + */ + private function normalizeDomain($domain) + { + if (isset($domain)) { + $domain = ltrim(strtolower($domain), '.'); + } + + return $domain; + } + + /** + * Processes path as per spec in RFC 6265. + * + * @see http://tools.ietf.org/html/rfc6265#section-5.1.4 + * @see http://tools.ietf.org/html/rfc6265#section-5.2.4 + * + * @param string|null $path + * + * @return string + */ + private function normalizePath($path) + { + $path = rtrim($path, '/'); + + if (empty($path) or '/' !== substr($path, 0, 1)) { + $path = '/'; + } + + return $path; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieJar.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieJar.php new file mode 100644 index 0000000..1479cc6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieJar.php @@ -0,0 +1,210 @@ + + */ +final class CookieJar implements \Countable, \IteratorAggregate +{ + /** + * @var \SplObjectStorage + */ + private $cookies; + + public function __construct() + { + $this->cookies = new \SplObjectStorage(); + } + + /** + * Checks if there is a cookie. + * + * @return bool + */ + public function hasCookie(Cookie $cookie) + { + return $this->cookies->contains($cookie); + } + + /** + * Adds a cookie. + */ + public function addCookie(Cookie $cookie) + { + if (!$this->hasCookie($cookie)) { + $cookies = $this->getMatchingCookies($cookie); + + foreach ($cookies as $matchingCookie) { + if ($cookie->getValue() !== $matchingCookie->getValue() || $cookie->getMaxAge() > $matchingCookie->getMaxAge()) { + $this->removeCookie($matchingCookie); + + continue; + } + } + + if ($cookie->hasValue()) { + $this->cookies->attach($cookie); + } + } + } + + /** + * Removes a cookie. + */ + public function removeCookie(Cookie $cookie) + { + $this->cookies->detach($cookie); + } + + /** + * Returns the cookies. + * + * @return Cookie[] + */ + public function getCookies() + { + $match = function ($matchCookie) { + return true; + }; + + return $this->findMatchingCookies($match); + } + + /** + * Returns all matching cookies. + * + * @return Cookie[] + */ + public function getMatchingCookies(Cookie $cookie) + { + $match = function ($matchCookie) use ($cookie) { + return $matchCookie->match($cookie); + }; + + return $this->findMatchingCookies($match); + } + + /** + * Finds matching cookies based on a callable. + * + * @return Cookie[] + */ + private function findMatchingCookies(callable $match) + { + $cookies = []; + + foreach ($this->cookies as $cookie) { + if ($match($cookie)) { + $cookies[] = $cookie; + } + } + + return $cookies; + } + + /** + * Checks if there are cookies. + * + * @return bool + */ + public function hasCookies() + { + return $this->cookies->count() > 0; + } + + /** + * Sets the cookies and removes any previous one. + * + * @param Cookie[] $cookies + */ + public function setCookies(array $cookies) + { + $this->clear(); + $this->addCookies($cookies); + } + + /** + * Adds some cookies. + * + * @param Cookie[] $cookies + */ + public function addCookies(array $cookies) + { + foreach ($cookies as $cookie) { + $this->addCookie($cookie); + } + } + + /** + * Removes some cookies. + * + * @param Cookie[] $cookies + */ + public function removeCookies(array $cookies) + { + foreach ($cookies as $cookie) { + $this->removeCookie($cookie); + } + } + + /** + * Removes cookies which match the given parameters. + * + * Null means that parameter should not be matched + * + * @param string|null $name + * @param string|null $domain + * @param string|null $path + */ + public function removeMatchingCookies($name = null, $domain = null, $path = null) + { + $match = function ($cookie) use ($name, $domain, $path) { + $match = true; + + if (isset($name)) { + $match = $match && ($cookie->getName() === $name); + } + + if (isset($domain)) { + $match = $match && $cookie->matchDomain($domain); + } + + if (isset($path)) { + $match = $match && $cookie->matchPath($path); + } + + return $match; + }; + + $cookies = $this->findMatchingCookies($match); + + $this->removeCookies($cookies); + } + + /** + * Removes all cookies. + */ + public function clear() + { + $this->cookies = new \SplObjectStorage(); + } + + /** + * {@inheritdoc} + */ + public function count() + { + return $this->cookies->count(); + } + + /** + * {@inheritdoc} + */ + public function getIterator() + { + return clone $this->cookies; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieUtil.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieUtil.php new file mode 100644 index 0000000..44c5314 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/CookieUtil.php @@ -0,0 +1,53 @@ + + */ +trait MessageDecorator +{ + /** + * @var MessageInterface + */ + private $message; + + /** + * Returns the decorated message. + * + * Since the underlying Message is immutable as well + * exposing it is not an issue, because it's state cannot be altered + * + * @return MessageInterface + */ + public function getMessage() + { + return $this->message; + } + + /** + * {@inheritdoc} + */ + public function getProtocolVersion() + { + return $this->message->getProtocolVersion(); + } + + /** + * {@inheritdoc} + */ + public function withProtocolVersion($version) + { + $new = clone $this; + $new->message = $this->message->withProtocolVersion($version); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getHeaders() + { + return $this->message->getHeaders(); + } + + /** + * {@inheritdoc} + */ + public function hasHeader($header) + { + return $this->message->hasHeader($header); + } + + /** + * {@inheritdoc} + */ + public function getHeader($header) + { + return $this->message->getHeader($header); + } + + /** + * {@inheritdoc} + */ + public function getHeaderLine($header) + { + return $this->message->getHeaderLine($header); + } + + /** + * {@inheritdoc} + */ + public function withHeader($header, $value) + { + $new = clone $this; + $new->message = $this->message->withHeader($header, $value); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function withAddedHeader($header, $value) + { + $new = clone $this; + $new->message = $this->message->withAddedHeader($header, $value); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function withoutHeader($header) + { + $new = clone $this; + $new->message = $this->message->withoutHeader($header); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getBody() + { + return $this->message->getBody(); + } + + /** + * {@inheritdoc} + */ + public function withBody(StreamInterface $body) + { + $new = clone $this; + $new->message = $this->message->withBody($body); + + return $new; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/RequestDecorator.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/RequestDecorator.php new file mode 100644 index 0000000..bd254a8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/RequestDecorator.php @@ -0,0 +1,86 @@ + + */ +trait RequestDecorator +{ + use MessageDecorator { + getMessage as getRequest; + } + + /** + * Exchanges the underlying request with another. + * + * @return self + */ + public function withRequest(RequestInterface $request) + { + $new = clone $this; + $new->message = $request; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getRequestTarget() + { + return $this->message->getRequestTarget(); + } + + /** + * {@inheritdoc} + */ + public function withRequestTarget($requestTarget) + { + $new = clone $this; + $new->message = $this->message->withRequestTarget($requestTarget); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getMethod() + { + return $this->message->getMethod(); + } + + /** + * {@inheritdoc} + */ + public function withMethod($method) + { + $new = clone $this; + $new->message = $this->message->withMethod($method); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getUri() + { + return $this->message->getUri(); + } + + /** + * {@inheritdoc} + */ + public function withUri(UriInterface $uri, $preserveHost = false) + { + $new = clone $this; + $new->message = $this->message->withUri($uri, $preserveHost); + + return $new; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/ResponseDecorator.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/ResponseDecorator.php new file mode 100644 index 0000000..20319ed --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/ResponseDecorator.php @@ -0,0 +1,55 @@ + + */ +trait ResponseDecorator +{ + use MessageDecorator { + getMessage as getResponse; + } + + /** + * Exchanges the underlying response with another. + * + * @return self + */ + public function withResponse(ResponseInterface $response) + { + $new = clone $this; + $new->message = $response; + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getStatusCode() + { + return $this->message->getStatusCode(); + } + + /** + * {@inheritdoc} + */ + public function withStatus($code, $reasonPhrase = '') + { + $new = clone $this; + $new->message = $this->message->withStatus($code, $reasonPhrase); + + return $new; + } + + /** + * {@inheritdoc} + */ + public function getReasonPhrase() + { + return $this->message->getReasonPhrase(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/StreamDecorator.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/StreamDecorator.php new file mode 100644 index 0000000..f405c7a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Decorator/StreamDecorator.php @@ -0,0 +1,138 @@ + + */ +trait StreamDecorator +{ + /** + * @var StreamInterface + */ + protected $stream; + + /** + * {@inheritdoc} + */ + public function __toString() + { + return $this->stream->__toString(); + } + + /** + * {@inheritdoc} + */ + public function close() + { + $this->stream->close(); + } + + /** + * {@inheritdoc} + */ + public function detach() + { + return $this->stream->detach(); + } + + /** + * {@inheritdoc} + */ + public function getSize() + { + return $this->stream->getSize(); + } + + /** + * {@inheritdoc} + */ + public function tell() + { + return $this->stream->tell(); + } + + /** + * {@inheritdoc} + */ + public function eof() + { + return $this->stream->eof(); + } + + /** + * {@inheritdoc} + */ + public function isSeekable() + { + return $this->stream->isSeekable(); + } + + /** + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + $this->stream->seek($offset, $whence); + } + + /** + * {@inheritdoc} + */ + public function rewind() + { + $this->stream->rewind(); + } + + /** + * {@inheritdoc} + */ + public function isWritable() + { + return $this->stream->isWritable(); + } + + /** + * {@inheritdoc} + */ + public function write($string) + { + return $this->stream->write($string); + } + + /** + * {@inheritdoc} + */ + public function isReadable() + { + return $this->stream->isReadable(); + } + + /** + * {@inheritdoc} + */ + public function read($length) + { + return $this->stream->read($length); + } + + /** + * {@inheritdoc} + */ + public function getContents() + { + return $this->stream->getContents(); + } + + /** + * {@inheritdoc} + */ + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/ChunkStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/ChunkStream.php new file mode 100644 index 0000000..74c2fbd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/ChunkStream.php @@ -0,0 +1,39 @@ + + */ +class ChunkStream extends FilteredStream +{ + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'chunk'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'dechunk'; + } + + /** + * {@inheritdoc} + */ + protected function fill() + { + parent::fill(); + + if ($this->stream->eof()) { + $this->buffer .= "0\r\n\r\n"; + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/CompressStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/CompressStream.php new file mode 100644 index 0000000..bdb740a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/CompressStream.php @@ -0,0 +1,45 @@ + + */ +class CompressStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + if (!extension_loaded('zlib')) { + throw new \RuntimeException('The zlib extension must be enabled to use this stream'); + } + + parent::__construct($stream, ['window' => 15, 'level' => $level]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => 15]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.deflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.inflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DechunkStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DechunkStream.php new file mode 100644 index 0000000..4cade83 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DechunkStream.php @@ -0,0 +1,29 @@ + + */ +class DechunkStream extends FilteredStream +{ + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'dechunk'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'chunk'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DecompressStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DecompressStream.php new file mode 100644 index 0000000..ab3a345 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DecompressStream.php @@ -0,0 +1,45 @@ + + */ +class DecompressStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + if (!extension_loaded('zlib')) { + throw new \RuntimeException('The zlib extension must be enabled to use this stream'); + } + + parent::__construct($stream, ['window' => 15]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => 15, 'level' => $level]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.inflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.deflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DeflateStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DeflateStream.php new file mode 100644 index 0000000..2ab3e00 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/DeflateStream.php @@ -0,0 +1,41 @@ + + */ +class DeflateStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + parent::__construct($stream, ['window' => -15, 'level' => $level]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => -15]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.deflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.inflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/Filter/Chunk.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/Filter/Chunk.php new file mode 100644 index 0000000..0f8f53b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/Filter/Chunk.php @@ -0,0 +1,30 @@ + + */ +class Chunk extends \php_user_filter +{ + /** + * {@inheritdoc} + */ + public function filter($in, $out, &$consumed, $closing) + { + while ($bucket = stream_bucket_make_writeable($in)) { + $lenbucket = stream_bucket_new($this->stream, dechex($bucket->datalen)."\r\n"); + stream_bucket_append($out, $lenbucket); + + $consumed += $bucket->datalen; + stream_bucket_append($out, $bucket); + + $lenbucket = stream_bucket_new($this->stream, "\r\n"); + stream_bucket_append($out, $lenbucket); + } + + return PSFS_PASS_ON; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/FilteredStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/FilteredStream.php new file mode 100644 index 0000000..a937c82 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/FilteredStream.php @@ -0,0 +1,234 @@ + + */ +abstract class FilteredStream implements StreamInterface +{ + use StreamDecorator { + rewind as private doRewind; + seek as private doSeek; + } + const BUFFER_SIZE = 8192; + + /** + * @var callable + */ + protected $readFilterCallback; + + /** + * @var resource + * + * @deprecated since version 1.5, will be removed in 2.0 + */ + protected $readFilter; + + /** + * @var callable + * + * @deprecated since version 1.5, will be removed in 2.0 + */ + protected $writeFilterCallback; + + /** + * @var resource + * + * @deprecated since version 1.5, will be removed in 2.0 + */ + protected $writeFilter; + + /** + * Internal buffer. + * + * @var string + */ + protected $buffer = ''; + + /** + * @param mixed|null $readFilterOptions + * @param mixed|null $writeFilterOptions deprecated since 1.5, will be removed in 2.0 + */ + public function __construct(StreamInterface $stream, $readFilterOptions = null, $writeFilterOptions = null) + { + if (null !== $readFilterOptions) { + $this->readFilterCallback = Filter\fun($this->readFilter(), $readFilterOptions); + } else { + $this->readFilterCallback = Filter\fun($this->readFilter()); + } + + if (null !== $writeFilterOptions) { + $this->writeFilterCallback = Filter\fun($this->writeFilter(), $writeFilterOptions); + + @trigger_error('The $writeFilterOptions argument is deprecated since version 1.5 and will be removed in 2.0.', E_USER_DEPRECATED); + } else { + $this->writeFilterCallback = Filter\fun($this->writeFilter()); + } + + $this->stream = $stream; + } + + /** + * {@inheritdoc} + */ + public function read($length) + { + if (strlen($this->buffer) >= $length) { + $read = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + + return $read; + } + + if ($this->stream->eof()) { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + $read = $this->buffer; + $this->buffer = ''; + $this->fill(); + + return $read.$this->read($length - strlen($read)); + } + + /** + * {@inheritdoc} + */ + public function eof() + { + return $this->stream->eof() && '' === $this->buffer; + } + + /** + * Buffer is filled by reading underlying stream. + * + * Callback is reading once more even if the stream is ended. + * This allow to get last data in the PHP buffer otherwise this + * bug is present : https://bugs.php.net/bug.php?id=48725 + */ + protected function fill() + { + $readFilterCallback = $this->readFilterCallback; + $this->buffer .= $readFilterCallback($this->stream->read(self::BUFFER_SIZE)); + + if ($this->stream->eof()) { + $this->buffer .= $readFilterCallback(); + } + } + + /** + * {@inheritdoc} + */ + public function getContents() + { + $buffer = ''; + + while (!$this->eof()) { + $buf = $this->read(self::BUFFER_SIZE); + // Using a loose equality here to match on '' and false. + if (null == $buf) { + break; + } + + $buffer .= $buf; + } + + return $buffer; + } + + /** + * Always returns null because we can't tell the size of a stream when we filter. + */ + public function getSize() + { + return null; + } + + /** + * {@inheritdoc} + */ + public function __toString() + { + return $this->getContents(); + } + + /** + * Filtered streams are not seekable. + * + * We would need to buffer and process everything to allow seeking. + */ + public function isSeekable() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function rewind() + { + @trigger_error('Filtered streams are not seekable. This method will start raising an exception in the next major version', E_USER_DEPRECATED); + $this->doRewind(); + } + + /** + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + @trigger_error('Filtered streams are not seekable. This method will start raising an exception in the next major version', E_USER_DEPRECATED); + $this->doSeek($offset, $whence); + } + + /** + * Returns the read filter name. + * + * @return string + * + * @deprecated since version 1.5, will be removed in 2.0 + */ + public function getReadFilter() + { + @trigger_error('The '.__CLASS__.'::'.__METHOD__.' method is deprecated since version 1.5 and will be removed in 2.0.', E_USER_DEPRECATED); + + return $this->readFilter(); + } + + /** + * Returns the write filter name. + * + * @return string + */ + abstract protected function readFilter(); + + /** + * Returns the write filter name. + * + * @return string + * + * @deprecated since version 1.5, will be removed in 2.0 + */ + public function getWriteFilter() + { + @trigger_error('The '.__CLASS__.'::'.__METHOD__.' method is deprecated since version 1.5 and will be removed in 2.0.', E_USER_DEPRECATED); + + return $this->writeFilter(); + } + + /** + * Returns the write filter name. + * + * @return string + */ + abstract protected function writeFilter(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipDecodeStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipDecodeStream.php new file mode 100644 index 0000000..92b5dad --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipDecodeStream.php @@ -0,0 +1,45 @@ + + */ +class GzipDecodeStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + if (!extension_loaded('zlib')) { + throw new \RuntimeException('The zlib extension must be enabled to use this stream'); + } + + parent::__construct($stream, ['window' => 31]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => 31, 'level' => $level]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.inflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.deflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipEncodeStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipEncodeStream.php new file mode 100644 index 0000000..13f097a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/GzipEncodeStream.php @@ -0,0 +1,45 @@ + + */ +class GzipEncodeStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + if (!extension_loaded('zlib')) { + throw new \RuntimeException('The zlib extension must be enabled to use this stream'); + } + + parent::__construct($stream, ['window' => 31, 'level' => $level]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => 31]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.deflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.inflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/InflateStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/InflateStream.php new file mode 100644 index 0000000..06c5187 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Encoding/InflateStream.php @@ -0,0 +1,45 @@ + + */ +class InflateStream extends FilteredStream +{ + /** + * @param int $level + */ + public function __construct(StreamInterface $stream, $level = -1) + { + if (!extension_loaded('zlib')) { + throw new \RuntimeException('The zlib extension must be enabled to use this stream'); + } + + parent::__construct($stream, ['window' => -15]); + + // @deprecated will be removed in 2.0 + $this->writeFilterCallback = Filter\fun($this->writeFilter(), ['window' => -15, 'level' => $level]); + } + + /** + * {@inheritdoc} + */ + protected function readFilter() + { + return 'zlib.inflate'; + } + + /** + * {@inheritdoc} + */ + protected function writeFilter() + { + return 'zlib.deflate'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Exception.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Exception.php new file mode 100644 index 0000000..80d4cd9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Exception.php @@ -0,0 +1,10 @@ + + */ +interface Formatter +{ + /** + * Formats a request. + * + * @return string + */ + public function formatRequest(RequestInterface $request); + + /** + * Formats a response. + * + * @return string + */ + public function formatResponse(ResponseInterface $response); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/CurlCommandFormatter.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/CurlCommandFormatter.php new file mode 100644 index 0000000..78b1d55 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/CurlCommandFormatter.php @@ -0,0 +1,93 @@ + + */ +class CurlCommandFormatter implements Formatter +{ + /** + * {@inheritdoc} + */ + public function formatRequest(RequestInterface $request) + { + $command = sprintf('curl %s', escapeshellarg((string) $request->getUri()->withFragment(''))); + if ('1.0' === $request->getProtocolVersion()) { + $command .= ' --http1.0'; + } elseif ('2.0' === $request->getProtocolVersion()) { + $command .= ' --http2'; + } + + $method = strtoupper($request->getMethod()); + if ('HEAD' === $method) { + $command .= ' --head'; + } elseif ('GET' !== $method) { + $command .= ' --request '.$method; + } + + $command .= $this->getHeadersAsCommandOptions($request); + + $body = $request->getBody(); + if ($body->getSize() > 0) { + // escapeshellarg argument max length on Windows, but longer body in curl command would be impractical anyways + if ($body->getSize() > 8192) { + $data = '[too long stream omitted]'; + } elseif ($body->isSeekable()) { + $data = $body->__toString(); + $body->rewind(); + // all non-printable ASCII characters and except for \t, \r, \n + if (preg_match('/([\x00-\x09\x0C\x0E-\x1F\x7F])/', $data)) { + $data = '[binary stream omitted]'; + } + } else { + $data = '[non-seekable stream omitted]'; + } + $escapedData = @escapeshellarg($data); + if (empty($escapedData)) { + $escapedData = 'We couldn\'t not escape the data properly'; + } + + $command .= sprintf(' --data %s', $escapedData); + } + + return $command; + } + + /** + * {@inheritdoc} + */ + public function formatResponse(ResponseInterface $response) + { + return ''; + } + + /** + * @return string + */ + private function getHeadersAsCommandOptions(RequestInterface $request) + { + $command = ''; + foreach ($request->getHeaders() as $name => $values) { + if ('host' === strtolower($name) && $values[0] === $request->getUri()->getHost()) { + continue; + } + + if ('user-agent' === strtolower($name)) { + $command .= sprintf(' -A %s', escapeshellarg($values[0])); + + continue; + } + + $command .= sprintf(' -H %s', escapeshellarg($name.': '.$request->getHeaderLine($name))); + } + + return $command; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/FullHttpMessageFormatter.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/FullHttpMessageFormatter.php new file mode 100644 index 0000000..bb22efe --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/FullHttpMessageFormatter.php @@ -0,0 +1,106 @@ + + */ +class FullHttpMessageFormatter implements Formatter +{ + /** + * The maximum length of the body. + * + * @var int|null + */ + private $maxBodyLength; + + /** + * @var string + */ + private $binaryDetectionRegex; + + /** + * @param int|null $maxBodyLength + * @param string $binaryDetectionRegex By default, this is all non-printable ASCII characters and except for \t, \r, \n + */ + public function __construct($maxBodyLength = 1000, string $binaryDetectionRegex = '/([\x00-\x09\x0C\x0E-\x1F\x7F])/') + { + $this->maxBodyLength = $maxBodyLength; + $this->binaryDetectionRegex = $binaryDetectionRegex; + } + + /** + * {@inheritdoc} + */ + public function formatRequest(RequestInterface $request) + { + $message = sprintf( + "%s %s HTTP/%s\n", + $request->getMethod(), + $request->getRequestTarget(), + $request->getProtocolVersion() + ); + + foreach ($request->getHeaders() as $name => $values) { + $message .= $name.': '.implode(', ', $values)."\n"; + } + + return $this->addBody($request, $message); + } + + /** + * {@inheritdoc} + */ + public function formatResponse(ResponseInterface $response) + { + $message = sprintf( + "HTTP/%s %s %s\n", + $response->getProtocolVersion(), + $response->getStatusCode(), + $response->getReasonPhrase() + ); + + foreach ($response->getHeaders() as $name => $values) { + $message .= $name.': '.implode(', ', $values)."\n"; + } + + return $this->addBody($response, $message); + } + + /** + * Add the message body if the stream is seekable. + * + * @param string $message + * + * @return string + */ + private function addBody(MessageInterface $request, $message) + { + $message .= "\n"; + $stream = $request->getBody(); + if (!$stream->isSeekable() || 0 === $this->maxBodyLength) { + // Do not read the stream + return $message; + } + + $data = $stream->__toString(); + $stream->rewind(); + + if (preg_match($this->binaryDetectionRegex, $data)) { + return $message.'[binary stream omitted]'; + } + + if (null === $this->maxBodyLength) { + return $message.$data; + } + + return $message.mb_substr($data, 0, $this->maxBodyLength); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/SimpleFormatter.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/SimpleFormatter.php new file mode 100644 index 0000000..b1fcabd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Formatter/SimpleFormatter.php @@ -0,0 +1,42 @@ + + * @author Márk Sági-Kazár + */ +class SimpleFormatter implements Formatter +{ + /** + * {@inheritdoc} + */ + public function formatRequest(RequestInterface $request) + { + return sprintf( + '%s %s %s', + $request->getMethod(), + $request->getUri()->__toString(), + $request->getProtocolVersion() + ); + } + + /** + * {@inheritdoc} + */ + public function formatResponse(ResponseInterface $response) + { + return sprintf( + '%s %s %s', + $response->getStatusCode(), + $response->getReasonPhrase(), + $response->getProtocolVersion() + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/DiactorosMessageFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/DiactorosMessageFactory.php new file mode 100644 index 0000000..6d54d35 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/DiactorosMessageFactory.php @@ -0,0 +1,82 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Diactoros PSR-17 factory + */ +final class DiactorosMessageFactory implements MessageFactory +{ + /** + * @var DiactorosStreamFactory + */ + private $streamFactory; + + public function __construct() + { + $this->streamFactory = new DiactorosStreamFactory(); + } + + /** + * {@inheritdoc} + */ + public function createRequest( + $method, + $uri, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + if (class_exists(LaminasRequest::class)) { + return (new LaminasRequest( + $uri, + $method, + $this->streamFactory->createStream($body), + $headers + ))->withProtocolVersion($protocolVersion); + } + + return (new ZendRequest( + $uri, + $method, + $this->streamFactory->createStream($body), + $headers + ))->withProtocolVersion($protocolVersion); + } + + /** + * {@inheritdoc} + */ + public function createResponse( + $statusCode = 200, + $reasonPhrase = null, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + if (class_exists(LaminasResponse::class)) { + return (new LaminasResponse( + $this->streamFactory->createStream($body), + $statusCode, + $headers + ))->withProtocolVersion($protocolVersion); + } + + return (new ZendResponse( + $this->streamFactory->createStream($body), + $statusCode, + $headers + ))->withProtocolVersion($protocolVersion); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/GuzzleMessageFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/GuzzleMessageFactory.php new file mode 100644 index 0000000..02989d9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/GuzzleMessageFactory.php @@ -0,0 +1,55 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Guzzle PSR-17 factory + */ +final class GuzzleMessageFactory implements MessageFactory +{ + /** + * {@inheritdoc} + */ + public function createRequest( + $method, + $uri, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + return new Request( + $method, + $uri, + $headers, + $body, + $protocolVersion + ); + } + + /** + * {@inheritdoc} + */ + public function createResponse( + $statusCode = 200, + $reasonPhrase = null, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + return new Response( + $statusCode, + $headers, + $body, + $protocolVersion, + $reasonPhrase + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/SlimMessageFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/SlimMessageFactory.php new file mode 100644 index 0000000..bee9322 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/MessageFactory/SlimMessageFactory.php @@ -0,0 +1,74 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Slim PSR-17 factory + */ +final class SlimMessageFactory implements MessageFactory +{ + /** + * @var SlimStreamFactory + */ + private $streamFactory; + + /** + * @var SlimUriFactory + */ + private $uriFactory; + + public function __construct() + { + $this->streamFactory = new SlimStreamFactory(); + $this->uriFactory = new SlimUriFactory(); + } + + /** + * {@inheritdoc} + */ + public function createRequest( + $method, + $uri, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + return (new Request( + $method, + $this->uriFactory->createUri($uri), + new Headers($headers), + [], + [], + $this->streamFactory->createStream($body), + [] + ))->withProtocolVersion($protocolVersion); + } + + /** + * {@inheritdoc} + */ + public function createResponse( + $statusCode = 200, + $reasonPhrase = null, + array $headers = [], + $body = null, + $protocolVersion = '1.1' + ) { + return (new Response( + $statusCode, + new Headers($headers), + $this->streamFactory->createStream($body) + ))->withProtocolVersion($protocolVersion); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher.php new file mode 100644 index 0000000..94fe532 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher.php @@ -0,0 +1,26 @@ + + */ +interface RequestMatcher +{ + /** + * Decides whether the rule(s) implemented by the strategy matches the supplied request. + * + * @param RequestInterface $request The PSR7 request to check for a match + * + * @return bool true if the request matches, false otherwise + */ + public function matches(RequestInterface $request); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/CallbackRequestMatcher.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/CallbackRequestMatcher.php new file mode 100644 index 0000000..1197dd9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/CallbackRequestMatcher.php @@ -0,0 +1,32 @@ + + */ +final class CallbackRequestMatcher implements RequestMatcher +{ + /** + * @var callable + */ + private $callback; + + public function __construct(callable $callback) + { + $this->callback = $callback; + } + + /** + * {@inheritdoc} + */ + public function matches(RequestInterface $request) + { + return (bool) call_user_func($this->callback, $request); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RegexRequestMatcher.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RegexRequestMatcher.php new file mode 100644 index 0000000..91f3729 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RegexRequestMatcher.php @@ -0,0 +1,41 @@ + + * + * @deprecated since version 1.2 and will be removed in 2.0. Use {@link RequestMatcher} instead. + */ +final class RegexRequestMatcher implements RequestMatcher +{ + /** + * Matching regex. + * + * @var string + */ + private $regex; + + /** + * @param string $regex + */ + public function __construct($regex) + { + $this->regex = $regex; + } + + /** + * {@inheritdoc} + */ + public function matches(RequestInterface $request) + { + return (bool) preg_match($this->regex, (string) $request->getUri()); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RequestMatcher.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RequestMatcher.php new file mode 100644 index 0000000..e2aa021 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/RequestMatcher/RequestMatcher.php @@ -0,0 +1,78 @@ + + * @author Joel Wurtz + */ +final class RequestMatcher implements RequestMatcherInterface +{ + /** + * @var string + */ + private $path; + + /** + * @var string + */ + private $host; + + /** + * @var array + */ + private $methods = []; + + /** + * @var string[] + */ + private $schemes = []; + + /** + * The regular expressions used for path or host must be specified without delimiter. + * You do not need to escape the forward slash / to match it. + * + * @param string|null $path Regular expression for the path + * @param string|null $host Regular expression for the hostname + * @param string|string[]|null $methods Method or list of methods to match + * @param string|string[]|null $schemes Scheme or list of schemes to match (e.g. http or https) + */ + public function __construct($path = null, $host = null, $methods = [], $schemes = []) + { + $this->path = $path; + $this->host = $host; + $this->methods = array_map('strtoupper', (array) $methods); + $this->schemes = array_map('strtolower', (array) $schemes); + } + + /** + * {@inheritdoc} + * + * @api + */ + public function matches(RequestInterface $request) + { + if ($this->schemes && !in_array($request->getUri()->getScheme(), $this->schemes)) { + return false; + } + + if ($this->methods && !in_array($request->getMethod(), $this->methods)) { + return false; + } + + if (null !== $this->path && !preg_match('{'.$this->path.'}', rawurldecode($request->getUri()->getPath()))) { + return false; + } + + if (null !== $this->host && !preg_match('{'.$this->host.'}i', $request->getUri()->getHost())) { + return false; + } + + return true; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Stream/BufferedStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Stream/BufferedStream.php new file mode 100644 index 0000000..1eac974 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/Stream/BufferedStream.php @@ -0,0 +1,270 @@ +stream = $stream; + $this->size = $stream->getSize(); + + if ($useFileBuffer) { + $this->resource = fopen('php://temp/maxmemory:'.$memoryBuffer, 'rw+'); + } else { + $this->resource = fopen('php://memory', 'rw+'); + } + + if (false === $this->resource) { + throw new \RuntimeException('Cannot create a resource over temp or memory implementation'); + } + } + + /** + * {@inheritdoc} + */ + public function __toString() + { + try { + $this->rewind(); + + return $this->getContents(); + } catch (\Throwable $throwable) { + return ''; + } catch (\Exception $exception) { // Layer to be BC with PHP 5, remove this when we only support PHP 7+ + return ''; + } + } + + /** + * {@inheritdoc} + */ + public function close() + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot close on a detached stream'); + } + + $this->stream->close(); + fclose($this->resource); + } + + /** + * {@inheritdoc} + */ + public function detach() + { + if (null === $this->resource) { + return; + } + + // Force reading the remaining data of the stream + $this->getContents(); + + $resource = $this->resource; + $this->stream->close(); + $this->stream = null; + $this->resource = null; + + return $resource; + } + + /** + * {@inheritdoc} + */ + public function getSize() + { + if (null === $this->resource) { + return; + } + + if (null === $this->size && $this->stream->eof()) { + return $this->written; + } + + return $this->size; + } + + /** + * {@inheritdoc} + */ + public function tell() + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot tell on a detached stream'); + } + + return ftell($this->resource); + } + + /** + * {@inheritdoc} + */ + public function eof() + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot call eof on a detached stream'); + } + + // We are at the end only when both our resource and underlying stream are at eof + return $this->stream->eof() && (ftell($this->resource) === $this->written); + } + + /** + * {@inheritdoc} + */ + public function isSeekable() + { + return null !== $this->resource; + } + + /** + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot seek on a detached stream'); + } + + fseek($this->resource, $offset, $whence); + } + + /** + * {@inheritdoc} + */ + public function rewind() + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot rewind on a detached stream'); + } + + rewind($this->resource); + } + + /** + * {@inheritdoc} + */ + public function isWritable() + { + return false; + } + + /** + * {@inheritdoc} + */ + public function write($string) + { + throw new \RuntimeException('Cannot write on this stream'); + } + + /** + * {@inheritdoc} + */ + public function isReadable() + { + return null !== $this->resource; + } + + /** + * {@inheritdoc} + */ + public function read($length) + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot read on a detached stream'); + } + + $read = ''; + + // First read from the resource + if (ftell($this->resource) !== $this->written) { + $read = fread($this->resource, $length); + } + + $bytesRead = strlen($read); + + if ($bytesRead < $length) { + $streamRead = $this->stream->read($length - $bytesRead); + + // Write on the underlying stream what we read + $this->written += fwrite($this->resource, $streamRead); + $read .= $streamRead; + } + + return $read; + } + + /** + * {@inheritdoc} + */ + public function getContents() + { + if (null === $this->resource) { + throw new \RuntimeException('Cannot read on a detached stream'); + } + + $read = ''; + + while (!$this->eof()) { + $read .= $this->read(8192); + } + + return $read; + } + + /** + * {@inheritdoc} + */ + public function getMetadata($key = null) + { + if (null === $this->resource) { + if (null === $key) { + return []; + } + + return; + } + + $metadata = stream_get_meta_data($this->resource); + + if (null === $key) { + return $metadata; + } + + if (!array_key_exists($key, $metadata)) { + return; + } + + return $metadata[$key]; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/DiactorosStreamFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/DiactorosStreamFactory.php new file mode 100644 index 0000000..8ae2b28 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/DiactorosStreamFactory.php @@ -0,0 +1,48 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Diactoros PSR-17 factory + */ +final class DiactorosStreamFactory implements StreamFactory +{ + /** + * {@inheritdoc} + */ + public function createStream($body = null) + { + if ($body instanceof StreamInterface) { + return $body; + } + + if (is_resource($body)) { + if (class_exists(LaminasStream::class)) { + return new LaminasStream($body); + } + + return new ZendStream($body); + } + + if (class_exists(LaminasStream::class)) { + $stream = new LaminasStream('php://memory', 'rw'); + } else { + $stream = new ZendStream('php://memory', 'rw'); + } + + if (null !== $body && '' !== $body) { + $stream->write((string) $body); + } + + return $stream; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/GuzzleStreamFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/GuzzleStreamFactory.php new file mode 100644 index 0000000..14d83e9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/GuzzleStreamFactory.php @@ -0,0 +1,28 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Guzzle PSR-17 factory + */ +final class GuzzleStreamFactory implements StreamFactory +{ + /** + * {@inheritdoc} + */ + public function createStream($body = null) + { + if (class_exists(Utils::class)) { + return Utils::streamFor($body); + } + + return \GuzzleHttp\Psr7\stream_for($body); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/SlimStreamFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/SlimStreamFactory.php new file mode 100644 index 0000000..9274aae --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/StreamFactory/SlimStreamFactory.php @@ -0,0 +1,39 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Slim PSR-17 factory + */ +final class SlimStreamFactory implements StreamFactory +{ + /** + * {@inheritdoc} + */ + public function createStream($body = null) + { + if ($body instanceof StreamInterface) { + return $body; + } + + if (is_resource($body)) { + return new Stream($body); + } + + $resource = fopen('php://memory', 'r+'); + $stream = new Stream($resource); + if (null !== $body && '' !== $body) { + $stream->write((string) $body); + } + + return $stream; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/DiactorosUriFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/DiactorosUriFactory.php new file mode 100644 index 0000000..be883de --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/DiactorosUriFactory.php @@ -0,0 +1,36 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Diactoros PSR-17 factory + */ +final class DiactorosUriFactory implements UriFactory +{ + /** + * {@inheritdoc} + */ + public function createUri($uri) + { + if ($uri instanceof UriInterface) { + return $uri; + } elseif (is_string($uri)) { + if (class_exists(LaminasUri::class)) { + return new LaminasUri($uri); + } + + return new ZendUri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/GuzzleUriFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/GuzzleUriFactory.php new file mode 100644 index 0000000..e09ac61 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/GuzzleUriFactory.php @@ -0,0 +1,29 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Guzzle PSR-17 factory + */ +final class GuzzleUriFactory implements UriFactory +{ + /** + * {@inheritdoc} + */ + public function createUri($uri) + { + if (class_exists(Utils::class)) { + return Utils::uriFor($uri); + } + + return uri_for($uri); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/SlimUriFactory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/SlimUriFactory.php new file mode 100644 index 0000000..e5bef03 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/UriFactory/SlimUriFactory.php @@ -0,0 +1,33 @@ + + * + * @deprecated This will be removed in php-http/message2.0. Consider using the official Slim PSR-17 factory + */ +final class SlimUriFactory implements UriFactory +{ + /** + * {@inheritdoc} + */ + public function createUri($uri) + { + if ($uri instanceof UriInterface) { + return $uri; + } + + if (is_string($uri)) { + return Uri::createFromString($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/filters.php b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/filters.php new file mode 100644 index 0000000..15ed73d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/php-http/message/src/filters.php @@ -0,0 +1,6 @@ +info('This is an info message'); +$msg->success('This is a success message'); +$msg->warning('This is a warning message'); +$msg->error('This is an error message'); + + +// If you need to check for errors (eg: when validating a form) you can: +if ($msg->hasErrors()) { + // There ARE errors +} else { + // There are NOT any errors +} + +// Wherever you want to display the messages simply call: +$msg->display(); +```` + +### Message Types + +#### Info +````php +$msg->info('This is a info message'); +```` +![Info Message](http://mikeeverhart.net/php-flash-messages/assets/img/info.png) + +#### Success +````php +$msg->success('This is a success message'); +```` +![Success Message](http://mikeeverhart.net/php-flash-messages/assets/img/success.png) + + +#### Warning +````php +$msg->warning('This is a warning message'); +```` +![Warning Message](http://mikeeverhart.net/php-flash-messages/assets/img/warning.png) + +#### Error +````php +$msg->error('This is a error message'); +```` +![Error Message](http://mikeeverhart.net/php-flash-messages/assets/img/error.png) + +#### Message Type Constants +Each message type can be referred to by its constant: INFO, SUCCESS, WARNING, ERROR. For example: +````php +$msg::INFO +$msg::SUCCESS +$msg::WARNING +$msg::ERROR +```` + +### Redirects + +It's possible to redirect to a different URL before displaying a message. For example, redirecting back to a form (and displaying an error message) so a user can correct an error. + +The preferred method of doing this is by passing the URL as the 2nd parameter: + +````php +$msg->error('This is an error message', 'http://yoursite.com/another-page'); +```` + +A redirect is executed as soon as the message it's attached to is queued. As such, if you need multiple messages AND need to redirect then include the URL with the last message: + +````php +$msg->success('This is a success message'); +$msg->success('This is another success message'); +$msg->error('This is an error message', 'http://redirect-url.com'); +````` + +### Sticky Messages +By default, all messages include a close button. The close button can be removed, thus making the message sticky. To make a message sticky pass `true` as the third parameter: + +````php +$msg->error("This is a sticky error message (it can't be closed)", null, true); +$msg->warning("This is a sticky warning message (it can't be closed)", null, true); +$msg->success("This is a sticky success message (it can't be closed)", null, true); +$msg->info("This is a sticky info message (it can't be closed)", null, true); +```` + +![Sticky Info Message](http://mikeeverhart.net/php-flash-messages/assets/img/sticky-info.png) +![Sticky Success Message](http://mikeeverhart.net/php-flash-messages/assets/img/sticky-success.png) +![Sticky Warning Message](http://mikeeverhart.net/php-flash-messages/assets/img/sticky-warning.png) +![Sticky Error Message](http://mikeeverhart.net/php-flash-messages/assets/img/sticky-error.png) + +There's also a special method, appropriately enough called `sticky()`, that can be used to make sticky messages: + +````php +$msg->sticky('This is also a sticky message'); +```` + +`sticky()` accepts an optional 2nd parameter for the redirect url, and a 3rd for the message type: + +````php +$msg->sticky('This is "success" sticky message', 'http://redirect-url.com', $msg::SUCCESS); +``` + +By default, `sticky()` will render as whatever the default message type is set to (usually `$msg::INFO`.) Use the 3rd parameter override this. + +## Helper Methods +### `hasErrors()` + +Check to see if there are any queued `ERROR` messages. + +````php +if ($msg->hasErrors()) { + // There are errors, so do something like redirect +} +```` + +### `hasMessages ( [string $type] )` + +Check to see if there are any specific message types (or any messages at all) queued. + +````php +// Check if there are any INFO messages +if ($msg->hasMessages($msg::INFO)) { + ... +} + +// Check if there are any SUCCESS messages +if ($msg->hasMessages($msg::SUCCESS)) { + ... +} + +// Check if there are any WARNING messages +if ($msg->hasMessages($msg::WARNING)) { + ... +} + +// Check if there are any ERROR messages +if ($msg->hasMessages($msg::ERROR)) { + ... +} + +// See if there are *any* messages queued at all +if ($msg->hasMessages()) { + ... +} +```` + +### `setCloseBtn ( string $html )` + +Sets the HTML for the close button that's displayed on (non-sticky) messages. + +````php +$msg->setCloseBtn('') +```` + +### `setCssClassMap ( array $cssClassMap )` + +Sets the CSS classes that are used for each specific message type. + +````php +$msg->setCssClassMap([ + $msg::INFO => 'alert-info', + $msg::SUCCESS => 'alert-success', + $msg::WARNING => 'alert-warning', + $msg::ERROR => 'alert-danger', +]); +```` + +### `setMsgAfter ( string $msgAfter )` + +Add a string of text (HTML or otherwise) after the message (but inside of the wrapper.) + + +For example, wrap a message in `

` tags: + +````php +$msg->setMsgAfter('

') +```` + +### `setMsgBefore ( string $msgBefore )` + +Add a string of text (HTML or otherwise) before the message (but inside of the wrapper.) + + +For example, wrap a message in `

` tags: + +````php +$msg->setMsgBefore('

') +```` + +### `setMsgCssClass ( [string $cssClass] )` + +Sets the CSS class that is applied to all messages, regardless of their type. + +````php +$msg->setMsgCssClass('alert') +```` + +### `setMsgWrapper ( string $html )` + +Sets the HTML that wraps each message. HTML should include two placeholders (`%s`) for the CSS class and message text. + +````php +$msg->setMsgWrapper("

%s
") +```` + +### `setStickyCssClass ( [string $cssClass] )` + +Set the CSS class used for sticky messages + +````php +$msg->setStickyCssClass('sticky') +```` + + +## License + +The MIT License (MIT) + +Copyright (c) 2015 Mike Everhart & PlasticBrain Media LLC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/composer.json new file mode 100644 index 0000000..457a6ef --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/composer.json @@ -0,0 +1,21 @@ +{ + "name": "plasticbrain/php-flash-messages", + "description": "A modern take on PHP session-based flash messages", + "keywords": ["flash", "messages", "session", "bootstrap"], + "authors": [ + { + "name": "Mike Everhart", + "email": "mike@plasticbrain.net" + } + ], + "license": "MIT", + "require": { + "php": ">=5.4.0" + }, + "require-dev": {}, + "autoload": { + "psr-4": { + "Plasticbrain\\FlashMessages\\": "src/" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/src/FlashMessages.php b/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/src/FlashMessages.php new file mode 100644 index 0000000..140b3bb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/plasticbrain/php-flash-messages/src/FlashMessages.php @@ -0,0 +1,444 @@ +display([$msg::SUCCESS, $msg::INFO, $msg::ERROR, $msg::WARNING]) + // + protected $msgTypes = [ + self::ERROR => 'error', + self::WARNING => 'warning', + self::SUCCESS => 'success', + self::INFO => 'info', + ]; + + // Each message gets wrapped in this + protected $msgWrapper = "
%s
\n"; + + // Prepend and append to each message (inside of the wrapper) + protected $msgBefore = ''; + protected $msgAfter = ''; + + // HTML for the close button + protected $closeBtn = ''; + + // CSS Classes + protected $stickyCssClass = 'sticky'; + protected $msgCssClass = 'alert dismissable'; + protected $cssClassMap = [ + self::INFO => 'alert-info', + self::SUCCESS => 'alert-success', + self::WARNING => 'alert-warning', + self::ERROR => 'alert-danger', + ]; + + // Where to redirect the user after a message is queued + protected $redirectUrl = null; + + // The unique ID for the session/messages (do not edit) + protected $msgId; + + + + + /** + * __construct + * + */ + public function __construct() + { + + // Generate a unique ID for this user and session + $this->msgId = sha1(uniqid()); + + // Create session array to hold our messages if it doesn't already exist + if (!array_key_exists('flash_messages', $_SESSION)) $_SESSION['flash_messages'] = []; + + } + + /** + * Add an info message + * + * @param string $message The message text + * @param string $redirectUrl Where to redirect once the message is added + * @param boolean $sticky Sticky the message (hides the close button) + * @return object + * + */ + public function info($message, $redirectUrl=null, $sticky=false) + { + return $this->add($message, self::INFO, $redirectUrl, $sticky); + } + + /** + * Add a success message + * + * @param string $message The message text + * @param string $redirectUrl Where to redirect once the message is added + * @param boolean $sticky Sticky the message (hides the close button) + * @return object + * + */ + public function success($message, $redirectUrl=null, $sticky=false) + { + return $this->add($message, self::SUCCESS, $redirectUrl, $sticky); + } + + /** + * Add a warning message + * + * @param string $message The message text + * @param string $redirectUrl Where to redirect once the message is added + * @param boolean $sticky Sticky the message (hides the close button) + * @return object + * + */ + public function warning($message, $redirectUrl=null, $sticky=false) + { + return $this->add($message, self::WARNING, $redirectUrl, $sticky); + } + + /** + * Add an error message + * + * @param string $message The message text + * @param string $redirectUrl Where to redirect once the message is added + * @param boolean $sticky Sticky the message (hides the close button) + * @return object + * + */ + public function error($message, $redirectUrl=null, $sticky=false) + { + return $this->add($message, self::ERROR, $redirectUrl, $sticky); + } + + /** + * Add a sticky message + * + * @param string $message The message text + * @param string $redirectUrl Where to redirect once the message is added + * @param string $type The $msgType + * @return object + * + */ + public function sticky($message=true, $redirectUrl=null, $type=self::defaultType) + { + return $this->add($message, $type, $redirectUrl, true); + } + + /** + * Add a flash message to the session data + * + * @param string $message The message text + * @param string $type The $msgType + * @param string $redirectUrl Where to redirect once the message is added + * @param boolean $sticky Whether or not the message is stickied + * @return object + * + */ + public function add($message, $type=self::defaultType, $redirectUrl=null, $sticky=false) + { + + // Make sure a message and valid type was passed + if (!isset($message[0])) return false; + if (strlen(trim($type)) > 1) $type = strtolower($type[0]); + if (!array_key_exists($type, $this->msgTypes)) $type = $this->defaultType; + + // Add the message to the session data + if (!array_key_exists( $type, $_SESSION['flash_messages'] )) $_SESSION['flash_messages'][$type] = array(); + $_SESSION['flash_messages'][$type][] = ['sticky' => $sticky, 'message' => $message]; + + // Handle the redirect if needed + if (!is_null($redirectUrl)) $this->redirectUrl = $redirectUrl; + $this->doRedirect(); + + return $this; + } + + /** + * Display the flash messages + * + * @param mixed $types (null) print all of the message types + * (array) print the given message types + * (string) print a single message type + * @param boolean $print Whether to print the data or return it + * @return string + * + */ + public function display($types=null, $print=true) + { + + if (!isset($_SESSION['flash_messages'])) return false; + + $output = ''; + + // Print all the message types + if (is_null($types) || !$types || (is_array($types) && empty($types)) ) { + $types = array_keys($this->msgTypes); + + // Print multiple message types (as defined by an array) + } elseif (is_array($types) && !empty($types)) { + $theTypes = $types; + $types = []; + foreach($theTypes as $type) { + $types[] = strtolower($type[0]); + } + + // Print only a single message type + } else { + $types = [strtolower($types[0])]; + } + + + // Retrieve and format the messages, then remove them from session data + foreach ($types as $type) { + if (!isset($_SESSION['flash_messages'][$type]) || empty($_SESSION['flash_messages'][$type]) ) continue; + foreach( $_SESSION['flash_messages'][$type] as $msgData ) { + $output .= $this->formatMessage($msgData, $type); + } + $this->clear($type); + } + + + // Print everything to the screen (or return the data) + if ($print) { + echo $output; + } else { + return $output; + } + } + + /** + * See if there are any queued error messages + * + * @return boolean + * + */ + public function hasErrors() + { + return empty($_SESSION['flash_messages'][self::ERROR]) ? false : true; + } + + /** + * See if there are any queued message + * + * @param string $type The $msgType + * @return boolean + * + */ + public function hasMessages($type=null) { + if (!is_null($type)) { + if (!empty($_SESSION['flash_messages'][$type])) return $_SESSION['flash_messages'][$type]; + } else { + foreach (array_keys($this->msgTypes) as $type) { + if (isset($_SESSION['flash_messages'][$type]) && !empty($_SESSION['flash_messages'][$type])) return $_SESSION['flash_messages'][$type]; + } + } + return false; + } + + /** + * Format a message + * + * @param array $msgDataArray Array of message data + * @param string $type The $msgType + * @return string The formatted message + * + */ + protected function formatMessage($msgDataArray, $type) + { + + $msgType = isset($this->msgTypes[$type]) ? $type : $this->defaultType; + $cssClass = $this->msgCssClass . ' ' . $this->cssClassMap[$type]; + $msgBefore = $this->msgBefore; + + // If sticky then append the sticky CSS class + if ($msgDataArray['sticky']) { + $cssClass .= ' ' . $this->stickyCssClass; + + // If it's not sticky then add the close button + } else { + $msgBefore = $this->closeBtn . $msgBefore; + } + + // Wrap the message if necessary + $formattedMessage = $msgBefore . $msgDataArray['message'] . $this->msgAfter; + + return sprintf( + $this->msgWrapper, + $cssClass, + $formattedMessage + ); + } + + /** + * Redirect the user if a URL was given + * + * @return object + * + */ + protected function doRedirect() + { + if ($this->redirectUrl) { + header('Location: ' . $this->redirectUrl); + exit(); + } + return $this; + } + + /** + * Clear the messages from the session data + * + * @param mixed $types (array) Clear all of the message types in array + * (string) Only clear the one given message type + * @return object + * + */ + protected function clear($types=[]) + { + if ((is_array($types) && empty($types)) || is_null($types) || !$types) { + unset($_SESSION['flash_messages']); + } elseif (!is_array($types)) { + $types = [$types]; + } + + foreach ($types as $type) { + unset($_SESSION['flash_messages'][$type]); + } + + return $this; + } + + + + /** + * Set the HTML that each message is wrapped in + * + * @param string $msgWrapper The HTML that each message is wrapped in. + * Note: Two placeholders (%s) are expected. + * The first is the $msgCssClass, + * The second is the message text. + * @return object + * + */ + public function setMsgWrapper($msgWrapper='') + { + $this->msgWrapper = $msgWrapper; + return $this; + } + + /** + * Prepend string to the message (inside of the message wrapper) + * + * @param string $msgBefore string to prepend to the message + * @return object + * + */ + public function setMsgBefore($msgBefore='') + { + $this->msgBefore = $msgBefore; + return $this; + } + + /** + * Append string to the message (inside of the message wrapper) + * + * @param string $msgAfter string to append to the message + * @return object + * + */ + public function setMsgAfter($msgAfter='') + { + $this->msgAfter = $msgAfter; + return $this; + } + + /** + * Set the HTML for the close button + * + * @param string $closeBtn HTML to use for the close button + * @return object + * + */ + public function setCloseBtn($closeBtn='') + { + $this->closeBtn = $closeBtn; + return $this; + } + + /** + * Set the CSS class for sticky notes + * + * @param string $stickyCssClass the CSS class to use for sticky messages + * @return object + * + */ + public function setStickyCssClass($stickyCssClass='') + { + $this->stickyCssClass = $stickyCssClass; + return $this; + } + + /** + * Set the CSS class for messages + * + * @param string $msgCssClass The CSS class to use for messages + * + * @return object + * + */ + public function setMsgCssClass($msgCssClass='') + { + $this->msgCssClass = $msgCssClass; + return $this; + } + + /** + * Set the CSS classes for message types + * + * @param mixed $msgType (string) The message type + * (array) key/value pairs for the class map + * @param mixed $cssClass (string) the CSS class to use + * (null) not used when $msgType is an array + * @return object + * + */ + public function setCssClassMap($msgType, $cssClass=null) + { + + if (!is_array($msgType) ) { + // Make sure there's a CSS class set + if (is_null($cssClass)) return $this; + $msgType = [$msgType => $cssClass]; + } + + foreach ($msgType as $type => $cssClass) { + $this->cssClassMap[$type] = $cssClass; + } + + return $this; + } + + +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/CHANGELOG.md new file mode 100644 index 0000000..74b1ef9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file, in reverse chronological order by release. + +## 1.0.1 - 2016-08-06 + +### Added + +- Nothing. + +### Deprecated + +- Nothing. + +### Removed + +- Nothing. + +### Fixed + +- Updated all `@return self` annotation references in interfaces to use + `@return static`, which more closelly follows the semantics of the + specification. +- Updated the `MessageInterface::getHeaders()` return annotation to use the + value `string[][]`, indicating the format is a nested array of strings. +- Updated the `@link` annotation for `RequestInterface::withRequestTarget()` + to point to the correct section of RFC 7230. +- Updated the `ServerRequestInterface::withUploadedFiles()` parameter annotation + to add the parameter name (`$uploadedFiles`). +- Updated a `@throws` annotation for the `UploadedFileInterface::moveTo()` + method to correctly reference the method parameter (it was referencing an + incorrect parameter name previously). + +## 1.0.0 - 2016-05-18 + +Initial stable release; reflects accepted PSR-7 specification. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/LICENSE new file mode 100644 index 0000000..c2d8e45 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 PHP Framework Interoperability Group + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/README.md new file mode 100644 index 0000000..2818533 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/README.md @@ -0,0 +1,13 @@ +PSR Http Message +================ + +This repository holds all interfaces/classes/traits related to +[PSR-7](http://www.php-fig.org/psr/psr-7/). + +Note that this is not a HTTP message implementation of its own. It is merely an +interface that describes a HTTP message. See the specification for more details. + +Usage +----- + +We'll certainly need some stuff in here. \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/composer.json new file mode 100644 index 0000000..b0d2937 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/composer.json @@ -0,0 +1,26 @@ +{ + "name": "psr/http-message", + "description": "Common interface for HTTP messages", + "keywords": ["psr", "psr-7", "http", "http-message", "request", "response"], + "homepage": "https://github.com/php-fig/http-message", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "http://www.php-fig.org/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/MessageInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/MessageInterface.php new file mode 100644 index 0000000..dd46e5e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/MessageInterface.php @@ -0,0 +1,187 @@ +getHeaders() as $name => $values) { + * echo $name . ": " . implode(", ", $values); + * } + * + * // Emit headers iteratively: + * foreach ($message->getHeaders() as $name => $values) { + * foreach ($values as $value) { + * header(sprintf('%s: %s', $name, $value), false); + * } + * } + * + * While header names are not case-sensitive, getHeaders() will preserve the + * exact case in which headers were originally specified. + * + * @return string[][] Returns an associative array of the message's headers. Each + * key MUST be a header name, and each value MUST be an array of strings + * for that header. + */ + public function getHeaders(); + + /** + * Checks if a header exists by the given case-insensitive name. + * + * @param string $name Case-insensitive header field name. + * @return bool Returns true if any header names match the given header + * name using a case-insensitive string comparison. Returns false if + * no matching header name is found in the message. + */ + public function hasHeader($name); + + /** + * Retrieves a message header value by the given case-insensitive name. + * + * This method returns an array of all the header values of the given + * case-insensitive header name. + * + * If the header does not appear in the message, this method MUST return an + * empty array. + * + * @param string $name Case-insensitive header field name. + * @return string[] An array of string values as provided for the given + * header. If the header does not appear in the message, this method MUST + * return an empty array. + */ + public function getHeader($name); + + /** + * Retrieves a comma-separated string of the values for a single header. + * + * This method returns all of the header values of the given + * case-insensitive header name as a string concatenated together using + * a comma. + * + * NOTE: Not all header values may be appropriately represented using + * comma concatenation. For such headers, use getHeader() instead + * and supply your own delimiter when concatenating. + * + * If the header does not appear in the message, this method MUST return + * an empty string. + * + * @param string $name Case-insensitive header field name. + * @return string A string of values as provided for the given header + * concatenated together using a comma. If the header does not appear in + * the message, this method MUST return an empty string. + */ + public function getHeaderLine($name); + + /** + * Return an instance with the provided value replacing the specified header. + * + * While header names are case-insensitive, the casing of the header will + * be preserved by this function, and returned from getHeaders(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new and/or updated header and value. + * + * @param string $name Case-insensitive header field name. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withHeader($name, $value); + + /** + * Return an instance with the specified header appended with the given value. + * + * Existing values for the specified header will be maintained. The new + * value(s) will be appended to the existing list. If the header did not + * exist previously, it will be added. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * new header and/or value. + * + * @param string $name Case-insensitive header field name to add. + * @param string|string[] $value Header value(s). + * @return static + * @throws \InvalidArgumentException for invalid header names or values. + */ + public function withAddedHeader($name, $value); + + /** + * Return an instance without the specified header. + * + * Header resolution MUST be done without case-sensitivity. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the named header. + * + * @param string $name Case-insensitive header field name to remove. + * @return static + */ + public function withoutHeader($name); + + /** + * Gets the body of the message. + * + * @return StreamInterface Returns the body as a stream. + */ + public function getBody(); + + /** + * Return an instance with the specified message body. + * + * The body MUST be a StreamInterface object. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return a new instance that has the + * new body stream. + * + * @param StreamInterface $body Body. + * @return static + * @throws \InvalidArgumentException When the body is not valid. + */ + public function withBody(StreamInterface $body); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/RequestInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/RequestInterface.php new file mode 100644 index 0000000..a96d4fd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/RequestInterface.php @@ -0,0 +1,129 @@ +getQuery()` + * or from the `QUERY_STRING` server param. + * + * @return array + */ + public function getQueryParams(); + + /** + * Return an instance with the specified query string arguments. + * + * These values SHOULD remain immutable over the course of the incoming + * request. They MAY be injected during instantiation, such as from PHP's + * $_GET superglobal, or MAY be derived from some other value such as the + * URI. In cases where the arguments are parsed from the URI, the data + * MUST be compatible with what PHP's parse_str() would return for + * purposes of how duplicate query parameters are handled, and how nested + * sets are handled. + * + * Setting query string arguments MUST NOT change the URI stored by the + * request, nor the values in the server params. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated query string arguments. + * + * @param array $query Array of query string arguments, typically from + * $_GET. + * @return static + */ + public function withQueryParams(array $query); + + /** + * Retrieve normalized file upload data. + * + * This method returns upload metadata in a normalized tree, with each leaf + * an instance of Psr\Http\Message\UploadedFileInterface. + * + * These values MAY be prepared from $_FILES or the message body during + * instantiation, or MAY be injected via withUploadedFiles(). + * + * @return array An array tree of UploadedFileInterface instances; an empty + * array MUST be returned if no data is present. + */ + public function getUploadedFiles(); + + /** + * Create a new instance with the specified uploaded files. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param array $uploadedFiles An array tree of UploadedFileInterface instances. + * @return static + * @throws \InvalidArgumentException if an invalid structure is provided. + */ + public function withUploadedFiles(array $uploadedFiles); + + /** + * Retrieve any parameters provided in the request body. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, this method MUST + * return the contents of $_POST. + * + * Otherwise, this method may return any results of deserializing + * the request body content; as parsing returns structured content, the + * potential types MUST be arrays or objects only. A null value indicates + * the absence of body content. + * + * @return null|array|object The deserialized body parameters, if any. + * These will typically be an array or object. + */ + public function getParsedBody(); + + /** + * Return an instance with the specified body parameters. + * + * These MAY be injected during instantiation. + * + * If the request Content-Type is either application/x-www-form-urlencoded + * or multipart/form-data, and the request method is POST, use this method + * ONLY to inject the contents of $_POST. + * + * The data IS NOT REQUIRED to come from $_POST, but MUST be the results of + * deserializing the request body content. Deserialization/parsing returns + * structured data, and, as such, this method ONLY accepts arrays or objects, + * or a null value if nothing was available to parse. + * + * As an example, if content negotiation determines that the request data + * is a JSON payload, this method could be used to create a request + * instance with the deserialized parameters. + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated body parameters. + * + * @param null|array|object $data The deserialized body data. This will + * typically be in an array or object. + * @return static + * @throws \InvalidArgumentException if an unsupported argument type is + * provided. + */ + public function withParsedBody($data); + + /** + * Retrieve attributes derived from the request. + * + * The request "attributes" may be used to allow injection of any + * parameters derived from the request: e.g., the results of path + * match operations; the results of decrypting cookies; the results of + * deserializing non-form-encoded message bodies; etc. Attributes + * will be application and request specific, and CAN be mutable. + * + * @return array Attributes derived from the request. + */ + public function getAttributes(); + + /** + * Retrieve a single derived request attribute. + * + * Retrieves a single derived request attribute as described in + * getAttributes(). If the attribute has not been previously set, returns + * the default value as provided. + * + * This method obviates the need for a hasAttribute() method, as it allows + * specifying a default value to return if the attribute is not found. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $default Default value to return if the attribute does not exist. + * @return mixed + */ + public function getAttribute($name, $default = null); + + /** + * Return an instance with the specified derived request attribute. + * + * This method allows setting a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that has the + * updated attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @param mixed $value The value of the attribute. + * @return static + */ + public function withAttribute($name, $value); + + /** + * Return an instance that removes the specified derived request attribute. + * + * This method allows removing a single derived request attribute as + * described in getAttributes(). + * + * This method MUST be implemented in such a way as to retain the + * immutability of the message, and MUST return an instance that removes + * the attribute. + * + * @see getAttributes() + * @param string $name The attribute name. + * @return static + */ + public function withoutAttribute($name); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/StreamInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/StreamInterface.php new file mode 100644 index 0000000..f68f391 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/psr/http-message/src/StreamInterface.php @@ -0,0 +1,158 @@ + + * [user-info@]host[:port] + * + * + * If the port component is not set or is the standard port for the current + * scheme, it SHOULD NOT be included. + * + * @see https://tools.ietf.org/html/rfc3986#section-3.2 + * @return string The URI authority, in "[user-info@]host[:port]" format. + */ + public function getAuthority(); + + /** + * Retrieve the user information component of the URI. + * + * If no user information is present, this method MUST return an empty + * string. + * + * If a user is present in the URI, this will return that value; + * additionally, if the password is also present, it will be appended to the + * user value, with a colon (":") separating the values. + * + * The trailing "@" character is not part of the user information and MUST + * NOT be added. + * + * @return string The URI user information, in "username[:password]" format. + */ + public function getUserInfo(); + + /** + * Retrieve the host component of the URI. + * + * If no host is present, this method MUST return an empty string. + * + * The value returned MUST be normalized to lowercase, per RFC 3986 + * Section 3.2.2. + * + * @see http://tools.ietf.org/html/rfc3986#section-3.2.2 + * @return string The URI host. + */ + public function getHost(); + + /** + * Retrieve the port component of the URI. + * + * If a port is present, and it is non-standard for the current scheme, + * this method MUST return it as an integer. If the port is the standard port + * used with the current scheme, this method SHOULD return null. + * + * If no port is present, and no scheme is present, this method MUST return + * a null value. + * + * If no port is present, but a scheme is present, this method MAY return + * the standard port for that scheme, but SHOULD return null. + * + * @return null|int The URI port. + */ + public function getPort(); + + /** + * Retrieve the path component of the URI. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * Normally, the empty path "" and absolute path "/" are considered equal as + * defined in RFC 7230 Section 2.7.3. But this method MUST NOT automatically + * do this normalization because in contexts with a trimmed base path, e.g. + * the front controller, this difference becomes significant. It's the task + * of the user to handle both "" and "/". + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.3. + * + * As an example, if the value should include a slash ("/") not intended as + * delimiter between path segments, that value MUST be passed in encoded + * form (e.g., "%2F") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.3 + * @return string The URI path. + */ + public function getPath(); + + /** + * Retrieve the query string of the URI. + * + * If no query string is present, this method MUST return an empty string. + * + * The leading "?" character is not part of the query and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.4. + * + * As an example, if a value in a key/value pair of the query string should + * include an ampersand ("&") not intended as a delimiter between values, + * that value MUST be passed in encoded form (e.g., "%26") to the instance. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.4 + * @return string The URI query string. + */ + public function getQuery(); + + /** + * Retrieve the fragment component of the URI. + * + * If no fragment is present, this method MUST return an empty string. + * + * The leading "#" character is not part of the fragment and MUST NOT be + * added. + * + * The value returned MUST be percent-encoded, but MUST NOT double-encode + * any characters. To determine what characters to encode, please refer to + * RFC 3986, Sections 2 and 3.5. + * + * @see https://tools.ietf.org/html/rfc3986#section-2 + * @see https://tools.ietf.org/html/rfc3986#section-3.5 + * @return string The URI fragment. + */ + public function getFragment(); + + /** + * Return an instance with the specified scheme. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified scheme. + * + * Implementations MUST support the schemes "http" and "https" case + * insensitively, and MAY accommodate other schemes if required. + * + * An empty scheme is equivalent to removing the scheme. + * + * @param string $scheme The scheme to use with the new instance. + * @return static A new instance with the specified scheme. + * @throws \InvalidArgumentException for invalid or unsupported schemes. + */ + public function withScheme($scheme); + + /** + * Return an instance with the specified user information. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified user information. + * + * Password is optional, but the user information MUST include the + * user; an empty string for the user is equivalent to removing user + * information. + * + * @param string $user The user name to use for authority. + * @param null|string $password The password associated with $user. + * @return static A new instance with the specified user information. + */ + public function withUserInfo($user, $password = null); + + /** + * Return an instance with the specified host. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified host. + * + * An empty host value is equivalent to removing the host. + * + * @param string $host The hostname to use with the new instance. + * @return static A new instance with the specified host. + * @throws \InvalidArgumentException for invalid hostnames. + */ + public function withHost($host); + + /** + * Return an instance with the specified port. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified port. + * + * Implementations MUST raise an exception for ports outside the + * established TCP and UDP port ranges. + * + * A null value provided for the port is equivalent to removing the port + * information. + * + * @param null|int $port The port to use with the new instance; a null value + * removes the port information. + * @return static A new instance with the specified port. + * @throws \InvalidArgumentException for invalid ports. + */ + public function withPort($port); + + /** + * Return an instance with the specified path. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified path. + * + * The path can either be empty or absolute (starting with a slash) or + * rootless (not starting with a slash). Implementations MUST support all + * three syntaxes. + * + * If the path is intended to be domain-relative rather than path relative then + * it must begin with a slash ("/"). Paths not starting with a slash ("/") + * are assumed to be relative to some base path known to the application or + * consumer. + * + * Users can provide both encoded and decoded path characters. + * Implementations ensure the correct encoding as outlined in getPath(). + * + * @param string $path The path to use with the new instance. + * @return static A new instance with the specified path. + * @throws \InvalidArgumentException for invalid paths. + */ + public function withPath($path); + + /** + * Return an instance with the specified query string. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified query string. + * + * Users can provide both encoded and decoded query characters. + * Implementations ensure the correct encoding as outlined in getQuery(). + * + * An empty query string value is equivalent to removing the query string. + * + * @param string $query The query string to use with the new instance. + * @return static A new instance with the specified query string. + * @throws \InvalidArgumentException for invalid query strings. + */ + public function withQuery($query); + + /** + * Return an instance with the specified URI fragment. + * + * This method MUST retain the state of the current instance, and return + * an instance that contains the specified URI fragment. + * + * Users can provide both encoded and decoded fragment characters. + * Implementations ensure the correct encoding as outlined in getFragment(). + * + * An empty fragment value is equivalent to removing the fragment. + * + * @param string $fragment The fragment to use with the new instance. + * @return static A new instance with the specified fragment. + */ + public function withFragment($fragment); + + /** + * Return the string representation as a URI reference. + * + * Depending on which components of the URI are present, the resulting + * string is either a full URI or relative reference according to RFC 3986, + * Section 4.1. The method concatenates the various components of the URI, + * using the appropriate delimiters: + * + * - If a scheme is present, it MUST be suffixed by ":". + * - If an authority is present, it MUST be prefixed by "//". + * - The path can be concatenated without delimiters. But there are two + * cases where the path has to be adjusted to make the URI reference + * valid as PHP does not allow to throw an exception in __toString(): + * - If the path is rootless and an authority is present, the path MUST + * be prefixed by "/". + * - If the path is starting with more than one "/" and no authority is + * present, the starting slashes MUST be reduced to one. + * - If a query is present, it MUST be prefixed by "?". + * - If a fragment is present, it MUST be prefixed by "#". + * + * @see http://tools.ietf.org/html/rfc3986#section-4.1 + * @return string + */ + public function __toString(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/LICENSE new file mode 100644 index 0000000..be5540c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ralph Khattar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/README.md new file mode 100644 index 0000000..9430d76 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/README.md @@ -0,0 +1,27 @@ +getallheaders +============= + +PHP `getallheaders()` polyfill. Compatible with PHP >= 5.3. + +[![Build Status](https://travis-ci.org/ralouphie/getallheaders.svg?branch=master)](https://travis-ci.org/ralouphie/getallheaders) +[![Coverage Status](https://coveralls.io/repos/ralouphie/getallheaders/badge.png?branch=master)](https://coveralls.io/r/ralouphie/getallheaders?branch=master) +[![Latest Stable Version](https://poser.pugx.org/ralouphie/getallheaders/v/stable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![Latest Unstable Version](https://poser.pugx.org/ralouphie/getallheaders/v/unstable.png)](https://packagist.org/packages/ralouphie/getallheaders) +[![License](https://poser.pugx.org/ralouphie/getallheaders/license.png)](https://packagist.org/packages/ralouphie/getallheaders) + + +This is a simple polyfill for [`getallheaders()`](http://www.php.net/manual/en/function.getallheaders.php). + +## Install + +For PHP version **`>= 5.6`**: + +``` +composer require ralouphie/getallheaders +``` + +For PHP version **`< 5.6`**: + +``` +composer require ralouphie/getallheaders "^2" +``` diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/composer.json new file mode 100644 index 0000000..de8ce62 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/composer.json @@ -0,0 +1,26 @@ +{ + "name": "ralouphie/getallheaders", + "description": "A polyfill for getallheaders.", + "license": "MIT", + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "require": { + "php": ">=5.6" + }, + "require-dev": { + "phpunit/phpunit": "^5 || ^6.5", + "php-coveralls/php-coveralls": "^2.1" + }, + "autoload": { + "files": ["src/getallheaders.php"] + }, + "autoload-dev": { + "psr-4": { + "getallheaders\\Tests\\": "tests/" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/src/getallheaders.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/src/getallheaders.php new file mode 100644 index 0000000..c7285a5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ralouphie/getallheaders/src/getallheaders.php @@ -0,0 +1,46 @@ + 'Content-Type', + 'CONTENT_LENGTH' => 'Content-Length', + 'CONTENT_MD5' => 'Content-Md5', + ); + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $key = substr($key, 5); + if (!isset($copy_server[$key]) || !isset($_SERVER[$key])) { + $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $key)))); + $headers[$key] = $value; + } + } elseif (isset($copy_server[$key])) { + $headers[$copy_server[$key]] = $value; + } + } + + if (!isset($headers['Authorization'])) { + if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) { + $headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION']; + } elseif (isset($_SERVER['PHP_AUTH_USER'])) { + $basic_pass = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + $headers['Authorization'] = 'Basic ' . base64_encode($_SERVER['PHP_AUTH_USER'] . ':' . $basic_pass); + } elseif (isset($_SERVER['PHP_AUTH_DIGEST'])) { + $headers['Authorization'] = $_SERVER['PHP_AUTH_DIGEST']; + } + } + + return $headers; + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/CHANGELOG.md new file mode 100644 index 0000000..56ddc4a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/CHANGELOG.md @@ -0,0 +1,85 @@ +# Changelog + +## 1.1.0 (2020-09-18) + +* Feature: Forward compatibility with react/promise 3. + (#39 by @WyriHaximus) + +* Add `.gitattributes` to exclude dev files from exports. + (#40 by @reedy) + +* Improve test suite, update to support PHP 8 and PHPUnit 9.3. + (#41 and #43 by @SimonFrings and #42 by @WyriHaximus) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.6.0 release. + +## 0.6.0 (2019-07-04) + +* Feature / BC break: Add support for `getMultiple()`, `setMultiple()`, `deleteMultiple()`, `clear()` and `has()` + supporting multiple cache items (inspired by PSR-16). + (#32 by @krlv and #37 by @clue) + +* Documentation for TTL precision with millisecond accuracy or below and + use high-resolution timer for cache TTL on PHP 7.3+. + (#35 and #38 by @clue) + +* Improve API documentation and allow legacy HHVM to fail in Travis CI config. + (#34 and #36 by @clue) + +* Prefix all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#31 by @WyriHaximus) + +## 0.5.0 (2018-06-25) + +* Improve documentation by describing what is expected of a class implementing `CacheInterface`. + (#21, #22, #23, #27 by @WyriHaximus) + +* Implemented (optional) Least Recently Used (LRU) cache algorithm for `ArrayCache`. + (#26 by @clue) + +* Added support for cache expiration (TTL). + (#29 by @clue and @WyriHaximus) + +* Renamed `remove` to `delete` making it more in line with `PSR-16`. + (#30 by @clue) + +## 0.4.2 (2017-12-20) + +* Improve documentation with usage and installation instructions + (#10 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` and + add forward compatibility with PHPUnit 5 and PHPUnit 6 and + sanitize Composer autoload paths + (#14 by @shaunbramley and #12 and #18 by @clue) + +## 0.4.1 (2016-02-25) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#9 by @clue) +* Adjust compatibility to 5.3 (#7 by @clue) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.0 (2013-04-14) + +* Version bump + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/README.md new file mode 100644 index 0000000..2986e25 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/README.md @@ -0,0 +1,366 @@ +# Cache + +[![Build Status](https://travis-ci.org/reactphp/cache.svg?branch=master)](https://travis-ci.org/reactphp/cache) + +Async, [Promise](https://github.com/reactphp/promise)-based cache interface +for [ReactPHP](https://reactphp.org/). + +The cache component provides a +[Promise](https://github.com/reactphp/promise)-based +[`CacheInterface`](#cacheinterface) and an in-memory [`ArrayCache`](#arraycache) +implementation of that. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. +This project is heavily inspired by +[PSR-16: Common Interface for Caching Libraries](https://www.php-fig.org/psr/psr-16/), +but uses an interface more suited for async, non-blocking applications. + +**Table of Contents** + +* [Usage](#usage) + * [CacheInterface](#cacheinterface) + * [get()](#get) + * [set()](#set) + * [delete()](#delete) + * [getMultiple()](#getmultiple) + * [setMultiple()](#setmultiple) + * [deleteMultiple()](#deletemultiple) + * [clear()](#clear) + * [has()](#has) + * [ArrayCache](#arraycache) +* [Common usage](#common-usage) + * [Fallback get](#fallback-get) + * [Fallback-get-and-set](#fallback-get-and-set) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +### CacheInterface + +The `CacheInterface` describes the main interface of this component. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. + +#### get() + +The `get(string $key, mixed $default = null): PromiseInterface` method can be used to +retrieve an item from the cache. + +This method will resolve with the cached value on success or with the +given `$default` value when no item can be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache + ->get('foo') + ->then('var_dump'); +``` + +This example fetches the value of the key `foo` and passes it to the +`var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +#### set() + +The `set(string $key, mixed $value, ?float $ttl = null): PromiseInterface` method can be used to +store an item in the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for this cache item. If this parameter is omitted (or `null`), the item +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache item results in a cache miss, +see also [`get()`](#get). + +```php +$cache->set('foo', 'bar', 60); +``` + +This example eventually sets the value of the key `foo` to `bar`. If it +already exists, it is overridden. + +This interface does not enforce any particular TTL resolution, so special +care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Cache implementations SHOULD work on a +best effort basis and SHOULD provide at least second accuracy unless +otherwise noted. Many existing cache implementations are known to provide +microsecond or millisecond accuracy, but it's generally not recommended +to rely on this high precision. + +This interface suggests that cache implementations SHOULD use a monotonic +time source if available. Given that a monotonic time source is only +available as of PHP 7.3 by default, cache implementations MAY fall back +to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s and then +adjust your system time forward by 20s, the cache item SHOULD still +expire in 30s. + +#### delete() + +The `delete(string $key): PromiseInterface` method can be used to +delete an item from the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. When no item for `$key` is found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->delete('foo'); +``` + +This example eventually deletes the key `foo` from the cache. As with +`set()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### getMultiple() + +The `getMultiple(string[] $keys, mixed $default = null): PromiseInterface` method can be used to +retrieve multiple cache items by their unique keys. + +This method will resolve with an array of cached values on success or with the +given `$default` value when an item can not be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache->getMultiple(array('name', 'age'))->then(function (array $values) { + $name = $values['name'] ?? 'User'; + $age = $values['age'] ?? 'n/a'; + + echo $name . ' is ' . $age . PHP_EOL; +}); +``` + +This example fetches the cache items for the `name` and `age` keys and +prints some example output. You can use any of the composition provided +by [promises](https://github.com/reactphp/promise). + +#### setMultiple() + +The `setMultiple(array $values, ?float $ttl = null): PromiseInterface` method can be used to +persist a set of key => value pairs in the cache, with an optional TTL. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for these cache items. If this parameter is omitted (or `null`), these items +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache items results in a cache miss, +see also [`getMultiple()`](#getmultiple). + +```php +$cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); +``` + +This example eventually sets the list of values - the key `foo` to `1` value +and the key `bar` to `2`. If some of the keys already exist, they are overridden. + +#### deleteMultiple() + +The `setMultiple(string[] $keys): PromiseInterface` method can be used to +delete multiple cache items in a single operation. + +This method will resolve with `true` on success or `false` when an error +occurs. When no items for `$keys` are found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->deleteMultiple(array('foo', 'bar, 'baz')); +``` + +This example eventually deletes keys `foo`, `bar` and `baz` from the cache. +As with `setMultiple()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### clear() + +The `clear(): PromiseInterface` method can be used to +wipe clean the entire cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->clear(); +``` + +This example eventually deletes all keys from the cache. As with `deleteMultiple()`, +this may not happen instantly and a promise is returned to provide guarantees +whether or not all the items have been removed from cache. + +#### has() + +The `has(string $key): PromiseInterface` method can be used to +determine whether an item is present in the cache. + +This method will resolve with `true` on success or `false` when no item can be found +or when an error occurs. Similarly, an expired cache item (once the time-to-live +is expired) is considered a cache miss. + +```php +$cache + ->has('foo') + ->then('var_dump'); +``` + +This example checks if the value of the key `foo` is set in the cache and passes +the result to the `var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +NOTE: It is recommended that has() is only to be used for cache warming type purposes +and not to be used within your live applications operations for get/set, as this method +is subject to a race condition where your has() will return true and immediately after, +another script can remove it making the state of your app out of date. + +### ArrayCache + +The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface). + +```php +$cache = new ArrayCache(); + +$cache->set('foo', 'bar'); +``` + +Its constructor accepts an optional `?int $limit` parameter to limit the +maximum number of entries to store in the LRU cache. If you add more +entries to this instance, it will automatically take care of removing +the one that was least recently used (LRU). + +For example, this snippet will overwrite the first value and only store +the last two entries: + +```php +$cache = new ArrayCache(2); + +$cache->set('foo', '1'); +$cache->set('bar', '2'); +$cache->set('baz', '3'); +``` + +This cache implementation is known to rely on wall-clock time to schedule +future cache expiration times when using any version before PHP 7.3, +because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s on PHP < 7.3 +and then adjust your system time forward by 20s, the cache item may +expire in 10s. See also [`set()`](#set) for more details. + +## Common usage + +### Fallback get + +A common use case of caches is to attempt fetching a cached value and as a +fallback retrieve it from the original data source if not found. Here is an +example of that: + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return getFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); +``` + +First an attempt is made to retrieve the value of `foo`. A callback function is +registered that will call `getFooFromDb` when the resulting value is null. +`getFooFromDb` is a function (can be any PHP callable) that will be called if the +key does not exist in the cache. + +`getFooFromDb` can handle the missing key by returning a promise for the +actual value from the database (or any other data source). As a result, this +chain will correctly fall back, and provide the value in both cases. + +### Fallback get and set + +To expand on the fallback get example, often you want to set the value on the +cache after fetching it from the data source. + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return $this->getAndCacheFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); + +public function getAndCacheFooFromDb() +{ + return $this->db + ->get('foo') + ->then(array($this, 'cacheFooFromDb')); +} + +public function cacheFooFromDb($foo) +{ + $this->cache->set('foo', $foo); + + return $foo; +} +``` + +By using chaining you can easily conditionally cache the value if it is +fetched from the database. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/cache:^1.1 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 7+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/composer.json new file mode 100644 index 0000000..ad0d9fe --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/composer.json @@ -0,0 +1,41 @@ +{ + "name": "react/cache", + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": ["cache", "caching", "promise", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react/promise": "^3.0 || ^2.0 || ^1.1" + }, + "autoload": { + "psr-4": { "React\\Cache\\": "src/" } + }, + "autoload-dev": { + "psr-4": { "React\\Tests\\Cache\\": "tests/" } + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/ArrayCache.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/ArrayCache.php new file mode 100644 index 0000000..81f25ef --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/ArrayCache.php @@ -0,0 +1,181 @@ +set('foo', 'bar'); + * ``` + * + * Its constructor accepts an optional `?int $limit` parameter to limit the + * maximum number of entries to store in the LRU cache. If you add more + * entries to this instance, it will automatically take care of removing + * the one that was least recently used (LRU). + * + * For example, this snippet will overwrite the first value and only store + * the last two entries: + * + * ```php + * $cache = new ArrayCache(2); + * + * $cache->set('foo', '1'); + * $cache->set('bar', '2'); + * $cache->set('baz', '3'); + * ``` + * + * This cache implementation is known to rely on wall-clock time to schedule + * future cache expiration times when using any version before PHP 7.3, + * because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s on PHP < 7.3 + * and then adjust your system time forward by 20s, the cache item may + * expire in 10s. See also [`set()`](#set) for more details. + * + * @param int|null $limit maximum number of entries to store in the LRU cache + */ + public function __construct($limit = null) + { + $this->limit = $limit; + + // prefer high-resolution timer, available as of PHP 7.3+ + $this->supportsHighResolution = \function_exists('hrtime'); + } + + public function get($key, $default = null) + { + // delete key if it is already expired => below will detect this as a cache miss + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve($default); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return Promise\resolve($value); + } + + public function set($key, $value, $ttl = null) + { + // unset before setting to ensure this entry will be added to end of array (LRU info) + unset($this->data[$key]); + $this->data[$key] = $value; + + // sort expiration times if TTL is given (first will expire first) + unset($this->expires[$key]); + if ($ttl !== null) { + $this->expires[$key] = $this->now() + $ttl; + \asort($this->expires); + } + + // ensure size limit is not exceeded or remove first entry from array + if ($this->limit !== null && \count($this->data) > $this->limit) { + // first try to check if there's any expired entry + // expiration times are sorted, so we can simply look at the first one + \reset($this->expires); + $key = \key($this->expires); + + // check to see if the first in the list of expiring keys is already expired + // if the first key is not expired, we have to overwrite by using LRU info + if ($key === null || $this->now() - $this->expires[$key] < 0) { + \reset($this->data); + $key = \key($this->data); + } + unset($this->data[$key], $this->expires[$key]); + } + + return Promise\resolve(true); + } + + public function delete($key) + { + unset($this->data[$key], $this->expires[$key]); + + return Promise\resolve(true); + } + + public function getMultiple(array $keys, $default = null) + { + $values = array(); + + foreach ($keys as $key) { + $values[$key] = $this->get($key, $default); + } + + return Promise\all($values); + } + + public function setMultiple(array $values, $ttl = null) + { + foreach ($values as $key => $value) { + $this->set($key, $value, $ttl); + } + + return Promise\resolve(true); + } + + public function deleteMultiple(array $keys) + { + foreach ($keys as $key) { + unset($this->data[$key], $this->expires[$key]); + } + + return Promise\resolve(true); + } + + public function clear() + { + $this->data = array(); + $this->expires = array(); + + return Promise\resolve(true); + } + + public function has($key) + { + // delete key if it is already expired + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve(false); + } + + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + + return Promise\resolve(true); + } + + /** + * @return float + */ + private function now() + { + return $this->supportsHighResolution ? \hrtime(true) * 1e-9 : \microtime(true); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/CacheInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/CacheInterface.php new file mode 100644 index 0000000..8e51c19 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/cache/src/CacheInterface.php @@ -0,0 +1,194 @@ +get('foo') + * ->then('var_dump'); + * ``` + * + * This example fetches the value of the key `foo` and passes it to the + * `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * @param string $key + * @param mixed $default Default value to return for cache miss or null if not given. + * @return PromiseInterface + */ + public function get($key, $default = null); + + /** + * Stores an item in the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for this cache item. If this parameter is omitted (or `null`), the item + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache item results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->set('foo', 'bar', 60); + * ``` + * + * This example eventually sets the value of the key `foo` to `bar`. If it + * already exists, it is overridden. + * + * This interface does not enforce any particular TTL resolution, so special + * care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Cache implementations SHOULD work on a + * best effort basis and SHOULD provide at least second accuracy unless + * otherwise noted. Many existing cache implementations are known to provide + * microsecond or millisecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * This interface suggests that cache implementations SHOULD use a monotonic + * time source if available. Given that a monotonic time source is only + * available as of PHP 7.3 by default, cache implementations MAY fall back + * to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s and then + * adjust your system time forward by 20s, the cache item SHOULD still + * expire in 30s. + * + * @param string $key + * @param mixed $value + * @param ?float $ttl + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function set($key, $value, $ttl = null); + + /** + * Deletes an item from the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. When no item for `$key` is found in the cache, it also resolves + * to `true`. If the cache implementation has to go over the network to + * delete it, it may take a while. + * + * ```php + * $cache->delete('foo'); + * ``` + * + * This example eventually deletes the key `foo` from the cache. As with + * `set()`, this may not happen instantly and a promise is returned to + * provide guarantees whether or not the item has been removed from cache. + * + * @param string $key + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function delete($key); + + /** + * Retrieves multiple cache items by their unique keys. + * + * This method will resolve with an array of cached values on success or with the + * given `$default` value when an item can not be found or when an error occurs. + * Similarly, an expired cache item (once the time-to-live is expired) is + * considered a cache miss. + * + * ```php + * $cache->getMultiple(array('name', 'age'))->then(function (array $values) { + * $name = $values['name'] ?? 'User'; + * $age = $values['age'] ?? 'n/a'; + * + * echo $name . ' is ' . $age . PHP_EOL; + * }); + * ``` + * + * This example fetches the cache items for the `name` and `age` keys and + * prints some example output. You can use any of the composition provided + * by [promises](https://github.com/reactphp/promise). + * + * @param string[] $keys A list of keys that can obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * @return PromiseInterface Returns a promise which resolves to an `array` of cached values + */ + public function getMultiple(array $keys, $default = null); + + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for these cache items. If this parameter is omitted (or `null`), these items + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache items results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); + * ``` + * + * This example eventually sets the list of values - the key `foo` to 1 value + * and the key `bar` to 2. If some of the keys already exist, they are overridden. + * + * @param array $values A list of key => value pairs for a multiple-set operation. + * @param ?float $ttl Optional. The TTL value of this item. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function setMultiple(array $values, $ttl = null); + + /** + * Deletes multiple cache items in a single operation. + * + * @param string[] $keys A list of string-based keys to be deleted. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function deleteMultiple(array $keys); + + /** + * Wipes clean the entire cache. + * + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function clear(); + + /** + * Determines whether an item is present in the cache. + * + * This method will resolve with `true` on success or `false` when no item can be found + * or when an error occurs. Similarly, an expired cache item (once the time-to-live + * is expired) is considered a cache miss. + * + * ```php + * $cache + * ->has('foo') + * ->then('var_dump'); + * ``` + * + * This example checks if the value of the key `foo` is set in the cache and passes + * the result to the `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * NOTE: It is recommended that has() is only to be used for cache warming type purposes + * and not to be used within your live applications operations for get/set, as this method + * is subject to a race condition where your has() will return true and immediately after, + * another script can remove it making the state of your app out of date. + * + * @param string $key The cache item key. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function has($key); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/CHANGELOG.md new file mode 100644 index 0000000..83e0520 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/CHANGELOG.md @@ -0,0 +1,396 @@ +# Changelog + +## 1.8.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#182 by @clue) + + ```php + // old (still supported) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config, $loop); + + // new (using default loop) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config); + ``` + +## 1.7.0 (2021-06-25) + +* Feature: Update DNS `Factory` to accept complete `Config` object. + Add new `FallbackExecutor` and use fallback DNS servers when `Config` lists multiple servers. + (#179 and #180 by @clue) + + ```php + // old (still supported) + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + $resolver = $factory->create($server, $loop); + + // new + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; + } + $resolver = $factory->create($config, $loop); + ``` + +## 1.6.0 (2021-06-21) + +* Feature: Add support for legacy `SPF` record type. + (#178 by @akondas and @clue) + +* Fix: Fix integer overflow for TCP/IP chunk size on 32 bit platforms. + (#177 by @clue) + +## 1.5.0 (2021-03-05) + +* Feature: Improve error reporting when query fails, include domain and query type and DNS server address where applicable. + (#174 by @clue) + +* Feature: Improve error handling when sending data to DNS server fails (macOS). + (#171 and #172 by @clue) + +* Fix: Improve DNS response parser to limit recursion for compressed labels. + (#169 by @clue) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#170 by @SimonFrings) + +## 1.4.0 (2020-09-18) + +* Feature: Support upcoming PHP 8. + (#168 by @clue) + +* Improve test suite and update to PHPUnit 9.3. + (#164 by @clue, #165 and #166 by @SimonFrings and #167 by @WyriHaximus) + +## 1.3.0 (2020-07-10) + +* Feature: Forward compatibility with react/promise v3. + (#153 by @WyriHaximus) + +* Feature: Support parsing `OPT` records (EDNS0). + (#157 by @clue) + +* Fix: Avoid PHP warnings due to lack of args in exception trace on PHP 7.4. + (#160 by @clue) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9 and PHP 7.4 and clean up test suite. + (#154 by @reedy, #156 by @clue and #163 by @SimonFrings) + +## 1.2.0 (2019-08-15) + +* Feature: Add `TcpTransportExecutor` to send DNS queries over TCP/IP connection, + add `SelectiveTransportExecutor` to retry with TCP if UDP is truncated and + automatically select transport protocol when no explicit `udp://` or `tcp://` scheme is given in `Factory`. + (#145, #146, #147 and #148 by @clue) + +* Feature: Support escaping literal dots and special characters in domain names. + (#144 by @clue) + +## 1.1.0 (2019-07-18) + +* Feature: Support parsing `CAA` and `SSHFP` records. + (#141 and #142 by @clue) + +* Feature: Add `ResolverInterface` as common interface for `Resolver` class. + (#139 by @clue) + +* Fix: Add missing private property definitions and + remove unneeded dependency on `react/stream`. + (#140 and #143 by @clue) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +This update involves a number of BC breaks due to dropped support for +deprecated functionality and some internal API cleanup. We've tried hard to +avoid BC breaks where possible and minimize impact otherwise. We expect that +most consumers of this package will actually not be affected by any BC +breaks, see below for more details: + +* BC break: Delete all deprecated APIs, use `Query` objects for `Message` questions + instead of nested arrays and increase code coverage to 100%. + (#130 by @clue) + +* BC break: Move `$nameserver` from `ExecutorInterface` to `UdpTransportExecutor`, + remove advanced/internal `UdpTransportExecutor` args for `Parser`/`BinaryDumper` and + add API documentation for `ExecutorInterface`. + (#135, #137 and #138 by @clue) + +* BC break: Replace `HeaderBag` attributes with simple `Message` properties. + (#132 by @clue) + +* BC break: Mark all `Record` attributes as required, add documentation vs `Query`. + (#136 by @clue) + +* BC break: Mark all classes as final to discourage inheritance + (#134 by @WyriHaximus) + +## 0.4.19 (2019-07-10) + +* Feature: Avoid garbage references when DNS resolution rejects on legacy PHP <= 5.6. + (#133 by @clue) + +## 0.4.18 (2019-09-07) + +* Feature / Fix: Implement `CachingExecutor` using cache TTL, deprecate old `CachedExecutor`, + respect TTL from response records when caching and do not cache truncated responses. + (#129 by @clue) + +* Feature: Limit cache size to 256 last responses by default. + (#127 by @clue) + +* Feature: Cooperatively resolve hosts to avoid running same query concurrently. + (#125 by @clue) + +## 0.4.17 (2019-04-01) + +* Feature: Support parsing `authority` and `additional` records from DNS response. + (#123 by @clue) + +* Feature: Support dumping records as part of outgoing binary DNS message. + (#124 by @clue) + +* Feature: Forward compatibility with upcoming Cache v0.6 and Cache v1.0 + (#121 by @clue) + +* Improve test suite to add forward compatibility with PHPUnit 7, + test against PHP 7.3 and use legacy PHPUnit 5 on legacy HHVM. + (#122 by @clue) + +## 0.4.16 (2018-11-11) + +* Feature: Improve promise cancellation for DNS lookup retries and clean up any garbage references. + (#118 by @clue) + +* Fix: Reject parsing malformed DNS response messages such as incomplete DNS response messages, + malformed record data or malformed compressed domain name labels. + (#115 and #117 by @clue) + +* Fix: Fix interpretation of TTL as UINT32 with most significant bit unset. + (#116 by @clue) + +* Fix: Fix caching advanced MX/SRV/TXT/SOA structures. + (#112 by @clue) + +## 0.4.15 (2018-07-02) + +* Feature: Add `resolveAll()` method to support custom query types in `Resolver`. + (#110 by @clue and @WyriHaximus) + + ```php + $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + }); + ``` + +* Feature: Support parsing `NS`, `TXT`, `MX`, `SOA` and `SRV` records. + (#104, #105, #106, #107 and #108 by @clue) + +* Feature: Add support for `Message::TYPE_ANY` and parse unknown types as binary data. + (#104 by @clue) + +* Feature: Improve error messages for failed queries and improve documentation. + (#109 by @clue) + +* Feature: Add reverse DNS lookup example. + (#111 by @clue) + +## 0.4.14 (2018-06-26) + +* Feature: Add `UdpTransportExecutor`, validate incoming DNS response messages + to avoid cache poisoning attacks and deprecate legacy `Executor`. + (#101 and #103 by @clue) + +* Feature: Forward compatibility with Cache 0.5 + (#102 by @clue) + +* Deprecate legacy `Query::$currentTime` and binary parser data attributes to clean up and simplify API. + (#99 by @clue) + +## 0.4.13 (2018-02-27) + +* Add `Config::loadSystemConfigBlocking()` to load default system config + and support parsing DNS config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac and WMIC on Windows) + (#92, #93, #94 and #95 by @clue) + + ```php + $config = Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + ``` + +* Remove unneeded cyclic dependency on react/socket + (#96 by @clue) + +## 0.4.12 (2018-01-14) + +* Improve test suite by adding forward compatibility with PHPUnit 6, + test against PHP 7.2, fix forward compatibility with upcoming EventLoop releases, + add test group to skip integration tests relying on internet connection + and add minor documentation improvements. + (#85 and #87 by @carusogabriel, #88 and #89 by @clue and #83 by @jsor) + +## 0.4.11 (2017-08-25) + +* Feature: Support resolving from default hosts file + (#75, #76 and #77 by @clue) + + This means that resolving hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $resolver->resolve('localhost')->then(function ($ip) { + echo 'IP: ' . $ip; + }); + ``` + + The new `HostsExecutor` exists for advanced usage and is otherwise used + internally for this feature. + +## 0.4.10 (2017-08-10) + +* Feature: Forward compatibility with EventLoop v1.0 and v0.5 and + lock minimum dependencies and work around circular dependency for tests + (#70 and #71 by @clue) + +* Fix: Work around DNS timeout issues for Windows users + (#74 by @clue) + +* Documentation and examples for advanced usage + (#66 by @WyriHaximus) + +* Remove broken TCP code, do not retry with invalid TCP query + (#73 by @clue) + +* Improve test suite by fixing HHVM build for now again and ignore future HHVM build errors and + lock Travis distro so new defaults will not break the build and + fix failing tests for PHP 7.1 + (#68 by @WyriHaximus and #69 and #72 by @clue) + +## 0.4.9 (2017-05-01) + +* Feature: Forward compatibility with upcoming Socket v1.0 and v0.8 + (#61 by @clue) + +## 0.4.8 (2017-04-16) + +* Feature: Add support for the AAAA record type to the protocol parser + (#58 by @othillo) + +* Feature: Add support for the PTR record type to the protocol parser + (#59 by @othillo) + +## 0.4.7 (2017-03-31) + +* Feature: Forward compatibility with upcoming Socket v0.6 and v0.7 component + (#57 by @clue) + +## 0.4.6 (2017-03-11) + +* Fix: Fix DNS timeout issues for Windows users and add forward compatibility + with Stream v0.5 and upcoming v0.6 + (#53 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` + (#54 by @clue) + +## 0.4.5 (2017-03-02) + +* Fix: Ensure we ignore the case of the answer + (#51 by @WyriHaximus) + +* Feature: Add `TimeoutExecutor` and simplify internal APIs to allow internal + code re-use for upcoming versions. + (#48 and #49 by @clue) + +## 0.4.4 (2017-02-13) + +* Fix: Fix handling connection and stream errors + (#45 by @clue) + +* Feature: Add examples and forward compatibility with upcoming Socket v0.5 component + (#46 and #47 by @clue) + +## 0.4.3 (2016-07-31) + +* Feature: Allow for cache adapter injection (#38 by @WyriHaximus) + + ```php + $factory = new React\Dns\Resolver\Factory(); + + $cache = new MyCustomCacheInstance(); + $resolver = $factory->createCached('8.8.8.8', $loop, $cache); + ``` + +* Feature: Support Promise cancellation (#35 by @clue) + + ```php + $promise = $resolver->resolve('reactphp.org'); + + $promise->cancel(); + ``` + +## 0.4.2 (2016-02-24) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#34 by @clue) +* Adjust compatibility to 5.3 (#30 by @clue) + +## 0.4.1 (2014-04-13) + +* Bug fix: Fixed PSR-4 autoload path (@marcj/WyriHaximus) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Bug fix: Properly resolve CNAME aliases +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.2 (2013-05-10) + +* Feature: Support default port for IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS + +## 0.2.5 (2012-11-26) + +* Version bump + +## 0.2.4 (2012-11-18) + +* Feature: Change to promise-based API (@jsor) + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Feature: DNS executor timeout handling (@arnaud-lb) +* Feature: DNS retry executor (@arnaud-lb) + +## 0.2.1 (2012-10-14) + +* Minor adjustments to DNS parser + +## 0.2.0 (2012-09-10) + +* Feature: DNS resolver diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/README.md new file mode 100644 index 0000000..81c5f61 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/README.md @@ -0,0 +1,452 @@ +# DNS + +[![CI status](https://github.com/reactphp/dns/workflows/CI/badge.svg)](https://github.com/reactphp/dns/actions) + +Async DNS resolver for [ReactPHP](https://reactphp.org/). + +The main point of the DNS component is to provide async DNS resolution. +However, it is really a toolkit for working with DNS messages, and could +easily be used to create a DNS server. + +**Table of contents** + +* [Basic usage](#basic-usage) +* [Caching](#caching) + * [Custom cache adapter](#custom-cache-adapter) +* [ResolverInterface](#resolverinterface) + * [resolve()](#resolve) + * [resolveAll()](#resolveall) +* [Advanced usage](#advanced-usage) + * [UdpTransportExecutor](#udptransportexecutor) + * [TcpTransportExecutor](#tcptransportexecutor) + * [SelectiveTransportExecutor](#selectivetransportexecutor) + * [HostsFileExecutor](#hostsfileexecutor) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [References](#references) + +## Basic usage + +The most basic usage is to just create a resolver through the resolver +factory. All you need to give it is a nameserver, then you can start resolving +names, baby! + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->create($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +See also the [first example](examples). + +The `Config` class can be used to load the system default config. This is an +operation that may access the filesystem and block. Ideally, this method should +thus be executed only once before the loop starts and not repeatedly while it is +running. +Note that this class may return an *empty* configuration if the system config +can not be loaded. As such, you'll likely want to apply a default nameserver +as above if none can be found. + +> Note that the factory loads the hosts file from the filesystem once when + creating the resolver instance. + Ideally, this method should thus be executed only once before the loop starts + and not repeatedly while it is running. + +But there's more. + +## Caching + +You can cache results by configuring the resolver to use a `CachedExecutor`: + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); + +... + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +If the first call returns before the second, only one query will be executed. +The second result will be served from an in memory cache. +This is particularly useful for long running scripts where the same hostnames +have to be looked up multiple times. + +See also the [third example](examples). + +### Custom cache adapter + +By default, the above will use an in memory cache. + +You can also specify a custom cache implementing [`CacheInterface`](https://github.com/reactphp/cache) to handle the record cache instead: + +```php +$cache = new React\Cache\ArrayCache(); +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached('8.8.8.8', null, $cache); +``` + +See also the wiki for possible [cache implementations](https://github.com/reactphp/react/wiki/Users#cache-implementations). + +## ResolverInterface + +
+ +### resolve() + +The `resolve(string $domain): PromiseInterface` method can be used to +resolve the given $domain name to a single IPv4 address (type `A` query). + +```php +$resolver->resolve('reactphp.org')->then(function ($ip) { + echo 'IP for reactphp.org is ' . $ip . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a single IP +address on success. + +If the DNS server sends a DNS response message that contains more than +one IP address for this query, it will randomly pick one of the IP +addresses from the response. If you want the full list of IP addresses +or want to send a different type of query, you should use the +[`resolveAll()`](#resolveall) method instead. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolve('reactphp.org'); + +$promise->cancel(); +``` + +### resolveAll() + +The `resolveAll(string $host, int $type): PromiseInterface` method can be used to +resolve all record values for the given $domain name and query $type. + +```php +$resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); + +$resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a list with all +record values on success. + +If the DNS server sends a DNS response message that contains one or more +records for this query, it will return a list with all record values +from the response. You can use the `Message::TYPE_*` constants to control +which type of query will be sent. Note that this method always returns a +list of record values, but each record value type depends on the query +type. For example, it returns the IPv4 addresses for type `A` queries, +the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, +`CNAME` and `PTR` queries and structured data for other queries. See also +the `Record` documentation for more details. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + +$promise->cancel(); +``` + +## Advanced Usage + +### UdpTransportExecutor + +The `UdpTransportExecutor` can be used to +send DNS queries over a UDP transport. + +This is the main class that sends a DNS query to your DNS server and is used +internally by the `Resolver` for the actual message transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `igor.io`. + +```php +$executor = new UdpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also the [fourth example](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 +); +``` + +Also note that this executor uses an unreliable UDP transport and that it +does not implement any retry logic, so you will likely want to use this in +combination with a `RetryExecutor` like this: + +```php +$executor = new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) + ) +); +``` + +> Internally, this class uses PHP's UDP sockets and does not take advantage + of [react/datagram](https://github.com/reactphp/datagram) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Datagram + component instead of reimplementing this socket logic from scratch. + +### TcpTransportExecutor + +The `TcpTransportExecutor` class can be used to +send DNS queries over a TCP/IP stream transport. + +This is one of the main classes that send a DNS query to your DNS server. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new TcpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also [example #92](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 +); +``` + +Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP +transport, so you do not necessarily have to implement any retry logic. + +Note that this executor is entirely async and as such allows you to execute +queries concurrently. The first query will establish a TCP/IP socket +connection to the DNS server which will be kept open for a short period. +Additional queries will automatically reuse this existing socket connection +to the DNS server, will pipeline multiple requests over this single +connection and will keep an idle connection open for a short period. The +initial TCP/IP connection overhead may incur a slight delay if you only send +occasional queries – when sending a larger number of concurrent queries over +an existing connection, it becomes increasingly more efficient and avoids +creating many concurrent sockets like the UDP-based executor. You may still +want to limit the number of (concurrent) queries in your application or you +may be facing rate limitations and bans on the resolver end. For many common +applications, you may want to avoid sending the same query multiple times +when the first one is still pending, so you will likely want to use this in +combination with a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +> Internally, this class uses PHP's TCP/IP sockets and does not take advantage + of [react/socket](https://github.com/reactphp/socket) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Socket + component instead of reimplementing this socket logic from scratch. + +### SelectiveTransportExecutor + +The `SelectiveTransportExecutor` class can be used to +Send DNS queries over a UDP or TCP/IP stream transport. + +This class will automatically choose the correct transport protocol to send +a DNS query to your DNS server. It will always try to send it over the more +efficient UDP transport first. If this query yields a size related issue +(truncated messages), it will retry over a streaming TCP/IP transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new SelectiveTransportExecutor($udpExecutor, $tcpExecutor); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +Note that this executor only implements the logic to select the correct +transport for the given DNS query. Implementing the correct transport logic, +implementing timeouts and any retry logic is left up to the given executors, +see also [`UdpTransportExecutor`](#udptransportexecutor) and +[`TcpTransportExecutor`](#tcptransportexecutor) for more details. + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new SelectiveTransportExecutor( + $datagramExecutor, + $streamExecutor + ) +); +``` + +### HostsFileExecutor + +Note that the above `UdpTransportExecutor` class always performs an actual DNS query. +If you also want to take entries from your hosts file into account, you may +use this code: + +```php +$hosts = \React\Dns\Config\HostsFile::loadFromPathBlocking(); + +$executor = new UdpTransportExecutor('8.8.8.8:53'); +$executor = new HostsFileExecutor($hosts, $executor); + +$executor->query( + new Query('localhost', Message::TYPE_A, Message::CLASS_IN) +); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/dns:^1.8 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +$ php vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## References + +* [RFC 1034](https://tools.ietf.org/html/rfc1034) Domain Names - Concepts and Facilities +* [RFC 1035](https://tools.ietf.org/html/rfc1035) Domain Names - Implementation and Specification diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/composer.json new file mode 100644 index 0000000..28482f5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/composer.json @@ -0,0 +1,45 @@ +{ + "name": "react/dns", + "description": "Async DNS resolver for ReactPHP", + "keywords": ["dns", "dns-resolver", "ReactPHP", "async"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react/cache": "^1.0 || ^0.6 || ^0.5", + "react/event-loop": "^1.2", + "react/promise": "^3.0 || ^2.7 || ^1.2.1", + "react/promise-timer": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.2", + "phpunit/phpunit": "^9.3 || ^4.8.35" + }, + "autoload": { + "psr-4": { "React\\Dns\\": "src" } + }, + "autoload-dev": { + "psr-4": { "React\\Tests\\Dns\\": "tests" } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/BadServerException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/BadServerException.php new file mode 100644 index 0000000..3d95213 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/BadServerException.php @@ -0,0 +1,7 @@ +nameservers = $matches[1]; + + return $config; + } + + /** + * Loads the DNS configurations from Windows's WMIC (from the given command or default command) + * + * Note that this method blocks while loading the given command and should + * thus be used with care! While this should be relatively fast for normal + * WMIC commands, it remains unknown if this may block under certain + * circumstances. In particular, this method should only be executed before + * the loop starts, not while it is running. + * + * Note that this method will only try to execute the given command try to + * parse its output, irrespective of whether this command exists. In + * particular, this command is only available on Windows. Currently, this + * will only parse valid nameserver entries from the command output and will + * ignore all other output without complaining. + * + * Note that the previous section implies that this may return an empty + * `Config` object if no valid nameserver entries can be found. + * + * @param ?string $command (advanced) should not be given (NULL) unless you know what you're doing + * @return self + * @link https://ss64.com/nt/wmic.html + */ + public static function loadWmicBlocking($command = null) + { + $contents = shell_exec($command === null ? 'wmic NICCONFIG get "DNSServerSearchOrder" /format:CSV' : $command); + preg_match_all('/(?<=[{;,"])([\da-f.:]{4,})(?=[};,"])/i', $contents, $matches); + + $config = new self(); + $config->nameservers = $matches[1]; + + return $config; + } + + public $nameservers = array(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Config/HostsFile.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Config/HostsFile.php new file mode 100644 index 0000000..c9e66da --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Config/HostsFile.php @@ -0,0 +1,153 @@ +contents = $contents; + } + + /** + * Returns all IPs for the given hostname + * + * @param string $name + * @return string[] + */ + public function getIpsForHost($name) + { + $name = strtolower($name); + + $ips = array(); + foreach (preg_split('/\r?\n/', $this->contents) as $line) { + $parts = preg_split('/\s+/', $line); + $ip = array_shift($parts); + if ($parts && array_search($name, $parts) !== false) { + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (strpos($ip, ':') !== false && ($pos = strpos($ip, '%')) !== false) { + $ip = substr($ip, 0, $pos); + } + + if (@inet_pton($ip) !== false) { + $ips[] = $ip; + } + } + } + + return $ips; + } + + /** + * Returns all hostnames for the given IPv4 or IPv6 address + * + * @param string $ip + * @return string[] + */ + public function getHostsForIp($ip) + { + // check binary representation of IP to avoid string case and short notation + $ip = @inet_pton($ip); + if ($ip === false) { + return array(); + } + + $names = array(); + foreach (preg_split('/\r?\n/', $this->contents) as $line) { + $parts = preg_split('/\s+/', $line, null, PREG_SPLIT_NO_EMPTY); + $addr = array_shift($parts); + + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (strpos($addr, ':') !== false && ($pos = strpos($addr, '%')) !== false) { + $addr = substr($addr, 0, $pos); + } + + if (@inet_pton($addr) === $ip) { + foreach ($parts as $part) { + $names[] = $part; + } + } + } + + return $names; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Message.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Message.php new file mode 100644 index 0000000..bac2b10 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Message.php @@ -0,0 +1,230 @@ +id = self::generateId(); + $request->rd = true; + $request->questions[] = $query; + + return $request; + } + + /** + * Creates a new response message for the given query with the given answer records + * + * @param Query $query + * @param Record[] $answers + * @return self + */ + public static function createResponseWithAnswersForQuery(Query $query, array $answers) + { + $response = new Message(); + $response->id = self::generateId(); + $response->qr = true; + $response->rd = true; + + $response->questions[] = $query; + + foreach ($answers as $record) { + $response->answers[] = $record; + } + + return $response; + } + + /** + * generates a random 16 bit message ID + * + * This uses a CSPRNG so that an outside attacker that is sending spoofed + * DNS response messages can not guess the message ID to avoid possible + * cache poisoning attacks. + * + * The `random_int()` function is only available on PHP 7+ or when + * https://github.com/paragonie/random_compat is installed. As such, using + * the latest supported PHP version is highly recommended. This currently + * falls back to a less secure random number generator on older PHP versions + * in the hope that this system is properly protected against outside + * attackers, for example by using one of the common local DNS proxy stubs. + * + * @return int + * @see self::getId() + * @codeCoverageIgnore + */ + private static function generateId() + { + if (function_exists('random_int')) { + return random_int(0, 0xffff); + } + return mt_rand(0, 0xffff); + } + + /** + * The 16 bit message ID + * + * The response message ID has to match the request message ID. This allows + * the receiver to verify this is the correct response message. An outside + * attacker may try to inject fake responses by "guessing" the message ID, + * so this should use a proper CSPRNG to avoid possible cache poisoning. + * + * @var int 16 bit message ID + * @see self::generateId() + */ + public $id = 0; + + /** + * @var bool Query/Response flag, query=false or response=true + */ + public $qr = false; + + /** + * @var int specifies the kind of query (4 bit), see self::OPCODE_* constants + * @see self::OPCODE_QUERY + */ + public $opcode = self::OPCODE_QUERY; + + /** + * + * @var bool Authoritative Answer + */ + public $aa = false; + + /** + * @var bool TrunCation + */ + public $tc = false; + + /** + * @var bool Recursion Desired + */ + public $rd = false; + + /** + * @var bool Recursion Available + */ + public $ra = false; + + /** + * @var int response code (4 bit), see self::RCODE_* constants + * @see self::RCODE_OK + */ + public $rcode = Message::RCODE_OK; + + /** + * An array of Query objects + * + * ```php + * $questions = array( + * new Query( + * 'reactphp.org', + * Message::TYPE_A, + * Message::CLASS_IN + * ) + * ); + * ``` + * + * @var Query[] + */ + public $questions = array(); + + /** + * @var Record[] + */ + public $answers = array(); + + /** + * @var Record[] + */ + public $authority = array(); + + /** + * @var Record[] + */ + public $additional = array(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Record.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Record.php new file mode 100644 index 0000000..c20403f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Model/Record.php @@ -0,0 +1,153 @@ +name = $name; + $this->type = $type; + $this->class = $class; + $this->ttl = $ttl; + $this->data = $data; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Protocol/BinaryDumper.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Protocol/BinaryDumper.php new file mode 100644 index 0000000..83861cf --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Protocol/BinaryDumper.php @@ -0,0 +1,199 @@ +headerToBinary($message); + $data .= $this->questionToBinary($message->questions); + $data .= $this->recordsToBinary($message->answers); + $data .= $this->recordsToBinary($message->authority); + $data .= $this->recordsToBinary($message->additional); + + return $data; + } + + /** + * @param Message $message + * @return string + */ + private function headerToBinary(Message $message) + { + $data = ''; + + $data .= pack('n', $message->id); + + $flags = 0x00; + $flags = ($flags << 1) | ($message->qr ? 1 : 0); + $flags = ($flags << 4) | $message->opcode; + $flags = ($flags << 1) | ($message->aa ? 1 : 0); + $flags = ($flags << 1) | ($message->tc ? 1 : 0); + $flags = ($flags << 1) | ($message->rd ? 1 : 0); + $flags = ($flags << 1) | ($message->ra ? 1 : 0); + $flags = ($flags << 3) | 0; // skip unused zero bit + $flags = ($flags << 4) | $message->rcode; + + $data .= pack('n', $flags); + + $data .= pack('n', count($message->questions)); + $data .= pack('n', count($message->answers)); + $data .= pack('n', count($message->authority)); + $data .= pack('n', count($message->additional)); + + return $data; + } + + /** + * @param Query[] $questions + * @return string + */ + private function questionToBinary(array $questions) + { + $data = ''; + + foreach ($questions as $question) { + $data .= $this->domainNameToBinary($question->name); + $data .= pack('n*', $question->type, $question->class); + } + + return $data; + } + + /** + * @param Record[] $records + * @return string + */ + private function recordsToBinary(array $records) + { + $data = ''; + + foreach ($records as $record) { + /* @var $record Record */ + switch ($record->type) { + case Message::TYPE_A: + case Message::TYPE_AAAA: + $binary = \inet_pton($record->data); + break; + case Message::TYPE_CNAME: + case Message::TYPE_NS: + case Message::TYPE_PTR: + $binary = $this->domainNameToBinary($record->data); + break; + case Message::TYPE_TXT: + case Message::TYPE_SPF: + $binary = $this->textsToBinary($record->data); + break; + case Message::TYPE_MX: + $binary = \pack( + 'n', + $record->data['priority'] + ); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SRV: + $binary = \pack( + 'n*', + $record->data['priority'], + $record->data['weight'], + $record->data['port'] + ); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SOA: + $binary = $this->domainNameToBinary($record->data['mname']); + $binary .= $this->domainNameToBinary($record->data['rname']); + $binary .= \pack( + 'N*', + $record->data['serial'], + $record->data['refresh'], + $record->data['retry'], + $record->data['expire'], + $record->data['minimum'] + ); + break; + case Message::TYPE_CAA: + $binary = \pack( + 'C*', + $record->data['flag'], + \strlen($record->data['tag']) + ); + $binary .= $record->data['tag']; + $binary .= $record->data['value']; + break; + case Message::TYPE_SSHFP: + $binary = \pack( + 'CCH*', + $record->data['algorithm'], + $record->data['type'], + $record->data['fingerprint'] + ); + break; + case Message::TYPE_OPT: + $binary = ''; + foreach ($record->data as $opt => $value) { + if ($opt === Message::OPT_TCP_KEEPALIVE && $value !== null) { + $value = \pack('n', round($value * 10)); + } + $binary .= \pack('n*', $opt, \strlen($value)) . $value; + } + break; + default: + // RDATA is already stored as binary value for unknown record types + $binary = $record->data; + } + + $data .= $this->domainNameToBinary($record->name); + $data .= \pack('nnNn', $record->type, $record->class, $record->ttl, \strlen($binary)); + $data .= $binary; + } + + return $data; + } + + /** + * @param string[] $texts + * @return string + */ + private function textsToBinary(array $texts) + { + $data = ''; + foreach ($texts as $text) { + $data .= \chr(\strlen($text)) . $text; + } + return $data; + } + + /** + * @param string $host + * @return string + */ + private function domainNameToBinary($host) + { + if ($host === '') { + return "\0"; + } + + // break up domain name at each dot that is not preceeded by a backslash (escaped notation) + return $this->textsToBinary( + \array_map( + 'stripcslashes', + \preg_split( + '/(?data = $data; + $message->consumed = null; + + if ($this->parse($data, $message) !== $message) { + throw new InvalidArgumentException('Unable to parse binary message'); + } + + unset($message->data, $message->consumed); + + return $message; + } + + private function parse($data, Message $message) + { + if (!isset($message->data[12 - 1])) { + return; + } + + list($id, $fields, $qdCount, $anCount, $nsCount, $arCount) = array_values(unpack('n*', substr($message->data, 0, 12))); + $message->consumed += 12; + + $message->id = $id; + $message->rcode = $fields & 0xf; + $message->ra = (($fields >> 7) & 1) === 1; + $message->rd = (($fields >> 8) & 1) === 1; + $message->tc = (($fields >> 9) & 1) === 1; + $message->aa = (($fields >> 10) & 1) === 1; + $message->opcode = ($fields >> 11) & 0xf; + $message->qr = (($fields >> 15) & 1) === 1; + + // parse all questions + for ($i = $qdCount; $i > 0; --$i) { + $question = $this->parseQuestion($message); + if ($question === null) { + return; + } else { + $message->questions[] = $question; + } + } + + // parse all answer records + for ($i = $anCount; $i > 0; --$i) { + $record = $this->parseRecord($message); + if ($record === null) { + return; + } else { + $message->answers[] = $record; + } + } + + // parse all authority records + for ($i = $nsCount; $i > 0; --$i) { + $record = $this->parseRecord($message); + if ($record === null) { + return; + } else { + $message->authority[] = $record; + } + } + + // parse all additional records + for ($i = $arCount; $i > 0; --$i) { + $record = $this->parseRecord($message); + if ($record === null) { + return; + } else { + $message->additional[] = $record; + } + } + + return $message; + } + + /** + * @param Message $message + * @return ?Query + */ + private function parseQuestion(Message $message) + { + $consumed = $message->consumed; + + list($labels, $consumed) = $this->readLabels($message->data, $consumed); + + if ($labels === null || !isset($message->data[$consumed + 4 - 1])) { + return; + } + + list($type, $class) = array_values(unpack('n*', substr($message->data, $consumed, 4))); + $consumed += 4; + + $message->consumed = $consumed; + + return new Query( + implode('.', $labels), + $type, + $class + ); + } + + /** + * @param Message $message + * @return ?Record returns parsed Record on success or null if data is invalid/incomplete + */ + private function parseRecord(Message $message) + { + $consumed = $message->consumed; + + list($name, $consumed) = $this->readDomain($message->data, $consumed); + + if ($name === null || !isset($message->data[$consumed + 10 - 1])) { + return null; + } + + list($type, $class) = array_values(unpack('n*', substr($message->data, $consumed, 4))); + $consumed += 4; + + list($ttl) = array_values(unpack('N', substr($message->data, $consumed, 4))); + $consumed += 4; + + // TTL is a UINT32 that must not have most significant bit set for BC reasons + if ($ttl < 0 || $ttl >= 1 << 31) { + $ttl = 0; + } + + list($rdLength) = array_values(unpack('n', substr($message->data, $consumed, 2))); + $consumed += 2; + + if (!isset($message->data[$consumed + $rdLength - 1])) { + return null; + } + + $rdata = null; + $expected = $consumed + $rdLength; + + if (Message::TYPE_A === $type) { + if ($rdLength === 4) { + $rdata = inet_ntop(substr($message->data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_AAAA === $type) { + if ($rdLength === 16) { + $rdata = inet_ntop(substr($message->data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_CNAME === $type || Message::TYPE_PTR === $type || Message::TYPE_NS === $type) { + list($rdata, $consumed) = $this->readDomain($message->data, $consumed); + } elseif (Message::TYPE_TXT === $type || Message::TYPE_SPF === $type) { + $rdata = array(); + while ($consumed < $expected) { + $len = ord($message->data[$consumed]); + $rdata[] = (string)substr($message->data, $consumed + 1, $len); + $consumed += $len + 1; + } + } elseif (Message::TYPE_MX === $type) { + if ($rdLength > 2) { + list($priority) = array_values(unpack('n', substr($message->data, $consumed, 2))); + list($target, $consumed) = $this->readDomain($message->data, $consumed + 2); + + $rdata = array( + 'priority' => $priority, + 'target' => $target + ); + } + } elseif (Message::TYPE_SRV === $type) { + if ($rdLength > 6) { + list($priority, $weight, $port) = array_values(unpack('n*', substr($message->data, $consumed, 6))); + list($target, $consumed) = $this->readDomain($message->data, $consumed + 6); + + $rdata = array( + 'priority' => $priority, + 'weight' => $weight, + 'port' => $port, + 'target' => $target + ); + } + } elseif (Message::TYPE_SSHFP === $type) { + if ($rdLength > 2) { + list($algorithm, $hash) = \array_values(\unpack('C*', \substr($message->data, $consumed, 2))); + $fingerprint = \bin2hex(\substr($message->data, $consumed + 2, $rdLength - 2)); + $consumed += $rdLength; + + $rdata = array( + 'algorithm' => $algorithm, + 'type' => $hash, + 'fingerprint' => $fingerprint + ); + } + } elseif (Message::TYPE_SOA === $type) { + list($mname, $consumed) = $this->readDomain($message->data, $consumed); + list($rname, $consumed) = $this->readDomain($message->data, $consumed); + + if ($mname !== null && $rname !== null && isset($message->data[$consumed + 20 - 1])) { + list($serial, $refresh, $retry, $expire, $minimum) = array_values(unpack('N*', substr($message->data, $consumed, 20))); + $consumed += 20; + + $rdata = array( + 'mname' => $mname, + 'rname' => $rname, + 'serial' => $serial, + 'refresh' => $refresh, + 'retry' => $retry, + 'expire' => $expire, + 'minimum' => $minimum + ); + } + } elseif (Message::TYPE_OPT === $type) { + $rdata = array(); + while (isset($message->data[$consumed + 4 - 1])) { + list($code, $length) = array_values(unpack('n*', substr($message->data, $consumed, 4))); + $value = (string) substr($message->data, $consumed + 4, $length); + if ($code === Message::OPT_TCP_KEEPALIVE && $value === '') { + $value = null; + } elseif ($code === Message::OPT_TCP_KEEPALIVE && $length === 2) { + list($value) = array_values(unpack('n', $value)); + $value = round($value * 0.1, 1); + } elseif ($code === Message::OPT_TCP_KEEPALIVE) { + break; + } + $rdata[$code] = $value; + $consumed += 4 + $length; + } + } elseif (Message::TYPE_CAA === $type) { + if ($rdLength > 3) { + list($flag, $tagLength) = array_values(unpack('C*', substr($message->data, $consumed, 2))); + + if ($tagLength > 0 && $rdLength - 2 - $tagLength > 0) { + $tag = substr($message->data, $consumed + 2, $tagLength); + $value = substr($message->data, $consumed + 2 + $tagLength, $rdLength - 2 - $tagLength); + $consumed += $rdLength; + + $rdata = array( + 'flag' => $flag, + 'tag' => $tag, + 'value' => $value + ); + } + } + } else { + // unknown types simply parse rdata as an opaque binary string + $rdata = substr($message->data, $consumed, $rdLength); + $consumed += $rdLength; + } + + // ensure parsing record data consumes expact number of bytes indicated in record length + if ($consumed !== $expected || $rdata === null) { + return null; + } + + $message->consumed = $consumed; + + return new Record($name, $type, $class, $ttl, $rdata); + } + + private function readDomain($data, $consumed) + { + list ($labels, $consumed) = $this->readLabels($data, $consumed); + + if ($labels === null) { + return array(null, null); + } + + // use escaped notation for each label part, then join using dots + return array( + \implode( + '.', + \array_map( + function ($label) { + return \addcslashes($label, "\0..\40.\177"); + }, + $labels + ) + ), + $consumed + ); + } + + /** + * @param string $data + * @param int $consumed + * @param int $compressionDepth maximum depth for compressed labels to avoid unreasonable recursion + * @return array + */ + private function readLabels($data, $consumed, $compressionDepth = 127) + { + $labels = array(); + + while (true) { + if (!isset($data[$consumed])) { + return array(null, null); + } + + $length = \ord($data[$consumed]); + + // end of labels reached + if ($length === 0) { + $consumed += 1; + break; + } + + // first two bits set? this is a compressed label (14 bit pointer offset) + if (($length & 0xc0) === 0xc0 && isset($data[$consumed + 1]) && $compressionDepth) { + $offset = ($length & ~0xc0) << 8 | \ord($data[$consumed + 1]); + if ($offset >= $consumed) { + return array(null, null); + } + + $consumed += 2; + list($newLabels) = $this->readLabels($data, $offset, $compressionDepth - 1); + + if ($newLabels === null) { + return array(null, null); + } + + $labels = array_merge($labels, $newLabels); + break; + } + + // length MUST be 0-63 (6 bits only) and data has to be large enough + if ($length & 0xc0 || !isset($data[$consumed + $length - 1])) { + return array(null, null); + } + + $labels[] = substr($data, $consumed + 1, $length); + $consumed += $length + 1; + } + + return array($labels, $consumed); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CachingExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CachingExecutor.php new file mode 100644 index 0000000..e530b24 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CachingExecutor.php @@ -0,0 +1,88 @@ +executor = $executor; + $this->cache = $cache; + } + + public function query(Query $query) + { + $id = $query->name . ':' . $query->type . ':' . $query->class; + $cache = $this->cache; + $that = $this; + $executor = $this->executor; + + $pending = $cache->get($id); + return new Promise(function ($resolve, $reject) use ($query, $id, $cache, $executor, &$pending, $that) { + $pending->then( + function ($message) use ($query, $id, $cache, $executor, &$pending, $that) { + // return cached response message on cache hit + if ($message !== null) { + return $message; + } + + // perform DNS lookup if not already cached + return $pending = $executor->query($query)->then( + function (Message $message) use ($cache, $id, $that) { + // DNS response message received => store in cache when not truncated and return + if (!$message->tc) { + $cache->set($id, $message, $that->ttl($message)); + } + + return $message; + } + ); + } + )->then($resolve, function ($e) use ($reject, &$pending) { + $reject($e); + $pending = null; + }); + }, function ($_, $reject) use (&$pending, $query) { + $reject(new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled')); + $pending->cancel(); + $pending = null; + }); + } + + /** + * @param Message $message + * @return int + * @internal + */ + public function ttl(Message $message) + { + // select TTL from answers (should all be the same), use smallest value if available + // @link https://tools.ietf.org/html/rfc2181#section-5.2 + $ttl = null; + foreach ($message->answers as $answer) { + if ($ttl === null || $answer->ttl < $ttl) { + $ttl = $answer->ttl; + } + } + + if ($ttl === null) { + $ttl = self::TTL; + } + + return $ttl; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CancellationException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CancellationException.php new file mode 100644 index 0000000..5432b36 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/CancellationException.php @@ -0,0 +1,7 @@ +executor = $base; + } + + public function query(Query $query) + { + $key = $this->serializeQueryToIdentity($query); + if (isset($this->pending[$key])) { + // same query is already pending, so use shared reference to pending query + $promise = $this->pending[$key]; + ++$this->counts[$key]; + } else { + // no such query pending, so start new query and keep reference until it's fulfilled or rejected + $promise = $this->executor->query($query); + $this->pending[$key] = $promise; + $this->counts[$key] = 1; + + $pending =& $this->pending; + $counts =& $this->counts; + $promise->then(function () use ($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }, function () use ($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }); + } + + // Return a child promise awaiting the pending query. + // Cancelling this child promise should only cancel the pending query + // when no other child promise is awaiting the same query. + $pending =& $this->pending; + $counts =& $this->counts; + return new Promise(function ($resolve, $reject) use ($promise) { + $promise->then($resolve, $reject); + }, function () use (&$promise, $key, $query, &$pending, &$counts) { + if (--$counts[$key] < 1) { + unset($pending[$key], $counts[$key]); + $promise->cancel(); + $promise = null; + } + throw new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + } + + private function serializeQueryToIdentity(Query $query) + { + return sprintf('%s:%s:%s', $query->name, $query->type, $query->class); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/ExecutorInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/ExecutorInterface.php new file mode 100644 index 0000000..b356dc6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/ExecutorInterface.php @@ -0,0 +1,43 @@ +query($query)->then( + * function (React\Dns\Model\Message $response) { + * // response message successfully received + * var_dump($response->rcode, $response->answers); + * }, + * function (Exception $error) { + * // failed to query due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $executor->query($query); + * + * $promise->cancel(); + * ``` + * + * @param Query $query + * @return \React\Promise\PromiseInterface<\React\Dns\Model\Message,\Exception> + * resolves with response message on success or rejects with an Exception on error + */ + public function query(Query $query); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/FallbackExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/FallbackExecutor.php new file mode 100644 index 0000000..83bd360 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/FallbackExecutor.php @@ -0,0 +1,49 @@ +executor = $executor; + $this->fallback = $fallback; + } + + public function query(Query $query) + { + $cancelled = false; + $fallback = $this->fallback; + $promise = $this->executor->query($query); + + return new Promise(function ($resolve, $reject) use (&$promise, $fallback, $query, &$cancelled) { + $promise->then($resolve, function (\Exception $e1) use ($fallback, $query, $resolve, $reject, &$cancelled, &$promise) { + // reject if primary resolution rejected due to cancellation + if ($cancelled) { + $reject($e1); + return; + } + + // start fallback query if primary query rejected + $promise = $fallback->query($query)->then($resolve, function (\Exception $e2) use ($e1, $reject) { + $append = $e2->getMessage(); + if (($pos = strpos($append, ':')) !== false) { + $append = substr($append, $pos + 2); + } + + // reject with combined error message if both queries fail + $reject(new \RuntimeException($e1->getMessage() . '. ' . $append)); + }); + }); + }, function () use (&$promise, &$cancelled) { + // cancel pending query (primary or fallback) + $cancelled = true; + $promise->cancel(); + }); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/HostsFileExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/HostsFileExecutor.php new file mode 100644 index 0000000..d6e2d93 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/HostsFileExecutor.php @@ -0,0 +1,89 @@ +hosts = $hosts; + $this->fallback = $fallback; + } + + public function query(Query $query) + { + if ($query->class === Message::CLASS_IN && ($query->type === Message::TYPE_A || $query->type === Message::TYPE_AAAA)) { + // forward lookup for type A or AAAA + $records = array(); + $expectsColon = $query->type === Message::TYPE_AAAA; + foreach ($this->hosts->getIpsForHost($query->name) as $ip) { + // ensure this is an IPv4/IPV6 address according to query type + if ((strpos($ip, ':') !== false) === $expectsColon) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $ip); + } + } + + if ($records) { + return Promise\resolve( + Message::createResponseWithAnswersForQuery($query, $records) + ); + } + } elseif ($query->class === Message::CLASS_IN && $query->type === Message::TYPE_PTR) { + // reverse lookup: extract IPv4 or IPv6 from special `.arpa` domain + $ip = $this->getIpFromHost($query->name); + + if ($ip !== null) { + $records = array(); + foreach ($this->hosts->getHostsForIp($ip) as $host) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $host); + } + + if ($records) { + return Promise\resolve( + Message::createResponseWithAnswersForQuery($query, $records) + ); + } + } + } + + return $this->fallback->query($query); + } + + private function getIpFromHost($host) + { + if (substr($host, -13) === '.in-addr.arpa') { + // IPv4: read as IP and reverse bytes + $ip = @inet_pton(substr($host, 0, -13)); + if ($ip === false || isset($ip[4])) { + return null; + } + + return inet_ntop(strrev($ip)); + } elseif (substr($host, -9) === '.ip6.arpa') { + // IPv6: replace dots, reverse nibbles and interpret as hexadecimal string + $ip = @inet_ntop(pack('H*', strrev(str_replace('.', '', substr($host, 0, -9))))); + if ($ip === false) { + return null; + } + + return $ip; + } else { + return null; + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/Query.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/Query.php new file mode 100644 index 0000000..a3dcfb5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/Query.php @@ -0,0 +1,69 @@ +name = $name; + $this->type = $type; + $this->class = $class; + } + + /** + * Describes the hostname and query type/class for this query + * + * The output format is supposed to be human readable and is subject to change. + * The format is inspired by RFC 3597 when handling unkown types/classes. + * + * @return string "example.com (A)" or "example.com (CLASS0 TYPE1234)" + * @link https://tools.ietf.org/html/rfc3597 + */ + public function describe() + { + $class = $this->class !== Message::CLASS_IN ? 'CLASS' . $this->class . ' ' : ''; + + $type = 'TYPE' . $this->type; + $ref = new \ReflectionClass('React\Dns\Model\Message'); + foreach ($ref->getConstants() as $name => $value) { + if ($value === $this->type && \strpos($name, 'TYPE_') === 0) { + $type = \substr($name, 5); + break; + } + } + + return $this->name . ' (' . $class . $type . ')'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/RetryExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/RetryExecutor.php new file mode 100644 index 0000000..7efcacc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/RetryExecutor.php @@ -0,0 +1,86 @@ +executor = $executor; + $this->retries = $retries; + } + + public function query(Query $query) + { + return $this->tryQuery($query, $this->retries); + } + + public function tryQuery(Query $query, $retries) + { + $deferred = new Deferred(function () use (&$promise) { + if ($promise instanceof CancellablePromiseInterface || (!\interface_exists('React\Promise\CancellablePromiseInterface') && \method_exists($promise, 'cancel'))) { + $promise->cancel(); + } + }); + + $success = function ($value) use ($deferred, &$errorback) { + $errorback = null; + $deferred->resolve($value); + }; + + $executor = $this->executor; + $errorback = function ($e) use ($deferred, &$promise, $query, $success, &$errorback, &$retries, $executor) { + if (!$e instanceof TimeoutException) { + $errorback = null; + $deferred->reject($e); + } elseif ($retries <= 0) { + $errorback = null; + $deferred->reject($e = new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: too many retries', + 0, + $e + )); + + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + $r->setAccessible(true); + $trace = $r->getValue($e); + + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as &$one) { + if (isset($one['args'])) { + foreach ($one['args'] as &$arg) { + if ($arg instanceof \Closure) { + $arg = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } else { + --$retries; + $promise = $executor->query($query)->then( + $success, + $errorback + ); + } + }; + + $promise = $this->executor->query($query)->then( + $success, + $errorback + ); + + return $deferred->promise(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/SelectiveTransportExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/SelectiveTransportExecutor.php new file mode 100644 index 0000000..0f0ca5d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/SelectiveTransportExecutor.php @@ -0,0 +1,85 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * Note that this executor only implements the logic to select the correct + * transport for the given DNS query. Implementing the correct transport logic, + * implementing timeouts and any retry logic is left up to the given executors, + * see also [`UdpTransportExecutor`](#udptransportexecutor) and + * [`TcpTransportExecutor`](#tcptransportexecutor) for more details. + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new SelectiveTransportExecutor( + * $datagramExecutor, + * $streamExecutor + * ) + * ); + * ``` + */ +class SelectiveTransportExecutor implements ExecutorInterface +{ + private $datagramExecutor; + private $streamExecutor; + + public function __construct(ExecutorInterface $datagramExecutor, ExecutorInterface $streamExecutor) + { + $this->datagramExecutor = $datagramExecutor; + $this->streamExecutor = $streamExecutor; + } + + public function query(Query $query) + { + $stream = $this->streamExecutor; + $pending = $this->datagramExecutor->query($query); + + return new Promise(function ($resolve, $reject) use (&$pending, $stream, $query) { + $pending->then( + $resolve, + function ($e) use (&$pending, $stream, $query, $resolve, $reject) { + if ($e->getCode() === (\defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90)) { + $pending = $stream->query($query)->then($resolve, $reject); + } else { + $reject($e); + } + } + ); + }, function () use (&$pending) { + $pending->cancel(); + $pending = null; + }); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TcpTransportExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TcpTransportExecutor.php new file mode 100644 index 0000000..7efeb90 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TcpTransportExecutor.php @@ -0,0 +1,364 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also [example #92](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP + * transport, so you do not necessarily have to implement any retry logic. + * + * Note that this executor is entirely async and as such allows you to execute + * queries concurrently. The first query will establish a TCP/IP socket + * connection to the DNS server which will be kept open for a short period. + * Additional queries will automatically reuse this existing socket connection + * to the DNS server, will pipeline multiple requests over this single + * connection and will keep an idle connection open for a short period. The + * initial TCP/IP connection overhead may incur a slight delay if you only send + * occasional queries – when sending a larger number of concurrent queries over + * an existing connection, it becomes increasingly more efficient and avoids + * creating many concurrent sockets like the UDP-based executor. You may still + * want to limit the number of (concurrent) queries in your application or you + * may be facing rate limitations and bans on the resolver end. For many common + * applications, you may want to avoid sending the same query multiple times + * when the first one is still pending, so you will likely want to use this in + * combination with a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's TCP/IP sockets and does not take advantage + * of [react/socket](https://github.com/reactphp/socket) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Socket + * component instead of reimplementing this socket logic from scratch. + */ +class TcpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + + /** + * @var ?resource + */ + private $socket; + + /** + * @var Deferred[] + */ + private $pending = array(); + + /** + * @var string[] + */ + private $names = array(); + + /** + * Maximum idle time when socket is current unused (i.e. no pending queries outstanding) + * + * If a new query is to be sent during the idle period, we can reuse the + * existing socket without having to wait for a new socket connection. + * This uses a rather small, hard-coded value to not keep any unneeded + * sockets open and to not keep the loop busy longer than needed. + * + * A future implementation may take advantage of `edns-tcp-keepalive` to keep + * the socket open for longer periods. This will likely require explicit + * configuration because this may consume additional resources and also keep + * the loop busy for longer than expected in some applications. + * + * @var float + * @link https://tools.ietf.org/html/rfc7766#section-6.2.1 + * @link https://tools.ietf.org/html/rfc7828 + */ + private $idlePeriod = 0.001; + + /** + * @var ?\React\EventLoop\TimerInterface + */ + private $idleTimer; + + private $writeBuffer = ''; + private $writePending = false; + + private $readBuffer = ''; + private $readPending = false; + + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, LoopInterface $loop = null) + { + if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + + $parts = \parse_url((\strpos($nameserver, '://') === false ? 'tcp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'tcp' || !\filter_var(\trim($parts['host'], '[]'), \FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + + $this->nameserver = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + + // keep shuffing message ID to avoid using the same message ID for two pending queries at the same time + while (isset($this->pending[$request->id])) { + $request->id = \mt_rand(0, 0xffff); // @codeCoverageIgnore + } + + $queryData = $this->dumper->toBinary($request); + $length = \strlen($queryData); + if ($length > 0xffff) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Query too large for TCP transport' + )); + } + + $queryData = \pack('n', $length) . $queryData; + + if ($this->socket === null) { + // create async TCP/IP connection (may take a while) + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT); + if ($socket === false) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + )); + } + + // set socket to non-blocking and wait for it to become writable (connection success/rejected) + \stream_set_blocking($socket, false); + if (\function_exists('stream_set_chunk_size')) { + \stream_set_chunk_size($socket, (int) ((1 << 31) - 1)); // @codeCoverageIgnore + } + $this->socket = $socket; + } + + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + + // wait for socket to become writable to actually write out data + $this->writeBuffer .= $queryData; + if (!$this->writePending) { + $this->writePending = true; + $this->loop->addWriteStream($this->socket, array($this, 'handleWritable')); + } + + $names =& $this->names; + $that = $this; + $deferred = new Deferred(function () use ($that, &$names, $request) { + // remove from list of pending names, but remember pending query + $name = $names[$request->id]; + unset($names[$request->id]); + $that->checkIdle(); + + throw new CancellationException('DNS query for ' . $name . ' has been cancelled'); + }); + + $this->pending[$request->id] = $deferred; + $this->names[$request->id] = $query->describe(); + + return $deferred->promise(); + } + + /** + * @internal + */ + public function handleWritable() + { + if ($this->readPending === false) { + $name = @\stream_socket_get_name($this->socket, true); + if ($name === false) { + // Connection failed? Check socket error if available for underlying errno/errstr. + // @codeCoverageIgnoreStart + if (\function_exists('socket_import_stream')) { + $socket = \socket_import_stream($this->socket); + $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR); + $errstr = \socket_strerror($errno); + } else { + $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111; + $errstr = 'Connection refused'; + } + // @codeCoverageIgnoreEnd + + $this->closeError('Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno); + return; + } + + $this->readPending = true; + $this->loop->addReadStream($this->socket, array($this, 'handleRead')); + } + + $written = @\fwrite($this->socket, $this->writeBuffer); + if ($written === false || $written === 0) { + $error = \error_get_last(); + \preg_match('/errno=(\d+) (.+)/', $error['message'], $m); + $this->closeError( + 'Unable to send query to DNS server ' . $this->nameserver . ' (' . (isset($m[2]) ? $m[2] : $error['message']) . ')', + isset($m[1]) ? (int) $m[1] : 0 + ); + return; + } + + if (isset($this->writeBuffer[$written])) { + $this->writeBuffer = \substr($this->writeBuffer, $written); + } else { + $this->loop->removeWriteStream($this->socket); + $this->writePending = false; + $this->writeBuffer = ''; + } + } + + /** + * @internal + */ + public function handleRead() + { + // read one chunk of data from the DNS server + // any error is fatal, this is a stream of TCP/IP data + $chunk = @\fread($this->socket, 65536); + if ($chunk === false || $chunk === '') { + $this->closeError('Connection to DNS server ' . $this->nameserver . ' lost'); + return; + } + + // reassemble complete message by concatenating all chunks. + $this->readBuffer .= $chunk; + + // response message header contains at least 12 bytes + while (isset($this->readBuffer[11])) { + // read response message length from first 2 bytes and ensure we have length + data in buffer + list(, $length) = \unpack('n', $this->readBuffer); + if (!isset($this->readBuffer[$length + 1])) { + return; + } + + $data = \substr($this->readBuffer, 2, $length); + $this->readBuffer = (string)substr($this->readBuffer, $length + 2); + + try { + $response = $this->parser->parseMessage($data); + } catch (\Exception $e) { + // reject all pending queries if we received an invalid message from remote server + $this->closeError('Invalid message received from DNS server ' . $this->nameserver); + return; + } + + // reject all pending queries if we received an unexpected response ID or truncated response + if (!isset($this->pending[$response->id]) || $response->tc) { + $this->closeError('Invalid response message received from DNS server ' . $this->nameserver); + return; + } + + $deferred = $this->pending[$response->id]; + unset($this->pending[$response->id], $this->names[$response->id]); + + $deferred->resolve($response); + + $this->checkIdle(); + } + } + + /** + * @internal + * @param string $reason + * @param int $code + */ + public function closeError($reason, $code = 0) + { + $this->readBuffer = ''; + if ($this->readPending) { + $this->loop->removeReadStream($this->socket); + $this->readPending = false; + } + + $this->writeBuffer = ''; + if ($this->writePending) { + $this->loop->removeWriteStream($this->socket); + $this->writePending = false; + } + + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + + @\fclose($this->socket); + $this->socket = null; + + foreach ($this->names as $id => $name) { + $this->pending[$id]->reject(new \RuntimeException( + 'DNS query for ' . $name . ' failed: ' . $reason, + $code + )); + } + $this->pending = $this->names = array(); + } + + /** + * @internal + */ + public function checkIdle() + { + if ($this->idleTimer === null && !$this->names) { + $that = $this; + $this->idleTimer = $this->loop->addTimer($this->idlePeriod, function () use ($that) { + $that->closeError('Idle timeout'); + }); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TimeoutException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TimeoutException.php new file mode 100644 index 0000000..109b0a9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/TimeoutException.php @@ -0,0 +1,7 @@ +executor = $executor; + $this->loop = $loop ?: Loop::get(); + $this->timeout = $timeout; + } + + public function query(Query $query) + { + return Timer\timeout($this->executor->query($query), $this->timeout, $this->loop)->then(null, function ($e) use ($query) { + if ($e instanceof Timer\TimeoutException) { + $e = new TimeoutException(sprintf("DNS query for %s timed out", $query->describe()), 0, $e); + } + throw $e; + }); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/UdpTransportExecutor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/UdpTransportExecutor.php new file mode 100644 index 0000000..4687109 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Query/UdpTransportExecutor.php @@ -0,0 +1,208 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also the [fourth example](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Also note that this executor uses an unreliable UDP transport and that it + * does not implement any retry logic, so you will likely want to use this in + * combination with a `RetryExecutor` like this: + * + * ```php + * $executor = new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's UDP sockets and does not take advantage + * of [react/datagram](https://github.com/reactphp/datagram) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Datagram + * component instead of reimplementing this socket logic from scratch. + */ +final class UdpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + + /** + * maximum UDP packet size to send and receive + * + * @var int + */ + private $maxPacketSize = 512; + + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, LoopInterface $loop = null) + { + if (\strpos($nameserver, '[') === false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + + $parts = \parse_url((\strpos($nameserver, '://') === false ? 'udp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'udp' || !\filter_var(\trim($parts['host'], '[]'), \FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + + $this->nameserver = 'udp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + + $queryData = $this->dumper->toBinary($request); + if (isset($queryData[$this->maxPacketSize])) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Query too large for UDP transport', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 + )); + } + + // UDP connections are instant, so try connection without a loop or timeout + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0); + if ($socket === false) { + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', + $errno + )); + } + + // set socket to non-blocking and immediately try to send (fill write buffer) + \stream_set_blocking($socket, false); + $written = @\fwrite($socket, $queryData); + + if ($written !== \strlen($queryData)) { + // Write may potentially fail, but most common errors are already caught by connection check above. + // Among others, macOS is known to report here when trying to send to broadcast address. + // This can also be reproduced by writing data exceeding `stream_set_chunk_size()` to a server refusing UDP data. + // fwrite(): send of 8192 bytes failed with errno=111 Connection refused + $error = \error_get_last(); + \preg_match('/errno=(\d+) (.+)/', $error['message'], $m); + return \React\Promise\reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: Unable to send query to DNS server ' . $this->nameserver . ' (' . (isset($m[2]) ? $m[2] : $error['message']) . ')', + isset($m[1]) ? (int) $m[1] : 0 + )); + } + + $loop = $this->loop; + $deferred = new Deferred(function () use ($loop, $socket, $query) { + // cancellation should remove socket from loop and close socket + $loop->removeReadStream($socket); + \fclose($socket); + + throw new CancellationException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + + $max = $this->maxPacketSize; + $parser = $this->parser; + $nameserver = $this->nameserver; + $loop->addReadStream($socket, function ($socket) use ($loop, $deferred, $query, $parser, $request, $max, $nameserver) { + // try to read a single data packet from the DNS server + // ignoring any errors, this is uses UDP packets and not a stream of data + $data = @\fread($socket, $max); + if ($data === false) { + return; + } + + try { + $response = $parser->parseMessage($data); + } catch (\Exception $e) { + // ignore and await next if we received an invalid message from remote server + // this may as well be a fake response from an attacker (possible DOS) + return; + } + + // ignore and await next if we received an unexpected response ID + // this may as well be a fake response from an attacker (possible cache poisoning) + if ($response->id !== $request->id) { + return; + } + + // we only react to the first valid message, so remove socket from loop and close + $loop->removeReadStream($socket); + \fclose($socket); + + if ($response->tc) { + $deferred->reject(new \RuntimeException( + 'DNS query for ' . $query->describe() . ' failed: The DNS server ' . $nameserver . ' returned a truncated result for a UDP query', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90 + )); + return; + } + + $deferred->resolve($response); + }); + + return $deferred->promise(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/RecordNotFoundException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/RecordNotFoundException.php new file mode 100644 index 0000000..3b70274 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/RecordNotFoundException.php @@ -0,0 +1,7 @@ +decorateHostsFileExecutor($this->createExecutor($config, $loop ?: Loop::get())); + + return new Resolver($executor); + } + + /** + * Creates a cached DNS resolver instance for the given DNS config and cache + * + * As of v1.7.0 it's recommended to pass a `Config` object instead of a + * single nameserver address. If the given config contains more than one DNS + * nameserver, all DNS nameservers will be used in order. The primary DNS + * server will always be used first before falling back to the secondary or + * tertiary DNS server. + * + * @param Config|string $config DNS Config object (recommended) or single nameserver address + * @param ?LoopInterface $loop + * @param ?CacheInterface $cache + * @return \React\Dns\Resolver\ResolverInterface + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + public function createCached($config, LoopInterface $loop = null, CacheInterface $cache = null) + { + // default to keeping maximum of 256 responses in cache unless explicitly given + if (!($cache instanceof CacheInterface)) { + $cache = new ArrayCache(256); + } + + $executor = $this->createExecutor($config, $loop ?: Loop::get()); + $executor = new CachingExecutor($executor, $cache); + $executor = $this->decorateHostsFileExecutor($executor); + + return new Resolver($executor); + } + + /** + * Tries to load the hosts file and decorates the given executor on success + * + * @param ExecutorInterface $executor + * @return ExecutorInterface + * @codeCoverageIgnore + */ + private function decorateHostsFileExecutor(ExecutorInterface $executor) + { + try { + $executor = new HostsFileExecutor( + HostsFile::loadFromPathBlocking(), + $executor + ); + } catch (\RuntimeException $e) { + // ignore this file if it can not be loaded + } + + // Windows does not store localhost in hosts file by default but handles this internally + // To compensate for this, we explicitly use hard-coded defaults for localhost + if (DIRECTORY_SEPARATOR === '\\') { + $executor = new HostsFileExecutor( + new HostsFile("127.0.0.1 localhost\n::1 localhost"), + $executor + ); + } + + return $executor; + } + + /** + * @param Config|string $nameserver + * @param LoopInterface $loop + * @return CoopExecutor + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + private function createExecutor($nameserver, LoopInterface $loop) + { + if ($nameserver instanceof Config) { + if (!$nameserver->nameservers) { + throw new \UnderflowException('Empty config with no DNS servers'); + } + + // Hard-coded to check up to 3 DNS servers to match default limits in place in most systems (see MAXNS config). + // Note to future self: Recursion isn't too hard, but how deep do we really want to go? + $primary = reset($nameserver->nameservers); + $secondary = next($nameserver->nameservers); + $tertiary = next($nameserver->nameservers); + + if ($tertiary !== false) { + // 3 DNS servers given => nest first with fallback for second and third + return new CoopExecutor( + new RetryExecutor( + new FallbackExecutor( + $this->createSingleExecutor($primary, $loop), + new FallbackExecutor( + $this->createSingleExecutor($secondary, $loop), + $this->createSingleExecutor($tertiary, $loop) + ) + ) + ) + ); + } elseif ($secondary !== false) { + // 2 DNS servers given => fallback from first to second + return new CoopExecutor( + new RetryExecutor( + new FallbackExecutor( + $this->createSingleExecutor($primary, $loop), + $this->createSingleExecutor($secondary, $loop) + ) + ) + ); + } else { + // 1 DNS server given => use single executor + $nameserver = $primary; + } + } + + return new CoopExecutor(new RetryExecutor($this->createSingleExecutor($nameserver, $loop))); + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return ExecutorInterface + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createSingleExecutor($nameserver, LoopInterface $loop) + { + $parts = \parse_url($nameserver); + + if (isset($parts['scheme']) && $parts['scheme'] === 'tcp') { + $executor = $this->createTcpExecutor($nameserver, $loop); + } elseif (isset($parts['scheme']) && $parts['scheme'] === 'udp') { + $executor = $this->createUdpExecutor($nameserver, $loop); + } else { + $executor = new SelectiveTransportExecutor( + $this->createUdpExecutor($nameserver, $loop), + $this->createTcpExecutor($nameserver, $loop) + ); + } + + return $executor; + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createTcpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor( + new TcpTransportExecutor($nameserver, $loop), + 5.0, + $loop + ); + } + + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createUdpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor( + new UdpTransportExecutor( + $nameserver, + $loop + ), + 5.0, + $loop + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/Resolver.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/Resolver.php new file mode 100644 index 0000000..92926f3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/Resolver.php @@ -0,0 +1,147 @@ +executor = $executor; + } + + public function resolve($domain) + { + return $this->resolveAll($domain, Message::TYPE_A)->then(function (array $ips) { + return $ips[array_rand($ips)]; + }); + } + + public function resolveAll($domain, $type) + { + $query = new Query($domain, $type, Message::CLASS_IN); + $that = $this; + + return $this->executor->query( + $query + )->then(function (Message $response) use ($query, $that) { + return $that->extractValues($query, $response); + }); + } + + /** + * [Internal] extract all resource record values from response for this query + * + * @param Query $query + * @param Message $response + * @return array + * @throws RecordNotFoundException when response indicates an error or contains no data + * @internal + */ + public function extractValues(Query $query, Message $response) + { + // reject if response code indicates this is an error response message + $code = $response->rcode; + if ($code !== Message::RCODE_OK) { + switch ($code) { + case Message::RCODE_FORMAT_ERROR: + $message = 'Format Error'; + break; + case Message::RCODE_SERVER_FAILURE: + $message = 'Server Failure'; + break; + case Message::RCODE_NAME_ERROR: + $message = 'Non-Existent Domain / NXDOMAIN'; + break; + case Message::RCODE_NOT_IMPLEMENTED: + $message = 'Not Implemented'; + break; + case Message::RCODE_REFUSED: + $message = 'Refused'; + break; + default: + $message = 'Unknown error response code ' . $code; + } + throw new RecordNotFoundException( + 'DNS query for ' . $query->describe() . ' returned an error response (' . $message . ')', + $code + ); + } + + $answers = $response->answers; + $addresses = $this->valuesByNameAndType($answers, $query->name, $query->type); + + // reject if we did not receive a valid answer (domain is valid, but no record for this type could be found) + if (0 === count($addresses)) { + throw new RecordNotFoundException( + 'DNS query for ' . $query->describe() . ' did not return a valid answer (NOERROR / NODATA)' + ); + } + + return array_values($addresses); + } + + /** + * @param \React\Dns\Model\Record[] $answers + * @param string $name + * @param int $type + * @return array + */ + private function valuesByNameAndType(array $answers, $name, $type) + { + // return all record values for this name and type (if any) + $named = $this->filterByName($answers, $name); + $records = $this->filterByType($named, $type); + if ($records) { + return $this->mapRecordData($records); + } + + // no matching records found? check if there are any matching CNAMEs instead + $cnameRecords = $this->filterByType($named, Message::TYPE_CNAME); + if ($cnameRecords) { + $cnames = $this->mapRecordData($cnameRecords); + foreach ($cnames as $cname) { + $records = array_merge( + $records, + $this->valuesByNameAndType($answers, $cname, $type) + ); + } + } + + return $records; + } + + private function filterByName(array $answers, $name) + { + return $this->filterByField($answers, 'name', $name); + } + + private function filterByType(array $answers, $type) + { + return $this->filterByField($answers, 'type', $type); + } + + private function filterByField(array $answers, $field, $value) + { + $value = strtolower($value); + return array_filter($answers, function ($answer) use ($field, $value) { + return $value === strtolower($answer->$field); + }); + } + + private function mapRecordData(array $records) + { + return array_map(function ($record) { + return $record->data; + }, $records); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/ResolverInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/ResolverInterface.php new file mode 100644 index 0000000..fe937dc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/dns/src/Resolver/ResolverInterface.php @@ -0,0 +1,94 @@ +resolve('reactphp.org')->then(function ($ip) { + * echo 'IP for reactphp.org is ' . $ip . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a single IP + * address on success. + * + * If the DNS server sends a DNS response message that contains more than + * one IP address for this query, it will randomly pick one of the IP + * addresses from the response. If you want the full list of IP addresses + * or want to send a different type of query, you should use the + * [`resolveAll()`](#resolveall) method instead. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolve('reactphp.org'); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * resolves with a single IP address on success or rejects with an Exception on error. + */ + public function resolve($domain); + + /** + * Resolves all record values for the given $domain name and query $type. + * + * ```php + * $resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + * echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * + * $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + * echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a list with all + * record values on success. + * + * If the DNS server sends a DNS response message that contains one or more + * records for this query, it will return a list with all record values + * from the response. You can use the `Message::TYPE_*` constants to control + * which type of query will be sent. Note that this method always returns a + * list of record values, but each record value type depends on the query + * type. For example, it returns the IPv4 addresses for type `A` queries, + * the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, + * `CNAME` and `PTR` queries and structured data for other queries. See also + * the `Record` documentation for more details. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * Resolves with all record values on success or rejects with an Exception on error. + */ + public function resolveAll($domain, $type); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/CHANGELOG.md new file mode 100644 index 0000000..bd9e69d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/CHANGELOG.md @@ -0,0 +1,426 @@ +# Changelog + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Introduce new concept of default loop with the new `Loop` class. + (#226 by @WyriHaximus, #229, #231 and #232 by @clue) + + The `Loop` class exists as a convenient global accessor for the event loop. + It provides all methods that exist on the `LoopInterface` as static methods and + will automatically execute the loop at the end of the program: + + ```php + $timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; + }); + + Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; + }); + ``` + + The explicit loop instructions are still valid and may still be useful in some applications, + especially for a transition period towards the more concise style. + The `Loop::get()` method can be used to get the currently active event loop instance. + + ```php + // deprecated + $loop = React\EventLoop\Factory::create(); + + // new + $loop = React\EventLoop\Loop::get(); + ``` + +* Minor documentation improvements and mark legacy extensions as deprecated. + (#234 by @SimonFrings, #214 by @WyriHaximus and #233 and #235 by @nhedger) + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config and run tests on PHP 8. + (#212 and #215 by @SimonFrings and #230 by @clue) + +## 1.1.1 (2020-01-01) + +* Fix: Fix reporting connection refused errors with `ExtUvLoop` on Linux and `StreamSelectLoop` on Windows. + (#207 and #208 by @clue) + +* Fix: Fix unsupported EventConfig and `SEGFAULT` on shutdown with `ExtEventLoop` on Windows. + (#205 by @clue) + +* Fix: Prevent interval overflow for timers very far in the future with `ExtUvLoop`. + (#196 by @PabloKowalczyk) + +* Fix: Check PCNTL functions for signal support instead of PCNTL extension with `StreamSelectLoop`. + (#195 by @clue) + +* Add `.gitattributes` to exclude dev files from exports. + (#201 by @reedy) + +* Improve test suite to fix testing `ExtUvLoop` on Travis, + fix Travis CI builds, do not install `libuv` on legacy PHP setups, + fix failing test cases due to inaccurate timers, + run tests on Windows via Travis CI and + run tests on PHP 7.4 and simplify test matrix and test setup. + (#197 by @WyriHaximus and #202, #203, #204 and #209 by @clue) + +## 1.1.0 (2019-02-07) + +* New UV based event loop (ext-uv). + (#112 by @WyriHaximus) + +* Use high resolution timer on PHP 7.3+. + (#182 by @clue) + +* Improve PCNTL signals by using async signal dispatching if available. + (#179 by @CharlotteDunois) + +* Improve test suite and test suite set up. + (#174 by @WyriHaximus, #181 by @clue) + +* Fix PCNTL signals edge case. + (#183 by @clue) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.5.3 release. + +## 0.5.3 (2018-07-09) + +* Improve performance by importing global functions. + (#167 by @Ocramius) + +* Improve test suite by simplifying test bootstrap by using dev autoloader. + (#169 by @lcobucci) + +* Minor internal changes to improved backward compatibility with PHP 5.3. + (#166 by @Donatello-za) + +## 0.5.2 (2018-04-24) + +* Feature: Improve memory consumption and runtime performance for `StreamSelectLoop` timers. + (#164 by @clue) + +* Improve test suite by removing I/O dependency at `StreamSelectLoopTest` to fix Mac OS X tests. + (#161 by @nawarian) + +## 0.5.1 (2018-04-09) + +* Feature: New `ExtEvLoop` (PECL ext-ev) (#148 by @kaduev13) + +## 0.5.0 (2018-04-05) + +A major feature release with a significant documentation overhaul and long overdue API cleanup! + +This update involves a number of BC breaks due to dropped support for deprecated +functionality. We've tried hard to avoid BC breaks where possible and minimize +impact otherwise. We expect that most consumers of this package will actually +not be affected by any BC breaks, see below for more details. + +We realize that the changes listed below may seem overwhelming, but we've tried +to be very clear about any possible BC breaks. Don't worry: In fact, all ReactPHP +components are already compatible and support both this new release as well as +providing backwards compatibility with the last release. + +* Feature / BC break: Add support for signal handling via new + `LoopInterface::addSignal()` and `LoopInterface::removeSignal()` methods. + (#104 by @WyriHaximus and #111 and #150 by @clue) + + ```php + $loop->addSignal(SIGINT, function () { + echo 'CTRL-C'; + }); + ``` + +* Feature: Significant documentation updates for `LoopInterface` and `Factory`. + (#100, #119, #126, #127, #159 and #160 by @clue, #113 by @WyriHaximus and #81 and #91 by @jsor) + +* Feature: Add examples to ease getting started + (#99, #100 and #125 by @clue, #59 by @WyriHaximus and #143 by @jsor) + +* Feature: Documentation for advanced timer concepts, such as monotonic time source vs wall-clock time + and high precision timers with millisecond accuracy or below. + (#130 and #157 by @clue) + +* Feature: Documentation for advanced stream concepts, such as edge-triggered event listeners + and stream buffers and allow throwing Exception if stream resource is not supported. + (#129 and #158 by @clue) + +* Feature: Throw `BadMethodCallException` on manual loop creation when required extension isn't installed. + (#153 by @WyriHaximus) + +* Feature / BC break: First class support for legacy PHP 5.3 through PHP 7.2 and HHVM + and remove all `callable` type hints for consistency reasons. + (#141 and #151 by @clue) + +* BC break: Documentation for timer API and clean up unneeded timer API. + (#102 by @clue) + + Remove `TimerInterface::cancel()`, use `LoopInterface::cancelTimer()` instead: + + ```php + // old (method invoked on timer instance) + $timer->cancel(); + + // already supported before: invoke method on loop instance + $loop->cancelTimer($timer); + ``` + + Remove unneeded `TimerInterface::setData()` and `TimerInterface::getData()`, + use closure binding to add arbitrary data to timer instead: + + ```php + // old (limited setData() and getData() only allows single variable) + $name = 'Tester'; + $timer = $loop->addTimer(1.0, function ($timer) { + echo 'Hello ' . $timer->getData() . PHP_EOL; + }); + $timer->setData($name); + + // already supported before: closure binding allows any number of variables + $name = 'Tester'; + $loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . PHP_EOL; + }); + ``` + + Remove unneeded `TimerInterface::getLoop()`, use closure binding instead: + + ```php + // old (getLoop() called on timer instance) + $loop->addTimer(0.1, function ($timer) { + $timer->getLoop()->stop(); + }); + + // already supported before: use closure binding as usual + $loop->addTimer(0.1, function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::isTimerActive()` and + `TimerInterface::isActive()` to reduce API surface. + (#133 by @clue) + + ```php + // old (method on timer instance or on loop instance) + $timer->isActive(); + $loop->isTimerActive($timer); + ``` + +* BC break: Move `TimerInterface` one level up to `React\EventLoop\TimerInterface`. + (#138 by @WyriHaximus) + + ```php + // old (notice obsolete "Timer" namespace) + assert($timer instanceof React\EventLoop\Timer\TimerInterface); + + // new + assert($timer instanceof React\EventLoop\TimerInterface); + ``` + +* BC break: Remove unneeded `LoopInterface::nextTick()` (and internal `NextTickQueue`), + use `LoopInterface::futureTick()` instead. + (#30 by @clue) + + ```php + // old (removed) + $loop->nextTick(function () { + echo 'tick'; + }); + + // already supported before + $loop->futureTick(function () { + echo 'tick'; + }); + ``` + +* BC break: Remove unneeded `$loop` argument for `LoopInterface::futureTick()` + (and fix internal cyclic dependency). + (#103 by @clue) + + ```php + // old ($loop gets passed by default) + $loop->futureTick(function ($loop) { + $loop->stop(); + }); + + // already supported before: use closure binding as usual + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::tick()`. + (#72 by @jsor) + + ```php + // old (removed) + $loop->tick(); + + // suggested work around for testing purposes only + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Documentation for advanced stream API and clean up unneeded stream API. + (#110 by @clue) + + Remove unneeded `$loop` argument for `LoopInterface::addReadStream()` + and `LoopInterface::addWriteStream()`, use closure binding instead: + + ```php + // old ($loop gets passed by default) + $loop->addReadStream($stream, function ($stream, $loop) { + $loop->removeReadStream($stream); + }); + + // already supported before: use closure binding as usual + $loop->addReadStream($stream, function ($stream) use ($loop) { + $loop->removeReadStream($stream); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::removeStream()` method, + use `LoopInterface::removeReadStream()` and `LoopInterface::removeWriteStream()` instead. + (#118 by @clue) + + ```php + // old + $loop->removeStream($stream); + + // already supported before + $loop->removeReadStream($stream); + $loop->removeWriteStream($stream); + ``` + +* BC break: Rename `LibEventLoop` to `ExtLibeventLoop` and `LibEvLoop` to `ExtLibevLoop` + for consistent naming for event loop implementations. + (#128 by @clue) + +* BC break: Remove optional `EventBaseConfig` argument from `ExtEventLoop` + and make its `FEATURE_FDS` enabled by default. + (#156 by @WyriHaximus) + +* BC break: Mark all classes as final to discourage inheritance. + (#131 by @clue) + +* Fix: Fix `ExtEventLoop` to keep track of stream resources (refcount) + (#123 by @clue) + +* Fix: Ensure large timer interval does not overflow on 32bit systems + (#132 by @clue) + +* Fix: Fix separately removing readable and writable side of stream when closing + (#139 by @clue) + +* Fix: Properly clean up event watchers for `ext-event` and `ext-libev` + (#149 by @clue) + +* Fix: Minor code cleanup and remove unneeded references + (#145 by @seregazhuk) + +* Fix: Discourage outdated `ext-libevent` on PHP 7 + (#62 by @cboden) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and PHPUnit 5, + lock Travis distro so new defaults will not break the build, + improve test suite to be less fragile and increase test timeouts, + test against PHP 7.2 and reduce fwrite() call length to one chunk. + (#106 and #144 by @clue, #120 and #124 by @carusogabriel, #147 by nawarian and #92 by @kelunik) + +* A number of changes were originally planned for this release but have been backported + to the last `v0.4.3` already: #74, #76, #79, #81 (refs #65, #66, #67), #88 and #93 + +## 0.4.3 (2017-04-27) + +* Bug fix: Bugfix in the usage sample code #57 (@dandelionred) +* Improvement: Remove branch-alias definition #53 (@WyriHaximus) +* Improvement: StreamSelectLoop: Use fresh time so Timers added during stream events are accurate #51 (@andrewminerd) +* Improvement: Avoid deprecation warnings in test suite due to deprecation of getMock() in PHPUnit #68 (@martinschroeder) +* Improvement: Add PHPUnit 4.8 to require-dev #69 (@shaunbramley) +* Improvement: Increase test timeouts for HHVM and unify timeout handling #70 (@clue) +* Improvement: Travis improvements (backported from #74) #75 (@clue) +* Improvement: Test suite now uses socket pairs instead of memory streams #66 (@martinschroeder) +* Improvement: StreamSelectLoop: Test suite uses signal constant names in data provider #67 (@martinschroeder) +* Improvement: ExtEventLoop: No longer suppress all errors #65 (@mamciek) +* Improvement: Readme cleanup #89 (@jsor) +* Improvement: Restructure and improve README #90 (@jsor) +* Bug fix: StreamSelectLoop: Fix erroneous zero-time sleep (backport to 0.4) #94 (@jsor) + +## 0.4.2 (2016-03-07) + +* Bug fix: No longer error when signals sent to StreamSelectLoop +* Support HHVM and PHP7 (@ondrejmirtes, @cebe) +* Feature: Added support for EventConfig for ExtEventLoop (@steverhoades) +* Bug fix: Fixed an issue loading loop extension libs via autoloader (@czarpino) + +## 0.4.1 (2014-04-13) + +* Bug fix: null timeout in StreamSelectLoop causing 100% CPU usage (@clue) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.4.0 (2014-02-02) + +* Feature: Added `EventLoopInterface::nextTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `EventLoopInterface::futureTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `ExtEventLoop` implementation using pecl/event (@jmalloc) +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: New method: `EventLoopInterface::nextTick()` +* BC break: New method: `EventLoopInterface::futureTick()` +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.5 (2016-12-28) + +This is a compatibility release that eases upgrading to the v0.4 release branch. +You should consider upgrading to the v0.4 release branch. + +* Feature: Cap min timer interval at 1µs, thus improving compatibility with v0.4 + (#47 by @clue) + +## 0.3.4 (2014-03-30) + +* Bug fix: Changed StreamSelectLoop to use non-blocking behavior on tick() (@astephens25) + +## 0.3.3 (2013-07-08) + +* Bug fix: No error on removing non-existent streams (@clue) +* Bug fix: Do not silently remove feof listeners in `LibEvLoop` + +## 0.3.0 (2013-04-14) + +* BC break: New timers API (@nrk) +* BC break: Remove check on return value from stream callbacks (@nrk) + +## 0.2.7 (2013-01-05) + +* Bug fix: Fix libevent timers with PHP 5.3 +* Bug fix: Fix libevent timer cancellation (@nrk) + +## 0.2.6 (2012-12-26) + +* Bug fix: Plug memory issue in libevent timers (@cameronjacobson) +* Bug fix: Correctly pause LibEvLoop on stop() + +## 0.2.3 (2012-11-14) + +* Feature: LibEvLoop, integration of `php-libev` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/README.md new file mode 100644 index 0000000..b89ad57 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/README.md @@ -0,0 +1,919 @@ +# EventLoop Component + +[![CI status](https://github.com/reactphp/event-loop/workflows/CI/badge.svg)](https://github.com/reactphp/event-loop/actions) + +[ReactPHP](https://reactphp.org/)'s core reactor event loop that libraries can use for evented I/O. + +In order for async based libraries to be interoperable, they need to use the +same event loop. This component provides a common `LoopInterface` that any +library can target. This allows them to be used in the same loop, with one +single [`run()`](#run) call that is controlled by the user. + +**Table of Contents** + +* [Quickstart example](#quickstart-example) +* [Usage](#usage) + * [Loop](#loop) + * [Loop methods](#loop-methods) + * [Loop autorun](#loop-autorun) + * [get()](#get) + * [~~Factory~~](#factory) + * [~~create()~~](#create) + * [Loop implementations](#loop-implementations) + * [StreamSelectLoop](#streamselectloop) + * [ExtEventLoop](#exteventloop) + * [ExtEvLoop](#extevloop) + * [ExtUvLoop](#extuvloop) + * [~~ExtLibeventLoop~~](#extlibeventloop) + * [~~ExtLibevLoop~~](#extlibevloop) + * [LoopInterface](#loopinterface) + * [run()](#run) + * [stop()](#stop) + * [addTimer()](#addtimer) + * [addPeriodicTimer()](#addperiodictimer) + * [cancelTimer()](#canceltimer) + * [futureTick()](#futuretick) + * [addSignal()](#addsignal) + * [removeSignal()](#removesignal) + * [addReadStream()](#addreadstream) + * [addWriteStream()](#addwritestream) + * [removeReadStream()](#removereadstream) + * [removeWriteStream()](#removewritestream) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Quickstart example + +Here is an async HTTP server built with just the event loop. + +```php +addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); + +$loop->run(); +``` + +While the former is more concise, the latter is more explicit. +In both cases, the program would perform the exact same steps. + +1. The event loop instance is created at the beginning of the program. This is + implicitly done the first time you call the [`Loop` class](#loop) or + explicitly when using the deprecated [`Factory::create() method`](#create) + (or manually instantiating any of the [loop implementations](#loop-implementations)). +2. The event loop is used directly or passed as an instance to library and + application code. In this example, a periodic timer is registered with the + event loop which simply outputs `Tick` every fraction of a second until another + timer stops the periodic timer after a second. +3. The event loop is run at the end of the program. This is automatically done + when using [`Loop` class](#loop) or explicitly with a single [`run()`](#run) + call at the end of the program. + +As of `v1.2.0`, we highly recommend using the [`Loop` class](#loop). +The explicit loop instructions are still valid and may still be useful in some +applications, especially for a transition period towards the more concise style. + +### Loop + +The `Loop` class exists as a convenient global accessor for the event loop. + +#### Loop methods + +The `Loop` class provides all methods that exist on the [`LoopInterface`](#loopinterface) +as static methods: + +* [run()](#run) +* [stop()](#stop) +* [addTimer()](#addtimer) +* [addPeriodicTimer()](#addperiodictimer) +* [cancelTimer()](#canceltimer) +* [futureTick()](#futuretick) +* [addSignal()](#addsignal) +* [removeSignal()](#removesignal) +* [addReadStream()](#addreadstream) +* [addWriteStream()](#addwritestream) +* [removeReadStream()](#removereadstream) +* [removeWriteStream()](#removewritestream) + +If you're working with the event loop in your application code, it's often +easiest to directly interface with the static methods defined on the `Loop` class +like this: + +```php +use React\EventLoop\Loop; + +$timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +On the other hand, if you're familiar with object-oriented programming (OOP) and +dependency injection (DI), you may want to inject an event loop instance and +invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +Each static method call will be forwarded as-is to the underlying event loop +instance by using the [`Loop::get()`](#get) call internally. +See [`LoopInterface`](#loopinterface) for more details about available methods. + +#### Loop autorun + +When using the `Loop` class, it will automatically execute the loop at the end of +the program. This means the following example will schedule a timer and will +automatically execute the program until the timer event fires: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(1.0, function () { + echo 'Hello' . PHP_EOL; +}); +``` + +As of `v1.2.0`, we highly recommend using the `Loop` class this way and omitting any +explicit [`run()`](#run) calls. For BC reasons, the explicit [`run()`](#run) +method is still valid and may still be useful in some applications, especially +for a transition period towards the more concise style. + +If you don't want the `Loop` to run automatically, you can either explicitly +[`run()`](#run) or [`stop()`](#stop) it. This can be useful if you're using +a global exception handler like this: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(10.0, function () { + echo 'Never happens'; +}); + +set_exception_handler(function (Throwable $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; + Loop::stop(); +}); + +throw new RuntimeException('Demo'); +``` + +#### get() + +The `get(): LoopInterface` method can be used to +get the currently active event loop instance. + +This method will always return the same event loop instance throughout the +lifetime of your application. + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +$loop = Loop::get(); + +assert($loop instanceof LoopInterface); +assert($loop === Loop::get()); +``` + +This is particularly useful if you're using object-oriented programming (OOP) +and dependency injection (DI). In this case, you may want to inject an event +loop instance and invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +See [`LoopInterface`](#loopinterface) for more details about available methods. + +### ~~Factory~~ + +> Deprecated since v1.2.0, see [`Loop` class](#loop) instead. + +The deprecated `Factory` class exists as a convenient way to pick the best available +[event loop implementation](#loop-implementations). + +#### ~~create()~~ + +> Deprecated since v1.2.0, see [`Loop::get()`](#get) instead. + +The deprecated `create(): LoopInterface` method can be used to +create a new event loop instance: + +```php +// deprecated +$loop = React\EventLoop\Factory::create(); + +// new +$loop = React\EventLoop\Loop::get(); +``` + +This method always returns an instance implementing [`LoopInterface`](#loopinterface), +the actual [event loop implementation](#loop-implementations) is an implementation detail. + +This method should usually only be called once at the beginning of the program. + +### Loop implementations + +In addition to the [`LoopInterface`](#loopinterface), there are a number of +event loop implementations provided. + +All of the event loops support these features: + +* File descriptor polling +* One-off timers +* Periodic timers +* Deferred execution on future loop tick + +For most consumers of this package, the underlying event loop implementation is +an implementation detail. +You should use the [`Factory`](#factory) to automatically create a new instance. + +Advanced! If you explicitly need a certain event loop implementation, you can +manually instantiate one of the following classes. +Note that you may have to install the required PHP extensions for the respective +event loop implementation first or they will throw a `BadMethodCallException` on creation. + +#### StreamSelectLoop + +A `stream_select()` based event loop. + +This uses the [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) +function and is the only implementation which works out of the box with PHP. + +This event loop works out of the box on PHP 5.3 through PHP 7+ and HHVM. +This means that no installation is required and this library works on all +platforms and supported PHP versions. +Accordingly, the [`Factory`](#factory) will use this event loop by default if +you do not install any of the event loop extensions listed below. + +Under the hood, it does a simple `select` system call. +This system call is limited to the maximum file descriptor number of +`FD_SETSIZE` (platform dependent, commonly 1024) and scales with `O(m)` +(`m` being the maximum file descriptor number passed). +This means that you may run into issues when handling thousands of streams +concurrently and you may want to look into using one of the alternative +event loop implementations listed below in this case. +If your use case is among the many common use cases that involve handling only +dozens or a few hundred streams at once, then this event loop implementation +performs really well. + +If you want to use signal handling (see also [`addSignal()`](#addsignal) below), +this event loop implementation requires `ext-pcntl`. +This extension is only available for Unix-like platforms and does not support +Windows. +It is commonly installed as part of many PHP distributions. +If this extension is missing (or you're running on Windows), signal handling is +not supported and throws a `BadMethodCallException` instead. + +This event loop is known to rely on wall-clock time to schedule future timers +when using any version before PHP 7.3, because a monotonic time source is +only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and +then adjust your system time forward by 20s, the timer may trigger in 10s. +See also [`addTimer()`](#addtimer) for more details. + +#### ExtEventLoop + +An `ext-event` based event loop. + +This uses the [`event` PECL extension](https://pecl.php.net/package/event), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 5.4 through PHP 7+. + +#### ExtEvLoop + +An `ext-ev` based event loop. + +This loop uses the [`ev` PECL extension](https://pecl.php.net/package/ev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + + +This loop is known to work with PHP 5.4 through PHP 7+. + +#### ExtUvLoop + +An `ext-uv` based event loop. + +This loop uses the [`uv` PECL extension](https://pecl.php.net/package/uv), +that provides an interface to `libuv` library. +`libuv` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 7+. + +#### ~~ExtLibeventLoop~~ + +> Deprecated since v1.2.0, use [`ExtEventLoop`](#exteventloop) instead. + +An `ext-libevent` based event loop. + +This uses the [`libevent` PECL extension](https://pecl.php.net/package/libevent), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This event loop does only work with PHP 5. +An [unofficial update](https://github.com/php/pecl-event-libevent/pull/2) for +PHP 7 does exist, but it is known to cause regular crashes due to `SEGFAULT`s. +To reiterate: Using this event loop on PHP 7 is not recommended. +Accordingly, the [`Factory`](#factory) will not try to use this event loop on +PHP 7. + +This event loop is known to trigger a readable listener only if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. +See also [`addReadStream()`](#addreadstream) for more details. + +#### ~~ExtLibevLoop~~ + +> Deprecated since v1.2.0, use [`ExtEvLoop`](#extevloop) instead. + +An `ext-libev` based event loop. + +This uses an [unofficial `libev` extension](https://github.com/m4rw3r/php-libev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + +This loop does only work with PHP 5. +An update for PHP 7 is [unlikely](https://github.com/m4rw3r/php-libev/issues/8) +to happen any time soon. + +### LoopInterface + +#### run() + +The `run(): void` method can be used to +run the event loop until there are no more tasks to perform. + +For many applications, this method is the only directly visible +invocation on the event loop. +As a rule of thumb, it is usally recommended to attach everything to the +same loop instance and then run the loop once at the bottom end of the +application. + +```php +$loop->run(); +``` + +This method will keep the loop running until there are no more tasks +to perform. In other words: This method will block until the last +timer, stream and/or signal has been removed. + +Likewise, it is imperative to ensure the application actually invokes +this method once. Adding listeners to the loop and missing to actually +run it will result in the application exiting without actually waiting +for any of the attached listeners. + +This method MUST NOT be called while the loop is already running. +This method MAY be called more than once after it has explicity been +[`stop()`ped](#stop) or after it automatically stopped because it +previously did no longer have anything to do. + +#### stop() + +The `stop(): void` method can be used to +instruct a running event loop to stop. + +This method is considered advanced usage and should be used with care. +As a rule of thumb, it is usually recommended to let the loop stop +only automatically when it no longer has anything to do. + +This method can be used to explicitly instruct the event loop to stop: + +```php +$loop->addTimer(3.0, function () use ($loop) { + $loop->stop(); +}); +``` + +Calling this method on a loop instance that is not currently running or +on a loop instance that has already been stopped has no effect. + +#### addTimer() + +The `addTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked once after the given interval. + +The timer callback function MUST be able to accept a single parameter, +the timer instance as also returned by this method or you MAY use a +function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure +the callback will be invoked only once after the given interval. +You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. + +```php +$loop->addTimer(0.8, function () { + echo 'world!' . PHP_EOL; +}); + +$loop->addTimer(0.3, function () { + echo 'hello '; +}); +``` + +See also [example #1](examples). + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->addTimer(1.0, function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +#### addPeriodicTimer() + +The `addPeriodicTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked repeatedly after the given interval. + +The timer callback function MUST be able to accept a single parameter, +the timer instance as also returned by this method or you MAY use a +function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +Unlike [`addTimer()`](#addtimer), this method will ensure the the +callback will be invoked infinitely after the given interval or until you +invoke [`cancelTimer`](#canceltimer). + +```php +$timer = $loop->addPeriodicTimer(0.1, function () { + echo 'tick!' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +See also [example #2](examples). + +If you want to limit the number of executions, you can bind +arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $n = 3; + $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + if ($n > 0) { + --$n; + echo "hello $name\n"; + } else { + $loop->cancelTimer($timer); + } + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +Additionally, periodic timers may be subject to timer drift due to +re-scheduling after each invocation. As such, it's generally not +recommended to rely on this for high precision intervals with millisecond +accuracy or below. + +#### cancelTimer() + +The `cancelTimer(TimerInterface $timer): void` method can be used to +cancel a pending timer. + +See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + +Calling this method on a timer instance that has not been added to this +loop instance or on a timer that has already been cancelled has no effect. + +#### futureTick() + +The `futureTick(callable $listener): void` method can be used to +schedule a callback to be invoked on a future tick of the event loop. + +This works very much similar to timers with an interval of zero seconds, +but does not require the overhead of scheduling a timer queue. + +The tick callback function MUST be able to accept zero parameters. + +The tick callback function MUST NOT throw an `Exception`. +The return value of the tick callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->futureTick(function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +Unlike timers, tick callbacks are guaranteed to be executed in the order +they are enqueued. +Also, once a callback is enqueued, there's no way to cancel this operation. + +This is often used to break down bigger tasks into smaller steps (a form +of cooperative multitasking). + +```php +$loop->futureTick(function () { + echo 'b'; +}); +$loop->futureTick(function () { + echo 'c'; +}); +echo 'a'; +``` + +See also [example #3](examples). + +#### addSignal() + +The `addSignal(int $signal, callable $listener): void` method can be used to +register a listener to be notified when a signal has been caught by this process. + +This is useful to catch user interrupt signals or shutdown signals from +tools like `supervisor` or `systemd`. + +The listener callback function MUST be able to accept a single parameter, +the signal added by this method or you MAY use a function which +has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +```php +$loop->addSignal(SIGINT, function (int $signal) { + echo 'Caught user interrupt signal' . PHP_EOL; +}); +``` + +See also [example #4](examples). + +Signaling is only available on Unix-like platform, Windows isn't +supported due to operating system limitations. +This method may throw a `BadMethodCallException` if signals aren't +supported on this platform, for example when required extensions are +missing. + +**Note: A listener can only be added once to the same signal, any +attempts to add it more then once will be ignored.** + +#### removeSignal() + +The `removeSignal(int $signal, callable $listener): void` method can be used to +remove a previously added signal listener. + +```php +$loop->removeSignal(SIGINT, $listener); +``` + +Any attempts to remove listeners that aren't registered will be ignored. + +#### addReadStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [readable Stream API](https://github.com/reactphp/stream#readablestreaminterface) + instead. + +The `addReadStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to read. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to read by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeReadStream()`](#removereadstream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The listener callback function MUST be able to accept a single parameter, +the stream resource added by this method or you MAY use a function which +has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addReadStream($stream, function ($stream) use ($name) { + echo $name . ' said: ' . fread($stream); +}); +``` + +See also [example #11](examples). + +You can invoke [`removeReadStream()`](#removereadstream) to remove the +read event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +Some event loop implementations are known to only trigger the listener if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. + +#### addWriteStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + instead. + +The `addWriteStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to write. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to write by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeWriteStream()`](#removewritestream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The listener callback function MUST be able to accept a single parameter, +the stream resource added by this method or you MAY use a function which +has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addWriteStream($stream, function ($stream) use ($name) { + fwrite($stream, 'Hello ' . $name); +}); +``` + +See also [example #12](examples). + +You can invoke [`removeWriteStream()`](#removewritestream) to remove the +write event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +#### removeReadStream() + +The `removeReadStream(resource $stream): void` method can be used to +remove the read event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +#### removeWriteStream() + +The `removeWriteStream(resource $stream): void` method can be used to +remove the write event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/event-loop:^1.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +Installing any of the event loop extensions is suggested, but entirely optional. +See also [event loop implementations](#loop-implementations) for more details. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See our [Stream component](https://github.com/reactphp/stream) for more + information on how streams are used in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/event-loop/dependents) + for a list of packages that use the EventLoop in real-world applications. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/composer.json new file mode 100644 index 0000000..d9b032e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/composer.json @@ -0,0 +1,49 @@ +{ + "name": "react/event-loop", + "description": "ReactPHP's core reactor event loop that libraries can use for evented I/O.", + "keywords": ["event-loop", "asynchronous"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "suggest": { + "ext-event": "~1.0 for ExtEventLoop", + "ext-pcntl": "For signal handling support when using the StreamSelectLoop", + "ext-uv": "* for ExtUvLoop" + }, + "autoload": { + "psr-4": { + "React\\EventLoop\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\EventLoop\\": "tests" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEvLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEvLoop.php new file mode 100644 index 0000000..7fcc29a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEvLoop.php @@ -0,0 +1,253 @@ +loop = new EvLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + + public function addReadStream($stream, $listener) + { + $key = (int)$stream; + + if (isset($this->readStreams[$key])) { + return; + } + + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::READ, $callback); + $this->readStreams[$key] = $event; + } + + /** + * @param resource $stream + * @param callable $listener + * + * @return \Closure + */ + private function getStreamListenerClosure($stream, $listener) + { + return function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + } + + public function addWriteStream($stream, $listener) + { + $key = (int)$stream; + + if (isset($this->writeStreams[$key])) { + return; + } + + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::WRITE, $callback); + $this->writeStreams[$key] = $event; + } + + public function removeReadStream($stream) + { + $key = (int)$stream; + + if (!isset($this->readStreams[$key])) { + return; + } + + $this->readStreams[$key]->stop(); + unset($this->readStreams[$key]); + } + + public function removeWriteStream($stream) + { + $key = (int)$stream; + + if (!isset($this->writeStreams[$key])) { + return; + } + + $this->writeStreams[$key]->stop(); + unset($this->writeStreams[$key]); + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $that = $this; + $timers = $this->timers; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = $this->loop->timer($timer->getInterval(), 0.0, $callback); + $this->timers->attach($timer, $event); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $event = $this->loop->timer($interval, $interval, $callback); + $this->timers->attach($timer, $event); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if (!isset($this->timers[$timer])) { + return; + } + + $event = $this->timers[$timer]; + $event->stop(); + $this->timers->detach($timer); + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams + && !$this->writeStreams + && !$this->timers->count() + && $this->signals->isEmpty(); + + $flags = Ev::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags |= Ev::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + + $this->loop->run($flags); + } + } + + public function stop() + { + $this->running = false; + } + + public function __destruct() + { + /** @var TimerInterface $timer */ + foreach ($this->timers as $timer) { + $this->cancelTimer($timer); + } + + foreach ($this->readStreams as $key => $stream) { + $this->removeReadStream($key); + } + + foreach ($this->writeStreams as $key => $stream) { + $this->removeWriteStream($key); + } + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = $this->loop->signal($signal, function() use ($signal) { + $this->signals->call($signal); + }); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal]->stop(); + unset($this->signalEvents[$signal]); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEventLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEventLoop.php new file mode 100644 index 0000000..7ce5001 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtEventLoop.php @@ -0,0 +1,275 @@ +requireFeatures(\EventConfig::FEATURE_FDS); + } + + $this->eventBase = new EventBase($config); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + + $this->createTimerCallback(); + $this->createStreamCallback(); + } + + public function __destruct() + { + // explicitly clear all references to Event objects to prevent SEGFAULTs on Windows + foreach ($this->timerEvents as $timer) { + $this->timerEvents->detach($timer); + } + + $this->readEvents = array(); + $this->writeEvents = array(); + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::READ, $this->streamCallback); + $event->add(); + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->readRefs[$key] = $stream; + } + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::WRITE, $this->streamCallback); + $event->add(); + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->writeRefs[$key] = $stream; + } + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->free(); + unset( + $this->readEvents[$key], + $this->readListeners[$key], + $this->readRefs[$key] + ); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->free(); + unset( + $this->writeEvents[$key], + $this->writeListeners[$key], + $this->writeRefs[$key] + ); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->contains($timer)) { + $this->timerEvents[$timer]->free(); + $this->timerEvents->detach($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = Event::signal($this->eventBase, $signal, array($this->signals, 'call')); + $this->signalEvents[$signal]->add(); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->free(); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = EventBase::LOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventBase::LOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + $this->eventBase->loop($flags); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $flags = Event::TIMEOUT; + + if ($timer->isPeriodic()) { + $flags |= Event::PERSIST; + } + + $event = new Event($this->eventBase, -1, $flags, $this->timerCallback, $timer); + $this->timerEvents[$timer] = $event; + + $event->add($timer->getInterval()); + } + + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use ($timers) { + \call_user_func($timer->getCallback(), $timer); + + if (!$timer->isPeriodic() && $timers->contains($timer)) { + $this->cancelTimer($timer); + } + }; + } + + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use (&$read, &$write) { + $key = (int) $stream; + + if (Event::READ === (Event::READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + + if (Event::WRITE === (Event::WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibevLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibevLoop.php new file mode 100644 index 0000000..2cf1ad5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibevLoop.php @@ -0,0 +1,201 @@ +loop = new EventLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + + public function addReadStream($stream, $listener) + { + if (isset($this->readEvents[(int) $stream])) { + return; + } + + $callback = function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + + $event = new IOEvent($callback, $stream, IOEvent::READ); + $this->loop->add($event); + + $this->readEvents[(int) $stream] = $event; + } + + public function addWriteStream($stream, $listener) + { + if (isset($this->writeEvents[(int) $stream])) { + return; + } + + $callback = function () use ($stream, $listener) { + \call_user_func($listener, $stream); + }; + + $event = new IOEvent($callback, $stream, IOEvent::WRITE); + $this->loop->add($event); + + $this->writeEvents[(int) $stream] = $event; + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->stop(); + $this->loop->remove($this->readEvents[$key]); + unset($this->readEvents[$key]); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->stop(); + $this->loop->remove($this->writeEvents[$key]); + unset($this->writeEvents[$key]); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer( $interval, $callback, false); + + $that = $this; + $timers = $this->timerEvents; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = new TimerEvent($callback, $timer->getInterval()); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $event = new TimerEvent($callback, $interval, $interval); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timerEvents[$timer])) { + $this->loop->remove($this->timerEvents[$timer]); + $this->timerEvents->detach($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = new SignalEvent(function () use ($signals, $signal) { + $signals->call($signal); + }, $signal); + $this->loop->add($this->signalEvents[$signal]); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->stop(); + $this->loop->remove($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = EventLoop::RUN_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventLoop::RUN_NOWAIT; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + $this->loop->run($flags); + } + } + + public function stop() + { + $this->running = false; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibeventLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibeventLoop.php new file mode 100644 index 0000000..2ea7ffa --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtLibeventLoop.php @@ -0,0 +1,285 @@ +eventBase = \event_base_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + + $this->createTimerCallback(); + $this->createStreamCallback(); + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_READ, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_WRITE, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + if (isset($this->readListeners[$key])) { + $event = $this->readEvents[$key]; + \event_del($event); + \event_free($event); + + unset( + $this->readEvents[$key], + $this->readListeners[$key] + ); + } + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + if (isset($this->writeListeners[$key])) { + $event = $this->writeEvents[$key]; + \event_del($event); + \event_free($event); + + unset( + $this->writeEvents[$key], + $this->writeListeners[$key] + ); + } + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->scheduleTimer($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->contains($timer)) { + $event = $this->timerEvents[$timer]; + \event_del($event); + \event_free($event); + + $this->timerEvents->detach($timer); + } + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = \event_new(); + \event_set($this->signalEvents[$signal], $signal, \EV_PERSIST | \EV_SIGNAL, array($this->signals, 'call')); + \event_base_set($this->signalEvents[$signal], $this->eventBase); + \event_add($this->signalEvents[$signal]); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \event_del($this->signalEvents[$signal]); + \event_free($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $flags = \EVLOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= \EVLOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + + \event_base_loop($this->eventBase, $flags); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $this->timerEvents[$timer] = $event = \event_timer_new(); + + \event_timer_set($event, $this->timerCallback, $timer); + \event_base_set($event, $this->eventBase); + \event_add($event, $timer->getInterval() * self::MICROSECONDS_PER_SECOND); + } + + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $that = $this; + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use ($timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + // Timer already cancelled ... + if (!$timers->contains($timer)) { + return; + } + + // Reschedule periodic timers ... + if ($timer->isPeriodic()) { + \event_add( + $timers[$timer], + $timer->getInterval() * ExtLibeventLoop::MICROSECONDS_PER_SECOND + ); + + // Clean-up one shot timers ... + } else { + $that->cancelTimer($timer); + } + }; + } + + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use (&$read, &$write) { + $key = (int) $stream; + + if (\EV_READ === (\EV_READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + + if (\EV_WRITE === (\EV_WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtUvLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtUvLoop.php new file mode 100644 index 0000000..4434720 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/ExtUvLoop.php @@ -0,0 +1,342 @@ +uv = \uv_loop_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->streamListener = $this->createStreamListener(); + $this->signals = new SignalsHandler(); + } + + /** + * Returns the underlying ext-uv event loop. (Internal ReactPHP use only.) + * + * @internal + * + * @return resource + */ + public function getUvLoop() + { + return $this->uv; + } + + /** + * {@inheritdoc} + */ + public function addReadStream($stream, $listener) + { + if (isset($this->readStreams[(int) $stream])) { + return; + } + + $this->readStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + + /** + * {@inheritdoc} + */ + public function addWriteStream($stream, $listener) + { + if (isset($this->writeStreams[(int) $stream])) { + return; + } + + $this->writeStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + + /** + * {@inheritdoc} + */ + public function removeReadStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + unset($this->readStreams[(int) $stream]); + $this->removeStream($stream); + } + + /** + * {@inheritdoc} + */ + public function removeWriteStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + unset($this->writeStreams[(int) $stream]); + $this->removeStream($stream); + } + + /** + * {@inheritdoc} + */ + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $that = $this; + $timers = $this->timers; + $callback = function () use ($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + + $event = \uv_timer_init($this->uv); + $this->timers->attach($timer, $event); + \uv_timer_start( + $event, + $this->convertFloatSecondsToMilliseconds($interval), + 0, + $callback + ); + + return $timer; + } + + /** + * {@inheritdoc} + */ + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $callback = function () use ($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + + $interval = $this->convertFloatSecondsToMilliseconds($interval); + $event = \uv_timer_init($this->uv); + $this->timers->attach($timer, $event); + \uv_timer_start( + $event, + $interval, + (int) $interval === 0 ? 1 : $interval, + $callback + ); + + return $timer; + } + + /** + * {@inheritdoc} + */ + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timers[$timer])) { + @\uv_timer_stop($this->timers[$timer]); + $this->timers->detach($timer); + } + } + + /** + * {@inheritdoc} + */ + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = \uv_signal_init($this->uv); + \uv_signal_start($this->signalEvents[$signal], function () use ($signals, $signal) { + $signals->call($signal); + }, $signal); + } + } + + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \uv_signal_stop($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + + /** + * {@inheritdoc} + */ + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams + && !$this->writeStreams + && !$this->timers->count() + && $this->signals->isEmpty(); + + // Use UV::RUN_ONCE when there are only I/O events active in the loop and block until one of those triggers, + // otherwise use UV::RUN_NOWAIT. + // @link http://docs.libuv.org/en/v1.x/loop.html#c.uv_run + $flags = \UV::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags = \UV::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + + \uv_run($this->uv, $flags); + } + } + + /** + * {@inheritdoc} + */ + public function stop() + { + $this->running = false; + } + + private function addStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + $this->streamEvents[(int)$stream] = \uv_poll_init_socket($this->uv, $stream); + } + + if ($this->streamEvents[(int) $stream] !== false) { + $this->pollStream($stream); + } + } + + private function removeStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + if (!isset($this->readStreams[(int) $stream]) + && !isset($this->writeStreams[(int) $stream])) { + \uv_poll_stop($this->streamEvents[(int) $stream]); + \uv_close($this->streamEvents[(int) $stream]); + unset($this->streamEvents[(int) $stream]); + return; + } + + $this->pollStream($stream); + } + + private function pollStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + + $flags = 0; + if (isset($this->readStreams[(int) $stream])) { + $flags |= \UV::READABLE; + } + + if (isset($this->writeStreams[(int) $stream])) { + $flags |= \UV::WRITABLE; + } + + \uv_poll_start($this->streamEvents[(int) $stream], $flags, $this->streamListener); + } + + /** + * Create a stream listener + * + * @return callable Returns a callback + */ + private function createStreamListener() + { + $callback = function ($event, $status, $events, $stream) { + // libuv automatically stops polling on error, re-enable polling to match other loop implementations + if ($status !== 0) { + $this->pollStream($stream); + + // libuv may report no events on error, but this should still invoke stream listeners to report closed connections + // re-enable both readable and writable, correct listeners will be checked below anyway + if ($events === 0) { + $events = \UV::READABLE | \UV::WRITABLE; + } + } + + if (isset($this->readStreams[(int) $stream]) && ($events & \UV::READABLE)) { + \call_user_func($this->readStreams[(int) $stream], $stream); + } + + if (isset($this->writeStreams[(int) $stream]) && ($events & \UV::WRITABLE)) { + \call_user_func($this->writeStreams[(int) $stream], $stream); + } + }; + + return $callback; + } + + /** + * @param float $interval + * @return int + */ + private function convertFloatSecondsToMilliseconds($interval) + { + if ($interval < 0) { + return 0; + } + + $maxValue = (int) (\PHP_INT_MAX / 1000); + $intInterval = (int) $interval; + + if (($intInterval <= 0 && $interval > 1) || $intInterval >= $maxValue) { + throw new \InvalidArgumentException( + "Interval overflow, value must be lower than '{$maxValue}', but '{$interval}' passed." + ); + } + + return (int) \floor($interval * 1000); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Factory.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Factory.php new file mode 100644 index 0000000..30bbfd7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Factory.php @@ -0,0 +1,75 @@ +futureTick(function () use (&$hasRun) { + $hasRun = true; + }); + + $stopped =& self::$stopped; + register_shutdown_function(function () use ($loop, &$hasRun, &$stopped) { + // Don't run if we're coming from a fatal error (uncaught exception). + $error = error_get_last(); + if ((isset($error['type']) ? $error['type'] : 0) & (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR)) { + return; + } + + if (!$hasRun && !$stopped) { + $loop->run(); + } + }); + // @codeCoverageIgnoreEnd + + return self::$instance; + } + + /** + * Internal undocumented method, behavior might change or throw in the + * future. Use with caution and at your own risk. + * + * @internal + * @return void + */ + public static function set(LoopInterface $loop) + { + self::$instance = $loop; + } + + /** + * [Advanced] Register a listener to be notified when a stream is ready to read. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addReadStream() + */ + public static function addReadStream($stream, $listener) + { + self::get()->addReadStream($stream, $listener); + } + + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addWriteStream() + */ + public static function addWriteStream($stream, $listener) + { + self::get()->addWriteStream($stream, $listener); + } + + /** + * Remove the read event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeReadStream() + */ + public static function removeReadStream($stream) + { + self::get()->removeReadStream($stream); + } + + /** + * Remove the write event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeWriteStream() + */ + public static function removeWriteStream($stream) + { + self::get()->removeWriteStream($stream); + } + + /** + * Enqueue a callback to be invoked once after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addTimer() + */ + public static function addTimer($interval, $callback) + { + return self::get()->addTimer($interval, $callback); + } + + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addPeriodicTimer() + */ + public static function addPeriodicTimer($interval, $callback) + { + return self::get()->addPeriodicTimer($interval, $callback); + } + + /** + * Cancel a pending timer. + * + * @param TimerInterface $timer + * @return void + * @see LoopInterface::cancelTimer() + */ + public static function cancelTimer(TimerInterface $timer) + { + return self::get()->cancelTimer($timer); + } + + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * @param callable $listener + * @return void + * @see LoopInterface::futureTick() + */ + public static function futureTick($listener) + { + self::get()->futureTick($listener); + } + + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::addSignal() + */ + public static function addSignal($signal, $listener) + { + self::get()->addSignal($signal, $listener); + } + + /** + * Removes a previously added signal listener. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::removeSignal() + */ + public static function removeSignal($signal, $listener) + { + self::get()->removeSignal($signal, $listener); + } + + /** + * Run the event loop until there are no more tasks to perform. + * + * @return void + * @see LoopInterface::run() + */ + public static function run() + { + self::get()->run(); + } + + /** + * Instruct a running event loop to stop. + * + * @return void + * @see LoopInterface::stop() + */ + public static function stop() + { + self::$stopped = true; + self::get()->stop(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/LoopInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/LoopInterface.php new file mode 100644 index 0000000..8146757 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/LoopInterface.php @@ -0,0 +1,463 @@ +addReadStream($stream, function ($stream) use ($name) { + * echo $name . ' said: ' . fread($stream); + * }); + * ``` + * + * See also [example #11](examples). + * + * You can invoke [`removeReadStream()`](#removereadstream) to remove the + * read event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeReadStream() + */ + public function addReadStream($stream, $listener); + + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * Note that this low-level API is considered advanced usage. + * Most use cases should probably use the higher-level + * [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + * instead. + * + * The first parameter MUST be a valid stream resource that supports + * checking whether it is ready to write by this loop implementation. + * A single stream resource MUST NOT be added more than once. + * Instead, either call [`removeWriteStream()`](#removewritestream) first or + * react to this event with a single listener and then dispatch from this + * listener. This method MAY throw an `Exception` if the given resource type + * is not supported by this loop implementation. + * + * The listener callback function MUST be able to accept a single parameter, + * the stream resource added by this method or you MAY use a function which + * has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * $loop->addWriteStream($stream, function ($stream) use ($name) { + * fwrite($stream, 'Hello ' . $name); + * }); + * ``` + * + * See also [example #12](examples). + * + * You can invoke [`removeWriteStream()`](#removewritestream) to remove the + * write event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * Some event loop implementations are known to only trigger the listener if + * the stream *becomes* readable (edge-triggered) and may not trigger if the + * stream has already been readable from the beginning. + * This also implies that a stream may not be recognized as readable when data + * is still left in PHP's internal stream buffers. + * As such, it's recommended to use `stream_set_read_buffer($stream, 0);` + * to disable PHP's internal read buffer in this case. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeWriteStream() + */ + public function addWriteStream($stream, $listener); + + /** + * Remove the read event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeReadStream($stream); + + /** + * Remove the write event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeWriteStream($stream); + + /** + * Enqueue a callback to be invoked once after the given interval. + * + * The timer callback function MUST be able to accept a single parameter, + * the timer instance as also returned by this method or you MAY use a + * function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure + * the callback will be invoked only once after the given interval. + * You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. + * + * ```php + * $loop->addTimer(0.8, function () { + * echo 'world!' . PHP_EOL; + * }); + * + * $loop->addTimer(0.3, function () { + * echo 'hello '; + * }); + * ``` + * + * See also [example #1](examples). + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->addTimer(1.0, function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addTimer($interval, $callback); + + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * The timer callback function MUST be able to accept a single parameter, + * the timer instance as also returned by this method or you MAY use a + * function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * Unlike [`addTimer()`](#addtimer), this method will ensure the the + * callback will be invoked infinitely after the given interval or until you + * invoke [`cancelTimer`](#canceltimer). + * + * ```php + * $timer = $loop->addPeriodicTimer(0.1, function () { + * echo 'tick!' . PHP_EOL; + * }); + * + * $loop->addTimer(1.0, function () use ($loop, $timer) { + * $loop->cancelTimer($timer); + * echo 'Done' . PHP_EOL; + * }); + * ``` + * + * See also [example #2](examples). + * + * If you want to limit the number of executions, you can bind + * arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $n = 3; + * $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + * if ($n > 0) { + * --$n; + * echo "hello $name\n"; + * } else { + * $loop->cancelTimer($timer); + * } + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * Additionally, periodic timers may be subject to timer drift due to + * re-scheduling after each invocation. As such, it's generally not + * recommended to rely on this for high precision intervals with millisecond + * accuracy or below. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addPeriodicTimer($interval, $callback); + + /** + * Cancel a pending timer. + * + * See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + * + * Calling this method on a timer instance that has not been added to this + * loop instance or on a timer that has already been cancelled has no effect. + * + * @param TimerInterface $timer The timer to cancel. + * + * @return void + */ + public function cancelTimer(TimerInterface $timer); + + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * This works very much similar to timers with an interval of zero seconds, + * but does not require the overhead of scheduling a timer queue. + * + * The tick callback function MUST be able to accept zero parameters. + * + * The tick callback function MUST NOT throw an `Exception`. + * The return value of the tick callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->futureTick(function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * Unlike timers, tick callbacks are guaranteed to be executed in the order + * they are enqueued. + * Also, once a callback is enqueued, there's no way to cancel this operation. + * + * This is often used to break down bigger tasks into smaller steps (a form + * of cooperative multitasking). + * + * ```php + * $loop->futureTick(function () { + * echo 'b'; + * }); + * $loop->futureTick(function () { + * echo 'c'; + * }); + * echo 'a'; + * ``` + * + * See also [example #3](examples). + * + * @param callable $listener The callback to invoke. + * + * @return void + */ + public function futureTick($listener); + + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * This is useful to catch user interrupt signals or shutdown signals from + * tools like `supervisor` or `systemd`. + * + * The listener callback function MUST be able to accept a single parameter, + * the signal added by this method or you MAY use a function which + * has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * ```php + * $loop->addSignal(SIGINT, function (int $signal) { + * echo 'Caught user interrupt signal' . PHP_EOL; + * }); + * ``` + * + * See also [example #4](examples). + * + * Signaling is only available on Unix-like platform, Windows isn't + * supported due to operating system limitations. + * This method may throw a `BadMethodCallException` if signals aren't + * supported on this platform, for example when required extensions are + * missing. + * + * **Note: A listener can only be added once to the same signal, any + * attempts to add it more then once will be ignored.** + * + * @param int $signal + * @param callable $listener + * + * @throws \BadMethodCallException when signals aren't supported on this + * platform, for example when required extensions are missing. + * + * @return void + */ + public function addSignal($signal, $listener); + + /** + * Removes a previously added signal listener. + * + * ```php + * $loop->removeSignal(SIGINT, $listener); + * ``` + * + * Any attempts to remove listeners that aren't registered will be ignored. + * + * @param int $signal + * @param callable $listener + * + * @return void + */ + public function removeSignal($signal, $listener); + + /** + * Run the event loop until there are no more tasks to perform. + * + * For many applications, this method is the only directly visible + * invocation on the event loop. + * As a rule of thumb, it is usally recommended to attach everything to the + * same loop instance and then run the loop once at the bottom end of the + * application. + * + * ```php + * $loop->run(); + * ``` + * + * This method will keep the loop running until there are no more tasks + * to perform. In other words: This method will block until the last + * timer, stream and/or signal has been removed. + * + * Likewise, it is imperative to ensure the application actually invokes + * this method once. Adding listeners to the loop and missing to actually + * run it will result in the application exiting without actually waiting + * for any of the attached listeners. + * + * This method MUST NOT be called while the loop is already running. + * This method MAY be called more than once after it has explicity been + * [`stop()`ped](#stop) or after it automatically stopped because it + * previously did no longer have anything to do. + * + * @return void + */ + public function run(); + + /** + * Instruct a running event loop to stop. + * + * This method is considered advanced usage and should be used with care. + * As a rule of thumb, it is usually recommended to let the loop stop + * only automatically when it no longer has anything to do. + * + * This method can be used to explicitly instruct the event loop to stop: + * + * ```php + * $loop->addTimer(3.0, function () use ($loop) { + * $loop->stop(); + * }); + * ``` + * + * Calling this method on a loop instance that is not currently running or + * on a loop instance that has already been stopped has no effect. + * + * @return void + */ + public function stop(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/SignalsHandler.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/SignalsHandler.php new file mode 100644 index 0000000..10d125d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/SignalsHandler.php @@ -0,0 +1,63 @@ +signals[$signal])) { + $this->signals[$signal] = array(); + } + + if (\in_array($listener, $this->signals[$signal])) { + return; + } + + $this->signals[$signal][] = $listener; + } + + public function remove($signal, $listener) + { + if (!isset($this->signals[$signal])) { + return; + } + + $index = \array_search($listener, $this->signals[$signal], true); + unset($this->signals[$signal][$index]); + + if (isset($this->signals[$signal]) && \count($this->signals[$signal]) === 0) { + unset($this->signals[$signal]); + } + } + + public function call($signal) + { + if (!isset($this->signals[$signal])) { + return; + } + + foreach ($this->signals[$signal] as $listener) { + \call_user_func($listener, $signal); + } + } + + public function count($signal) + { + if (!isset($this->signals[$signal])) { + return 0; + } + + return \count($this->signals[$signal]); + } + + public function isEmpty() + { + return !$this->signals; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/StreamSelectLoop.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/StreamSelectLoop.php new file mode 100644 index 0000000..b89d800 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/StreamSelectLoop.php @@ -0,0 +1,308 @@ +futureTickQueue = new FutureTickQueue(); + $this->timers = new Timers(); + $this->pcntl = \function_exists('pcntl_signal') && \function_exists('pcntl_signal_dispatch'); + $this->pcntlPoll = $this->pcntl && !\function_exists('pcntl_async_signals'); + $this->signals = new SignalsHandler(); + + // prefer async signals if available (PHP 7.1+) or fall back to dispatching on each tick + if ($this->pcntl && !$this->pcntlPoll) { + \pcntl_async_signals(true); + } + } + + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + + if (!isset($this->readStreams[$key])) { + $this->readStreams[$key] = $stream; + $this->readListeners[$key] = $listener; + } + } + + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + + if (!isset($this->writeStreams[$key])) { + $this->writeStreams[$key] = $stream; + $this->writeListeners[$key] = $listener; + } + } + + public function removeReadStream($stream) + { + $key = (int) $stream; + + unset( + $this->readStreams[$key], + $this->readListeners[$key] + ); + } + + public function removeWriteStream($stream) + { + $key = (int) $stream; + + unset( + $this->writeStreams[$key], + $this->writeListeners[$key] + ); + } + + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, false); + + $this->timers->add($timer); + + return $timer; + } + + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, true); + + $this->timers->add($timer); + + return $timer; + } + + public function cancelTimer(TimerInterface $timer) + { + $this->timers->cancel($timer); + } + + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + + public function addSignal($signal, $listener) + { + if ($this->pcntl === false) { + throw new \BadMethodCallException('Event loop feature "signals" isn\'t supported by the "StreamSelectLoop"'); + } + + $first = $this->signals->count($signal) === 0; + $this->signals->add($signal, $listener); + + if ($first) { + \pcntl_signal($signal, array($this->signals, 'call')); + } + } + + public function removeSignal($signal, $listener) + { + if (!$this->signals->count($signal)) { + return; + } + + $this->signals->remove($signal, $listener); + + if ($this->signals->count($signal) === 0) { + \pcntl_signal($signal, \SIG_DFL); + } + } + + public function run() + { + $this->running = true; + + while ($this->running) { + $this->futureTickQueue->tick(); + + $this->timers->tick(); + + // Future-tick queue has pending callbacks ... + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $timeout = 0; + + // There is a pending timer, only block until it is due ... + } elseif ($scheduledAt = $this->timers->getFirst()) { + $timeout = $scheduledAt - $this->timers->getTime(); + if ($timeout < 0) { + $timeout = 0; + } else { + // Convert float seconds to int microseconds. + // Ensure we do not exceed maximum integer size, which may + // cause the loop to tick once every ~35min on 32bit systems. + $timeout *= self::MICROSECONDS_PER_SECOND; + $timeout = $timeout > \PHP_INT_MAX ? \PHP_INT_MAX : (int)$timeout; + } + + // The only possible event is stream or signal activity, so wait forever ... + } elseif ($this->readStreams || $this->writeStreams || !$this->signals->isEmpty()) { + $timeout = null; + + // There's nothing left to do ... + } else { + break; + } + + $this->waitForStreamActivity($timeout); + } + } + + public function stop() + { + $this->running = false; + } + + /** + * Wait/check for stream activity, or until the next timer is due. + * + * @param integer|null $timeout Activity timeout in microseconds, or null to wait forever. + */ + private function waitForStreamActivity($timeout) + { + $read = $this->readStreams; + $write = $this->writeStreams; + + $available = $this->streamSelect($read, $write, $timeout); + if ($this->pcntlPoll) { + \pcntl_signal_dispatch(); + } + if (false === $available) { + // if a system call has been interrupted, + // we cannot rely on it's outcome + return; + } + + foreach ($read as $stream) { + $key = (int) $stream; + + if (isset($this->readListeners[$key])) { + \call_user_func($this->readListeners[$key], $stream); + } + } + + foreach ($write as $stream) { + $key = (int) $stream; + + if (isset($this->writeListeners[$key])) { + \call_user_func($this->writeListeners[$key], $stream); + } + } + } + + /** + * Emulate a stream_select() implementation that does not break when passed + * empty stream arrays. + * + * @param array $read An array of read streams to select upon. + * @param array $write An array of write streams to select upon. + * @param int|null $timeout Activity timeout in microseconds, or null to wait forever. + * + * @return int|false The total number of streams that are ready for read/write. + * Can return false if stream_select() is interrupted by a signal. + */ + private function streamSelect(array &$read, array &$write, $timeout) + { + if ($read || $write) { + // We do not usually use or expose the `exceptfds` parameter passed to the underlying `select`. + // However, Windows does not report failed connection attempts in `writefds` passed to `select` like most other platforms. + // Instead, it uses `writefds` only for successful connection attempts and `exceptfds` for failed connection attempts. + // We work around this by adding all sockets that look like a pending connection attempt to `exceptfds` automatically on Windows and merge it back later. + // This ensures the public API matches other loop implementations across all platforms (see also test suite or rather test matrix). + // Lacking better APIs, every write-only socket that has not yet read any data is assumed to be in a pending connection attempt state. + // @link https://docs.microsoft.com/de-de/windows/win32/api/winsock2/nf-winsock2-select + $except = null; + if (\DIRECTORY_SEPARATOR === '\\') { + $except = array(); + foreach ($write as $key => $socket) { + if (!isset($read[$key]) && @\ftell($socket) === 0) { + $except[$key] = $socket; + } + } + } + + // suppress warnings that occur, when stream_select is interrupted by a signal + $ret = @\stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout); + + if ($except) { + $write = \array_merge($write, $except); + } + return $ret; + } + + if ($timeout > 0) { + \usleep($timeout); + } elseif ($timeout === null) { + // wait forever (we only reach this if we're only awaiting signals) + // this may be interrupted and return earlier when a signal is received + \sleep(PHP_INT_MAX); + } + + return 0; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Tick/FutureTickQueue.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Tick/FutureTickQueue.php new file mode 100644 index 0000000..efabcbc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Tick/FutureTickQueue.php @@ -0,0 +1,60 @@ +queue = new SplQueue(); + } + + /** + * Add a callback to be invoked on a future tick of the event loop. + * + * Callbacks are guaranteed to be executed in the order they are enqueued. + * + * @param callable $listener The callback to invoke. + */ + public function add($listener) + { + $this->queue->enqueue($listener); + } + + /** + * Flush the callback queue. + */ + public function tick() + { + // Only invoke as many callbacks as were on the queue when tick() was called. + $count = $this->queue->count(); + + while ($count--) { + \call_user_func( + $this->queue->dequeue() + ); + } + } + + /** + * Check if the next tick queue is empty. + * + * @return boolean + */ + public function isEmpty() + { + return $this->queue->isEmpty(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timer.php new file mode 100644 index 0000000..da3602a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timer.php @@ -0,0 +1,55 @@ +interval = (float) $interval; + $this->callback = $callback; + $this->periodic = (bool) $periodic; + } + + public function getInterval() + { + return $this->interval; + } + + public function getCallback() + { + return $this->callback; + } + + public function isPeriodic() + { + return $this->periodic; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timers.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timers.php new file mode 100644 index 0000000..70adc13 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/Timer/Timers.php @@ -0,0 +1,107 @@ +useHighResolution = \function_exists('hrtime'); + } + + public function updateTime() + { + return $this->time = $this->useHighResolution ? \hrtime(true) * 1e-9 : \microtime(true); + } + + public function getTime() + { + return $this->time ?: $this->updateTime(); + } + + public function add(TimerInterface $timer) + { + $id = \spl_object_hash($timer); + $this->timers[$id] = $timer; + $this->schedule[$id] = $timer->getInterval() + $this->updateTime(); + $this->sorted = false; + } + + public function contains(TimerInterface $timer) + { + return isset($this->timers[\spl_object_hash($timer)]); + } + + public function cancel(TimerInterface $timer) + { + $id = \spl_object_hash($timer); + unset($this->timers[$id], $this->schedule[$id]); + } + + public function getFirst() + { + // ensure timers are sorted to simply accessing next (first) one + if (!$this->sorted) { + $this->sorted = true; + \asort($this->schedule); + } + + return \reset($this->schedule); + } + + public function isEmpty() + { + return \count($this->timers) === 0; + } + + public function tick() + { + // ensure timers are sorted so we can execute in order + if (!$this->sorted) { + $this->sorted = true; + \asort($this->schedule); + } + + $time = $this->updateTime(); + + foreach ($this->schedule as $id => $scheduled) { + // schedule is ordered, so loop until first timer that is not scheduled for execution now + if ($scheduled >= $time) { + break; + } + + // skip any timers that are removed while we process the current schedule + if (!isset($this->schedule[$id]) || $this->schedule[$id] !== $scheduled) { + continue; + } + + $timer = $this->timers[$id]; + \call_user_func($timer->getCallback(), $timer); + + // re-schedule if this is a periodic timer and it has not been cancelled explicitly already + if ($timer->isPeriodic() && isset($this->timers[$id])) { + $this->schedule[$id] = $timer->getInterval() + $time; + $this->sorted = false; + } else { + unset($this->timers[$id], $this->schedule[$id]); + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/TimerInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/TimerInterface.php new file mode 100644 index 0000000..cdcf773 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/event-loop/src/TimerInterface.php @@ -0,0 +1,27 @@ +listen(new React\Socket\Server(8080)); + + // new + $http = new React\Http\HttpServer($handler); + $http->listen(new React\Socket\SocketServer('127.0.0.1:8080')); + ``` + +## 1.4.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#410 by @clue) + + ```php + // old (still supported) + $browser = new React\Http\Browser($loop); + $server = new React\Http\Server($loop, $handler); + + // new (using default loop) + $browser = new React\Http\Browser(); + $server = new React\Http\Server($handler); + ``` + +## 1.3.0 (2021-04-11) + +* Feature: Support persistent connections (`Connection: keep-alive`). + (#405 by @clue) + + This shows a noticeable performance improvement especially when benchmarking + using persistent connections (which is the default pretty much everywhere). + Together with other changes in this release, this improves benchmarking + performance by around 100%. + +* Feature: Require `Host` request header for HTTP/1.1 requests. + (#404 by @clue) + +* Minor documentation improvements. + (#398 by @fritz-gerneth and #399 and #400 by @pavog) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#402 by @SimonFrings) + +## 1.2.0 (2020-12-04) + +* Feature: Keep request body in memory also after consuming request body. + (#395 by @clue) + + This means consumers can now always access the complete request body as + detailed in the documentation. This allows building custom parsers and more + advanced processing models without having to mess with the default parsers. + +## 1.1.0 (2020-09-11) + +* Feature: Support upcoming PHP 8 release, update to reactphp/socket v1.6 and adjust type checks for invalid chunk headers. + (#391 by @clue) + +* Feature: Consistently resolve base URL according to HTTP specs. + (#379 by @clue) + +* Feature / Fix: Expose `Transfer-Encoding: chunked` response header and fix chunked responses for `HEAD` requests. + (#381 by @clue) + +* Internal refactoring to remove unneeded `MessageFactory` and `Response` classes. + (#380 and #389 by @clue) + +* Minor documentation improvements and improve test suite, update to support PHPUnit 9.3. + (#385 by @clue and #393 by @SimonFrings) + +## 1.0.0 (2020-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2020/announcing-reactphp-http). + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +This update involves some major new features and a number of BC breaks due to +some necessary API cleanup. We've tried hard to avoid BC breaks where possible +and minimize impact otherwise. We expect that most consumers of this package +will be affected by BC breaks, but updating should take no longer than a few +minutes. See below for more details: + +* Feature: Add async HTTP client implementation. + (#368 by @clue) + + ```php + $browser = new React\Http\Browser($loop); + $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + echo $response->getBody(); + }); + ``` + + The code has been imported as-is from [clue/reactphp-buzz v2.9.0](https://github.com/clue/reactphp-buzz), + with only minor changes to the namespace and we otherwise leave all the existing APIs unchanged. + Upgrading from [clue/reactphp-buzz v2.9.0](https://github.com/clue/reactphp-buzz) + to this release should be a matter of updating some namespace references only: + + ```php + // old + $browser = new Clue\React\Buzz\Browser($loop); + + // new + $browser = new React\Http\Browser($loop); + ``` + +* Feature / BC break: Add `LoopInterface` as required first constructor argument to `Server` and + change `Server` to accept variadic middleware handlers instead of `array`. + (#361 and #362 by @WyriHaximus) + + ```php + // old + $server = new React\Http\Server($handler); + $server = new React\Http\Server([$middleware, $handler]); + + // new + $server = new React\Http\Server($loop, $handler); + $server = new React\Http\Server($loop, $middleware, $handler); + ``` + +* Feature / BC break: Move `Response` class to `React\Http\Message\Response` and + expose `ServerRequest` class to `React\Http\Message\ServerRequest`. + (#370 by @clue) + + ```php + // old + $response = new React\Http\Response(200, [], 'Hello!'); + + // new + $response = new React\Http\Message\Response(200, [], 'Hello!'); + ``` + +* Feature / BC break: Add `StreamingRequestMiddleware` to stream incoming requests, mark `StreamingServer` as internal. + (#367 by @clue) + + ```php + // old: advanced StreamingServer is now internal only + $server = new React\Http\StreamingServer($handler); + + // new: use StreamingRequestMiddleware instead of StreamingServer + $server = new React\Http\Server( + $loop, + new React\Http\Middleware\StreamingRequestMiddleware(), + $handler + ); + ``` + +* Feature / BC break: Improve default concurrency to 1024 requests and cap default request buffer at 64K. + (#371 by @clue) + + This improves default concurrency to 1024 requests and caps the default request buffer at 64K. + The previous defaults resulted in just 4 concurrent requests with a request buffer of 8M. + See [`Server`](README.md#server) for details on how to override these defaults. + +* Feature: Expose ReactPHP in `User-Agent` client-side request header and in `Server` server-side response header. + (#374 by @clue) + +* Mark all classes as `final` to discourage inheriting from it. + (#373 by @WyriHaximus) + +* Improve documentation and use fully-qualified class names throughout the documentation and + add ReactPHP core team as authors to `composer.json` and license file. + (#366 and #369 by @WyriHaximus and #375 by @clue) + +* Improve test suite and support skipping all online tests with `--exclude-group internet`. + (#372 by @clue) + +## 0.8.7 (2020-07-05) + +* Fix: Fix parsing multipart request body with quoted header parameters (dot net). + (#363 by @ebimmel) + +* Fix: Fix calculating concurrency when `post_max_size` ini is unlimited. + (#365 by @clue) + +* Improve test suite to run tests on PHPUnit 9 and clean up test suite. + (#364 by @SimonFrings) + +## 0.8.6 (2020-01-12) + +* Fix: Fix parsing `Cookie` request header with comma in its values. + (#352 by @fiskie) + +* Fix: Avoid unneeded warning when decoding invalid data on PHP 7.4. + (#357 by @WyriHaximus) + +* Add .gitattributes to exclude dev files from exports. + (#353 by @reedy) + +## 0.8.5 (2019-10-29) + +* Internal refactorings and optimizations to improve request parsing performance. + Benchmarks suggest number of requests/s improved by ~30% for common `GET` requests. + (#345, #346, #349 and #350 by @clue) + +* Add documentation and example for JSON/XML request body and + improve documentation for concurrency and streaming requests and for error handling. + (#341 and #342 by @clue) + +## 0.8.4 (2019-01-16) + +* Improvement: Internal refactoring to simplify response header logic. + (#321 by @clue) + +* Improvement: Assign Content-Length response header automatically only when size is known. + (#329 by @clue) + +* Improvement: Import global functions for better performance. + (#330 by @WyriHaximus) + +## 0.8.3 (2018-04-11) + +* Feature: Do not pause connection stream to detect closed connections immediately. + (#315 by @clue) + +* Feature: Keep incoming `Transfer-Encoding: chunked` request header. + (#316 by @clue) + +* Feature: Reject invalid requests that contain both `Content-Length` and `Transfer-Encoding` request headers. + (#318 by @clue) + +* Minor internal refactoring to simplify connection close logic after sending response. + (#317 by @clue) + +## 0.8.2 (2018-04-06) + +* Fix: Do not pass `$next` handler to final request handler. + (#308 by @clue) + +* Fix: Fix awaiting queued handlers when cancelling a queued handler. + (#313 by @clue) + +* Fix: Fix Server to skip `SERVER_ADDR` params for Unix domain sockets (UDS). + (#307 by @clue) + +* Documentation for PSR-15 middleware and minor documentation improvements. + (#314 by @clue and #297, #298 and #310 by @seregazhuk) + +* Minor code improvements and micro optimizations. + (#301 by @seregazhuk and #305 by @kalessil) + +## 0.8.1 (2018-01-05) + +* Major request handler performance improvement. Benchmarks suggest number of + requests/s improved by more than 50% for common `GET` requests! + We now avoid queuing, buffering and wrapping incoming requests in promises + when we're below limits and instead can directly process common requests. + (#291, #292, #293, #294 and #296 by @clue) + +* Fix: Fix concurrent invoking next middleware request handlers + (#293 by @clue) + +* Small code improvements + (#286 by @seregazhuk) + +* Improve test suite to be less fragile when using `ext-event` and + fix test suite forward compatibility with upcoming EventLoop releases + (#288 and #290 by @clue) + +## 0.8.0 (2017-12-12) + +* Feature / BC break: Add new `Server` facade that buffers and parses incoming + HTTP requests. This provides full PSR-7 compatibility, including support for + form submissions with POST fields and file uploads. + The old `Server` has been renamed to `StreamingServer` for advanced usage + and is used internally. + (#266, #271, #281, #282, #283 and #284 by @WyriHaximus and @clue) + + ```php + // old: handle incomplete/streaming requests + $server = new Server($handler); + + // new: handle complete, buffered and parsed requests + // new: full PSR-7 support, including POST fields and file uploads + $server = new Server($handler); + + // new: handle incomplete/streaming requests + $server = new StreamingServer($handler); + ``` + + > While this is technically a small BC break, this should in fact not break + most consuming code. If you rely on the old request streaming, you can + explicitly use the advanced `StreamingServer` to restore old behavior. + +* Feature: Add support for middleware request handler arrays + (#215, #228, #229, #236, #237, #238, #246, #247, #277, #279 and #285 by @WyriHaximus, @clue and @jsor) + + ```php + // new: middleware request handler arrays + $server = new Server(array( + function (ServerRequestInterface $request, callable $next) { + $request = $request->withHeader('Processed', time()); + return $next($request); + }, + function (ServerRequestInterface $request) { + return new Response(); + } + )); + ``` + +* Feature: Add support for limiting how many next request handlers can be + executed concurrently (`LimitConcurrentRequestsMiddleware`) + (#272 by @clue and @WyriHaximus) + + ```php + // new: explicitly limit concurrency + $server = new Server(array( + new LimitConcurrentRequestsMiddleware(10), + $handler + )); + ``` + +* Feature: Add support for buffering the incoming request body + (`RequestBodyBufferMiddleware`). + This feature mimics PHP's default behavior and respects its `post_max_size` + ini setting by default and allows explicit configuration. + (#216, #224, #263, #276 and #278 by @WyriHaximus and #235 by @andig) + + ```php + // new: buffer up to 10 requests with 8 MiB each + $server = new StreamingServer(array( + new LimitConcurrentRequestsMiddleware(10), + new RequestBodyBufferMiddleware('8M'), + $handler + )); + ``` + +* Feature: Add support for parsing form submissions with POST fields and file + uploads (`RequestBodyParserMiddleware`). + This feature mimics PHP's default behavior and respects its ini settings and + `MAX_FILE_SIZE` POST fields by default and allows explicit configuration. + (#220, #226, #252, #261, #264, #265, #267, #268, #274 by @WyriHaximus and @clue) + + ```php + // new: buffer up to 10 requests with 8 MiB each + // and limit to 4 uploads with 2 MiB each + $server = new StreamingServer(array( + new LimitConcurrentRequestsMiddleware(10), + new RequestBodyBufferMiddleware('8M'), + new RequestBodyParserMiddleware('2M', 4) + $handler + )); + ``` + +* Feature: Update Socket to work around sending secure HTTPS responses with PHP < 7.1.4 + (#244 by @clue) + +* Feature: Support sending same response header multiple times (e.g. `Set-Cookie`) + (#248 by @clue) + +* Feature: Raise maximum request header size to 8k to match common implementations + (#253 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6, test + against PHP 7.1 and PHP 7.2 and refactor and remove risky and duplicate tests. + (#243, #269 and #270 by @carusogabriel and #249 by @clue) + +* Minor code refactoring to move internal classes to `React\Http\Io` namespace + and clean up minor code and documentation issues + (#251 by @clue, #227 by @kalessil, #240 by @christoph-kluge, #230 by @jsor and #280 by @andig) + +## 0.7.4 (2017-08-16) + +* Improvement: Target evenement 3.0 a long side 2.0 and 1.0 + (#212 by @WyriHaximus) + +## 0.7.3 (2017-08-14) + +* Feature: Support `Throwable` when setting previous exception from server callback + (#155 by @jsor) + +* Fix: Fixed URI parsing for origin-form requests that contain scheme separator + such as `/path?param=http://example.com`. + (#209 by @aaronbonneau) + +* Improve test suite by locking Travis distro so new defaults will not break the build + (#211 by @clue) + +## 0.7.2 (2017-07-04) + +* Fix: Stricter check for invalid request-line in HTTP requests + (#206 by @clue) + +* Refactor to use HTTP response reason phrases from response object + (#205 by @clue) + +## 0.7.1 (2017-06-17) + +* Fix: Fix parsing CONNECT request without `Host` header + (#201 by @clue) + +* Internal preparation for future PSR-7 `UploadedFileInterface` + (#199 by @WyriHaximus) + +## 0.7.0 (2017-05-29) + +* Feature / BC break: Use PSR-7 (http-message) standard and + `Request-In-Response-Out`-style request handler callback. + Pass standard PSR-7 `ServerRequestInterface` and expect any standard + PSR-7 `ResponseInterface` in return for the request handler callback. + (#146 and #152 and #170 by @legionth) + + ```php + // old + $app = function (Request $request, Response $response) { + $response->writeHead(200, array('Content-Type' => 'text/plain')); + $response->end("Hello world!\n"); + }; + + // new + $app = function (ServerRequestInterface $request) { + return new Response( + 200, + array('Content-Type' => 'text/plain'), + "Hello world!\n" + ); + }; + ``` + + A `Content-Length` header will automatically be included if the size can be + determined from the response body. + (#164 by @maciejmrozinski) + + The request handler callback will automatically make sure that responses to + HEAD requests and certain status codes, such as `204` (No Content), never + contain a response body. + (#156 by @clue) + + The intermediary `100 Continue` response will automatically be sent if + demanded by a HTTP/1.1 client. + (#144 by @legionth) + + The request handler callback can now return a standard `Promise` if + processing the request needs some time, such as when querying a database. + Similarly, the request handler may return a streaming response if the + response body comes from a `ReadableStreamInterface` or its size is + unknown in advance. + + ```php + // old + $app = function (Request $request, Response $response) use ($db) { + $db->query()->then(function ($result) use ($response) { + $response->writeHead(200, array('Content-Type' => 'text/plain')); + $response->end($result); + }); + }; + + // new + $app = function (ServerRequestInterface $request) use ($db) { + return $db->query()->then(function ($result) { + return new Response( + 200, + array('Content-Type' => 'text/plain'), + $result + ); + }); + }; + ``` + + Pending promies and response streams will automatically be canceled once the + client connection closes. + (#187 and #188 by @clue) + + The `ServerRequestInterface` contains the full effective request URI, + server-side parameters, query parameters and parsed cookies values as + defined in PSR-7. + (#167 by @clue and #174, #175 and #180 by @legionth) + + ```php + $app = function (ServerRequestInterface $request) { + return new Response( + 200, + array('Content-Type' => 'text/plain'), + $request->getUri()->getScheme() + ); + }; + ``` + + Advanced: Support duplex stream response for `Upgrade` requests such as + `Upgrade: WebSocket` or custom protocols and `CONNECT` requests + (#189 and #190 by @clue) + + > Note that the request body will currently not be buffered and parsed by + default, which depending on your particilar use-case, may limit + interoperability with the PSR-7 (http-message) ecosystem. + The provided streaming request body interfaces allow you to perform + buffering and parsing as needed in the request handler callback. + See also the README and examples for more details. + +* Feature / BC break: Replace `request` listener with callback function and + use `listen()` method to support multiple listening sockets + (#97 by @legionth and #193 by @clue) + + ```php + // old + $server = new Server($socket); + $server->on('request', $app); + + // new + $server = new Server($app); + $server->listen($socket); + ``` + +* Feature: Support the more advanced HTTP requests, such as + `OPTIONS * HTTP/1.1` (`OPTIONS` method in asterisk-form), + `GET http://example.com/path HTTP/1.1` (plain proxy requests in absolute-form), + `CONNECT example.com:443 HTTP/1.1` (`CONNECT` proxy requests in authority-form) + and sanitize `Host` header value across all requests. + (#157, #158, #161, #165, #169 and #173 by @clue) + +* Feature: Forward compatibility with Socket v1.0, v0.8, v0.7 and v0.6 and + forward compatibility with Stream v1.0 and v0.7 + (#154, #163, #183, #184 and #191 by @clue) + +* Feature: Simplify examples to ease getting started and + add benchmarking example + (#151 and #162 by @clue) + +* Improve test suite by adding tests for case insensitive chunked transfer + encoding and ignoring HHVM test failures until Travis tests work again. + (#150 by @legionth and #185 by @clue) + +## 0.6.0 (2017-03-09) + +* Feature / BC break: The `Request` and `Response` objects now follow strict + stream semantics and their respective methods and events. + (#116, #129, #133, #135, #136, #137, #138, #140, #141 by @legionth + and #122, #123, #130, #131, #132, #142 by @clue) + + This implies that the `Server` now supports proper detection of the request + message body stream, such as supporting decoding chunked transfer encoding, + delimiting requests with an explicit `Content-Length` header + and those with an empty request message body. + + These streaming semantics are compatible with previous Stream v0.5, future + compatible with v0.5 and upcoming v0.6 versions and can be used like this: + + ```php + $http->on('request', function (Request $request, Response $response) { + $contentLength = 0; + $request->on('data', function ($data) use (&$contentLength) { + $contentLength += strlen($data); + }); + + $request->on('end', function () use ($response, &$contentLength){ + $response->writeHead(200, array('Content-Type' => 'text/plain')); + $response->end("The length of the submitted request body is: " . $contentLength); + }); + + // an error occured + // e.g. on invalid chunked encoded data or an unexpected 'end' event + $request->on('error', function (\Exception $exception) use ($response, &$contentLength) { + $response->writeHead(400, array('Content-Type' => 'text/plain')); + $response->end("An error occured while reading at length: " . $contentLength); + }); + }); + ``` + + Similarly, the `Request` and `Response` now strictly follow the + `close()` method and `close` event semantics. + Closing the `Request` does not interrupt the underlying TCP/IP in + order to allow still sending back a valid response message. + Closing the `Response` does terminate the underlying TCP/IP + connection in order to clean up resources. + + You should make sure to always attach a `request` event listener + like above. The `Server` will not respond to an incoming HTTP + request otherwise and keep the TCP/IP connection pending until the + other side chooses to close the connection. + +* Feature: Support `HTTP/1.1` and `HTTP/1.0` for `Request` and `Response`. + (#124, #125, #126, #127, #128 by @clue and #139 by @legionth) + + The outgoing `Response` will automatically use the same HTTP version as the + incoming `Request` message and will only apply `HTTP/1.1` semantics if + applicable. This includes that the `Response` will automatically attach a + `Date` and `Connection: close` header if applicable. + + This implies that the `Server` now automatically responds with HTTP error + messages for invalid requests (status 400) and those exceeding internal + request header limits (status 431). + +## 0.5.0 (2017-02-16) + +* Feature / BC break: Change `Request` methods to be in line with PSR-7 + (#117 by @clue) + * Rename `getQuery()` to `getQueryParams()` + * Rename `getHttpVersion()` to `getProtocolVersion()` + * Change `getHeaders()` to always return an array of string values + for each header + +* Feature / BC break: Update Socket component to v0.5 and + add secure HTTPS server support + (#90 and #119 by @clue) + + ```php + // old plaintext HTTP server + $socket = new React\Socket\Server($loop); + $socket->listen(8080, '127.0.0.1'); + $http = new React\Http\Server($socket); + + // new plaintext HTTP server + $socket = new React\Socket\Server('127.0.0.1:8080', $loop); + $http = new React\Http\Server($socket); + + // new secure HTTPS server + $socket = new React\Socket\Server('127.0.0.1:8080', $loop); + $socket = new React\Socket\SecureServer($socket, $loop, array( + 'local_cert' => __DIR__ . '/localhost.pem' + )); + $http = new React\Http\Server($socket); + ``` + +* BC break: Mark internal APIs as internal or private and + remove unneeded `ServerInterface` + (#118 by @clue, #95 by @legionth) + +## 0.4.4 (2017-02-13) + +* Feature: Add request header accessors (à la PSR-7) + (#103 by @clue) + + ```php + // get value of host header + $host = $request->getHeaderLine('Host'); + + // get list of all cookie headers + $cookies = $request->getHeader('Cookie'); + ``` + +* Feature: Forward `pause()` and `resume()` from `Request` to underlying connection + (#110 by @clue) + + ```php + // support back-pressure when piping request into slower destination + $request->pipe($dest); + + // manually pause/resume request + $request->pause(); + $request->resume(); + ``` + +* Fix: Fix `100-continue` to be handled case-insensitive and ignore it for HTTP/1.0. + Similarly, outgoing response headers are now handled case-insensitive, e.g + we no longer apply chunked transfer encoding with mixed-case `Content-Length`. + (#107 by @clue) + + ```php + // now handled case-insensitive + $request->expectsContinue(); + + // now works just like properly-cased header + $response->writeHead($status, array('content-length' => 0)); + ``` + +* Fix: Do not emit empty `data` events and ignore empty writes in order to + not mess up chunked transfer encoding + (#108 and #112 by @clue) + +* Lock and test minimum required dependency versions and support PHPUnit v5 + (#113, #115 and #114 by @andig) + +## 0.4.3 (2017-02-10) + +* Fix: Do not take start of body into account when checking maximum header size + (#88 by @nopolabs) + +* Fix: Remove `data` listener if `HeaderParser` emits an error + (#83 by @nick4fake) + +* First class support for PHP 5.3 through PHP 7 and HHVM + (#101 and #102 by @clue, #66 by @WyriHaximus) + +* Improve test suite by adding PHPUnit to require-dev, + improving forward compatibility with newer PHPUnit versions + and replacing unneeded test stubs + (#92 and #93 by @nopolabs, #100 by @legionth) + +## 0.4.2 (2016-11-09) + +* Remove all listeners after emitting error in RequestHeaderParser #68 @WyriHaximus +* Catch Guzzle parse request errors #65 @WyriHaximus +* Remove branch-alias definition as per reactphp/react#343 #58 @WyriHaximus +* Add functional example to ease getting started #64 by @clue +* Naming, immutable array manipulation #37 @cboden + +## 0.4.1 (2015-05-21) + +* Replaced guzzle/parser with guzzlehttp/psr7 by @cboden +* FIX Continue Header by @iannsp +* Missing type hint by @marenzo + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Bug fix: Emit end event when Response closes (@beaucollins) + +## 0.2.3 (2012-11-14) + +* Bug fix: Forward drain events from HTTP response (@cs278) +* Dependency: Updated guzzle deps to `3.0.*` + +## 0.2.2 (2012-10-28) + +* Version bump + +## 0.2.1 (2012-10-14) + +* Feature: Support HTTP 1.1 continue + +## 0.2.0 (2012-09-10) + +* Bump React dependencies to v0.2 + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/README.md new file mode 100644 index 0000000..63865d5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/README.md @@ -0,0 +1,2776 @@ +# HTTP + +[![CI status](https://github.com/reactphp/http/workflows/CI/badge.svg)](https://github.com/reactphp/http/actions) + +Event-driven, streaming HTTP client and server implementation for [ReactPHP](https://reactphp.org/). + +This HTTP library provides re-usable implementations for an HTTP client and +server based on ReactPHP's [`Socket`](https://github.com/reactphp/socket) and +[`EventLoop`](https://github.com/reactphp/event-loop) components. +Its client component allows you to send any number of async HTTP/HTTPS requests +concurrently. +Its server component allows you to build plaintext HTTP and secure HTTPS servers +that accept incoming HTTP requests from HTTP clients (such as web browsers). +This library provides async, streaming means for all of this, so you can handle +multiple concurrent HTTP requests without blocking. + +**Table of contents** + +* [Quickstart example](#quickstart-example) +* [Client Usage](#client-usage) + * [Request methods](#request-methods) + * [Promises](#promises) + * [Cancellation](#cancellation) + * [Timeouts](#timeouts) + * [Authentication](#authentication) + * [Redirects](#redirects) + * [Blocking](#blocking) + * [Concurrency](#concurrency) + * [Streaming response](#streaming-response) + * [Streaming request](#streaming-request) + * [HTTP proxy](#http-proxy) + * [SOCKS proxy](#socks-proxy) + * [SSH proxy](#ssh-proxy) + * [Unix domain sockets](#unix-domain-sockets) +* [Server Usage](#server-usage) + * [HttpServer](#httpserver) + * [listen()](#listen) + * [Server Request](#server-request) + * [Request parameters](#request-parameters) + * [Query parameters](#query-parameters) + * [Request body](#request-body) + * [Streaming incoming request](#streaming-incoming-request) + * [Request method](#request-method) + * [Cookie parameters](#cookie-parameters) + * [Invalid request](#invalid-request) + * [Server Response](#server-response) + * [Deferred response](#deferred-response) + * [Streaming outgoing response](#streaming-outgoing-response) + * [Response length](#response-length) + * [Invalid response](#invalid-response) + * [Default response headers](#default-response-headers) + * [Middleware](#middleware) + * [Custom middleware](#custom-middleware) + * [Third-Party Middleware](#third-party-middleware) +* [API](#api) + * [Browser](#browser) + * [get()](#get) + * [post()](#post) + * [head()](#head) + * [patch()](#patch) + * [put()](#put) + * [delete()](#delete) + * [request()](#request) + * [requestStreaming()](#requeststreaming) + * [withTimeout()](#withtimeout) + * [withFollowRedirects()](#withfollowredirects) + * [withRejectErrorResponse()](#withrejecterrorresponse) + * [withBase()](#withbase) + * [withProtocolVersion()](#withprotocolversion) + * [withResponseBuffer()](#withresponsebuffer) + * [React\Http\Message](#reacthttpmessage) + * [Response](#response) + * [ServerRequest](#serverrequest) + * [ResponseException](#responseexception) + * [React\Http\Middleware](#reacthttpmiddleware) + * [StreamingRequestMiddleware](#streamingrequestmiddleware) + * [LimitConcurrentRequestsMiddleware](#limitconcurrentrequestsmiddleware) + * [RequestBodyBufferMiddleware](#requestbodybuffermiddleware) + * [RequestBodyParserMiddleware](#requestbodyparsermiddleware) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +Once [installed](#install), you can use the following code to access a +HTTP webserver and send some simple HTTP GET requests: + +```php +$client = new React\Http\Browser(); + +$client->get('http://www.google.com/')->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump($response->getHeaders(), (string)$response->getBody()); +}); +``` + +This is an HTTP server which responds with `Hello World!` to every request. + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Hello World!\n" + ); +}); + +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); +$http->listen($socket); +``` + +See also the [examples](examples/). + +## Client Usage + +### Request methods + +Most importantly, this project provides a [`Browser`](#browser) object that +offers several methods that resemble the HTTP protocol methods: + +```php +$browser->get($url, array $headers = array()); +$browser->head($url, array $headers = array()); +$browser->post($url, array $headers = array(), string|ReadableStreamInterface $contents = ''); +$browser->delete($url, array $headers = array(), string|ReadableStreamInterface $contents = ''); +$browser->put($url, array $headers = array(), string|ReadableStreamInterface $contents = ''); +$browser->patch($url, array $headers = array(), string|ReadableStreamInterface $contents = ''); +``` + +Each of these methods requires a `$url` and some optional parameters to send an +HTTP request. Each of these method names matches the respective HTTP request +method, for example the [`get()`](#get) method sends an HTTP `GET` request. + +You can optionally pass an associative array of additional `$headers` that will be +sent with this HTTP request. Additionally, each method will automatically add a +matching `Content-Length` request header if an outgoing request body is given and its +size is known and non-empty. For an empty request body, if will only include a +`Content-Length: 0` request header if the request method usually expects a request +body (only applies to `POST`, `PUT` and `PATCH` HTTP request methods). + +If you're using a [streaming request body](#streaming-request), it will default +to using `Transfer-Encoding: chunked` unless you explicitly pass in a matching `Content-Length` +request header. See also [streaming request](#streaming-request) for more details. + +By default, all of the above methods default to sending requests using the +HTTP/1.1 protocol version. If you want to explicitly use the legacy HTTP/1.0 +protocol version, you can use the [`withProtocolVersion()`](#withprotocolversion) +method. If you want to use any other or even custom HTTP request method, you can +use the [`request()`](#request) method. + +Each of the above methods supports async operation and either *fulfills* with a +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +or *rejects* with an `Exception`. +Please see the following chapter about [promises](#promises) for more details. + +### Promises + +Sending requests is async (non-blocking), so you can actually send multiple +requests in parallel. +The `Browser` will respond to each request with a +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +message, the order is not guaranteed. +Sending requests uses a [Promise](https://github.com/reactphp/promise)-based +interface that makes it easy to react to when an HTTP request is completed +(i.e. either successfully fulfilled or rejected with an error): + +```php +$browser->get($url)->then( + function (Psr\Http\Message\ResponseInterface $response) { + var_dump('Response received', $response); + }, + function (Exception $error) { + var_dump('There was an error', $error->getMessage()); + } +); +``` + +If this looks strange to you, you can also use the more traditional [blocking API](#blocking). + +Keep in mind that resolving the Promise with the full response message means the +whole response body has to be kept in memory. +This is easy to get started and works reasonably well for smaller responses +(such as common HTML pages or RESTful or JSON API requests). + +You may also want to look into the [streaming API](#streaming-response): + +* If you're dealing with lots of concurrent requests (100+) or +* If you want to process individual data chunks as they happen (without having to wait for the full response body) or +* If you're expecting a big response body size (1 MiB or more, for example when downloading binary files) or +* If you're unsure about the response body size (better be safe than sorry when accessing arbitrary remote HTTP endpoints and the response body size is unknown in advance). + +### Cancellation + +The returned Promise is implemented in such a way that it can be cancelled +when it is still pending. +Cancelling a pending promise will reject its value with an Exception and +clean up any underlying resources. + +```php +$promise = $browser->get($url); + +Loop::addTimer(2.0, function () use ($promise) { + $promise->cancel(); +}); +``` + +### Timeouts + +This library uses a very efficient HTTP implementation, so most HTTP requests +should usually be completed in mere milliseconds. However, when sending HTTP +requests over an unreliable network (the internet), there are a number of things +that can go wrong and may cause the request to fail after a time. As such, this +library respects PHP's `default_socket_timeout` setting (default 60s) as a timeout +for sending the outgoing HTTP request and waiting for a successful response and +will otherwise cancel the pending request and reject its value with an Exception. + +Note that this timeout value covers creating the underlying transport connection, +sending the HTTP request, receiving the HTTP response headers and its full +response body and following any eventual [redirects](#redirects). See also +[redirects](#redirects) below to configure the number of redirects to follow (or +disable following redirects altogether) and also [streaming](#streaming-response) +below to not take receiving large response bodies into account for this timeout. + +You can use the [`withTimeout()` method](#withtimeout) to pass a custom timeout +value in seconds like this: + +```php +$browser = $browser->withTimeout(10.0); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // response received within 10 seconds maximum + var_dump($response->getHeaders()); +}); +``` + +Similarly, you can use a bool `false` to not apply a timeout at all +or use a bool `true` value to restore the default handling. +See [`withTimeout()`](#withtimeout) for more details. + +If you're using a [streaming response body](#streaming-response), the time it +takes to receive the response body stream will not be included in the timeout. +This allows you to keep this incoming stream open for a longer time, such as +when downloading a very large stream or when streaming data over a long-lived +connection. + +If you're using a [streaming request body](#streaming-request), the time it +takes to send the request body stream will not be included in the timeout. This +allows you to keep this outgoing stream open for a longer time, such as when +uploading a very large stream. + +Note that this timeout handling applies to the higher-level HTTP layer. Lower +layers such as socket and DNS may also apply (different) timeout values. In +particular, the underlying socket connection uses the same `default_socket_timeout` +setting to establish the underlying transport connection. To control this +connection timeout behavior, you can [inject a custom `Connector`](#browser) +like this: + +```php +$browser = new React\Http\Browser( + new React\Socket\Connector( + array( + 'timeout' => 5 + ) + ) +); +``` + +### Authentication + +This library supports [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) +using the `Authorization: Basic …` request header or allows you to set an explicit +`Authorization` request header. + +By default, this library does not include an outgoing `Authorization` request +header. If the server requires authentication, if may return a `401` (Unauthorized) +status code which will reject the request by default (see also the +[`withRejectErrorResponse()` method](#withrejecterrorresponse) below). + +In order to pass authentication details, you can simply pass the username and +password as part of the request URL like this: + +```php +$promise = $browser->get('https://user:pass@example.com/api'); +``` + +Note that special characters in the authentication details have to be +percent-encoded, see also [`rawurlencode()`](https://www.php.net/manual/en/function.rawurlencode.php). +This example will automatically pass the base64-encoded authentication details +using the outgoing `Authorization: Basic …` request header. If the HTTP endpoint +you're talking to requires any other authentication scheme, you can also pass +this header explicitly. This is common when using (RESTful) HTTP APIs that use +OAuth access tokens or JSON Web Tokens (JWT): + +```php +$token = 'abc123'; + +$promise = $browser->get( + 'https://example.com/api', + array( + 'Authorization' => 'Bearer ' . $token + ) +); +``` + +When following redirects, the `Authorization` request header will never be sent +to any remote hosts by default. When following a redirect where the `Location` +response header contains authentication details, these details will be sent for +following requests. See also [redirects](#redirects) below. + +### Redirects + +By default, this library follows any redirects and obeys `3xx` (Redirection) +status codes using the `Location` response header from the remote server. +The promise will be fulfilled with the last response from the chain of redirects. + +```php +$browser->get($url, $headers)->then(function (Psr\Http\Message\ResponseInterface $response) { + // the final response will end up here + var_dump($response->getHeaders()); +}); +``` + +Any redirected requests will follow the semantics of the original request and +will include the same request headers as the original request except for those +listed below. +If the original request contained a request body, this request body will never +be passed to the redirected request. Accordingly, each redirected request will +remove any `Content-Length` and `Content-Type` request headers. + +If the original request used HTTP authentication with an `Authorization` request +header, this request header will only be passed as part of the redirected +request if the redirected URL is using the same host. In other words, the +`Authorizaton` request header will not be forwarded to other foreign hosts due to +possible privacy/security concerns. When following a redirect where the `Location` +response header contains authentication details, these details will be sent for +following requests. + +You can use the [`withFollowRedirects()`](#withfollowredirects) method to +control the maximum number of redirects to follow or to return any redirect +responses as-is and apply custom redirection logic like this: + +```php +$browser = $browser->withFollowRedirects(false); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // any redirects will now end up here + var_dump($response->getHeaders()); +}); +``` + +See also [`withFollowRedirects()`](#withfollowredirects) for more details. + +### Blocking + +As stated above, this library provides you a powerful, async API by default. + +If, however, you want to integrate this into your traditional, blocking environment, +you should look into also using [clue/reactphp-block](https://github.com/clue/reactphp-block). + +The resulting blocking code could look something like this: + +```php +use Clue\React\Block; + +$browser = new React\Http\Browser(); + +$promise = $browser->get('http://example.com/'); + +try { + $response = Block\await($promise, Loop::get()); + // response successfully received +} catch (Exception $e) { + // an error occured while performing the request +} +``` + +Similarly, you can also process multiple requests concurrently and await an array of `Response` objects: + +```php +$promises = array( + $browser->get('http://example.com/'), + $browser->get('http://www.example.org/'), +); + +$responses = Block\awaitAll($promises, Loop::get()); +``` + +Please refer to [clue/reactphp-block](https://github.com/clue/reactphp-block#readme) for more details. + +Keep in mind the above remark about buffering the whole response message in memory. +As an alternative, you may also see one of the following chapters for the +[streaming API](#streaming-response). + +### Concurrency + +As stated above, this library provides you a powerful, async API. Being able to +send a large number of requests at once is one of the core features of this +project. For instance, you can easily send 100 requests concurrently while +processing SQL queries at the same time. + +Remember, with great power comes great responsibility. Sending an excessive +number of requests may either take up all resources on your side or it may even +get you banned by the remote side if it sees an unreasonable number of requests +from your side. + +```php +// watch out if array contains many elements +foreach ($urls as $url) { + $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump($response->getHeaders()); + }); +} +``` + +As a consequence, it's usually recommended to limit concurrency on the sending +side to a reasonable value. It's common to use a rather small limit, as doing +more than a dozen of things at once may easily overwhelm the receiving side. You +can use [clue/reactphp-mq](https://github.com/clue/reactphp-mq) as a lightweight +in-memory queue to concurrently do many (but not too many) things at once: + +```php +// wraps Browser in a Queue object that executes no more than 10 operations at once +$q = new Clue\React\Mq\Queue(10, null, function ($url) use ($browser) { + return $browser->get($url); +}); + +foreach ($urls as $url) { + $q($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump($response->getHeaders()); + }); +} +``` + +Additional requests that exceed the concurrency limit will automatically be +enqueued until one of the pending requests completes. This integrates nicely +with the existing [Promise-based API](#promises). Please refer to +[clue/reactphp-mq](https://github.com/clue/reactphp-mq) for more details. + +This in-memory approach works reasonably well for some thousand outstanding +requests. If you're processing a very large input list (think millions of rows +in a CSV or NDJSON file), you may want to look into using a streaming approach +instead. See [clue/reactphp-flux](https://github.com/clue/reactphp-flux) for +more details. + +### Streaming response + +All of the above examples assume you want to store the whole response body in memory. +This is easy to get started and works reasonably well for smaller responses. + +However, there are several situations where it's usually a better idea to use a +streaming approach, where only small chunks have to be kept in memory: + +* If you're dealing with lots of concurrent requests (100+) or +* If you want to process individual data chunks as they happen (without having to wait for the full response body) or +* If you're expecting a big response body size (1 MiB or more, for example when downloading binary files) or +* If you're unsure about the response body size (better be safe than sorry when accessing arbitrary remote HTTP endpoints and the response body size is unknown in advance). + +You can use the [`requestStreaming()`](#requeststreaming) method to send an +arbitrary HTTP request and receive a streaming response. It uses the same HTTP +message API, but does not buffer the response body in memory. It only processes +the response body in small chunks as data is received and forwards this data +through [ReactPHP's Stream API](https://github.com/reactphp/stream). This works +for (any number of) responses of arbitrary sizes. + +This means it resolves with a normal +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface), +which can be used to access the response message parameters as usual. +You can access the message body as usual, however it now also +implements [ReactPHP's `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +as well as parts of the [PSR-7 `StreamInterface`](https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface). + +```php +$browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + $body = $response->getBody(); + assert($body instanceof Psr\Http\Message\StreamInterface); + assert($body instanceof React\Stream\ReadableStreamInterface); + + $body->on('data', function ($chunk) { + echo $chunk; + }); + + $body->on('error', function (Exception $error) { + echo 'Error: ' . $error->getMessage() . PHP_EOL; + }); + + $body->on('close', function () { + echo '[DONE]' . PHP_EOL; + }); +}); +``` + +See also the [stream download benchmark example](examples/91-client-benchmark-download.php) and +the [stream forwarding example](examples/21-client-request-streaming-to-stdout.php). + +You can invoke the following methods on the message body: + +```php +$body->on($event, $callback); +$body->eof(); +$body->isReadable(); +$body->pipe(React\Stream\WritableStreamInterface $dest, array $options = array()); +$body->close(); +$body->pause(); +$body->resume(); +``` + +Because the message body is in a streaming state, invoking the following methods +doesn't make much sense: + +```php +$body->__toString(); // '' +$body->detach(); // throws BadMethodCallException +$body->getSize(); // null +$body->tell(); // throws BadMethodCallException +$body->isSeekable(); // false +$body->seek(); // throws BadMethodCallException +$body->rewind(); // throws BadMethodCallException +$body->isWritable(); // false +$body->write(); // throws BadMethodCallException +$body->read(); // throws BadMethodCallException +$body->getContents(); // throws BadMethodCallException +``` + +Note how [timeouts](#timeouts) apply slightly differently when using streaming. +In streaming mode, the timeout value covers creating the underlying transport +connection, sending the HTTP request, receiving the HTTP response headers and +following any eventual [redirects](#redirects). In particular, the timeout value +does not take receiving (possibly large) response bodies into account. + +If you want to integrate the streaming response into a higher level API, then +working with Promise objects that resolve with Stream objects is often inconvenient. +Consider looking into also using [react/promise-stream](https://github.com/reactphp/promise-stream). +The resulting streaming code could look something like this: + +```php +use React\Promise\Stream; + +function download(Browser $browser, string $url): React\Stream\ReadableStreamInterface { + return Stream\unwrapReadable( + $browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + return $response->getBody(); + }) + ); +} + +$stream = download($browser, $url); +$stream->on('data', function ($data) { + echo $data; +}); +``` + +See also the [`requestStreaming()`](#requeststreaming) method for more details. + +### Streaming request + +Besides streaming the response body, you can also stream the request body. +This can be useful if you want to send big POST requests (uploading files etc.) +or process many outgoing streams at once. +Instead of passing the body as a string, you can simply pass an instance +implementing [ReactPHP's `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +to the [request methods](#request-methods) like this: + +```php +$browser->post($url, array(), $stream)->then(function (Psr\Http\Message\ResponseInterface $response) { + echo 'Successfully sent.'; +}); +``` + +If you're using a streaming request body (`React\Stream\ReadableStreamInterface`), it will +default to using `Transfer-Encoding: chunked` or you have to explicitly pass in a +matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->post($url, array('Content-Length' => '11'), $body); +``` + +If the streaming request body emits an `error` event or is explicitly closed +without emitting a successful `end` event first, the request will automatically +be closed and rejected. + +### HTTP proxy + +You can also establish your outgoing connections through an HTTP CONNECT proxy server +by adding a dependency to [clue/reactphp-http-proxy](https://github.com/clue/reactphp-http-proxy). + +HTTP CONNECT proxy servers (also commonly known as "HTTPS proxy" or "SSL proxy") +are commonly used to tunnel HTTPS traffic through an intermediary ("proxy"), to +conceal the origin address (anonymity) or to circumvent address blocking +(geoblocking). While many (public) HTTP CONNECT proxy servers often limit this +to HTTPS port`443` only, this can technically be used to tunnel any TCP/IP-based +protocol, such as plain HTTP and TLS-encrypted HTTPS. + +```php +$proxy = new Clue\React\HttpProxy\ProxyConnector( + 'http://127.0.0.1:8080', + new React\Socket\Connector() +); + +$connector = new React\Socket\Connector(array( + 'tcp' => $proxy, + 'dns' => false +)); + +$browser = new React\Http\Browser($connector); +``` + +See also the [HTTP CONNECT proxy example](examples/11-client-http-connect-proxy.php). + +### SOCKS proxy + +You can also establish your outgoing connections through a SOCKS proxy server +by adding a dependency to [clue/reactphp-socks](https://github.com/clue/reactphp-socks). + +The SOCKS proxy protocol family (SOCKS5, SOCKS4 and SOCKS4a) is commonly used to +tunnel HTTP(S) traffic through an intermediary ("proxy"), to conceal the origin +address (anonymity) or to circumvent address blocking (geoblocking). While many +(public) SOCKS proxy servers often limit this to HTTP(S) port `80` and `443` +only, this can technically be used to tunnel any TCP/IP-based protocol. + +```php +$proxy = new Clue\React\Socks\Client( + 'socks://127.0.0.1:1080', + new React\Socket\Connector() +); + +$connector = new React\Socket\Connector(array( + 'tcp' => $proxy, + 'dns' => false +)); + +$browser = new React\Http\Browser($connector); +``` + +See also the [SOCKS proxy example](examples/12-client-socks-proxy.php). + +### SSH proxy + +You can also establish your outgoing connections through an SSH server +by adding a dependency to [clue/reactphp-ssh-proxy](https://github.com/clue/reactphp-ssh-proxy). + +[Secure Shell (SSH)](https://en.wikipedia.org/wiki/Secure_Shell) is a secure +network protocol that is most commonly used to access a login shell on a remote +server. Its architecture allows it to use multiple secure channels over a single +connection. Among others, this can also be used to create an "SSH tunnel", which +is commonly used to tunnel HTTP(S) traffic through an intermediary ("proxy"), to +conceal the origin address (anonymity) or to circumvent address blocking +(geoblocking). This can be used to tunnel any TCP/IP-based protocol (HTTP, SMTP, +IMAP etc.), allows you to access local services that are otherwise not accessible +from the outside (database behind firewall) and as such can also be used for +plain HTTP and TLS-encrypted HTTPS. + +```php +$proxy = new Clue\React\SshProxy\SshSocksConnector('me@localhost:22', Loop::get()); + +$connector = new React\Socket\Connector(array( + 'tcp' => $proxy, + 'dns' => false +)); + +$browser = new React\Http\Browser($connector); +``` + +See also the [SSH proxy example](examples/13-client-ssh-proxy.php). + +### Unix domain sockets + +By default, this library supports transport over plaintext TCP/IP and secure +TLS connections for the `http://` and `https://` URL schemes respectively. +This library also supports Unix domain sockets (UDS) when explicitly configured. + +In order to use a UDS path, you have to explicitly configure the connector to +override the destination URL so that the hostname given in the request URL will +no longer be used to establish the connection: + +```php +$connector = new React\Socket\FixedUriConnector( + 'unix:///var/run/docker.sock', + new React\Socket\UnixConnector() +); + +$browser = new React\Http\Browser($connector); + +$client->get('http://localhost/info')->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump($response->getHeaders(), (string)$response->getBody()); +}); +``` + +See also the [Unix Domain Sockets (UDS) example](examples/14-client-unix-domain-sockets.php). + + +## Server Usage + +### HttpServer + + + +The `React\Http\HttpServer` class is responsible for handling incoming connections and then +processing each incoming HTTP request. + +When a complete HTTP request has been received, it will invoke the given +request handler function. This request handler function needs to be passed to +the constructor and will be invoked with the respective [request](#server-request) +object and expects a [response](#server-response) object in return: + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Hello World!\n" + ); +}); +``` + +Each incoming HTTP request message is always represented by the +[PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface), +see also following [request](#server-request) chapter for more details. + +Each outgoing HTTP response message is always represented by the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface), +see also following [response](#server-response) chapter for more details. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +In order to start listening for any incoming connections, the `HttpServer` needs +to be attached to an instance of +[`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface) +through the [`listen()`](#listen) method as described in the following +chapter. In its most simple form, you can attach this to a +[`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) +in order to start a plaintext HTTP server like this: + +```php +$http = new React\Http\HttpServer($handler); + +$socket = new React\Socket\SocketServer('0.0.0.0:8080'); +$http->listen($socket); +``` + +See also the [`listen()`](#listen) method and the +[hello world server example](examples/51-server-hello-world.php) +for more details. + +By default, the `HttpServer` buffers and parses the complete incoming HTTP +request in memory. It will invoke the given request handler function when the +complete request headers and request body has been received. This means the +[request](#server-request) object passed to your request handler function will be +fully compatible with PSR-7 (http-message). This provides sane defaults for +80% of the use cases and is the recommended way to use this library unless +you're sure you know what you're doing. + +On the other hand, buffering complete HTTP requests in memory until they can +be processed by your request handler function means that this class has to +employ a number of limits to avoid consuming too much memory. In order to +take the more advanced configuration out your hand, it respects setting from +your [`php.ini`](https://www.php.net/manual/en/ini.core.php) to apply its +default settings. This is a list of PHP settings this class respects with +their respective default values: + +``` +memory_limit 128M +post_max_size 8M // capped at 64K + +enable_post_data_reading 1 +max_input_nesting_level 64 +max_input_vars 1000 + +file_uploads 1 +upload_max_filesize 2M +max_file_uploads 20 +``` + +In particular, the `post_max_size` setting limits how much memory a single +HTTP request is allowed to consume while buffering its request body. This +needs to be limited because the server can process a large number of requests +concurrently, so the server may potentially consume a large amount of memory +otherwise. To support higher concurrency by default, this value is capped +at `64K`. If you assign a higher value, it will only allow `64K` by default. +If a request exceeds this limit, its request body will be ignored and it will +be processed like a request with no request body at all. See below for +explicit configuration to override this setting. + +By default, this class will try to avoid consuming more than half of your +`memory_limit` for buffering multiple concurrent HTTP requests. As such, with +the above default settings of `128M` max, it will try to consume no more than +`64M` for buffering multiple concurrent HTTP requests. As a consequence, it +will limit the concurrency to `1024` HTTP requests with the above defaults. + +It is imperative that you assign reasonable values to your PHP ini settings. +It is usually recommended to not support buffering incoming HTTP requests +with a large HTTP request body (e.g. large file uploads). If you want to +increase this buffer size, you will have to also increase the total memory +limit to allow for more concurrent requests (set `memory_limit 512M` or more) +or explicitly limit concurrency. + +In order to override the above buffering defaults, you can configure the +`HttpServer` explicitly. You can use the +[`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and +[`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) +to explicitly configure the total number of requests that can be handled at +once like this: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + new React\Http\Middleware\RequestBodyParserMiddleware(), + $handler +); +``` + +In this example, we allow processing up to 100 concurrent requests at once +and each request can buffer up to `2M`. This means you may have to keep a +maximum of `200M` of memory for incoming request body buffers. Accordingly, +you need to adjust the `memory_limit` ini setting to allow for these buffers +plus your actual application logic memory requirements (think `512M` or more). + +> Internally, this class automatically assigns these middleware handlers + automatically when no [`StreamingRequestMiddleware`](#streamingrequestmiddleware) + is given. Accordingly, you can use this example to override all default + settings to implement custom limits. + +As an alternative to buffering the complete request body in memory, you can +also use a streaming approach where only small chunks of data have to be kept +in memory: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + $handler +); +``` + +In this case, it will invoke the request handler function once the HTTP +request headers have been received, i.e. before receiving the potentially +much larger HTTP request body. This means the [request](#server-request) passed to +your request handler function may not be fully compatible with PSR-7. This is +specifically designed to help with more advanced use cases where you want to +have full control over consuming the incoming HTTP request body and +concurrency settings. See also [streaming incoming request](#streaming-incoming-request) +below for more details. + +> Changelog v1.5.0: This class has been renamed to `HttpServer` from the + previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + +### listen() + +The `listen(React\Socket\ServerInterface $socket): void` method can be used to +start listening for HTTP requests on the given socket server instance. + +The given [`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface) +is responsible for emitting the underlying streaming connections. This +HTTP server needs to be attached to it in order to process any +connections and pase incoming streaming data as incoming HTTP request +messages. In its most common form, you can attach this to a +[`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) +in order to start a plaintext HTTP server like this: + +```php +$http = new React\Http\HttpServer($handler); + +$socket = new React\Socket\SocketServer('0.0.0.0:8080'); +$http->listen($socket); +``` + +See also [hello world server example](examples/51-server-hello-world.php) +for more details. + +This example will start listening for HTTP requests on the alternative +HTTP port `8080` on all interfaces (publicly). As an alternative, it is +very common to use a reverse proxy and let this HTTP server listen on the +localhost (loopback) interface only by using the listen address +`127.0.0.1:8080` instead. This way, you host your application(s) on the +default HTTP port `80` and only route specific requests to this HTTP +server. + +Likewise, it's usually recommended to use a reverse proxy setup to accept +secure HTTPS requests on default HTTPS port `443` (TLS termination) and +only route plaintext requests to this HTTP server. As an alternative, you +can also accept secure HTTPS requests with this HTTP server by attaching +this to a [`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) +using a secure TLS listen address, a certificate file and optional +`passphrase` like this: + +```php +$http = new React\Http\HttpServer($handler); + +$socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', array( + 'tls' => array( + 'local_cert' => __DIR__ . '/localhost.pem' + ) +)); +$http->listen($socket); +``` + +See also [hello world HTTPS example](examples/61-server-hello-world-https.php) +for more details. + +### Server Request + +As seen above, the [`HttpServer`](#httpserver) class is responsible for handling +incoming connections and then processing each incoming HTTP request. + +The request object will be processed once the request has +been received by the client. +This request object implements the +[PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface) +which in turn extends the +[PSR-7 `RequestInterface`](https://www.php-fig.org/psr/psr-7/#32-psrhttpmessagerequestinterface) +and will be passed to the callback function like this. + + ```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $body = "The method of the request is: " . $request->getMethod(); + $body .= "The requested path is: " . $request->getUri()->getPath(); + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + $body + ); +}); +``` + +For more details about the request object, also check out the documentation of +[PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface) +and +[PSR-7 `RequestInterface`](https://www.php-fig.org/psr/psr-7/#32-psrhttpmessagerequestinterface). + +#### Request parameters + +The `getServerParams(): mixed[]` method can be used to +get server-side parameters similar to the `$_SERVER` variable. +The following parameters are currently available: + +* `REMOTE_ADDR` + The IP address of the request sender +* `REMOTE_PORT` + Port of the request sender +* `SERVER_ADDR` + The IP address of the server +* `SERVER_PORT` + The port of the server +* `REQUEST_TIME` + Unix timestamp when the complete request header has been received, + as integer similar to `time()` +* `REQUEST_TIME_FLOAT` + Unix timestamp when the complete request header has been received, + as float similar to `microtime(true)` +* `HTTPS` + Set to 'on' if the request used HTTPS, otherwise it won't be set + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $body = "Your IP is: " . $request->getServerParams()['REMOTE_ADDR']; + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + $body + ); +}); +``` + +See also [whatsmyip server example](examples/53-server-whatsmyip.php). + +> Advanced: Note that address parameters will not be set if you're listening on + a Unix domain socket (UDS) path as this protocol lacks the concept of + host/port. + +#### Query parameters + +The `getQueryParams(): array` method can be used to get the query parameters +similiar to the `$_GET` variable. + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $queryParams = $request->getQueryParams(); + + $body = 'The query parameter "foo" is not set. Click the following link '; + $body .= 'to use query parameter in your request'; + + if (isset($queryParams['foo'])) { + $body = 'The value of "foo" is: ' . htmlspecialchars($queryParams['foo']); + } + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/html' + ), + $body + ); +}); +``` + +The response in the above example will return a response body with a link. +The URL contains the query parameter `foo` with the value `bar`. +Use [`htmlentities`](https://www.php.net/manual/en/function.htmlentities.php) +like in this example to prevent +[Cross-Site Scripting (abbreviated as XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting). + +See also [server query parameters example](examples/54-server-query-parameter.php). + +#### Request body + +By default, the [`Server`](#httpserver) will buffer and parse the full request body +in memory. This means the given request object includes the parsed request body +and any file uploads. + +> As an alternative to the default buffering logic, you can also use the + [`StreamingRequestMiddleware`](#streamingrequestmiddleware). Jump to the next + chapter to learn more about how to process a + [streaming incoming request](#streaming-incoming-request). + +As stated above, each incoming HTTP request is always represented by the +[PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface). +This interface provides several methods that are useful when working with the +incoming request body as described below. + +The `getParsedBody(): null|array|object` method can be used to +get the parsed request body, similar to +[PHP's `$_POST` variable](https://www.php.net/manual/en/reserved.variables.post.php). +This method may return a (possibly nested) array structure with all body +parameters or a `null` value if the request body could not be parsed. +By default, this method will only return parsed data for requests using +`Content-Type: application/x-www-form-urlencoded` or `Content-Type: multipart/form-data` +request headers (commonly used for `POST` requests for HTML form submission data). + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $name = $request->getParsedBody()['name'] ?? 'anonymous'; + + return new React\Http\Message\Response( + 200, + array(), + "Hello $name!\n" + ); +}); +``` + +See also [form upload example](examples/62-server-form-upload.php) for more details. + +The `getBody(): StreamInterface` method can be used to +get the raw data from this request body, similar to +[PHP's `php://input` stream](https://www.php.net/manual/en/wrappers.php.php#wrappers.php.input). +This method returns an instance of the request body represented by the +[PSR-7 `StreamInterface`](https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface). +This is particularly useful when using a custom request body that will not +otherwise be parsed by default, such as a JSON (`Content-Type: application/json`) or +an XML (`Content-Type: application/xml`) request body (which is commonly used for +`POST`, `PUT` or `PATCH` requests in JSON-based or RESTful/RESTish APIs). + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $data = json_decode((string)$request->getBody()); + $name = $data->name ?? 'anonymous'; + + return new React\Http\Message\Response( + 200, + array('Content-Type' => 'application/json'), + json_encode(['message' => "Hello $name!"]) + ); +}); +``` + +See also [JSON API server example](examples/59-server-json-api.php) for more details. + +The `getUploadedFiles(): array` method can be used to +get the uploaded files in this request, similar to +[PHP's `$_FILES` variable](https://www.php.net/manual/en/reserved.variables.files.php). +This method returns a (possibly nested) array structure with all file uploads, each represented by the +[PSR-7 `UploadedFileInterface`](https://www.php-fig.org/psr/psr-7/#36-psrhttpmessageuploadedfileinterface). +This array will only be filled when using the `Content-Type: multipart/form-data` +request header (commonly used for `POST` requests for HTML file uploads). + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $files = $request->getUploadedFiles(); + $name = isset($files['avatar']) ? $files['avatar']->getClientFilename() : 'nothing'; + + return new React\Http\Message\Response( + 200, + array(), + "Uploaded $name\n" + ); +}); +``` + +See also [form upload server example](examples/62-server-form-upload.php) for more details. + +The `getSize(): ?int` method can be used to +get the size of the request body, similar to PHP's `$_SERVER['CONTENT_LENGTH']` variable. +This method returns the complete size of the request body measured in number +of bytes as defined by the message boundaries. +This value may be `0` if the request message does not contain a request body +(such as a simple `GET` request). +This method operates on the buffered request body, i.e. the request body size +is always known, even when the request does not specify a `Content-Length` request +header or when using `Transfer-Encoding: chunked` for HTTP/1.1 requests. + +> Note: The `HttpServer` automatically takes care of handling requests with the + additional `Expect: 100-continue` request header. When HTTP/1.1 clients want to + send a bigger request body, they MAY send only the request headers with an + additional `Expect: 100-continue` request header and wait before sending the actual + (large) message body. In this case the server will automatically send an + intermediary `HTTP/1.1 100 Continue` response to the client. This ensures you + will receive the request body without a delay as expected. + +#### Streaming incoming request + +If you're using the advanced [`StreamingRequestMiddleware`](#streamingrequestmiddleware), +the request object will be processed once the request headers have been received. +This means that this happens irrespective of (i.e. *before*) receiving the +(potentially much larger) request body. + +> Note that this is non-standard behavior considered advanced usage. Jump to the + previous chapter to learn more about how to process a buffered [request body](#request-body). + +While this may be uncommon in the PHP ecosystem, this is actually a very powerful +approach that gives you several advantages not otherwise possible: + +* React to requests *before* receiving a large request body, + such as rejecting an unauthenticated request or one that exceeds allowed + message lengths (file uploads). +* Start processing parts of the request body before the remainder of the request + body arrives or if the sender is slowly streaming data. +* Process a large request body without having to buffer anything in memory, + such as accepting a huge file upload or possibly unlimited request body stream. + +The `getBody(): StreamInterface` method can be used to +access the request body stream. +In the streaming mode, this method returns a stream instance that implements both the +[PSR-7 `StreamInterface`](https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface) +and the [ReactPHP `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface). +However, most of the +[PSR-7 `StreamInterface`](https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface) +methods have been designed under the assumption of being in control of a +synchronous request body. +Given that this does not apply to this server, the following +[PSR-7 `StreamInterface`](https://www.php-fig.org/psr/psr-7/#34-psrhttpmessagestreaminterface) +methods are not used and SHOULD NOT be called: +`tell()`, `eof()`, `seek()`, `rewind()`, `write()` and `read()`. +If this is an issue for your use case and/or you want to access uploaded files, +it's highly recommended to use a buffered [request body](#request-body) or use the +[`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) instead. +The [ReactPHP `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +gives you access to the incoming request body as the individual chunks arrive: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + function (Psr\Http\Message\ServerRequestInterface $request) { + $body = $request->getBody(); + assert($body instanceof Psr\Http\Message\StreamInterface); + assert($body instanceof React\Stream\ReadableStreamInterface); + + return new React\Promise\Promise(function ($resolve, $reject) use ($body) { + $bytes = 0; + $body->on('data', function ($data) use (&$bytes) { + $bytes += strlen($data); + }); + + $body->on('end', function () use ($resolve, &$bytes){ + $resolve(new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Received $bytes bytes\n" + )); + }); + + // an error occures e.g. on invalid chunked encoded data or an unexpected 'end' event + $body->on('error', function (\Exception $exception) use ($resolve, &$bytes) { + $resolve(new React\Http\Message\Response( + 400, + array( + 'Content-Type' => 'text/plain' + ), + "Encountered error after $bytes bytes: {$exception->getMessage()}\n" + )); + }); + }); + } +); +``` + +The above example simply counts the number of bytes received in the request body. +This can be used as a skeleton for buffering or processing the request body. + +See also [streaming request server example](examples/63-server-streaming-request.php) for more details. + +The `data` event will be emitted whenever new data is available on the request +body stream. +The server also automatically takes care of decoding any incoming requests using +`Transfer-Encoding: chunked` and will only emit the actual payload as data. + +The `end` event will be emitted when the request body stream terminates +successfully, i.e. it was read until its expected end. + +The `error` event will be emitted in case the request stream contains invalid +data for `Transfer-Encoding: chunked` or when the connection closes before +the complete request stream has been received. +The server will automatically stop reading from the connection and discard all +incoming data instead of closing it. +A response message can still be sent (unless the connection is already closed). + +A `close` event will be emitted after an `error` or `end` event. + +For more details about the request body stream, check out the documentation of +[ReactPHP `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface). + +The `getSize(): ?int` method can be used to +get the size of the request body, similar to PHP's `$_SERVER['CONTENT_LENGTH']` variable. +This method returns the complete size of the request body measured in number +of bytes as defined by the message boundaries. +This value may be `0` if the request message does not contain a request body +(such as a simple `GET` request). +This method operates on the streaming request body, i.e. the request body size +may be unknown (`null`) when using `Transfer-Encoding: chunked` for HTTP/1.1 requests. + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + function (Psr\Http\Message\ServerRequestInterface $request) { + $size = $request->getBody()->getSize(); + if ($size === null) { + $body = 'The request does not contain an explicit length.'; + $body .= 'This example does not accept chunked transfer encoding.'; + + return new React\Http\Message\Response( + 411, + array( + 'Content-Type' => 'text/plain' + ), + $body + ); + } + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Request body size: " . $size . " bytes\n" + ); + } +); +``` + +> Note: The `HttpServer` automatically takes care of handling requests with the + additional `Expect: 100-continue` request header. When HTTP/1.1 clients want to + send a bigger request body, they MAY send only the request headers with an + additional `Expect: 100-continue` request header and wait before sending the actual + (large) message body. In this case the server will automatically send an + intermediary `HTTP/1.1 100 Continue` response to the client. This ensures you + will receive the streaming request body without a delay as expected. + +#### Request method + +Note that the server supports *any* request method (including custom and non- +standard ones) and all request-target formats defined in the HTTP specs for each +respective method, including *normal* `origin-form` requests as well as +proxy requests in `absolute-form` and `authority-form`. +The `getUri(): UriInterface` method can be used to get the effective request +URI which provides you access to individiual URI components. +Note that (depending on the given `request-target`) certain URI components may +or may not be present, for example the `getPath(): string` method will return +an empty string for requests in `asterisk-form` or `authority-form`. +Its `getHost(): string` method will return the host as determined by the +effective request URI, which defaults to the local socket address if a HTTP/1.0 +client did not specify one (i.e. no `Host` header). +Its `getScheme(): string` method will return `http` or `https` depending +on whether the request was made over a secure TLS connection to the target host. + +The `Host` header value will be sanitized to match this host component plus the +port component only if it is non-standard for this URI scheme. + +You can use `getMethod(): string` and `getRequestTarget(): string` to +check this is an accepted request and may want to reject other requests with +an appropriate error code, such as `400` (Bad Request) or `405` (Method Not +Allowed). + +> The `CONNECT` method is useful in a tunneling setup (HTTPS proxy) and not + something most HTTP servers would want to care about. + Note that if you want to handle this method, the client MAY send a different + request-target than the `Host` header value (such as removing default ports) + and the request-target MUST take precendence when forwarding. + +#### Cookie parameters + +The `getCookieParams(): string[]` method can be used to +get all cookies sent with the current request. + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $key = 'react\php'; + + if (isset($request->getCookieParams()[$key])) { + $body = "Your cookie value is: " . $request->getCookieParams()[$key]; + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + $body + ); + } + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain', + 'Set-Cookie' => urlencode($key) . '=' . urlencode('test;more') + ), + "Your cookie has been set." + ); +}); +``` + +The above example will try to set a cookie on first access and +will try to print the cookie value on all subsequent tries. +Note how the example uses the `urlencode()` function to encode +non-alphanumeric characters. +This encoding is also used internally when decoding the name and value of cookies +(which is in line with other implementations, such as PHP's cookie functions). + +See also [cookie server example](examples/55-server-cookie-handling.php) for more details. + +#### Invalid request + +The `HttpServer` class supports both HTTP/1.1 and HTTP/1.0 request messages. +If a client sends an invalid request message, uses an invalid HTTP +protocol version or sends an invalid `Transfer-Encoding` request header value, +the server will automatically send a `400` (Bad Request) HTTP error response +to the client and close the connection. +On top of this, it will emit an `error` event that can be used for logging +purposes like this: + +```php +$http->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that the server will also emit an `error` event if you do not return a +valid response object from your request handler function. See also +[invalid response](#invalid-response) for more details. + +### Server Response + +The callback function passed to the constructor of the [`HttpServer`](#httpserver) is +responsible for processing the request and returning a response, which will be +delivered to the client. + +This function MUST return an instance implementing +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +object or a +[ReactPHP Promise](https://github.com/reactphp/promise) +which resolves with a [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) object. + +This projects ships a [`Response` class](#response) which implements the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface). +In its most simple form, you can use it like this: + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Hello World!\n" + ); +}); +``` + +We use this [`Response` class](#response) throughout our project examples, but +feel free to use any other implementation of the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface). +See also the [`Response` class](#response) for more details. + +#### Deferred response + +The example above returns the response directly, because it needs +no time to be processed. +Using a database, the file system or long calculations +(in fact every action that will take >=1ms) to create your +response, will slow down the server. +To prevent this you SHOULD use a +[ReactPHP Promise](https://github.com/reactphp/promise#reactpromise). +This example shows how such a long-term action could look like: + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + return new Promise(function ($resolve, $reject) { + Loop::addTimer(1.5, function() use ($resolve) { + $response = new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Hello world" + ); + $resolve($response); + }); + }); +}); +``` + +The above example will create a response after 1.5 second. +This example shows that you need a promise, +if your response needs time to created. +The `ReactPHP Promise` will resolve in a `Response` object when the request +body ends. +If the client closes the connection while the promise is still pending, the +promise will automatically be cancelled. +The promise cancellation handler can be used to clean up any pending resources +allocated in this case (if applicable). +If a promise is resolved after the client closes, it will simply be ignored. + +#### Streaming outgoing response + +The `Response` class in this project supports to add an instance which implements the +[ReactPHP `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +for the response body. +So you are able stream data directly into the response body. +Note that other implementations of the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +may only support strings. + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $stream = new ThroughStream(); + + $timer = Loop::addPeriodicTimer(0.5, function () use ($stream) { + $stream->write(microtime(true) . PHP_EOL); + }); + + Loop::addTimer(5, function() use ($timer, $stream) { + Loop::cancelTimer($timer); + $stream->end(); + }); + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + $stream + ); +}); +``` + +The above example will emit every 0.5 seconds the current Unix timestamp +with microseconds as float to the client and will end after 5 seconds. +This is just a example you could use of the streaming, +you could also send a big amount of data via little chunks +or use it for body data that needs to calculated. + +If the request handler resolves with a response stream that is already closed, +it will simply send an empty response body. +If the client closes the connection while the stream is still open, the +response stream will automatically be closed. +If a promise is resolved with a streaming body after the client closes, the +response stream will automatically be closed. +The `close` event can be used to clean up any pending resources allocated +in this case (if applicable). + +> Note that special care has to be taken if you use a body stream instance that + implements ReactPHP's + [`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface) + (such as the `ThroughStream` in the above example). +> +> For *most* cases, this will simply only consume its readable side and forward + (send) any data that is emitted by the stream, thus entirely ignoring the + writable side of the stream. + If however this is either a `101` (Switching Protocols) response or a `2xx` + (Successful) response to a `CONNECT` method, it will also *write* data to the + writable side of the stream. + This can be avoided by either rejecting all requests with the `CONNECT` + method (which is what most *normal* origin HTTP servers would likely do) or + or ensuring that only ever an instance of + [ReactPHP's `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) + is used. +> +> The `101` (Switching Protocols) response code is useful for the more advanced + `Upgrade` requests, such as upgrading to the WebSocket protocol or + implementing custom protocol logic that is out of scope of the HTTP specs and + this HTTP library. + If you want to handle the `Upgrade: WebSocket` header, you will likely want + to look into using [Ratchet](http://socketo.me/) instead. + If you want to handle a custom protocol, you will likely want to look into the + [HTTP specs](https://tools.ietf.org/html/rfc7230#section-6.7) and also see + [examples #81 and #82](examples/) for more details. + In particular, the `101` (Switching Protocols) response code MUST NOT be used + unless you send an `Upgrade` response header value that is also present in + the corresponding HTTP/1.1 `Upgrade` request header value. + The server automatically takes care of sending a `Connection: upgrade` + header value in this case, so you don't have to. +> +> The `CONNECT` method is useful in a tunneling setup (HTTPS proxy) and not + something most origin HTTP servers would want to care about. + The HTTP specs define an opaque "tunneling mode" for this method and make no + use of the message body. + For consistency reasons, this library uses a `DuplexStreamInterface` in the + response body for tunneled application data. + This implies that that a `2xx` (Successful) response to a `CONNECT` request + can in fact use a streaming response body for the tunneled application data, + so that any raw data the client sends over the connection will be piped + through the writable stream for consumption. + Note that while the HTTP specs make no use of the request body for `CONNECT` + requests, one may still be present. Normal request body processing applies + here and the connection will only turn to "tunneling mode" after the request + body has been processed (which should be empty in most cases). + See also [HTTP CONNECT server example](examples/72-server-http-connect-proxy.php) for more details. + +#### Response length + +If the response body size is known, a `Content-Length` response header will be +added automatically. This is the most common use case, for example when using +a `string` response body like this: + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + "Hello World!\n" + ); +}); +``` + +If the response body size is unknown, a `Content-Length` response header can not +be added automatically. When using a [streaming outgoing response](#streaming-outgoing-response) +without an explicit `Content-Length` response header, outgoing HTTP/1.1 response +messages will automatically use `Transfer-Encoding: chunked` while legacy HTTP/1.0 +response messages will contain the plain response body. If you know the length +of your streaming response body, you MAY want to specify it explicitly like this: + +```php +$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) { + $stream = new ThroughStream(); + + Loop::addTimer(2.0, function () use ($stream) { + $stream->end("Hello World!\n"); + }); + + return new React\Http\Message\Response( + 200, + array( + 'Content-Length' => '13', + 'Content-Type' => 'text/plain', + ), + $stream + ); +}); +``` + +Any response to a `HEAD` request and any response with a `1xx` (Informational), +`204` (No Content) or `304` (Not Modified) status code will *not* include a +message body as per the HTTP specs. +This means that your callback does not have to take special care of this and any +response body will simply be ignored. + +Similarly, any `2xx` (Successful) response to a `CONNECT` request, any response +with a `1xx` (Informational) or `204` (No Content) status code will *not* +include a `Content-Length` or `Transfer-Encoding` header as these do not apply +to these messages. +Note that a response to a `HEAD` request and any response with a `304` (Not +Modified) status code MAY include these headers even though +the message does not contain a response body, because these header would apply +to the message if the same request would have used an (unconditional) `GET`. + +#### Invalid response + +As stated above, each outgoing HTTP response is always represented by the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface). +If your request handler function returns an invalid value or throws an +unhandled `Exception` or `Throwable`, the server will automatically send a `500` +(Internal Server Error) HTTP error response to the client. +On top of this, it will emit an `error` event that can be used for logging +purposes like this: + +```php +$http->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; + if ($e->getPrevious() !== null) { + echo 'Previous: ' . $e->getPrevious()->getMessage() . PHP_EOL; + } +}); +``` + +Note that the server will also emit an `error` event if the client sends an +invalid HTTP request that never reaches your request handler function. See +also [invalid request](#invalid-request) for more details. +Additionally, a [streaming incoming request](#streaming-incoming-request) body +can also emit an `error` event on the request body. + +The server will only send a very generic `500` (Interval Server Error) HTTP +error response without any further details to the client if an unhandled +error occurs. While we understand this might make initial debugging harder, +it also means that the server does not leak any application details or stack +traces to the outside by default. It is usually recommended to catch any +`Exception` or `Throwable` within your request handler function or alternatively +use a [`middleware`](#middleware) to avoid this generic error handling and +create your own HTTP response message instead. + +#### Default response headers + +When a response is returned from the request handler function, it will be +processed by the [`HttpServer`](#httpserver) and then sent back to the client. + +A `Server: ReactPHP/1` response header will be added automatically. You can add +a custom `Server` response header like this: + +```php +$http = new React\Http\HttpServer(function (ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Server' => 'PHP/3' + ) + ); +}); +``` + +If you do not want to send this `Sever` response header at all (such as when you +don't want to expose the underlying server software), you can use an empty +string value like this: + +```php +$http = new React\Http\HttpServer(function (ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Server' => '' + ) + ); +}); +``` + +A `Date` response header will be added automatically with the current system +date and time if none is given. You can add a custom `Date` response header +like this: + +```php +$http = new React\Http\HttpServer(function (ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Date' => gmdate('D, d M Y H:i:s \G\M\T') + ) + ); +}); +``` + +If you do not want to send this `Date` response header at all (such as when you +don't have an appropriate clock to rely on), you can use an empty string value +like this: + +```php +$http = new React\Http\HttpServer(function (ServerRequestInterface $request) { + return new React\Http\Message\Response( + 200, + array( + 'Date' => '' + ) + ); +}); +``` + +The `HttpServer` class will automatically add the protocol version of the request, +so you don't have to. For instance, if the client sends the request using the +HTTP/1.1 protocol version, the response message will also use the same protocol +version, no matter what version is returned from the request handler function. + +The server supports persistent connections. An appropriate `Connection: keep-alive` +or `Connection: close` response header will be added automatically, respecting the +matching request header value and HTTP default header values. The server is +responsible for handling the `Connection` response header, so you SHOULD NOT pass +this response header yourself, unless you explicitly want to override the user's +choice with a `Connection: close` response header. + +### Middleware + +As documented above, the [`HttpServer`](#httpserver) accepts a single request handler +argument that is responsible for processing an incoming HTTP request and then +creating and returning an outgoing HTTP response. + +Many common use cases involve validating, processing, manipulating the incoming +HTTP request before passing it to the final business logic request handler. +As such, this project supports the concept of middleware request handlers. + +#### Custom middleware + +A middleware request handler is expected to adhere the following rules: + +* It is a valid `callable`. +* It accepts an instance implementing + [PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface) + as first argument and an optional `callable` as second argument. +* It returns either: + * An instance implementing + [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) + for direct consumption. + * Any promise which can be consumed by + [`Promise\resolve()`](https://reactphp.org/promise/#resolve) resolving to a + [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) + for deferred consumption. + * It MAY throw an `Exception` (or return a rejected promise) in order to + signal an error condition and abort the chain. +* It calls `$next($request)` to continue processing the next middleware + request handler or returns explicitly without calling `$next` to + abort the chain. + * The `$next` request handler (recursively) invokes the next request + handler from the chain with the same logic as above and returns (or throws) + as above. + * The `$request` may be modified prior to calling `$next($request)` to + change the incoming request the next middleware operates on. + * The `$next` return value may be consumed to modify the outgoing response. + * The `$next` request handler MAY be called more than once if you want to + implement custom "retry" logic etc. + +Note that this very simple definition allows you to use either anonymous +functions or any classes that use the magic `__invoke()` method. +This allows you to easily create custom middleware request handlers on the fly +or use a class based approach to ease using existing middleware implementations. + +While this project does provide the means to *use* middleware implementations, +it does not aim to *define* how middleware implementations should look like. +We realize that there's a vivid ecosystem of middleware implementations and +ongoing effort to standardize interfaces between these with +[PSR-15](https://www.php-fig.org/psr/psr-15/) (HTTP Server Request Handlers) +and support this goal. +As such, this project only bundles a few middleware implementations that are +required to match PHP's request behavior (see below) and otherwise actively +encourages [Third-Party Middleware](#third-party-middleware) implementations. + +In order to use middleware request handlers, simply pass an array with all +callables as defined above to the [`HttpServer`](#httpserver). +The following example adds a middleware request handler that adds the current time to the request as a +header (`Request-Time`) and a final request handler that always returns a 200 code without a body: + +```php +$http = new React\Http\HttpServer( + function (Psr\Http\Message\ServerRequestInterface $request, callable $next) { + $request = $request->withHeader('Request-Time', time()); + return $next($request); + }, + function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response(200); + } +); +``` + +> Note how the middleware request handler and the final request handler have a + very simple (and similar) interface. The only difference is that the final + request handler does not receive a `$next` handler. + +Similarly, you can use the result of the `$next` middleware request handler +function to modify the outgoing response. +Note that as per the above documentation, the `$next` middleware request handler may return a +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +directly or one wrapped in a promise for deferred resolution. +In order to simplify handling both paths, you can simply wrap this in a +[`Promise\resolve()`](https://reactphp.org/promise/#resolve) call like this: + +```php +$http = new React\Http\HttpServer( + function (Psr\Http\Message\ServerRequestInterface $request, callable $next) { + $promise = React\Promise\resolve($next($request)); + return $promise->then(function (ResponseInterface $response) { + return $response->withHeader('Content-Type', 'text/html'); + }); + }, + function (Psr\Http\Message\ServerRequestInterface $request) { + return new React\Http\Message\Response(200); + } +); +``` + +Note that the `$next` middleware request handler may also throw an +`Exception` (or return a rejected promise) as described above. +The previous example does not catch any exceptions and would thus signal an +error condition to the `HttpServer`. +Alternatively, you can also catch any `Exception` to implement custom error +handling logic (or logging etc.) by wrapping this in a +[`Promise`](https://reactphp.org/promise/#promise) like this: + +```php +$http = new React\Http\HttpServer( + function (Psr\Http\Message\ServerRequestInterface $request, callable $next) { + $promise = new React\Promise\Promise(function ($resolve) use ($next, $request) { + $resolve($next($request)); + }); + return $promise->then(null, function (Exception $e) { + return new React\Http\Message\Response( + 500, + array(), + 'Internal error: ' . $e->getMessage() + ); + }); + }, + function (Psr\Http\Message\ServerRequestInterface $request) { + if (mt_rand(0, 1) === 1) { + throw new RuntimeException('Database error'); + } + return new React\Http\Message\Response(200); + } +); +``` + +#### Third-Party Middleware + +While this project does provide the means to *use* middleware implementations +(see above), it does not aim to *define* how middleware implementations should +look like. We realize that there's a vivid ecosystem of middleware +implementations and ongoing effort to standardize interfaces between these with +[PSR-15](https://www.php-fig.org/psr/psr-15/) (HTTP Server Request Handlers) +and support this goal. +As such, this project only bundles a few middleware implementations that are +required to match PHP's request behavior (see +[middleware implementations](#reacthttpmiddleware)) and otherwise actively +encourages third-party middleware implementations. + +While we would love to support PSR-15 directly in `react/http`, we understand +that this interface does not specifically target async APIs and as such does +not take advantage of promises for [deferred responses](#deferred-response). +The gist of this is that where PSR-15 enforces a +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +return value, we also accept a `PromiseInterface`. +As such, we suggest using the external +[PSR-15 middleware adapter](https://github.com/friends-of-reactphp/http-middleware-psr15-adapter) +that uses on the fly monkey patching of these return values which makes using +most PSR-15 middleware possible with this package without any changes required. + +Other than that, you can also use the above [middleware definition](#middleware) +to create custom middleware. A non-exhaustive list of third-party middleware can +be found at the [middleware wiki](https://github.com/reactphp/reactphp/wiki/Users#http-middleware). +If you build or know a custom middleware, make sure to let the world know and +feel free to add it to this list. + +## API + +### Browser + +The `React\Http\Browser` is responsible for sending HTTP requests to your HTTP server +and keeps track of pending incoming HTTP responses. + +```php +$browser = new React\Http\Browser(); +``` + +This class takes two optional arguments for more advanced usage: + +```php +// constructor signature as of v1.5.0 +$browser = new React\Http\Browser(?ConnectorInterface $connector = null, ?LoopInterface $loop = null); + +// legacy constructor signature before v1.5.0 +$browser = new React\Http\Browser(?LoopInterface $loop = null, ?ConnectorInterface $connector = null); +``` + +If you need custom connector settings (DNS resolution, TLS parameters, timeouts, +proxy servers etc.), you can explicitly pass a custom instance of the +[`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface): + +```php +$connector = new React\Socket\Connector(array( + 'dns' => '127.0.0.1', + 'tcp' => array( + 'bindto' => '192.168.10.1:0' + ), + 'tls' => array( + 'verify_peer' => false, + 'verify_peer_name' => false + ) +)); + +$browser = new React\Http\Browser($connector); +``` + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Note that the browser class is final and shouldn't be extended, it is likely to be marked final in a future release. + +#### get() + +The `get(string $url, array $headers = array()): PromiseInterface` method can be used to +send an HTTP GET request. + +```php +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump((string)$response->getBody()); +}); +``` + +See also [GET request client example](examples/01-client-get-request.php). + +#### post() + +The `post(string $url, array $headers = array(), string|ReadableStreamInterface $contents = ''): PromiseInterface` method can be used to +send an HTTP POST request. + +```php +$browser->post( + $url, + [ + 'Content-Type' => 'application/json' + ], + json_encode($data) +)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump(json_decode((string)$response->getBody())); +}); +``` + +See also [POST JSON client example](examples/04-client-post-json.php). + +This method is also commonly used to submit HTML form data: + +```php +$data = [ + 'user' => 'Alice', + 'password' => 'secret' +]; + +$browser->post( + $url, + [ + 'Content-Type' => 'application/x-www-form-urlencoded' + ], + http_build_query($data) +); +``` + +This method will automatically add a matching `Content-Length` request +header if the outgoing request body is a `string`. If you're using a +streaming request body (`ReadableStreamInterface`), it will default to +using `Transfer-Encoding: chunked` or you have to explicitly pass in a +matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->post($url, array('Content-Length' => '11'), $body); +``` + +#### head() + +The `head(string $url, array $headers = array()): PromiseInterface` method can be used to +send an HTTP HEAD request. + +```php +$browser->head($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump($response->getHeaders()); +}); +``` + +#### patch() + +The `patch(string $url, array $headers = array(), string|ReadableStreamInterface $contents = ''): PromiseInterface` method can be used to +send an HTTP PATCH request. + +```php +$browser->patch( + $url, + [ + 'Content-Type' => 'application/json' + ], + json_encode($data) +)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump(json_decode((string)$response->getBody())); +}); +``` + +This method will automatically add a matching `Content-Length` request +header if the outgoing request body is a `string`. If you're using a +streaming request body (`ReadableStreamInterface`), it will default to +using `Transfer-Encoding: chunked` or you have to explicitly pass in a +matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->patch($url, array('Content-Length' => '11'), $body); +``` + +#### put() + +The `put(string $url, array $headers = array()): PromiseInterface` method can be used to +send an HTTP PUT request. + +```php +$browser->put( + $url, + [ + 'Content-Type' => 'text/xml' + ], + $xml->asXML() +)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump((string)$response->getBody()); +}); +``` + +See also [PUT XML client example](examples/05-client-put-xml.php). + +This method will automatically add a matching `Content-Length` request +header if the outgoing request body is a `string`. If you're using a +streaming request body (`ReadableStreamInterface`), it will default to +using `Transfer-Encoding: chunked` or you have to explicitly pass in a +matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->put($url, array('Content-Length' => '11'), $body); +``` + +#### delete() + +The `delete(string $url, array $headers = array()): PromiseInterface` method can be used to +send an HTTP DELETE request. + +```php +$browser->delete($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump((string)$response->getBody()); +}); +``` + +#### request() + +The `request(string $method, string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +send an arbitrary HTTP request. + +The preferred way to send an HTTP request is by using the above +[request methods](#request-methods), for example the [`get()`](#get) +method to send an HTTP `GET` request. + +As an alternative, if you want to use a custom HTTP request method, you +can use this method: + +```php +$browser->request('OPTIONS', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + var_dump((string)$response->getBody()); +}); +``` + +This method will automatically add a matching `Content-Length` request +header if the size of the outgoing request body is known and non-empty. +For an empty request body, if will only include a `Content-Length: 0` +request header if the request method usually expects a request body (only +applies to `POST`, `PUT` and `PATCH`). + +If you're using a streaming request body (`ReadableStreamInterface`), it +will default to using `Transfer-Encoding: chunked` or you have to +explicitly pass in a matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->request('POST', $url, array('Content-Length' => '11'), $body); +``` + +#### requestStreaming() + +The `requestStreaming(string $method, string $url, array $headers = array(), string|ReadableStreamInterface $body = ''): PromiseInterface` method can be used to +send an arbitrary HTTP request and receive a streaming response without buffering the response body. + +The preferred way to send an HTTP request is by using the above +[request methods](#request-methods), for example the [`get()`](#get) +method to send an HTTP `GET` request. Each of these methods will buffer +the whole response body in memory by default. This is easy to get started +and works reasonably well for smaller responses. + +In some situations, it's a better idea to use a streaming approach, where +only small chunks have to be kept in memory. You can use this method to +send an arbitrary HTTP request and receive a streaming response. It uses +the same HTTP message API, but does not buffer the response body in +memory. It only processes the response body in small chunks as data is +received and forwards this data through [ReactPHP's Stream API](https://github.com/reactphp/stream). +This works for (any number of) responses of arbitrary sizes. + +```php +$browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + $body = $response->getBody(); + assert($body instanceof Psr\Http\Message\StreamInterface); + assert($body instanceof React\Stream\ReadableStreamInterface); + + $body->on('data', function ($chunk) { + echo $chunk; + }); + + $body->on('error', function (Exception $error) { + echo 'Error: ' . $error->getMessage() . PHP_EOL; + }); + + $body->on('close', function () { + echo '[DONE]' . PHP_EOL; + }); +}); +``` + +See also [ReactPHP's `ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +and the [streaming response](#streaming-response) for more details, +examples and possible use-cases. + +This method will automatically add a matching `Content-Length` request +header if the size of the outgoing request body is known and non-empty. +For an empty request body, if will only include a `Content-Length: 0` +request header if the request method usually expects a request body (only +applies to `POST`, `PUT` and `PATCH`). + +If you're using a streaming request body (`ReadableStreamInterface`), it +will default to using `Transfer-Encoding: chunked` or you have to +explicitly pass in a matching `Content-Length` request header like so: + +```php +$body = new React\Stream\ThroughStream(); +Loop::addTimer(1.0, function () use ($body) { + $body->end("hello world"); +}); + +$browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body); +``` + +#### withTimeout() + +The `withTimeout(bool|number $timeout): Browser` method can be used to +change the maximum timeout used for waiting for pending requests. + +You can pass in the number of seconds to use as a new timeout value: + +```php +$browser = $browser->withTimeout(10.0); +``` + +You can pass in a bool `false` to disable any timeouts. In this case, +requests can stay pending forever: + +```php +$browser = $browser->withTimeout(false); +``` + +You can pass in a bool `true` to re-enable default timeout handling. This +will respects PHP's `default_socket_timeout` setting (default 60s): + +```php +$browser = $browser->withTimeout(true); +``` + +See also [timeouts](#timeouts) for more details about timeout handling. + +Notice that the [`Browser`](#browser) is an immutable object, i.e. this +method actually returns a *new* [`Browser`](#browser) instance with the +given timeout value applied. + +#### withFollowRedirects() + +The `withFollowRedirects(bool|int $followRedirects): Browser` method can be used to +change how HTTP redirects will be followed. + +You can pass in the maximum number of redirects to follow: + +```php +$browser = $browser->withFollowRedirects(5); +``` + +The request will automatically be rejected when the number of redirects +is exceeded. You can pass in a `0` to reject the request for any +redirects encountered: + +```php +$browser = $browser->withFollowRedirects(0); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // only non-redirected responses will now end up here + var_dump($response->getHeaders()); +}); +``` + +You can pass in a bool `false` to disable following any redirects. In +this case, requests will resolve with the redirection response instead +of following the `Location` response header: + +```php +$browser = $browser->withFollowRedirects(false); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // any redirects will now end up here + var_dump($response->getHeaderLine('Location')); +}); +``` + +You can pass in a bool `true` to re-enable default redirect handling. +This defaults to following a maximum of 10 redirects: + +```php +$browser = $browser->withFollowRedirects(true); +``` + +See also [redirects](#redirects) for more details about redirect handling. + +Notice that the [`Browser`](#browser) is an immutable object, i.e. this +method actually returns a *new* [`Browser`](#browser) instance with the +given redirect setting applied. + +#### withRejectErrorResponse() + +The `withRejectErrorResponse(bool $obeySuccessCode): Browser` method can be used to +change whether non-successful HTTP response status codes (4xx and 5xx) will be rejected. + +You can pass in a bool `false` to disable rejecting incoming responses +that use a 4xx or 5xx response status code. In this case, requests will +resolve with the response message indicating an error condition: + +```php +$browser = $browser->withRejectErrorResponse(false); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // any HTTP response will now end up here + var_dump($response->getStatusCode(), $response->getReasonPhrase()); +}); +``` + +You can pass in a bool `true` to re-enable default status code handling. +This defaults to rejecting any response status codes in the 4xx or 5xx +range with a [`ResponseException`](#responseexception): + +```php +$browser = $browser->withRejectErrorResponse(true); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // any successful HTTP response will now end up here + var_dump($response->getStatusCode(), $response->getReasonPhrase()); +}, function (Exception $e) { + if ($e instanceof React\Http\Message\ResponseException) { + // any HTTP response error message will now end up here + $response = $e->getResponse(); + var_dump($response->getStatusCode(), $response->getReasonPhrase()); + } else { + var_dump($e->getMessage()); + } +}); +``` + +Notice that the [`Browser`](#browser) is an immutable object, i.e. this +method actually returns a *new* [`Browser`](#browser) instance with the +given setting applied. + +#### withBase() + +The `withBase(string|null $baseUrl): Browser` method can be used to +change the base URL used to resolve relative URLs to. + +If you configure a base URL, any requests to relative URLs will be +processed by first resolving this relative to the given absolute base +URL. This supports resolving relative path references (like `../` etc.). +This is particularly useful for (RESTful) API calls where all endpoints +(URLs) are located under a common base URL. + +```php +$browser = $browser->withBase('http://api.example.com/v3/'); + +// will request http://api.example.com/v3/users +$browser->get('users')->then(…); +``` + +You can pass in a `null` base URL to return a new instance that does not +use a base URL: + +```php +$browser = $browser->withBase(null); +``` + +Accordingly, any requests using relative URLs to a browser that does not +use a base URL can not be completed and will be rejected without sending +a request. + +This method will throw an `InvalidArgumentException` if the given +`$baseUrl` argument is not a valid URL. + +Notice that the [`Browser`](#browser) is an immutable object, i.e. the `withBase()` method +actually returns a *new* [`Browser`](#browser) instance with the given base URL applied. + +#### withProtocolVersion() + +The `withProtocolVersion(string $protocolVersion): Browser` method can be used to +change the HTTP protocol version that will be used for all subsequent requests. + +All the above [request methods](#request-methods) default to sending +requests as HTTP/1.1. This is the preferred HTTP protocol version which +also provides decent backwards-compatibility with legacy HTTP/1.0 +servers. As such, there should rarely be a need to explicitly change this +protocol version. + +If you want to explicitly use the legacy HTTP/1.0 protocol version, you +can use this method: + +```php +$browser = $browser->withProtocolVersion('1.0'); + +$browser->get($url)->then(…); +``` + +Notice that the [`Browser`](#browser) is an immutable object, i.e. this +method actually returns a *new* [`Browser`](#browser) instance with the +new protocol version applied. + +#### withResponseBuffer() + +The `withResponseBuffer(int $maximumSize): Browser` method can be used to +change the maximum size for buffering a response body. + +The preferred way to send an HTTP request is by using the above +[request methods](#request-methods), for example the [`get()`](#get) +method to send an HTTP `GET` request. Each of these methods will buffer +the whole response body in memory by default. This is easy to get started +and works reasonably well for smaller responses. + +By default, the response body buffer will be limited to 16 MiB. If the +response body exceeds this maximum size, the request will be rejected. + +You can pass in the maximum number of bytes to buffer: + +```php +$browser = $browser->withResponseBuffer(1024 * 1024); + +$browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + // response body will not exceed 1 MiB + var_dump($response->getHeaders(), (string) $response->getBody()); +}); +``` + +Note that the response body buffer has to be kept in memory for each +pending request until its transfer is completed and it will only be freed +after a pending request is fulfilled. As such, increasing this maximum +buffer size to allow larger response bodies is usually not recommended. +Instead, you can use the [`requestStreaming()` method](#requeststreaming) +to receive responses with arbitrary sizes without buffering. Accordingly, +this maximum buffer size setting has no effect on streaming responses. + +Notice that the [`Browser`](#browser) is an immutable object, i.e. this +method actually returns a *new* [`Browser`](#browser) instance with the +given setting applied. + +### React\Http\Message + +#### Response + +The `React\Http\Message\Response` class can be used to +represent an outgoing server response message. + +```php +$response = new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/html' + ), + "Hello world!\n" +); +``` + +This class implements the +[PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) +which in turn extends the +[PSR-7 `MessageInterface`](https://www.php-fig.org/psr/psr-7/#31-psrhttpmessagemessageinterface). + +> Internally, this implementation builds on top of an existing incoming + response message and only adds required streaming support. This base class is + considered an implementation detail that may change in the future. + +#### ServerRequest + +The `React\Http\Message\ServerRequest` class can be used to +respresent an incoming server request message. + +This class implements the +[PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface) +which extends the +[PSR-7 `RequestInterface`](https://www.php-fig.org/psr/psr-7/#32-psrhttpmessagerequestinterface) +which in turn extends the +[PSR-7 `MessageInterface`](https://www.php-fig.org/psr/psr-7/#31-psrhttpmessagemessageinterface). + +This is mostly used internally to represent each incoming request message. +Likewise, you can also use this class in test cases to test how your web +application reacts to certain HTTP requests. + +> Internally, this implementation builds on top of an existing outgoing + request message and only adds required server methods. This base class is + considered an implementation detail that may change in the future. + +#### ResponseException + +The `React\Http\Message\ResponseException` is an `Exception` sub-class that will be used to reject +a request promise if the remote server returns a non-success status code +(anything but 2xx or 3xx). +You can control this behavior via the [`withRejectErrorResponse()` method](#withrejecterrorresponse). + +The `getCode(): int` method can be used to +return the HTTP response status code. + +The `getResponse(): ResponseInterface` method can be used to +access its underlying response object. + +### React\Http\Middleware + +#### StreamingRequestMiddleware + +The `React\Http\Middleware\StreamingRequestMiddleware` can be used to +process incoming requests with a streaming request body (without buffering). + +This allows you to process requests of any size without buffering the request +body in memory. Instead, it will represent the request body as a +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +that emit chunks of incoming data as it is received: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + function (Psr\Http\Message\ServerRequestInterface $request) { + $body = $request->getBody(); + assert($body instanceof Psr\Http\Message\StreamInterface); + assert($body instanceof React\Stream\ReadableStreamInterface); + + return new React\Promise\Promise(function ($resolve) use ($body) { + $bytes = 0; + $body->on('data', function ($chunk) use (&$bytes) { + $bytes += \count($chunk); + }); + $body->on('close', function () use (&$bytes, $resolve) { + $resolve(new React\Http\Message\Response( + 200, + [], + "Received $bytes bytes\n" + )); + }); + }); + } +); +``` + +See also [streaming incoming request](#streaming-incoming-request) +for more details. + +Additionally, this middleware can be used in combination with the +[`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and +[`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) +to explicitly configure the total number of requests that can be handled at +once: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + new React\Http\Middleware\RequestBodyParserMiddleware(), + $handler +); +``` + +> Internally, this class is used as a "marker" to not trigger the default + request buffering behavior in the `HttpServer`. It does not implement any logic + on its own. + +#### LimitConcurrentRequestsMiddleware + +The `React\Http\Middleware\LimitConcurrentRequestsMiddleware` can be used to +limit how many next handlers can be executed concurrently. + +If this middleware is invoked, it will check if the number of pending +handlers is below the allowed limit and then simply invoke the next handler +and it will return whatever the next handler returns (or throws). + +If the number of pending handlers exceeds the allowed limit, the request will +be queued (and its streaming body will be paused) and it will return a pending +promise. +Once a pending handler returns (or throws), it will pick the oldest request +from this queue and invokes the next handler (and its streaming body will be +resumed). + +The following example shows how this middleware can be used to ensure no more +than 10 handlers will be invoked at once: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(10), + $handler +); +``` + +Similarly, this middleware is often used in combination with the +[`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) +to limit the total number of requests that can be buffered at once: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + new React\Http\Middleware\RequestBodyParserMiddleware(), + $handler +); +``` + +More sophisticated examples include limiting the total number of requests +that can be buffered at once and then ensure the actual request handler only +processes one request after another without any concurrency: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + new React\Http\Middleware\RequestBodyParserMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(1), // only execute 1 handler (no concurrency) + $handler +); +``` + +#### RequestBodyBufferMiddleware + +One of the built-in middleware is the `React\Http\Middleware\RequestBodyBufferMiddleware` which +can be used to buffer the whole incoming request body in memory. +This can be useful if full PSR-7 compatibility is needed for the request handler +and the default streaming request body handling is not needed. +The constructor accepts one optional argument, the maximum request body size. +When one isn't provided it will use `post_max_size` (default 8 MiB) from PHP's +configuration. +(Note that the value from your matching SAPI will be used, which is the CLI +configuration in most cases.) + +Any incoming request that has a request body that exceeds this limit will be +accepted, but its request body will be discarded (empty request body). +This is done in order to avoid having to keep an incoming request with an +excessive size (for example, think of a 2 GB file upload) in memory. +This allows the next middleware handler to still handle this request, but it +will see an empty request body. +This is similar to PHP's default behavior, where the body will not be parsed +if this limit is exceeded. However, unlike PHP's default behavior, the raw +request body is not available via `php://input`. + +The `RequestBodyBufferMiddleware` will buffer requests with bodies of known size +(i.e. with `Content-Length` header specified) as well as requests with bodies of +unknown size (i.e. with `Transfer-Encoding: chunked` header). + +All requests will be buffered in memory until the request body end has +been reached and then call the next middleware handler with the complete, +buffered request. +Similarly, this will immediately invoke the next middleware handler for requests +that have an empty request body (such as a simple `GET` request) and requests +that are already buffered (such as due to another middleware). + +Note that the given buffer size limit is applied to each request individually. +This means that if you allow a 2 MiB limit and then receive 1000 concurrent +requests, up to 2000 MiB may be allocated for these buffers alone. +As such, it's highly recommended to use this along with the +[`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) (see above) to limit +the total number of concurrent requests. + +Usage: + +```php +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(16 * 1024 * 1024), // 16 MiB + function (Psr\Http\Message\ServerRequestInterface $request) { + // The body from $request->getBody() is now fully available without the need to stream it + return new React\Http\Message\Response(200); + }, +); +``` + +#### RequestBodyParserMiddleware + +The `React\Http\Middleware\RequestBodyParserMiddleware` takes a fully buffered request body +(generally from [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware)), +and parses the form values and file uploads from the incoming HTTP request body. + +This middleware handler takes care of applying values from HTTP +requests that use `Content-Type: application/x-www-form-urlencoded` or +`Content-Type: multipart/form-data` to resemble PHP's default superglobals +`$_POST` and `$_FILES`. +Instead of relying on these superglobals, you can use the +`$request->getParsedBody()` and `$request->getUploadedFiles()` methods +as defined by PSR-7. + +Accordingly, each file upload will be represented as instance implementing the +[PSR-7 `UploadedFileInterface`](https://www.php-fig.org/psr/psr-7/#36-psrhttpmessageuploadedfileinterface). +Due to its blocking nature, the `moveTo()` method is not available and throws +a `RuntimeException` instead. +You can use `$contents = (string)$file->getStream();` to access the file +contents and persist this to your favorite data store. + +```php +$handler = function (Psr\Http\Message\ServerRequestInterface $request) { + // If any, parsed form fields are now available from $request->getParsedBody() + $body = $request->getParsedBody(); + $name = isset($body['name']) ? $body['name'] : 'unnamed'; + + $files = $request->getUploadedFiles(); + $avatar = isset($files['avatar']) ? $files['avatar'] : null; + if ($avatar instanceof Psr\Http\Message\UploadedFileInterface) { + if ($avatar->getError() === UPLOAD_ERR_OK) { + $uploaded = $avatar->getSize() . ' bytes'; + } elseif ($avatar->getError() === UPLOAD_ERR_INI_SIZE) { + $uploaded = 'file too large'; + } else { + $uploaded = 'with error'; + } + } else { + $uploaded = 'nothing'; + } + + return new React\Http\Message\Response( + 200, + array( + 'Content-Type' => 'text/plain' + ), + $name . ' uploaded ' . $uploaded + ); +}; + +$http = new React\Http\HttpServer( + new React\Http\Middleware\StreamingRequestMiddleware(), + new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + new React\Http\Middleware\RequestBodyBufferMiddleware(16 * 1024 * 1024), // 16 MiB + new React\Http\Middleware\RequestBodyParserMiddleware(), + $handler +); +``` + +See also [form upload server example](examples/62-server-form-upload.php) for more details. + +By default, this middleware respects the +[`upload_max_filesize`](https://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize) +(default `2M`) ini setting. +Files that exceed this limit will be rejected with an `UPLOAD_ERR_INI_SIZE` error. +You can control the maximum filesize for each individual file upload by +explicitly passing the maximum filesize in bytes as the first parameter to the +constructor like this: + +```php +new React\Http\Middleware\RequestBodyParserMiddleware(8 * 1024 * 1024); // 8 MiB limit per file +``` + +By default, this middleware respects the +[`file_uploads`](https://www.php.net/manual/en/ini.core.php#ini.file-uploads) +(default `1`) and +[`max_file_uploads`](https://www.php.net/manual/en/ini.core.php#ini.max-file-uploads) +(default `20`) ini settings. +These settings control if any and how many files can be uploaded in a single request. +If you upload more files in a single request, additional files will be ignored +and the `getUploadedFiles()` method returns a truncated array. +Note that upload fields left blank on submission do not count towards this limit. +You can control the maximum number of file uploads per request by explicitly +passing the second parameter to the constructor like this: + +```php +new React\Http\Middleware\RequestBodyParserMiddleware(10 * 1024, 100); // 100 files with 10 KiB each +``` + +> Note that this middleware handler simply parses everything that is already + buffered in the request body. + It is imperative that the request body is buffered by a prior middleware + handler as given in the example above. + This previous middleware handler is also responsible for rejecting incoming + requests that exceed allowed message sizes (such as big file uploads). + The [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) used above + simply discards excessive request bodies, resulting in an empty body. + If you use this middleware without buffering first, it will try to parse an + empty (streaming) body and may thus assume an empty data structure. + See also [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) for + more details. + +> PHP's `MAX_FILE_SIZE` hidden field is respected by this middleware. + Files that exceed this limit will be rejected with an `UPLOAD_ERR_FORM_SIZE` error. + +> This middleware respects the + [`max_input_vars`](https://www.php.net/manual/en/info.configuration.php#ini.max-input-vars) + (default `1000`) and + [`max_input_nesting_level`](https://www.php.net/manual/en/info.configuration.php#ini.max-input-nesting-level) + (default `64`) ini settings. + +> Note that this middleware ignores the + [`enable_post_data_reading`](https://www.php.net/manual/en/ini.core.php#ini.enable-post-data-reading) + (default `1`) ini setting because it makes little sense to respect here and + is left up to higher-level implementations. + If you want to respect this setting, you have to check its value and + effectively avoid using this middleware entirely. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/http:^1.5 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +$ php vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/composer.json new file mode 100644 index 0000000..44387e5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/composer.json @@ -0,0 +1,52 @@ +{ + "name": "react/http", + "description": "Event-driven, streaming HTTP client and server implementation for ReactPHP", + "keywords": ["HTTP client", "HTTP server", "HTTP", "HTTPS", "event-driven", "streaming", "client", "server", "PSR-7", "async", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "psr/http-message": "^1.0", + "react/event-loop": "^1.2", + "react/promise": "^2.3 || ^1.2.1", + "react/promise-stream": "^1.1", + "react/socket": "^1.9", + "react/stream": "^1.2", + "ringcentral/psr7": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.1", + "clue/http-proxy-react": "^1.3", + "clue/reactphp-ssh-proxy": "^1.0", + "clue/socks-react": "^1.0", + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + }, + "autoload": { + "psr-4": { "React\\Http\\": "src" } + }, + "autoload-dev": { + "psr-4": { "React\\Tests\\Http\\": "tests" } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Browser.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Browser.php new file mode 100644 index 0000000..5879b97 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Browser.php @@ -0,0 +1,766 @@ + '127.0.0.1', + * 'tcp' => array( + * 'bindto' => '192.168.10.1:0' + * ), + * 'tls' => array( + * 'verify_peer' => false, + * 'verify_peer_name' => false + * ) + * )); + * + * $browser = new React\Http\Browser($connector); + * ``` + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * @param null|ConnectorInterface|LoopInterface $connector + * @param null|LoopInterface|ConnectorInterface $loop + * @throws \InvalidArgumentException for invalid arguments + */ + public function __construct($connector = null, $loop = null) + { + // swap arguments for legacy constructor signature + if (($connector instanceof LoopInterface || $connector === null) && ($loop instanceof ConnectorInterface || $loop === null)) { + $swap = $loop; + $loop = $connector; + $connector = $swap; + } + + if (($connector !== null && !$connector instanceof ConnectorInterface) || ($loop !== null && !$loop instanceof LoopInterface)) { + throw new \InvalidArgumentException('Expected "?ConnectorInterface $connector" and "?LoopInterface $loop" arguments'); + } + + $loop = $loop ?: Loop::get(); + $this->transaction = new Transaction( + Sender::createFromLoop($loop, $connector), + $loop + ); + } + + /** + * Sends an HTTP GET request + * + * ```php + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump((string)$response->getBody()); + * }); + * ``` + * + * See also [GET request client example](../examples/01-client-get-request.php). + * + * @param string $url URL for the request. + * @param array $headers + * @return PromiseInterface + */ + public function get($url, array $headers = array()) + { + return $this->requestMayBeStreaming('GET', $url, $headers); + } + + /** + * Sends an HTTP POST request + * + * ```php + * $browser->post( + * $url, + * [ + * 'Content-Type' => 'application/json' + * ], + * json_encode($data) + * )->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump(json_decode((string)$response->getBody())); + * }); + * ``` + * + * See also [POST JSON client example](../examples/04-client-post-json.php). + * + * This method is also commonly used to submit HTML form data: + * + * ```php + * $data = [ + * 'user' => 'Alice', + * 'password' => 'secret' + * ]; + * + * $browser->post( + * $url, + * [ + * 'Content-Type' => 'application/x-www-form-urlencoded' + * ], + * http_build_query($data) + * ); + * ``` + * + * This method will automatically add a matching `Content-Length` request + * header if the outgoing request body is a `string`. If you're using a + * streaming request body (`ReadableStreamInterface`), it will default to + * using `Transfer-Encoding: chunked` or you have to explicitly pass in a + * matching `Content-Length` request header like so: + * + * ```php + * $body = new React\Stream\ThroughStream(); + * Loop::addTimer(1.0, function () use ($body) { + * $body->end("hello world"); + * }); + * + * $browser->post($url, array('Content-Length' => '11'), $body); + * ``` + * + * @param string $url URL for the request. + * @param array $headers + * @param string|ReadableStreamInterface $contents + * @return PromiseInterface + */ + public function post($url, array $headers = array(), $contents = '') + { + return $this->requestMayBeStreaming('POST', $url, $headers, $contents); + } + + /** + * Sends an HTTP HEAD request + * + * ```php + * $browser->head($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump($response->getHeaders()); + * }); + * ``` + * + * @param string $url URL for the request. + * @param array $headers + * @return PromiseInterface + */ + public function head($url, array $headers = array()) + { + return $this->requestMayBeStreaming('HEAD', $url, $headers); + } + + /** + * Sends an HTTP PATCH request + * + * ```php + * $browser->patch( + * $url, + * [ + * 'Content-Type' => 'application/json' + * ], + * json_encode($data) + * )->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump(json_decode((string)$response->getBody())); + * }); + * ``` + * + * This method will automatically add a matching `Content-Length` request + * header if the outgoing request body is a `string`. If you're using a + * streaming request body (`ReadableStreamInterface`), it will default to + * using `Transfer-Encoding: chunked` or you have to explicitly pass in a + * matching `Content-Length` request header like so: + * + * ```php + * $body = new React\Stream\ThroughStream(); + * Loop::addTimer(1.0, function () use ($body) { + * $body->end("hello world"); + * }); + * + * $browser->patch($url, array('Content-Length' => '11'), $body); + * ``` + * + * @param string $url URL for the request. + * @param array $headers + * @param string|ReadableStreamInterface $contents + * @return PromiseInterface + */ + public function patch($url, array $headers = array(), $contents = '') + { + return $this->requestMayBeStreaming('PATCH', $url , $headers, $contents); + } + + /** + * Sends an HTTP PUT request + * + * ```php + * $browser->put( + * $url, + * [ + * 'Content-Type' => 'text/xml' + * ], + * $xml->asXML() + * )->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump((string)$response->getBody()); + * }); + * ``` + * + * See also [PUT XML client example](../examples/05-client-put-xml.php). + * + * This method will automatically add a matching `Content-Length` request + * header if the outgoing request body is a `string`. If you're using a + * streaming request body (`ReadableStreamInterface`), it will default to + * using `Transfer-Encoding: chunked` or you have to explicitly pass in a + * matching `Content-Length` request header like so: + * + * ```php + * $body = new React\Stream\ThroughStream(); + * Loop::addTimer(1.0, function () use ($body) { + * $body->end("hello world"); + * }); + * + * $browser->put($url, array('Content-Length' => '11'), $body); + * ``` + * + * @param string $url URL for the request. + * @param array $headers + * @param string|ReadableStreamInterface $contents + * @return PromiseInterface + */ + public function put($url, array $headers = array(), $contents = '') + { + return $this->requestMayBeStreaming('PUT', $url, $headers, $contents); + } + + /** + * Sends an HTTP DELETE request + * + * ```php + * $browser->delete($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump((string)$response->getBody()); + * }); + * ``` + * + * @param string $url URL for the request. + * @param array $headers + * @param string|ReadableStreamInterface $contents + * @return PromiseInterface + */ + public function delete($url, array $headers = array(), $contents = '') + { + return $this->requestMayBeStreaming('DELETE', $url, $headers, $contents); + } + + /** + * Sends an arbitrary HTTP request. + * + * The preferred way to send an HTTP request is by using the above + * [request methods](#request-methods), for example the [`get()`](#get) + * method to send an HTTP `GET` request. + * + * As an alternative, if you want to use a custom HTTP request method, you + * can use this method: + * + * ```php + * $browser->request('OPTIONS', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * var_dump((string)$response->getBody()); + * }); + * ``` + * + * This method will automatically add a matching `Content-Length` request + * header if the size of the outgoing request body is known and non-empty. + * For an empty request body, if will only include a `Content-Length: 0` + * request header if the request method usually expects a request body (only + * applies to `POST`, `PUT` and `PATCH`). + * + * If you're using a streaming request body (`ReadableStreamInterface`), it + * will default to using `Transfer-Encoding: chunked` or you have to + * explicitly pass in a matching `Content-Length` request header like so: + * + * ```php + * $body = new React\Stream\ThroughStream(); + * Loop::addTimer(1.0, function () use ($body) { + * $body->end("hello world"); + * }); + * + * $browser->request('POST', $url, array('Content-Length' => '11'), $body); + * ``` + * + * @param string $method HTTP request method, e.g. GET/HEAD/POST etc. + * @param string $url URL for the request + * @param array $headers Additional request headers + * @param string|ReadableStreamInterface $body HTTP request body contents + * @return PromiseInterface + */ + public function request($method, $url, array $headers = array(), $body = '') + { + return $this->withOptions(array('streaming' => false))->requestMayBeStreaming($method, $url, $headers, $body); + } + + /** + * Sends an arbitrary HTTP request and receives a streaming response without buffering the response body. + * + * The preferred way to send an HTTP request is by using the above + * [request methods](#request-methods), for example the [`get()`](#get) + * method to send an HTTP `GET` request. Each of these methods will buffer + * the whole response body in memory by default. This is easy to get started + * and works reasonably well for smaller responses. + * + * In some situations, it's a better idea to use a streaming approach, where + * only small chunks have to be kept in memory. You can use this method to + * send an arbitrary HTTP request and receive a streaming response. It uses + * the same HTTP message API, but does not buffer the response body in + * memory. It only processes the response body in small chunks as data is + * received and forwards this data through [ReactPHP's Stream API](https://github.com/reactphp/stream). + * This works for (any number of) responses of arbitrary sizes. + * + * ```php + * $browser->requestStreaming('GET', $url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * $body = $response->getBody(); + * assert($body instanceof Psr\Http\Message\StreamInterface); + * assert($body instanceof React\Stream\ReadableStreamInterface); + * + * $body->on('data', function ($chunk) { + * echo $chunk; + * }); + * + * $body->on('error', function (Exception $error) { + * echo 'Error: ' . $error->getMessage() . PHP_EOL; + * }); + * + * $body->on('close', function () { + * echo '[DONE]' . PHP_EOL; + * }); + * }); + * ``` + * + * See also [`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) + * and the [streaming response](#streaming-response) for more details, + * examples and possible use-cases. + * + * This method will automatically add a matching `Content-Length` request + * header if the size of the outgoing request body is known and non-empty. + * For an empty request body, if will only include a `Content-Length: 0` + * request header if the request method usually expects a request body (only + * applies to `POST`, `PUT` and `PATCH`). + * + * If you're using a streaming request body (`ReadableStreamInterface`), it + * will default to using `Transfer-Encoding: chunked` or you have to + * explicitly pass in a matching `Content-Length` request header like so: + * + * ```php + * $body = new React\Stream\ThroughStream(); + * Loop::addTimer(1.0, function () use ($body) { + * $body->end("hello world"); + * }); + * + * $browser->requestStreaming('POST', $url, array('Content-Length' => '11'), $body); + * ``` + * + * @param string $method HTTP request method, e.g. GET/HEAD/POST etc. + * @param string $url URL for the request + * @param array $headers Additional request headers + * @param string|ReadableStreamInterface $body HTTP request body contents + * @return PromiseInterface + */ + public function requestStreaming($method, $url, $headers = array(), $body = '') + { + return $this->withOptions(array('streaming' => true))->requestMayBeStreaming($method, $url, $headers, $body); + } + + /** + * Changes the maximum timeout used for waiting for pending requests. + * + * You can pass in the number of seconds to use as a new timeout value: + * + * ```php + * $browser = $browser->withTimeout(10.0); + * ``` + * + * You can pass in a bool `false` to disable any timeouts. In this case, + * requests can stay pending forever: + * + * ```php + * $browser = $browser->withTimeout(false); + * ``` + * + * You can pass in a bool `true` to re-enable default timeout handling. This + * will respects PHP's `default_socket_timeout` setting (default 60s): + * + * ```php + * $browser = $browser->withTimeout(true); + * ``` + * + * See also [timeouts](#timeouts) for more details about timeout handling. + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * given timeout value applied. + * + * @param bool|number $timeout + * @return self + */ + public function withTimeout($timeout) + { + if ($timeout === true) { + $timeout = null; + } elseif ($timeout === false) { + $timeout = -1; + } elseif ($timeout < 0) { + $timeout = 0; + } + + return $this->withOptions(array( + 'timeout' => $timeout, + )); + } + + /** + * Changes how HTTP redirects will be followed. + * + * You can pass in the maximum number of redirects to follow: + * + * ```php + * $browser = $browser->withFollowRedirects(5); + * ``` + * + * The request will automatically be rejected when the number of redirects + * is exceeded. You can pass in a `0` to reject the request for any + * redirects encountered: + * + * ```php + * $browser = $browser->withFollowRedirects(0); + * + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * // only non-redirected responses will now end up here + * var_dump($response->getHeaders()); + * }); + * ``` + * + * You can pass in a bool `false` to disable following any redirects. In + * this case, requests will resolve with the redirection response instead + * of following the `Location` response header: + * + * ```php + * $browser = $browser->withFollowRedirects(false); + * + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * // any redirects will now end up here + * var_dump($response->getHeaderLine('Location')); + * }); + * ``` + * + * You can pass in a bool `true` to re-enable default redirect handling. + * This defaults to following a maximum of 10 redirects: + * + * ```php + * $browser = $browser->withFollowRedirects(true); + * ``` + * + * See also [redirects](#redirects) for more details about redirect handling. + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * given redirect setting applied. + * + * @param bool|int $followRedirects + * @return self + */ + public function withFollowRedirects($followRedirects) + { + return $this->withOptions(array( + 'followRedirects' => $followRedirects !== false, + 'maxRedirects' => \is_bool($followRedirects) ? null : $followRedirects + )); + } + + /** + * Changes whether non-successful HTTP response status codes (4xx and 5xx) will be rejected. + * + * You can pass in a bool `false` to disable rejecting incoming responses + * that use a 4xx or 5xx response status code. In this case, requests will + * resolve with the response message indicating an error condition: + * + * ```php + * $browser = $browser->withRejectErrorResponse(false); + * + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * // any HTTP response will now end up here + * var_dump($response->getStatusCode(), $response->getReasonPhrase()); + * }); + * ``` + * + * You can pass in a bool `true` to re-enable default status code handling. + * This defaults to rejecting any response status codes in the 4xx or 5xx + * range: + * + * ```php + * $browser = $browser->withRejectErrorResponse(true); + * + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * // any successful HTTP response will now end up here + * var_dump($response->getStatusCode(), $response->getReasonPhrase()); + * }, function (Exception $e) { + * if ($e instanceof React\Http\Message\ResponseException) { + * // any HTTP response error message will now end up here + * $response = $e->getResponse(); + * var_dump($response->getStatusCode(), $response->getReasonPhrase()); + * } else { + * var_dump($e->getMessage()); + * } + * }); + * ``` + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * given setting applied. + * + * @param bool $obeySuccessCode + * @return self + */ + public function withRejectErrorResponse($obeySuccessCode) + { + return $this->withOptions(array( + 'obeySuccessCode' => $obeySuccessCode, + )); + } + + /** + * Changes the base URL used to resolve relative URLs to. + * + * If you configure a base URL, any requests to relative URLs will be + * processed by first resolving this relative to the given absolute base + * URL. This supports resolving relative path references (like `../` etc.). + * This is particularly useful for (RESTful) API calls where all endpoints + * (URLs) are located under a common base URL. + * + * ```php + * $browser = $browser->withBase('http://api.example.com/v3/'); + * + * // will request http://api.example.com/v3/users + * $browser->get('users')->then(…); + * ``` + * + * You can pass in a `null` base URL to return a new instance that does not + * use a base URL: + * + * ```php + * $browser = $browser->withBase(null); + * ``` + * + * Accordingly, any requests using relative URLs to a browser that does not + * use a base URL can not be completed and will be rejected without sending + * a request. + * + * This method will throw an `InvalidArgumentException` if the given + * `$baseUrl` argument is not a valid URL. + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. the `withBase()` method + * actually returns a *new* [`Browser`](#browser) instance with the given base URL applied. + * + * @param string|null $baseUrl absolute base URL + * @return self + * @throws InvalidArgumentException if the given $baseUrl is not a valid absolute URL + * @see self::withoutBase() + */ + public function withBase($baseUrl) + { + $browser = clone $this; + if ($baseUrl === null) { + $browser->baseUrl = null; + return $browser; + } + + $browser->baseUrl = new Uri($baseUrl); + if (!\in_array($browser->baseUrl->getScheme(), array('http', 'https')) || $browser->baseUrl->getHost() === '') { + throw new \InvalidArgumentException('Base URL must be absolute'); + } + + return $browser; + } + + /** + * Changes the HTTP protocol version that will be used for all subsequent requests. + * + * All the above [request methods](#request-methods) default to sending + * requests as HTTP/1.1. This is the preferred HTTP protocol version which + * also provides decent backwards-compatibility with legacy HTTP/1.0 + * servers. As such, there should rarely be a need to explicitly change this + * protocol version. + * + * If you want to explicitly use the legacy HTTP/1.0 protocol version, you + * can use this method: + * + * ```php + * $browser = $browser->withProtocolVersion('1.0'); + * + * $browser->get($url)->then(…); + * ``` + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * new protocol version applied. + * + * @param string $protocolVersion HTTP protocol version to use, must be one of "1.1" or "1.0" + * @return self + * @throws InvalidArgumentException + */ + public function withProtocolVersion($protocolVersion) + { + if (!\in_array($protocolVersion, array('1.0', '1.1'), true)) { + throw new InvalidArgumentException('Invalid HTTP protocol version, must be one of "1.1" or "1.0"'); + } + + $browser = clone $this; + $browser->protocolVersion = (string) $protocolVersion; + + return $browser; + } + + /** + * Changes the maximum size for buffering a response body. + * + * The preferred way to send an HTTP request is by using the above + * [request methods](#request-methods), for example the [`get()`](#get) + * method to send an HTTP `GET` request. Each of these methods will buffer + * the whole response body in memory by default. This is easy to get started + * and works reasonably well for smaller responses. + * + * By default, the response body buffer will be limited to 16 MiB. If the + * response body exceeds this maximum size, the request will be rejected. + * + * You can pass in the maximum number of bytes to buffer: + * + * ```php + * $browser = $browser->withResponseBuffer(1024 * 1024); + * + * $browser->get($url)->then(function (Psr\Http\Message\ResponseInterface $response) { + * // response body will not exceed 1 MiB + * var_dump($response->getHeaders(), (string) $response->getBody()); + * }); + * ``` + * + * Note that the response body buffer has to be kept in memory for each + * pending request until its transfer is completed and it will only be freed + * after a pending request is fulfilled. As such, increasing this maximum + * buffer size to allow larger response bodies is usually not recommended. + * Instead, you can use the [`requestStreaming()` method](#requeststreaming) + * to receive responses with arbitrary sizes without buffering. Accordingly, + * this maximum buffer size setting has no effect on streaming responses. + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * given setting applied. + * + * @param int $maximumSize + * @return self + * @see self::requestStreaming() + */ + public function withResponseBuffer($maximumSize) + { + return $this->withOptions(array( + 'maximumSize' => $maximumSize + )); + } + + /** + * Changes the [options](#options) to use: + * + * The [`Browser`](#browser) class exposes several options for the handling of + * HTTP transactions. These options resemble some of PHP's + * [HTTP context options](http://php.net/manual/en/context.http.php) and + * can be controlled via the following API (and their defaults): + * + * ```php + * // deprecated + * $newBrowser = $browser->withOptions(array( + * 'timeout' => null, // see withTimeout() instead + * 'followRedirects' => true, // see withFollowRedirects() instead + * 'maxRedirects' => 10, // see withFollowRedirects() instead + * 'obeySuccessCode' => true, // see withRejectErrorResponse() instead + * 'streaming' => false, // deprecated, see requestStreaming() instead + * )); + * ``` + * + * See also [timeouts](#timeouts), [redirects](#redirects) and + * [streaming](#streaming) for more details. + * + * Notice that the [`Browser`](#browser) is an immutable object, i.e. this + * method actually returns a *new* [`Browser`](#browser) instance with the + * options applied. + * + * @param array $options + * @return self + * @see self::withTimeout() + * @see self::withFollowRedirects() + * @see self::withRejectErrorResponse() + */ + private function withOptions(array $options) + { + $browser = clone $this; + $browser->transaction = $this->transaction->withOptions($options); + + return $browser; + } + + /** + * @param string $method + * @param string $url + * @param array $headers + * @param string|ReadableStreamInterface $body + * @return PromiseInterface + */ + private function requestMayBeStreaming($method, $url, array $headers = array(), $body = '') + { + if ($this->baseUrl !== null) { + // ensure we're actually below the base URL + $url = Uri::resolve($this->baseUrl, $url); + } + + if ($body instanceof ReadableStreamInterface) { + $body = new ReadableBodyStream($body); + } + + return $this->transaction->send( + new Request($method, $url, $headers, $body, $this->protocolVersion) + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Client.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Client.php new file mode 100644 index 0000000..7a97349 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Client.php @@ -0,0 +1,31 @@ +connector = $connector; + } + + public function request($method, $url, array $headers = array(), $protocolVersion = '1.0') + { + $requestData = new RequestData($method, $url, $headers, $protocolVersion); + + return new Request($this->connector, $requestData); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Request.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Request.php new file mode 100644 index 0000000..51e0331 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/Request.php @@ -0,0 +1,237 @@ +connector = $connector; + $this->requestData = $requestData; + } + + public function isWritable() + { + return self::STATE_END > $this->state && !$this->ended; + } + + private function writeHead() + { + $this->state = self::STATE_WRITING_HEAD; + + $requestData = $this->requestData; + $streamRef = &$this->stream; + $stateRef = &$this->state; + $pendingWrites = &$this->pendingWrites; + $that = $this; + + $promise = $this->connect(); + $promise->then( + function (ConnectionInterface $stream) use ($requestData, &$streamRef, &$stateRef, &$pendingWrites, $that) { + $streamRef = $stream; + + $stream->on('drain', array($that, 'handleDrain')); + $stream->on('data', array($that, 'handleData')); + $stream->on('end', array($that, 'handleEnd')); + $stream->on('error', array($that, 'handleError')); + $stream->on('close', array($that, 'handleClose')); + + $headers = (string) $requestData; + + $more = $stream->write($headers . $pendingWrites); + + $stateRef = Request::STATE_HEAD_WRITTEN; + + // clear pending writes if non-empty + if ($pendingWrites !== '') { + $pendingWrites = ''; + + if ($more) { + $that->emit('drain'); + } + } + }, + array($this, 'closeError') + ); + + $this->on('close', function() use ($promise) { + $promise->cancel(); + }); + } + + public function write($data) + { + if (!$this->isWritable()) { + return false; + } + + // write directly to connection stream if already available + if (self::STATE_HEAD_WRITTEN <= $this->state) { + return $this->stream->write($data); + } + + // otherwise buffer and try to establish connection + $this->pendingWrites .= $data; + if (self::STATE_WRITING_HEAD > $this->state) { + $this->writeHead(); + } + + return false; + } + + public function end($data = null) + { + if (!$this->isWritable()) { + return; + } + + if (null !== $data) { + $this->write($data); + } else if (self::STATE_WRITING_HEAD > $this->state) { + $this->writeHead(); + } + + $this->ended = true; + } + + /** @internal */ + public function handleDrain() + { + $this->emit('drain'); + } + + /** @internal */ + public function handleData($data) + { + $this->buffer .= $data; + + // buffer until double CRLF (or double LF for compatibility with legacy servers) + if (false !== strpos($this->buffer, "\r\n\r\n") || false !== strpos($this->buffer, "\n\n")) { + try { + $response = gPsr\parse_response($this->buffer); + $bodyChunk = (string) $response->getBody(); + } catch (\InvalidArgumentException $exception) { + $this->emit('error', array($exception)); + } + + $this->buffer = null; + + $this->stream->removeListener('drain', array($this, 'handleDrain')); + $this->stream->removeListener('data', array($this, 'handleData')); + $this->stream->removeListener('end', array($this, 'handleEnd')); + $this->stream->removeListener('error', array($this, 'handleError')); + $this->stream->removeListener('close', array($this, 'handleClose')); + + if (!isset($response)) { + return; + } + + $this->stream->on('close', array($this, 'handleClose')); + + $this->emit('response', array($response, $this->stream)); + + $this->stream->emit('data', array($bodyChunk)); + } + } + + /** @internal */ + public function handleEnd() + { + $this->closeError(new \RuntimeException( + "Connection ended before receiving response" + )); + } + + /** @internal */ + public function handleError(\Exception $error) + { + $this->closeError(new \RuntimeException( + "An error occurred in the underlying stream", + 0, + $error + )); + } + + /** @internal */ + public function handleClose() + { + $this->close(); + } + + /** @internal */ + public function closeError(\Exception $error) + { + if (self::STATE_END <= $this->state) { + return; + } + $this->emit('error', array($error)); + $this->close(); + } + + public function close() + { + if (self::STATE_END <= $this->state) { + return; + } + + $this->state = self::STATE_END; + $this->pendingWrites = ''; + + if ($this->stream) { + $this->stream->close(); + } + + $this->emit('close'); + $this->removeAllListeners(); + } + + protected function connect() + { + $scheme = $this->requestData->getScheme(); + if ($scheme !== 'https' && $scheme !== 'http') { + return Promise\reject( + new \InvalidArgumentException('Invalid request URL given') + ); + } + + $host = $this->requestData->getHost(); + $port = $this->requestData->getPort(); + + if ($scheme === 'https') { + $host = 'tls://' . $host; + } + + return $this->connector + ->connect($host . ':' . $port); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/RequestData.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/RequestData.php new file mode 100644 index 0000000..a5908a0 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Client/RequestData.php @@ -0,0 +1,128 @@ +method = $method; + $this->url = $url; + $this->headers = $headers; + $this->protocolVersion = $protocolVersion; + } + + private function mergeDefaultheaders(array $headers) + { + $port = ($this->getDefaultPort() === $this->getPort()) ? '' : ":{$this->getPort()}"; + $connectionHeaders = ('1.1' === $this->protocolVersion) ? array('Connection' => 'close') : array(); + $authHeaders = $this->getAuthHeaders(); + + $defaults = array_merge( + array( + 'Host' => $this->getHost().$port, + 'User-Agent' => 'ReactPHP/1', + ), + $connectionHeaders, + $authHeaders + ); + + // remove all defaults that already exist in $headers + $lower = array_change_key_case($headers, CASE_LOWER); + foreach ($defaults as $key => $_) { + if (isset($lower[strtolower($key)])) { + unset($defaults[$key]); + } + } + + return array_merge($defaults, $headers); + } + + public function getScheme() + { + return parse_url($this->url, PHP_URL_SCHEME); + } + + public function getHost() + { + return parse_url($this->url, PHP_URL_HOST); + } + + public function getPort() + { + return (int) parse_url($this->url, PHP_URL_PORT) ?: $this->getDefaultPort(); + } + + public function getDefaultPort() + { + return ('https' === $this->getScheme()) ? 443 : 80; + } + + public function getPath() + { + $path = parse_url($this->url, PHP_URL_PATH); + $queryString = parse_url($this->url, PHP_URL_QUERY); + + // assume "/" path by default, but allow "OPTIONS *" + if ($path === null) { + $path = ($this->method === 'OPTIONS' && $queryString === null) ? '*': '/'; + } + if ($queryString !== null) { + $path .= '?' . $queryString; + } + + return $path; + } + + public function setProtocolVersion($version) + { + $this->protocolVersion = $version; + } + + public function __toString() + { + $headers = $this->mergeDefaultheaders($this->headers); + + $data = ''; + $data .= "{$this->method} {$this->getPath()} HTTP/{$this->protocolVersion}\r\n"; + foreach ($headers as $name => $values) { + foreach ((array)$values as $value) { + $data .= "$name: $value\r\n"; + } + } + $data .= "\r\n"; + + return $data; + } + + private function getUrlUserPass() + { + $components = parse_url($this->url); + + if (isset($components['user'])) { + return array( + 'user' => $components['user'], + 'pass' => isset($components['pass']) ? $components['pass'] : null, + ); + } + } + + private function getAuthHeaders() + { + if (null !== $auth = $this->getUrlUserPass()) { + return array( + 'Authorization' => 'Basic ' . base64_encode($auth['user'].':'.$auth['pass']), + ); + } + + return array(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/HttpServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/HttpServer.php new file mode 100644 index 0000000..d5f947d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/HttpServer.php @@ -0,0 +1,343 @@ + 'text/plain' + * ), + * "Hello World!\n" + * ); + * }); + * ``` + * + * Each incoming HTTP request message is always represented by the + * [PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface), + * see also following [request](#server-request) chapter for more details. + * + * Each outgoing HTTP response message is always represented by the + * [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface), + * see also following [response](#server-response) chapter for more details. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * In order to start listening for any incoming connections, the `HttpServer` needs + * to be attached to an instance of + * [`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface) + * through the [`listen()`](#listen) method as described in the following + * chapter. In its most simple form, you can attach this to a + * [`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) + * in order to start a plaintext HTTP server like this: + * + * ```php + * $http = new React\Http\HttpServer($handler); + * + * $socket = new React\Socket\SocketServer('0.0.0.0:8080'); + * $http->listen($socket); + * ``` + * + * See also the [`listen()`](#listen) method and + * [hello world server example](../examples/51-server-hello-world.php) + * for more details. + * + * By default, the `HttpServer` buffers and parses the complete incoming HTTP + * request in memory. It will invoke the given request handler function when the + * complete request headers and request body has been received. This means the + * [request](#server-request) object passed to your request handler function will be + * fully compatible with PSR-7 (http-message). This provides sane defaults for + * 80% of the use cases and is the recommended way to use this library unless + * you're sure you know what you're doing. + * + * On the other hand, buffering complete HTTP requests in memory until they can + * be processed by your request handler function means that this class has to + * employ a number of limits to avoid consuming too much memory. In order to + * take the more advanced configuration out your hand, it respects setting from + * your [`php.ini`](https://www.php.net/manual/en/ini.core.php) to apply its + * default settings. This is a list of PHP settings this class respects with + * their respective default values: + * + * ``` + * memory_limit 128M + * post_max_size 8M // capped at 64K + * + * enable_post_data_reading 1 + * max_input_nesting_level 64 + * max_input_vars 1000 + * + * file_uploads 1 + * upload_max_filesize 2M + * max_file_uploads 20 + * ``` + * + * In particular, the `post_max_size` setting limits how much memory a single + * HTTP request is allowed to consume while buffering its request body. This + * needs to be limited because the server can process a large number of requests + * concurrently, so the server may potentially consume a large amount of memory + * otherwise. To support higher concurrency by default, this value is capped + * at `64K`. If you assign a higher value, it will only allow `64K` by default. + * If a request exceeds this limit, its request body will be ignored and it will + * be processed like a request with no request body at all. See below for + * explicit configuration to override this setting. + * + * By default, this class will try to avoid consuming more than half of your + * `memory_limit` for buffering multiple concurrent HTTP requests. As such, with + * the above default settings of `128M` max, it will try to consume no more than + * `64M` for buffering multiple concurrent HTTP requests. As a consequence, it + * will limit the concurrency to `1024` HTTP requests with the above defaults. + * + * It is imperative that you assign reasonable values to your PHP ini settings. + * It is usually recommended to not support buffering incoming HTTP requests + * with a large HTTP request body (e.g. large file uploads). If you want to + * increase this buffer size, you will have to also increase the total memory + * limit to allow for more concurrent requests (set `memory_limit 512M` or more) + * or explicitly limit concurrency. + * + * In order to override the above buffering defaults, you can configure the + * `HttpServer` explicitly. You can use the + * [`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and + * [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) + * to explicitly configure the total number of requests that can be handled at + * once like this: + * + * ```php + * $http = new React\Http\HttpServer( + * new React\Http\Middleware\StreamingRequestMiddleware(), + * new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + * new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + * new React\Http\Middleware\RequestBodyParserMiddleware(), + * $handler + * )); + * ``` + * + * In this example, we allow processing up to 100 concurrent requests at once + * and each request can buffer up to `2M`. This means you may have to keep a + * maximum of `200M` of memory for incoming request body buffers. Accordingly, + * you need to adjust the `memory_limit` ini setting to allow for these buffers + * plus your actual application logic memory requirements (think `512M` or more). + * + * > Internally, this class automatically assigns these middleware handlers + * automatically when no [`StreamingRequestMiddleware`](#streamingrequestmiddleware) + * is given. Accordingly, you can use this example to override all default + * settings to implement custom limits. + * + * As an alternative to buffering the complete request body in memory, you can + * also use a streaming approach where only small chunks of data have to be kept + * in memory: + * + * ```php + * $http = new React\Http\HttpServer( + * new React\Http\Middleware\StreamingRequestMiddleware(), + * $handler + * ); + * ``` + * + * In this case, it will invoke the request handler function once the HTTP + * request headers have been received, i.e. before receiving the potentially + * much larger HTTP request body. This means the [request](#server-request) passed to + * your request handler function may not be fully compatible with PSR-7. This is + * specifically designed to help with more advanced use cases where you want to + * have full control over consuming the incoming HTTP request body and + * concurrency settings. See also [streaming incoming request](#streaming-incoming-request) + * below for more details. + * + * > Changelog v1.5.0: This class has been renamed to `HttpServer` from the + * previous `Server` class in order to avoid any ambiguities. + * The previous name has been deprecated and should not be used anymore. + */ +final class HttpServer extends EventEmitter +{ + /** + * The maximum buffer size used for each request. + * + * This needs to be limited because the server can process a large number of + * requests concurrently, so the server may potentially consume a large + * amount of memory otherwise. + * + * See `RequestBodyBufferMiddleware` to override this setting. + * + * @internal + */ + const MAXIMUM_BUFFER_SIZE = 65536; // 64 KiB + + /** + * @var StreamingServer + */ + private $streamingServer; + + /** + * Creates an HTTP server that invokes the given callback for each incoming HTTP request + * + * In order to process any connections, the server needs to be attached to an + * instance of `React\Socket\ServerInterface` which emits underlying streaming + * connections in order to then parse incoming data as HTTP. + * See also [listen()](#listen) for more details. + * + * @param callable|LoopInterface $requestHandlerOrLoop + * @param callable[] ...$requestHandler + * @see self::listen() + */ + public function __construct($requestHandlerOrLoop) + { + $requestHandlers = \func_get_args(); + if (reset($requestHandlers) instanceof LoopInterface) { + $loop = \array_shift($requestHandlers); + } else { + $loop = Loop::get(); + } + + $requestHandlersCount = \count($requestHandlers); + if ($requestHandlersCount === 0 || \count(\array_filter($requestHandlers, 'is_callable')) < $requestHandlersCount) { + throw new \InvalidArgumentException('Invalid request handler given'); + } + + $streaming = false; + foreach ((array) $requestHandlers as $handler) { + if ($handler instanceof StreamingRequestMiddleware) { + $streaming = true; + break; + } + } + + $middleware = array(); + if (!$streaming) { + $maxSize = $this->getMaxRequestSize(); + $concurrency = $this->getConcurrentRequestsLimit(\ini_get('memory_limit'), $maxSize); + if ($concurrency !== null) { + $middleware[] = new LimitConcurrentRequestsMiddleware($concurrency); + } + $middleware[] = new RequestBodyBufferMiddleware($maxSize); + // Checking for an empty string because that is what a boolean + // false is returned as by ini_get depending on the PHP version. + // @link http://php.net/manual/en/ini.core.php#ini.enable-post-data-reading + // @link http://php.net/manual/en/function.ini-get.php#refsect1-function.ini-get-notes + // @link https://3v4l.org/qJtsa + $enablePostDataReading = \ini_get('enable_post_data_reading'); + if ($enablePostDataReading !== '') { + $middleware[] = new RequestBodyParserMiddleware(); + } + } + + $middleware = \array_merge($middleware, $requestHandlers); + + $this->streamingServer = new StreamingServer($loop, new MiddlewareRunner($middleware)); + + $that = $this; + $this->streamingServer->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + }); + } + + /** + * Starts listening for HTTP requests on the given socket server instance + * + * The given [`React\Socket\ServerInterface`](https://github.com/reactphp/socket#serverinterface) + * is responsible for emitting the underlying streaming connections. This + * HTTP server needs to be attached to it in order to process any + * connections and pase incoming streaming data as incoming HTTP request + * messages. In its most common form, you can attach this to a + * [`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) + * in order to start a plaintext HTTP server like this: + * + * ```php + * $http = new React\Http\HttpServer($handler); + * + * $socket = new React\Socket\SocketServer('0.0.0.0:8080'); + * $http->listen($socket); + * ``` + * + * See also [hello world server example](../examples/51-server-hello-world.php) + * for more details. + * + * This example will start listening for HTTP requests on the alternative + * HTTP port `8080` on all interfaces (publicly). As an alternative, it is + * very common to use a reverse proxy and let this HTTP server listen on the + * localhost (loopback) interface only by using the listen address + * `127.0.0.1:8080` instead. This way, you host your application(s) on the + * default HTTP port `80` and only route specific requests to this HTTP + * server. + * + * Likewise, it's usually recommended to use a reverse proxy setup to accept + * secure HTTPS requests on default HTTPS port `443` (TLS termination) and + * only route plaintext requests to this HTTP server. As an alternative, you + * can also accept secure HTTPS requests with this HTTP server by attaching + * this to a [`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) + * using a secure TLS listen address, a certificate file and optional + * `passphrase` like this: + * + * ```php + * $http = new React\Http\HttpServer($handler); + * + * $socket = new React\Socket\SocketServer('tls://0.0.0.0:8443', array( + * 'tls' => array( + * 'local_cert' => __DIR__ . '/localhost.pem' + * ) + * )); + * $http->listen($socket); + * ``` + * + * See also [hello world HTTPS example](../examples/61-server-hello-world-https.php) + * for more details. + * + * @param ServerInterface $socket + */ + public function listen(ServerInterface $socket) + { + $this->streamingServer->listen($socket); + } + + /** + * @param string $memory_limit + * @param string $post_max_size + * @return ?int + */ + private function getConcurrentRequestsLimit($memory_limit, $post_max_size) + { + if ($memory_limit == -1) { + return null; + } + + $availableMemory = IniUtil::iniSizeToBytes($memory_limit) / 2; + $concurrentRequests = (int) \ceil($availableMemory / IniUtil::iniSizeToBytes($post_max_size)); + + return $concurrentRequests; + } + + /** + * @param ?string $post_max_size + * @return int + */ + private function getMaxRequestSize($post_max_size = null) + { + $maxSize = IniUtil::iniSizeToBytes($post_max_size === null ? \ini_get('post_max_size') : $post_max_size); + + return ($maxSize === 0 || $maxSize >= self::MAXIMUM_BUFFER_SIZE) ? self::MAXIMUM_BUFFER_SIZE : $maxSize; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/BufferedBody.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/BufferedBody.php new file mode 100644 index 0000000..2f81bc5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/BufferedBody.php @@ -0,0 +1,176 @@ +buffer = $buffer; + } + + public function __toString() + { + if ($this->closed) { + return ''; + } + + $this->seek(0); + + return $this->getContents(); + } + + public function close() + { + $this->buffer = ''; + $this->position = 0; + $this->closed = true; + } + + public function detach() + { + $this->close(); + + return null; + } + + public function getSize() + { + return $this->closed ? null : \strlen($this->buffer); + } + + public function tell() + { + if ($this->closed) { + throw new \RuntimeException('Unable to tell position of closed stream'); + } + + return $this->position; + } + + public function eof() + { + return $this->position >= \strlen($this->buffer); + } + + public function isSeekable() + { + return !$this->closed; + } + + public function seek($offset, $whence = \SEEK_SET) + { + if ($this->closed) { + throw new \RuntimeException('Unable to seek on closed stream'); + } + + $old = $this->position; + + if ($whence === \SEEK_SET) { + $this->position = $offset; + } elseif ($whence === \SEEK_CUR) { + $this->position += $offset; + } elseif ($whence === \SEEK_END) { + $this->position = \strlen($this->buffer) + $offset; + } else { + throw new \InvalidArgumentException('Invalid seek mode given'); + } + + if (!\is_int($this->position) || $this->position < 0) { + $this->position = $old; + throw new \RuntimeException('Unable to seek to position'); + } + } + + public function rewind() + { + $this->seek(0); + } + + public function isWritable() + { + return !$this->closed; + } + + public function write($string) + { + if ($this->closed) { + throw new \RuntimeException('Unable to write to closed stream'); + } + + if ($string === '') { + return 0; + } + + if ($this->position > 0 && !isset($this->buffer[$this->position - 1])) { + $this->buffer = \str_pad($this->buffer, $this->position, "\0"); + } + + $len = \strlen($string); + $this->buffer = \substr($this->buffer, 0, $this->position) . $string . \substr($this->buffer, $this->position + $len); + $this->position += $len; + + return $len; + } + + public function isReadable() + { + return !$this->closed; + } + + public function read($length) + { + if ($this->closed) { + throw new \RuntimeException('Unable to read from closed stream'); + } + + if ($length < 1) { + throw new \InvalidArgumentException('Invalid read length given'); + } + + if ($this->position + $length > \strlen($this->buffer)) { + $length = \strlen($this->buffer) - $this->position; + } + + if (!isset($this->buffer[$this->position])) { + return ''; + } + + $pos = $this->position; + $this->position += $length; + + return \substr($this->buffer, $pos, $length); + } + + public function getContents() + { + if ($this->closed) { + throw new \RuntimeException('Unable to read from closed stream'); + } + + if (!isset($this->buffer[$this->position])) { + return ''; + } + + $pos = $this->position; + $this->position = \strlen($this->buffer); + + return \substr($this->buffer, $pos); + } + + public function getMetadata($key = null) + { + return $key === null ? array() : null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedDecoder.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedDecoder.php new file mode 100644 index 0000000..2f58f42 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedDecoder.php @@ -0,0 +1,175 @@ +input = $input; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed && $this->input->isReadable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->buffer = ''; + + $this->closed = true; + + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleEnd() + { + if (!$this->closed) { + $this->handleError(new Exception('Unexpected end event')); + } + } + + /** @internal */ + public function handleError(Exception $e) + { + $this->emit('error', array($e)); + $this->close(); + } + + /** @internal */ + public function handleData($data) + { + $this->buffer .= $data; + + while ($this->buffer !== '') { + if (!$this->headerCompleted) { + $positionCrlf = \strpos($this->buffer, static::CRLF); + + if ($positionCrlf === false) { + // Header shouldn't be bigger than 1024 bytes + if (isset($this->buffer[static::MAX_CHUNK_HEADER_SIZE])) { + $this->handleError(new Exception('Chunk header size inclusive extension bigger than' . static::MAX_CHUNK_HEADER_SIZE. ' bytes')); + } + return; + } + + $header = \strtolower((string)\substr($this->buffer, 0, $positionCrlf)); + $hexValue = $header; + + if (\strpos($header, ';') !== false) { + $array = \explode(';', $header); + $hexValue = $array[0]; + } + + if ($hexValue !== '') { + $hexValue = \ltrim(\trim($hexValue), "0"); + if ($hexValue === '') { + $hexValue = "0"; + } + } + + $this->chunkSize = @\hexdec($hexValue); + if (!\is_int($this->chunkSize) || \dechex($this->chunkSize) !== $hexValue) { + $this->handleError(new Exception($hexValue . ' is not a valid hexadecimal number')); + return; + } + + $this->buffer = (string)\substr($this->buffer, $positionCrlf + 2); + $this->headerCompleted = true; + if ($this->buffer === '') { + return; + } + } + + $chunk = (string)\substr($this->buffer, 0, $this->chunkSize - $this->transferredSize); + + if ($chunk !== '') { + $this->transferredSize += \strlen($chunk); + $this->emit('data', array($chunk)); + $this->buffer = (string)\substr($this->buffer, \strlen($chunk)); + } + + $positionCrlf = \strpos($this->buffer, static::CRLF); + + if ($positionCrlf === 0) { + if ($this->chunkSize === 0) { + $this->emit('end'); + $this->close(); + return; + } + $this->chunkSize = 0; + $this->headerCompleted = false; + $this->transferredSize = 0; + $this->buffer = (string)\substr($this->buffer, 2); + } elseif ($this->chunkSize === 0) { + // end chunk received, skip all trailer data + $this->buffer = (string)\substr($this->buffer, $positionCrlf); + } + + if ($positionCrlf !== 0 && $this->chunkSize !== 0 && $this->chunkSize === $this->transferredSize && \strlen($this->buffer) > 2) { + // the first 2 characters are not CRLF, send error event + $this->handleError(new Exception('Chunk does not end with a CRLF')); + return; + } + + if ($positionCrlf !== 0 && \strlen($this->buffer) < 2) { + // No CRLF found, wait for additional data which could be a CRLF + return; + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedEncoder.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedEncoder.php new file mode 100644 index 0000000..c84ef54 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ChunkedEncoder.php @@ -0,0 +1,92 @@ +input = $input; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed && $this->input->isReadable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleData($data) + { + if ($data !== '') { + $this->emit('data', array( + \dechex(\strlen($data)) . "\r\n" . $data . "\r\n" + )); + } + } + + /** @internal */ + public function handleError(\Exception $e) + { + $this->emit('error', array($e)); + $this->close(); + } + + /** @internal */ + public function handleEnd() + { + $this->emit('data', array("0\r\n\r\n")); + + if (!$this->closed) { + $this->emit('end'); + $this->close(); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/CloseProtectionStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/CloseProtectionStream.php new file mode 100644 index 0000000..2e1ed6e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/CloseProtectionStream.php @@ -0,0 +1,111 @@ +input = $input; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed && $this->input->isReadable(); + } + + public function pause() + { + if ($this->closed) { + return; + } + + $this->paused = true; + $this->input->pause(); + } + + public function resume() + { + if ($this->closed) { + return; + } + + $this->paused = false; + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + // stop listening for incoming events + $this->input->removeListener('data', array($this, 'handleData')); + $this->input->removeListener('error', array($this, 'handleError')); + $this->input->removeListener('end', array($this, 'handleEnd')); + $this->input->removeListener('close', array($this, 'close')); + + // resume the stream to ensure we discard everything from incoming connection + if ($this->paused) { + $this->paused = false; + $this->input->resume(); + } + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleData($data) + { + $this->emit('data', array($data)); + } + + /** @internal */ + public function handleEnd() + { + $this->emit('end'); + $this->close(); + } + + /** @internal */ + public function handleError(\Exception $e) + { + $this->emit('error', array($e)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/EmptyBodyStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/EmptyBodyStream.php new file mode 100644 index 0000000..5056219 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/EmptyBodyStream.php @@ -0,0 +1,142 @@ +closed; + } + + public function pause() + { + // NOOP + } + + public function resume() + { + // NOOP + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + $this->emit('close'); + $this->removeAllListeners(); + } + + public function getSize() + { + return 0; + } + + /** @ignore */ + public function __toString() + { + return ''; + } + + /** @ignore */ + public function detach() + { + return null; + } + + /** @ignore */ + public function tell() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function eof() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function isSeekable() + { + return false; + } + + /** @ignore */ + public function seek($offset, $whence = SEEK_SET) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function rewind() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function isWritable() + { + return false; + } + + /** @ignore */ + public function write($string) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function read($length) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function getContents() + { + return ''; + } + + /** @ignore */ + public function getMetadata($key = null) + { + return ($key === null) ? array() : null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/HttpBodyStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/HttpBodyStream.php new file mode 100644 index 0000000..25d15a1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/HttpBodyStream.php @@ -0,0 +1,182 @@ +input = $input; + $this->size = $size; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed && $this->input->isReadable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + public function getSize() + { + return $this->size; + } + + /** @ignore */ + public function __toString() + { + return ''; + } + + /** @ignore */ + public function detach() + { + return null; + } + + /** @ignore */ + public function tell() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function eof() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function isSeekable() + { + return false; + } + + /** @ignore */ + public function seek($offset, $whence = SEEK_SET) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function rewind() + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function isWritable() + { + return false; + } + + /** @ignore */ + public function write($string) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function read($length) + { + throw new \BadMethodCallException(); + } + + /** @ignore */ + public function getContents() + { + return ''; + } + + /** @ignore */ + public function getMetadata($key = null) + { + return null; + } + + /** @internal */ + public function handleData($data) + { + $this->emit('data', array($data)); + } + + /** @internal */ + public function handleError(\Exception $e) + { + $this->emit('error', array($e)); + $this->close(); + } + + /** @internal */ + public function handleEnd() + { + if (!$this->closed) { + $this->emit('end'); + $this->close(); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/IniUtil.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/IniUtil.php new file mode 100644 index 0000000..612aae2 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/IniUtil.php @@ -0,0 +1,48 @@ +stream = $stream; + $this->maxLength = $maxLength; + + $this->stream->on('data', array($this, 'handleData')); + $this->stream->on('end', array($this, 'handleEnd')); + $this->stream->on('error', array($this, 'handleError')); + $this->stream->on('close', array($this, 'close')); + } + + public function isReadable() + { + return !$this->closed && $this->stream->isReadable(); + } + + public function pause() + { + $this->stream->pause(); + } + + public function resume() + { + $this->stream->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + $this->stream->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleData($data) + { + if (($this->transferredLength + \strlen($data)) > $this->maxLength) { + // Only emit data until the value of 'Content-Length' is reached, the rest will be ignored + $data = (string)\substr($data, 0, $this->maxLength - $this->transferredLength); + } + + if ($data !== '') { + $this->transferredLength += \strlen($data); + $this->emit('data', array($data)); + } + + if ($this->transferredLength === $this->maxLength) { + // 'Content-Length' reached, stream will end + $this->emit('end'); + $this->close(); + $this->stream->removeListener('data', array($this, 'handleData')); + } + } + + /** @internal */ + public function handleError(\Exception $e) + { + $this->emit('error', array($e)); + $this->close(); + } + + /** @internal */ + public function handleEnd() + { + if (!$this->closed) { + $this->handleError(new \Exception('Unexpected end event')); + } + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MiddlewareRunner.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MiddlewareRunner.php new file mode 100644 index 0000000..dedf6ff --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MiddlewareRunner.php @@ -0,0 +1,61 @@ +middleware = \array_values($middleware); + } + + /** + * @param ServerRequestInterface $request + * @return ResponseInterface|PromiseInterface + * @throws \Exception + */ + public function __invoke(ServerRequestInterface $request) + { + if (empty($this->middleware)) { + throw new \RuntimeException('No middleware to run'); + } + + return $this->call($request, 0); + } + + /** @internal */ + public function call(ServerRequestInterface $request, $position) + { + // final request handler will be invoked without a next handler + if (!isset($this->middleware[$position + 1])) { + $handler = $this->middleware[$position]; + return $handler($request); + } + + $that = $this; + $next = function (ServerRequestInterface $request) use ($that, $position) { + return $that->call($request, $position + 1); + }; + + // invoke middleware request handler with next handler + $handler = $this->middleware[$position]; + return $handler($request, $next); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MultipartParser.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MultipartParser.php new file mode 100644 index 0000000..d868ca8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/MultipartParser.php @@ -0,0 +1,329 @@ +maxInputVars = (int)$var; + } + $var = \ini_get('max_input_nesting_level'); + if ($var !== false) { + $this->maxInputNestingLevel = (int)$var; + } + + if ($uploadMaxFilesize === null) { + $uploadMaxFilesize = \ini_get('upload_max_filesize'); + } + + $this->uploadMaxFilesize = IniUtil::iniSizeToBytes($uploadMaxFilesize); + $this->maxFileUploads = $maxFileUploads === null ? (\ini_get('file_uploads') === '' ? 0 : (int)\ini_get('max_file_uploads')) : (int)$maxFileUploads; + } + + public function parse(ServerRequestInterface $request) + { + $contentType = $request->getHeaderLine('content-type'); + if(!\preg_match('/boundary="?(.*?)"?$/', $contentType, $matches)) { + return $request; + } + + $this->request = $request; + $this->parseBody('--' . $matches[1], (string)$request->getBody()); + + $request = $this->request; + $this->request = null; + $this->postCount = 0; + $this->filesCount = 0; + $this->emptyCount = 0; + $this->maxFileSize = null; + + return $request; + } + + private function parseBody($boundary, $buffer) + { + $len = \strlen($boundary); + + // ignore everything before initial boundary (SHOULD be empty) + $start = \strpos($buffer, $boundary . "\r\n"); + + while ($start !== false) { + // search following boundary (preceded by newline) + // ignore last if not followed by boundary (SHOULD end with "--") + $start += $len + 2; + $end = \strpos($buffer, "\r\n" . $boundary, $start); + if ($end === false) { + break; + } + + // parse one part and continue searching for next + $this->parsePart(\substr($buffer, $start, $end - $start)); + $start = $end; + } + } + + private function parsePart($chunk) + { + $pos = \strpos($chunk, "\r\n\r\n"); + if ($pos === false) { + return; + } + + $headers = $this->parseHeaders((string)substr($chunk, 0, $pos)); + $body = (string)\substr($chunk, $pos + 4); + + if (!isset($headers['content-disposition'])) { + return; + } + + $name = $this->getParameterFromHeader($headers['content-disposition'], 'name'); + if ($name === null) { + return; + } + + $filename = $this->getParameterFromHeader($headers['content-disposition'], 'filename'); + if ($filename !== null) { + $this->parseFile( + $name, + $filename, + isset($headers['content-type'][0]) ? $headers['content-type'][0] : null, + $body + ); + } else { + $this->parsePost($name, $body); + } + } + + private function parseFile($name, $filename, $contentType, $contents) + { + $file = $this->parseUploadedFile($filename, $contentType, $contents); + if ($file === null) { + return; + } + + $this->request = $this->request->withUploadedFiles($this->extractPost( + $this->request->getUploadedFiles(), + $name, + $file + )); + } + + private function parseUploadedFile($filename, $contentType, $contents) + { + $size = \strlen($contents); + + // no file selected (zero size and empty filename) + if ($size === 0 && $filename === '') { + // ignore excessive number of empty file uploads + if (++$this->emptyCount + $this->filesCount > $this->maxInputVars) { + return; + } + + return new UploadedFile( + Psr7\stream_for(), + $size, + \UPLOAD_ERR_NO_FILE, + $filename, + $contentType + ); + } + + // ignore excessive number of file uploads + if (++$this->filesCount > $this->maxFileUploads) { + return; + } + + // file exceeds "upload_max_filesize" ini setting + if ($size > $this->uploadMaxFilesize) { + return new UploadedFile( + Psr7\stream_for(), + $size, + \UPLOAD_ERR_INI_SIZE, + $filename, + $contentType + ); + } + + // file exceeds MAX_FILE_SIZE value + if ($this->maxFileSize !== null && $size > $this->maxFileSize) { + return new UploadedFile( + Psr7\stream_for(), + $size, + \UPLOAD_ERR_FORM_SIZE, + $filename, + $contentType + ); + } + + return new UploadedFile( + Psr7\stream_for($contents), + $size, + \UPLOAD_ERR_OK, + $filename, + $contentType + ); + } + + private function parsePost($name, $value) + { + // ignore excessive number of post fields + if (++$this->postCount > $this->maxInputVars) { + return; + } + + $this->request = $this->request->withParsedBody($this->extractPost( + $this->request->getParsedBody(), + $name, + $value + )); + + if (\strtoupper($name) === 'MAX_FILE_SIZE') { + $this->maxFileSize = (int)$value; + + if ($this->maxFileSize === 0) { + $this->maxFileSize = null; + } + } + } + + private function parseHeaders($header) + { + $headers = array(); + + foreach (\explode("\r\n", \trim($header)) as $line) { + $parts = \explode(':', $line, 2); + if (!isset($parts[1])) { + continue; + } + + $key = \strtolower(trim($parts[0])); + $values = \explode(';', $parts[1]); + $values = \array_map('trim', $values); + $headers[$key] = $values; + } + + return $headers; + } + + private function getParameterFromHeader(array $header, $parameter) + { + foreach ($header as $part) { + if (\preg_match('/' . $parameter . '="?(.*?)"?$/', $part, $matches)) { + return $matches[1]; + } + } + + return null; + } + + private function extractPost($postFields, $key, $value) + { + $chunks = \explode('[', $key); + if (\count($chunks) == 1) { + $postFields[$key] = $value; + return $postFields; + } + + // ignore this key if maximum nesting level is exceeded + if (isset($chunks[$this->maxInputNestingLevel])) { + return $postFields; + } + + $chunkKey = \rtrim($chunks[0], ']'); + $parent = &$postFields; + for ($i = 1; isset($chunks[$i]); $i++) { + $previousChunkKey = $chunkKey; + + if ($previousChunkKey === '') { + $parent[] = array(); + \end($parent); + $parent = &$parent[\key($parent)]; + } else { + if (!isset($parent[$previousChunkKey]) || !\is_array($parent[$previousChunkKey])) { + $parent[$previousChunkKey] = array(); + } + $parent = &$parent[$previousChunkKey]; + } + + $chunkKey = \rtrim($chunks[$i], ']'); + } + + if ($chunkKey === '') { + $parent[] = $value; + } else { + $parent[$chunkKey] = $value; + } + + return $postFields; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/PauseBufferStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/PauseBufferStream.php new file mode 100644 index 0000000..fb5ed45 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/PauseBufferStream.php @@ -0,0 +1,188 @@ +input = $input; + + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'handleClose')); + } + + /** + * pause and remember this was not explicitly from user control + * + * @internal + */ + public function pauseImplicit() + { + $this->pause(); + $this->implicit = true; + } + + /** + * resume only if this was previously paused implicitly and not explicitly from user control + * + * @internal + */ + public function resumeImplicit() + { + if ($this->implicit) { + $this->resume(); + } + } + + public function isReadable() + { + return !$this->closed; + } + + public function pause() + { + if ($this->closed) { + return; + } + + $this->input->pause(); + $this->paused = true; + $this->implicit = false; + } + + public function resume() + { + if ($this->closed) { + return; + } + + $this->paused = false; + $this->implicit = false; + + if ($this->dataPaused !== '') { + $this->emit('data', array($this->dataPaused)); + $this->dataPaused = ''; + } + + if ($this->errorPaused) { + $this->emit('error', array($this->errorPaused)); + return $this->close(); + } + + if ($this->endPaused) { + $this->endPaused = false; + $this->emit('end'); + return $this->close(); + } + + if ($this->closePaused) { + $this->closePaused = false; + return $this->close(); + } + + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->dataPaused = ''; + $this->endPaused = $this->closePaused = false; + $this->errorPaused = null; + + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleData($data) + { + if ($this->paused) { + $this->dataPaused .= $data; + return; + } + + $this->emit('data', array($data)); + } + + /** @internal */ + public function handleError(\Exception $e) + { + if ($this->paused) { + $this->errorPaused = $e; + return; + } + + $this->emit('error', array($e)); + $this->close(); + } + + /** @internal */ + public function handleEnd() + { + if ($this->paused) { + $this->endPaused = true; + return; + } + + if (!$this->closed) { + $this->emit('end'); + $this->close(); + } + } + + /** @internal */ + public function handleClose() + { + if ($this->paused) { + $this->closePaused = true; + return; + } + + $this->close(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ReadableBodyStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ReadableBodyStream.php new file mode 100644 index 0000000..daef45f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/ReadableBodyStream.php @@ -0,0 +1,153 @@ +input = $input; + $this->size = $size; + + $that = $this; + $pos =& $this->position; + $input->on('data', function ($data) use ($that, &$pos, $size) { + $that->emit('data', array($data)); + + $pos += \strlen($data); + if ($size !== null && $pos >= $size) { + $that->handleEnd(); + } + }); + $input->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + $that->close(); + }); + $input->on('end', array($that, 'handleEnd')); + $input->on('close', array($that, 'close')); + } + + public function close() + { + if (!$this->closed) { + $this->closed = true; + $this->input->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } + } + + public function isReadable() + { + return $this->input->isReadable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function eof() + { + return !$this->isReadable(); + } + + public function __toString() + { + return ''; + } + + public function detach() + { + throw new \BadMethodCallException(); + } + + public function getSize() + { + return $this->size; + } + + public function tell() + { + throw new \BadMethodCallException(); + } + + public function isSeekable() + { + return false; + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \BadMethodCallException(); + } + + public function rewind() + { + throw new \BadMethodCallException(); + } + + public function isWritable() + { + return false; + } + + public function write($string) + { + throw new \BadMethodCallException(); + } + + public function read($length) + { + throw new \BadMethodCallException(); + } + + public function getContents() + { + throw new \BadMethodCallException(); + } + + public function getMetadata($key = null) + { + return ($key === null) ? array() : null; + } + + /** @internal */ + public function handleEnd() + { + if ($this->position !== $this->size && $this->size !== null) { + $this->emit('error', array(new \UnderflowException('Unexpected end of response body after ' . $this->position . '/' . $this->size . ' bytes'))); + } else { + $this->emit('end'); + } + + $this->close(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/RequestHeaderParser.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/RequestHeaderParser.php new file mode 100644 index 0000000..64b5dcd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/RequestHeaderParser.php @@ -0,0 +1,278 @@ +maxSize; + $that = $this; + $conn->on('data', $fn = function ($data) use (&$buffer, &$fn, $conn, $maxSize, $that) { + // append chunk of data to buffer and look for end of request headers + $buffer .= $data; + $endOfHeader = \strpos($buffer, "\r\n\r\n"); + + // reject request if buffer size is exceeded + if ($endOfHeader > $maxSize || ($endOfHeader === false && isset($buffer[$maxSize]))) { + $conn->removeListener('data', $fn); + $fn = null; + + $that->emit('error', array( + new \OverflowException("Maximum header size of {$maxSize} exceeded.", 431), + $conn + )); + return; + } + + // ignore incomplete requests + if ($endOfHeader === false) { + return; + } + + // request headers received => try to parse request + $conn->removeListener('data', $fn); + $fn = null; + + try { + $request = $that->parseRequest( + (string)\substr($buffer, 0, $endOfHeader + 2), + $conn->getRemoteAddress(), + $conn->getLocalAddress() + ); + } catch (Exception $exception) { + $buffer = ''; + $that->emit('error', array( + $exception, + $conn + )); + return; + } + + $contentLength = 0; + if ($request->hasHeader('Transfer-Encoding')) { + $contentLength = null; + } elseif ($request->hasHeader('Content-Length')) { + $contentLength = (int)$request->getHeaderLine('Content-Length'); + } + + if ($contentLength === 0) { + // happy path: request body is known to be empty + $stream = new EmptyBodyStream(); + $request = $request->withBody($stream); + } else { + // otherwise body is present => delimit using Content-Length or ChunkedDecoder + $stream = new CloseProtectionStream($conn); + if ($contentLength !== null) { + $stream = new LengthLimitedStream($stream, $contentLength); + } else { + $stream = new ChunkedDecoder($stream); + } + + $request = $request->withBody(new HttpBodyStream($stream, $contentLength)); + } + + $bodyBuffer = isset($buffer[$endOfHeader + 4]) ? \substr($buffer, $endOfHeader + 4) : ''; + $buffer = ''; + $that->emit('headers', array($request, $conn)); + + if ($bodyBuffer !== '') { + $conn->emit('data', array($bodyBuffer)); + } + + // happy path: request body is known to be empty => immediately end stream + if ($contentLength === 0) { + $stream->emit('end'); + $stream->close(); + } + }); + } + + /** + * @param string $headers buffer string containing request headers only + * @param ?string $remoteSocketUri + * @param ?string $localSocketUri + * @return ServerRequestInterface + * @throws \InvalidArgumentException + * @internal + */ + public function parseRequest($headers, $remoteSocketUri, $localSocketUri) + { + // additional, stricter safe-guard for request line + // because request parser doesn't properly cope with invalid ones + $start = array(); + if (!\preg_match('#^(?[^ ]+) (?[^ ]+) HTTP/(?\d\.\d)#m', $headers, $start)) { + throw new \InvalidArgumentException('Unable to parse invalid request-line'); + } + + // only support HTTP/1.1 and HTTP/1.0 requests + if ($start['version'] !== '1.1' && $start['version'] !== '1.0') { + throw new \InvalidArgumentException('Received request with invalid protocol version', 505); + } + + // match all request header fields into array, thanks to @kelunik for checking the HTTP specs and coming up with this regex + $matches = array(); + $n = \preg_match_all('/^([^()<>@,;:\\\"\/\[\]?={}\x01-\x20\x7F]++):[\x20\x09]*+((?:[\x20\x09]*+[\x21-\x7E\x80-\xFF]++)*+)[\x20\x09]*+[\r]?+\n/m', $headers, $matches, \PREG_SET_ORDER); + + // check number of valid header fields matches number of lines + request line + if (\substr_count($headers, "\n") !== $n + 1) { + throw new \InvalidArgumentException('Unable to parse invalid request header fields'); + } + + // format all header fields into associative array + $host = null; + $fields = array(); + foreach ($matches as $match) { + $fields[$match[1]][] = $match[2]; + + // match `Host` request header + if ($host === null && \strtolower($match[1]) === 'host') { + $host = $match[2]; + } + } + + // create new obj implementing ServerRequestInterface by preserving all + // previous properties and restoring original request-target + $serverParams = array( + 'REQUEST_TIME' => \time(), + 'REQUEST_TIME_FLOAT' => \microtime(true) + ); + + // scheme is `http` unless TLS is used + $localParts = \parse_url($localSocketUri); + if (isset($localParts['scheme']) && $localParts['scheme'] === 'tls') { + $scheme = 'https://'; + $serverParams['HTTPS'] = 'on'; + } else { + $scheme = 'http://'; + } + + // default host if unset comes from local socket address or defaults to localhost + $hasHost = $host !== null; + if ($host === null) { + $host = isset($localParts['host'], $localParts['port']) ? $localParts['host'] . ':' . $localParts['port'] : '127.0.0.1'; + } + + if ($start['method'] === 'OPTIONS' && $start['target'] === '*') { + // support asterisk-form for `OPTIONS *` request line only + $uri = $scheme . $host; + } elseif ($start['method'] === 'CONNECT') { + $parts = \parse_url('tcp://' . $start['target']); + + // check this is a valid authority-form request-target (host:port) + if (!isset($parts['scheme'], $parts['host'], $parts['port']) || \count($parts) !== 3) { + throw new \InvalidArgumentException('CONNECT method MUST use authority-form request target'); + } + $uri = $scheme . $start['target']; + } else { + // support absolute-form or origin-form for proxy requests + if ($start['target'][0] === '/') { + $uri = $scheme . $host . $start['target']; + } else { + // ensure absolute-form request-target contains a valid URI + $parts = \parse_url($start['target']); + + // make sure value contains valid host component (IP or hostname), but no fragment + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'http' || isset($parts['fragment'])) { + throw new \InvalidArgumentException('Invalid absolute-form request-target'); + } + + $uri = $start['target']; + } + } + + // apply REMOTE_ADDR and REMOTE_PORT if source address is known + // address should always be known, unless this is over Unix domain sockets (UDS) + if ($remoteSocketUri !== null) { + $remoteAddress = \parse_url($remoteSocketUri); + $serverParams['REMOTE_ADDR'] = $remoteAddress['host']; + $serverParams['REMOTE_PORT'] = $remoteAddress['port']; + } + + // apply SERVER_ADDR and SERVER_PORT if server address is known + // address should always be known, even for Unix domain sockets (UDS) + // but skip UDS as it doesn't have a concept of host/port. + if ($localSocketUri !== null && isset($localParts['host'], $localParts['port'])) { + $serverParams['SERVER_ADDR'] = $localParts['host']; + $serverParams['SERVER_PORT'] = $localParts['port']; + } + + $request = new ServerRequest( + $start['method'], + $uri, + $fields, + '', + $start['version'], + $serverParams + ); + + // only assign request target if it is not in origin-form (happy path for most normal requests) + if ($start['target'][0] !== '/') { + $request = $request->withRequestTarget($start['target']); + } + + if ($hasHost) { + // Optional Host request header value MUST be valid (host and optional port) + $parts = \parse_url('http://' . $request->getHeaderLine('Host')); + + // make sure value contains valid host component (IP or hostname) + if (!$parts || !isset($parts['scheme'], $parts['host'])) { + $parts = false; + } + + // make sure value does not contain any other URI component + unset($parts['scheme'], $parts['host'], $parts['port']); + if ($parts === false || $parts) { + throw new \InvalidArgumentException('Invalid Host header value'); + } + } elseif (!$hasHost && $start['version'] === '1.1' && $start['method'] !== 'CONNECT') { + // require Host request header for HTTP/1.1 (except for CONNECT method) + throw new \InvalidArgumentException('Missing required Host request header'); + } elseif (!$hasHost) { + // remove default Host request header for HTTP/1.0 when not explicitly given + $request = $request->withoutHeader('Host'); + } + + // ensure message boundaries are valid according to Content-Length and Transfer-Encoding request headers + if ($request->hasHeader('Transfer-Encoding')) { + if (\strtolower($request->getHeaderLine('Transfer-Encoding')) !== 'chunked') { + throw new \InvalidArgumentException('Only chunked-encoding is allowed for Transfer-Encoding', 501); + } + + // Transfer-Encoding: chunked and Content-Length header MUST NOT be used at the same time + // as per https://tools.ietf.org/html/rfc7230#section-3.3.3 + if ($request->hasHeader('Content-Length')) { + throw new \InvalidArgumentException('Using both `Transfer-Encoding: chunked` and `Content-Length` is not allowed', 400); + } + } elseif ($request->hasHeader('Content-Length')) { + $string = $request->getHeaderLine('Content-Length'); + + if ((string)(int)$string !== $string) { + // Content-Length value is not an integer or not a single integer + throw new \InvalidArgumentException('The value of `Content-Length` is not valid', 400); + } + } + + return $request; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Sender.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Sender.php new file mode 100644 index 0000000..c1bbab4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Sender.php @@ -0,0 +1,159 @@ +http = $http; + } + + /** + * + * @internal + * @param RequestInterface $request + * @return PromiseInterface Promise + */ + public function send(RequestInterface $request) + { + $body = $request->getBody(); + $size = $body->getSize(); + + if ($size !== null && $size !== 0) { + // automatically assign a "Content-Length" request header if the body size is known and non-empty + $request = $request->withHeader('Content-Length', (string)$size); + } elseif ($size === 0 && \in_array($request->getMethod(), array('POST', 'PUT', 'PATCH'))) { + // only assign a "Content-Length: 0" request header if the body is expected for certain methods + $request = $request->withHeader('Content-Length', '0'); + } elseif ($body instanceof ReadableStreamInterface && $body->isReadable() && !$request->hasHeader('Content-Length')) { + // use "Transfer-Encoding: chunked" when this is a streaming body and body size is unknown + $request = $request->withHeader('Transfer-Encoding', 'chunked'); + } else { + // do not use chunked encoding if size is known or if this is an empty request body + $size = 0; + } + + $headers = array(); + foreach ($request->getHeaders() as $name => $values) { + $headers[$name] = implode(', ', $values); + } + + $requestStream = $this->http->request($request->getMethod(), (string)$request->getUri(), $headers, $request->getProtocolVersion()); + + $deferred = new Deferred(function ($_, $reject) use ($requestStream) { + // close request stream if request is cancelled + $reject(new \RuntimeException('Request cancelled')); + $requestStream->close(); + }); + + $requestStream->on('error', function($error) use ($deferred) { + $deferred->reject($error); + }); + + $requestStream->on('response', function (ResponseInterface $response, ReadableStreamInterface $body) use ($deferred, $request) { + $length = null; + $code = $response->getStatusCode(); + if ($request->getMethod() === 'HEAD' || ($code >= 100 && $code < 200) || $code == 204 || $code == 304) { + $length = 0; + } elseif (\strtolower($response->getHeaderLine('Transfer-Encoding')) === 'chunked') { + $body = new ChunkedDecoder($body); + } elseif ($response->hasHeader('Content-Length')) { + $length = (int) $response->getHeaderLine('Content-Length'); + } + + $deferred->resolve($response->withBody(new ReadableBodyStream($body, $length))); + }); + + if ($body instanceof ReadableStreamInterface) { + if ($body->isReadable()) { + // length unknown => apply chunked transfer-encoding + if ($size === null) { + $body = new ChunkedEncoder($body); + } + + // pipe body into request stream + // add dummy write to immediately start request even if body does not emit any data yet + $body->pipe($requestStream); + $requestStream->write(''); + + $body->on('close', $close = function () use ($deferred, $requestStream) { + $deferred->reject(new \RuntimeException('Request failed because request body closed unexpectedly')); + $requestStream->close(); + }); + $body->on('error', function ($e) use ($deferred, $requestStream, $close, $body) { + $body->removeListener('close', $close); + $deferred->reject(new \RuntimeException('Request failed because request body reported an error', 0, $e)); + $requestStream->close(); + }); + $body->on('end', function () use ($close, $body) { + $body->removeListener('close', $close); + }); + } else { + // stream is not readable => end request without body + $requestStream->end(); + } + } else { + // body is fully buffered => write as one chunk + $requestStream->end((string)$body); + } + + return $deferred->promise(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/StreamingServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/StreamingServer.php new file mode 100644 index 0000000..2c912df --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/StreamingServer.php @@ -0,0 +1,378 @@ + 'text/plain' + * ), + * "Hello World!\n" + * ); + * }); + * ``` + * + * Each incoming HTTP request message is always represented by the + * [PSR-7 `ServerRequestInterface`](https://www.php-fig.org/psr/psr-7/#321-psrhttpmessageserverrequestinterface), + * see also following [request](#request) chapter for more details. + * Each outgoing HTTP response message is always represented by the + * [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface), + * see also following [response](#response) chapter for more details. + * + * In order to process any connections, the server needs to be attached to an + * instance of `React\Socket\ServerInterface` through the [`listen()`](#listen) method + * as described in the following chapter. In its most simple form, you can attach + * this to a [`React\Socket\SocketServer`](https://github.com/reactphp/socket#socketserver) + * in order to start a plaintext HTTP server like this: + * + * ```php + * $server = new StreamingServer($loop, $handler); + * + * $socket = new React\Socket\SocketServer('0.0.0.0:8080', array(), $loop); + * $server->listen($socket); + * ``` + * + * See also the [`listen()`](#listen) method and the [first example](examples) for more details. + * + * The `StreamingServer` class is considered advanced usage and unless you know + * what you're doing, you're recommended to use the [`HttpServer`](#httpserver) class + * instead. The `StreamingServer` class is specifically designed to help with + * more advanced use cases where you want to have full control over consuming + * the incoming HTTP request body and concurrency settings. + * + * In particular, this class does not buffer and parse the incoming HTTP request + * in memory. It will invoke the request handler function once the HTTP request + * headers have been received, i.e. before receiving the potentially much larger + * HTTP request body. This means the [request](#request) passed to your request + * handler function may not be fully compatible with PSR-7. See also + * [streaming request](#streaming-request) below for more details. + * + * @see \React\Http\HttpServer + * @see \React\Http\Message\Response + * @see self::listen() + * @internal + */ +final class StreamingServer extends EventEmitter +{ + private $callback; + private $parser; + private $loop; + + /** + * Creates an HTTP server that invokes the given callback for each incoming HTTP request + * + * In order to process any connections, the server needs to be attached to an + * instance of `React\Socket\ServerInterface` which emits underlying streaming + * connections in order to then parse incoming data as HTTP. + * See also [listen()](#listen) for more details. + * + * @param LoopInterface $loop + * @param callable $requestHandler + * @see self::listen() + */ + public function __construct(LoopInterface $loop, $requestHandler) + { + if (!\is_callable($requestHandler)) { + throw new \InvalidArgumentException('Invalid request handler given'); + } + + $this->loop = $loop; + + $this->callback = $requestHandler; + $this->parser = new RequestHeaderParser(); + + $that = $this; + $this->parser->on('headers', function (ServerRequestInterface $request, ConnectionInterface $conn) use ($that) { + $that->handleRequest($conn, $request); + }); + + $this->parser->on('error', function(\Exception $e, ConnectionInterface $conn) use ($that) { + $that->emit('error', array($e)); + + // parsing failed => assume dummy request and send appropriate error + $that->writeError( + $conn, + $e->getCode() !== 0 ? $e->getCode() : 400, + new ServerRequest('GET', '/') + ); + }); + } + + /** + * Starts listening for HTTP requests on the given socket server instance + * + * @param ServerInterface $socket + * @see \React\Http\HttpServer::listen() + */ + public function listen(ServerInterface $socket) + { + $socket->on('connection', array($this->parser, 'handle')); + } + + /** @internal */ + public function handleRequest(ConnectionInterface $conn, ServerRequestInterface $request) + { + if ($request->getProtocolVersion() !== '1.0' && '100-continue' === \strtolower($request->getHeaderLine('Expect'))) { + $conn->write("HTTP/1.1 100 Continue\r\n\r\n"); + } + + // execute request handler callback + $callback = $this->callback; + try { + $response = $callback($request); + } catch (\Exception $error) { + // request handler callback throws an Exception + $response = Promise\reject($error); + } catch (\Throwable $error) { // @codeCoverageIgnoreStart + // request handler callback throws a PHP7+ Error + $response = Promise\reject($error); // @codeCoverageIgnoreEnd + } + + // cancel pending promise once connection closes + if ($response instanceof CancellablePromiseInterface) { + $conn->on('close', function () use ($response) { + $response->cancel(); + }); + } + + // happy path: response returned, handle and return immediately + if ($response instanceof ResponseInterface) { + return $this->handleResponse($conn, $request, $response); + } + + // did not return a promise? this is an error, convert into one for rejection below. + if (!$response instanceof PromiseInterface) { + $response = Promise\resolve($response); + } + + $that = $this; + $response->then( + function ($response) use ($that, $conn, $request) { + if (!$response instanceof ResponseInterface) { + $message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but resolved with "%s" instead.'; + $message = \sprintf($message, \is_object($response) ? \get_class($response) : \gettype($response)); + $exception = new \RuntimeException($message); + + $that->emit('error', array($exception)); + return $that->writeError($conn, 500, $request); + } + $that->handleResponse($conn, $request, $response); + }, + function ($error) use ($that, $conn, $request) { + $message = 'The response callback is expected to resolve with an object implementing Psr\Http\Message\ResponseInterface, but rejected with "%s" instead.'; + $message = \sprintf($message, \is_object($error) ? \get_class($error) : \gettype($error)); + + $previous = null; + + if ($error instanceof \Throwable || $error instanceof \Exception) { + $previous = $error; + } + + $exception = new \RuntimeException($message, null, $previous); + + $that->emit('error', array($exception)); + return $that->writeError($conn, 500, $request); + } + ); + } + + /** @internal */ + public function writeError(ConnectionInterface $conn, $code, ServerRequestInterface $request) + { + $response = new Response( + $code, + array( + 'Content-Type' => 'text/plain', + 'Connection' => 'close' // we do not want to keep the connection open after an error + ), + 'Error ' . $code + ); + + // append reason phrase to response body if known + $reason = $response->getReasonPhrase(); + if ($reason !== '') { + $body = $response->getBody(); + $body->seek(0, SEEK_END); + $body->write(': ' . $reason); + } + + $this->handleResponse($conn, $request, $response); + } + + + /** @internal */ + public function handleResponse(ConnectionInterface $connection, ServerRequestInterface $request, ResponseInterface $response) + { + // return early and close response body if connection is already closed + $body = $response->getBody(); + if (!$connection->isWritable()) { + $body->close(); + return; + } + + $code = $response->getStatusCode(); + $method = $request->getMethod(); + + // assign HTTP protocol version from request automatically + $version = $request->getProtocolVersion(); + $response = $response->withProtocolVersion($version); + + // assign default "Server" header automatically + if (!$response->hasHeader('Server')) { + $response = $response->withHeader('Server', 'ReactPHP/1'); + } elseif ($response->getHeaderLine('Server') === ''){ + $response = $response->withoutHeader('Server'); + } + + // assign default "Date" header from current time automatically + if (!$response->hasHeader('Date')) { + // IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + $response = $response->withHeader('Date', gmdate('D, d M Y H:i:s') . ' GMT'); + } elseif ($response->getHeaderLine('Date') === ''){ + $response = $response->withoutHeader('Date'); + } + + // assign "Content-Length" and "Transfer-Encoding" headers automatically + $chunked = false; + if (($method === 'CONNECT' && $code >= 200 && $code < 300) || ($code >= 100 && $code < 200) || $code === 204) { + // 2xx response to CONNECT and 1xx and 204 MUST NOT include Content-Length or Transfer-Encoding header + $response = $response->withoutHeader('Content-Length')->withoutHeader('Transfer-Encoding'); + } elseif ($body->getSize() !== null) { + // assign Content-Length header when using a "normal" buffered body string + $response = $response->withHeader('Content-Length', (string)$body->getSize())->withoutHeader('Transfer-Encoding'); + } elseif (!$response->hasHeader('Content-Length') && $version === '1.1') { + // assign chunked transfer-encoding if no 'content-length' is given for HTTP/1.1 responses + $response = $response->withHeader('Transfer-Encoding', 'chunked'); + $chunked = true; + } else { + // remove any Transfer-Encoding headers unless automatically enabled above + // we do not want to keep connection alive, so pretend we received "Connection: close" request header + $response = $response->withoutHeader('Transfer-Encoding'); + $request = $request->withHeader('Connection', 'close'); + } + + // assign "Connection" header automatically + $persist = false; + if ($code === 101) { + // 101 (Switching Protocols) response uses Connection: upgrade header + // This implies that this stream now uses another protocol and we + // may not persist this connection for additional requests. + $response = $response->withHeader('Connection', 'upgrade'); + } elseif (\strtolower($request->getHeaderLine('Connection')) === 'close' || \strtolower($response->getHeaderLine('Connection')) === 'close') { + // obey explicit "Connection: close" request header or response header if present + $response = $response->withHeader('Connection', 'close'); + } elseif ($version === '1.1') { + // HTTP/1.1 assumes persistent connection support by default, so we don't need to inform client + $persist = true; + } elseif (strtolower($request->getHeaderLine('Connection')) === 'keep-alive') { + // obey explicit "Connection: keep-alive" request header and inform client + $persist = true; + $response = $response->withHeader('Connection', 'keep-alive'); + } else { + // remove any Connection headers unless automatically enabled above + $response = $response->withoutHeader('Connection'); + } + + // 101 (Switching Protocols) response (for Upgrade request) forwards upgraded data through duplex stream + // 2xx (Successful) response to CONNECT forwards tunneled application data through duplex stream + if (($code === 101 || ($method === 'CONNECT' && $code >= 200 && $code < 300)) && $body instanceof HttpBodyStream && $body->input instanceof WritableStreamInterface) { + if ($request->getBody()->isReadable()) { + // request is still streaming => wait for request close before forwarding following data from connection + $request->getBody()->on('close', function () use ($connection, $body) { + if ($body->input->isWritable()) { + $connection->pipe($body->input); + $connection->resume(); + } + }); + } elseif ($body->input->isWritable()) { + // request already closed => forward following data from connection + $connection->pipe($body->input); + $connection->resume(); + } + } + + // build HTTP response header by appending status line and header fields + $headers = "HTTP/" . $version . " " . $code . " " . $response->getReasonPhrase() . "\r\n"; + foreach ($response->getHeaders() as $name => $values) { + foreach ($values as $value) { + $headers .= $name . ": " . $value . "\r\n"; + } + } + + // response to HEAD and 1xx, 204 and 304 responses MUST NOT include a body + // exclude status 101 (Switching Protocols) here for Upgrade request handling above + if ($method === 'HEAD' || $code === 100 || ($code > 101 && $code < 200) || $code === 204 || $code === 304) { + $body = ''; + } + + // this is a non-streaming response body or the body stream already closed? + if (!$body instanceof ReadableStreamInterface || !$body->isReadable()) { + // add final chunk if a streaming body is already closed and uses `Transfer-Encoding: chunked` + if ($body instanceof ReadableStreamInterface && $chunked) { + $body = "0\r\n\r\n"; + } + + // write response headers and body + $connection->write($headers . "\r\n" . $body); + + // either wait for next request over persistent connection or end connection + if ($persist) { + $this->parser->handle($connection); + } else { + $connection->end(); + } + return; + } + + $connection->write($headers . "\r\n"); + + if ($chunked) { + $body = new ChunkedEncoder($body); + } + + // Close response stream once connection closes. + // Note that this TCP/IP close detection may take some time, + // in particular this may only fire on a later read/write attempt. + $connection->on('close', array($body, 'close')); + + // write streaming body and then wait for next request over persistent connection + if ($persist) { + $body->pipe($connection, array('end' => false)); + $parser = $this->parser; + $body->on('end', function () use ($connection, $parser, $body) { + $connection->removeListener('close', array($body, 'close')); + $parser->handle($connection); + }); + } else { + $body->pipe($connection); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Transaction.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Transaction.php new file mode 100644 index 0000000..9449503 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/Transaction.php @@ -0,0 +1,303 @@ +sender = $sender; + $this->loop = $loop; + } + + /** + * @param array $options + * @return self returns new instance, without modifying existing instance + */ + public function withOptions(array $options) + { + $transaction = clone $this; + foreach ($options as $name => $value) { + if (property_exists($transaction, $name)) { + // restore default value if null is given + if ($value === null) { + $default = new self($this->sender, $this->loop); + $value = $default->$name; + } + + $transaction->$name = $value; + } + } + + return $transaction; + } + + public function send(RequestInterface $request) + { + $deferred = new Deferred(function () use (&$deferred) { + if (isset($deferred->pending)) { + $deferred->pending->cancel(); + unset($deferred->pending); + } + }); + + $deferred->numRequests = 0; + + // use timeout from options or default to PHP's default_socket_timeout (60) + $timeout = (float)($this->timeout !== null ? $this->timeout : ini_get("default_socket_timeout")); + + $loop = $this->loop; + $this->next($request, $deferred)->then( + function (ResponseInterface $response) use ($deferred, $loop, &$timeout) { + if (isset($deferred->timeout)) { + $loop->cancelTimer($deferred->timeout); + unset($deferred->timeout); + } + $timeout = -1; + $deferred->resolve($response); + }, + function ($e) use ($deferred, $loop, &$timeout) { + if (isset($deferred->timeout)) { + $loop->cancelTimer($deferred->timeout); + unset($deferred->timeout); + } + $timeout = -1; + $deferred->reject($e); + } + ); + + if ($timeout < 0) { + return $deferred->promise(); + } + + $body = $request->getBody(); + if ($body instanceof ReadableStreamInterface && $body->isReadable()) { + $that = $this; + $body->on('close', function () use ($that, $deferred, &$timeout) { + if ($timeout >= 0) { + $that->applyTimeout($deferred, $timeout); + } + }); + } else { + $this->applyTimeout($deferred, $timeout); + } + + return $deferred->promise(); + } + + /** + * @internal + * @param Deferred $deferred + * @param number $timeout + * @return void + */ + public function applyTimeout(Deferred $deferred, $timeout) + { + $deferred->timeout = $this->loop->addTimer($timeout, function () use ($timeout, $deferred) { + $deferred->reject(new \RuntimeException( + 'Request timed out after ' . $timeout . ' seconds' + )); + if (isset($deferred->pending)) { + $deferred->pending->cancel(); + unset($deferred->pending); + } + }); + } + + private function next(RequestInterface $request, Deferred $deferred) + { + $this->progress('request', array($request)); + + $that = $this; + ++$deferred->numRequests; + + $promise = $this->sender->send($request); + + if (!$this->streaming) { + $promise = $promise->then(function ($response) use ($deferred, $that) { + return $that->bufferResponse($response, $deferred); + }); + } + + $deferred->pending = $promise; + + return $promise->then( + function (ResponseInterface $response) use ($request, $that, $deferred) { + return $that->onResponse($response, $request, $deferred); + } + ); + } + + /** + * @internal + * @param ResponseInterface $response + * @return PromiseInterface Promise + */ + public function bufferResponse(ResponseInterface $response, $deferred) + { + $stream = $response->getBody(); + + $size = $stream->getSize(); + if ($size !== null && $size > $this->maximumSize) { + $stream->close(); + return \React\Promise\reject(new \OverflowException( + 'Response body size of ' . $size . ' bytes exceeds maximum of ' . $this->maximumSize . ' bytes', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 0 + )); + } + + // body is not streaming => already buffered + if (!$stream instanceof ReadableStreamInterface) { + return \React\Promise\resolve($response); + } + + // buffer stream and resolve with buffered body + $maximumSize = $this->maximumSize; + $promise = \React\Promise\Stream\buffer($stream, $maximumSize)->then( + function ($body) use ($response) { + return $response->withBody(\RingCentral\Psr7\stream_for($body)); + }, + function ($e) use ($stream, $maximumSize) { + // try to close stream if buffering fails (or is cancelled) + $stream->close(); + + if ($e instanceof \OverflowException) { + $e = new \OverflowException( + 'Response body size exceeds maximum of ' . $maximumSize . ' bytes', + \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 0 + ); + } + + throw $e; + } + ); + + $deferred->pending = $promise; + + return $promise; + } + + /** + * @internal + * @param ResponseInterface $response + * @param RequestInterface $request + * @throws ResponseException + * @return ResponseInterface|PromiseInterface + */ + public function onResponse(ResponseInterface $response, RequestInterface $request, $deferred) + { + $this->progress('response', array($response, $request)); + + // follow 3xx (Redirection) response status codes if Location header is present and not explicitly disabled + // @link https://tools.ietf.org/html/rfc7231#section-6.4 + if ($this->followRedirects && ($response->getStatusCode() >= 300 && $response->getStatusCode() < 400) && $response->hasHeader('Location')) { + return $this->onResponseRedirect($response, $request, $deferred); + } + + // only status codes 200-399 are considered to be valid, reject otherwise + if ($this->obeySuccessCode && ($response->getStatusCode() < 200 || $response->getStatusCode() >= 400)) { + throw new ResponseException($response); + } + + // resolve our initial promise + return $response; + } + + /** + * @param ResponseInterface $response + * @param RequestInterface $request + * @return PromiseInterface + * @throws \RuntimeException + */ + private function onResponseRedirect(ResponseInterface $response, RequestInterface $request, Deferred $deferred) + { + // resolve location relative to last request URI + $location = Uri::resolve($request->getUri(), $response->getHeaderLine('Location')); + + $request = $this->makeRedirectRequest($request, $location); + $this->progress('redirect', array($request)); + + if ($deferred->numRequests >= $this->maxRedirects) { + throw new \RuntimeException('Maximum number of redirects (' . $this->maxRedirects . ') exceeded'); + } + + return $this->next($request, $deferred); + } + + /** + * @param RequestInterface $request + * @param UriInterface $location + * @return RequestInterface + */ + private function makeRedirectRequest(RequestInterface $request, UriInterface $location) + { + $originalHost = $request->getUri()->getHost(); + $request = $request + ->withoutHeader('Host') + ->withoutHeader('Content-Type') + ->withoutHeader('Content-Length'); + + // Remove authorization if changing hostnames (but not if just changing ports or protocols). + if ($location->getHost() !== $originalHost) { + $request = $request->withoutHeader('Authorization'); + } + + // naïve approach.. + $method = ($request->getMethod() === 'HEAD') ? 'HEAD' : 'GET'; + + return new Request($method, $location, $request->getHeaders()); + } + + private function progress($name, array $args = array()) + { + return; + + echo $name; + + foreach ($args as $arg) { + echo ' '; + if ($arg instanceof ResponseInterface) { + echo 'HTTP/' . $arg->getProtocolVersion() . ' ' . $arg->getStatusCode() . ' ' . $arg->getReasonPhrase(); + } elseif ($arg instanceof RequestInterface) { + echo $arg->getMethod() . ' ' . $arg->getRequestTarget() . ' HTTP/' . $arg->getProtocolVersion(); + } else { + echo $arg; + } + } + + echo PHP_EOL; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/UploadedFile.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/UploadedFile.php new file mode 100644 index 0000000..f2a6c9e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Io/UploadedFile.php @@ -0,0 +1,130 @@ +stream = $stream; + $this->size = $size; + + if (!\is_int($error) || !\in_array($error, array( + \UPLOAD_ERR_OK, + \UPLOAD_ERR_INI_SIZE, + \UPLOAD_ERR_FORM_SIZE, + \UPLOAD_ERR_PARTIAL, + \UPLOAD_ERR_NO_FILE, + \UPLOAD_ERR_NO_TMP_DIR, + \UPLOAD_ERR_CANT_WRITE, + \UPLOAD_ERR_EXTENSION, + ))) { + throw new InvalidArgumentException( + 'Invalid error code, must be an UPLOAD_ERR_* constant' + ); + } + $this->error = $error; + $this->filename = $filename; + $this->mediaType = $mediaType; + } + + /** + * {@inheritdoc} + */ + public function getStream() + { + if ($this->error !== \UPLOAD_ERR_OK) { + throw new RuntimeException('Cannot retrieve stream due to upload error'); + } + + return $this->stream; + } + + /** + * {@inheritdoc} + */ + public function moveTo($targetPath) + { + throw new RuntimeException('Not implemented'); + } + + /** + * {@inheritdoc} + */ + public function getSize() + { + return $this->size; + } + + /** + * {@inheritdoc} + */ + public function getError() + { + return $this->error; + } + + /** + * {@inheritdoc} + */ + public function getClientFilename() + { + return $this->filename; + } + + /** + * {@inheritdoc} + */ + public function getClientMediaType() + { + return $this->mediaType; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/Response.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/Response.php new file mode 100644 index 0000000..5d799c5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/Response.php @@ -0,0 +1,65 @@ + 'text/html' + * ), + * "Hello world!\n" + * ); + * ``` + * + * This class implements the + * [PSR-7 `ResponseInterface`](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface) + * which in turn extends the + * [PSR-7 `MessageInterface`](https://www.php-fig.org/psr/psr-7/#31-psrhttpmessagemessageinterface). + * + * > Internally, this implementation builds on top of an existing incoming + * response message and only adds required streaming support. This base class is + * considered an implementation detail that may change in the future. + * + * @see \Psr\Http\Message\ResponseInterface + */ +final class Response extends Psr7Response +{ + /** + * @param int $status HTTP status code (e.g. 200/404) + * @param array $headers additional response headers + * @param string|ReadableStreamInterface|StreamInterface $body response body + * @param string $version HTTP protocol version (e.g. 1.1/1.0) + * @param ?string $reason custom HTTP response phrase + * @throws \InvalidArgumentException for an invalid body + */ + public function __construct( + $status = 200, + array $headers = array(), + $body = '', + $version = '1.1', + $reason = null + ) { + if ($body instanceof ReadableStreamInterface && !$body instanceof StreamInterface) { + $body = new HttpBodyStream($body, null); + } elseif (!\is_string($body) && !$body instanceof StreamInterface) { + throw new \InvalidArgumentException('Invalid response body given'); + } + + parent::__construct( + $status, + $headers, + $body, + $version, + $reason + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ResponseException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ResponseException.php new file mode 100644 index 0000000..f4912c9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ResponseException.php @@ -0,0 +1,43 @@ +getStatusCode() . ' (' . $response->getReasonPhrase() . ')'; + } + if ($code === null) { + $code = $response->getStatusCode(); + } + parent::__construct($message, $code, $previous); + + $this->response = $response; + } + + /** + * Access its underlying response object. + * + * @return ResponseInterface + */ + public function getResponse() + { + return $this->response; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ServerRequest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ServerRequest.php new file mode 100644 index 0000000..5c01819 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Message/ServerRequest.php @@ -0,0 +1,194 @@ + Internally, this implementation builds on top of an existing outgoing + * request message and only adds required server methods. This base class is + * considered an implementation detail that may change in the future. + * + * @see ServerRequestInterface + */ +final class ServerRequest extends Request implements ServerRequestInterface +{ + private $attributes = array(); + + private $serverParams; + private $fileParams = array(); + private $cookies = array(); + private $queryParams = array(); + private $parsedBody; + + /** + * @param string $method HTTP method for the request. + * @param string|UriInterface $url URL for the request. + * @param array $headers Headers for the message. + * @param string|ReadableStreamInterface|StreamInterface $body Message body. + * @param string $version HTTP protocol version. + * @param array $serverParams server-side parameters + * @throws \InvalidArgumentException for an invalid URL or body + */ + public function __construct( + $method, + $url, + array $headers = array(), + $body = '', + $version = '1.1', + $serverParams = array() + ) { + $stream = null; + if ($body instanceof ReadableStreamInterface && !$body instanceof StreamInterface) { + $stream = $body; + $body = null; + } elseif (!\is_string($body) && !$body instanceof StreamInterface) { + throw new \InvalidArgumentException('Invalid server request body given'); + } + + $this->serverParams = $serverParams; + parent::__construct($method, $url, $headers, $body, $version); + + if ($stream !== null) { + $size = (int) $this->getHeaderLine('Content-Length'); + if (\strtolower($this->getHeaderLine('Transfer-Encoding')) === 'chunked') { + $size = null; + } + $this->stream = new HttpBodyStream($stream, $size); + } + + $query = $this->getUri()->getQuery(); + if ($query !== '') { + \parse_str($query, $this->queryParams); + } + + // Multiple cookie headers are not allowed according + // to https://tools.ietf.org/html/rfc6265#section-5.4 + $cookieHeaders = $this->getHeader("Cookie"); + + if (count($cookieHeaders) === 1) { + $this->cookies = $this->parseCookie($cookieHeaders[0]); + } + } + + public function getServerParams() + { + return $this->serverParams; + } + + public function getCookieParams() + { + return $this->cookies; + } + + public function withCookieParams(array $cookies) + { + $new = clone $this; + $new->cookies = $cookies; + return $new; + } + + public function getQueryParams() + { + return $this->queryParams; + } + + public function withQueryParams(array $query) + { + $new = clone $this; + $new->queryParams = $query; + return $new; + } + + public function getUploadedFiles() + { + return $this->fileParams; + } + + public function withUploadedFiles(array $uploadedFiles) + { + $new = clone $this; + $new->fileParams = $uploadedFiles; + return $new; + } + + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data) + { + $new = clone $this; + $new->parsedBody = $data; + return $new; + } + + public function getAttributes() + { + return $this->attributes; + } + + public function getAttribute($name, $default = null) + { + if (!\array_key_exists($name, $this->attributes)) { + return $default; + } + return $this->attributes[$name]; + } + + public function withAttribute($name, $value) + { + $new = clone $this; + $new->attributes[$name] = $value; + return $new; + } + + public function withoutAttribute($name) + { + $new = clone $this; + unset($new->attributes[$name]); + return $new; + } + + /** + * @param string $cookie + * @return array + */ + private function parseCookie($cookie) + { + $cookieArray = \explode(';', $cookie); + $result = array(); + + foreach ($cookieArray as $pair) { + $pair = \trim($pair); + $nameValuePair = \explode('=', $pair, 2); + + if (\count($nameValuePair) === 2) { + $key = \urldecode($nameValuePair[0]); + $value = \urldecode($nameValuePair[1]); + $result[$key] = $value; + } + } + + return $result; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/LimitConcurrentRequestsMiddleware.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/LimitConcurrentRequestsMiddleware.php new file mode 100644 index 0000000..5333810 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/LimitConcurrentRequestsMiddleware.php @@ -0,0 +1,211 @@ +limit = $limit; + } + + public function __invoke(ServerRequestInterface $request, $next) + { + // happy path: simply invoke next request handler if we're below limit + if ($this->pending < $this->limit) { + ++$this->pending; + + try { + $response = $next($request); + } catch (\Exception $e) { + $this->processQueue(); + throw $e; + } catch (\Throwable $e) { // @codeCoverageIgnoreStart + // handle Errors just like Exceptions (PHP 7+ only) + $this->processQueue(); + throw $e; // @codeCoverageIgnoreEnd + } + + // happy path: if next request handler returned immediately, + // we can simply try to invoke the next queued request + if ($response instanceof ResponseInterface) { + $this->processQueue(); + return $response; + } + + // if the next handler returns a pending promise, we have to + // await its resolution before invoking next queued request + return $this->await(Promise\resolve($response)); + } + + // if we reach this point, then this request will need to be queued + // check if the body is streaming, in which case we need to buffer everything + $body = $request->getBody(); + if ($body instanceof ReadableStreamInterface) { + // pause actual body to stop emitting data until the handler is called + $size = $body->getSize(); + $body = new PauseBufferStream($body); + $body->pauseImplicit(); + + // replace with buffering body to ensure any readable events will be buffered + $request = $request->withBody(new HttpBodyStream( + $body, + $size + )); + } + + // get next queue position + $queue =& $this->queue; + $queue[] = null; + \end($queue); + $id = \key($queue); + + $deferred = new Deferred(function ($_, $reject) use (&$queue, $id) { + // queued promise cancelled before its next handler is invoked + // remove from queue and reject explicitly + unset($queue[$id]); + $reject(new \RuntimeException('Cancelled queued next handler')); + }); + + // queue request and process queue if pending does not exceed limit + $queue[$id] = $deferred; + + $pending = &$this->pending; + $that = $this; + return $deferred->promise()->then(function () use ($request, $next, $body, &$pending, $that) { + // invoke next request handler + ++$pending; + + try { + $response = $next($request); + } catch (\Exception $e) { + $that->processQueue(); + throw $e; + } catch (\Throwable $e) { // @codeCoverageIgnoreStart + // handle Errors just like Exceptions (PHP 7+ only) + $that->processQueue(); + throw $e; // @codeCoverageIgnoreEnd + } + + // resume readable stream and replay buffered events + if ($body instanceof PauseBufferStream) { + $body->resumeImplicit(); + } + + // if the next handler returns a pending promise, we have to + // await its resolution before invoking next queued request + return $that->await(Promise\resolve($response)); + }); + } + + /** + * @internal + * @param PromiseInterface $promise + * @return PromiseInterface + */ + public function await(PromiseInterface $promise) + { + $that = $this; + + return $promise->then(function ($response) use ($that) { + $that->processQueue(); + + return $response; + }, function ($error) use ($that) { + $that->processQueue(); + + return Promise\reject($error); + }); + } + + /** + * @internal + */ + public function processQueue() + { + // skip if we're still above concurrency limit or there's no queued request waiting + if (--$this->pending >= $this->limit || !$this->queue) { + return; + } + + $first = \reset($this->queue); + unset($this->queue[key($this->queue)]); + + $first->resolve(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyBufferMiddleware.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyBufferMiddleware.php new file mode 100644 index 0000000..c13a5de --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyBufferMiddleware.php @@ -0,0 +1,70 @@ +sizeLimit = IniUtil::iniSizeToBytes($sizeLimit); + } + + public function __invoke(ServerRequestInterface $request, $stack) + { + $body = $request->getBody(); + $size = $body->getSize(); + + // happy path: skip if body is known to be empty (or is already buffered) + if ($size === 0 || !$body instanceof ReadableStreamInterface) { + // replace with empty body if body is streaming (or buffered size exceeds limit) + if ($body instanceof ReadableStreamInterface || $size > $this->sizeLimit) { + $request = $request->withBody(new BufferedBody('')); + } + + return $stack($request); + } + + // request body of known size exceeding limit + $sizeLimit = $this->sizeLimit; + if ($size > $this->sizeLimit) { + $sizeLimit = 0; + } + + return Stream\buffer($body, $sizeLimit)->then(function ($buffer) use ($request, $stack) { + $request = $request->withBody(new BufferedBody($buffer)); + + return $stack($request); + }, function ($error) use ($stack, $request, $body) { + // On buffer overflow keep the request body stream in, + // but ignore the contents and wait for the close event + // before passing the request on to the next middleware. + if ($error instanceof OverflowException) { + return Stream\first($body, 'close')->then(function () use ($stack, $request) { + return $stack($request); + }); + } + + throw $error; + }); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyParserMiddleware.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyParserMiddleware.php new file mode 100644 index 0000000..be5ba16 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/RequestBodyParserMiddleware.php @@ -0,0 +1,46 @@ +multipart = new MultipartParser($uploadMaxFilesize, $maxFileUploads); + } + + public function __invoke(ServerRequestInterface $request, $next) + { + $type = \strtolower($request->getHeaderLine('Content-Type')); + list ($type) = \explode(';', $type); + + if ($type === 'application/x-www-form-urlencoded') { + return $next($this->parseFormUrlencoded($request)); + } + + if ($type === 'multipart/form-data') { + return $next($this->multipart->parse($request)); + } + + return $next($request); + } + + private function parseFormUrlencoded(ServerRequestInterface $request) + { + // parse string into array structure + // ignore warnings due to excessive data structures (max_input_vars and max_input_nesting_level) + $ret = array(); + @\parse_str((string)$request->getBody(), $ret); + + return $request->withParsedBody($ret); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/StreamingRequestMiddleware.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/StreamingRequestMiddleware.php new file mode 100644 index 0000000..6ab74b7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Middleware/StreamingRequestMiddleware.php @@ -0,0 +1,69 @@ +getBody(); + * assert($body instanceof Psr\Http\Message\StreamInterface); + * assert($body instanceof React\Stream\ReadableStreamInterface); + * + * return new React\Promise\Promise(function ($resolve) use ($body) { + * $bytes = 0; + * $body->on('data', function ($chunk) use (&$bytes) { + * $bytes += \count($chunk); + * }); + * $body->on('close', function () use (&$bytes, $resolve) { + * $resolve(new React\Http\Response( + * 200, + * [], + * "Received $bytes bytes\n" + * )); + * }); + * }); + * } + * ); + * ``` + * + * See also [streaming incoming request](../../README.md#streaming-incoming-request) + * for more details. + * + * Additionally, this middleware can be used in combination with the + * [`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and + * [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) + * to explicitly configure the total number of requests that can be handled at + * once: + * + * ```php + * $http = new React\Http\HttpServer( + * new React\Http\Middleware\StreamingRequestMiddleware(), + * new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers + * new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request + * new React\Http\Middleware\RequestBodyParserMiddleware(), + * $handler + * ); + * ``` + * + * > Internally, this class is used as a "marker" to not trigger the default + * request buffering behavior in the `HttpServer`. It does not implement any logic + * on its own. + */ +final class StreamingRequestMiddleware +{ + public function __invoke(ServerRequestInterface $request, $next) + { + return $next($request); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Server.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Server.php new file mode 100644 index 0000000..9bb9cf7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/http/src/Server.php @@ -0,0 +1,18 @@ + Contains no other changes, so it's actually fully compatible with the v0.1.2 release. + +## 0.1.2 (2017-10-18) + +* Feature: Optional maximum buffer length for `buffer()` (#3 by @WyriHaximus) +* Improvement: Readme improvements (#5 by @jsor) + +## 0.1.1 (2017-05-15) + +* Improvement: Forward compatibility with stream 1.0, 0.7, 0.6, and 0.5 (#2 by @WyriHaximus) + +## 0.1.0 (2017-05-10) + +* Initial release, adapted from [`clue/promise-stream-react`](https://github.com/clue/php-promise-stream-react) diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/LICENSE new file mode 100644 index 0000000..7baae8e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Christian Lück + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/README.md new file mode 100644 index 0000000..68ace16 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/README.md @@ -0,0 +1,282 @@ +# PromiseStream + +[![Build Status](https://travis-ci.org/reactphp/promise-stream.svg?branch=master)](https://travis-ci.org/reactphp/promise-stream) + +The missing link between Promise-land and Stream-land +for [ReactPHP](https://reactphp.org/). + +**Table of Contents** + +* [Usage](#usage) + * [buffer()](#buffer) + * [first()](#first) + * [all()](#all) + * [unwrapReadable()](#unwrapreadable) + * [unwrapWritable()](#unwrapwritable) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +This lightweight library consists only of a few simple functions. +All functions reside under the `React\Promise\Stream` namespace. + +The below examples assume you use an import statement similar to this: + +```php +use React\Promise\Stream; + +Stream\buffer(…); +``` + +Alternatively, you can also refer to them with their fully-qualified name: + +```php +\React\Promise\Stream\buffer(…); +``` + +### buffer() + +The `buffer(ReadableStreamInterface $stream, ?int $maxLength = null): PromiseInterface` function can be used to +create a `Promise` which resolves with the stream data buffer. + +```php +$stream = accessSomeJsonStream(); + +Stream\buffer($stream)->then(function ($contents) { + var_dump(json_decode($contents)); +}); +``` + +The promise will resolve with all data chunks concatenated once the stream closes. + +The promise will resolve with an empty string if the stream is already closed. + +The promise will reject if the stream emits an error. + +The promise will reject if it is cancelled. + +The optional `$maxLength` argument defaults to no limit. In case the maximum +length is given and the stream emits more data before the end, the promise +will be rejected with an `\OverflowException`. + +```php +$stream = accessSomeToLargeStream(); + +Stream\buffer($stream, 1024)->then(function ($contents) { + var_dump(json_decode($contents)); +}, function ($error) { + // Reaching here when the stream buffer goes above the max size, + // in this example that is 1024 bytes, + // or when the stream emits an error. +}); +``` + +### first() + +The `first(ReadableStreamInterface|WritableStreamInterface $stream, string $event = 'data'): PromiseInterface` function can be used to +create a `Promise` which resolves once the given event triggers for the first time. + +```php +$stream = accessSomeJsonStream(); + +Stream\first($stream)->then(function ($chunk) { + echo 'The first chunk arrived: ' . $chunk; +}); +``` + +The promise will resolve with whatever the first event emitted or `null` if the +event does not pass any data. +If you do not pass a custom event name, then it will wait for the first "data" +event and resolve with a string containing the first data chunk. + +The promise will reject if the stream emits an error – unless you're waiting for +the "error" event, in which case it will resolve. + +The promise will reject once the stream closes – unless you're waiting for the +"close" event, in which case it will resolve. + +The promise will reject if the stream is already closed. + +The promise will reject if it is cancelled. + +### all() + +The `all(ReadableStreamInterface|WritableStreamInterface $stream, string $event = 'data'): PromiseInterface` function can be used to +create a `Promise` which resolves with an array of all the event data. + +```php +$stream = accessSomeJsonStream(); + +Stream\all($stream)->then(function ($chunks) { + echo 'The stream consists of ' . count($chunks) . ' chunk(s)'; +}); +``` + +The promise will resolve with an array of whatever all events emitted or `null` if the +events do not pass any data. +If you do not pass a custom event name, then it will wait for all the "data" +events and resolve with an array containing all the data chunks. + +The promise will resolve with an array once the stream closes. + +The promise will resolve with an empty array if the stream is already closed. + +The promise will reject if the stream emits an error. + +The promise will reject if it is cancelled. + +### unwrapReadable() + +The `unwrapReadable(PromiseInterface $promise): ReadableStreamInterface` function can be used to +unwrap a `Promise` which resolves with a `ReadableStreamInterface`. + +This function returns a readable stream instance (implementing `ReadableStreamInterface`) +right away which acts as a proxy for the future promise resolution. +Once the given Promise resolves with a `ReadableStreamInterface`, its data will +be piped to the output stream. + +```php +//$promise = someFunctionWhichResolvesWithAStream(); +$promise = startDownloadStream($uri); + +$stream = Stream\unwrapReadable($promise); + +$stream->on('data', function ($data) { + echo $data; +}); + +$stream->on('end', function () { + echo 'DONE'; +}); +``` + +If the given promise is either rejected or fulfilled with anything but an +instance of `ReadableStreamInterface`, then the output stream will emit +an `error` event and close: + +```php +$promise = startDownloadStream($invalidUri); + +$stream = Stream\unwrapReadable($promise); + +$stream->on('error', function (Exception $error) { + echo 'Error: ' . $error->getMessage(); +}); +``` + +The given `$promise` SHOULD be pending, i.e. it SHOULD NOT be fulfilled or rejected +at the time of invoking this function. +If the given promise is already settled and does not resolve with an +instance of `ReadableStreamInterface`, then you will not be able to receive +the `error` event. + +You can `close()` the resulting stream at any time, which will either try to +`cancel()` the pending promise or try to `close()` the underlying stream. + +```php +$promise = startDownloadStream($uri); + +$stream = Stream\unwrapReadable($promise); + +$loop->addTimer(2.0, function () use ($stream) { + $stream->close(); +}); +``` + +### unwrapWritable() + +The `unwrapWritable(PromiseInterface $promise): WritableStreamInterface` function can be used to +unwrap a `Promise` which resolves with a `WritableStreamInterface`. + +This function returns a writable stream instance (implementing `WritableStreamInterface`) +right away which acts as a proxy for the future promise resolution. +Any writes to this instance will be buffered in memory for when the promise resolves. +Once the given Promise resolves with a `WritableStreamInterface`, any data you +have written to the proxy will be forwarded transparently to the inner stream. + +```php +//$promise = someFunctionWhichResolvesWithAStream(); +$promise = startUploadStream($uri); + +$stream = Stream\unwrapWritable($promise); + +$stream->write('hello'); +$stream->end('world'); + +$stream->on('close', function () { + echo 'DONE'; +}); +``` + +If the given promise is either rejected or fulfilled with anything but an +instance of `WritableStreamInterface`, then the output stream will emit +an `error` event and close: + +```php +$promise = startUploadStream($invalidUri); + +$stream = Stream\unwrapWritable($promise); + +$stream->on('error', function (Exception $error) { + echo 'Error: ' . $error->getMessage(); +}); +``` + +The given `$promise` SHOULD be pending, i.e. it SHOULD NOT be fulfilled or rejected +at the time of invoking this function. +If the given promise is already settled and does not resolve with an +instance of `WritableStreamInterface`, then you will not be able to receive +the `error` event. + +You can `close()` the resulting stream at any time, which will either try to +`cancel()` the pending promise or try to `close()` the underlying stream. + +```php +$promise = startUploadStream($uri); + +$stream = Stream\unwrapWritable($promise); + +$loop->addTimer(2.0, function () use ($stream) { + $stream->close(); +}); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/promise-stream:^1.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 7+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/composer.json new file mode 100644 index 0000000..7fe0bc3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/composer.json @@ -0,0 +1,31 @@ +{ + "name": "react/promise-stream", + "description": "The missing link between Promise-land and Stream-land for ReactPHP", + "keywords": ["unwrap", "stream", "buffer", "promise", "ReactPHP", "async"], + "homepage": "https://github.com/reactphp/promise-stream", + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "email": "christian@lueck.tv" + } + ], + "autoload": { + "psr-4": { "React\\Promise\\Stream\\" : "src/" }, + "files": [ "src/functions_include.php" ] + }, + "autoload-dev": { + "psr-4": { "React\\Tests\\Promise\\Stream\\": "tests/" } + }, + "require": { + "php": ">=5.3", + "react/stream": "^1.0 || ^0.7 || ^0.6 || ^0.5 || ^0.4.6", + "react/promise": "^2.1 || ^1.2" + }, + "require-dev": { + "react/event-loop": "^1.0 || ^0.5 || ^0.4 || ^0.3", + "react/promise-timer": "^1.0", + "clue/block-react": "^1.0", + "phpunit/phpunit": "^7.0 || ^6.4 || ^5.7 || ^4.8.35" + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/phpunit.xml.dist b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/phpunit.xml.dist new file mode 100644 index 0000000..a40caa1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/phpunit.xml.dist @@ -0,0 +1,19 @@ + + + + + + ./tests/ + + + + + ./src/ + + + \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapReadableStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapReadableStream.php new file mode 100644 index 0000000..acd23be --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapReadableStream.php @@ -0,0 +1,137 @@ + + */ + public function __construct(PromiseInterface $promise) + { + $out = $this; + $closed =& $this->closed; + + $this->promise = $promise->then( + function ($stream) { + if (!$stream instanceof ReadableStreamInterface) { + throw new InvalidArgumentException('Not a readable stream'); + } + return $stream; + } + )->then( + function (ReadableStreamInterface $stream) use ($out, &$closed) { + // stream is already closed, make sure to close output stream + if (!$stream->isReadable()) { + $out->close(); + return $stream; + } + + // resolves but output is already closed, make sure to close stream silently + if ($closed) { + $stream->close(); + return $stream; + } + + // stream any writes into output stream + $stream->on('data', function ($data) use ($out) { + $out->emit('data', array($data, $out)); + }); + + // forward end events and close + $stream->on('end', function () use ($out, &$closed) { + if (!$closed) { + $out->emit('end', array($out)); + $out->close(); + } + }); + + // error events cancel output stream + $stream->on('error', function ($error) use ($out) { + $out->emit('error', array($error, $out)); + $out->close(); + }); + + // close both streams once either side closes + $stream->on('close', array($out, 'close')); + $out->on('close', array($stream, 'close')); + + return $stream; + }, + function ($e) use ($out, &$closed) { + if (!$closed) { + $out->emit('error', array($e, $out)); + $out->close(); + } + + // resume() and pause() may attach to this promise, so ensure we actually reject here + throw $e; + } + ); + } + + public function isReadable() + { + return !$this->closed; + } + + public function pause() + { + if ($this->promise !== null) { + $this->promise->then(function (ReadableStreamInterface $stream) { + $stream->pause(); + }); + } + } + + public function resume() + { + if ($this->promise !== null) { + $this->promise->then(function (ReadableStreamInterface $stream) { + $stream->resume(); + }); + } + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + + return $dest; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + // try to cancel promise once the stream closes + if ($this->promise instanceof CancellablePromiseInterface) { + $this->promise->cancel(); + } + $this->promise = null; + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapWritableStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapWritableStream.php new file mode 100644 index 0000000..f19e706 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/UnwrapWritableStream.php @@ -0,0 +1,164 @@ + + */ + public function __construct(PromiseInterface $promise) + { + $out = $this; + $store =& $this->stream; + $buffer =& $this->buffer; + $ending =& $this->ending; + $closed =& $this->closed; + + $this->promise = $promise->then( + function ($stream) { + if (!$stream instanceof WritableStreamInterface) { + throw new InvalidArgumentException('Not a writable stream'); + } + return $stream; + } + )->then( + function (WritableStreamInterface $stream) use ($out, &$store, &$buffer, &$ending, &$closed) { + // stream is already closed, make sure to close output stream + if (!$stream->isWritable()) { + $out->close(); + return $stream; + } + + // resolves but output is already closed, make sure to close stream silently + if ($closed) { + $stream->close(); + return $stream; + } + + // forward drain events for back pressure + $stream->on('drain', function () use ($out) { + $out->emit('drain', array($out)); + }); + + // error events cancel output stream + $stream->on('error', function ($error) use ($out) { + $out->emit('error', array($error, $out)); + $out->close(); + }); + + // close both streams once either side closes + $stream->on('close', array($out, 'close')); + $out->on('close', array($stream, 'close')); + + if ($buffer) { + // flush buffer to stream and check if its buffer is not exceeded + $drained = true; + foreach ($buffer as $chunk) { + if (!$stream->write($chunk)) { + $drained = false; + } + } + $buffer = array(); + + if ($drained) { + // signal drain event, because the output stream previous signalled a full buffer + $out->emit('drain', array($out)); + } + } + + if ($ending) { + $stream->end(); + } else { + $store = $stream; + } + + return $stream; + }, + function ($e) use ($out, &$closed) { + if (!$closed) { + $out->emit('error', array($e, $out)); + $out->close(); + } + } + ); + } + + public function write($data) + { + if ($this->ending) { + return false; + } + + // forward to inner stream if possible + if ($this->stream !== null) { + return $this->stream->write($data); + } + + // append to buffer and signal the buffer is full + $this->buffer[] = $data; + return false; + } + + public function end($data = null) + { + if ($this->ending) { + return; + } + + $this->ending = true; + + // forward to inner stream if possible + if ($this->stream !== null) { + return $this->stream->end($data); + } + + // append to buffer + if ($data !== null) { + $this->buffer[] = $data; + } + } + + public function isWritable() + { + return !$this->ending; + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->buffer = array(); + $this->ending = true; + $this->closed = true; + + // try to cancel promise once the stream closes + if ($this->promise instanceof CancellablePromiseInterface) { + $this->promise->cancel(); + } + $this->promise = $this->stream = null; + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions.php new file mode 100644 index 0000000..6a4c9a1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions.php @@ -0,0 +1,356 @@ +then(function ($contents) { + * var_dump(json_decode($contents)); + * }); + * ``` + * + * The promise will resolve with all data chunks concatenated once the stream closes. + * + * The promise will resolve with an empty string if the stream is already closed. + * + * The promise will reject if the stream emits an error. + * + * The promise will reject if it is cancelled. + * + * The optional `$maxLength` argument defaults to no limit. In case the maximum + * length is given and the stream emits more data before the end, the promise + * will be rejected with an `\OverflowException`. + * + * ```php + * $stream = accessSomeToLargeStream(); + * + * Stream\buffer($stream, 1024)->then(function ($contents) { + * var_dump(json_decode($contents)); + * }, function ($error) { + * // Reaching here when the stream buffer goes above the max size, + * // in this example that is 1024 bytes, + * // or when the stream emits an error. + * }); + * ``` + * + * @param ReadableStreamInterface $stream + * @param ?int $maxLength Maximum number of bytes to buffer or null for unlimited. + * @return PromiseInterface + */ +function buffer(ReadableStreamInterface $stream, $maxLength = null) +{ + // stream already ended => resolve with empty buffer + if (!$stream->isReadable()) { + return Promise\resolve(''); + } + + $buffer = ''; + + $promise = new Promise\Promise(function ($resolve, $reject) use ($stream, $maxLength, &$buffer, &$bufferer) { + $bufferer = function ($data) use (&$buffer, $reject, $maxLength) { + $buffer .= $data; + + if ($maxLength !== null && isset($buffer[$maxLength])) { + $reject(new \OverflowException('Buffer exceeded maximum length')); + } + }; + + $stream->on('data', $bufferer); + + $stream->on('error', function ($error) use ($reject) { + $reject(new \RuntimeException('An error occured on the underlying stream while buffering', 0, $error)); + }); + + $stream->on('close', function () use ($resolve, &$buffer) { + $resolve($buffer); + }); + }, function ($_, $reject) { + $reject(new \RuntimeException('Cancelled buffering')); + }); + + return $promise->then(null, function ($error) use (&$buffer, $bufferer, $stream) { + // promise rejected => clear buffer and buffering + $buffer = ''; + $stream->removeListener('data', $bufferer); + + throw $error; + }); +} + +/** + * Creates a `Promise` which resolves once the given event triggers for the first time. + * + * ```php + * $stream = accessSomeJsonStream(); + * + * Stream\first($stream)->then(function ($chunk) { + * echo 'The first chunk arrived: ' . $chunk; + * }); + * ``` + * + * The promise will resolve with whatever the first event emitted or `null` if the + * event does not pass any data. + * If you do not pass a custom event name, then it will wait for the first "data" + * event and resolve with a string containing the first data chunk. + * + * The promise will reject if the stream emits an error – unless you're waiting for + * the "error" event, in which case it will resolve. + * + * The promise will reject once the stream closes – unless you're waiting for the + * "close" event, in which case it will resolve. + * + * The promise will reject if the stream is already closed. + * + * The promise will reject if it is cancelled. + * + * @param ReadableStreamInterface|WritableStreamInterface $stream + * @param string $event + * @return PromiseInterface + */ +function first(EventEmitterInterface $stream, $event = 'data') +{ + if ($stream instanceof ReadableStreamInterface) { + // readable or duplex stream not readable => already closed + // a half-open duplex stream is considered closed if its readable side is closed + if (!$stream->isReadable()) { + return Promise\reject(new \RuntimeException('Stream already closed')); + } + } elseif ($stream instanceof WritableStreamInterface) { + // writable-only stream (not duplex) not writable => already closed + if (!$stream->isWritable()) { + return Promise\reject(new \RuntimeException('Stream already closed')); + } + } + + return new Promise\Promise(function ($resolve, $reject) use ($stream, $event, &$listener) { + $listener = function ($data = null) use ($stream, $event, &$listener, $resolve) { + $stream->removeListener($event, $listener); + $resolve($data); + }; + $stream->on($event, $listener); + + if ($event !== 'error') { + $stream->on('error', function ($error) use ($stream, $event, $listener, $reject) { + $stream->removeListener($event, $listener); + $reject(new \RuntimeException('An error occured on the underlying stream while waiting for event', 0, $error)); + }); + } + + $stream->on('close', function () use ($stream, $event, $listener, $reject) { + $stream->removeListener($event, $listener); + $reject(new \RuntimeException('Stream closed')); + }); + }, function ($_, $reject) use ($stream, $event, &$listener) { + $stream->removeListener($event, $listener); + $reject(new \RuntimeException('Operation cancelled')); + }); +} + +/** + * Creates a `Promise` which resolves with an array of all the event data. + * + * ```php + * $stream = accessSomeJsonStream(); + * + * Stream\all($stream)->then(function ($chunks) { + * echo 'The stream consists of ' . count($chunks) . ' chunk(s)'; + * }); + * ``` + * + * The promise will resolve with an array of whatever all events emitted or `null` if the + * events do not pass any data. + * If you do not pass a custom event name, then it will wait for all the "data" + * events and resolve with an array containing all the data chunks. + * + * The promise will resolve with an array once the stream closes. + * + * The promise will resolve with an empty array if the stream is already closed. + * + * The promise will reject if the stream emits an error. + * + * The promise will reject if it is cancelled. + * + * @param ReadableStreamInterface|WritableStreamInterface $stream + * @param string $event + * @return PromiseInterface + */ +function all(EventEmitterInterface $stream, $event = 'data') +{ + // stream already ended => resolve with empty buffer + if ($stream instanceof ReadableStreamInterface) { + // readable or duplex stream not readable => already closed + // a half-open duplex stream is considered closed if its readable side is closed + if (!$stream->isReadable()) { + return Promise\resolve(array()); + } + } elseif ($stream instanceof WritableStreamInterface) { + // writable-only stream (not duplex) not writable => already closed + if (!$stream->isWritable()) { + return Promise\resolve(array()); + } + } + + $buffer = array(); + $bufferer = function ($data = null) use (&$buffer) { + $buffer []= $data; + }; + $stream->on($event, $bufferer); + + $promise = new Promise\Promise(function ($resolve, $reject) use ($stream, &$buffer) { + $stream->on('error', function ($error) use ($reject) { + $reject(new \RuntimeException('An error occured on the underlying stream while buffering', 0, $error)); + }); + + $stream->on('close', function () use ($resolve, &$buffer) { + $resolve($buffer); + }); + }, function ($_, $reject) { + $reject(new \RuntimeException('Cancelled buffering')); + }); + + return $promise->then(null, function ($error) use (&$buffer, $bufferer, $stream, $event) { + // promise rejected => clear buffer and buffering + $buffer = array(); + $stream->removeListener($event, $bufferer); + + throw $error; + }); +} + +/** + * Unwraps a `Promise` which resolves with a `ReadableStreamInterface`. + * + * This function returns a readable stream instance (implementing `ReadableStreamInterface`) + * right away which acts as a proxy for the future promise resolution. + * Once the given Promise resolves with a `ReadableStreamInterface`, its data will + * be piped to the output stream. + * + * ```php + * //$promise = someFunctionWhichResolvesWithAStream(); + * $promise = startDownloadStream($uri); + * + * $stream = Stream\unwrapReadable($promise); + * + * $stream->on('data', function ($data) { + * echo $data; + * }); + * + * $stream->on('end', function () { + * echo 'DONE'; + * }); + * ``` + * + * If the given promise is either rejected or fulfilled with anything but an + * instance of `ReadableStreamInterface`, then the output stream will emit + * an `error` event and close: + * + * ```php + * $promise = startDownloadStream($invalidUri); + * + * $stream = Stream\unwrapReadable($promise); + * + * $stream->on('error', function (Exception $error) { + * echo 'Error: ' . $error->getMessage(); + * }); + * ``` + * + * The given `$promise` SHOULD be pending, i.e. it SHOULD NOT be fulfilled or rejected + * at the time of invoking this function. + * If the given promise is already settled and does not resolve with an + * instance of `ReadableStreamInterface`, then you will not be able to receive + * the `error` event. + * + * You can `close()` the resulting stream at any time, which will either try to + * `cancel()` the pending promise or try to `close()` the underlying stream. + * + * ```php + * $promise = startDownloadStream($uri); + * + * $stream = Stream\unwrapReadable($promise); + * + * $loop->addTimer(2.0, function () use ($stream) { + * $stream->close(); + * }); + * ``` + * + * @param PromiseInterface $promise + * @return ReadableStreamInterface + */ +function unwrapReadable(PromiseInterface $promise) +{ + return new UnwrapReadableStream($promise); +} + +/** + * Unwraps a `Promise` which resolves with a `WritableStreamInterface`. + * + * This function returns a writable stream instance (implementing `WritableStreamInterface`) + * right away which acts as a proxy for the future promise resolution. + * Any writes to this instance will be buffered in memory for when the promise resolves. + * Once the given Promise resolves with a `WritableStreamInterface`, any data you + * have written to the proxy will be forwarded transparently to the inner stream. + * + * ```php + * //$promise = someFunctionWhichResolvesWithAStream(); + * $promise = startUploadStream($uri); + * + * $stream = Stream\unwrapWritable($promise); + * + * $stream->write('hello'); + * $stream->end('world'); + * + * $stream->on('close', function () { + * echo 'DONE'; + * }); + * ``` + * + * If the given promise is either rejected or fulfilled with anything but an + * instance of `WritableStreamInterface`, then the output stream will emit + * an `error` event and close: + * + * ```php + * $promise = startUploadStream($invalidUri); + * + * $stream = Stream\unwrapWritable($promise); + * + * $stream->on('error', function (Exception $error) { + * echo 'Error: ' . $error->getMessage(); + * }); + * ``` + * + * The given `$promise` SHOULD be pending, i.e. it SHOULD NOT be fulfilled or rejected + * at the time of invoking this function. + * If the given promise is already settled and does not resolve with an + * instance of `WritableStreamInterface`, then you will not be able to receive + * the `error` event. + * + * You can `close()` the resulting stream at any time, which will either try to + * `cancel()` the pending promise or try to `close()` the underlying stream. + * + * ```php + * $promise = startUploadStream($uri); + * + * $stream = Stream\unwrapWritable($promise); + * + * $loop->addTimer(2.0, function () use ($stream) { + * $stream->close(); + * }); + * ``` + * + * @param PromiseInterface $promise + * @return WritableStreamInterface + */ +function unwrapWritable(PromiseInterface $promise) +{ + return new UnwrapWritableStream($promise); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions_include.php new file mode 100644 index 0000000..768a4fd --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/src/functions_include.php @@ -0,0 +1,7 @@ +close(); + + $promise = Stream\all($stream); + + $this->expectPromiseResolveWith(array(), $promise); + } + + public function testClosedWritableStreamResolvesWithEmptyBuffer() + { + $stream = new ThroughStream(); + $stream->close(); + + $promise = Stream\all($stream); + + $this->expectPromiseResolveWith(array(), $promise); + } + + public function testPendingStreamWillNotResolve() + { + $stream = new ThroughStream(); + + $promise = Stream\all($stream); + + $promise->then($this->expectCallableNever(), $this->expectCallableNever()); + } + + public function testClosingStreamResolvesWithEmptyBuffer() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream); + + $stream->close(); + + $this->expectPromiseResolveWith(array(), $promise); + } + + public function testClosingWritableStreamResolvesWithEmptyBuffer() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream); + + $stream->close(); + + $this->expectPromiseResolveWith(array(), $promise); + } + + public function testEmittingDataOnStreamResolvesWithArrayOfData() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream); + + $stream->emit('data', array('hello', $stream)); + $stream->emit('data', array('world', $stream)); + $stream->close(); + + $this->expectPromiseResolveWith(array('hello', 'world'), $promise); + } + + public function testEmittingCustomEventOnStreamResolvesWithArrayOfCustomEventData() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream, 'a'); + + $stream->emit('a', array('hello')); + $stream->emit('b', array('ignored')); + $stream->emit('a'); + $stream->close(); + + $this->expectPromiseResolveWith(array('hello', null), $promise); + } + + public function testEmittingErrorOnStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream); + + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseReject($promise); + } + + public function testEmittingErrorAfterEmittingDataOnStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\all($stream); + + $stream->emit('data', array('hello', $stream)); + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseReject($promise); + } + + public function testCancelPendingStreamWillReject() + { + $stream = new ThroughStream(); + + $promise = Stream\all($stream); + + $promise->cancel(); + + $this->expectPromiseReject($promise); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/BufferTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/BufferTest.php new file mode 100644 index 0000000..567d26a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/BufferTest.php @@ -0,0 +1,120 @@ +close(); + + $promise = Stream\buffer($stream); + + $this->expectPromiseResolveWith('', $promise); + } + + public function testPendingStreamWillNotResolve() + { + $stream = new ThroughStream(); + + $promise = Stream\buffer($stream); + + $promise->then($this->expectCallableNever(), $this->expectCallableNever()); + } + + public function testClosingStreamResolvesWithEmptyBuffer() + { + $stream = new ThroughStream(); + $promise = Stream\buffer($stream); + + $stream->close(); + + $this->expectPromiseResolveWith('', $promise); + } + + public function testEmittingDataOnStreamResolvesWithConcatenatedData() + { + $stream = new ThroughStream(); + $promise = Stream\buffer($stream); + + $stream->emit('data', array('hello', $stream)); + $stream->emit('data', array('world', $stream)); + $stream->close(); + + $this->expectPromiseResolveWith('helloworld', $promise); + } + + public function testEmittingErrorOnStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\buffer($stream); + + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseReject($promise); + } + + public function testEmittingErrorAfterEmittingDataOnStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\buffer($stream); + + $stream->emit('data', array('hello', $stream)); + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseReject($promise); + } + + public function testCancelPendingStreamWillReject() + { + $stream = new ThroughStream(); + + $promise = Stream\buffer($stream); + + $promise->cancel(); + + $this->expectPromiseReject($promise); + } + + public function testMaximumSize() + { + $loop = Factory::create(); + $stream = new ThroughStream(); + + $loop->addTimer(0.1, function () use ($stream) { + $stream->write('12345678910111213141516'); + }); + + $promise = Stream\buffer($stream, 16); + + if (method_exists($this, 'expectException')) { + $this->expectException('OverflowException'); + $this->expectExceptionMessage('Buffer exceeded maximum length'); + } else { + $this->setExpectedException('\OverflowException', 'Buffer exceeded maximum length'); + } + Block\await($promise, $loop, 10); + } + + public function testUnderMaximumSize() + { + $loop = Factory::create(); + $stream = new ThroughStream(); + + $loop->addTimer(0.1, function () use ($stream) { + $stream->write('1234567891011'); + $stream->end(); + }); + + $promise = Stream\buffer($stream, 16); + + $result = Block\await($promise, $loop, 10); + $this->assertSame('1234567891011', $result); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/CallableStub.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/CallableStub.php new file mode 100644 index 0000000..f398c04 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/CallableStub.php @@ -0,0 +1,10 @@ +close(); + + $promise = Stream\first($stream); + + $this->expectPromiseReject($promise); + } + + public function testClosedWritableStreamRejects() + { + $stream = new ThroughStream(); + $stream->close(); + + $promise = Stream\first($stream); + + $this->expectPromiseReject($promise); + } + + public function testPendingStreamWillNotResolve() + { + $stream = new ThroughStream(); + + $promise = Stream\first($stream); + + $promise->then($this->expectCallableNever(), $this->expectCallableNever()); + } + + public function testClosingStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream); + + $stream->close(); + + $this->expectPromiseReject($promise); + } + + public function testClosingWritableStreamRejects() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream); + + $stream->close(); + + $this->expectPromiseReject($promise); + } + + public function testClosingStreamResolvesWhenWaitingForCloseEvent() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream, 'close'); + + $stream->close(); + + $this->expectPromiseResolve($promise); + } + + public function testEmittingDataOnStreamResolvesWithFirstEvent() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream); + + $stream->emit('data', array('hello', $stream)); + $stream->emit('data', array('world', $stream)); + $stream->close(); + + $this->expectPromiseResolveWith('hello', $promise); + } + + public function testEmittingErrorOnStreamWillReject() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream); + + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseReject($promise); + } + + public function testEmittingErrorResolvesWhenWaitingForErrorEvent() + { + $stream = new ThroughStream(); + $promise = Stream\first($stream, 'error'); + + $stream->emit('error', array(new \RuntimeException('test'))); + + $this->expectPromiseResolve($promise); + } + + public function testCancelPendingStreamWillReject() + { + $stream = new ThroughStream(); + + $promise = Stream\first($stream); + + $promise->cancel(); + + $this->expectPromiseReject($promise); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/TestCase.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/TestCase.php new file mode 100644 index 0000000..f73c2d4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/TestCase.php @@ -0,0 +1,85 @@ +createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke'); + + return $mock; + } + + protected function expectCallableOnceWith($value) + { + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->equalTo($value)); + + return $mock; + } + + protected function expectCallableOnceParameter($type) + { + $mock = $this->createCallableMock(); + $mock + ->expects($this->once()) + ->method('__invoke') + ->with($this->isInstanceOf($type)); + + return $mock; + } + + protected function expectCallableNever() + { + $mock = $this->createCallableMock(); + $mock + ->expects($this->never()) + ->method('__invoke'); + + return $mock; + } + + /** + * @link https://github.com/reactphp/react/blob/master/tests/React/Tests/Socket/TestCase.php (taken from reactphp/react) + */ + protected function createCallableMock() + { + return $this->getMockBuilder('React\Tests\Promise\Stream\CallableStub')->getMock(); + } + + protected function expectPromiseResolve($promise) + { + $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + + $promise->then($this->expectCallableOnce(), $this->expectCallableNever()); + + return $promise; + } + + protected function expectPromiseResolveWith($with, $promise) + { + $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + + $promise->then($this->expectCallableOnce($with), $this->expectCallableNever()); + + return $promise; + } + + protected function expectPromiseReject($promise) + { + $this->assertInstanceOf('React\Promise\PromiseInterface', $promise); + + $promise->then($this->expectCallableNever(), $this->expectCallableOnce()); + + return $promise; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapReadableTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapReadableTest.php new file mode 100644 index 0000000..a6db4de --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapReadableTest.php @@ -0,0 +1,345 @@ +loop = Factory::create(); + } + + public function testReturnsReadableStreamForPromise() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $this->assertTrue($stream->isReadable()); + } + + public function testClosingStreamMakesItNotReadable() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $stream->on('end', $this->expectCallableNever()); + $stream->on('error', $this->expectCallableNever()); + + $stream->close(); + + $this->assertFalse($stream->isReadable()); + } + + public function testClosingRejectingStreamMakesItNotReadable() + { + $promise = Timer\reject(0.001, $this->loop); + $stream = Stream\unwrapReadable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $stream->on('end', $this->expectCallableNever()); + $stream->on('error', $this->expectCallableNever()); + + $stream->close(); + $this->loop->run(); + + $this->assertFalse($stream->isReadable()); + } + + public function testClosingStreamWillCancelInputPromiseAndMakeStreamNotReadable() + { + $promise = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $stream = Stream\unwrapReadable($promise); + + $stream->close(); + + $this->assertFalse($stream->isReadable()); + } + + public function testEmitsErrorWhenPromiseRejects() + { + $promise = Timer\reject(0.001, $this->loop); + + $stream = Stream\unwrapReadable($promise); + + $this->assertTrue($stream->isReadable()); + + $stream->on('error', $this->expectCallableOnce()); + $stream->on('end', $this->expectCallableNever()); + + $this->loop->run(); + + $this->assertFalse($stream->isReadable()); + } + + public function testEmitsErrorWhenPromiseResolvesWithWrongValue() + { + $promise = Timer\resolve(0.001, $this->loop); + + $stream = Stream\unwrapReadable($promise); + + $this->assertTrue($stream->isReadable()); + + $stream->on('error', $this->expectCallableOnce()); + $stream->on('end', $this->expectCallableNever()); + + $this->loop->run(); + + $this->assertFalse($stream->isReadable()); + } + + public function testReturnsClosedStreamIfInputStreamIsClosed() + { + $input = new ThroughStream(); + $input->close(); + + $promise = Promise\resolve($input); + + $stream = Stream\unwrapReadable($promise); + + $this->assertFalse($stream->isReadable()); + } + + public function testReturnsClosedStreamIfInputHasWrongValue() + { + $promise = Promise\resolve(42); + + $stream = Stream\unwrapReadable($promise); + + $this->assertFalse($stream->isReadable()); + } + + public function testReturnsStreamThatWillBeClosedWhenPromiseResolvesWithClosedInputStream() + { + $input = new ThroughStream(); + $input->close(); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + + $stream = Stream\unwrapReadable($promise); + + $this->assertTrue($stream->isReadable()); + + $stream->on('close', $this->expectCallableOnce()); + + $this->loop->run(); + + $this->assertFalse($stream->isReadable()); + } + + public function testEmitsDataWhenInputEmitsData() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->on('data', $this->expectCallableOnceWith('hello world')); + $input->emit('data', array('hello world')); + } + + public function testEmitsErrorAndClosesWhenInputEmitsError() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->on('error', $this->expectCallableOnceWith(new \RuntimeException())); + $stream->on('close', $this->expectCallableOnce()); + $input->emit('error', array(new \RuntimeException())); + + $this->assertFalse($stream->isReadable()); + } + + public function testEmitsEndAndClosesWhenInputEmitsEnd() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->on('end', $this->expectCallableOnce()); + $stream->on('close', $this->expectCallableOnce()); + $input->emit('end', array()); + + $this->assertFalse($stream->isReadable()); + } + + public function testEmitsCloseOnlyOnceWhenClosingStreamMultipleTimes() + { + $promise = new Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->on('end', $this->expectCallableNever()); + $stream->on('close', $this->expectCallableOnce()); + + $stream->close(); + $stream->close(); + } + + public function testForwardsPauseToInputStream() + { + $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input->expects($this->once())->method('pause'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->pause(); + } + + /** + * @doesNotPerformAssertions + */ + public function testPauseAfterCloseHasNoEffect() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->close(); + $stream->pause(); + } + + + /** + * @doesNotPerformAssertions + */ + public function testPauseAfterErrorDueToInvalidInputHasNoEffect() + { + $promise = \React\Promise\reject(new \RuntimeException()); + $stream = Stream\unwrapReadable($promise); + + $stream->pause(); + } + + public function testForwardsResumeToInputStream() + { + $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input->expects($this->once())->method('resume'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->resume(); + } + + /** + * @doesNotPerformAssertions + */ + public function testResumeAfterCloseHasNoEffect() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->close(); + $stream->resume(); + } + + public function testPipingStreamWillForwardDataEvents() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $output = new ThroughStream(); + $outputPromise = Stream\buffer($output); + $stream->pipe($output); + + $input->emit('data', array('hello')); + $input->emit('data', array('world')); + $input->end(); + + $outputPromise->then($this->expectCallableOnceWith('helloworld')); + } + + public function testClosingStreamWillCloseInputStream() + { + $input = $this->getMockBuilder('React\Stream\ReadableStreamInterface')->getMock(); + $input->expects($this->once())->method('isReadable')->willReturn(true); + $input->expects($this->once())->method('close'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapReadable($promise); + + $stream->close(); + } + + public function testClosingStreamWillCloseStreamIfItIgnoredCancellationAndResolvesLater() + { + $input = new ThroughStream(); + + $loop = $this->loop; + $promise = new Promise\Promise(function ($resolve) use ($loop, $input) { + $loop->addTimer(0.001, function () use ($resolve, $input) { + $resolve($input); + }); + }); + + $stream = Stream\unwrapReadable($promise); + + $stream->on('close', $this->expectCallableOnce()); + + $stream->close(); + + Block\await($promise, $this->loop); + + $this->assertFalse($input->isReadable()); + } + + public function testClosingStreamWillCloseStreamFromCancellationHandler() + { + $input = new ThroughStream(); + + $promise = new \React\Promise\Promise(function () { }, function ($resolve) use ($input) { + $resolve($input); + }); + + $stream = Stream\unwrapReadable($promise); + + $stream->on('close', $this->expectCallableOnce()); + + $stream->close(); + + $this->assertFalse($input->isReadable()); + } + + public function testCloseShouldRemoveAllListenersAfterCloseEvent() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $this->assertCount(1, $stream->listeners('close')); + + $stream->close(); + + $this->assertCount(0, $stream->listeners('close')); + } + + public function testCloseShouldRemoveReferenceToPromiseToAvoidGarbageReferences() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapReadable($promise); + + $stream->close(); + + $ref = new \ReflectionProperty($stream, 'promise'); + $ref->setAccessible(true); + $value = $ref->getValue($stream); + + $this->assertNull($value); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapWritableTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapWritableTest.php new file mode 100644 index 0000000..07cc8e3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-stream/tests/UnwrapWritableTest.php @@ -0,0 +1,451 @@ +loop = Factory::create(); + } + + public function testReturnsWritableStreamForPromise() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $this->assertTrue($stream->isWritable()); + } + + public function testClosingStreamMakesItNotWritable() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $stream->on('error', $this->expectCallableNever()); + + $stream->close(); + + $this->assertFalse($stream->isWritable()); + } + + public function testClosingRejectingStreamMakesItNotWritable() + { + $promise = Timer\reject(0.001, $this->loop); + $stream = Stream\unwrapWritable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $stream->on('error', $this->expectCallableNever()); + + $stream->close(); + $this->loop->run(); + + $this->assertFalse($stream->isWritable()); + } + + public function testClosingStreamWillCancelInputPromiseAndMakeStreamNotWritable() + { + $promise = new \React\Promise\Promise(function () { }, $this->expectCallableOnce()); + $stream = Stream\unwrapWritable($promise); + + $stream->close(); + + $this->assertFalse($stream->isWritable()); + } + + public function testEmitsErrorWhenPromiseRejects() + { + $promise = Timer\reject(0.001, $this->loop); + + $stream = Stream\unwrapWritable($promise); + + $this->assertTrue($stream->isWritable()); + + $stream->on('error', $this->expectCallableOnce()); + $stream->on('close', $this->expectCallableOnce()); + + $this->loop->run(); + + $this->assertFalse($stream->isWritable()); + } + + public function testEmitsErrorWhenPromiseResolvesWithWrongValue() + { + $promise = Timer\resolve(0.001, $this->loop); + + $stream = Stream\unwrapWritable($promise); + + $this->assertTrue($stream->isWritable()); + + $stream->on('error', $this->expectCallableOnce()); + $stream->on('close', $this->expectCallableOnce()); + + $this->loop->run(); + + $this->assertFalse($stream->isWritable()); + } + + public function testReturnsClosedStreamIfInputStreamIsClosed() + { + $input = new ThroughStream(); + $input->close(); + + $promise = Promise\resolve($input); + + $stream = Stream\unwrapWritable($promise); + + $this->assertFalse($stream->isWritable()); + } + + public function testReturnsClosedStreamIfInputHasWrongValue() + { + $promise = Promise\resolve(42); + + $stream = Stream\unwrapWritable($promise); + + $this->assertFalse($stream->isWritable()); + } + + public function testReturnsStreamThatWillBeClosedWhenPromiseResolvesWithClosedInputStream() + { + $input = new ThroughStream(); + $input->close(); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + + $stream = Stream\unwrapWritable($promise); + + $this->assertTrue($stream->isWritable()); + + $stream->on('close', $this->expectCallableOnce()); + + $this->loop->run(); + + $this->assertFalse($stream->isWritable()); + } + + public function testForwardsDataImmediatelyIfPromiseIsAlreadyResolved() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->with('hello'); + $input->expects($this->never())->method('end'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->write('hello'); + } + + public function testForwardsOriginalDataOncePromiseResolves() + { + $data = new \stdClass(); + + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->with($data); + $input->expects($this->never())->method('end'); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + $stream = Stream\unwrapWritable($promise); + + $stream->write($data); + + $this->loop->run(); + } + + public function testForwardsDataInOriginalChunksOncePromiseResolves() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->exactly(2))->method('write')->withConsecutive(array('hello'), array('world')); + $input->expects($this->never())->method('end'); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + $stream = Stream\unwrapWritable($promise); + + $stream->write('hello'); + $stream->write('world'); + + $this->loop->run(); + } + + public function testForwardsDataAndEndImmediatelyIfPromiseIsAlreadyResolved() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->with('hello'); + $input->expects($this->once())->method('end')->with('!'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->write('hello'); + $stream->end('!'); + } + + public function testForwardsDataAndEndOncePromiseResolves() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->exactly(3))->method('write')->withConsecutive(array('hello'), array('world'), array('!')); + $input->expects($this->once())->method('end'); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + $stream = Stream\unwrapWritable($promise); + + $stream->write('hello'); + $stream->write('world'); + $stream->end('!'); + + $this->loop->run(); + } + + public function testForwardsNoDataWhenWritingAfterEndIfPromiseIsAlreadyResolved() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->never())->method('write'); + $input->expects($this->once())->method('end'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->end(); + $stream->end(); + $stream->write('nope'); + } + + public function testForwardsNoDataWhenWritingAfterEndOncePromiseResolves() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->never())->method('write'); + $input->expects($this->once())->method('end'); + + $promise = Timer\resolve(0.001, $this->loop)->then(function () use ($input) { + return $input; + }); + $stream = Stream\unwrapWritable($promise); + + $stream->end(); + $stream->write('nope'); + + $this->loop->run(); + } + + public function testWriteReturnsFalseWhenPromiseIsPending() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $ret = $stream->write('nope'); + + $this->assertFalse($ret); + } + + public function testWriteReturnsTrueWhenUnwrappedStreamReturnsTrueForWrite() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->willReturn(true); + + $promise = \React\Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $ret = $stream->write('hello'); + + $this->assertTrue($ret); + } + + public function testWriteReturnsFalseWhenUnwrappedStreamReturnsFalseForWrite() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->willReturn(false); + + $promise = \React\Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $ret = $stream->write('nope'); + + $this->assertFalse($ret); + } + + public function testWriteAfterCloseReturnsFalse() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $stream->close(); + $ret = $stream->write('nope'); + + $this->assertFalse($ret); + } + + public function testEmitsErrorAndClosesWhenInputEmitsError() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->on('error', $this->expectCallableOnceWith(new \RuntimeException())); + $stream->on('close', $this->expectCallableOnce()); + $input->emit('error', array(new \RuntimeException())); + + $this->assertFalse($stream->isWritable()); + } + + public function testEmitsDrainWhenPromiseResolvesWithStreamWhenForwardingData() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->with('hello')->willReturn(true); + + $deferred = new Deferred(); + $stream = Stream\unwrapWritable($deferred->promise()); + $stream->write('hello'); + + $stream->on('drain', $this->expectCallableOnce()); + $deferred->resolve($input); + } + + public function testDoesNotEmitDrainWhenStreamBufferExceededAfterForwardingData() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('write')->with('hello')->willReturn(false); + + $deferred = new Deferred(); + $stream = Stream\unwrapWritable($deferred->promise()); + $stream->write('hello'); + + $stream->on('drain', $this->expectCallableNever()); + $deferred->resolve($input); + } + + public function testEmitsDrainWhenInputEmitsDrain() + { + $input = new ThroughStream(); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->on('drain', $this->expectCallableOnce()); + $input->emit('drain', array()); + } + + public function testEmitsCloseOnlyOnceWhenClosingStreamMultipleTimes() + { + $promise = new Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $stream->on('error', $this->expectCallableNever()); + + $stream->close(); + $stream->close(); + } + + public function testClosingStreamWillCloseInputStream() + { + $input = $this->getMockBuilder('React\Stream\WritableStreamInterface')->getMock(); + $input->expects($this->once())->method('isWritable')->willReturn(true); + $input->expects($this->once())->method('close'); + + $promise = Promise\resolve($input); + $stream = Stream\unwrapWritable($promise); + + $stream->close(); + } + + public function testClosingStreamWillCloseStreamIfItIgnoredCancellationAndResolvesLater() + { + $input = new ThroughStream(); + $input->on('close', $this->expectCallableOnce()); + + $deferred = new Deferred(); + + $stream = Stream\unwrapReadable($deferred->promise()); + + $stream->on('close', $this->expectCallableOnce()); + + $stream->close(); + + $this->assertTrue($input->isReadable()); + + $deferred->resolve($input); + + $this->assertFalse($input->isReadable()); + } + + public function testClosingStreamWillCloseStreamFromCancellationHandler() + { + $input = new ThroughStream(); + + $promise = new \React\Promise\Promise(function () { }, function ($resolve) use ($input) { + $resolve($input); + }); + + $stream = Stream\unwrapWritable($promise); + + $stream->on('close', $this->expectCallableOnce()); + + $stream->close(); + + $this->assertFalse($input->isWritable()); + } + + public function testCloseShouldRemoveAllListenersAfterCloseEvent() + { + $promise = new \React\Promise\Promise(function () { }); + $stream = Stream\unwrapWritable($promise); + + $stream->on('close', $this->expectCallableOnce()); + $this->assertCount(1, $stream->listeners('close')); + + $stream->close(); + + $this->assertCount(0, $stream->listeners('close')); + } + + public function testCloseShouldRemoveReferenceToPromiseAndStreamToAvoidGarbageReferences() + { + $promise = \React\Promise\resolve(new ThroughStream()); + $stream = Stream\unwrapWritable($promise); + + $stream->close(); + + $ref = new \ReflectionProperty($stream, 'promise'); + $ref->setAccessible(true); + $value = $ref->getValue($stream); + + $this->assertNull($value); + + $ref = new \ReflectionProperty($stream, 'stream'); + $ref->setAccessible(true); + $value = $ref->getValue($stream); + + $this->assertNull($value); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/CHANGELOG.md new file mode 100644 index 0000000..56e4de2 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/CHANGELOG.md @@ -0,0 +1,95 @@ +# Changelog + +## 1.7.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#46 by @clue) + + ```php + // old (still supported) + $promise = timeout($promise, $time, $loop); + $promise = resolve($time, $loop); + $promise = reject($time, $loop); + + // new (using default loop) + $promise = timeout($promise, $time); + $promise = resolve($time); + $promise = reject($time); + ``` + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config, run tests on PHP 8 and add full core team to the license. + (#43 by @WyriHaximus, #44 and #45 by @SimonFrings) + +## 1.6.0 (2020-07-10) + +* Feature: Forward compatibility with react/promise v3. + (#37 by @WyriHaximus) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9 and PHP 7.4 and clean up test suite. + (#38 by @WyriHaximus, #39 by @reedy, #41 by @clue and #42 by @SimonFrings) + +## 1.5.1 (2019-03-27) + +* Fix: Typo in readme + (#35 by @aak74) + +* Improvement: Only include functions file when functions aren't defined + (#36 by @Niko9911) + +## 1.5.0 (2018-06-13) + +* Feature: Improve memory consumption by cleaning up garbage references to pending promise without canceller. + (#34 by @clue) + +## 1.4.0 (2018-06-11) + +* Feature: Improve memory consumption by cleaning up garbage references. + (#33 by @clue) + +## 1.3.0 (2018-04-24) + +* Feature: Improve memory consumption by cleaning up unneeded references. + (#32 by @clue) + +## 1.2.1 (2017-12-22) + +* README improvements + (#28 by @jsor) + +* Improve test suite by adding forward compatiblity with PHPUnit 6 and + fix test suite forward compatibility with upcoming EventLoop releases + (#30 and #31 by @clue) + +## 1.2.0 (2017-08-08) + +* Feature: Only start timers if input Promise is still pending and + return a settled output promise if the input is already settled. + (#25 by @clue) + +* Feature: Cap minimum timer interval at 1µs across all versions + (#23 by @clue) + +* Feature: Forward compatibility with EventLoop v1.0 and v0.5 + (#27 by @clue) + +* Improve test suite by adding PHPUnit to require-dev and + lock Travis distro so new defaults will not break the build + (#24 and #26 by @clue) + +## 1.1.1 (2016-12-27) + +* Improve test suite to use PSR-4 autoloader and proper namespaces. + (#21 by @clue) + +## 1.1.0 (2016-02-29) + +* Feature: Support promise cancellation for all timer primitives + (#18 by @clue) + +## 1.0.0 (2015-09-29) + +* First tagged release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/LICENSE new file mode 100644 index 0000000..56119ec --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/README.md new file mode 100644 index 0000000..364fe31 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/README.md @@ -0,0 +1,390 @@ +# PromiseTimer + +[![CI status](https://github.com/reactphp/promise-timer/workflows/CI/badge.svg)](https://github.com/reactphp/promise-timer/actions) + +A trivial implementation of timeouts for `Promise`s, built on top of [ReactPHP](https://reactphp.org/). + +**Table of contents** + +* [Usage](#usage) + * [timeout()](#timeout) + * [Timeout cancellation](#timeout-cancellation) + * [Cancellation handler](#cancellation-handler) + * [Input cancellation](#input-cancellation) + * [Output cancellation](#output-cancellation) + * [Collections](#collections) + * [resolve()](#resolve) + * [Resolve cancellation](#resolve-cancellation) + * [reject()](#reject) + * [Reject cancellation](#reject-cancellation) + * [TimeoutException](#timeoutexception) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +This lightweight library consists only of a few simple functions. +All functions reside under the `React\Promise\Timer` namespace. + +The below examples assume you use an import statement similar to this: + +```php +use React\Promise\Timer; + +Timer\timeout(…); +``` + +Alternatively, you can also refer to them with their fully-qualified name: + +```php +\React\Promise\Timer\timeout(…); +``` + +### timeout() + +The `timeout(PromiseInterface $promise, $time, LoopInterface $loop = null)` function +can be used to *cancel* operations that take *too long*. +You need to pass in an input `$promise` that represents a pending operation and timeout parameters. +It returns a new `Promise` with the following resolution behavior: + +* If the input `$promise` resolves before `$time` seconds, resolve the resulting promise with its fulfillment value. +* If the input `$promise` rejects before `$time` seconds, reject the resulting promise with its rejection value. +* If the input `$promise` does not settle before `$time` seconds, *cancel* the operation and reject the resulting promise with a [`TimeoutException`](#timeoutexception). + +Internally, the given `$time` value will be used to start a timer that will +*cancel* the pending operation once it triggers. +This implies that if you pass a really small (or negative) value, it will still +start a timer and will thus trigger at the earliest possible time in the future. + +If the input `$promise` is already settled, then the resulting promise will +resolve or reject immediately without starting a timer at all. + +This function takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use. You can use a `null` value here in order to +use the [default loop](https://github.com/reactphp/event-loop#loop). This value +SHOULD NOT be given unless you're sure you want to explicitly use a given event +loop instance. + +A common use case for handling only resolved values looks like this: + +```php +$promise = accessSomeRemoteResource(); +Timer\timeout($promise, 10.0)->then(function ($value) { + // the operation finished within 10.0 seconds +}); +``` + +A more complete example could look like this: + +```php +$promise = accessSomeRemoteResource(); +Timer\timeout($promise, 10.0)->then( + function ($value) { + // the operation finished within 10.0 seconds + }, + function ($error) { + if ($error instanceof Timer\TimeoutException) { + // the operation has failed due to a timeout + } else { + // the input operation has failed due to some other error + } + } +); +``` + +Or if you're using [react/promise v2.2.0](https://github.com/reactphp/promise) or up: + +```php +Timer\timeout($promise, 10.0) + ->then(function ($value) { + // the operation finished within 10.0 seconds + }) + ->otherwise(function (Timer\TimeoutException $error) { + // the operation has failed due to a timeout + }) + ->otherwise(function ($error) { + // the input operation has failed due to some other error + }) +; +``` + +#### Timeout cancellation + +As discussed above, the [`timeout()`](#timeout) function will *cancel* the +underlying operation if it takes *too long*. +This means that you can be sure the resulting promise will then be rejected +with a [`TimeoutException`](#timeoutexception). + +However, what happens to the underlying input `$promise` is a bit more tricky: +Once the timer fires, we will try to call +[`$promise->cancel()`](https://github.com/reactphp/promise#cancellablepromiseinterfacecancel) +on the input `$promise` which in turn invokes its [cancellation handler](#cancellation-handler). + +This means that it's actually up the input `$promise` to handle +[cancellation support](https://github.com/reactphp/promise#cancellablepromiseinterface). + +* A common use case involves cleaning up any resources like open network sockets or + file handles or terminating external processes or timers. + +* If the given input `$promise` does not support cancellation, then this is a NO-OP. + This means that while the resulting promise will still be rejected, the underlying + input `$promise` may still be pending and can hence continue consuming resources. + +See the following chapter for more details on the cancellation handler. + +#### Cancellation handler + +For example, an implementation for the above operation could look like this: + +```php +function accessSomeRemoteResource() +{ + return new Promise( + function ($resolve, $reject) use (&$socket) { + // this will be called once the promise is created + // a common use case involves opening any resources and eventually resolving + $socket = createSocket(); + $socket->on('data', function ($data) use ($resolve) { + $resolve($data); + }); + }, + function ($resolve, $reject) use (&$socket) { + // this will be called once calling `cancel()` on this promise + // a common use case involves cleaning any resources and then rejecting + $socket->close(); + $reject(new \RuntimeException('Operation cancelled')); + } + ); +} +``` + +In this example, calling `$promise->cancel()` will invoke the registered cancellation +handler which then closes the network socket and rejects the `Promise` instance. + +If no cancellation handler is passed to the `Promise` constructor, then invoking +its `cancel()` method it is effectively a NO-OP. +This means that it may still be pending and can hence continue consuming resources. + +For more details on the promise cancellation, please refer to the +[Promise documentation](https://github.com/reactphp/promise#cancellablepromiseinterface). + +#### Input cancellation + +Irrespective of the timeout handling, you can also explicitly `cancel()` the +input `$promise` at any time. +This means that the `timeout()` handling does not affect cancellation of the +input `$promise`, as demonstrated in the following example: + +```php +$promise = accessSomeRemoteResource(); +$timeout = Timer\timeout($promise, 10.0); + +$promise->cancel(); +``` + +The registered [cancellation handler](#cancellation-handler) is responsible for +handling the `cancel()` call: + +* A described above, a common use involves resource cleanup and will then *reject* + the `Promise`. + If the input `$promise` is being rejected, then the timeout will be aborted + and the resulting promise will also be rejected. +* If the input `$promise` is still pending, then the timout will continue + running until the timer expires. + The same happens if the input `$promise` does not register a + [cancellation handler](#cancellation-handler). + +#### Output cancellation + +Similarily, you can also explicitly `cancel()` the resulting promise like this: + +```php +$promise = accessSomeRemoteResource(); +$timeout = Timer\timeout($promise, 10.0); + +$timeout->cancel(); +``` + +Note how this looks very similar to the above [input cancellation](#input-cancellation) +example. Accordingly, it also behaves very similar. + +Calling `cancel()` on the resulting promise will merely try +to `cancel()` the input `$promise`. +This means that we do not take over responsibility of the outcome and it's +entirely up to the input `$promise` to handle cancellation support. + +The registered [cancellation handler](#cancellation-handler) is responsible for +handling the `cancel()` call: + +* As described above, a common use involves resource cleanup and will then *reject* + the `Promise`. + If the input `$promise` is being rejected, then the timeout will be aborted + and the resulting promise will also be rejected. +* If the input `$promise` is still pending, then the timout will continue + running until the timer expires. + The same happens if the input `$promise` does not register a + [cancellation handler](#cancellation-handler). + +To re-iterate, note that calling `cancel()` on the resulting promise will merely +try to cancel the input `$promise` only. +It is then up to the cancellation handler of the input promise to settle the promise. +If the input promise is still pending when the timeout occurs, then the normal +[timeout cancellation](#timeout-cancellation) handling will trigger, effectively rejecting +the output promise with a [`TimeoutException`](#timeoutexception). + +This is done for consistency with the [timeout cancellation](#timeout-cancellation) +handling and also because it is assumed this is often used like this: + +```php +$timeout = Timer\timeout(accessSomeRemoteResource(), 10.0); + +$timeout->cancel(); +``` + +As described above, this example works as expected and cleans up any resources +allocated for the input `$promise`. + +Note that if the given input `$promise` does not support cancellation, then this +is a NO-OP. +This means that while the resulting promise will still be rejected after the +timeout, the underlying input `$promise` may still be pending and can hence +continue consuming resources. + +#### Collections + +If you want to wait for multiple promises to resolve, you can use the normal promise primitives like this: + +```php +$promises = array( + accessSomeRemoteResource(), + accessSomeRemoteResource(), + accessSomeRemoteResource() +); + +$promise = \React\Promise\all($promises); + +Timer\timeout($promise, 10)->then(function ($values) { + // *all* promises resolved +}); +``` + +The applies to all promise collection primitives alike, i.e. `all()`, `race()`, `any()`, `some()` etc. + +For more details on the promise primitives, please refer to the +[Promise documentation](https://github.com/reactphp/promise#functions). + +### resolve() + +The `resolve($time, LoopInterface $loop = null)` function can be used to create a new Promise that +resolves in `$time` seconds with the `$time` as the fulfillment value. + +```php +Timer\resolve(1.5)->then(function ($time) { + echo 'Thanks for waiting ' . $time . ' seconds' . PHP_EOL; +}); +``` + +Internally, the given `$time` value will be used to start a timer that will +resolve the promise once it triggers. +This implies that if you pass a really small (or negative) value, it will still +start a timer and will thus trigger at the earliest possible time in the future. + +This function takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use. You can use a `null` value here in order to +use the [default loop](https://github.com/reactphp/event-loop#loop). This value +SHOULD NOT be given unless you're sure you want to explicitly use a given event +loop instance. + +#### Resolve cancellation + +You can explicitly `cancel()` the resulting timer promise at any time: + +```php +$timer = Timer\resolve(2.0); + +$timer->cancel(); +``` + +This will abort the timer and *reject* with a `RuntimeException`. + +### reject() + +The `reject($time, LoopInterface $loop = null)` function can be used to create a new Promise +which rejects in `$time` seconds with a `TimeoutException`. + +```php +Timer\reject(2.0)->then(null, function (TimeoutException $e) { + echo 'Rejected after ' . $e->getTimeout() . ' seconds ' . PHP_EOL; +}); +``` + +Internally, the given `$time` value will be used to start a timer that will +reject the promise once it triggers. +This implies that if you pass a really small (or negative) value, it will still +start a timer and will thus trigger at the earliest possible time in the future. + +This function takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use. You can use a `null` value here in order to +use the [default loop](https://github.com/reactphp/event-loop#loop). This value +SHOULD NOT be given unless you're sure you want to explicitly use a given event +loop instance. + +This function complements the [`resolve()`](#resolve) function +and can be used as a basic building block for higher-level promise consumers. + +#### Reject cancellation + +You can explicitly `cancel()` the resulting timer promise at any time: + +```php +$timer = Timer\reject(2.0); + +$timer->cancel(); +``` + +This will abort the timer and *reject* with a `RuntimeException`. + +### TimeoutException + +The `TimeoutException` extends PHP's built-in `RuntimeException`. + +The `getTimeout()` method can be used to get the timeout value in seconds. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/promise-timer:^1.7 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/composer.json new file mode 100644 index 0000000..7335298 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/composer.json @@ -0,0 +1,44 @@ +{ + "name": "react/promise-timer", + "description": "A trivial implementation of timeouts for Promises, built on top of ReactPHP.", + "keywords": ["Promise", "timeout", "timer", "event-loop", "ReactPHP", "async"], + "homepage": "https://github.com/reactphp/promise-timer", + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "autoload": { + "psr-4": { "React\\Promise\\Timer\\": "src/" }, + "files": [ "src/functions_include.php" ] + }, + "autoload-dev": { + "psr-4": { "React\\Tests\\Promise\\Timer\\": "tests/" } + }, + "require": { + "php": ">=5.3", + "react/event-loop": "^1.2", + "react/promise": "^3.0 || ^2.7.0 || ^1.2.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35" + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/TimeoutException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/TimeoutException.php new file mode 100644 index 0000000..18ea72f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/TimeoutException.php @@ -0,0 +1,22 @@ +timeout = $timeout; + } + + public function getTimeout() + { + return $this->timeout; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions.php new file mode 100644 index 0000000..c82a144 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions.php @@ -0,0 +1,90 @@ +cancel(); + $promise = null; + }; + } + + if ($loop === null) { + $loop = Loop::get(); + } + + return new Promise(function ($resolve, $reject) use ($loop, $time, $promise) { + $timer = null; + $promise = $promise->then(function ($v) use (&$timer, $loop, $resolve) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $resolve($v); + }, function ($v) use (&$timer, $loop, $reject) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = false; + $reject($v); + }); + + // promise already resolved => no need to start timer + if ($timer === false) { + return; + } + + // start timeout timer which will cancel the input promise + $timer = $loop->addTimer($time, function () use ($time, &$promise, $reject) { + $reject(new TimeoutException($time, 'Timed out after ' . $time . ' seconds')); + + // try to invoke cancellation handler of input promise and then clean + // reference in order to avoid garbage references in call stack. + if ($promise instanceof CancellablePromiseInterface || (!\interface_exists('React\Promise\CancellablePromiseInterface') && \method_exists($promise, 'cancel'))) { + $promise->cancel(); + } + $promise = null; + }); + }, $canceller); +} + +function resolve($time, LoopInterface $loop = null) +{ + if ($loop === null) { + $loop = Loop::get(); + } + + return new Promise(function ($resolve) use ($loop, $time, &$timer) { + // resolve the promise when the timer fires in $time seconds + $timer = $loop->addTimer($time, function () use ($time, $resolve) { + $resolve($time); + }); + }, function () use (&$timer, $loop) { + // cancelling this promise will cancel the timer, clean the reference + // in order to avoid garbage references in call stack and then reject. + $loop->cancelTimer($timer); + $timer = null; + + throw new \RuntimeException('Timer cancelled'); + }); +} + +function reject($time, LoopInterface $loop = null) +{ + return resolve($time, $loop)->then(function ($time) { + throw new TimeoutException($time, 'Timer expired after ' . $time . ' seconds'); + }); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions_include.php new file mode 100644 index 0000000..1d5673a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise-timer/src/functions_include.php @@ -0,0 +1,7 @@ +always(function() use ($promises) { + foreach ($promises as $promise) { + if ($promise instanceof \React\Promise\CancellablePromiseInterface) { + $promise->cancel(); + } + } + }); + } + ``` + * `all()` and `map()` functions now preserve the order of the array (#77). + * Fix circular references when resolving a promise with itself (#71). + +* 2.4.1 (2016-05-03) + + * Fix `some()` not cancelling pending promises when too much input promises + reject (16ff799). + +* 2.4.0 (2016-03-31) + + * Support foreign thenables in `resolve()`. + Any object that provides a `then()` method is now assimilated to a trusted + promise that follows the state of this thenable (#52). + * Fix `some()` and `any()` for input arrays containing not enough items + (#34). + +* 2.3.0 (2016-03-24) + + * Allow cancellation of promises returned by functions working on promise + collections (#36). + * Handle `\Throwable` in the same way as `\Exception` (#51 by @joshdifabio). + +* 2.2.2 (2016-02-26) + + * Fix cancellation handlers called multiple times (#47 by @clue). + +* 2.2.1 (2015-07-03) + + * Fix stack error when resolving a promise in its own fulfillment or + rejection handlers. + +* 2.2.0 (2014-12-30) + + * Introduce new `ExtendedPromiseInterface` implemented by all promises. + * Add new `done()` method (part of the `ExtendedPromiseInterface`). + * Add new `otherwise()` method (part of the `ExtendedPromiseInterface`). + * Add new `always()` method (part of the `ExtendedPromiseInterface`). + * Add new `progress()` method (part of the `ExtendedPromiseInterface`). + * Rename `Deferred::progress` to `Deferred::notify` to avoid confusion with + `ExtendedPromiseInterface::progress` (a `Deferred::progress` alias is + still available for backward compatibility) + * `resolve()` now always returns a `ExtendedPromiseInterface`. + +* 2.1.0 (2014-10-15) + + * Introduce new `CancellablePromiseInterface` implemented by all promises. + * Add new `cancel()` method (part of the `CancellablePromiseInterface`). + +* 2.0.0 (2013-12-10) + + New major release. The goal is to streamline the API and to make it more + compliant with other promise libraries and especially with the new upcoming + [ES6 promises specification](https://github.com/domenic/promises-unwrapping/). + + * Add standalone Promise class. + * Add new `race()` function. + * BC break: Bump minimum PHP version to PHP 5.4. + * BC break: Remove `ResolverInterface` and `PromiseInterface` from + `Deferred`. + * BC break: Change signature of `PromiseInterface`. + * BC break: Remove `When` and `Util` classes and move static methods to + functions. + * BC break: `FulfilledPromise` and `RejectedPromise` now throw an exception + when initialized with a promise instead of a value/reason. + * BC break: `Deferred::resolve()` and `Deferred::reject()` no longer return + a promise. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/LICENSE new file mode 100644 index 0000000..5919d20 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2012-2016 Jan Sorgalla + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/README.md new file mode 100644 index 0000000..6588c72 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/README.md @@ -0,0 +1,876 @@ +Promise +======= + +A lightweight implementation of +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +[![Build Status](https://travis-ci.org/reactphp/promise.svg?branch=master)](http://travis-ci.org/reactphp/promise) +[![Coverage Status](https://coveralls.io/repos/github/reactphp/promise/badge.svg?branch=master)](https://coveralls.io/github/reactphp/promise?branch=master) + +Table of Contents +----------------- + +1. [Introduction](#introduction) +2. [Concepts](#concepts) + * [Deferred](#deferred) + * [Promise](#promise-1) +3. [API](#api) + * [Deferred](#deferred-1) + * [Deferred::promise()](#deferredpromise) + * [Deferred::resolve()](#deferredresolve) + * [Deferred::reject()](#deferredreject) + * [Deferred::notify()](#deferrednotify) + * [PromiseInterface](#promiseinterface) + * [PromiseInterface::then()](#promiseinterfacethen) + * [ExtendedPromiseInterface](#extendedpromiseinterface) + * [ExtendedPromiseInterface::done()](#extendedpromiseinterfacedone) + * [ExtendedPromiseInterface::otherwise()](#extendedpromiseinterfaceotherwise) + * [ExtendedPromiseInterface::always()](#extendedpromiseinterfacealways) + * [ExtendedPromiseInterface::progress()](#extendedpromiseinterfaceprogress) + * [CancellablePromiseInterface](#cancellablepromiseinterface) + * [CancellablePromiseInterface::cancel()](#cancellablepromiseinterfacecancel) + * [Promise](#promise-2) + * [FulfilledPromise](#fulfilledpromise) + * [RejectedPromise](#rejectedpromise) + * [LazyPromise](#lazypromise) + * [Functions](#functions) + * [resolve()](#resolve) + * [reject()](#reject) + * [all()](#all) + * [race()](#race) + * [any()](#any) + * [some()](#some) + * [map()](#map) + * [reduce()](#reduce) + * [PromisorInterface](#promisorinterface) +4. [Examples](#examples) + * [How to use Deferred](#how-to-use-deferred) + * [How promise forwarding works](#how-promise-forwarding-works) + * [Resolution forwarding](#resolution-forwarding) + * [Rejection forwarding](#rejection-forwarding) + * [Mixed resolution and rejection forwarding](#mixed-resolution-and-rejection-forwarding) + * [Progress event forwarding](#progress-event-forwarding) + * [done() vs. then()](#done-vs-then) +5. [Install](#install) +6. [Credits](#credits) +7. [License](#license) + +Introduction +------------ + +Promise is a library implementing +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +It also provides several other useful promise-related concepts, such as joining +multiple promises and mapping and reducing collections of promises. + +If you've never heard about promises before, +[read this first](https://gist.github.com/3889970). + +Concepts +-------- + +### Deferred + +A **Deferred** represents a computation or unit of work that may not have +completed yet. Typically (but not always), that computation will be something +that executes asynchronously and completes at some point in the future. + +### Promise + +While a deferred represents the computation itself, a **Promise** represents +the result of that computation. Thus, each deferred has a promise that acts as +a placeholder for its actual result. + +API +--- + +### Deferred + +A deferred represents an operation whose resolution is pending. It has separate +promise and resolver parts. + +```php +$deferred = new React\Promise\Deferred(); + +$promise = $deferred->promise(); + +$deferred->resolve(mixed $value = null); +$deferred->reject(mixed $reason = null); +$deferred->notify(mixed $update = null); +``` + +The `promise` method returns the promise of the deferred. + +The `resolve` and `reject` methods control the state of the deferred. + +The deprecated `notify` method is for progress notification. + +The constructor of the `Deferred` accepts an optional `$canceller` argument. +See [Promise](#promise-2) for more information. + +#### Deferred::promise() + +```php +$promise = $deferred->promise(); +``` + +Returns the promise of the deferred, which you can hand out to others while +keeping the authority to modify its state to yourself. + +#### Deferred::resolve() + +```php +$deferred->resolve(mixed $value = null); +``` + +Resolves the promise returned by `promise()`. All consumers are notified by +having `$onFulfilled` (which they registered via `$promise->then()`) called with +`$value`. + +If `$value` itself is a promise, the promise will transition to the state of +this promise once it is resolved. + +#### Deferred::reject() + +```php +$deferred->reject(mixed $reason = null); +``` + +Rejects the promise returned by `promise()`, signalling that the deferred's +computation failed. +All consumers are notified by having `$onRejected` (which they registered via +`$promise->then()`) called with `$reason`. + +If `$reason` itself is a promise, the promise will be rejected with the outcome +of this promise regardless whether it fulfills or rejects. + +#### Deferred::notify() + +> Deprecated in v2.6.0: Progress support is deprecated and should not be used anymore. + +```php +$deferred->notify(mixed $update = null); +``` + +Triggers progress notifications, to indicate to consumers that the computation +is making progress toward its result. + +All consumers are notified by having `$onProgress` (which they registered via +`$promise->then()`) called with `$update`. + +### PromiseInterface + +The promise interface provides the common interface for all promise +implementations. + +A promise represents an eventual outcome, which is either fulfillment (success) +and an associated value, or rejection (failure) and an associated reason. + +Once in the fulfilled or rejected state, a promise becomes immutable. +Neither its state nor its result (or error) can be modified. + +#### Implementations + +* [Promise](#promise-2) +* [FulfilledPromise](#fulfilledpromise) (deprecated) +* [RejectedPromise](#rejectedpromise) (deprecated) +* [LazyPromise](#lazypromise) (deprecated) + +#### PromiseInterface::then() + +```php +$transformedPromise = $promise->then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null); +``` + +Transforms a promise's value by applying a function to the promise's fulfillment +or rejection value. Returns a new promise for the transformed result. + +The `then()` method registers new fulfilled, rejection and progress handlers +with a promise (all parameters are optional): + + * `$onFulfilled` will be invoked once the promise is fulfilled and passed + the result as the first argument. + * `$onRejected` will be invoked once the promise is rejected and passed the + reason as the first argument. + * `$onProgress` (deprecated) will be invoked whenever the producer of the promise + triggers progress notifications and passed a single argument (whatever it + wants) to indicate progress. + +It returns a new promise that will fulfill with the return value of either +`$onFulfilled` or `$onRejected`, whichever is called, or will reject with +the thrown exception if either throws. + +A promise makes the following guarantees about handlers registered in +the same call to `then()`: + + 1. Only one of `$onFulfilled` or `$onRejected` will be called, + never both. + 2. `$onFulfilled` and `$onRejected` will never be called more + than once. + 3. `$onProgress` (deprecated) may be called multiple times. + +#### See also + +* [resolve()](#resolve) - Creating a resolved promise +* [reject()](#reject) - Creating a rejected promise +* [ExtendedPromiseInterface::done()](#extendedpromiseinterfacedone) +* [done() vs. then()](#done-vs-then) + +### ExtendedPromiseInterface + +The ExtendedPromiseInterface extends the PromiseInterface with useful shortcut +and utility methods which are not part of the Promises/A specification. + +#### Implementations + +* [Promise](#promise-1) +* [FulfilledPromise](#fulfilledpromise) (deprecated) +* [RejectedPromise](#rejectedpromise) (deprecated) +* [LazyPromise](#lazypromise) (deprecated) + +#### ExtendedPromiseInterface::done() + +```php +$promise->done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null); +``` + +Consumes the promise's ultimate value if the promise fulfills, or handles the +ultimate error. + +It will cause a fatal error if either `$onFulfilled` or `$onRejected` throw or +return a rejected promise. + +Since the purpose of `done()` is consumption rather than transformation, +`done()` always returns `null`. + +#### See also + +* [PromiseInterface::then()](#promiseinterfacethen) +* [done() vs. then()](#done-vs-then) + +#### ExtendedPromiseInterface::otherwise() + +```php +$promise->otherwise(callable $onRejected); +``` + +Registers a rejection handler for promise. It is a shortcut for: + +```php +$promise->then(null, $onRejected); +``` + +Additionally, you can type hint the `$reason` argument of `$onRejected` to catch +only specific errors. + +```php +$promise + ->otherwise(function (\RuntimeException $reason) { + // Only catch \RuntimeException instances + // All other types of errors will propagate automatically + }) + ->otherwise(function ($reason) { + // Catch other errors + )}; +``` + +#### ExtendedPromiseInterface::always() + +```php +$newPromise = $promise->always(callable $onFulfilledOrRejected); +``` + +Allows you to execute "cleanup" type tasks in a promise chain. + +It arranges for `$onFulfilledOrRejected` to be called, with no arguments, +when the promise is either fulfilled or rejected. + +* If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will fulfill with the same value as `$promise`. +* If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. +* If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will reject with the same reason as `$promise`. +* If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. + +`always()` behaves similarly to the synchronous finally statement. When combined +with `otherwise()`, `always()` allows you to write code that is similar to the familiar +synchronous catch/finally pair. + +Consider the following synchronous code: + +```php +try { + return doSomething(); +} catch(\Exception $e) { + return handleError($e); +} finally { + cleanup(); +} +``` + +Similar asynchronous code (with `doSomething()` that returns a promise) can be +written: + +```php +return doSomething() + ->otherwise('handleError') + ->always('cleanup'); +``` + +#### ExtendedPromiseInterface::progress() + +> Deprecated in v2.6.0: Progress support is deprecated and should not be used anymore. + +```php +$promise->progress(callable $onProgress); +``` + +Registers a handler for progress updates from promise. It is a shortcut for: + +```php +$promise->then(null, null, $onProgress); +``` + +### CancellablePromiseInterface + +A cancellable promise provides a mechanism for consumers to notify the creator +of the promise that they are not longer interested in the result of an +operation. + +#### CancellablePromiseInterface::cancel() + +``` php +$promise->cancel(); +``` + +The `cancel()` method notifies the creator of the promise that there is no +further interest in the results of the operation. + +Once a promise is settled (either fulfilled or rejected), calling `cancel()` on +a promise has no effect. + +#### Implementations + +* [Promise](#promise-1) +* [FulfilledPromise](#fulfilledpromise) (deprecated) +* [RejectedPromise](#rejectedpromise) (deprecated) +* [LazyPromise](#lazypromise) (deprecated) + +### Promise + +Creates a promise whose state is controlled by the functions passed to +`$resolver`. + +```php +$resolver = function (callable $resolve, callable $reject, callable $notify) { + // Do some work, possibly asynchronously, and then + // resolve or reject. You can notify of progress events (deprecated) + // along the way if you want/need. + + $resolve($awesomeResult); + // or throw new Exception('Promise rejected'); + // or $resolve($anotherPromise); + // or $reject($nastyError); + // or $notify($progressNotification); +}; + +$canceller = function () { + // Cancel/abort any running operations like network connections, streams etc. + + // Reject promise by throwing an exception + throw new Exception('Promise cancelled'); +}; + +$promise = new React\Promise\Promise($resolver, $canceller); +``` + +The promise constructor receives a resolver function and an optional canceller +function which both will be called with 3 arguments: + + * `$resolve($value)` - Primary function that seals the fate of the + returned promise. Accepts either a non-promise value, or another promise. + When called with a non-promise value, fulfills promise with that value. + When called with another promise, e.g. `$resolve($otherPromise)`, promise's + fate will be equivalent to that of `$otherPromise`. + * `$reject($reason)` - Function that rejects the promise. It is recommended to + just throw an exception instead of using `$reject()`. + * `$notify($update)` - Deprecated function that issues progress events for the promise. + +If the resolver or canceller throw an exception, the promise will be rejected +with that thrown exception as the rejection reason. + +The resolver function will be called immediately, the canceller function only +once all consumers called the `cancel()` method of the promise. + +### FulfilledPromise + +> Deprecated in v2.8.0: External usage of `FulfilledPromise` is deprecated, use `resolve()` instead. + +Creates a already fulfilled promise. + +```php +$promise = React\Promise\FulfilledPromise($value); +``` + +Note, that `$value` **cannot** be a promise. It's recommended to use +[resolve()](#resolve) for creating resolved promises. + +### RejectedPromise + +> Deprecated in v2.8.0: External usage of `RejectedPromise` is deprecated, use `reject()` instead. + +Creates a already rejected promise. + +```php +$promise = React\Promise\RejectedPromise($reason); +``` + +Note, that `$reason` **cannot** be a promise. It's recommended to use +[reject()](#reject) for creating rejected promises. + +### LazyPromise + +> Deprecated in v2.8.0: LazyPromise is deprecated and should not be used anymore. + +Creates a promise which will be lazily initialized by `$factory` once a consumer +calls the `then()` method. + +```php +$factory = function () { + $deferred = new React\Promise\Deferred(); + + // Do some heavy stuff here and resolve the deferred once completed + + return $deferred->promise(); +}; + +$promise = new React\Promise\LazyPromise($factory); + +// $factory will only be executed once we call then() +$promise->then(function ($value) { +}); +``` + +### Functions + +Useful functions for creating, joining, mapping and reducing collections of +promises. + +All functions working on promise collections (like `all()`, `race()`, `some()` +etc.) support cancellation. This means, if you call `cancel()` on the returned +promise, all promises in the collection are cancelled. If the collection itself +is a promise which resolves to an array, this promise is also cancelled. + +#### resolve() + +```php +$promise = React\Promise\resolve(mixed $promiseOrValue); +``` + +Creates a promise for the supplied `$promiseOrValue`. + +If `$promiseOrValue` is a value, it will be the resolution value of the +returned promise. + +If `$promiseOrValue` is a thenable (any object that provides a `then()` method), +a trusted promise that follows the state of the thenable is returned. + +If `$promiseOrValue` is a promise, it will be returned as is. + +Note: The promise returned is always a promise implementing +[ExtendedPromiseInterface](#extendedpromiseinterface). If you pass in a custom +promise which only implements [PromiseInterface](#promiseinterface), this +promise will be assimilated to a extended promise following `$promiseOrValue`. + +#### reject() + +```php +$promise = React\Promise\reject(mixed $promiseOrValue); +``` + +Creates a rejected promise for the supplied `$promiseOrValue`. + +If `$promiseOrValue` is a value, it will be the rejection value of the +returned promise. + +If `$promiseOrValue` is a promise, its completion value will be the rejected +value of the returned promise. + +This can be useful in situations where you need to reject a promise without +throwing an exception. For example, it allows you to propagate a rejection with +the value of another promise. + +#### all() + +```php +$promise = React\Promise\all(array|React\Promise\PromiseInterface $promisesOrValues); +``` + +Returns a promise that will resolve only once all the items in +`$promisesOrValues` have resolved. The resolution value of the returned promise +will be an array containing the resolution values of each of the items in +`$promisesOrValues`. + +#### race() + +```php +$promise = React\Promise\race(array|React\Promise\PromiseInterface $promisesOrValues); +``` + +Initiates a competitive race that allows one winner. Returns a promise which is +resolved in the same way the first settled promise resolves. + +#### any() + +```php +$promise = React\Promise\any(array|React\Promise\PromiseInterface $promisesOrValues); +``` + +Returns a promise that will resolve when any one of the items in +`$promisesOrValues` resolves. The resolution value of the returned promise +will be the resolution value of the triggering item. + +The returned promise will only reject if *all* items in `$promisesOrValues` are +rejected. The rejection value will be an array of all rejection reasons. + +The returned promise will also reject with a `React\Promise\Exception\LengthException` +if `$promisesOrValues` contains 0 items. + +#### some() + +```php +$promise = React\Promise\some(array|React\Promise\PromiseInterface $promisesOrValues, integer $howMany); +``` + +Returns a promise that will resolve when `$howMany` of the supplied items in +`$promisesOrValues` resolve. The resolution value of the returned promise +will be an array of length `$howMany` containing the resolution values of the +triggering items. + +The returned promise will reject if it becomes impossible for `$howMany` items +to resolve (that is, when `(count($promisesOrValues) - $howMany) + 1` items +reject). The rejection value will be an array of +`(count($promisesOrValues) - $howMany) + 1` rejection reasons. + +The returned promise will also reject with a `React\Promise\Exception\LengthException` +if `$promisesOrValues` contains less items than `$howMany`. + +#### map() + +```php +$promise = React\Promise\map(array|React\Promise\PromiseInterface $promisesOrValues, callable $mapFunc); +``` + +Traditional map function, similar to `array_map()`, but allows input to contain +promises and/or values, and `$mapFunc` may return either a value or a promise. + +The map function receives each item as argument, where item is a fully resolved +value of a promise or value in `$promisesOrValues`. + +#### reduce() + +```php +$promise = React\Promise\reduce(array|React\Promise\PromiseInterface $promisesOrValues, callable $reduceFunc , $initialValue = null); +``` + +Traditional reduce function, similar to `array_reduce()`, but input may contain +promises and/or values, and `$reduceFunc` may return either a value or a +promise, *and* `$initialValue` may be a promise or a value for the starting +value. + +### PromisorInterface + +The `React\Promise\PromisorInterface` provides a common interface for objects +that provide a promise. `React\Promise\Deferred` implements it, but since it +is part of the public API anyone can implement it. + +Examples +-------- + +### How to use Deferred + +```php +function getAwesomeResultPromise() +{ + $deferred = new React\Promise\Deferred(); + + // Execute a Node.js-style function using the callback pattern + computeAwesomeResultAsynchronously(function ($error, $result) use ($deferred) { + if ($error) { + $deferred->reject($error); + } else { + $deferred->resolve($result); + } + }); + + // Return the promise + return $deferred->promise(); +} + +getAwesomeResultPromise() + ->then( + function ($value) { + // Deferred resolved, do something with $value + }, + function ($reason) { + // Deferred rejected, do something with $reason + }, + function ($update) { + // Progress notification triggered, do something with $update + } + ); +``` + +### How promise forwarding works + +A few simple examples to show how the mechanics of Promises/A forwarding works. +These examples are contrived, of course, and in real usage, promise chains will +typically be spread across several function calls, or even several levels of +your application architecture. + +#### Resolution forwarding + +Resolved promises forward resolution values to the next promise. +The first promise, `$deferred->promise()`, will resolve with the value passed +to `$deferred->resolve()` below. + +Each call to `then()` returns a new promise that will resolve with the return +value of the previous handler. This creates a promise "pipeline". + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + // $x will be the value passed to $deferred->resolve() below + // and returns a *new promise* for $x + 1 + return $x + 1; + }) + ->then(function ($x) { + // $x === 2 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 3 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 4 + // This handler receives the return value of the + // previous handler. + echo 'Resolve ' . $x; + }); + +$deferred->resolve(1); // Prints "Resolve 4" +``` + +#### Rejection forwarding + +Rejected promises behave similarly, and also work similarly to try/catch: +When you catch an exception, you must rethrow for it to propagate. + +Similarly, when you handle a rejected promise, to propagate the rejection, +"rethrow" it by either returning a rejected promise, or actually throwing +(since promise translates thrown exceptions into rejections) + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->otherwise(function (\Exception $x) { + // Propagate the rejection + throw $x; + }) + ->otherwise(function (\Exception $x) { + // Can also propagate by returning another rejection + return React\Promise\reject( + new \Exception($x->getMessage() + 1) + ); + }) + ->otherwise(function ($x) { + echo 'Reject ' . $x->getMessage(); // 3 + }); + +$deferred->resolve(1); // Prints "Reject 3" +``` + +#### Mixed resolution and rejection forwarding + +Just like try/catch, you can choose to propagate or not. Mixing resolutions and +rejections will still forward handler results in a predictable way. + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + return $x + 1; + }) + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->otherwise(function (\Exception $x) { + // Handle the rejection, and don't propagate. + // This is like catch without a rethrow + return $x->getMessage() + 1; + }) + ->then(function ($x) { + echo 'Mixed ' . $x; // 4 + }); + +$deferred->resolve(1); // Prints "Mixed 4" +``` + +#### Progress event forwarding + +> Deprecated in v2.6.0: Progress support is deprecated and should not be used anymore. + +In the same way as resolution and rejection handlers, your progress handler +**MUST** return a progress event to be propagated to the next link in the chain. +If you return nothing, `null` will be propagated. + +Also in the same way as resolutions and rejections, if you don't register a +progress handler, the update will be propagated through. + +If your progress handler throws an exception, the exception will be propagated +to the next link in the chain. The best thing to do is to ensure your progress +handlers do not throw exceptions. + +This gives you the opportunity to transform progress events at each step in the +chain so that they are meaningful to the next step. It also allows you to choose +not to transform them, and simply let them propagate untransformed, by not +registering a progress handler. + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->progress(function ($update) { + return $update + 1; + }) + ->progress(function ($update) { + echo 'Progress ' . $update; // 2 + }); + +$deferred->notify(1); // Prints "Progress 2" +``` + +### done() vs. then() + +The golden rule is: + + Either return your promise, or call done() on it. + +At a first glance, `then()` and `done()` seem very similar. However, there are +important distinctions. + +The intent of `then()` is to transform a promise's value and to pass or return +a new promise for the transformed value along to other parts of your code. + +The intent of `done()` is to consume a promise's value, transferring +responsibility for the value to your code. + +In addition to transforming a value, `then()` allows you to recover from, or +propagate intermediate errors. Any errors that are not handled will be caught +by the promise machinery and used to reject the promise returned by `then()`. + +Calling `done()` transfers all responsibility for errors to your code. If an +error (either a thrown exception or returned rejection) escapes the +`$onFulfilled` or `$onRejected` callbacks you provide to done, it will be +rethrown in an uncatchable way causing a fatal error. + +```php +function getJsonResult() +{ + return queryApi() + ->then( + // Transform API results to an object + function ($jsonResultString) { + return json_decode($jsonResultString); + }, + // Transform API errors to an exception + function ($jsonErrorString) { + $object = json_decode($jsonErrorString); + throw new ApiErrorException($object->errorMessage); + } + ); +} + +// Here we provide no rejection handler. If the promise returned has been +// rejected, the ApiErrorException will be thrown +getJsonResult() + ->done( + // Consume transformed object + function ($jsonResultObject) { + // Do something with $jsonResultObject + } + ); + +// Here we provide a rejection handler which will either throw while debugging +// or log the exception +getJsonResult() + ->done( + function ($jsonResultObject) { + // Do something with $jsonResultObject + }, + function (ApiErrorException $exception) { + if (isDebug()) { + throw $exception; + } else { + logException($exception); + } + } + ); +``` + +Note that if a rejection value is not an instance of `\Exception`, it will be +wrapped in an exception of the type `React\Promise\UnhandledRejectionException`. + +You can get the original rejection reason by calling `$exception->getReason()`. + +Install +------- + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/promise:^2.8 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.4 through current PHP 7+ and HHVM. +It's *highly recommended to use PHP 7+* for this project due to its vast +performance improvements. + +Credits +------- + +Promise is a port of [when.js](https://github.com/cujojs/when) +by [Brian Cavalier](https://github.com/briancavalier). + +Also, large parts of the documentation have been ported from the when.js +[Wiki](https://github.com/cujojs/when/wiki) and the +[API docs](https://github.com/cujojs/when/blob/master/docs/api.md). + +License +------- + +Released under the [MIT](LICENSE) license. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/composer.json new file mode 100644 index 0000000..b3e723a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/composer.json @@ -0,0 +1,29 @@ +{ + "name": "react/promise", + "description": "A lightweight implementation of CommonJS Promises/A for PHP", + "license": "MIT", + "authors": [ + {"name": "Jan Sorgalla", "email": "jsorgalla@gmail.com"} + ], + "require": { + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^7.0 || ^6.5 || ^5.7 || ^4.8.36" + }, + "autoload": { + "psr-4": { + "React\\Promise\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "autoload-dev": { + "psr-4": { + "React\\Promise\\": ["tests", "tests/fixtures"] + } + }, + "keywords": [ + "promise", + "promises" + ] +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/CancellablePromiseInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/CancellablePromiseInterface.php new file mode 100644 index 0000000..6b3a8c6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/CancellablePromiseInterface.php @@ -0,0 +1,17 @@ +started) { + return; + } + + $this->started = true; + $this->drain(); + } + + public function enqueue($cancellable) + { + if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) { + return; + } + + $length = \array_push($this->queue, $cancellable); + + if ($this->started && 1 === $length) { + $this->drain(); + } + } + + private function drain() + { + for ($i = key($this->queue); isset($this->queue[$i]); $i++) { + $cancellable = $this->queue[$i]; + + $exception = null; + + try { + $cancellable->cancel(); + } catch (\Throwable $exception) { + } catch (\Exception $exception) { + } + + unset($this->queue[$i]); + + if ($exception) { + throw $exception; + } + } + + $this->queue = []; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Deferred.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Deferred.php new file mode 100644 index 0000000..3ca034b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Deferred.php @@ -0,0 +1,65 @@ +canceller = $canceller; + } + + public function promise() + { + if (null === $this->promise) { + $this->promise = new Promise(function ($resolve, $reject, $notify) { + $this->resolveCallback = $resolve; + $this->rejectCallback = $reject; + $this->notifyCallback = $notify; + }, $this->canceller); + $this->canceller = null; + } + + return $this->promise; + } + + public function resolve($value = null) + { + $this->promise(); + + \call_user_func($this->resolveCallback, $value); + } + + public function reject($reason = null) + { + $this->promise(); + + \call_user_func($this->rejectCallback, $reason); + } + + /** + * @deprecated 2.6.0 Progress support is deprecated and should not be used anymore. + * @param mixed $update + */ + public function notify($update = null) + { + $this->promise(); + + \call_user_func($this->notifyCallback, $update); + } + + /** + * @deprecated 2.2.0 + * @see Deferred::notify() + */ + public function progress($update = null) + { + $this->notify($update); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Exception/LengthException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Exception/LengthException.php new file mode 100644 index 0000000..775c48d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Exception/LengthException.php @@ -0,0 +1,7 @@ +then(null, $onRejected); + * ``` + * + * Additionally, you can type hint the `$reason` argument of `$onRejected` to catch + * only specific errors. + * + * @param callable $onRejected + * @return ExtendedPromiseInterface + */ + public function otherwise(callable $onRejected); + + /** + * Allows you to execute "cleanup" type tasks in a promise chain. + * + * It arranges for `$onFulfilledOrRejected` to be called, with no arguments, + * when the promise is either fulfilled or rejected. + * + * * If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will fulfill with the same value as `$promise`. + * * If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * * If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will reject with the same reason as `$promise`. + * * If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * + * `always()` behaves similarly to the synchronous finally statement. When combined + * with `otherwise()`, `always()` allows you to write code that is similar to the familiar + * synchronous catch/finally pair. + * + * Consider the following synchronous code: + * + * ```php + * try { + * return doSomething(); + * } catch(\Exception $e) { + * return handleError($e); + * } finally { + * cleanup(); + * } + * ``` + * + * Similar asynchronous code (with `doSomething()` that returns a promise) can be + * written: + * + * ```php + * return doSomething() + * ->otherwise('handleError') + * ->always('cleanup'); + * ``` + * + * @param callable $onFulfilledOrRejected + * @return ExtendedPromiseInterface + */ + public function always(callable $onFulfilledOrRejected); + + /** + * Registers a handler for progress updates from promise. It is a shortcut for: + * + * ```php + * $promise->then(null, null, $onProgress); + * ``` + * + * @param callable $onProgress + * @return ExtendedPromiseInterface + * @deprecated 2.6.0 Progress support is deprecated and should not be used anymore. + */ + public function progress(callable $onProgress); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/FulfilledPromise.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/FulfilledPromise.php new file mode 100644 index 0000000..1472752 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/FulfilledPromise.php @@ -0,0 +1,71 @@ +value = $value; + } + + public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null === $onFulfilled) { + return $this; + } + + try { + return resolve($onFulfilled($this->value)); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } catch (\Exception $exception) { + return new RejectedPromise($exception); + } + } + + public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null === $onFulfilled) { + return; + } + + $result = $onFulfilled($this->value); + + if ($result instanceof ExtendedPromiseInterface) { + $result->done(); + } + } + + public function otherwise(callable $onRejected) + { + return $this; + } + + public function always(callable $onFulfilledOrRejected) + { + return $this->then(function ($value) use ($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use ($value) { + return $value; + }); + }); + } + + public function progress(callable $onProgress) + { + return $this; + } + + public function cancel() + { + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/LazyPromise.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/LazyPromise.php new file mode 100644 index 0000000..bbe9293 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/LazyPromise.php @@ -0,0 +1,66 @@ +factory = $factory; + } + + public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + return $this->promise()->then($onFulfilled, $onRejected, $onProgress); + } + + public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + return $this->promise()->done($onFulfilled, $onRejected, $onProgress); + } + + public function otherwise(callable $onRejected) + { + return $this->promise()->otherwise($onRejected); + } + + public function always(callable $onFulfilledOrRejected) + { + return $this->promise()->always($onFulfilledOrRejected); + } + + public function progress(callable $onProgress) + { + return $this->promise()->progress($onProgress); + } + + public function cancel() + { + return $this->promise()->cancel(); + } + + /** + * @internal + * @see Promise::settle() + */ + public function promise() + { + if (null === $this->promise) { + try { + $this->promise = resolve(\call_user_func($this->factory)); + } catch (\Throwable $exception) { + $this->promise = new RejectedPromise($exception); + } catch (\Exception $exception) { + $this->promise = new RejectedPromise($exception); + } + } + + return $this->promise; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Promise.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Promise.php new file mode 100644 index 0000000..33759e6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/Promise.php @@ -0,0 +1,256 @@ +canceller = $canceller; + + // Explicitly overwrite arguments with null values before invoking + // resolver function. This ensure that these arguments do not show up + // in the stack trace in PHP 7+ only. + $cb = $resolver; + $resolver = $canceller = null; + $this->call($cb); + } + + public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null !== $this->result) { + return $this->result->then($onFulfilled, $onRejected, $onProgress); + } + + if (null === $this->canceller) { + return new static($this->resolver($onFulfilled, $onRejected, $onProgress)); + } + + // This promise has a canceller, so we create a new child promise which + // has a canceller that invokes the parent canceller if all other + // followers are also cancelled. We keep a reference to this promise + // instance for the static canceller function and clear this to avoid + // keeping a cyclic reference between parent and follower. + $parent = $this; + ++$parent->requiredCancelRequests; + + return new static( + $this->resolver($onFulfilled, $onRejected, $onProgress), + static function () use (&$parent) { + if (++$parent->cancelRequests >= $parent->requiredCancelRequests) { + $parent->cancel(); + } + + $parent = null; + } + ); + } + + public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null !== $this->result) { + return $this->result->done($onFulfilled, $onRejected, $onProgress); + } + + $this->handlers[] = static function (ExtendedPromiseInterface $promise) use ($onFulfilled, $onRejected) { + $promise + ->done($onFulfilled, $onRejected); + }; + + if ($onProgress) { + $this->progressHandlers[] = $onProgress; + } + } + + public function otherwise(callable $onRejected) + { + return $this->then(null, static function ($reason) use ($onRejected) { + if (!_checkTypehint($onRejected, $reason)) { + return new RejectedPromise($reason); + } + + return $onRejected($reason); + }); + } + + public function always(callable $onFulfilledOrRejected) + { + return $this->then(static function ($value) use ($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use ($value) { + return $value; + }); + }, static function ($reason) use ($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use ($reason) { + return new RejectedPromise($reason); + }); + }); + } + + public function progress(callable $onProgress) + { + return $this->then(null, null, $onProgress); + } + + public function cancel() + { + if (null === $this->canceller || null !== $this->result) { + return; + } + + $canceller = $this->canceller; + $this->canceller = null; + + $this->call($canceller); + } + + private function resolver(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + return function ($resolve, $reject, $notify) use ($onFulfilled, $onRejected, $onProgress) { + if ($onProgress) { + $progressHandler = static function ($update) use ($notify, $onProgress) { + try { + $notify($onProgress($update)); + } catch (\Throwable $e) { + $notify($e); + } catch (\Exception $e) { + $notify($e); + } + }; + } else { + $progressHandler = $notify; + } + + $this->handlers[] = static function (ExtendedPromiseInterface $promise) use ($onFulfilled, $onRejected, $resolve, $reject, $progressHandler) { + $promise + ->then($onFulfilled, $onRejected) + ->done($resolve, $reject, $progressHandler); + }; + + $this->progressHandlers[] = $progressHandler; + }; + } + + private function reject($reason = null) + { + if (null !== $this->result) { + return; + } + + $this->settle(reject($reason)); + } + + private function settle(ExtendedPromiseInterface $promise) + { + $promise = $this->unwrap($promise); + + if ($promise === $this) { + $promise = new RejectedPromise( + new \LogicException('Cannot resolve a promise with itself.') + ); + } + + $handlers = $this->handlers; + + $this->progressHandlers = $this->handlers = []; + $this->result = $promise; + $this->canceller = null; + + foreach ($handlers as $handler) { + $handler($promise); + } + } + + private function unwrap($promise) + { + $promise = $this->extract($promise); + + while ($promise instanceof self && null !== $promise->result) { + $promise = $this->extract($promise->result); + } + + return $promise; + } + + private function extract($promise) + { + if ($promise instanceof LazyPromise) { + $promise = $promise->promise(); + } + + return $promise; + } + + private function call(callable $cb) + { + // Explicitly overwrite argument with null value. This ensure that this + // argument does not show up in the stack trace in PHP 7+ only. + $callback = $cb; + $cb = null; + + // Use reflection to inspect number of arguments expected by this callback. + // We did some careful benchmarking here: Using reflection to avoid unneeded + // function arguments is actually faster than blindly passing them. + // Also, this helps avoiding unnecessary function arguments in the call stack + // if the callback creates an Exception (creating garbage cycles). + if (\is_array($callback)) { + $ref = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $ref = new \ReflectionMethod($callback, '__invoke'); + } else { + $ref = new \ReflectionFunction($callback); + } + $args = $ref->getNumberOfParameters(); + + try { + if ($args === 0) { + $callback(); + } else { + // Keep references to this promise instance for the static resolve/reject functions. + // By using static callbacks that are not bound to this instance + // and passing the target promise instance by reference, we can + // still execute its resolving logic and still clear this + // reference when settling the promise. This helps avoiding + // garbage cycles if any callback creates an Exception. + // These assumptions are covered by the test suite, so if you ever feel like + // refactoring this, go ahead, any alternative suggestions are welcome! + $target =& $this; + $progressHandlers =& $this->progressHandlers; + + $callback( + static function ($value = null) use (&$target) { + if ($target !== null) { + $target->settle(resolve($value)); + $target = null; + } + }, + static function ($reason = null) use (&$target) { + if ($target !== null) { + $target->reject($reason); + $target = null; + } + }, + static function ($update = null) use (&$progressHandlers) { + foreach ($progressHandlers as $handler) { + $handler($update); + } + } + ); + } + } catch (\Throwable $e) { + $target = null; + $this->reject($e); + } catch (\Exception $e) { + $target = null; + $this->reject($e); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/PromiseInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/PromiseInterface.php new file mode 100644 index 0000000..edcb007 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/PromiseInterface.php @@ -0,0 +1,41 @@ +reason = $reason; + } + + public function then(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null === $onRejected) { + return $this; + } + + try { + return resolve($onRejected($this->reason)); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } catch (\Exception $exception) { + return new RejectedPromise($exception); + } + } + + public function done(callable $onFulfilled = null, callable $onRejected = null, callable $onProgress = null) + { + if (null === $onRejected) { + throw UnhandledRejectionException::resolve($this->reason); + } + + $result = $onRejected($this->reason); + + if ($result instanceof self) { + throw UnhandledRejectionException::resolve($result->reason); + } + + if ($result instanceof ExtendedPromiseInterface) { + $result->done(); + } + } + + public function otherwise(callable $onRejected) + { + if (!_checkTypehint($onRejected, $this->reason)) { + return $this; + } + + return $this->then(null, $onRejected); + } + + public function always(callable $onFulfilledOrRejected) + { + return $this->then(null, function ($reason) use ($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use ($reason) { + return new RejectedPromise($reason); + }); + }); + } + + public function progress(callable $onProgress) + { + return $this; + } + + public function cancel() + { + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/UnhandledRejectionException.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/UnhandledRejectionException.php new file mode 100644 index 0000000..e7fe2f7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/UnhandledRejectionException.php @@ -0,0 +1,31 @@ +reason = $reason; + + $message = \sprintf('Unhandled Rejection: %s', \json_encode($reason)); + + parent::__construct($message, 0); + } + + public function getReason() + { + return $this->reason; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions.php new file mode 100644 index 0000000..bdbdf52 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions.php @@ -0,0 +1,351 @@ +then($resolve, $reject, $notify); + }, $canceller); + } + + return new FulfilledPromise($promiseOrValue); +} + +/** + * Creates a rejected promise for the supplied `$promiseOrValue`. + * + * If `$promiseOrValue` is a value, it will be the rejection value of the + * returned promise. + * + * If `$promiseOrValue` is a promise, its completion value will be the rejected + * value of the returned promise. + * + * This can be useful in situations where you need to reject a promise without + * throwing an exception. For example, it allows you to propagate a rejection with + * the value of another promise. + * + * @param mixed $promiseOrValue + * @return PromiseInterface + */ +function reject($promiseOrValue = null) +{ + if ($promiseOrValue instanceof PromiseInterface) { + return resolve($promiseOrValue)->then(function ($value) { + return new RejectedPromise($value); + }); + } + + return new RejectedPromise($promiseOrValue); +} + +/** + * Returns a promise that will resolve only once all the items in + * `$promisesOrValues` have resolved. The resolution value of the returned promise + * will be an array containing the resolution values of each of the items in + * `$promisesOrValues`. + * + * @param array $promisesOrValues + * @return PromiseInterface + */ +function all($promisesOrValues) +{ + return map($promisesOrValues, function ($val) { + return $val; + }); +} + +/** + * Initiates a competitive race that allows one winner. Returns a promise which is + * resolved in the same way the first settled promise resolves. + * + * The returned promise will become **infinitely pending** if `$promisesOrValues` + * contains 0 items. + * + * @param array $promisesOrValues + * @return PromiseInterface + */ +function race($promisesOrValues) +{ + $cancellationQueue = new CancellationQueue(); + $cancellationQueue->enqueue($promisesOrValues); + + return new Promise(function ($resolve, $reject, $notify) use ($promisesOrValues, $cancellationQueue) { + resolve($promisesOrValues) + ->done(function ($array) use ($cancellationQueue, $resolve, $reject, $notify) { + if (!is_array($array) || !$array) { + $resolve(); + return; + } + + foreach ($array as $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + + resolve($promiseOrValue) + ->done($resolve, $reject, $notify); + } + }, $reject, $notify); + }, $cancellationQueue); +} + +/** + * Returns a promise that will resolve when any one of the items in + * `$promisesOrValues` resolves. The resolution value of the returned promise + * will be the resolution value of the triggering item. + * + * The returned promise will only reject if *all* items in `$promisesOrValues` are + * rejected. The rejection value will be an array of all rejection reasons. + * + * The returned promise will also reject with a `React\Promise\Exception\LengthException` + * if `$promisesOrValues` contains 0 items. + * + * @param array $promisesOrValues + * @return PromiseInterface + */ +function any($promisesOrValues) +{ + return some($promisesOrValues, 1) + ->then(function ($val) { + return \array_shift($val); + }); +} + +/** + * Returns a promise that will resolve when `$howMany` of the supplied items in + * `$promisesOrValues` resolve. The resolution value of the returned promise + * will be an array of length `$howMany` containing the resolution values of the + * triggering items. + * + * The returned promise will reject if it becomes impossible for `$howMany` items + * to resolve (that is, when `(count($promisesOrValues) - $howMany) + 1` items + * reject). The rejection value will be an array of + * `(count($promisesOrValues) - $howMany) + 1` rejection reasons. + * + * The returned promise will also reject with a `React\Promise\Exception\LengthException` + * if `$promisesOrValues` contains less items than `$howMany`. + * + * @param array $promisesOrValues + * @param int $howMany + * @return PromiseInterface + */ +function some($promisesOrValues, $howMany) +{ + $cancellationQueue = new CancellationQueue(); + $cancellationQueue->enqueue($promisesOrValues); + + return new Promise(function ($resolve, $reject, $notify) use ($promisesOrValues, $howMany, $cancellationQueue) { + resolve($promisesOrValues) + ->done(function ($array) use ($howMany, $cancellationQueue, $resolve, $reject, $notify) { + if (!\is_array($array) || $howMany < 1) { + $resolve([]); + return; + } + + $len = \count($array); + + if ($len < $howMany) { + throw new Exception\LengthException( + \sprintf( + 'Input array must contain at least %d item%s but contains only %s item%s.', + $howMany, + 1 === $howMany ? '' : 's', + $len, + 1 === $len ? '' : 's' + ) + ); + } + + $toResolve = $howMany; + $toReject = ($len - $toResolve) + 1; + $values = []; + $reasons = []; + + foreach ($array as $i => $promiseOrValue) { + $fulfiller = function ($val) use ($i, &$values, &$toResolve, $toReject, $resolve) { + if ($toResolve < 1 || $toReject < 1) { + return; + } + + $values[$i] = $val; + + if (0 === --$toResolve) { + $resolve($values); + } + }; + + $rejecter = function ($reason) use ($i, &$reasons, &$toReject, $toResolve, $reject) { + if ($toResolve < 1 || $toReject < 1) { + return; + } + + $reasons[$i] = $reason; + + if (0 === --$toReject) { + $reject($reasons); + } + }; + + $cancellationQueue->enqueue($promiseOrValue); + + resolve($promiseOrValue) + ->done($fulfiller, $rejecter, $notify); + } + }, $reject, $notify); + }, $cancellationQueue); +} + +/** + * Traditional map function, similar to `array_map()`, but allows input to contain + * promises and/or values, and `$mapFunc` may return either a value or a promise. + * + * The map function receives each item as argument, where item is a fully resolved + * value of a promise or value in `$promisesOrValues`. + * + * @param array $promisesOrValues + * @param callable $mapFunc + * @return PromiseInterface + */ +function map($promisesOrValues, callable $mapFunc) +{ + $cancellationQueue = new CancellationQueue(); + $cancellationQueue->enqueue($promisesOrValues); + + return new Promise(function ($resolve, $reject, $notify) use ($promisesOrValues, $mapFunc, $cancellationQueue) { + resolve($promisesOrValues) + ->done(function ($array) use ($mapFunc, $cancellationQueue, $resolve, $reject, $notify) { + if (!\is_array($array) || !$array) { + $resolve([]); + return; + } + + $toResolve = \count($array); + $values = []; + + foreach ($array as $i => $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + $values[$i] = null; + + resolve($promiseOrValue) + ->then($mapFunc) + ->done( + function ($mapped) use ($i, &$values, &$toResolve, $resolve) { + $values[$i] = $mapped; + + if (0 === --$toResolve) { + $resolve($values); + } + }, + $reject, + $notify + ); + } + }, $reject, $notify); + }, $cancellationQueue); +} + +/** + * Traditional reduce function, similar to `array_reduce()`, but input may contain + * promises and/or values, and `$reduceFunc` may return either a value or a + * promise, *and* `$initialValue` may be a promise or a value for the starting + * value. + * + * @param array $promisesOrValues + * @param callable $reduceFunc + * @param mixed $initialValue + * @return PromiseInterface + */ +function reduce($promisesOrValues, callable $reduceFunc, $initialValue = null) +{ + $cancellationQueue = new CancellationQueue(); + $cancellationQueue->enqueue($promisesOrValues); + + return new Promise(function ($resolve, $reject, $notify) use ($promisesOrValues, $reduceFunc, $initialValue, $cancellationQueue) { + resolve($promisesOrValues) + ->done(function ($array) use ($reduceFunc, $initialValue, $cancellationQueue, $resolve, $reject, $notify) { + if (!\is_array($array)) { + $array = []; + } + + $total = \count($array); + $i = 0; + + // Wrap the supplied $reduceFunc with one that handles promises and then + // delegates to the supplied. + $wrappedReduceFunc = function ($current, $val) use ($reduceFunc, $cancellationQueue, $total, &$i) { + $cancellationQueue->enqueue($val); + + return $current + ->then(function ($c) use ($reduceFunc, $total, &$i, $val) { + return resolve($val) + ->then(function ($value) use ($reduceFunc, $total, &$i, $c) { + return $reduceFunc($c, $value, $i++, $total); + }); + }); + }; + + $cancellationQueue->enqueue($initialValue); + + \array_reduce($array, $wrappedReduceFunc, resolve($initialValue)) + ->done($resolve, $reject, $notify); + }, $reject, $notify); + }, $cancellationQueue); +} + +/** + * @internal + */ +function _checkTypehint(callable $callback, $object) +{ + if (!\is_object($object)) { + return true; + } + + if (\is_array($callback)) { + $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $callbackReflection = new \ReflectionMethod($callback, '__invoke'); + } else { + $callbackReflection = new \ReflectionFunction($callback); + } + + $parameters = $callbackReflection->getParameters(); + + if (!isset($parameters[0])) { + return true; + } + + $expectedException = $parameters[0]; + + if (!$expectedException->getClass()) { + return true; + } + + return $expectedException->getClass()->isInstance($object); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions_include.php new file mode 100644 index 0000000..bd0c54f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/promise/src/functions_include.php @@ -0,0 +1,5 @@ +connect('tls://example.com:443'); + $promise->then(function (ConnectionInterface $conn) use ($loop) { + // … + }, function (Exception $e) { + echo $e->getMessage(); + }); + ``` + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.8.12 release. + +## 0.8.12 (2018-06-11) + +* Feature: Improve memory consumption for failed and cancelled connection attempts. + (#161 by @clue) + +* Improve test suite to fix Travis config to test against legacy PHP 5.3 again. + (#162 by @clue) + +## 0.8.11 (2018-04-24) + +* Feature: Improve memory consumption for cancelled connection attempts and + simplify skipping DNS lookup when connecting to IP addresses. + (#159 and #160 by @clue) + +## 0.8.10 (2018-02-28) + +* Feature: Update DNS dependency to support loading system default DNS + nameserver config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac/Docker/WSL and WMIC on Windows) + (#152 by @clue) + + This means that connecting to hosts that are managed by a local DNS server, + such as a corporate DNS server or when using Docker containers, will now + work as expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('intranet.example:80')->then(function ($connection) { + // … + }); + ``` + +## 0.8.9 (2018-01-18) + +* Feature: Support explicitly choosing TLS version to negotiate with remote side + by respecting `crypto_method` context parameter for all classes. + (#149 by @clue) + + By default, all connector and server classes support TLSv1.0+ and exclude + support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly + choose the TLS version you want to negotiate with the remote side: + + ```php + // new: now supports 'crypto_method` context parameter for all classes + $connector = new Connector($loop, array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) + )); + ``` + +* Minor internal clean up to unify class imports + (#148 by @clue) + +## 0.8.8 (2018-01-06) + +* Improve test suite by adding test group to skip integration tests relying on + internet connection and fix minor documentation typo. + (#146 by @clue and #145 by @cn007b) + +## 0.8.7 (2017-12-24) + +* Fix: Fix closing socket resource before removing from loop + (#141 by @clue) + + This fixes the root cause of an uncaught `Exception` that only manifested + itself after the recent Stream v0.7.4 component update and only if you're + using `ext-event` (`ExtEventLoop`). + +* Improve test suite by testing against PHP 7.2 + (#140 by @carusogabriel) + +## 0.8.6 (2017-11-18) + +* Feature: Add Unix domain socket (UDS) support to `Server` with `unix://` URI scheme + and add advanced `UnixServer` class. + (#120 by @andig) + + ```php + // new: Server now supports "unix://" scheme + $server = new Server('unix:///tmp/server.sock', $loop); + + // new: advanced usage + $server = new UnixServer('/tmp/server.sock', $loop); + ``` + +* Restructure examples to ease getting started + (#136 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#133 by @gabriel-caruso and #134 by @clue) + +## 0.8.5 (2017-10-23) + +* Fix: Work around PHP bug with Unix domain socket (UDS) paths for Mac OS X + (#123 by @andig) + +* Fix: Fix `SecureServer` to return `null` URI if server socket is already closed + (#129 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit v5 and + forward compatibility with upcoming EventLoop releases in tests and + test Mac OS X on Travis + (#122 by @andig and #125, #127 and #130 by @clue) + +* Readme improvements + (#118 by @jsor) + +## 0.8.4 (2017-09-16) + +* Feature: Add `FixedUriConnector` decorator to use fixed, preconfigured URI instead + (#117 by @clue) + + This can be useful for consumers that do not support certain URIs, such as + when you want to explicitly connect to a Unix domain socket (UDS) path + instead of connecting to a default address assumed by an higher-level API: + + ```php + $connector = new FixedUriConnector( + 'unix:///var/run/docker.sock', + new UnixConnector($loop) + ); + + // destination will be ignored, actually connects to Unix domain socket + $promise = $connector->connect('localhost:80'); + ``` + +## 0.8.3 (2017-09-08) + +* Feature: Reduce memory consumption for failed connections + (#113 by @valga) + +* Fix: Work around write chunk size for TLS streams for PHP < 7.1.14 + (#114 by @clue) + +## 0.8.2 (2017-08-25) + +* Feature: Update DNS dependency to support hosts file on all platforms + (#112 by @clue) + + This means that connecting to hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('localhost:8080')->then(function ($connection) { + // … + }); + ``` + +## 0.8.1 (2017-08-15) + +* Feature: Forward compatibility with upcoming EventLoop v1.0 and v0.5 and + target evenement 3.0 a long side 2.0 and 1.0 + (#104 by @clue and #111 by @WyriHaximus) + +* Improve test suite by locking Travis distro so new defaults will not break the build and + fix HHVM build for now again and ignore future HHVM build errors + (#109 and #110 by @clue) + +* Minor documentation fixes + (#103 by @christiaan and #108 by @hansott) + +## 0.8.0 (2017-05-09) + +* Feature: New `Server` class now acts as a facade for existing server classes + and renamed old `Server` to `TcpServer` for advanced usage. + (#96 and #97 by @clue) + + The `Server` class is now the main class in this package that implements the + `ServerInterface` and allows you to accept incoming streaming connections, + such as plaintext TCP/IP or secure TLS connection streams. + + > This is not a BC break and consumer code does not have to be updated. + +* Feature / BC break: All addresses are now URIs that include the URI scheme + (#98 by @clue) + + ```diff + - $parts = parse_url('tcp://' . $conn->getRemoteAddress()); + + $parts = parse_url($conn->getRemoteAddress()); + ``` + +* Fix: Fix `unix://` addresses for Unix domain socket (UDS) paths + (#100 by @clue) + +* Feature: Forward compatibility with Stream v1.0 and v0.7 + (#99 by @clue) + +## 0.7.2 (2017-04-24) + +* Fix: Work around latest PHP 7.0.18 and 7.1.4 no longer accepting full URIs + (#94 by @clue) + +## 0.7.1 (2017-04-10) + +* Fix: Ignore HHVM errors when closing connection that is already closing + (#91 by @clue) + +## 0.7.0 (2017-04-10) + +* Feature: Merge SocketClient component into this component + (#87 by @clue) + + This means that this package now provides async, streaming plaintext TCP/IP + and secure TLS socket server and client connections for ReactPHP. + + ``` + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + + Accordingly, the `ConnectionInterface` is now used to represent both incoming + server side connections as well as outgoing client side connections. + + If you've previously used the SocketClient component to establish outgoing + client connections, upgrading should take no longer than a few minutes. + All classes have been merged as-is from the latest `v0.7.0` release with no + other changes, so you can simply update your code to use the updated namespace + like this: + + ```php + // old from SocketClient component and namespace + $connector = new React\SocketClient\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + + // new + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + +## 0.6.0 (2017-04-04) + +* Feature: Add `LimitingServer` to limit and keep track of open connections + (#86 by @clue) + + ```php + $server = new Server(0, $loop); + $server = new LimitingServer($server, 100); + + $server->on('connection', function (ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … + }); + ``` + +* Feature / BC break: Add `pause()` and `resume()` methods to limit active + connections + (#84 by @clue) + + ```php + $server = new Server(0, $loop); + $server->pause(); + + $loop->addTimer(1.0, function() use ($server) { + $server->resume(); + }); + ``` + +## 0.5.1 (2017-03-09) + +* Feature: Forward compatibility with Stream v0.5 and upcoming v0.6 + (#79 by @clue) + +## 0.5.0 (2017-02-14) + +* Feature / BC break: Replace `listen()` call with URIs passed to constructor + and reject listening on hostnames with `InvalidArgumentException` + and replace `ConnectionException` with `RuntimeException` for consistency + (#61, #66 and #72 by @clue) + + ```php + // old + $server = new Server($loop); + $server->listen(8080); + + // new + $server = new Server(8080, $loop); + ``` + + Similarly, you can now pass a full listening URI to the constructor to change + the listening host: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, '127.0.0.1'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + Trying to start listening on (DNS) host names will now throw an + `InvalidArgumentException`, use IP addresses instead: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, 'localhost'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + If trying to listen fails (such as if port is already in use or port below + 1024 may require root access etc.), it will now throw a `RuntimeException`, + the `ConnectionException` class has been removed: + + ```php + // old: throws React\Socket\ConnectionException + $server = new Server($loop); + $server->listen(80); + + // new: throws RuntimeException + $server = new Server(80, $loop); + ``` + +* Feature / BC break: Rename `shutdown()` to `close()` for consistency throughout React + (#62 by @clue) + + ```php + // old + $server->shutdown(); + + // new + $server->close(); + ``` + +* Feature / BC break: Replace `getPort()` with `getAddress()` + (#67 by @clue) + + ```php + // old + echo $server->getPort(); // 8080 + + // new + echo $server->getAddress(); // 127.0.0.1:8080 + ``` + +* Feature / BC break: `getRemoteAddress()` returns full address instead of only IP + (#65 by @clue) + + ```php + // old + echo $connection->getRemoteAddress(); // 192.168.0.1 + + // new + echo $connection->getRemoteAddress(); // 192.168.0.1:51743 + ``` + +* Feature / BC break: Add `getLocalAddress()` method + (#68 by @clue) + + ```php + echo $connection->getLocalAddress(); // 127.0.0.1:8080 + ``` + +* BC break: The `Server` and `SecureServer` class are now marked `final` + and you can no longer `extend` them + (which was never documented or recommended anyway). + Public properties and event handlers are now internal only. + Please use composition instead of extension. + (#71, #70 and #69 by @clue) + +## 0.4.6 (2017-01-26) + +* Feature: Support socket context options passed to `Server` + (#64 by @clue) + +* Fix: Properly return `null` for unknown addresses + (#63 by @clue) + +* Improve documentation for `ServerInterface` and lock test suite requirements + (#60 by @clue, #57 by @shaunbramley) + +## 0.4.5 (2017-01-08) + +* Feature: Add `SecureServer` for secure TLS connections + (#55 by @clue) + +* Add functional integration tests + (#54 by @clue) + +## 0.4.4 (2016-12-19) + +* Feature / Fix: `ConnectionInterface` should extend `DuplexStreamInterface` + documentation + (#50 by @clue) + +* Feature / Fix: Improve test suite and switch to normal stream handler + (#51 by @clue) + +* Feature: Add examples + (#49 by @clue) + +## 0.4.3 (2016-03-01) + +* Bug fix: Suppress errors on stream_socket_accept to prevent PHP from crashing +* Support for PHP7 and HHVM +* Support PHP 5.3 again + +## 0.4.2 (2014-05-25) + +* Verify stream is a valid resource in Connection + +## 0.4.1 (2014-04-13) + +* Bug fix: Check read buffer for data before shutdown signal and end emit (@ArtyDev) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: Reset socket to non-blocking after shutting down (PHP bug) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.3 (2013-07-08) + +* Version bump + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.1 (2013-04-21) + +* Feature: Support binding to IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.0 (2012-09-10) + +* Bump React dependencies to v0.2 + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/README.md new file mode 100644 index 0000000..934e53c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/README.md @@ -0,0 +1,1553 @@ +# Socket + +[![CI status](https://github.com/reactphp/socket/workflows/CI/badge.svg)](https://github.com/reactphp/socket/actions) + +Async, streaming plaintext TCP/IP and secure TLS socket server and client +connections for [ReactPHP](https://reactphp.org/). + +The socket library provides re-usable interfaces for a socket-layer +server and client based on the [`EventLoop`](https://github.com/reactphp/event-loop) +and [`Stream`](https://github.com/reactphp/stream) components. +Its server component allows you to build networking servers that accept incoming +connections from networking clients (such as an HTTP server). +Its client component allows you to build networking clients that establish +outgoing connections to networking servers (such as an HTTP or database client). +This library provides async, streaming means for all of this, so you can +handle multiple concurrent connections without blocking. + +**Table of Contents** + +* [Quickstart example](#quickstart-example) +* [Connection usage](#connection-usage) + * [ConnectionInterface](#connectioninterface) + * [getRemoteAddress()](#getremoteaddress) + * [getLocalAddress()](#getlocaladdress) +* [Server usage](#server-usage) + * [ServerInterface](#serverinterface) + * [connection event](#connection-event) + * [error event](#error-event) + * [getAddress()](#getaddress) + * [pause()](#pause) + * [resume()](#resume) + * [close()](#close) + * [SocketServer](#socketserver) + * [Advanced server usage](#advanced-server-usage) + * [TcpServer](#tcpserver) + * [SecureServer](#secureserver) + * [UnixServer](#unixserver) + * [LimitingServer](#limitingserver) + * [getConnections()](#getconnections) +* [Client usage](#client-usage) + * [ConnectorInterface](#connectorinterface) + * [connect()](#connect) + * [Connector](#connector) + * [Advanced client usage](#advanced-client-usage) + * [TcpConnector](#tcpconnector) + * [HappyEyeBallsConnector](#happyeyeballsconnector) + * [DnsConnector](#dnsconnector) + * [SecureConnector](#secureconnector) + * [TimeoutConnector](#timeoutconnector) + * [UnixConnector](#unixconnector) + * [FixUriConnector](#fixeduriconnector) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +Here is a server that closes the connection if you send it anything: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); + +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write("Hello " . $connection->getRemoteAddress() . "!\n"); + $connection->write("Welcome to this amazing server!\n"); + $connection->write("Here's a tip: don't say anything.\n"); + + $connection->on('data', function ($data) use ($connection) { + $connection->close(); + }); +}); +``` + +See also the [examples](examples). + +Here's a client that outputs the output of said server and then attempts to +send it a string: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->pipe(new React\Stream\WritableResourceStream(STDOUT)); + $connection->write("Hello World!\n"); +}); +``` + +## Connection usage + +### ConnectionInterface + +The `ConnectionInterface` is used to represent any incoming and outgoing +connection, such as a normal TCP/IP connection. + +An incoming or outgoing connection is a duplex stream (both readable and +writable) that implements React's +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). +It contains additional properties for the local and remote address (client IP) +where this connection has been established to/from. + +Most commonly, instances implementing this `ConnectionInterface` are emitted +by all classes implementing the [`ServerInterface`](#serverinterface) and +used by all classes implementing the [`ConnectorInterface`](#connectorinterface). + +Because the `ConnectionInterface` implements the underlying +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface) +you can use any of its events and methods as usual: + +```php +$connection->on('data', function ($chunk) { + echo $chunk; +}); + +$connection->on('end', function () { + echo 'ended'; +}); + +$connection->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage(); +}); + +$connection->on('close', function () { + echo 'closed'; +}); + +$connection->write($data); +$connection->end($data = null); +$connection->close(); +// … +``` + +For more details, see the +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + +#### getRemoteAddress() + +The `getRemoteAddress(): ?string` method returns the full remote address +(URI) where this connection has been established with. + +```php +$address = $connection->getRemoteAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the remote address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based connection and you only want the remote IP, you may +use something like this: + +```php +$address = $connection->getRemoteAddress(); +$ip = trim(parse_url($address, PHP_URL_HOST), '[]'); +echo 'Connection with ' . $ip . PHP_EOL; +``` + +#### getLocalAddress() + +The `getLocalAddress(): ?string` method returns the full local address +(URI) where this connection has been established with. + +```php +$address = $connection->getLocalAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the local address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +This method complements the [`getRemoteAddress()`](#getremoteaddress) method, +so they should not be confused. + +If your `TcpServer` instance is listening on multiple interfaces (e.g. using +the address `0.0.0.0`), you can use this method to find out which interface +actually accepted this connection (such as a public or local interface). + +If your system has multiple interfaces (e.g. a WAN and a LAN interface), +you can use this method to find out which interface was actually +used for this connection. + +## Server usage + +### ServerInterface + +The `ServerInterface` is responsible for providing an interface for accepting +incoming streaming connections, such as a normal TCP/IP connection. + +Most higher-level components (such as a HTTP server) accept an instance +implementing this interface to accept incoming streaming connections. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. +This means that you SHOULD typehint against this interface instead of a concrete +implementation of this interface. + +Besides defining a few methods, this interface also implements the +[`EventEmitterInterface`](https://github.com/igorw/evenement) +which allows you to react to certain events. + +#### connection event + +The `connection` event will be emitted whenever a new connection has been +established, i.e. a new client connects to this server socket: + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'new connection' . PHP_EOL; +}); +``` + +See also the [`ConnectionInterface`](#connectioninterface) for more details +about handling the incoming connection. + +#### error event + +The `error` event will be emitted whenever there's an error accepting a new +connection from a client. + +```php +$socket->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that this is not a fatal error event, i.e. the server keeps listening for +new connections even after this event. + + +#### getAddress() + +The `getAddress(): ?string` method can be used to +return the full address (URI) this server is currently listening on. + +```php +$address = $socket->getAddress(); +echo 'Server listening on ' . $address . PHP_EOL; +``` + +If the address can not be determined or is unknown at this time (such as +after the socket has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443` +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based server and you only want the local port, you may +use something like this: + +```php +$address = $socket->getAddress(); +$port = parse_url($address, PHP_URL_PORT); +echo 'Server listening on port ' . $port . PHP_EOL; +``` + +#### pause() + +The `pause(): void` method can be used to +pause accepting new incoming connections. + +Removes the socket resource from the EventLoop and thus stop accepting +new connections. Note that the listening socket stays active and is not +closed. + +This means that new incoming connections will stay pending in the +operating system backlog until its configurable backlog is filled. +Once the backlog is filled, the operating system may reject further +incoming connections until the backlog is drained again by resuming +to accept new connections. + +Once the server is paused, no futher `connection` events SHOULD +be emitted. + +```php +$socket->pause(); + +$socket->on('connection', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +server MAY continue emitting `connection` events. + +Unless otherwise noted, a successfully opened server SHOULD NOT start +in paused state. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### resume() + +The `resume(): void` method can be used to +resume accepting new incoming connections. + +Re-attach the socket resource to the EventLoop after a previous `pause()`. + +```php +$socket->pause(); + +Loop::addTimer(1.0, function () use ($socket) { + $socket->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### close() + +The `close(): void` method can be used to +shut down this listening socket. + +This will stop listening for new incoming connections on this socket. + +```php +echo 'Shutting down server socket' . PHP_EOL; +$socket->close(); +``` + +Calling this method more than once on the same instance is a NO-OP. + +### SocketServer + + + +The `SocketServer` class is the main class in this package that implements the +[`ServerInterface`](#serverinterface) and allows you to accept incoming +streaming connections, such as plaintext TCP/IP or secure TLS connection streams. + +In order to accept plaintext TCP/IP connections, you can simply pass a host +and port combination like this: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +Listening on the localhost address `127.0.0.1` means it will not be reachable from +outside of this system. +In order to change the host the socket is listening on, you can provide an IP +address of an interface or use the special `0.0.0.0` address to listen on all +interfaces: + +```php +$socket = new React\Socket\SocketServer('0.0.0.0:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080'); +``` + +In order to use a random port assignment, you can use the port `0`: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:0'); +$address = $socket->getAddress(); +``` + +To listen on a Unix domain socket (UDS) path, you MUST prefix the URI with the +`unix://` scheme: + +```php +$socket = new React\Socket\SocketServer('unix:///tmp/server.sock'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$socket = new React\Socket\SocketServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\SocketServer('127.0.0.1:8080'); + +// throws RuntimeException because port is already in use +$second = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + See the exception message and code for more details about the actual error + condition. + +Optionally, you can specify [TCP socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080', array( + 'tcp' => array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true + ) +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + Passing unknown context options has no effect. + The `backlog` context option defaults to `511` unless given explicitly. + +You can start a secure TLS (formerly known as SSL) server by simply prepending +the `tls://` URI scheme. +Internally, it will wait for plaintext TCP/IP connections and then performs a +TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8080', array( + 'tls' => array( + 'local_cert' => 'server.pem' + ) +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an + incoming connection initializes its TLS context. + This implies that any invalid certificate file paths or contents will only cause + an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' + ) +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER + ) +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + The outer context array allows you to also use `tcp` (and possibly more) + context options at the same time. + Passing unknown context options has no effect. + If you do not use the `tls://` scheme, then passing `tls` context options + has no effect. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Note that the `SocketServer` class is a concrete implementation for TCP/IP sockets. + If you want to typehint in your higher-level protocol implementation, you SHOULD + use the generic [`ServerInterface`](#serverinterface) instead. + +> Changelog v1.9.0: This class has been added with an improved constructor signature + as a replacement for the previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + +### Advanced server usage + +#### TcpServer + +The `TcpServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting plaintext TCP/IP connections. + +```php +$server = new React\Socket\TcpServer(8080); +``` + +As above, the `$uri` parameter can consist of only a port, in which case the +server will default to listening on the localhost address `127.0.0.1`, +which means it will not be reachable from outside of this system. + +In order to use a random port assignment, you can use the port `0`: + +```php +$server = new React\Socket\TcpServer(0); +$address = $server->getAddress(); +``` + +In order to change the host the socket is listening on, you can provide an IP +address through the first parameter provided to the constructor, optionally +preceded by the `tcp://` scheme: + +```php +$server = new React\Socket\TcpServer('192.168.0.1:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$server = new React\Socket\TcpServer('[::1]:8080'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$server = new React\Socket\TcpServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\TcpServer(8080); + +// throws RuntimeException because port is already in use +$second = new React\Socket\TcpServer(8080); +``` + +> Note that these error conditions may vary depending on your system and/or +configuration. +See the exception message and code for more details about the actual error +condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$server = new React\Socket\TcpServer('[::1]:8080', null, array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. +The `backlog` context option defaults to `511` unless given explicitly. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### SecureServer + +The `SecureServer` class implements the [`ServerInterface`](#serverinterface) +and is responsible for providing a secure TLS (formerly known as SSL) server. + +It does so by wrapping a [`TcpServer`](#tcpserver) instance which waits for plaintext +TCP/IP connections and then performs a TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem' +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an +incoming connection initializes its TLS context. +This implies that any invalid certificate file paths or contents will only cause +an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. + +Whenever a client completes the TLS handshake, it will emit a `connection` event +with a connection instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +Whenever a client fails to perform a successful TLS handshake, it will emit an +`error` event and then close the underlying TCP/IP connection: + +```php +$server->on('error', function (Exception $e) { + echo 'Error' . $e->getMessage() . PHP_EOL; +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +Note that the `SecureServer` class is a concrete implementation for TLS sockets. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ServerInterface`](#serverinterface) instead. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Despite allowing any `ServerInterface` as first parameter, +you SHOULD pass a `TcpServer` instance as first parameter, unless you +know what you're doing. +Internally, the `SecureServer` has to set the required TLS context options on +the underlying stream resources. +These resources are not exposed through any of the interfaces defined in this +package, but only through the internal `Connection` class. +The `TcpServer` class is guaranteed to emit connections that implement +the `ConnectionInterface` and uses the internal `Connection` class in order to +expose these underlying resources. +If you use a custom `ServerInterface` and its `connection` event does not +meet this requirement, the `SecureServer` will emit an `error` event and +then close the underlying connection. + +#### UnixServer + +The `UnixServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting connections on Unix domain sockets (UDS). + +```php +$server = new React\Socket\UnixServer('/tmp/server.sock'); +``` + +As above, the `$uri` parameter can consist of only a socket path or socket path +prefixed by the `unix://` scheme. + +If the given URI appears to be valid, but listening on it fails (such as if the +socket is already in use or the file not accessible etc.), it will throw a +`RuntimeException`: + +```php +$first = new React\Socket\UnixServer('/tmp/same.sock'); + +// throws RuntimeException because socket is already in use +$second = new React\Socket\UnixServer('/tmp/same.sock'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + In particular, Zend PHP does only report "Unknown error" when the UDS path + already exists and can not be bound. You may want to check `is_file()` on the + given UDS path to report a more user-friendly error message in this case. + See the exception message and code for more details about the actual error + condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'New connection' . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### LimitingServer + +The `LimitingServer` decorator wraps a given `ServerInterface` and is responsible +for limiting and keeping track of open connections to this server instance. + +Whenever the underlying server emits a `connection` event, it will check its +limits and then either + - keep track of this connection by adding it to the list of + open connections and then forward the `connection` event + - or reject (close) the connection when its limits are exceeded and will + forward an `error` event instead. + +Whenever a connection closes, it will remove this connection from the list of +open connections. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [second example](examples) for more details. + +You have to pass a maximum number of open connections to ensure +the server will automatically reject (close) connections once this limit +is exceeded. In this case, it will emit an `error` event to inform about +this and no `connection` event will be emitted. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +You MAY pass a `null` limit in order to put no limit on the number of +open connections and keep accepting new connection until you run out of +operating system resources (such as open file handles). This may be +useful if you do not want to take care of applying a limit but still want +to use the `getConnections()` method. + +You can optionally configure the server to pause accepting new +connections once the connection limit is reached. In this case, it will +pause the underlying server and no longer process any new connections at +all, thus also no longer closing any excessive connections. +The underlying operating system is responsible for keeping a backlog of +pending connections until its limit is reached, at which point it will +start rejecting further connections. +Once the server is below the connection limit, it will continue consuming +connections from the backlog and will process any outstanding data on +each connection. +This mode may be useful for some protocols that are designed to wait for +a response message (such as HTTP), but may be less useful for other +protocols that demand immediate responses (such as a "welcome" message in +an interactive chat). + +```php +$server = new React\Socket\LimitingServer($server, 100, true); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +##### getConnections() + +The `getConnections(): ConnectionInterface[]` method can be used to +return an array with all currently active connections. + +```php +foreach ($server->getConnection() as $connection) { + $connection->write('Hi!'); +} +``` + +## Client usage + +### ConnectorInterface + +The `ConnectorInterface` is responsible for providing an interface for +establishing streaming connections, such as a normal TCP/IP connection. + +This is the main interface defined in this package and it is used throughout +React's vast ecosystem. + +Most higher-level components (such as HTTP, database or other networking +service clients) accept an instance implementing this interface to create their +TCP/IP connection to the underlying networking service. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. + +The interface only offers a single method: + +#### connect() + +The `connect(string $uri): PromiseInterface` method +can be used to create a streaming connection to the given remote address. + +It returns a [Promise](https://github.com/reactphp/promise) which either +fulfills with a stream implementing [`ConnectionInterface`](#connectioninterface) +on success or rejects with an `Exception` if the connection is not successful: + +```php +$connector->connect('google.com:443')->then( + function (React\Socket\ConnectionInterface $connection) { + // connection successfully established + }, + function (Exception $error) { + // failed to connect due to $error + } +); +``` + +See also [`ConnectionInterface`](#connectioninterface) for more details. + +The returned Promise MUST be implemented in such a way that it can be +cancelled when it is still pending. Cancelling a pending promise MUST +reject its value with an `Exception`. It SHOULD clean up any underlying +resources and references as applicable: + +```php +$promise = $connector->connect($uri); + +$promise->cancel(); +``` + +### Connector + +The `Connector` class is the main class in this package that implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create streaming connections. + +You can use this connector to create any kind of streaming connections, such +as plaintext TCP/IP, secure TLS or local Unix connection streams. + +It binds to the main event loop and can be used like this: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect($uri)->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +In order to create a plaintext TCP/IP connection, you can simply pass a host +and port combination like this: + +```php +$connector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> If you do no specify a URI scheme in the destination URI, it will assume + `tcp://` as a default and establish a plaintext TCP/IP connection. + Note that TCP/IP connections require a host and port part in the destination + URI like above, all other URI components are optional. + +In order to create a secure TLS connection, you can use the `tls://` URI scheme +like this: + +```php +$connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +In order to create a local Unix domain socket connection, you can use the +`unix://` URI scheme like this: + +```php +$connector->connect('unix:///tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, including + the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +Under the hood, the `Connector` is implemented as a *higher-level facade* +for the lower-level connectors implemented in this package. This means it +also shares all of their features and implementation details. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ConnectorInterface`](#connectorinterface) instead. + +As of `v1.4.0`, the `Connector` class defaults to using the +[happy eyeballs algorithm](https://en.wikipedia.org/wiki/Happy_Eyeballs) to +automatically connect over IPv4 or IPv6 when a hostname is given. +This automatically attempts to connect using both IPv4 and IPv6 at the same time +(preferring IPv6), thus avoiding the usual problems faced by users with imperfect +IPv6 connections or setups. +If you want to revert to the old behavior of only doing an IPv4 lookup and +only attempt a single IPv4 connection, you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'happy_eyeballs' => false +)); +``` + +Similarly, you can also affect the default DNS behavior as follows. +The `Connector` class will try to detect your system DNS settings (and uses +Google's public DNS server `8.8.8.8` as a fallback if unable to determine your +system settings) to resolve all public hostnames into underlying IP addresses by +default. +If you explicitly want to use a custom DNS server (such as a local DNS relay or +a company wide DNS server), you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => '127.0.1.1' +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +If you do not want to use a DNS resolver at all and want to connect to IP +addresses only, you can also set up your `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => false +)); + +$connector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +Advanced: If you need a custom DNS `React\Dns\Resolver\ResolverInterface` instance, you +can also set up your `Connector` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); + +$connector = new React\Socket\Connector(array( + 'dns' => $resolver +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, the `tcp://` and `tls://` URI schemes will use timeout value that +respects your `default_socket_timeout` ini setting (which defaults to 60s). +If you want a custom timeout value, you can simply pass this like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => 10.0 +)); +``` + +Similarly, if you do not want to apply a timeout at all and let the operating +system handle this, you can pass a boolean flag like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => false +)); +``` + +By default, the `Connector` supports the `tcp://`, `tls://` and `unix://` +URI schemes. If you want to explicitly prohibit any of these, you can simply +pass boolean flags like this: + +```php +// only allow secure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => false, + 'tls' => true, + 'unix' => false, +)); + +$connector->connect('tls://google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +The `tcp://` and `tls://` also accept additional context options passed to +the underlying connectors. +If you want to explicitly pass additional context options, you can simply +pass arrays of context options like this: + +```php +// allow insecure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => array( + 'bindto' => '192.168.0.1:0' + ), + 'tls' => array( + 'verify_peer' => false, + 'verify_peer_name' => false + ), +)); + +$connector->connect('tls://localhost:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$connector = new React\Socket\Connector(array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) +)); +``` + +> For more details about context options, please refer to the PHP documentation + about [socket context options](https://www.php.net/manual/en/context.socket.php) + and [SSL context options](https://www.php.net/manual/en/context.ssl.php). + +Advanced: By default, the `Connector` supports the `tcp://`, `tls://` and +`unix://` URI schemes. +For this, it sets up the required connector classes automatically. +If you want to explicitly pass custom connectors for any of these, you can simply +pass an instance implementing the `ConnectorInterface` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); +$tcp = new React\Socket\HappyEyeBallsConnector(null, new React\Socket\TcpConnector(), $resolver); + +$tls = new React\Socket\SecureConnector($tcp); + +$unix = new React\Socket\UnixConnector(); + +$connector = new React\Socket\Connector(array( + 'tcp' => $tcp, + 'tls' => $tls, + 'unix' => $unix, + + 'dns' => false, + 'timeout' => false, +)); + +$connector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> Internally, the `tcp://` connector will always be wrapped by the DNS resolver, + unless you disable DNS like in the above example. In this case, the `tcp://` + connector receives the actual hostname instead of only the resolved IP address + and is thus responsible for performing the lookup. + Internally, the automatically created `tls://` connector will always wrap the + underlying `tcp://` connector for establishing the underlying plaintext + TCP/IP connection before enabling secure TLS mode. If you want to use a custom + underlying `tcp://` connector for secure TLS connections only, you may + explicitly pass a `tls://` connector like above instead. + Internally, the `tcp://` and `tls://` connectors will always be wrapped by + `TimeoutConnector`, unless you disable timeouts like in the above example. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Changelog v1.9.0: The constructur signature has been updated to take the +> optional `$context` as the first parameter and the optional `$loop` as a second +> argument. The previous signature has been deprecated and should not be used anymore. +> +> ```php +> // constructor signature as of v1.9.0 +> $connector = new React\Socket\Connector(array $context = [], ?LoopInterface $loop = null); +> +> // legacy constructor signature before v1.9.0 +> $connector = new React\Socket\Connector(?LoopInterface $loop = null, array $context = []); +> ``` + +### Advanced client usage + +#### TcpConnector + +The `TcpConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any IP-port-combination: + +```php +$tcpConnector = new React\Socket\TcpConnector(); + +$tcpConnector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $tcpConnector->connect('127.0.0.1:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will close the underlying socket +resource, thus cancelling the pending TCP/IP connection, and reject the +resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[socket context options](https://www.php.net/manual/en/context.socket.php) +to the constructor like this: + +```php +$tcpConnector = new React\Socket\TcpConnector(null, array( + 'bindto' => '192.168.0.1:0' +)); +``` + +Note that this class only allows you to connect to IP-port-combinations. +If the given URI is invalid, does not contain a valid IP address and port +or contains any other scheme, it will reject with an +`InvalidArgumentException`: + +If the given URI appears to be valid, but connecting to it fails (such as if +the remote host rejects the connection etc.), it will reject with a +`RuntimeException`. + +If you want to connect to hostname-port-combinations, see also the following chapter. + +> Advanced usage: Internally, the `TcpConnector` allocates an empty *context* +resource for each stream resource. +If the destination URI contains a `hostname` query parameter, its value will +be used to set up the TLS peer name. +This is used by the `SecureConnector` and `DnsConnector` to verify the peer +name and can also be used if you want a custom TLS peer name. + +#### HappyEyeBallsConnector + +The `HappyEyeBallsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. Internally it implements the +happy eyeballs algorithm from [`RFC6555`](https://tools.ietf.org/html/rfc6555) and +[`RFC8305`](https://tools.ietf.org/html/rfc8305) to support IPv6 and IPv4 hostnames. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\HappyEyeBallsConnector(null, $tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookups +and/or the underlying TCP/IP connection(s) and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Internally, the `HappyEyeBallsConnector` relies on a `Resolver` to +look up the IP addresses for the given hostname. +It will then replace the hostname in the destination URI with this IP's and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The Happy Eye Balls algorithm describes looking the IPv6 and IPv4 address for +the given hostname so this connector sends out two DNS lookups for the A and +AAAA records. It then uses all IP addresses (both v6 and v4) and tries to +connect to all of them with a 50ms interval in between. Alterating between IPv6 +and IPv4 addresses. When a connection is established all the other DNS lookups +and connection attempts are cancelled. + +#### DnsConnector + +The `DnsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\DnsConnector($tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookup +and/or the underlying TCP/IP connection and reject the resulting promise. + +> Advanced usage: Internally, the `DnsConnector` relies on a `React\Dns\Resolver\ResolverInterface` +to look up the IP address for the given hostname. +It will then replace the hostname in the destination URI with this IP and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The underlying connector is thus responsible for creating a connection to the +target IP address, while this query parameter can be used to check the original +hostname and is used by the `TcpConnector` to set up the TLS peer name. +If a `hostname` is given explicitly, this query parameter will not be modified, +which can be useful if you want a custom TLS peer name. + +#### SecureConnector + +The `SecureConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create secure +TLS (formerly known as SSL) connections to any hostname-port-combination. + +It does so by decorating a given `DnsConnector` instance so that it first +creates a plaintext TCP/IP connection and then enables TLS encryption on this +stream. + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector); + +$secureConnector->connect('www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n"); + ... +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $secureConnector->connect('www.google.com:443'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying TCP/IP +connection and/or the SSL/TLS negotiation and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[SSL context options](https://www.php.net/manual/en/context.ssl.php) +to the constructor like this: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'verify_peer' => false, + 'verify_peer_name' => false +)); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT +)); +``` + +> Advanced usage: Internally, the `SecureConnector` relies on setting up the +required *context options* on the underlying stream resource. +It should therefor be used with a `TcpConnector` somewhere in the connector +stack so that it can allocate an empty *context* resource for each stream +resource and verify the peer name. +Failing to do so may result in a TLS peer name mismatch error or some hard to +trace race conditions, because all stream resources will use a single, shared +*default context* resource otherwise. + +#### TimeoutConnector + +The `TimeoutConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to add timeout +handling to any existing connector instance. + +It does so by decorating any given [`ConnectorInterface`](#connectorinterface) +instance and starting a timer that will automatically reject and abort any +underlying connection attempt if it takes too long. + +```php +$timeoutConnector = new React\Socket\TimeoutConnector($connector, 3.0); + +$timeoutConnector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + // connection succeeded within 3.0 seconds +}); +``` + +See also any of the [examples](examples). + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $timeoutConnector->connect('google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying connection +attempt, abort the timer and reject the resulting promise. + +#### UnixConnector + +The `UnixConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to connect to +Unix domain socket (UDS) paths like this: + +```php +$connector = new React\Socket\UnixConnector(); + +$connector->connect('/tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("HELLO\n"); +}); +``` + +Connecting to Unix domain sockets is an atomic operation, i.e. its promise will +settle (either resolve or reject) immediately. +As such, calling `cancel()` on the resulting promise has no effect. + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, prepended + with the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +#### FixedUriConnector + +The `FixedUriConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and decorates an existing Connector +to always use a fixed, preconfigured URI. + +This can be useful for consumers that do not support certain URIs, such as +when you want to explicitly connect to a Unix domain socket (UDS) path +instead of connecting to a default address assumed by an higher-level API: + +```php +$connector = new React\Socket\FixedUriConnector( + 'unix:///var/run/docker.sock', + new React\Socket\UnixConnector() +); + +// destination will be ignored, actually connects to Unix domain socket +$promise = $connector->connect('localhost:80'); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/socket:^1.9 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use PHP 7+* for this project, partly due to its vast +performance improvements and partly because legacy PHP versions require several +workarounds as described below. + +Secure TLS connections received some major upgrades starting with PHP 5.6, with +the defaults now being more secure, while older versions required explicit +context options. +This library does not take responsibility over these context options, so it's +up to consumers of this library to take care of setting appropriate context +options as described above. + +PHP < 7.3.3 (and PHP < 7.2.15) suffers from a bug where feof() might +block with 100% CPU usage on fragmented TLS records. +We try to work around this by always consuming the complete receive +buffer at once to avoid stale data in TLS buffers. This is known to +work around high CPU usage for well-behaving peers, but this may +cause very large data chunks for high throughput scenarios. The buggy +behavior can still be triggered due to network I/O buffers or +malicious peers on affected versions, upgrading is highly recommended. + +PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big +chunks of data over TLS streams at once. +We try to work around this by limiting the write chunk size to 8192 +bytes for older PHP versions only. +This is only a work-around and has a noticable performance penalty on +affected versions. + +This project also supports running on HHVM. +Note that really old HHVM < 3.8 does not support secure TLS connections, as it +lacks the required `stream_socket_enable_crypto()` function. +As such, trying to create a secure TLS connections on affected versions will +return a rejected promise instead. +This issue is also covered by our test suite, which will skip related tests +on affected versions. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +$ php vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/composer.json new file mode 100644 index 0000000..9ff445f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/composer.json @@ -0,0 +1,52 @@ +{ + "name": "react/socket", + "description": "Async, streaming plaintext TCP/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": ["async", "socket", "stream", "connection", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0", + "react/dns": "^1.8", + "react/event-loop": "^1.2", + "react/promise": "^2.6.0 || ^1.2.1", + "react/promise-timer": "^1.4.0", + "react/stream": "^1.2" + }, + "require-dev": { + "clue/block-react": "^1.2", + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35", + "react/promise-stream": "^1.2" + }, + "autoload": { + "psr-4": { + "React\\Socket\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Socket\\": "tests" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connection.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connection.php new file mode 100644 index 0000000..5e3b00d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connection.php @@ -0,0 +1,187 @@ += 70300 && \PHP_VERSION_ID < 70303); + + // PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big + // chunks of data over TLS streams at once. + // We try to work around this by limiting the write chunk size to 8192 + // bytes for older PHP versions only. + // This is only a work-around and has a noticable performance penalty on + // affected versions. Please update your PHP version. + // This applies to all streams because TLS may be enabled later on. + // See https://github.com/reactphp/socket/issues/105 + $limitWriteChunks = (\PHP_VERSION_ID < 70018 || (\PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70104)); + + $this->input = new DuplexResourceStream( + $resource, + $loop, + $clearCompleteBuffer ? -1 : null, + new WritableResourceStream($resource, $loop, null, $limitWriteChunks ? 8192 : null) + ); + + $this->stream = $resource; + + Util::forwardEvents($this->input, $this, array('data', 'end', 'error', 'close', 'pipe', 'drain')); + + $this->input->on('close', array($this, 'close')); + } + + public function isReadable() + { + return $this->input->isReadable(); + } + + public function isWritable() + { + return $this->input->isWritable(); + } + + public function pause() + { + $this->input->pause(); + } + + public function resume() + { + $this->input->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return $this->input->pipe($dest, $options); + } + + public function write($data) + { + return $this->input->write($data); + } + + public function end($data = null) + { + $this->input->end($data); + } + + public function close() + { + $this->input->close(); + $this->handleClose(); + $this->removeAllListeners(); + } + + public function handleClose() + { + if (!\is_resource($this->stream)) { + return; + } + + // Try to cleanly shut down socket and ignore any errors in case other + // side already closed. Shutting down may return to blocking mode on + // some legacy versions, so reset to non-blocking just in case before + // continuing to close the socket resource. + // Underlying Stream implementation will take care of closing file + // handle, so we otherwise keep this open here. + @\stream_socket_shutdown($this->stream, \STREAM_SHUT_RDWR); + \stream_set_blocking($this->stream, false); + } + + public function getRemoteAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + + return $this->parseAddress(\stream_socket_get_name($this->stream, true)); + } + + public function getLocalAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + + return $this->parseAddress(\stream_socket_get_name($this->stream, false)); + } + + private function parseAddress($address) + { + if ($address === false) { + return null; + } + + if ($this->unix) { + // remove trailing colon from address for HHVM < 3.19: https://3v4l.org/5C1lo + // note that technically ":" is a valid address, so keep this in place otherwise + if (\substr($address, -1) === ':' && \defined('HHVM_VERSION_ID') && \HHVM_VERSION_ID < 31900) { + $address = (string)\substr($address, 0, -1); // @codeCoverageIgnore + } + + // work around unknown addresses should return null value: https://3v4l.org/5C1lo and https://bugs.php.net/bug.php?id=74556 + // PHP uses "\0" string and HHVM uses empty string (colon removed above) + if ($address === '' || $address[0] === "\x00" ) { + return null; // @codeCoverageIgnore + } + + return 'unix://' . $address; + } + + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore + } + + return ($this->encryptionEnabled ? 'tls' : 'tcp') . '://' . $address; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectionInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectionInterface.php new file mode 100644 index 0000000..64613b5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectionInterface.php @@ -0,0 +1,119 @@ +on('data', function ($chunk) { + * echo $chunk; + * }); + * + * $connection->on('end', function () { + * echo 'ended'; + * }); + * + * $connection->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage(); + * }); + * + * $connection->on('close', function () { + * echo 'closed'; + * }); + * + * $connection->write($data); + * $connection->end($data = null); + * $connection->close(); + * // … + * ``` + * + * For more details, see the + * [`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + * + * @see DuplexStreamInterface + * @see ServerInterface + * @see ConnectorInterface + */ +interface ConnectionInterface extends DuplexStreamInterface +{ + /** + * Returns the full remote address (URI) where this connection has been established with + * + * ```php + * $address = $connection->getRemoteAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the remote address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based connection and you only want the remote IP, you may + * use something like this: + * + * ```php + * $address = $connection->getRemoteAddress(); + * $ip = trim(parse_url($address, PHP_URL_HOST), '[]'); + * echo 'Connection with ' . $ip . PHP_EOL; + * ``` + * + * @return ?string remote address (URI) or null if unknown + */ + public function getRemoteAddress(); + + /** + * Returns the full local address (full URI with scheme, IP and port) where this connection has been established with + * + * ```php + * $address = $connection->getLocalAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the local address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * This method complements the [`getRemoteAddress()`](#getremoteaddress) method, + * so they should not be confused. + * + * If your `TcpServer` instance is listening on multiple interfaces (e.g. using + * the address `0.0.0.0`), you can use this method to find out which interface + * actually accepted this connection (such as a public or local interface). + * + * If your system has multiple interfaces (e.g. a WAN and a LAN interface), + * you can use this method to find out which interface was actually + * used for this connection. + * + * @return ?string local address (URI) or null if unknown + * @see self::getRemoteAddress() + */ + public function getLocalAddress(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connector.php new file mode 100644 index 0000000..b500eb3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Connector.php @@ -0,0 +1,178 @@ + true, + 'tls' => true, + 'unix' => true, + + 'dns' => true, + 'timeout' => true, + 'happy_eyeballs' => true, + ); + + if ($context['timeout'] === true) { + $context['timeout'] = (float)\ini_get("default_socket_timeout"); + } + + if ($context['tcp'] instanceof ConnectorInterface) { + $tcp = $context['tcp']; + } else { + $tcp = new TcpConnector( + $loop, + \is_array($context['tcp']) ? $context['tcp'] : array() + ); + } + + if ($context['dns'] !== false) { + if ($context['dns'] instanceof ResolverInterface) { + $resolver = $context['dns']; + } else { + if ($context['dns'] !== true) { + $config = $context['dns']; + } else { + // try to load nameservers from system config or default to Google's public DNS + $config = DnsConfig::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; // @codeCoverageIgnore + } + } + + $factory = new DnsFactory(); + $resolver = $factory->createCached( + $config, + $loop + ); + } + + if ($context['happy_eyeballs'] === true) { + $tcp = new HappyEyeBallsConnector($loop, $tcp, $resolver); + } else { + $tcp = new DnsConnector($tcp, $resolver); + } + } + + if ($context['tcp'] !== false) { + $context['tcp'] = $tcp; + + if ($context['timeout'] !== false) { + $context['tcp'] = new TimeoutConnector( + $context['tcp'], + $context['timeout'], + $loop + ); + } + + $this->connectors['tcp'] = $context['tcp']; + } + + if ($context['tls'] !== false) { + if (!$context['tls'] instanceof ConnectorInterface) { + $context['tls'] = new SecureConnector( + $tcp, + $loop, + \is_array($context['tls']) ? $context['tls'] : array() + ); + } + + if ($context['timeout'] !== false) { + $context['tls'] = new TimeoutConnector( + $context['tls'], + $context['timeout'], + $loop + ); + } + + $this->connectors['tls'] = $context['tls']; + } + + if ($context['unix'] !== false) { + if (!$context['unix'] instanceof ConnectorInterface) { + $context['unix'] = new UnixConnector($loop); + } + $this->connectors['unix'] = $context['unix']; + } + } + + public function connect($uri) + { + $scheme = 'tcp'; + if (\strpos($uri, '://') !== false) { + $scheme = (string)\substr($uri, 0, \strpos($uri, '://')); + } + + if (!isset($this->connectors[$scheme])) { + return \React\Promise\reject(new \RuntimeException( + 'No connector available for URI scheme "' . $scheme . '"' + )); + } + + return $this->connectors[$scheme]->connect($uri); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectorInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectorInterface.php new file mode 100644 index 0000000..3dd78f1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ConnectorInterface.php @@ -0,0 +1,58 @@ +connect('google.com:443')->then( + * function (React\Socket\ConnectionInterface $connection) { + * // connection successfully established + * }, + * function (Exception $error) { + * // failed to connect due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $connector->connect($uri); + * + * $promise->cancel(); + * ``` + * + * @param string $uri + * @return \React\Promise\PromiseInterface resolves with a stream implementing ConnectionInterface on success or rejects with an Exception on error + * @see ConnectionInterface + */ + public function connect($uri); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/DnsConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/DnsConnector.php new file mode 100644 index 0000000..9d0341b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/DnsConnector.php @@ -0,0 +1,115 @@ +connector = $connector; + $this->resolver = $resolver; + } + + public function connect($uri) + { + if (\strpos($uri, '://') === false) { + $parts = \parse_url('tcp://' . $uri); + unset($parts['scheme']); + } else { + $parts = \parse_url($uri); + } + + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid')); + } + + $host = \trim($parts['host'], '[]'); + $connector = $this->connector; + + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (false !== \filter_var($host, \FILTER_VALIDATE_IP)) { + return $connector->connect($uri); + } + + $promise = $this->resolver->resolve($host); + $resolved = null; + + return new Promise\Promise( + function ($resolve, $reject) use (&$promise, &$resolved, $uri, $connector, $host, $parts) { + // resolve/reject with result of DNS lookup + $promise->then(function ($ip) use (&$promise, &$resolved, $connector, $host, $parts) { + $resolved = $ip; + $uri = ''; + + // prepend original scheme if known + if (isset($parts['scheme'])) { + $uri .= $parts['scheme'] . '://'; + } + + if (\strpos($ip, ':') !== false) { + // enclose IPv6 addresses in square brackets before appending port + $uri .= '[' . $ip . ']'; + } else { + $uri .= $ip; + } + + // append original port if known + if (isset($parts['port'])) { + $uri .= ':' . $parts['port']; + } + + // append orignal path if known + if (isset($parts['path'])) { + $uri .= $parts['path']; + } + + // append original query if known + if (isset($parts['query'])) { + $uri .= '?' . $parts['query']; + } + + // append original hostname as query if resolved via DNS and if + // destination URI does not contain "hostname" query param already + $args = array(); + \parse_str(isset($parts['query']) ? $parts['query'] : '', $args); + if ($host !== $ip && !isset($args['hostname'])) { + $uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host); + } + + // append original fragment if known + if (isset($parts['fragment'])) { + $uri .= '#' . $parts['fragment']; + } + + return $promise = $connector->connect($uri); + }, function ($e) use ($uri, $reject) { + $reject(new \RuntimeException('Connection to ' . $uri .' failed during DNS lookup: ' . $e->getMessage(), 0, $e)); + })->then($resolve, $reject); + }, + function ($_, $reject) use (&$promise, &$resolved, $uri) { + // cancellation should reject connection attempt + // reject DNS resolution with custom reason, otherwise rely on connection cancellation below + if ($resolved === null) { + $reject(new \RuntimeException('Connection to ' . $uri . ' cancelled during DNS lookup')); + } + + // (try to) cancel pending DNS lookup / connection attempt + if ($promise instanceof CancellablePromiseInterface) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $_ = $reject = null; + + $promise->cancel(); + $promise = null; + } + } + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/FixedUriConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/FixedUriConnector.php new file mode 100644 index 0000000..f83241d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/FixedUriConnector.php @@ -0,0 +1,41 @@ +connect('localhost:80'); + * ``` + */ +class FixedUriConnector implements ConnectorInterface +{ + private $uri; + private $connector; + + /** + * @param string $uri + * @param ConnectorInterface $connector + */ + public function __construct($uri, ConnectorInterface $connector) + { + $this->uri = $uri; + $this->connector = $connector; + } + + public function connect($_) + { + return $this->connector->connect($this->uri); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php new file mode 100644 index 0000000..4ec671a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php @@ -0,0 +1,361 @@ + false, + Message::TYPE_AAAA => false, + ); + public $resolverPromises = array(); + public $connectionPromises = array(); + public $connectQueue = array(); + public $nextAttemptTimer; + public $parts; + public $ipsCount = 0; + public $failureCount = 0; + public $resolve; + public $reject; + + public $lastErrorFamily; + public $lastError6; + public $lastError4; + + public function __construct(LoopInterface $loop, ConnectorInterface $connector, ResolverInterface $resolver, $uri, $host, $parts) + { + $this->loop = $loop; + $this->connector = $connector; + $this->resolver = $resolver; + $this->uri = $uri; + $this->host = $host; + $this->parts = $parts; + } + + public function connect() + { + $timer = null; + $that = $this; + return new Promise\Promise(function ($resolve, $reject) use ($that, &$timer) { + $lookupResolve = function ($type) use ($that, $resolve, $reject) { + return function (array $ips) use ($that, $type, $resolve, $reject) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = true; + + $that->mixIpsIntoConnectQueue($ips); + + // start next connection attempt if not already awaiting next + if ($that->nextAttemptTimer === null && $that->connectQueue) { + $that->check($resolve, $reject); + } + }; + }; + + $that->resolverPromises[Message::TYPE_AAAA] = $that->resolve(Message::TYPE_AAAA, $reject)->then($lookupResolve(Message::TYPE_AAAA)); + $that->resolverPromises[Message::TYPE_A] = $that->resolve(Message::TYPE_A, $reject)->then(function (array $ips) use ($that, &$timer) { + // happy path: IPv6 has resolved already (or could not resolve), continue with IPv4 addresses + if ($that->resolved[Message::TYPE_AAAA] === true || !$ips) { + return $ips; + } + + // Otherwise delay processing IPv4 lookup until short timer passes or IPv6 resolves in the meantime + $deferred = new Promise\Deferred(); + $timer = $that->loop->addTimer($that::RESOLUTION_DELAY, function () use ($deferred, $ips) { + $deferred->resolve($ips); + }); + + $that->resolverPromises[Message::TYPE_AAAA]->then(function () use ($that, $timer, $deferred, $ips) { + $that->loop->cancelTimer($timer); + $deferred->resolve($ips); + }); + + return $deferred->promise(); + })->then($lookupResolve(Message::TYPE_A)); + }, function ($_, $reject) use ($that, &$timer) { + $reject(new \RuntimeException('Connection to ' . $that->uri . ' cancelled' . (!$that->connectionPromises ? ' during DNS lookup' : ''))); + $_ = $reject = null; + + $that->cleanUp(); + if ($timer instanceof TimerInterface) { + $that->loop->cancelTimer($timer); + } + }); + } + + /** + * @internal + * @param int $type DNS query type + * @param callable $reject + * @return \React\Promise\PromiseInterface Returns a promise that + * always resolves with a list of IP addresses on success or an empty + * list on error. + */ + public function resolve($type, $reject) + { + $that = $this; + return $that->resolver->resolveAll($that->host, $type)->then(null, function (\Exception $e) use ($type, $reject, $that) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = true; + + if ($type === Message::TYPE_A) { + $that->lastError4 = $e->getMessage(); + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $e->getMessage(); + $that->lastErrorFamily = 6; + } + + // cancel next attempt timer when there are no more IPs to connect to anymore + if ($that->nextAttemptTimer !== null && !$that->connectQueue) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + + if ($that->hasBeenResolved() && $that->ipsCount === 0) { + $reject(new \RuntimeException($that->error())); + } + + // Exception already handled above, so don't throw an unhandled rejection here + return array(); + }); + } + + /** + * @internal + */ + public function check($resolve, $reject) + { + $ip = \array_shift($this->connectQueue); + + // start connection attempt and remember array position to later unset again + $this->connectionPromises[] = $this->attemptConnection($ip); + \end($this->connectionPromises); + $index = \key($this->connectionPromises); + + $that = $this; + $that->connectionPromises[$index]->then(function ($connection) use ($that, $index, $resolve) { + unset($that->connectionPromises[$index]); + + $that->cleanUp(); + + $resolve($connection); + }, function (\Exception $e) use ($that, $index, $ip, $resolve, $reject) { + unset($that->connectionPromises[$index]); + + $that->failureCount++; + + if (\strpos($ip, ':') === false) { + $that->lastError4 = $e->getMessage(); + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $e->getMessage(); + $that->lastErrorFamily = 6; + } + + // start next connection attempt immediately on error + if ($that->connectQueue) { + if ($that->nextAttemptTimer !== null) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + + $that->check($resolve, $reject); + } + + if ($that->hasBeenResolved() === false) { + return; + } + + if ($that->ipsCount === $that->failureCount) { + $that->cleanUp(); + + $reject(new \RuntimeException($that->error())); + } + }); + + // Allow next connection attempt in 100ms: https://tools.ietf.org/html/rfc8305#section-5 + // Only start timer when more IPs are queued or when DNS query is still pending (might add more IPs) + if ($this->nextAttemptTimer === null && (\count($this->connectQueue) > 0 || $this->resolved[Message::TYPE_A] === false || $this->resolved[Message::TYPE_AAAA] === false)) { + $this->nextAttemptTimer = $this->loop->addTimer(self::CONNECTION_ATTEMPT_DELAY, function () use ($that, $resolve, $reject) { + $that->nextAttemptTimer = null; + + if ($that->connectQueue) { + $that->check($resolve, $reject); + } + }); + } + } + + /** + * @internal + */ + public function attemptConnection($ip) + { + $uri = ''; + + // prepend original scheme if known + if (isset($this->parts['scheme'])) { + $uri .= $this->parts['scheme'] . '://'; + } + + if (\strpos($ip, ':') !== false) { + // enclose IPv6 addresses in square brackets before appending port + $uri .= '[' . $ip . ']'; + } else { + $uri .= $ip; + } + + // append original port if known + if (isset($this->parts['port'])) { + $uri .= ':' . $this->parts['port']; + } + + // append orignal path if known + if (isset($this->parts['path'])) { + $uri .= $this->parts['path']; + } + + // append original query if known + if (isset($this->parts['query'])) { + $uri .= '?' . $this->parts['query']; + } + + // append original hostname as query if resolved via DNS and if + // destination URI does not contain "hostname" query param already + $args = array(); + \parse_str(isset($this->parts['query']) ? $this->parts['query'] : '', $args); + if ($this->host !== $ip && !isset($args['hostname'])) { + $uri .= (isset($this->parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($this->host); + } + + // append original fragment if known + if (isset($this->parts['fragment'])) { + $uri .= '#' . $this->parts['fragment']; + } + + return $this->connector->connect($uri); + } + + /** + * @internal + */ + public function cleanUp() + { + // clear list of outstanding IPs to avoid creating new connections + $this->connectQueue = array(); + + foreach ($this->connectionPromises as $connectionPromise) { + if ($connectionPromise instanceof CancellablePromiseInterface) { + $connectionPromise->cancel(); + } + } + + foreach ($this->resolverPromises as $resolverPromise) { + if ($resolverPromise instanceof CancellablePromiseInterface) { + $resolverPromise->cancel(); + } + } + + if ($this->nextAttemptTimer instanceof TimerInterface) { + $this->loop->cancelTimer($this->nextAttemptTimer); + $this->nextAttemptTimer = null; + } + } + + /** + * @internal + */ + public function hasBeenResolved() + { + foreach ($this->resolved as $typeHasBeenResolved) { + if ($typeHasBeenResolved === false) { + return false; + } + } + + return true; + } + + /** + * Mixes an array of IP addresses into the connect queue in such a way they alternate when attempting to connect. + * The goal behind it is first attempt to connect to IPv6, then to IPv4, then to IPv6 again until one of those + * attempts succeeds. + * + * @link https://tools.ietf.org/html/rfc8305#section-4 + * + * @internal + */ + public function mixIpsIntoConnectQueue(array $ips) + { + \shuffle($ips); + $this->ipsCount += \count($ips); + $connectQueueStash = $this->connectQueue; + $this->connectQueue = array(); + while (\count($connectQueueStash) > 0 || \count($ips) > 0) { + if (\count($ips) > 0) { + $this->connectQueue[] = \array_shift($ips); + } + if (\count($connectQueueStash) > 0) { + $this->connectQueue[] = \array_shift($connectQueueStash); + } + } + } + + /** + * @internal + * @return string + */ + public function error() + { + if ($this->lastError4 === $this->lastError6) { + $message = $this->lastError6; + } elseif ($this->lastErrorFamily === 6) { + $message = 'Last error for IPv6: ' . $this->lastError6 . '. Previous error for IPv4: ' . $this->lastError4; + } else { + $message = 'Last error for IPv4: ' . $this->lastError4 . '. Previous error for IPv6: ' . $this->lastError6; + } + + if ($this->hasBeenResolved() && $this->ipsCount === 0) { + if ($this->lastError6 === $this->lastError4) { + $message = ' during DNS lookup: ' . $this->lastError6; + } else { + $message = ' during DNS lookup. ' . $message; + } + } else { + $message = ': ' . $message; + } + + return 'Connection to ' . $this->uri . ' failed' . $message; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnector.php new file mode 100644 index 0000000..677b7c7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/HappyEyeBallsConnector.php @@ -0,0 +1,63 @@ +loop = $loop ?: Loop::get(); + $this->connector = $connector; + $this->resolver = $resolver; + } + + public function connect($uri) + { + + if (\strpos($uri, '://') === false) { + $parts = \parse_url('tcp://' . $uri); + unset($parts['scheme']); + } else { + $parts = \parse_url($uri); + } + + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid')); + } + + $host = \trim($parts['host'], '[]'); + + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (false !== \filter_var($host, \FILTER_VALIDATE_IP)) { + return $this->connector->connect($uri); + } + + $builder = new HappyEyeBallsConnectionBuilder( + $this->loop, + $this->connector, + $this->resolver, + $uri, + $host, + $parts + ); + return $builder->connect(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/LimitingServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/LimitingServer.php new file mode 100644 index 0000000..d19000b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/LimitingServer.php @@ -0,0 +1,203 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +class LimitingServer extends EventEmitter implements ServerInterface +{ + private $connections = array(); + private $server; + private $limit; + + private $pauseOnLimit = false; + private $autoPaused = false; + private $manuPaused = false; + + /** + * Instantiates a new LimitingServer. + * + * You have to pass a maximum number of open connections to ensure + * the server will automatically reject (close) connections once this limit + * is exceeded. In this case, it will emit an `error` event to inform about + * this and no `connection` event will be emitted. + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * You MAY pass a `null` limit in order to put no limit on the number of + * open connections and keep accepting new connection until you run out of + * operating system resources (such as open file handles). This may be + * useful if you do not want to take care of applying a limit but still want + * to use the `getConnections()` method. + * + * You can optionally configure the server to pause accepting new + * connections once the connection limit is reached. In this case, it will + * pause the underlying server and no longer process any new connections at + * all, thus also no longer closing any excessive connections. + * The underlying operating system is responsible for keeping a backlog of + * pending connections until its limit is reached, at which point it will + * start rejecting further connections. + * Once the server is below the connection limit, it will continue consuming + * connections from the backlog and will process any outstanding data on + * each connection. + * This mode may be useful for some protocols that are designed to wait for + * a response message (such as HTTP), but may be less useful for other + * protocols that demand immediate responses (such as a "welcome" message in + * an interactive chat). + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100, true); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * @param ServerInterface $server + * @param int|null $connectionLimit + * @param bool $pauseOnLimit + */ + public function __construct(ServerInterface $server, $connectionLimit, $pauseOnLimit = false) + { + $this->server = $server; + $this->limit = $connectionLimit; + if ($connectionLimit !== null) { + $this->pauseOnLimit = $pauseOnLimit; + } + + $this->server->on('connection', array($this, 'handleConnection')); + $this->server->on('error', array($this, 'handleError')); + } + + /** + * Returns an array with all currently active connections + * + * ```php + * foreach ($server->getConnection() as $connection) { + * $connection->write('Hi!'); + * } + * ``` + * + * @return ConnectionInterface[] + */ + public function getConnections() + { + return $this->connections; + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + if (!$this->manuPaused) { + $this->manuPaused = true; + + if (!$this->autoPaused) { + $this->server->pause(); + } + } + } + + public function resume() + { + if ($this->manuPaused) { + $this->manuPaused = false; + + if (!$this->autoPaused) { + $this->server->resume(); + } + } + } + + public function close() + { + $this->server->close(); + } + + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + // close connection if limit exceeded + if ($this->limit !== null && \count($this->connections) >= $this->limit) { + $this->handleError(new \OverflowException('Connection closed because server reached connection limit')); + $connection->close(); + return; + } + + $this->connections[] = $connection; + $that = $this; + $connection->on('close', function () use ($that, $connection) { + $that->handleDisconnection($connection); + }); + + // pause accepting new connections if limit exceeded + if ($this->pauseOnLimit && !$this->autoPaused && \count($this->connections) >= $this->limit) { + $this->autoPaused = true; + + if (!$this->manuPaused) { + $this->server->pause(); + } + } + + $this->emit('connection', array($connection)); + } + + /** @internal */ + public function handleDisconnection(ConnectionInterface $connection) + { + unset($this->connections[\array_search($connection, $this->connections)]); + + // continue accepting new connection if below limit + if ($this->autoPaused && \count($this->connections) < $this->limit) { + $this->autoPaused = false; + + if (!$this->manuPaused) { + $this->server->resume(); + } + } + } + + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureConnector.php new file mode 100644 index 0000000..0e6bd7c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureConnector.php @@ -0,0 +1,85 @@ +connector = $connector; + $this->streamEncryption = new StreamEncryption($loop ?: Loop::get(), false); + $this->context = $context; + } + + public function connect($uri) + { + if (!\function_exists('stream_socket_enable_crypto')) { + return Promise\reject(new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)')); // @codeCoverageIgnore + } + + if (\strpos($uri, '://') === false) { + $uri = 'tls://' . $uri; + } + + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme']) || $parts['scheme'] !== 'tls') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid')); + } + + $uri = \str_replace('tls://', '', $uri); + $context = $this->context; + + $encryption = $this->streamEncryption; + $connected = false; + $promise = $this->connector->connect($uri)->then(function (ConnectionInterface $connection) use ($context, $encryption, $uri, &$promise, &$connected) { + // (unencrypted) TCP/IP connection succeeded + $connected = true; + + if (!$connection instanceof Connection) { + $connection->close(); + throw new \UnexpectedValueException('Base connector does not use internal Connection class exposing stream resource'); + } + + // set required SSL/TLS context options + foreach ($context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + + // try to enable encryption + return $promise = $encryption->enable($connection)->then(null, function ($error) use ($connection, $uri) { + // establishing encryption failed => close invalid connection and return error + $connection->close(); + + throw new \RuntimeException( + 'Connection to ' . $uri . ' failed during TLS handshake: ' . $error->getMessage(), + $error->getCode() + ); + }); + }); + + return new \React\Promise\Promise( + function ($resolve, $reject) use ($promise) { + $promise->then($resolve, $reject); + }, + function ($_, $reject) use (&$promise, $uri, &$connected) { + if ($connected) { + $reject(new \RuntimeException('Connection to ' . $uri . ' cancelled during TLS handshake')); + } + + $promise->cancel(); + $promise = null; + } + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureServer.php new file mode 100644 index 0000000..d0525c9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SecureServer.php @@ -0,0 +1,206 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + * + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * Whenever a client fails to perform a successful TLS handshake, it will emit an + * `error` event and then close the underlying TCP/IP connection: + * + * ```php + * $server->on('error', function (Exception $e) { + * echo 'Error' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * Note that the `SecureServer` class is a concrete implementation for TLS sockets. + * If you want to typehint in your higher-level protocol implementation, you SHOULD + * use the generic `ServerInterface` instead. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class SecureServer extends EventEmitter implements ServerInterface +{ + private $tcp; + private $encryption; + private $context; + + /** + * Creates a secure TLS server and starts waiting for incoming connections + * + * It does so by wrapping a `TcpServer` instance which waits for plaintext + * TCP/IP connections and then performs a TLS handshake for each connection. + * It thus requires valid [TLS context options], + * which in its most basic form may look something like this if you're using a + * PEM encoded certificate file: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem' + * )); + * ``` + * + * Note that the certificate file will not be loaded on instantiation but when an + * incoming connection initializes its TLS context. + * This implies that any invalid certificate file paths or contents will only cause + * an `error` event at a later time. + * + * If your private key is encrypted with a passphrase, you have to specify it + * like this: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem', + * 'passphrase' => 'secret' + * )); + * ``` + * + * Note that available [TLS context options], + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Advanced usage: Despite allowing any `ServerInterface` as first parameter, + * you SHOULD pass a `TcpServer` instance as first parameter, unless you + * know what you're doing. + * Internally, the `SecureServer` has to set the required TLS context options on + * the underlying stream resources. + * These resources are not exposed through any of the interfaces defined in this + * package, but only through the internal `Connection` class. + * The `TcpServer` class is guaranteed to emit connections that implement + * the `ConnectionInterface` and uses the internal `Connection` class in order to + * expose these underlying resources. + * If you use a custom `ServerInterface` and its `connection` event does not + * meet this requirement, the `SecureServer` will emit an `error` event and + * then close the underlying connection. + * + * @param ServerInterface|TcpServer $tcp + * @param ?LoopInterface $loop + * @param array $context + * @throws BadMethodCallException for legacy HHVM < 3.8 due to lack of support + * @see TcpServer + * @link https://www.php.net/manual/en/context.ssl.php for TLS context options + */ + public function __construct(ServerInterface $tcp, LoopInterface $loop = null, array $context = array()) + { + if (!\function_exists('stream_socket_enable_crypto')) { + throw new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)'); // @codeCoverageIgnore + } + + // default to empty passphrase to suppress blocking passphrase prompt + $context += array( + 'passphrase' => '' + ); + + $this->tcp = $tcp; + $this->encryption = new StreamEncryption($loop ?: Loop::get()); + $this->context = $context; + + $that = $this; + $this->tcp->on('connection', function ($connection) use ($that) { + $that->handleConnection($connection); + }); + $this->tcp->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + $address = $this->tcp->getAddress(); + if ($address === null) { + return null; + } + + return \str_replace('tcp://' , 'tls://', $address); + } + + public function pause() + { + $this->tcp->pause(); + } + + public function resume() + { + $this->tcp->resume(); + } + + public function close() + { + return $this->tcp->close(); + } + + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + if (!$connection instanceof Connection) { + $this->emit('error', array(new \UnexpectedValueException('Base server does not use internal Connection class exposing stream resource'))); + $connection->close(); + return; + } + + foreach ($this->context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + + // get remote address before starting TLS handshake in case connection closes during handshake + $remote = $connection->getRemoteAddress(); + $that = $this; + + $this->encryption->enable($connection)->then( + function ($conn) use ($that) { + $that->emit('connection', array($conn)); + }, + function ($error) use ($that, $connection, $remote) { + $error = new \RuntimeException( + 'Connection from ' . $remote . ' failed during TLS handshake: ' . $error->getMessage(), + $error->getCode() + ); + + $that->emit('error', array($error)); + $connection->close(); + } + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Server.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Server.php new file mode 100644 index 0000000..7d4111e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/Server.php @@ -0,0 +1,114 @@ + $context); + } + + // apply default options if not explicitly given + $context += array( + 'tcp' => array(), + 'tls' => array(), + 'unix' => array() + ); + + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== false) { + $scheme = \substr($uri, 0, $pos); + } + + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } else { + $server = new TcpServer(str_replace('tls://', '', $uri), $loop, $context['tcp']); + + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + + $this->server = $server; + + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use ($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (Exception $error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + $this->server->pause(); + } + + public function resume() + { + $this->server->resume(); + } + + public function close() + { + $this->server->close(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ServerInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ServerInterface.php new file mode 100644 index 0000000..aa79fa1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/ServerInterface.php @@ -0,0 +1,151 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'new connection' . PHP_EOL; + * }); + * ``` + * + * See also the `ConnectionInterface` for more details about handling the + * incoming connection. + * + * error event: + * The `error` event will be emitted whenever there's an error accepting a new + * connection from a client. + * + * ```php + * $socket->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * Note that this is not a fatal error event, i.e. the server keeps listening for + * new connections even after this event. + * + * @see ConnectionInterface + */ +interface ServerInterface extends EventEmitterInterface +{ + /** + * Returns the full address (URI) this server is currently listening on + * + * ```php + * $address = $socket->getAddress(); + * echo 'Server listening on ' . $address . PHP_EOL; + * ``` + * + * If the address can not be determined or is unknown at this time (such as + * after the socket has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80` or `tls://127.0.0.1:443`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based server and you only want the local port, you may + * use something like this: + * + * ```php + * $address = $socket->getAddress(); + * $port = parse_url($address, PHP_URL_PORT); + * echo 'Server listening on port ' . $port . PHP_EOL; + * ``` + * + * @return ?string the full listening address (URI) or NULL if it is unknown (not applicable to this server socket or already closed) + */ + public function getAddress(); + + /** + * Pauses accepting new incoming connections. + * + * Removes the socket resource from the EventLoop and thus stop accepting + * new connections. Note that the listening socket stays active and is not + * closed. + * + * This means that new incoming connections will stay pending in the + * operating system backlog until its configurable backlog is filled. + * Once the backlog is filled, the operating system may reject further + * incoming connections until the backlog is drained again by resuming + * to accept new connections. + * + * Once the server is paused, no futher `connection` events SHOULD + * be emitted. + * + * ```php + * $socket->pause(); + * + * $socket->on('connection', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * server MAY continue emitting `connection` events. + * + * Unless otherwise noted, a successfully opened server SHOULD NOT start + * in paused state. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::resume() + * @return void + */ + public function pause(); + + /** + * Resumes accepting new incoming connections. + * + * Re-attach the socket resource to the EventLoop after a previous `pause()`. + * + * ```php + * $socket->pause(); + * + * Loop::addTimer(1.0, function () use ($socket) { + * $socket->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::pause() + * @return void + */ + public function resume(); + + /** + * Shuts down this listening socket + * + * This will stop listening for new incoming connections on this socket. + * + * Calling this method more than once on the same instance is a NO-OP. + * + * @return void + */ + public function close(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SocketServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SocketServer.php new file mode 100644 index 0000000..973bbaf --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/SocketServer.php @@ -0,0 +1,93 @@ + array(), + 'tls' => array(), + 'unix' => array() + ); + + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== false) { + $scheme = \substr($uri, 0, $pos); + } + + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } else { + if (preg_match('#^(?:\w+://)?\d+$#', $uri)) { + throw new \InvalidArgumentException('Invalid URI given'); + } + + $server = new TcpServer(str_replace('tls://', '', $uri), $loop, $context['tcp']); + + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + + $this->server = $server; + + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use ($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (\Exception $error) use ($that) { + $that->emit('error', array($error)); + }); + } + + public function getAddress() + { + return $this->server->getAddress(); + } + + public function pause() + { + $this->server->pause(); + } + + public function resume() + { + $this->server->resume(); + } + + public function close() + { + $this->server->close(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/StreamEncryption.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/StreamEncryption.php new file mode 100644 index 0000000..8321b69 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/StreamEncryption.php @@ -0,0 +1,141 @@ +loop = $loop; + $this->server = $server; + + // support TLSv1.0+ by default and exclude legacy SSLv2/SSLv3. + // As of PHP 7.2+ the main crypto method constant includes all TLS versions. + // As of PHP 5.6+ the crypto method is a bitmask, so we explicitly include all TLS versions. + // For legacy PHP < 5.6 the crypto method is a single value only and this constant includes all TLS versions. + // @link https://3v4l.org/9PSST + if ($server) { + $this->method = \STREAM_CRYPTO_METHOD_TLS_SERVER; + + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_2_SERVER; // @codeCoverageIgnore + } + } else { + $this->method = \STREAM_CRYPTO_METHOD_TLS_CLIENT; + + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; // @codeCoverageIgnore + } + } + } + + public function enable(Connection $stream) + { + return $this->toggle($stream, true); + } + + public function toggle(Connection $stream, $toggle) + { + // pause actual stream instance to continue operation on raw stream socket + $stream->pause(); + + // TODO: add write() event to make sure we're not sending any excessive data + + // cancelling this leaves this stream in an inconsistent state… + $deferred = new Deferred(function () { + throw new \RuntimeException(); + }); + + // get actual stream socket from stream instance + $socket = $stream->stream; + + // get crypto method from context options or use global setting from constructor + $method = $this->method; + $context = \stream_context_get_options($socket); + if (isset($context['ssl']['crypto_method'])) { + $method = $context['ssl']['crypto_method']; + } + + $that = $this; + $toggleCrypto = function () use ($socket, $deferred, $toggle, $method, $that) { + $that->toggleCrypto($socket, $deferred, $toggle, $method); + }; + + $this->loop->addReadStream($socket, $toggleCrypto); + + if (!$this->server) { + $toggleCrypto(); + } + + $loop = $this->loop; + + return $deferred->promise()->then(function () use ($stream, $socket, $loop, $toggle) { + $loop->removeReadStream($socket); + + $stream->encryptionEnabled = $toggle; + $stream->resume(); + + return $stream; + }, function($error) use ($stream, $socket, $loop) { + $loop->removeReadStream($socket); + $stream->resume(); + throw $error; + }); + } + + public function toggleCrypto($socket, Deferred $deferred, $toggle, $method) + { + $error = null; + \set_error_handler(function ($_, $errstr) use (&$error) { + $error = \str_replace(array("\r", "\n"), ' ', $errstr); + + // remove useless function name from error message + if (($pos = \strpos($error, "): ")) !== false) { + $error = \substr($error, $pos + 3); + } + }); + + $result = \stream_socket_enable_crypto($socket, $toggle, $method); + + \restore_error_handler(); + + if (true === $result) { + $deferred->resolve(); + } else if (false === $result) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $d = $deferred; + $deferred = null; + + if (\feof($socket) || $error === null) { + // EOF or failed without error => connection closed during handshake + $d->reject(new \UnexpectedValueException( + 'Connection lost during TLS handshake', + \defined('SOCKET_ECONNRESET') ? \SOCKET_ECONNRESET : 0 + )); + } else { + // handshake failed with error message + $d->reject(new \UnexpectedValueException( + 'Unable to complete TLS handshake: ' . $error + )); + } + } else { + // need more data, will retry + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpConnector.php new file mode 100644 index 0000000..532533b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpConnector.php @@ -0,0 +1,123 @@ +loop = $loop ?: Loop::get(); + $this->context = $context; + } + + public function connect($uri) + { + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + } + + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid')); + } + + $ip = \trim($parts['host'], '[]'); + if (false === \filter_var($ip, \FILTER_VALIDATE_IP)) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $ip . '" does not contain a valid host IP')); + } + + // use context given in constructor + $context = array( + 'socket' => $this->context + ); + + // parse arguments from query component of URI + $args = array(); + if (isset($parts['query'])) { + \parse_str($parts['query'], $args); + } + + // If an original hostname has been given, use this for TLS setup. + // This can happen due to layers of nested connectors, such as a + // DnsConnector reporting its original hostname. + // These context options are here in case TLS is enabled later on this stream. + // If TLS is not enabled later, this doesn't hurt either. + if (isset($args['hostname'])) { + $context['ssl'] = array( + 'SNI_enabled' => true, + 'peer_name' => $args['hostname'] + ); + + // Legacy PHP < 5.6 ignores peer_name and requires legacy context options instead. + // The SNI_server_name context option has to be set here during construction, + // as legacy PHP ignores any values set later. + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID < 50600) { + $context['ssl'] += array( + 'SNI_server_name' => $args['hostname'], + 'CN_match' => $args['hostname'] + ); + } + // @codeCoverageIgnoreEnd + } + + // latest versions of PHP no longer accept any other URI components and + // HHVM fails to parse URIs with a query but no path, so let's simplify our URI here + $remote = 'tcp://' . $parts['host'] . ':' . $parts['port']; + + $stream = @\stream_socket_client( + $remote, + $errno, + $errstr, + 0, + \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT, + \stream_context_create($context) + ); + + if (false === $stream) { + return Promise\reject(new \RuntimeException( + \sprintf("Connection to %s failed: %s", $uri, $errstr), + $errno + )); + } + + // wait for connection + $loop = $this->loop; + return new Promise\Promise(function ($resolve, $reject) use ($loop, $stream, $uri) { + $loop->addWriteStream($stream, function ($stream) use ($loop, $resolve, $reject, $uri) { + $loop->removeWriteStream($stream); + + // The following hack looks like the only way to + // detect connection refused errors with PHP's stream sockets. + if (false === \stream_socket_get_name($stream, true)) { + \fclose($stream); + + $reject(new \RuntimeException('Connection to ' . $uri . ' failed: Connection refused')); + } else { + $resolve(new Connection($stream, $loop)); + } + }); + }, function () use ($loop, $stream, $uri) { + $loop->removeWriteStream($stream); + \fclose($stream); + + // @codeCoverageIgnoreStart + // legacy PHP 5.3 sometimes requires a second close call (see tests) + if (\PHP_VERSION_ID < 50400 && \is_resource($stream)) { + \fclose($stream); + } + // @codeCoverageIgnoreEnd + + throw new \RuntimeException('Connection to ' . $uri . ' cancelled during TCP/IP handshake'); + }); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpServer.php new file mode 100644 index 0000000..26eda8f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TcpServer.php @@ -0,0 +1,243 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class TcpServer extends EventEmitter implements ServerInterface +{ + private $master; + private $loop; + private $listening = false; + + /** + * Creates a plaintext TCP/IP socket server and starts listening on the given address + * + * This starts accepting new incoming connections on the given address. + * See also the `connection event` documented in the `ServerInterface` + * for more details. + * + * ```php + * $server = new React\Socket\TcpServer(8080); + * ``` + * + * As above, the `$uri` parameter can consist of only a port, in which case the + * server will default to listening on the localhost address `127.0.0.1`, + * which means it will not be reachable from outside of this system. + * + * In order to use a random port assignment, you can use the port `0`: + * + * ```php + * $server = new React\Socket\TcpServer(0); + * $address = $server->getAddress(); + * ``` + * + * In order to change the host the socket is listening on, you can provide an IP + * address through the first parameter provided to the constructor, optionally + * preceded by the `tcp://` scheme: + * + * ```php + * $server = new React\Socket\TcpServer('192.168.0.1:8080'); + * ``` + * + * If you want to listen on an IPv6 address, you MUST enclose the host in square + * brackets: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080'); + * ``` + * + * If the given URI is invalid, does not contain a port, any other scheme or if it + * contains a hostname, it will throw an `InvalidArgumentException`: + * + * ```php + * // throws InvalidArgumentException due to missing port + * $server = new React\Socket\TcpServer('127.0.0.1'); + * ``` + * + * If the given URI appears to be valid, but listening on it fails (such as if port + * is already in use or port below 1024 may require root access etc.), it will + * throw a `RuntimeException`: + * + * ```php + * $first = new React\Socket\TcpServer(8080); + * + * // throws RuntimeException because port is already in use + * $second = new React\Socket\TcpServer(8080); + * ``` + * + * Note that these error conditions may vary depending on your system and/or + * configuration. + * See the exception message and code for more details about the actual error + * condition. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) + * for the underlying stream socket resource like this: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080', null, array( + * 'backlog' => 200, + * 'so_reuseport' => true, + * 'ipv6_v6only' => true + * )); + * ``` + * + * Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * The `backlog` context option defaults to `511` unless given explicitly. + * + * @param string|int $uri + * @param ?LoopInterface $loop + * @param array $context + * @throws InvalidArgumentException if the listening address is invalid + * @throws RuntimeException if listening on this address fails (already in use etc.) + */ + public function __construct($uri, LoopInterface $loop = null, array $context = array()) + { + $this->loop = $loop ?: Loop::get(); + + // a single port has been given => assume localhost + if ((string)(int)$uri === (string)$uri) { + $uri = '127.0.0.1:' . $uri; + } + + // assume default scheme if none has been given + if (\strpos($uri, '://') === false) { + $uri = 'tcp://' . $uri; + } + + // parse_url() does not accept null ports (random port assignment) => manually remove + if (\substr($uri, -2) === ':0') { + $parts = \parse_url(\substr($uri, 0, -2)); + if ($parts) { + $parts['port'] = 0; + } + } else { + $parts = \parse_url($uri); + } + + // ensure URI contains TCP scheme, host and port + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + throw new \InvalidArgumentException('Invalid URI "' . $uri . '" given'); + } + + if (false === \filter_var(\trim($parts['host'], '[]'), \FILTER_VALIDATE_IP)) { + throw new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP'); + } + + $this->master = @\stream_socket_server( + $uri, + $errno, + $errstr, + \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, + \stream_context_create(array('socket' => $context + array('backlog' => 511))) + ); + if (false === $this->master) { + throw new \RuntimeException('Failed to listen on "' . $uri . '": ' . $errstr, $errno); + } + \stream_set_blocking($this->master, false); + + $this->resume(); + } + + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + + $address = \stream_socket_get_name($this->master, false); + + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); // @codeCoverageIgnore + } + + return 'tcp://' . $address; + } + + public function pause() + { + if (!$this->listening) { + return; + } + + $this->loop->removeReadStream($this->master); + $this->listening = false; + } + + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use ($that) { + $newSocket = @\stream_socket_accept($master, 0); + if (false === $newSocket) { + $that->emit('error', array(new \RuntimeException('Error accepting new connection'))); + + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = true; + } + + public function close() + { + if (!\is_resource($this->master)) { + return; + } + + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleConnection($socket) + { + $this->emit('connection', array( + new Connection($socket, $this->loop) + )); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TimeoutConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TimeoutConnector.php new file mode 100644 index 0000000..02cccee --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/TimeoutConnector.php @@ -0,0 +1,51 @@ +connector = $connector; + $this->timeout = $timeout; + $this->loop = $loop ?: Loop::get(); + } + + public function connect($uri) + { + return Timer\timeout($this->connector->connect($uri), $this->timeout, $this->loop)->then(null, self::handler($uri)); + } + + /** + * Creates a static rejection handler that reports a proper error message in case of a timeout. + * + * This uses a private static helper method to ensure this closure is not + * bound to this instance and the exception trace does not include a + * reference to this instance and its connector stack as a result. + * + * @param string $uri + * @return callable + */ + private static function handler($uri) + { + return function (\Exception $e) use ($uri) { + if ($e instanceof TimeoutException) { + throw new \RuntimeException( + 'Connection to ' . $uri . ' timed out after ' . $e->getTimeout() . ' seconds', + \defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 0 + ); + } + + throw $e; + }; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixConnector.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixConnector.php new file mode 100644 index 0000000..4cfb5a3 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixConnector.php @@ -0,0 +1,45 @@ +loop = $loop ?: Loop::get(); + } + + public function connect($path) + { + if (\strpos($path, '://') === false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $path . '" is invalid')); + } + + $resource = @\stream_socket_client($path, $errno, $errstr, 1.0); + + if (!$resource) { + return Promise\reject(new \RuntimeException('Unable to connect to unix domain socket "' . $path . '": ' . $errstr, $errno)); + } + + $connection = new Connection($resource, $this->loop); + $connection->unix = true; + + return Promise\resolve($connection); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixServer.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixServer.php new file mode 100644 index 0000000..a3dd8a1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/socket/src/UnixServer.php @@ -0,0 +1,148 @@ +loop = $loop ?: Loop::get(); + + if (\strpos($path, '://') === false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + throw new \InvalidArgumentException('Given URI "' . $path . '" is invalid'); + } + + $this->master = @\stream_socket_server( + $path, + $errno, + $errstr, + \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, + \stream_context_create(array('socket' => $context)) + ); + if (false === $this->master) { + // PHP does not seem to report errno/errstr for Unix domain sockets (UDS) right now. + // This only applies to UDS server sockets, see also https://3v4l.org/NAhpr. + // Parse PHP warning message containing unknown error, HHVM reports proper info at least. + if ($errno === 0 && $errstr === '') { + $error = \error_get_last(); + if (\preg_match('/\(([^\)]+)\)|\[(\d+)\]: (.*)/', $error['message'], $match)) { + $errstr = isset($match[3]) ? $match['3'] : $match[1]; + $errno = isset($match[2]) ? (int)$match[2] : 0; + } + } + + throw new \RuntimeException('Failed to listen on Unix domain socket "' . $path . '": ' . $errstr, $errno); + } + \stream_set_blocking($this->master, 0); + + $this->resume(); + } + + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + + return 'unix://' . \stream_socket_get_name($this->master, false); + } + + public function pause() + { + if (!$this->listening) { + return; + } + + $this->loop->removeReadStream($this->master); + $this->listening = false; + } + + public function resume() + { + if ($this->listening || !is_resource($this->master)) { + return; + } + + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use ($that) { + $newSocket = @\stream_socket_accept($master, 0); + if (false === $newSocket) { + $that->emit('error', array(new \RuntimeException('Error accepting new connection'))); + + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = true; + } + + public function close() + { + if (!\is_resource($this->master)) { + return; + } + + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + + /** @internal */ + public function handleConnection($socket) + { + $connection = new Connection($socket, $this->loop); + $connection->unix = true; + + $this->emit('connection', array( + $connection + )); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/CHANGELOG.md new file mode 100644 index 0000000..9bafba7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/CHANGELOG.md @@ -0,0 +1,435 @@ +# Changelog + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#159 by @clue) + + ```php + // old (still supported) + $stream = new ReadableResourceStream($resource, $loop); + $stream = new WritabeResourceStream($resource, $loop); + $stream = new DuplexResourceStream($resource, $loop); + + // new (using default loop) + $stream = new ReadableResourceStream($resource); + $stream = new WritabeResourceStream($resource); + $stream = new DuplexResourceStream($resource); + ``` + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config, run tests on PHP 8 and add full core team to the license. + (#153, #156 and #157 by @SimonFrings and #154 by @WyriHaximus) + +## 1.1.1 (2020-05-04) + +* Fix: Fix faulty write buffer behavior when sending large data chunks over TLS (Mac OS X only). + (#150 by @clue) + +* Minor code style improvements to fix phpstan analysis warnings and + add `.gitattributes` to exclude dev files from exports. + (#140 by @flow-control and #144 by @reedy) + +* Improve test suite to run tests on PHP 7.4 and simplify test matrix. + (#147 by @clue) + +## 1.1.0 (2019-01-01) + +* Improvement: Increase performance by optimizing global function and constant look ups. + (#137 by @WyriHaximus) + +* Travis: Test against PHP 7.3. + (#138 by @WyriHaximus) + +* Fix: Ignore empty reads. + (#139 by @WyriHaximus) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.7.7 release. + +## 0.7.7 (2018-01-19) + +* Improve test suite by fixing forward compatibility with upcoming EventLoop + releases, avoid risky tests and add test group to skip integration tests + relying on internet connection and apply appropriate test timeouts. + (#128, #131 and #132 by @clue) + +## 0.7.6 (2017-12-21) + +* Fix: Work around reading from unbuffered pipe stream in legacy PHP < 5.4.28 and PHP < 5.5.12 + (#126 by @clue) + +* Improve test suite by simplifying test bootstrapping logic via Composer and + test against PHP 7.2 + (#127 by @clue and #124 by @carusogabriel) + +## 0.7.5 (2017-11-20) + +* Fix: Igore excessive `fopen()` mode flags for `WritableResourceStream` + (#119 by @clue) + +* Fix: Fix forward compatibility with upcoming EventLoop releases + (#121 by @clue) + +* Restructure examples to ease getting started + (#123 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#122 by @gabriel-caruso and #120 by @clue) + +## 0.7.4 (2017-10-11) + +* Fix: Remove event listeners from `CompositeStream` once closed and + remove undocumented left-over `close` event argument + (#116 by @clue) + +* Minor documentation improvements: Fix wrong class name in example, + fix typos in README and + fix forward compatibility with upcoming EventLoop releases in example + (#113 by @docteurklein and #114 and #115 by @clue) + +* Improve test suite by running against Mac OS X on Travis + (#112 by @clue) + +## 0.7.3 (2017-08-05) + +* Improvement: Support Événement 3.0 a long side 2.0 and 1.0 + (#108 by @WyriHaximus) + +* Readme: Corrected loop initialization in usage example + (#109 by @pulyavin) + +* Travis: Lock linux distribution preventing future builds from breaking + (#110 by @clue) + +## 0.7.2 (2017-06-15) + +* Bug fix: WritableResourceStream: Close the underlying stream when closing the stream. + (#107 by @WyriHaximus) + +## 0.7.1 (2017-05-20) + +* Feature: Add optional `$writeChunkSize` parameter to limit maximum number of + bytes to write at once. + (#105 by @clue) + + ```php + $stream = new WritableResourceStream(STDOUT, $loop, null, 8192); + ``` + +* Ignore HHVM test failures for now until Travis tests work again + (#106 by @clue) + +## 0.7.0 (2017-05-04) + +* Removed / BC break: Remove deprecated and unneeded functionality + (#45, #87, #90, #91 and #93 by @clue) + + * Remove deprecated `Stream` class, use `DuplexResourceStream` instead + (#87 by @clue) + + * Remove public `$buffer` property, use new constructor parameters instead + (#91 by @clue) + + * Remove public `$stream` property from all resource streams + (#90 by @clue) + + * Remove undocumented and now unused `ReadableStream` and `WritableStream` + (#93 by @clue) + + * Remove `BufferedSink` + (#45 by @clue) + +* Feature / BC break: Simplify `ThroughStream` by using data callback instead of + inheritance. It is now a direct implementation of `DuplexStreamInterface`. + (#88 and #89 by @clue) + + ```php + $through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; + }); + $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + + $through->write(array(2, true)); + ``` + +* Feature / BC break: The `CompositeStream` starts closed if either side is + already closed and forwards pause to pipe source on first write attempt. + (#96 and #103 by @clue) + + If either side of the composite stream closes, it will also close the other + side. We now also ensure that if either side is already closed during + instantiation, it will also close the other side. + +* BC break: Mark all classes as `final` and + mark internal API as `private` to discourage inheritance + (#95 and #99 by @clue) + +* Feature / BC break: Only emit `error` event for fatal errors + (#92 by @clue) + + > The `error` event was previously also allowed to be emitted for non-fatal + errors, but our implementations actually only ever emitted this as a fatal + error and then closed the stream. + +* Feature: Explicitly allow custom events and exclude any semantics + (#97 by @clue) + +* Strict definition for event callback functions + (#101 by @clue) + +* Support legacy PHP 5.3 through PHP 7.1 and HHVM and improve usage documentation + (#100 and #102 by @clue) + +* Actually require all dependencies so this is self-contained and improve + forward compatibility with EventLoop v1.0 and v0.5 + (#94 and #98 by @clue) + +## 0.6.0 (2017-03-26) + +* Feature / Fix / BC break: Add `DuplexResourceStream` and deprecate `Stream` + (#85 by @clue) + + ```php + // old (does still work for BC reasons) + $stream = new Stream($connection, $loop); + + // new + $stream = new DuplexResourceStream($connection, $loop); + ``` + + Note that the `DuplexResourceStream` now rejects read-only or write-only + streams, so this may affect BC. If you want a read-only or write-only + resource, use `ReadableResourceStream` or `WritableResourceStream` instead of + `DuplexResourceStream`. + + > BC note: This class was previously called `Stream`. The `Stream` class still + exists for BC reasons and will be removed in future versions of this package. + +* Feature / BC break: Add `WritableResourceStream` (previously called `Buffer`) + (#84 by @clue) + + ```php + // old + $stream = new Buffer(STDOUT, $loop); + + // new + $stream = new WritableResourceStream(STDOUT, $loop); + ``` + +* Feature: Add `ReadableResourceStream` + (#83 by @clue) + + ```php + $stream = new ReadableResourceStream(STDIN, $loop); + ``` + +* Fix / BC Break: Enforce using non-blocking I/O + (#46 by @clue) + + > BC note: This is known to affect process pipes on Windows which do not + support non-blocking I/O and could thus block the whole EventLoop previously. + +* Feature / Fix / BC break: Consistent semantics for + `DuplexStreamInterface::end()` to ensure it SHOULD also end readable side + (#86 by @clue) + +* Fix: Do not use unbuffered reads on pipe streams for legacy PHP < 5.4 + (#80 by @clue) + +## 0.5.0 (2017-03-08) + +* Feature / BC break: Consistent `end` event semantics (EOF) + (#70 by @clue) + + The `end` event will now only be emitted for a *successful* end, not if the + stream closes due to an unrecoverable `error` event or if you call `close()` + explicitly. + If you want to detect when the stream closes (terminates), use the `close` + event instead. + +* BC break: Remove custom (undocumented) `full-drain` event from `Buffer` + (#63 and #68 by @clue) + + > The `full-drain` event was undocumented and mostly used internally. + Relying on this event has attracted some low-quality code in the past, so + we've removed this from the public API in order to work out a better + solution instead. + If you want to detect when the buffer finishes flushing data to the stream, + you may want to look into its `end()` method or the `close` event instead. + +* Feature / BC break: Consistent event semantics and documentation, + explicitly state *when* events will be emitted and *which* arguments they + receive. + (#73 and #69 by @clue) + + The documentation now explicitly defines each event and its arguments. + Custom events and event arguments are still supported. + Most notably, all defined events only receive inherently required event + arguments and no longer transmit the instance they are emitted on for + consistency and performance reasons. + + ```php + // old (inconsistent and not supported by all implementations) + $stream->on('data', function ($data, $stream) { + // process $data + }); + + // new (consistent throughout the whole ecosystem) + $stream->on('data', function ($data) use ($stream) { + // process $data + }); + ``` + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature / BC break: Consistent method semantics and documentation + (#72 by @clue) + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature: Consistent `pipe()` semantics for closed and closing streams + (#71 from @clue) + + The source stream will now always be paused via `pause()` when the + destination stream closes. Also, properly stop piping if the source + stream closes and remove all event forwarding. + +* Improve test suite by adding PHPUnit to `require-dev` and improving coverage. + (#74 and #75 by @clue, #66 by @nawarian) + +## 0.4.6 (2017-01-25) + +* Feature: The `Buffer` can now be injected into the `Stream` (or be used standalone) + (#62 by @clue) + +* Fix: Forward `close` event only once for `CompositeStream` and `ThroughStream` + (#60 by @clue) + +* Fix: Consistent `close` event behavior for `Buffer` + (#61 by @clue) + +## 0.4.5 (2016-11-13) + +* Feature: Support setting read buffer size to `null` (infinite) + (#42 by @clue) + +* Fix: Do not emit `full-drain` event if `Buffer` is closed during `drain` event + (#55 by @clue) + +* Vastly improved performance by factor of 10x to 20x. + Raise default buffer sizes to 64 KiB and simplify and improve error handling + and unneeded function calls. + (#53, #55, #56 by @clue) + +## 0.4.4 (2016-08-22) + +* Bug fix: Emit `error` event and close `Stream` when accessing the underlying + stream resource fails with a permanent error. + (#52 and #40 by @clue, #25 by @lysenkobv) + +* Bug fix: Do not emit empty `data` event if nothing has been read (stream reached EOF) + (#39 by @clue) + +* Bug fix: Ignore empty writes to `Buffer` + (#51 by @clue) + +* Add benchmarking script to measure throughput in CI + (#41 by @clue) + +## 0.4.3 (2015-10-07) + +* Bug fix: Read buffer to 0 fixes error with libevent and large quantity of I/O (@mbonneau) +* Bug fix: No double-write during drain call (@arnaud-lb) +* Bug fix: Support HHVM (@clue) +* Adjust compatibility to 5.3 (@clue) + +## 0.4.2 (2014-09-09) + +* Added DuplexStreamInterface +* Stream sets stream resources to non-blocking +* Fixed potential race condition in pipe + +## 0.4.1 (2014-04-13) + +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: [Stream] Fixed 100% CPU spike from non-empty write buffer on closed stream + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.3 (2013-07-08) + +* Bug fix: [Stream] Correctly detect closed connections + +## 0.3.2 (2013-05-10) + +* Bug fix: [Stream] Make sure CompositeStream is closed properly + +## 0.3.1 (2013-04-21) + +* Bug fix: [Stream] Allow any `ReadableStreamInterface` on `BufferedSink::createPromise()` + +## 0.3.0 (2013-04-14) + +* Feature: [Stream] Factory method for BufferedSink + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.5 (2012-11-26) + +* Feature: Make BufferedSink trigger progress events on the promise (@jsor) + +## 0.2.4 (2012-11-18) + +* Feature: Added ThroughStream, CompositeStream, ReadableStream and WritableStream +* Feature: Added BufferedSink + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Version bump + +## 0.2.1 (2012-10-14) + +* Bug fix: Check for EOF in `Buffer::write()` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Bug fix: Testing and functional against PHP >= 5.3.3 and <= 5.3.8 + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/LICENSE new file mode 100644 index 0000000..d6f8901 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/README.md new file mode 100644 index 0000000..460f51a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/README.md @@ -0,0 +1,1248 @@ +# Stream + +[![CI status](https://github.com/reactphp/stream/workflows/CI/badge.svg)](https://github.com/reactphp/stream/actions) + +Event-driven readable and writable streams for non-blocking I/O in [ReactPHP](https://reactphp.org/). + +In order to make the [EventLoop](https://github.com/reactphp/event-loop) +easier to use, this component introduces the powerful concept of "streams". +Streams allow you to efficiently process huge amounts of data (such as a multi +Gigabyte file download) in small chunks without having to store everything in +memory at once. +They are very similar to the streams found in PHP itself, +but have an interface more suited for async, non-blocking I/O. + +**Table of contents** + +* [Stream usage](#stream-usage) + * [ReadableStreamInterface](#readablestreaminterface) + * [data event](#data-event) + * [end event](#end-event) + * [error event](#error-event) + * [close event](#close-event) + * [isReadable()](#isreadable) + * [pause()](#pause) + * [resume()](#resume) + * [pipe()](#pipe) + * [close()](#close) + * [WritableStreamInterface](#writablestreaminterface) + * [drain event](#drain-event) + * [pipe event](#pipe-event) + * [error event](#error-event-1) + * [close event](#close-event-1) + * [isWritable()](#iswritable) + * [write()](#write) + * [end()](#end) + * [close()](#close-1) + * [DuplexStreamInterface](#duplexstreaminterface) +* [Creating streams](#creating-streams) + * [ReadableResourceStream](#readableresourcestream) + * [WritableResourceStream](#writableresourcestream) + * [DuplexResourceStream](#duplexresourcestream) + * [ThroughStream](#throughstream) + * [CompositeStream](#compositestream) +* [Usage](#usage) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Stream usage + +ReactPHP uses the concept of "streams" throughout its ecosystem to provide a +consistent higher-level abstraction for processing streams of arbitrary data +contents and size. +While a stream itself is a quite low-level concept, it can be used as a powerful +abstraction to build higher-level components and protocols on top. + +If you're new to this concept, it helps to think of them as a water pipe: +You can consume water from a source or you can produce water and forward (pipe) +it to any destination (sink). + +Similarly, streams can either be + +* readable (such as `STDIN` terminal input) or +* writable (such as `STDOUT` terminal output) or +* duplex (both readable *and* writable, such as a TCP/IP connection) + +Accordingly, this package defines the following three interfaces + +* [`ReadableStreamInterface`](#readablestreaminterface) +* [`WritableStreamInterface`](#writablestreaminterface) +* [`DuplexStreamInterface`](#duplexstreaminterface) + +### ReadableStreamInterface + +The `ReadableStreamInterface` is responsible for providing an interface for +read-only streams and the readable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### data event + +The `data` event will be emitted whenever some data was read/received +from this source stream. +The event receives a single mixed argument for incoming data. + +```php +$stream->on('data', function ($data) { + echo $data; +}); +``` + +This event MAY be emitted any number of times, which may be zero times if +this stream does not send any data at all. +It SHOULD not be emitted after an `end` or `close` event. + +The given `$data` argument may be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit the raw (binary) payload data that is received over the wire as +chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end event + +The `end` event will be emitted once the source stream has successfully +reached the end of the stream (EOF). + +```php +$stream->on('end', function () { + echo 'END'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +a successful end was detected. +It SHOULD NOT be emitted after a previous `end` or `close` event. +It MUST NOT be emitted if the stream closes due to a non-successful +end, such as after a previous `error` event. + +After the stream is ended, it MUST switch to non-readable mode, +see also `isReadable()`. + +This event will only be emitted if the *end* was reached successfully, +not if the stream was interrupted by an unrecoverable error or explicitly +closed. Not all streams know this concept of a "successful end". +Many use-cases involve detecting when the stream closes (terminates) +instead, in this case you should use the `close` event. +After the stream emits an `end` event, it SHOULD usually be followed by a +`close` event. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit this event if either the remote side closes the connection or +a file handle was successfully read until reaching its end (EOF). + +Note that this event should not be confused with the `end()` method. +This event defines a successful end *reading* from a source stream, while +the `end()` method defines *writing* a successful end to a destination +stream. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to read from this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$server->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error or after an unexpected `data` or premature +`end` event. +It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-readable mode, see +also `close()` and `isReadable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and do not make assumption about data +boundaries (such as unexpected `data` or premature `end` events). +In other words, many lower-level protocols (such as TCP/IP) may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-readable mode, +see also `isReadable()`. + +Unlike the `end` event, this event SHOULD be emitted whenever the stream +closes, irrespective of whether this happens implicitly due to an +unrecoverable error or explicitly when either side closes the stream. +If you only want to detect a *successful* end, you should use the `end` +event instead. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after reading a *successful* `end` +event or after a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this event should not be confused with the `end` event. + +#### isReadable() + +The `isReadable(): bool` method can be used to +check whether this stream is in a readable state (not closed already). + +This method can be used to check if the stream still accepts incoming +data events or if it is ended or closed already. +Once the stream is non-readable, no further `data` or `end` events SHOULD +be emitted. + +```php +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +A successfully opened stream always MUST start in readable mode. + +Once the stream ends or closes, it MUST switch to non-readable mode. +This can happen any time, explicitly through `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-readable mode, it MUST NOT transition +back to readable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `isWritable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### pause() + +The `pause(): void` method can be used to +pause reading incoming data events. + +Removes the data source file descriptor from the event loop. This +allows you to throttle incoming data. + +Unless otherwise noted, a successfully opened stream SHOULD NOT start +in paused state. + +Once the stream is paused, no futher `data` or `end` events SHOULD +be emitted. + +```php +$stream->pause(); + +$stream->on('data', assertShouldNeverCalled()); +$stream->on('end', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +stream MAY continue emitting `data` events. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. + +See also `resume()`. + +#### resume() + +The `resume(): void` method can be used to +resume reading incoming data events. + +Re-attach the data source after a previous `pause()`. + +```php +$stream->pause(); + +Loop::addTimer(1.0, function () use ($stream) { + $stream->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + +See also `pause()`. + +#### pipe() + +The `pipe(WritableStreamInterface $dest, array $options = [])` method can be used to +pipe all the data from this readable source into the given writable destination. + +Automatically sends all incoming data to the destination. +Automatically throttles the source based on what the destination can handle. + +```php +$source->pipe($dest); +``` + +Similarly, you can also pipe an instance implementing `DuplexStreamInterface` +into itself in order to write back all the data that is received. +This may be a useful feature for a TCP/IP echo service: + +```php +$connection->pipe($connection); +``` + +This method returns the destination stream as-is, which can be used to +set up chains of piped streams: + +```php +$source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); +``` + +By default, this will call `end()` on the destination stream once the +source stream emits an `end` event. This can be disabled like this: + +```php +$source->pipe($dest, array('end' => false)); +``` + +Note that this only applies to the `end` event. +If an `error` or explicit `close` event happens on the source stream, +you'll have to manually close the destination stream: + +```php +$source->pipe($dest); +$source->on('close', function () use ($dest) { + $dest->end('BYE!'); +}); +``` + +If the source stream is not readable (closed state), then this is a NO-OP. + +```php +$source->close(); +$source->pipe($dest); // NO-OP +``` + +If the destinantion stream is not writable (closed state), then this will simply +throttle (pause) the source stream: + +```php +$dest->close(); +$source->pipe($dest); // calls $source->pause() +``` + +Similarly, if the destination stream is closed while the pipe is still +active, it will also throttle (pause) the source stream: + +```php +$source->pipe($dest); +$dest->close(); // calls $source->pause() +``` + +Once the pipe is set up successfully, the destination stream MUST emit +a `pipe` event with this source stream an event argument. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to (forcefully) close the stream. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-readable +mode, see also `isReadable()`. +This means that no further `data` or `end` events SHOULD be emitted. + +```php +$stream->close(); +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this method should not be confused with the `end()` method. + +### WritableStreamInterface + +The `WritableStreamInterface` is responsible for providing an interface for +write-only streams and the writable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### drain event + +The `drain` event will be emitted whenever the write buffer became full +previously and is now ready to accept more data. + +```php +$stream->on('drain', function () use ($stream) { + echo 'Stream is now ready to accept more data'; +}); +``` + +This event SHOULD be emitted once every time the buffer became full +previously and is now ready to accept more data. +In other words, this event MAY be emitted any number of times, which may +be zero times if the buffer never became full in the first place. +This event SHOULD NOT be emitted if the buffer has not become full +previously. + +This event is mostly used internally, see also `write()` for more details. + +#### pipe event + +The `pipe` event will be emitted whenever a readable stream is `pipe()`d +into this stream. +The event receives a single `ReadableStreamInterface` argument for the +source stream. + +```php +$stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + echo 'Now receiving piped data'; + + // explicitly close target if source emits an error + $source->on('error', function () use ($stream) { + $stream->close(); + }); +}); + +$source->pipe($stream); +``` + +This event MUST be emitted once for each readable stream that is +successfully piped into this destination stream. +In other words, this event MAY be emitted any number of times, which may +be zero times if no stream is ever piped into this stream. +This event MUST NOT be emitted if either the source is not readable +(closed already) or this destination is not writable (closed already). + +This event is mostly used internally, see also `pipe()` for more details. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to write to this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$stream->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error. +It SHOULD NOT be emitted after a previous `error` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-writable mode, see +also `close()` and `isWritable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-writable mode, +see also `isWritable()`. + +This event SHOULD be emitted whenever the stream closes, irrespective of +whether this happens implicitly due to an unrecoverable error or +explicitly when either side closes the stream. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after flushing the buffer from +the `end()` method, after receiving a *successful* `end` event or after +a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. +Note that this event should not be confused with the `end` event. + +#### isWritable() + +The `isWritable(): bool` method can be used to +check whether this stream is in a writable state (not closed already). + +This method can be used to check if the stream still accepts writing +any data or if it is ended or closed already. +Writing any data to a non-writable stream is a NO-OP: + +```php +assert($stream->isWritable() === false); + +$stream->write('end'); // NO-OP +$stream->end('end'); // NO-OP +``` + +A successfully opened stream always MUST start in writable mode. + +Once the stream ends or closes, it MUST switch to non-writable mode. +This can happen any time, explicitly through `end()` or `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-writable mode, it MUST NOT transition +back to writable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `isReadable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### write() + +The `write(mixed $data): bool` method can be used to +write some data into the stream. + +A successful write MUST be confirmed with a boolean `true`, which means +that either the data was written (flushed) immediately or is buffered and +scheduled for a future write. Note that this interface gives you no +control over explicitly flushing the buffered data, as finding the +appropriate time for this is beyond the scope of this interface and left +up to the implementation of this interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +If a stream cannot handle writing (or flushing) the data, it SHOULD emit +an `error` event and MAY `close()` the stream if it can not recover from +this error. + +If the internal buffer is full after adding `$data`, then `write()` +SHOULD return `false`, indicating that the caller should stop sending +data until the buffer drains. +The stream SHOULD send a `drain` event once the buffer is ready to accept +more data. + +Similarly, if the the stream is not writable (already in a closed state) +it MUST NOT process the given `$data` and SHOULD return `false`, +indicating that the caller should stop sending data. + +The given `$data` argument MAY be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will only accept the raw (binary) payload data that is transferred over +the wire as chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end() + +The `end(mixed $data = null): void` method can be used to +successfully end the stream (after optionally sending some final data). + +This method can be used to successfully end the stream, i.e. close +the stream after sending out all data that is currently buffered. + +```php +$stream->write('hello'); +$stream->write('world'); +$stream->end(); +``` + +If there's no data currently buffered and nothing to be flushed, then +this method MAY `close()` the stream immediately. + +If there's still data in the buffer that needs to be flushed first, then +this method SHOULD try to write out this data and only then `close()` +the stream. +Once the stream is closed, it SHOULD emit a `close` event. + +Note that this interface gives you no control over explicitly flushing +the buffered data, as finding the appropriate time for this is beyond the +scope of this interface and left up to the implementation of this +interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +You can optionally pass some final data that is written to the stream +before ending the stream. If a non-`null` value is given as `$data`, then +this method will behave just like calling `write($data)` before ending +with no data. + +```php +// shorter version +$stream->end('bye'); + +// same as longer version +$stream->write('bye'); +$stream->end(); +``` + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->end(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +If this stream is a `DuplexStreamInterface`, calling this method SHOULD +also end its readable side, unless the stream supports half-open mode. +In other words, after calling this method, these streams SHOULD switch +into non-writable AND non-readable mode, see also `isReadable()`. +This implies that in this case, the stream SHOULD NOT emit any `data` +or `end` events anymore. +Streams MAY choose to use the `pause()` method logic for this, but +special care may have to be taken to ensure a following call to the +`resume()` method SHOULD NOT continue emitting readable events. + +Note that this method should not be confused with the `close()` method. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to forcefully close the stream, i.e. close +the stream without waiting for any buffered data to be flushed. +If there's still data in the buffer, this data SHOULD be discarded. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->close(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +Note that this method should not be confused with the `end()` method. +Unlike the `end()` method, this method does not take care of any existing +buffers and simply discards any buffer contents. +Likewise, this method may also be called after calling `end()` on a +stream in order to stop waiting for the stream to flush its final data. + +```php +$stream->end(); +Loop::addTimer(1.0, function () use ($stream) { + $stream->close(); +}); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. + +### DuplexStreamInterface + +The `DuplexStreamInterface` is responsible for providing an interface for +duplex streams (both readable and writable). + +It builds on top of the existing interfaces for readable and writable streams +and follows the exact same method and event semantics. +If you're new to this concept, you should look into the +`ReadableStreamInterface` and `WritableStreamInterface` first. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to the same events defined +on the `ReadbleStreamInterface` and `WritableStreamInterface`. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +See also [`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) for more details. + +## Creating streams + +ReactPHP uses the concept of "streams" throughout its ecosystem, so that +many higher-level consumers of this package only deal with +[stream usage](#stream-usage). +This implies that stream instances are most often created within some +higher-level components and many consumers never actually have to deal with +creating a stream instance. + +* Use [react/socket](https://github.com/reactphp/socket) + if you want to accept incoming or establish outgoing plaintext TCP/IP or + secure TLS socket connection streams. +* Use [react/http](https://github.com/reactphp/http) + if you want to receive an incoming HTTP request body streams. +* Use [react/child-process](https://github.com/reactphp/child-process) + if you want to communicate with child processes via process pipes such as + STDIN, STDOUT, STDERR etc. +* Use experimental [react/filesystem](https://github.com/reactphp/filesystem) + if you want to read from / write to the filesystem. +* See also the last chapter for [more real-world applications](#more). + +However, if you are writing a lower-level component or want to create a stream +instance from a stream resource, then the following chapter is for you. + +> Note that the following examples use `fopen()` and `stream_socket_client()` + for illustration purposes only. + These functions SHOULD NOT be used in a truly async program because each call + may take several seconds to complete and would block the EventLoop otherwise. + Additionally, the `fopen()` call will return a file handle on some platforms + which may or may not be supported by all EventLoop implementations. + As an alternative, you may want to use higher-level libraries listed above. + +### ReadableResourceStream + +The `ReadableResourceStream` is a concrete implementation of the +[`ReadableStreamInterface`](#readablestreaminterface) for PHP's stream resources. + +This can be used to represent a read-only resource like a file stream opened in +readable mode or a stream such as `STDIN`: + +```php +$stream = new ReadableResourceStream(STDIN); +$stream->on('data', function ($chunk) { + echo $chunk; +}); +$stream->on('end', function () { + echo 'END'; +}); +``` + +See also [`ReadableStreamInterface`](#readablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened in reading mode (e.g. `fopen()` mode `r`). +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new ReadableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDIN etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new ReadableResourceStream(STDIN); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$stream = new ReadableResourceStream(STDIN, null, 8192); +``` + +> PHP bug warning: If the PHP process has explicitly been started without a + `STDIN` stream, then trying to read from `STDIN` may return data from + another stream resource. This does not happen if you start this with an empty + stream like `php test.php < /dev/null` instead of `php test.php <&-`. + See [#81](https://github.com/reactphp/stream/issues/81) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### WritableResourceStream + +The `WritableResourceStream` is a concrete implementation of the +[`WritableStreamInterface`](#writablestreaminterface) for PHP's stream resources. + +This can be used to represent a write-only resource like a file stream opened in +writable mode or a stream such as `STDOUT` or `STDERR`: + +```php +$stream = new WritableResourceStream(STDOUT); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`WritableStreamInterface`](#writablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new WritableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new WritableResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $writeBufferSoftLimit` parameter that controls +this maximum buffer size in bytes. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +```php +$stream = new WritableResourceStream(STDOUT, null, 8192); +``` + +This class takes an optional `int|null $writeChunkSize` parameter that controls +this maximum buffer size in bytes to write at once to the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be written +at once to the underlying stream resource. Note that the actual number +of bytes written may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "write everything available" to the +underlying stream resource. + +```php +$stream = new WritableResourceStream(STDOUT, null, null, 8192); +``` + +See also [`write()`](#write) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### DuplexResourceStream + +The `DuplexResourceStream` is a concrete implementation of the +[`DuplexStreamInterface`](#duplexstreaminterface) for PHP's stream resources. + +This can be used to represent a read-and-write resource like a file stream opened +in read and write mode mode or a stream such as a TCP/IP connection: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`DuplexStreamInterface`](#duplexstreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for reading *and* writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new DuplexResourceStream(false); +``` + +See also the [`ReadableResourceStream`](#readableresourcestream) for read-only +and the [`WritableResourceStream`](#writableresourcestream) for write-only +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new DuplexResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn, null, 8192); +``` + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes another optional `WritableStreamInterface|null $buffer` parameter +that controls this write behavior of this stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +If you want to change the write buffer soft limit, you can pass an instance of +[`WritableResourceStream`](#writableresourcestream) like this: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$buffer = new WritableResourceStream($conn, null, 8192); +$stream = new DuplexResourceStream($conn, null, null, $buffer); +``` + +See also [`WritableResourceStream`](#writableresourcestream) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### ThroughStream + +The `ThroughStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and will simply pass any data +you write to it through to its readable end. + +```php +$through = new ThroughStream(); +$through->on('data', $this->expectCallableOnceWith('hello')); + +$through->write('hello'); +``` + +Similarly, the [`end()` method](#end) will end the stream and emit an +[`end` event](#end-event) and then [`close()`](#close-1) the stream. +The [`close()` method](#close-1) will close the stream and emit a +[`close` event](#close-event). +Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + +```php +$through = new ThroughStream(); +$source->pipe($through)->pipe($dest); +``` + +Optionally, its constructor accepts any callable function which will then be +used to *filter* any data written to it. This function receives a single data +argument as passed to the writable side and must return the data as it will be +passed to its readable end: + +```php +$through = new ThroughStream('strtoupper'); +$source->pipe($through)->pipe($dest); +``` + +Note that this class makes no assumptions about any data types. This can be +used to convert data, for example for transforming any structured data into +a newline-delimited JSON (NDJSON) stream like this: + +```php +$through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; +}); +$through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + +$through->write(array(2, true)); +``` + +The callback function is allowed to throw an `Exception`. In this case, +the stream will emit an `error` event and then [`close()`](#close-1) the stream. + +```php +$through = new ThroughStream(function ($data) { + if (!is_string($data)) { + throw new \UnexpectedValueException('Only strings allowed'); + } + return $data; +}); +$through->on('error', $this->expectCallableOnce())); +$through->on('close', $this->expectCallableOnce())); +$through->on('data', $this->expectCallableNever())); + +$through->write(2); +``` + +### CompositeStream + +The `CompositeStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and can be used to create a +single duplex stream from two individual streams implementing +[`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) respectively. + +This is useful for some APIs which may require a single +[`DuplexStreamInterface`](#duplexstreaminterface) or simply because it's often +more convenient to work with a single stream instance like this: + +```php +$stdin = new ReadableResourceStream(STDIN); +$stdout = new WritableResourceStream(STDOUT); + +$stdio = new CompositeStream($stdin, $stdout); + +$stdio->on('data', function ($chunk) use ($stdio) { + $stdio->write('You said: ' . $chunk); +}); +``` + +This is a well-behaving stream which forwards all stream events from the +underlying streams and forwards all streams calls to the underlying streams. + +If you `write()` to the duplex stream, it will simply `write()` to the +writable side and return its status. + +If you `end()` the duplex stream, it will `end()` the writable side and will +`pause()` the readable side. + +If you `close()` the duplex stream, both input streams will be closed. +If either of the two input streams emits a `close` event, the duplex stream +will also close. +If either of the two input streams is already closed while constructing the +duplex stream, it will `close()` the other side and return a closed stream. + +## Usage + +The following example can be used to pipe the contents of a source file into +a destination file without having to ever read the whole file into memory: + +```php +$source = new React\Stream\ReadableResourceStream(fopen('source.txt', 'r')); +$dest = new React\Stream\WritableResourceStream(fopen('destination.txt', 'w')); + +$source->pipe($dest); +``` + +> Note that this example uses `fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also [creating streams](#creating-streams) for more sophisticated + examples. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +$ composer require react/stream:^1.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use PHP 7+* for this project due to its vast +performance improvements. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +$ composer install +``` + +To run the test suite, go to the project root and run: + +```bash +$ php vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +$ php vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See [creating streams](#creating-streams) for more information on how streams + are created in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/stream/dependents) + for a list of packages that use streams in real-world applications. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/composer.json new file mode 100644 index 0000000..b235f5a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/composer.json @@ -0,0 +1,47 @@ +{ + "name": "react/stream", + "description": "Event-driven readable and writable streams for non-blocking I/O in ReactPHP", + "keywords": ["event-driven", "readable", "writable", "stream", "non-blocking", "io", "pipe", "ReactPHP"], + "license": "MIT", + "authors": [ + { + "name": "Christian Lück", + "homepage": "https://clue.engineering/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https://wyrihaximus.net/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https://sorgalla.com/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https://cboden.dev/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.8", + "react/event-loop": "^1.2", + "evenement/evenement": "^3.0 || ^2.0 || ^1.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.3 || ^5.7 || ^4.8.35", + "clue/stream-filter": "~1.2" + }, + "autoload": { + "psr-4": { + "React\\Stream\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "React\\Tests\\Stream\\": "tests" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/CompositeStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/CompositeStream.php new file mode 100644 index 0000000..dde091d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/CompositeStream.php @@ -0,0 +1,83 @@ +readable = $readable; + $this->writable = $writable; + + if (!$readable->isReadable() || !$writable->isWritable()) { + $this->close(); + return; + } + + Util::forwardEvents($this->readable, $this, array('data', 'end', 'error')); + Util::forwardEvents($this->writable, $this, array('drain', 'error', 'pipe')); + + $this->readable->on('close', array($this, 'close')); + $this->writable->on('close', array($this, 'close')); + } + + public function isReadable() + { + return $this->readable->isReadable(); + } + + public function pause() + { + $this->readable->pause(); + } + + public function resume() + { + if (!$this->writable->isWritable()) { + return; + } + + $this->readable->resume(); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function isWritable() + { + return $this->writable->isWritable(); + } + + public function write($data) + { + return $this->writable->write($data); + } + + public function end($data = null) + { + $this->readable->pause(); + $this->writable->end($data); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + $this->readable->close(); + $this->writable->close(); + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexResourceStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexResourceStream.php new file mode 100644 index 0000000..c3163c6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexResourceStream.php @@ -0,0 +1,227 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + + if ($buffer === null) { + $buffer = new WritableResourceStream($stream, $loop); + } + + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = ($readChunkSize === null) ? 65536 : (int)$readChunkSize; + $this->buffer = $buffer; + + $that = $this; + + $this->buffer->on('error', function ($error) use ($that) { + $that->emit('error', array($error)); + }); + + $this->buffer->on('close', array($this, 'close')); + + $this->buffer->on('drain', function () use ($that) { + $that->emit('drain'); + }); + + $this->resume(); + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = false; + } + } + + public function resume() + { + if (!$this->listening && $this->readable) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = true; + } + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + return $this->buffer->write($data); + } + + public function close() + { + if (!$this->writable && !$this->closing) { + return; + } + + $this->closing = false; + + $this->readable = false; + $this->writable = false; + + $this->emit('close'); + $this->pause(); + $this->buffer->close(); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + public function end($data = null) + { + if (!$this->writable) { + return; + } + + $this->closing = true; + + $this->readable = false; + $this->writable = false; + $this->pause(); + + $this->buffer->end($data); + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + /** @internal */ + public function handleData($stream) + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) { + $error = new \ErrorException( + $errstr, + 0, + $errno, + $errfile, + $errline + ); + }); + + $data = \stream_get_contents($stream, $this->bufferSize); + + \restore_error_handler(); + + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) { + $meta = \stream_get_meta_data($resource); + + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return true; + } + } + return false; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexStreamInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexStreamInterface.php new file mode 100644 index 0000000..631ce31 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/DuplexStreamInterface.php @@ -0,0 +1,39 @@ + Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see ReadableStreamInterface + * @see WritableStreamInterface + */ +interface DuplexStreamInterface extends ReadableStreamInterface, WritableStreamInterface +{ +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableResourceStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableResourceStream.php new file mode 100644 index 0000000..1b0b08c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableResourceStream.php @@ -0,0 +1,179 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = ($readChunkSize === null) ? 65536 : (int)$readChunkSize; + + $this->resume(); + } + + public function isReadable() + { + return !$this->closed; + } + + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = false; + } + } + + public function resume() + { + if (!$this->listening && !$this->closed) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = true; + } + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->closed = true; + + $this->emit('close'); + $this->pause(); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + /** @internal */ + public function handleData() + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use (&$error) { + $error = new \ErrorException( + $errstr, + 0, + $errno, + $errfile, + $errline + ); + }); + + $data = \stream_get_contents($this->stream, $this->bufferSize); + + \restore_error_handler(); + + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || (\PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512)) { + $meta = \stream_get_meta_data($resource); + + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return true; + } + } + return false; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableStreamInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableStreamInterface.php new file mode 100644 index 0000000..fa3d59c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ReadableStreamInterface.php @@ -0,0 +1,362 @@ +on('data', function ($data) { + * echo $data; + * }); + * ``` + * + * This event MAY be emitted any number of times, which may be zero times if + * this stream does not send any data at all. + * It SHOULD not be emitted after an `end` or `close` event. + * + * The given `$data` argument may be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit the raw (binary) payload data that is received over the wire as + * chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * end event: + * The `end` event will be emitted once the source stream has successfully + * reached the end of the stream (EOF). + * + * ```php + * $stream->on('end', function () { + * echo 'END'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * a successful end was detected. + * It SHOULD NOT be emitted after a previous `end` or `close` event. + * It MUST NOT be emitted if the stream closes due to a non-successful + * end, such as after a previous `error` event. + * + * After the stream is ended, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * This event will only be emitted if the *end* was reached successfully, + * not if the stream was interrupted by an unrecoverable error or explicitly + * closed. Not all streams know this concept of a "successful end". + * Many use-cases involve detecting when the stream closes (terminates) + * instead, in this case you should use the `close` event. + * After the stream emits an `end` event, it SHOULD usually be followed by a + * `close` event. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit this event if either the remote side closes the connection or + * a file handle was successfully read until reaching its end (EOF). + * + * Note that this event should not be confused with the `end()` method. + * This event defines a successful end *reading* from a source stream, while + * the `end()` method defines *writing* a successful end to a destination + * stream. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to read from this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error or after an unexpected `data` or premature + * `end` event. + * It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-readable mode, see + * also `close()` and `isReadable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and do not make assumption about data + * boundaries (such as unexpected `data` or premature `end` events). + * In other words, many lower-level protocols (such as TCP/IP) may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * Unlike the `end` event, this event SHOULD be emitted whenever the stream + * closes, irrespective of whether this happens implicitly due to an + * unrecoverable error or explicitly when either side closes the stream. + * If you only want to detect a *successful* end, you should use the `end` + * event instead. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after reading a *successful* `end` + * event or after a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + */ +interface ReadableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a readable state (not closed already). + * + * This method can be used to check if the stream still accepts incoming + * data events or if it is ended or closed already. + * Once the stream is non-readable, no further `data` or `end` events SHOULD + * be emitted. + * + * ```php + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * A successfully opened stream always MUST start in readable mode. + * + * Once the stream ends or closes, it MUST switch to non-readable mode. + * This can happen any time, explicitly through `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-readable mode, it MUST NOT transition + * back to readable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `isWritable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isReadable(); + + /** + * Pauses reading incoming data events. + * + * Removes the data source file descriptor from the event loop. This + * allows you to throttle incoming data. + * + * Unless otherwise noted, a successfully opened stream SHOULD NOT start + * in paused state. + * + * Once the stream is paused, no futher `data` or `end` events SHOULD + * be emitted. + * + * ```php + * $stream->pause(); + * + * $stream->on('data', assertShouldNeverCalled()); + * $stream->on('end', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * stream MAY continue emitting `data` events. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * + * @see self::resume() + * @return void + */ + public function pause(); + + /** + * Resumes reading incoming data events. + * + * Re-attach the data source after a previous `pause()`. + * + * ```php + * $stream->pause(); + * + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * + * @see self::pause() + * @return void + */ + public function resume(); + + /** + * Pipes all the data from this readable source into the given writable destination. + * + * Automatically sends all incoming data to the destination. + * Automatically throttles the source based on what the destination can handle. + * + * ```php + * $source->pipe($dest); + * ``` + * + * Similarly, you can also pipe an instance implementing `DuplexStreamInterface` + * into itself in order to write back all the data that is received. + * This may be a useful feature for a TCP/IP echo service: + * + * ```php + * $connection->pipe($connection); + * ``` + * + * This method returns the destination stream as-is, which can be used to + * set up chains of piped streams: + * + * ```php + * $source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); + * ``` + * + * By default, this will call `end()` on the destination stream once the + * source stream emits an `end` event. This can be disabled like this: + * + * ```php + * $source->pipe($dest, array('end' => false)); + * ``` + * + * Note that this only applies to the `end` event. + * If an `error` or explicit `close` event happens on the source stream, + * you'll have to manually close the destination stream: + * + * ```php + * $source->pipe($dest); + * $source->on('close', function () use ($dest) { + * $dest->end('BYE!'); + * }); + * ``` + * + * If the source stream is not readable (closed state), then this is a NO-OP. + * + * ```php + * $source->close(); + * $source->pipe($dest); // NO-OP + * ``` + * + * If the destinantion stream is not writable (closed state), then this will simply + * throttle (pause) the source stream: + * + * ```php + * $dest->close(); + * $source->pipe($dest); // calls $source->pause() + * ``` + * + * Similarly, if the destination stream is closed while the pipe is still + * active, it will also throttle (pause) the source stream: + * + * ```php + * $source->pipe($dest); + * $dest->close(); // calls $source->pause() + * ``` + * + * Once the pipe is set up successfully, the destination stream MUST emit + * a `pipe` event with this source stream an event argument. + * + * @param WritableStreamInterface $dest + * @param array $options + * @return WritableStreamInterface $dest stream as-is + */ + public function pipe(WritableStreamInterface $dest, array $options = array()); + + /** + * Closes the stream (forcefully). + * + * This method can be used to (forcefully) close the stream. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-readable + * mode, see also `isReadable()`. + * This means that no further `data` or `end` events SHOULD be emitted. + * + * ```php + * $stream->close(); + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this method should not be confused with the `end()` method. + * + * @return void + * @see WritableStreamInterface::close() + */ + public function close(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ThroughStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ThroughStream.php new file mode 100644 index 0000000..6f73fb8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/ThroughStream.php @@ -0,0 +1,190 @@ +on('data', $this->expectCallableOnceWith('hello')); + * + * $through->write('hello'); + * ``` + * + * Similarly, the [`end()` method](#end) will end the stream and emit an + * [`end` event](#end-event) and then [`close()`](#close-1) the stream. + * The [`close()` method](#close-1) will close the stream and emit a + * [`close` event](#close-event). + * Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + * + * ```php + * $through = new ThroughStream(); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Optionally, its constructor accepts any callable function which will then be + * used to *filter* any data written to it. This function receives a single data + * argument as passed to the writable side and must return the data as it will be + * passed to its readable end: + * + * ```php + * $through = new ThroughStream('strtoupper'); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Note that this class makes no assumptions about any data types. This can be + * used to convert data, for example for transforming any structured data into + * a newline-delimited JSON (NDJSON) stream like this: + * + * ```php + * $through = new ThroughStream(function ($data) { + * return json_encode($data) . PHP_EOL; + * }); + * $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + * + * $through->write(array(2, true)); + * ``` + * + * The callback function is allowed to throw an `Exception`. In this case, + * the stream will emit an `error` event and then [`close()`](#close-1) the stream. + * + * ```php + * $through = new ThroughStream(function ($data) { + * if (!is_string($data)) { + * throw new \UnexpectedValueException('Only strings allowed'); + * } + * return $data; + * }); + * $through->on('error', $this->expectCallableOnce())); + * $through->on('close', $this->expectCallableOnce())); + * $through->on('data', $this->expectCallableNever())); + * + * $through->write(2); + * ``` + * + * @see WritableStreamInterface::write() + * @see WritableStreamInterface::end() + * @see DuplexStreamInterface::close() + * @see WritableStreamInterface::pipe() + */ +final class ThroughStream extends EventEmitter implements DuplexStreamInterface +{ + private $readable = true; + private $writable = true; + private $closed = false; + private $paused = false; + private $drain = false; + private $callback; + + public function __construct($callback = null) + { + if ($callback !== null && !\is_callable($callback)) { + throw new InvalidArgumentException('Invalid transformation callback given'); + } + + $this->callback = $callback; + } + + public function pause() + { + $this->paused = true; + } + + public function resume() + { + if ($this->drain) { + $this->drain = false; + $this->emit('drain'); + } + $this->paused = false; + } + + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + if ($this->callback !== null) { + try { + $data = \call_user_func($this->callback, $data); + } catch (\Exception $e) { + $this->emit('error', array($e)); + $this->close(); + + return false; + } + } + + $this->emit('data', array($data)); + + if ($this->paused) { + $this->drain = true; + return false; + } + + return true; + } + + public function end($data = null) + { + if (!$this->writable) { + return; + } + + if (null !== $data) { + $this->write($data); + + // return if write() already caused the stream to close + if (!$this->writable) { + return; + } + } + + $this->readable = false; + $this->writable = false; + $this->paused = true; + $this->drain = false; + + $this->emit('end'); + $this->close(); + } + + public function close() + { + if ($this->closed) { + return; + } + + $this->readable = false; + $this->writable = false; + $this->closed = true; + $this->paused = true; + $this->drain = false; + $this->callback = null; + + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/Util.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/Util.php new file mode 100644 index 0000000..056b037 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/Util.php @@ -0,0 +1,75 @@ + NO-OP + if (!$source->isReadable()) { + return $dest; + } + + // destination not writable => just pause() source + if (!$dest->isWritable()) { + $source->pause(); + + return $dest; + } + + $dest->emit('pipe', array($source)); + + // forward all source data events as $dest->write() + $source->on('data', $dataer = function ($data) use ($source, $dest) { + $feedMore = $dest->write($data); + + if (false === $feedMore) { + $source->pause(); + } + }); + $dest->on('close', function () use ($source, $dataer) { + $source->removeListener('data', $dataer); + $source->pause(); + }); + + // forward destination drain as $source->resume() + $dest->on('drain', $drainer = function () use ($source) { + $source->resume(); + }); + $source->on('close', function () use ($dest, $drainer) { + $dest->removeListener('drain', $drainer); + }); + + // forward end event from source as $dest->end() + $end = isset($options['end']) ? $options['end'] : true; + if ($end) { + $source->on('end', $ender = function () use ($dest) { + $dest->end(); + }); + $dest->on('close', function () use ($source, $ender) { + $source->removeListener('end', $ender); + }); + } + + return $dest; + } + + public static function forwardEvents($source, $target, array $events) + { + foreach ($events as $event) { + $source->on($event, function () use ($event, $target) { + $target->emit($event, \func_get_args()); + }); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableResourceStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableResourceStream.php new file mode 100644 index 0000000..1af16b1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableResourceStream.php @@ -0,0 +1,168 @@ +stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->softLimit = ($writeBufferSoftLimit === null) ? 65536 : (int)$writeBufferSoftLimit; + $this->writeChunkSize = ($writeChunkSize === null) ? -1 : (int)$writeChunkSize; + } + + public function isWritable() + { + return $this->writable; + } + + public function write($data) + { + if (!$this->writable) { + return false; + } + + $this->data .= $data; + + if (!$this->listening && $this->data !== '') { + $this->listening = true; + + $this->loop->addWriteStream($this->stream, array($this, 'handleWrite')); + } + + return !isset($this->data[$this->softLimit - 1]); + } + + public function end($data = null) + { + if (null !== $data) { + $this->write($data); + } + + $this->writable = false; + + // close immediately if buffer is already empty + // otherwise wait for buffer to flush first + if ($this->data === '') { + $this->close(); + } + } + + public function close() + { + if ($this->closed) { + return; + } + + if ($this->listening) { + $this->listening = false; + $this->loop->removeWriteStream($this->stream); + } + + $this->closed = true; + $this->writable = false; + $this->data = ''; + + $this->emit('close'); + $this->removeAllListeners(); + + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + + /** @internal */ + public function handleWrite() + { + $error = null; + \set_error_handler(function ($_, $errstr) use (&$error) { + $error = $errstr; + }); + + if ($this->writeChunkSize === -1) { + $sent = \fwrite($this->stream, $this->data); + } else { + $sent = \fwrite($this->stream, $this->data, $this->writeChunkSize); + } + + \restore_error_handler(); + + // Only report errors if *nothing* could be sent and an error has been raised. + // Ignore non-fatal warnings if *some* data could be sent. + // Any hard (permanent) error will fail to send any data at all. + // Sending excessive amounts of data will only flush *some* data and then + // report a temporary error (EAGAIN) which we do not raise here in order + // to keep the stream open for further tries to write. + // Should this turn out to be a permanent error later, it will eventually + // send *nothing* and we can detect this. + if (($sent === 0 || $sent === false) && $error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to write to stream: ' . $error))); + $this->close(); + + return; + } + + $exceeded = isset($this->data[$this->softLimit - 1]); + $this->data = (string) \substr($this->data, $sent); + + // buffer has been above limit and is now below limit + if ($exceeded && !isset($this->data[$this->softLimit - 1])) { + $this->emit('drain'); + } + + // buffer is now completely empty => stop trying to write + if ($this->data === '') { + // stop waiting for resource to be writable + if ($this->listening) { + $this->loop->removeWriteStream($this->stream); + $this->listening = false; + } + + // buffer is end()ing and now completely empty => close buffer + if (!$this->writable) { + $this->close(); + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableStreamInterface.php b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableStreamInterface.php new file mode 100644 index 0000000..9b54680 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/react/stream/src/WritableStreamInterface.php @@ -0,0 +1,347 @@ +on('drain', function () use ($stream) { + * echo 'Stream is now ready to accept more data'; + * }); + * ``` + * + * This event SHOULD be emitted once every time the buffer became full + * previously and is now ready to accept more data. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if the buffer never became full in the first place. + * This event SHOULD NOT be emitted if the buffer has not become full + * previously. + * + * This event is mostly used internally, see also `write()` for more details. + * + * pipe event: + * The `pipe` event will be emitted whenever a readable stream is `pipe()`d + * into this stream. + * The event receives a single `ReadableStreamInterface` argument for the + * source stream. + * + * ```php + * $stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + * echo 'Now receiving piped data'; + * + * // explicitly close target if source emits an error + * $source->on('error', function () use ($stream) { + * $stream->close(); + * }); + * }); + * + * $source->pipe($stream); + * ``` + * + * This event MUST be emitted once for each readable stream that is + * successfully piped into this destination stream. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if no stream is ever piped into this stream. + * This event MUST NOT be emitted if either the source is not readable + * (closed already) or this destination is not writable (closed already). + * + * This event is mostly used internally, see also `pipe()` for more details. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to write to this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error. + * It SHOULD NOT be emitted after a previous `error` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-writable mode, see + * also `close()` and `isWritable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-writable mode, + * see also `isWritable()`. + * + * This event SHOULD be emitted whenever the stream closes, irrespective of + * whether this happens implicitly due to an unrecoverable error or + * explicitly when either side closes the stream. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after flushing the buffer from + * the `end()` method, after receiving a *successful* `end` event or after + * a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + * @see DuplexStreamInterface + */ +interface WritableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a writable state (not closed already). + * + * This method can be used to check if the stream still accepts writing + * any data or if it is ended or closed already. + * Writing any data to a non-writable stream is a NO-OP: + * + * ```php + * assert($stream->isWritable() === false); + * + * $stream->write('end'); // NO-OP + * $stream->end('end'); // NO-OP + * ``` + * + * A successfully opened stream always MUST start in writable mode. + * + * Once the stream ends or closes, it MUST switch to non-writable mode. + * This can happen any time, explicitly through `end()` or `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-writable mode, it MUST NOT transition + * back to writable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `isReadable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isWritable(); + + /** + * Write some data into the stream. + * + * A successful write MUST be confirmed with a boolean `true`, which means + * that either the data was written (flushed) immediately or is buffered and + * scheduled for a future write. Note that this interface gives you no + * control over explicitly flushing the buffered data, as finding the + * appropriate time for this is beyond the scope of this interface and left + * up to the implementation of this interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * If a stream cannot handle writing (or flushing) the data, it SHOULD emit + * an `error` event and MAY `close()` the stream if it can not recover from + * this error. + * + * If the internal buffer is full after adding `$data`, then `write()` + * SHOULD return `false`, indicating that the caller should stop sending + * data until the buffer drains. + * The stream SHOULD send a `drain` event once the buffer is ready to accept + * more data. + * + * Similarly, if the the stream is not writable (already in a closed state) + * it MUST NOT process the given `$data` and SHOULD return `false`, + * indicating that the caller should stop sending data. + * + * The given `$data` argument MAY be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will only accept the raw (binary) payload data that is transferred over + * the wire as chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * @param mixed|string $data + * @return bool + */ + public function write($data); + + /** + * Successfully ends the stream (after optionally sending some final data). + * + * This method can be used to successfully end the stream, i.e. close + * the stream after sending out all data that is currently buffered. + * + * ```php + * $stream->write('hello'); + * $stream->write('world'); + * $stream->end(); + * ``` + * + * If there's no data currently buffered and nothing to be flushed, then + * this method MAY `close()` the stream immediately. + * + * If there's still data in the buffer that needs to be flushed first, then + * this method SHOULD try to write out this data and only then `close()` + * the stream. + * Once the stream is closed, it SHOULD emit a `close` event. + * + * Note that this interface gives you no control over explicitly flushing + * the buffered data, as finding the appropriate time for this is beyond the + * scope of this interface and left up to the implementation of this + * interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * You can optionally pass some final data that is written to the stream + * before ending the stream. If a non-`null` value is given as `$data`, then + * this method will behave just like calling `write($data)` before ending + * with no data. + * + * ```php + * // shorter version + * $stream->end('bye'); + * + * // same as longer version + * $stream->write('bye'); + * $stream->end(); + * ``` + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->end(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * If this stream is a `DuplexStreamInterface`, calling this method SHOULD + * also end its readable side, unless the stream supports half-open mode. + * In other words, after calling this method, these streams SHOULD switch + * into non-writable AND non-readable mode, see also `isReadable()`. + * This implies that in this case, the stream SHOULD NOT emit any `data` + * or `end` events anymore. + * Streams MAY choose to use the `pause()` method logic for this, but + * special care may have to be taken to ensure a following call to the + * `resume()` method SHOULD NOT continue emitting readable events. + * + * Note that this method should not be confused with the `close()` method. + * + * @param mixed|string|null $data + * @return void + */ + public function end($data = null); + + /** + * Closes the stream (forcefully). + * + * This method can be used to forcefully close the stream, i.e. close + * the stream without waiting for any buffered data to be flushed. + * If there's still data in the buffer, this data SHOULD be discarded. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->close(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * Note that this method should not be confused with the `end()` method. + * Unlike the `end()` method, this method does not take care of any existing + * buffers and simply discards any buffer contents. + * Likewise, this method may also be called after calling `end()` on a + * stream in order to stop waiting for the stream to flush its final data. + * + * ```php + * $stream->end(); + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->close(); + * }); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * + * @return void + * @see ReadableStreamInterface::close() + */ + public function close(); +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.gitignore b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.gitignore new file mode 100644 index 0000000..83ec41e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.gitignore @@ -0,0 +1,11 @@ +phpunit.xml +composer.phar +composer.lock +composer-test.lock +vendor/ +build/artifacts/ +artifacts/ +docs/_build +docs/*.pyc +.idea +.DS_STORE diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.travis.yml b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.travis.yml new file mode 100644 index 0000000..08f3721 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/.travis.yml @@ -0,0 +1,21 @@ +language: php + +sudo: false + +install: + - travis_retry composer install --no-interaction --prefer-source + +script: make test + +matrix: + include: + - php: 5.3 + dist: precise + - php: 5.4 + - php: 5.5 + - php: 5.6 + - php: 7.0 + - php: hhvm + allow_failures: + - php: hhvm + fast_finish: true diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/CHANGELOG.md b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/CHANGELOG.md new file mode 100644 index 0000000..642dc9a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/CHANGELOG.md @@ -0,0 +1,28 @@ +# CHANGELOG + +## 1.2.0 - 2015-08-15 + +* Body as `"0"` is now properly added to a response. +* Now allowing forward seeking in CachingStream. +* Now properly parsing HTTP requests that contain proxy targets in + `parse_request`. +* functions.php is now conditionally required. +* user-info is no longer dropped when resolving URIs. + +## 1.1.0 - 2015-06-24 + +* URIs can now be relative. +* `multipart/form-data` headers are now overridden case-insensitively. +* URI paths no longer encode the following characters because they are allowed + in URIs: "(", ")", "*", "!", "'" +* A port is no longer added to a URI when the scheme is missing and no port is + present. + +## 1.0.0 - 2015-05-19 + +Initial release. + +Currently unsupported: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Dockerfile b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Dockerfile new file mode 100644 index 0000000..846e8cf --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Dockerfile @@ -0,0 +1,5 @@ +FROM greensheep/dockerfiles-php-5.3 +RUN apt-get update -y +RUN apt-get install -y curl +RUN curl -sS https://getcomposer.org/installer | php +RUN mv composer.phar /usr/local/bin/composer \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/LICENSE b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/LICENSE new file mode 100644 index 0000000..581d95f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Michael Dowling, https://github.com/mtdowling + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Makefile b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Makefile new file mode 100644 index 0000000..73a5c5b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/Makefile @@ -0,0 +1,21 @@ +all: clean test + +test: + vendor/bin/phpunit $(TEST) + +coverage: + vendor/bin/phpunit --coverage-html=artifacts/coverage $(TEST) + +view-coverage: + open artifacts/coverage/index.html + +clean: + rm -rf artifacts/* + +.PHONY: docker-login +docker-login: + docker run -t -i -v $(shell pwd):/opt/psr7 ringcentral-psr7 /bin/bash + +.PHONY: docker-build +docker-build: + docker build -t ringcentral-psr7 . \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/README.md b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/README.md new file mode 100644 index 0000000..b4a6061 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/README.md @@ -0,0 +1,587 @@ +# PSR-7 Message Implementation + +This repository contains a partial [PSR-7](http://www.php-fig.org/psr/psr-7/) +message implementation, several stream decorators, and some helpful +functionality like query string parsing. Currently missing +ServerRequestInterface and UploadedFileInterface; a pull request for these features is welcome. + + +# Stream implementation + +This package comes with a number of stream implementations and stream +decorators. + + +## AppendStream + +`RingCentral\Psr7\AppendStream` + +Reads from multiple streams, one after the other. + +```php +use RingCentral\Psr7; + +$a = Psr7\stream_for('abc, '); +$b = Psr7\stream_for('123.'); +$composed = new Psr7\AppendStream([$a, $b]); + +$composed->addStream(Psr7\stream_for(' Above all listen to me'). + +echo $composed(); // abc, 123. Above all listen to me. +``` + + +## BufferStream + +`RingCentral\Psr7\BufferStream` + +Provides a buffer stream that can be written to to fill a buffer, and read +from to remove bytes from the buffer. + +This stream returns a "hwm" metadata value that tells upstream consumers +what the configured high water mark of the stream is, or the maximum +preferred size of the buffer. + +```php +use RingCentral\Psr7; + +// When more than 1024 bytes are in the buffer, it will begin returning +// false to writes. This is an indication that writers should slow down. +$buffer = new Psr7\BufferStream(1024); +``` + + +## CachingStream + +The CachingStream is used to allow seeking over previously read bytes on +non-seekable streams. This can be useful when transferring a non-seekable +entity body fails due to needing to rewind the stream (for example, resulting +from a redirect). Data that is read from the remote stream will be buffered in +a PHP temp stream so that previously read bytes are cached first in memory, +then on disk. + +```php +use RingCentral\Psr7; + +$original = Psr7\stream_for(fopen('http://www.google.com', 'r')); +$stream = new Psr7\CachingStream($original); + +$stream->read(1024); +echo $stream->tell(); +// 1024 + +$stream->seek(0); +echo $stream->tell(); +// 0 +``` + + +## DroppingStream + +`RingCentral\Psr7\DroppingStream` + +Stream decorator that begins dropping data once the size of the underlying +stream becomes too full. + +```php +use RingCentral\Psr7; + +// Create an empty stream +$stream = Psr7\stream_for(); + +// Start dropping data when the stream has more than 10 bytes +$dropping = new Psr7\DroppingStream($stream, 10); + +$stream->write('01234567890123456789'); +echo $stream; // 0123456789 +``` + + +## FnStream + +`RingCentral\Psr7\FnStream` + +Compose stream implementations based on a hash of functions. + +Allows for easy testing and extension of a provided stream without needing to +to create a concrete class for a simple extension point. + +```php + +use RingCentral\Psr7; + +$stream = Psr7\stream_for('hi'); +$fnStream = Psr7\FnStream::decorate($stream, [ + 'rewind' => function () use ($stream) { + echo 'About to rewind - '; + $stream->rewind(); + echo 'rewound!'; + } +]); + +$fnStream->rewind(); +// Outputs: About to rewind - rewound! +``` + + +## InflateStream + +`RingCentral\Psr7\InflateStream` + +Uses PHP's zlib.inflate filter to inflate deflate or gzipped content. + +This stream decorator skips the first 10 bytes of the given stream to remove +the gzip header, converts the provided stream to a PHP stream resource, +then appends the zlib.inflate filter. The stream is then converted back +to a Guzzle stream resource to be used as a Guzzle stream. + + +## LazyOpenStream + +`RingCentral\Psr7\LazyOpenStream` + +Lazily reads or writes to a file that is opened only after an IO operation +take place on the stream. + +```php +use RingCentral\Psr7; + +$stream = new Psr7\LazyOpenStream('/path/to/file', 'r'); +// The file has not yet been opened... + +echo $stream->read(10); +// The file is opened and read from only when needed. +``` + + +## LimitStream + +`RingCentral\Psr7\LimitStream` + +LimitStream can be used to read a subset or slice of an existing stream object. +This can be useful for breaking a large file into smaller pieces to be sent in +chunks (e.g. Amazon S3's multipart upload API). + +```php +use RingCentral\Psr7; + +$original = Psr7\stream_for(fopen('/tmp/test.txt', 'r+')); +echo $original->getSize(); +// >>> 1048576 + +// Limit the size of the body to 1024 bytes and start reading from byte 2048 +$stream = new Psr7\LimitStream($original, 1024, 2048); +echo $stream->getSize(); +// >>> 1024 +echo $stream->tell(); +// >>> 0 +``` + + +## MultipartStream + +`RingCentral\Psr7\MultipartStream` + +Stream that when read returns bytes for a streaming multipart or +multipart/form-data stream. + + +## NoSeekStream + +`RingCentral\Psr7\NoSeekStream` + +NoSeekStream wraps a stream and does not allow seeking. + +```php +use RingCentral\Psr7; + +$original = Psr7\stream_for('foo'); +$noSeek = new Psr7\NoSeekStream($original); + +echo $noSeek->read(3); +// foo +var_export($noSeek->isSeekable()); +// false +$noSeek->seek(0); +var_export($noSeek->read(3)); +// NULL +``` + + +## PumpStream + +`RingCentral\Psr7\PumpStream` + +Provides a read only stream that pumps data from a PHP callable. + +When invoking the provided callable, the PumpStream will pass the amount of +data requested to read to the callable. The callable can choose to ignore +this value and return fewer or more bytes than requested. Any extra data +returned by the provided callable is buffered internally until drained using +the read() function of the PumpStream. The provided callable MUST return +false when there is no more data to read. + + +## Implementing stream decorators + +Creating a stream decorator is very easy thanks to the +`RingCentral\Psr7\StreamDecoratorTrait`. This trait provides methods that +implement `Psr\Http\Message\StreamInterface` by proxying to an underlying +stream. Just `use` the `StreamDecoratorTrait` and implement your custom +methods. + +For example, let's say we wanted to call a specific function each time the last +byte is read from a stream. This could be implemented by overriding the +`read()` method. + +```php +use Psr\Http\Message\StreamInterface; +use RingCentral\Psr7\StreamDecoratorTrait; + +class EofCallbackStream implements StreamInterface +{ + use StreamDecoratorTrait; + + private $callback; + + public function __construct(StreamInterface $stream, callable $cb) + { + $this->stream = $stream; + $this->callback = $cb; + } + + public function read($length) + { + $result = $this->stream->read($length); + + // Invoke the callback when EOF is hit. + if ($this->eof()) { + call_user_func($this->callback); + } + + return $result; + } +} +``` + +This decorator could be added to any existing stream and used like so: + +```php +use RingCentral\Psr7; + +$original = Psr7\stream_for('foo'); + +$eofStream = new EofCallbackStream($original, function () { + echo 'EOF!'; +}); + +$eofStream->read(2); +$eofStream->read(1); +// echoes "EOF!" +$eofStream->seek(0); +$eofStream->read(3); +// echoes "EOF!" +``` + + +## PHP StreamWrapper + +You can use the `RingCentral\Psr7\StreamWrapper` class if you need to use a +PSR-7 stream as a PHP stream resource. + +Use the `RingCentral\Psr7\StreamWrapper::getResource()` method to create a PHP +stream from a PSR-7 stream. + +```php +use RingCentral\Psr7\StreamWrapper; + +$stream = RingCentral\Psr7\stream_for('hello!'); +$resource = StreamWrapper::getResource($stream); +echo fread($resource, 6); // outputs hello! +``` + + +# Function API + +There are various functions available under the `RingCentral\Psr7` namespace. + + +## `function str` + +`function str(MessageInterface $message)` + +Returns the string representation of an HTTP message. + +```php +$request = new RingCentral\Psr7\Request('GET', 'http://example.com'); +echo RingCentral\Psr7\str($request); +``` + + +## `function uri_for` + +`function uri_for($uri)` + +This function accepts a string or `Psr\Http\Message\UriInterface` and returns a +UriInterface for the given value. If the value is already a `UriInterface`, it +is returned as-is. + +```php +$uri = RingCentral\Psr7\uri_for('http://example.com'); +assert($uri === RingCentral\Psr7\uri_for($uri)); +``` + + +## `function stream_for` + +`function stream_for($resource = '', array $options = [])` + +Create a new stream based on the input type. + +Options is an associative array that can contain the following keys: + +* - metadata: Array of custom metadata. +* - size: Size of the stream. + +This method accepts the following `$resource` types: + +- `Psr\Http\Message\StreamInterface`: Returns the value as-is. +- `string`: Creates a stream object that uses the given string as the contents. +- `resource`: Creates a stream object that wraps the given PHP stream resource. +- `Iterator`: If the provided value implements `Iterator`, then a read-only + stream object will be created that wraps the given iterable. Each time the + stream is read from, data from the iterator will fill a buffer and will be + continuously called until the buffer is equal to the requested read size. + Subsequent read calls will first read from the buffer and then call `next` + on the underlying iterator until it is exhausted. +- `object` with `__toString()`: If the object has the `__toString()` method, + the object will be cast to a string and then a stream will be returned that + uses the string value. +- `NULL`: When `null` is passed, an empty stream object is returned. +- `callable` When a callable is passed, a read-only stream object will be + created that invokes the given callable. The callable is invoked with the + number of suggested bytes to read. The callable can return any number of + bytes, but MUST return `false` when there is no more data to return. The + stream object that wraps the callable will invoke the callable until the + number of requested bytes are available. Any additional bytes will be + buffered and used in subsequent reads. + +```php +$stream = RingCentral\Psr7\stream_for('foo'); +$stream = RingCentral\Psr7\stream_for(fopen('/path/to/file', 'r')); + +$generator function ($bytes) { + for ($i = 0; $i < $bytes; $i++) { + yield ' '; + } +} + +$stream = RingCentral\Psr7\stream_for($generator(100)); +``` + + +## `function parse_header` + +`function parse_header($header)` + +Parse an array of header values containing ";" separated data into an array of +associative arrays representing the header key value pair data of the header. +When a parameter does not contain a value, but just contains a key, this +function will inject a key with a '' string value. + + +## `function normalize_header` + +`function normalize_header($header)` + +Converts an array of header values that may contain comma separated headers +into an array of headers with no comma separated values. + + +## `function modify_request` + +`function modify_request(RequestInterface $request, array $changes)` + +Clone and modify a request with the given changes. This method is useful for +reducing the number of clones needed to mutate a message. + +The changes can be one of: + +- method: (string) Changes the HTTP method. +- set_headers: (array) Sets the given headers. +- remove_headers: (array) Remove the given headers. +- body: (mixed) Sets the given body. +- uri: (UriInterface) Set the URI. +- query: (string) Set the query string value of the URI. +- version: (string) Set the protocol version. + + +## `function rewind_body` + +`function rewind_body(MessageInterface $message)` + +Attempts to rewind a message body and throws an exception on failure. The body +of the message will only be rewound if a call to `tell()` returns a value other +than `0`. + + +## `function try_fopen` + +`function try_fopen($filename, $mode)` + +Safely opens a PHP stream resource using a filename. + +When fopen fails, PHP normally raises a warning. This function adds an error +handler that checks for errors and throws an exception instead. + + +## `function copy_to_string` + +`function copy_to_string(StreamInterface $stream, $maxLen = -1)` + +Copy the contents of a stream into a string until the given number of bytes +have been read. + + +## `function copy_to_stream` + +`function copy_to_stream(StreamInterface $source, StreamInterface $dest, $maxLen = -1)` + +Copy the contents of a stream into another stream until the given number of +bytes have been read. + + +## `function hash` + +`function hash(StreamInterface $stream, $algo, $rawOutput = false)` + +Calculate a hash of a Stream. This method reads the entire stream to calculate +a rolling hash (based on PHP's hash_init functions). + + +## `function readline` + +`function readline(StreamInterface $stream, $maxLength = null)` + +Read a line from the stream up to the maximum allowed buffer length. + + +## `function parse_request` + +`function parse_request($message)` + +Parses a request message string into a request object. + + +## `function parse_server_request` + +`function parse_server_request($message, array $serverParams = array())` + +Parses a request message string into a server-side request object. + + +## `function parse_response` + +`function parse_response($message)` + +Parses a response message string into a response object. + + +## `function parse_query` + +`function parse_query($str, $urlEncoding = true)` + +Parse a query string into an associative array. + +If multiple values are found for the same key, the value of that key value pair +will become an array. This function does not parse nested PHP style arrays into +an associative array (e.g., `foo[a]=1&foo[b]=2` will be parsed into +`['foo[a]' => '1', 'foo[b]' => '2']`). + + +## `function build_query` + +`function build_query(array $params, $encoding = PHP_QUERY_RFC3986)` + +Build a query string from an array of key value pairs. + +This function can use the return value of parseQuery() to build a query string. +This function does not modify the provided keys when an array is encountered +(like http_build_query would). + + +## `function mimetype_from_filename` + +`function mimetype_from_filename($filename)` + +Determines the mimetype of a file by looking at its extension. + + +## `function mimetype_from_extension` + +`function mimetype_from_extension($extension)` + +Maps a file extensions to a mimetype. + + +# Static URI methods + +The `RingCentral\Psr7\Uri` class has several static methods to manipulate URIs. + + +## `RingCentral\Psr7\Uri::removeDotSegments` + +`public static function removeDotSegments($path) -> UriInterface` + +Removes dot segments from a path and returns the new path. + +See http://tools.ietf.org/html/rfc3986#section-5.2.4 + + +## `RingCentral\Psr7\Uri::resolve` + +`public static function resolve(UriInterface $base, $rel) -> UriInterface` + +Resolve a base URI with a relative URI and return a new URI. + +See http://tools.ietf.org/html/rfc3986#section-5 + + +## `RingCentral\Psr7\Uri::withQueryValue` + +`public static function withQueryValue(UriInterface $uri, $key, $value) -> UriInterface` + +Create a new URI with a specific query string value. + +Any existing query string values that exactly match the provided key are +removed and replaced with the given key value pair. + +Note: this function will convert "=" to "%3D" and "&" to "%26". + + +## `RingCentral\Psr7\Uri::withoutQueryValue` + +`public static function withoutQueryValue(UriInterface $uri, $key, $value) -> UriInterface` + +Create a new URI with a specific query string value removed. + +Any existing query string values that exactly match the provided key are +removed. + +Note: this function will convert "=" to "%3D" and "&" to "%26". + + +## `RingCentral\Psr7\Uri::fromParts` + +`public static function fromParts(array $parts) -> UriInterface` + +Create a `RingCentral\Psr7\Uri` object from a hash of `parse_url` parts. + + +# Not Implemented + +A few aspects of PSR-7 are not implemented in this project. A pull request for +any of these features is welcome: + +- `Psr\Http\Message\ServerRequestInterface` +- `Psr\Http\Message\UploadedFileInterface` diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/composer.json b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/composer.json new file mode 100644 index 0000000..4955053 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/composer.json @@ -0,0 +1,35 @@ +{ + "name": "ringcentral/psr7", + "type": "library", + "description": "PSR-7 message implementation", + "keywords": ["message", "stream", "http", "uri"], + "license": "MIT", + "authors": [ + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + } + ], + "require": { + "php": ">=5.3", + "psr/http-message": "~1.0" + }, + "require-dev": { + "phpunit/phpunit": "~4.0" + }, + "provide": { + "psr/http-message-implementation": "1.0" + }, + "autoload": { + "psr-4": { + "RingCentral\\Psr7\\": "src/" + }, + "files": ["src/functions_include.php"] + }, + "extra": { + "branch-alias": { + "dev-master": "1.0-dev" + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/phpunit.xml.dist b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/phpunit.xml.dist new file mode 100644 index 0000000..500cd53 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + + tests + + + + + src + + src/ + + + + diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/AppendStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/AppendStream.php new file mode 100644 index 0000000..8b8df6f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/AppendStream.php @@ -0,0 +1,233 @@ +addStream($stream); + } + } + + public function __toString() + { + try { + $this->rewind(); + return $this->getContents(); + } catch (\Exception $e) { + return ''; + } + } + + /** + * Add a stream to the AppendStream + * + * @param StreamInterface $stream Stream to append. Must be readable. + * + * @throws \InvalidArgumentException if the stream is not readable + */ + public function addStream(StreamInterface $stream) + { + if (!$stream->isReadable()) { + throw new \InvalidArgumentException('Each stream must be readable'); + } + + // The stream is only seekable if all streams are seekable + if (!$stream->isSeekable()) { + $this->seekable = false; + } + + $this->streams[] = $stream; + } + + public function getContents() + { + return copy_to_string($this); + } + + /** + * Closes each attached stream. + * + * {@inheritdoc} + */ + public function close() + { + $this->pos = $this->current = 0; + + foreach ($this->streams as $stream) { + $stream->close(); + } + + $this->streams = array(); + } + + /** + * Detaches each attached stream + * + * {@inheritdoc} + */ + public function detach() + { + $this->close(); + $this->detached = true; + } + + public function tell() + { + return $this->pos; + } + + /** + * Tries to calculate the size by adding the size of each stream. + * + * If any of the streams do not return a valid number, then the size of the + * append stream cannot be determined and null is returned. + * + * {@inheritdoc} + */ + public function getSize() + { + $size = 0; + + foreach ($this->streams as $stream) { + $s = $stream->getSize(); + if ($s === null) { + return null; + } + $size += $s; + } + + return $size; + } + + public function eof() + { + return !$this->streams || + ($this->current >= count($this->streams) - 1 && + $this->streams[$this->current]->eof()); + } + + public function rewind() + { + $this->seek(0); + } + + /** + * Attempts to seek to the given position. Only supports SEEK_SET. + * + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if (!$this->seekable) { + throw new \RuntimeException('This AppendStream is not seekable'); + } elseif ($whence !== SEEK_SET) { + throw new \RuntimeException('The AppendStream can only seek with SEEK_SET'); + } + + $this->pos = $this->current = 0; + + // Rewind each stream + foreach ($this->streams as $i => $stream) { + try { + $stream->rewind(); + } catch (\Exception $e) { + throw new \RuntimeException('Unable to seek stream ' + . $i . ' of the AppendStream', 0, $e); + } + } + + // Seek to the actual position by reading from each stream + while ($this->pos < $offset && !$this->eof()) { + $result = $this->read(min(8096, $offset - $this->pos)); + if ($result === '') { + break; + } + } + } + + /** + * Reads from all of the appended streams until the length is met or EOF. + * + * {@inheritdoc} + */ + public function read($length) + { + $buffer = ''; + $total = count($this->streams) - 1; + $remaining = $length; + $progressToNext = false; + + while ($remaining > 0) { + + // Progress to the next stream if needed. + if ($progressToNext || $this->streams[$this->current]->eof()) { + $progressToNext = false; + if ($this->current === $total) { + break; + } + $this->current++; + } + + $result = $this->streams[$this->current]->read($remaining); + + // Using a loose comparison here to match on '', false, and null + if ($result == null) { + $progressToNext = true; + continue; + } + + $buffer .= $result; + $remaining = $length - strlen($buffer); + } + + $this->pos += strlen($buffer); + + return $buffer; + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return false; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to an AppendStream'); + } + + public function getMetadata($key = null) + { + return $key ? null : array(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/BufferStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/BufferStream.php new file mode 100644 index 0000000..a1e236d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/BufferStream.php @@ -0,0 +1,137 @@ +hwm = $hwm; + } + + public function __toString() + { + return $this->getContents(); + } + + public function getContents() + { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + public function close() + { + $this->buffer = ''; + } + + public function detach() + { + $this->close(); + } + + public function getSize() + { + return strlen($this->buffer); + } + + public function isReadable() + { + return true; + } + + public function isWritable() + { + return true; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a BufferStream'); + } + + public function eof() + { + return strlen($this->buffer) === 0; + } + + public function tell() + { + throw new \RuntimeException('Cannot determine the position of a BufferStream'); + } + + /** + * Reads data from the buffer. + */ + public function read($length) + { + $currentLength = strlen($this->buffer); + + if ($length >= $currentLength) { + // No need to slice the buffer because we don't have enough data. + $result = $this->buffer; + $this->buffer = ''; + } else { + // Slice up the result to provide a subset of the buffer. + $result = substr($this->buffer, 0, $length); + $this->buffer = substr($this->buffer, $length); + } + + return $result; + } + + /** + * Writes data to the buffer. + */ + public function write($string) + { + $this->buffer .= $string; + + // TODO: What should happen here? + if (strlen($this->buffer) >= $this->hwm) { + return false; + } + + return strlen($string); + } + + public function getMetadata($key = null) + { + if ($key == 'hwm') { + return $this->hwm; + } + + return $key ? null : array(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/CachingStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/CachingStream.php new file mode 100644 index 0000000..ce3aca8 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/CachingStream.php @@ -0,0 +1,135 @@ +remoteStream = $stream; + parent::__construct($target ?: new Stream(fopen('php://temp', 'r+'))); + } + + public function getSize() + { + return max($this->stream->getSize(), $this->remoteStream->getSize()); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + if ($whence == SEEK_SET) { + $byte = $offset; + } elseif ($whence == SEEK_CUR) { + $byte = $offset + $this->tell(); + } elseif ($whence == SEEK_END) { + $size = $this->remoteStream->getSize(); + if ($size === null) { + $size = $this->cacheEntireStream(); + } + // Because 0 is the first byte, we seek to size - 1. + $byte = $size - 1 - $offset; + } else { + throw new \InvalidArgumentException('Invalid whence'); + } + + $diff = $byte - $this->stream->getSize(); + + if ($diff > 0) { + // If the seek byte is greater the number of read bytes, then read + // the difference of bytes to cache the bytes and inherently seek. + $this->read($diff); + } else { + // We can just do a normal seek since we've already seen this byte. + $this->stream->seek($byte); + } + } + + public function read($length) + { + // Perform a regular read on any previously read data from the buffer + $data = $this->stream->read($length); + $remaining = $length - strlen($data); + + // More data was requested so read from the remote stream + if ($remaining) { + // If data was written to the buffer in a position that would have + // been filled from the remote stream, then we must skip bytes on + // the remote stream to emulate overwriting bytes from that + // position. This mimics the behavior of other PHP stream wrappers. + $remoteData = $this->remoteStream->read( + $remaining + $this->skipReadBytes + ); + + if ($this->skipReadBytes) { + $len = strlen($remoteData); + $remoteData = substr($remoteData, $this->skipReadBytes); + $this->skipReadBytes = max(0, $this->skipReadBytes - $len); + } + + $data .= $remoteData; + $this->stream->write($remoteData); + } + + return $data; + } + + public function write($string) + { + // When appending to the end of the currently read stream, you'll want + // to skip bytes from being read from the remote stream to emulate + // other stream wrappers. Basically replacing bytes of data of a fixed + // length. + $overflow = (strlen($string) + $this->tell()) - $this->remoteStream->tell(); + if ($overflow > 0) { + $this->skipReadBytes += $overflow; + } + + return $this->stream->write($string); + } + + public function eof() + { + return $this->stream->eof() && $this->remoteStream->eof(); + } + + /** + * Close both the remote stream and buffer stream + */ + public function close() + { + $this->remoteStream->close() && $this->stream->close(); + } + + private function cacheEntireStream() + { + $target = new FnStream(array('write' => 'strlen')); + copy_to_stream($this, $target); + + return $this->tell(); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/DroppingStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/DroppingStream.php new file mode 100644 index 0000000..3a34d38 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/DroppingStream.php @@ -0,0 +1,41 @@ +maxLength = $maxLength; + } + + public function write($string) + { + $diff = $this->maxLength - $this->stream->getSize(); + + // Begin returning 0 when the underlying stream is too large. + if ($diff <= 0) { + return 0; + } + + // Write the stream or a subset of the stream if needed. + if (strlen($string) < $diff) { + return $this->stream->write($string); + } + + return $this->stream->write(substr($string, 0, $diff)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/FnStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/FnStream.php new file mode 100644 index 0000000..f78dc8b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/FnStream.php @@ -0,0 +1,163 @@ +methods = $methods; + + // Create the functions on the class + foreach ($methods as $name => $fn) { + $this->{'_fn_' . $name} = $fn; + } + } + + /** + * Lazily determine which methods are not implemented. + * @throws \BadMethodCallException + */ + public function __get($name) + { + throw new \BadMethodCallException(str_replace('_fn_', '', $name) + . '() is not implemented in the FnStream'); + } + + /** + * The close method is called on the underlying stream only if possible. + */ + public function __destruct() + { + if (isset($this->_fn_close)) { + call_user_func($this->_fn_close); + } + } + + /** + * Adds custom functionality to an underlying stream by intercepting + * specific method calls. + * + * @param StreamInterface $stream Stream to decorate + * @param array $methods Hash of method name to a closure + * + * @return FnStream + */ + public static function decorate(StreamInterface $stream, array $methods) + { + // If any of the required methods were not provided, then simply + // proxy to the decorated stream. + foreach (array_diff(self::$slots, array_keys($methods)) as $diff) { + $methods[$diff] = array($stream, $diff); + } + + return new self($methods); + } + + public function __toString() + { + return call_user_func($this->_fn___toString); + } + + public function close() + { + return call_user_func($this->_fn_close); + } + + public function detach() + { + return call_user_func($this->_fn_detach); + } + + public function getSize() + { + return call_user_func($this->_fn_getSize); + } + + public function tell() + { + return call_user_func($this->_fn_tell); + } + + public function eof() + { + return call_user_func($this->_fn_eof); + } + + public function isSeekable() + { + return call_user_func($this->_fn_isSeekable); + } + + public function rewind() + { + call_user_func($this->_fn_rewind); + } + + public function seek($offset, $whence = SEEK_SET) + { + call_user_func($this->_fn_seek, $offset, $whence); + } + + public function isWritable() + { + return call_user_func($this->_fn_isWritable); + } + + public function write($string) + { + return call_user_func($this->_fn_write, $string); + } + + public function isReadable() + { + return call_user_func($this->_fn_isReadable); + } + + public function read($length) + { + return call_user_func($this->_fn_read, $length); + } + + public function getContents() + { + return call_user_func($this->_fn_getContents); + } + + public function getMetadata($key = null) + { + return call_user_func($this->_fn_getMetadata, $key); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/InflateStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/InflateStream.php new file mode 100644 index 0000000..c718002 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/InflateStream.php @@ -0,0 +1,27 @@ +filename = $filename; + $this->mode = $mode; + parent::__construct(); + } + + /** + * Creates the underlying stream lazily when required. + * + * @return StreamInterface + */ + protected function createStream() + { + return stream_for(try_fopen($this->filename, $this->mode)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/LimitStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/LimitStream.php new file mode 100644 index 0000000..57eeca9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/LimitStream.php @@ -0,0 +1,154 @@ +setLimit($limit); + $this->setOffset($offset); + } + + public function eof() + { + // Always return true if the underlying stream is EOF + if ($this->stream->eof()) { + return true; + } + + // No limit and the underlying stream is not at EOF + if ($this->limit == -1) { + return false; + } + + return $this->stream->tell() >= $this->offset + $this->limit; + } + + /** + * Returns the size of the limited subset of data + * {@inheritdoc} + */ + public function getSize() + { + if (null === ($length = $this->stream->getSize())) { + return null; + } elseif ($this->limit == -1) { + return $length - $this->offset; + } else { + return min($this->limit, $length - $this->offset); + } + } + + /** + * Allow for a bounded seek on the read limited stream + * {@inheritdoc} + */ + public function seek($offset, $whence = SEEK_SET) + { + if ($whence !== SEEK_SET || $offset < 0) { + throw new \RuntimeException(sprintf( + 'Cannot seek to offset % with whence %s', + $offset, + $whence + )); + } + + $offset += $this->offset; + + if ($this->limit !== -1) { + if ($offset > $this->offset + $this->limit) { + $offset = $this->offset + $this->limit; + } + } + + $this->stream->seek($offset); + } + + /** + * Give a relative tell() + * {@inheritdoc} + */ + public function tell() + { + return $this->stream->tell() - $this->offset; + } + + /** + * Set the offset to start limiting from + * + * @param int $offset Offset to seek to and begin byte limiting from + * + * @throws \RuntimeException if the stream cannot be seeked. + */ + public function setOffset($offset) + { + $current = $this->stream->tell(); + + if ($current !== $offset) { + // If the stream cannot seek to the offset position, then read to it + if ($this->stream->isSeekable()) { + $this->stream->seek($offset); + } elseif ($current > $offset) { + throw new \RuntimeException("Could not seek to stream offset $offset"); + } else { + $this->stream->read($offset - $current); + } + } + + $this->offset = $offset; + } + + /** + * Set the limit of bytes that the decorator allows to be read from the + * stream. + * + * @param int $limit Number of bytes to allow to be read from the stream. + * Use -1 for no limit. + */ + public function setLimit($limit) + { + $this->limit = $limit; + } + + public function read($length) + { + if ($this->limit == -1) { + return $this->stream->read($length); + } + + // Check if the current position is less than the total allowed + // bytes + original offset + $remaining = ($this->offset + $this->limit) - $this->stream->tell(); + if ($remaining > 0) { + // Only return the amount of requested data, ensuring that the byte + // limit is not exceeded + return $this->stream->read(min($remaining, $length)); + } + + return ''; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MessageTrait.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MessageTrait.php new file mode 100644 index 0000000..9330bcb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MessageTrait.php @@ -0,0 +1,167 @@ +protocol; + } + + public function withProtocolVersion($version) + { + if ($this->protocol === $version) { + return $this; + } + + $new = clone $this; + $new->protocol = $version; + return $new; + } + + public function getHeaders() + { + return $this->headerLines; + } + + public function hasHeader($header) + { + return isset($this->headers[strtolower($header)]); + } + + public function getHeader($header) + { + $name = strtolower($header); + return isset($this->headers[$name]) ? $this->headers[$name] : array(); + } + + public function getHeaderLine($header) + { + return implode(', ', $this->getHeader($header)); + } + + public function withHeader($header, $value) + { + $new = clone $this; + $header = trim($header); + $name = strtolower($header); + + if (!is_array($value)) { + $new->headers[$name] = array(trim($value)); + } else { + $new->headers[$name] = $value; + foreach ($new->headers[$name] as &$v) { + $v = trim($v); + } + } + + // Remove the header lines. + foreach (array_keys($new->headerLines) as $key) { + if (strtolower($key) === $name) { + unset($new->headerLines[$key]); + } + } + + // Add the header line. + $new->headerLines[$header] = $new->headers[$name]; + + return $new; + } + + public function withAddedHeader($header, $value) + { + if (!$this->hasHeader($header)) { + return $this->withHeader($header, $value); + } + + $header = trim($header); + $name = strtolower($header); + + $value = (array) $value; + foreach ($value as &$v) { + $v = trim($v); + } + + $new = clone $this; + $new->headers[$name] = array_merge($new->headers[$name], $value); + $new->headerLines[$header] = array_merge($new->headerLines[$header], $value); + + return $new; + } + + public function withoutHeader($header) + { + if (!$this->hasHeader($header)) { + return $this; + } + + $new = clone $this; + $name = strtolower($header); + unset($new->headers[$name]); + + foreach (array_keys($new->headerLines) as $key) { + if (strtolower($key) === $name) { + unset($new->headerLines[$key]); + } + } + + return $new; + } + + public function getBody() + { + if (!$this->stream) { + $this->stream = stream_for(''); + } + + return $this->stream; + } + + public function withBody(StreamInterface $body) + { + if ($body === $this->stream) { + return $this; + } + + $new = clone $this; + $new->stream = $body; + return $new; + } + + protected function setHeaders(array $headers) + { + $this->headerLines = $this->headers = array(); + foreach ($headers as $header => $value) { + $header = trim($header); + $name = strtolower($header); + if (!is_array($value)) { + $value = trim($value); + $this->headers[$name][] = $value; + $this->headerLines[$header][] = $value; + } else { + foreach ($value as $v) { + $v = trim($v); + $this->headers[$name][] = $v; + $this->headerLines[$header][] = $v; + } + } + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MultipartStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MultipartStream.php new file mode 100644 index 0000000..8c5e5bc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/MultipartStream.php @@ -0,0 +1,152 @@ +boundary = $boundary ?: uniqid(); + parent::__construct($this->createStream($elements)); + } + + /** + * Get the boundary + * + * @return string + */ + public function getBoundary() + { + return $this->boundary; + } + + public function isWritable() + { + return false; + } + + /** + * Get the headers needed before transferring the content of a POST file + */ + private function getHeaders(array $headers) + { + $str = ''; + foreach ($headers as $key => $value) { + $str .= "{$key}: {$value}\r\n"; + } + + return "--{$this->boundary}\r\n" . trim($str) . "\r\n\r\n"; + } + + /** + * Create the aggregate stream that will be used to upload the POST data + */ + protected function createStream(array $elements) + { + $stream = new AppendStream(); + + foreach ($elements as $element) { + $this->addElement($stream, $element); + } + + // Add the trailing boundary with CRLF + $stream->addStream(stream_for("--{$this->boundary}--\r\n")); + + return $stream; + } + + private function addElement(AppendStream $stream, array $element) + { + foreach (array('contents', 'name') as $key) { + if (!array_key_exists($key, $element)) { + throw new \InvalidArgumentException("A '{$key}' key is required"); + } + } + + $element['contents'] = stream_for($element['contents']); + + if (empty($element['filename'])) { + $uri = $element['contents']->getMetadata('uri'); + if (substr($uri, 0, 6) !== 'php://') { + $element['filename'] = $uri; + } + } + + list($body, $headers) = $this->createElement( + $element['name'], + $element['contents'], + isset($element['filename']) ? $element['filename'] : null, + isset($element['headers']) ? $element['headers'] : array() + ); + + $stream->addStream(stream_for($this->getHeaders($headers))); + $stream->addStream($body); + $stream->addStream(stream_for("\r\n")); + } + + /** + * @return array + */ + private function createElement($name, $stream, $filename, array $headers) + { + // Set a default content-disposition header if one was no provided + $disposition = $this->getHeader($headers, 'content-disposition'); + if (!$disposition) { + $headers['Content-Disposition'] = $filename + ? sprintf('form-data; name="%s"; filename="%s"', + $name, + basename($filename)) + : "form-data; name=\"{$name}\""; + } + + // Set a default content-length header if one was no provided + $length = $this->getHeader($headers, 'content-length'); + if (!$length) { + if ($length = $stream->getSize()) { + $headers['Content-Length'] = (string) $length; + } + } + + // Set a default Content-Type if one was not supplied + $type = $this->getHeader($headers, 'content-type'); + if (!$type && $filename) { + if ($type = mimetype_from_filename($filename)) { + $headers['Content-Type'] = $type; + } + } + + return array($stream, $headers); + } + + private function getHeader(array $headers, $key) + { + $lowercaseHeader = strtolower($key); + foreach ($headers as $k => $v) { + if (strtolower($k) === $lowercaseHeader) { + return $v; + } + } + + return null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/NoSeekStream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/NoSeekStream.php new file mode 100644 index 0000000..328fdda --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/NoSeekStream.php @@ -0,0 +1,21 @@ +source = $source; + $this->size = isset($options['size']) ? $options['size'] : null; + $this->metadata = isset($options['metadata']) ? $options['metadata'] : array(); + $this->buffer = new BufferStream(); + } + + public function __toString() + { + try { + return copy_to_string($this); + } catch (\Exception $e) { + return ''; + } + } + + public function close() + { + $this->detach(); + } + + public function detach() + { + $this->tellPos = false; + $this->source = null; + } + + public function getSize() + { + return $this->size; + } + + public function tell() + { + return $this->tellPos; + } + + public function eof() + { + return !$this->source; + } + + public function isSeekable() + { + return false; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + throw new \RuntimeException('Cannot seek a PumpStream'); + } + + public function isWritable() + { + return false; + } + + public function write($string) + { + throw new \RuntimeException('Cannot write to a PumpStream'); + } + + public function isReadable() + { + return true; + } + + public function read($length) + { + $data = $this->buffer->read($length); + $readLen = strlen($data); + $this->tellPos += $readLen; + $remaining = $length - $readLen; + + if ($remaining) { + $this->pump($remaining); + $data .= $this->buffer->read($remaining); + $this->tellPos += strlen($data) - $readLen; + } + + return $data; + } + + public function getContents() + { + $result = ''; + while (!$this->eof()) { + $result .= $this->read(1000000); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!$key) { + return $this->metadata; + } + + return isset($this->metadata[$key]) ? $this->metadata[$key] : null; + } + + private function pump($length) + { + if ($this->source) { + do { + $data = call_user_func($this->source, $length); + if ($data === false || $data === null) { + $this->source = null; + return; + } + $this->buffer->write($data); + $length -= strlen($data); + } while ($length > 0); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Request.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Request.php new file mode 100644 index 0000000..bb0f2fc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Request.php @@ -0,0 +1,146 @@ +method = strtoupper($method); + $this->uri = $uri; + $this->setHeaders($headers); + $this->protocol = $protocolVersion; + + $host = $uri->getHost(); + if ($host && !$this->hasHeader('Host')) { + $this->updateHostFromUri($host); + } + + if ($body) { + $this->stream = stream_for($body); + } + } + + public function getRequestTarget() + { + if ($this->requestTarget !== null) { + return $this->requestTarget; + } + + $target = $this->uri->getPath(); + if ($target == null) { + $target = '/'; + } + if ($this->uri->getQuery()) { + $target .= '?' . $this->uri->getQuery(); + } + + return $target; + } + + public function withRequestTarget($requestTarget) + { + if (preg_match('#\s#', $requestTarget)) { + throw new InvalidArgumentException( + 'Invalid request target provided; cannot contain whitespace' + ); + } + + $new = clone $this; + $new->requestTarget = $requestTarget; + return $new; + } + + public function getMethod() + { + return $this->method; + } + + public function withMethod($method) + { + $new = clone $this; + $new->method = strtoupper($method); + return $new; + } + + public function getUri() + { + return $this->uri; + } + + public function withUri(UriInterface $uri, $preserveHost = false) + { + if ($uri === $this->uri) { + return $this; + } + + $new = clone $this; + $new->uri = $uri; + + if (!$preserveHost) { + if ($host = $uri->getHost()) { + $new->updateHostFromUri($host); + } + } + + return $new; + } + + public function withHeader($header, $value) + { + /** @var Request $newInstance */ + $newInstance = parent::withHeader($header, $value); + return $newInstance; + } + + private function updateHostFromUri($host) + { + // Ensure Host is the first header. + // See: http://tools.ietf.org/html/rfc7230#section-5.4 + if ($port = $this->uri->getPort()) { + $host .= ':' . $port; + } + + $this->headerLines = array('Host' => array($host)) + $this->headerLines; + $this->headers = array('host' => array($host)) + $this->headers; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Response.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Response.php new file mode 100644 index 0000000..a6d9451 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Response.php @@ -0,0 +1,129 @@ + 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-status', + 208 => 'Already Reported', + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 306 => 'Switch Proxy', + 307 => 'Temporary Redirect', + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Time-out', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Request Entity Too Large', + 414 => 'Request-URI Too Large', + 415 => 'Unsupported Media Type', + 416 => 'Requested range not satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', + 422 => 'Unprocessable Entity', + 423 => 'Locked', + 424 => 'Failed Dependency', + 425 => 'Unordered Collection', + 426 => 'Upgrade Required', + 428 => 'Precondition Required', + 429 => 'Too Many Requests', + 431 => 'Request Header Fields Too Large', + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Time-out', + 505 => 'HTTP Version not supported', + 506 => 'Variant Also Negotiates', + 507 => 'Insufficient Storage', + 508 => 'Loop Detected', + 511 => 'Network Authentication Required', + ); + + /** @var null|string */ + private $reasonPhrase = ''; + + /** @var int */ + private $statusCode = 200; + + /** + * @param int $status Status code for the response, if any. + * @param array $headers Headers for the response, if any. + * @param mixed $body Stream body. + * @param string $version Protocol version. + * @param string $reason Reason phrase (a default will be used if possible). + */ + public function __construct( + $status = 200, + array $headers = array(), + $body = null, + $version = '1.1', + $reason = null + ) { + $this->statusCode = (int) $status; + + if ($body !== null) { + $this->stream = stream_for($body); + } + + $this->setHeaders($headers); + if (!$reason && isset(self::$phrases[$this->statusCode])) { + $this->reasonPhrase = self::$phrases[$status]; + } else { + $this->reasonPhrase = (string) $reason; + } + + $this->protocol = $version; + } + + public function getStatusCode() + { + return $this->statusCode; + } + + public function getReasonPhrase() + { + return $this->reasonPhrase; + } + + public function withStatus($code, $reasonPhrase = '') + { + $new = clone $this; + $new->statusCode = (int) $code; + if (!$reasonPhrase && isset(self::$phrases[$new->statusCode])) { + $reasonPhrase = self::$phrases[$new->statusCode]; + } + $new->reasonPhrase = $reasonPhrase; + return $new; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/ServerRequest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/ServerRequest.php new file mode 100644 index 0000000..8408a09 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/ServerRequest.php @@ -0,0 +1,122 @@ +serverParams = $serverParams; + } + + public function getServerParams() + { + return $this->serverParams; + } + + public function getCookieParams() + { + return $this->cookies; + } + + public function withCookieParams(array $cookies) + { + $new = clone $this; + $new->cookies = $cookies; + return $new; + } + + public function getQueryParams() + { + return $this->queryParams; + } + + public function withQueryParams(array $query) + { + $new = clone $this; + $new->queryParams = $query; + return $new; + } + + public function getUploadedFiles() + { + return $this->fileParams; + } + + public function withUploadedFiles(array $uploadedFiles) + { + $new = clone $this; + $new->fileParams = $uploadedFiles; + return $new; + } + + public function getParsedBody() + { + return $this->parsedBody; + } + + public function withParsedBody($data) + { + $new = clone $this; + $new->parsedBody = $data; + return $new; + } + + public function getAttributes() + { + return $this->attributes; + } + + public function getAttribute($name, $default = null) + { + if (!array_key_exists($name, $this->attributes)) { + return $default; + } + return $this->attributes[$name]; + } + + public function withAttribute($name, $value) + { + $new = clone $this; + $new->attributes[$name] = $value; + return $new; + } + + public function withoutAttribute($name) + { + $new = clone $this; + unset($new->attributes[$name]); + return $new; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Stream.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Stream.php new file mode 100644 index 0000000..0a0157c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Stream.php @@ -0,0 +1,245 @@ + array( + 'r' => true, 'w+' => true, 'r+' => true, 'x+' => true, 'c+' => true, + 'rb' => true, 'w+b' => true, 'r+b' => true, 'x+b' => true, + 'c+b' => true, 'rt' => true, 'w+t' => true, 'r+t' => true, + 'x+t' => true, 'c+t' => true, 'a+' => true + ), + 'write' => array( + 'w' => true, 'w+' => true, 'rw' => true, 'r+' => true, 'x+' => true, + 'c+' => true, 'wb' => true, 'w+b' => true, 'r+b' => true, + 'x+b' => true, 'c+b' => true, 'w+t' => true, 'r+t' => true, + 'x+t' => true, 'c+t' => true, 'a' => true, 'a+' => true + ) + ); + + /** + * This constructor accepts an associative array of options. + * + * - size: (int) If a read stream would otherwise have an indeterminate + * size, but the size is known due to foreknownledge, then you can + * provide that size, in bytes. + * - metadata: (array) Any additional metadata to return when the metadata + * of the stream is accessed. + * + * @param resource $stream Stream resource to wrap. + * @param array $options Associative array of options. + * + * @throws \InvalidArgumentException if the stream is not a stream resource + */ + public function __construct($stream, $options = array()) + { + if (!is_resource($stream)) { + throw new \InvalidArgumentException('Stream must be a resource'); + } + + if (isset($options['size'])) { + $this->size = $options['size']; + } + + $this->customMetadata = isset($options['metadata']) + ? $options['metadata'] + : array(); + + $this->stream = $stream; + $meta = stream_get_meta_data($this->stream); + $this->seekable = $meta['seekable']; + $this->readable = isset(self::$readWriteHash['read'][$meta['mode']]); + $this->writable = isset(self::$readWriteHash['write'][$meta['mode']]); + $this->uri = $this->getMetadata('uri'); + } + + public function __get($name) + { + if ($name == 'stream') { + throw new \RuntimeException('The stream is detached'); + } + + throw new \BadMethodCallException('No value for ' . $name); + } + + /** + * Closes the stream when the destructed + */ + public function __destruct() + { + $this->close(); + } + + public function __toString() + { + try { + $this->seek(0); + return (string) stream_get_contents($this->stream); + } catch (\Exception $e) { + return ''; + } + } + + public function getContents() + { + $contents = stream_get_contents($this->stream); + + if ($contents === false) { + throw new \RuntimeException('Unable to read stream contents'); + } + + return $contents; + } + + public function close() + { + if (isset($this->stream)) { + if (is_resource($this->stream)) { + fclose($this->stream); + } + $this->detach(); + } + } + + public function detach() + { + if (!isset($this->stream)) { + return null; + } + + $result = $this->stream; + unset($this->stream); + $this->size = $this->uri = null; + $this->readable = $this->writable = $this->seekable = false; + + return $result; + } + + public function getSize() + { + if ($this->size !== null) { + return $this->size; + } + + if (!isset($this->stream)) { + return null; + } + + // Clear the stat cache if the stream has a URI + if ($this->uri) { + clearstatcache(true, $this->uri); + } + + $stats = fstat($this->stream); + if (isset($stats['size'])) { + $this->size = $stats['size']; + return $this->size; + } + + return null; + } + + public function isReadable() + { + return $this->readable; + } + + public function isWritable() + { + return $this->writable; + } + + public function isSeekable() + { + return $this->seekable; + } + + public function eof() + { + return !$this->stream || feof($this->stream); + } + + public function tell() + { + $result = ftell($this->stream); + + if ($result === false) { + throw new \RuntimeException('Unable to determine stream position'); + } + + return $result; + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + if (!$this->seekable) { + throw new \RuntimeException('Stream is not seekable'); + } elseif (fseek($this->stream, $offset, $whence) === -1) { + throw new \RuntimeException('Unable to seek to stream position ' + . $offset . ' with whence ' . var_export($whence, true)); + } + } + + public function read($length) + { + if (!$this->readable) { + throw new \RuntimeException('Cannot read from non-readable stream'); + } + + return fread($this->stream, $length); + } + + public function write($string) + { + if (!$this->writable) { + throw new \RuntimeException('Cannot write to a non-writable stream'); + } + + // We can't know the size after writing anything + $this->size = null; + $result = fwrite($this->stream, $string); + + if ($result === false) { + throw new \RuntimeException('Unable to write to stream'); + } + + return $result; + } + + public function getMetadata($key = null) + { + if (!isset($this->stream)) { + return $key ? null : array(); + } elseif (!$key) { + return $this->customMetadata + stream_get_meta_data($this->stream); + } elseif (isset($this->customMetadata[$key])) { + return $this->customMetadata[$key]; + } + + $meta = stream_get_meta_data($this->stream); + + return isset($meta[$key]) ? $meta[$key] : null; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamDecoratorTrait.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamDecoratorTrait.php new file mode 100644 index 0000000..e22c674 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamDecoratorTrait.php @@ -0,0 +1,139 @@ +stream = $stream; + } + + /** + * Magic method used to create a new stream if streams are not added in + * the constructor of a decorator (e.g., LazyOpenStream). + * + * @param string $name Name of the property (allows "stream" only). + * + * @return StreamInterface + */ + public function __get($name) + { + if ($name == 'stream') { + $this->stream = $this->createStream(); + return $this->stream; + } + + throw new \UnexpectedValueException("$name not found on class"); + } + + public function __toString() + { + try { + if ($this->isSeekable()) { + $this->seek(0); + } + return $this->getContents(); + } catch (\Exception $e) { + // Really, PHP? https://bugs.php.net/bug.php?id=53648 + trigger_error('StreamDecorator::__toString exception: ' + . (string) $e, E_USER_ERROR); + return ''; + } + } + + public function getContents() + { + return copy_to_string($this); + } + + /** + * Allow decorators to implement custom methods + * + * @param string $method Missing method name + * @param array $args Method arguments + * + * @return mixed + */ + public function __call($method, array $args) + { + $result = call_user_func_array(array($this->stream, $method), $args); + + // Always return the wrapped object if the result is a return $this + return $result === $this->stream ? $this : $result; + } + + public function close() + { + $this->stream->close(); + } + + public function getMetadata($key = null) + { + return $this->stream->getMetadata($key); + } + + public function detach() + { + return $this->stream->detach(); + } + + public function getSize() + { + return $this->stream->getSize(); + } + + public function eof() + { + return $this->stream->eof(); + } + + public function tell() + { + return $this->stream->tell(); + } + + public function isReadable() + { + return $this->stream->isReadable(); + } + + public function isWritable() + { + return $this->stream->isWritable(); + } + + public function isSeekable() + { + return $this->stream->isSeekable(); + } + + public function rewind() + { + $this->seek(0); + } + + public function seek($offset, $whence = SEEK_SET) + { + $this->stream->seek($offset, $whence); + } + + public function read($length) + { + return $this->stream->read($length); + } + + public function write($string) + { + return $this->stream->write($string); + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamWrapper.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamWrapper.php new file mode 100644 index 0000000..8cc07d7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/StreamWrapper.php @@ -0,0 +1,121 @@ +isReadable()) { + $mode = $stream->isWritable() ? 'r+' : 'r'; + } elseif ($stream->isWritable()) { + $mode = 'w'; + } else { + throw new \InvalidArgumentException('The stream must be readable, ' + . 'writable, or both.'); + } + + return fopen('guzzle://stream', $mode, null, stream_context_create(array( + 'guzzle' => array('stream' => $stream) + ))); + } + + /** + * Registers the stream wrapper if needed + */ + public static function register() + { + if (!in_array('guzzle', stream_get_wrappers())) { + stream_wrapper_register('guzzle', __CLASS__); + } + } + + public function stream_open($path, $mode, $options, &$opened_path) + { + $options = stream_context_get_options($this->context); + + if (!isset($options['guzzle']['stream'])) { + return false; + } + + $this->mode = $mode; + $this->stream = $options['guzzle']['stream']; + + return true; + } + + public function stream_read($count) + { + return $this->stream->read($count); + } + + public function stream_write($data) + { + return (int) $this->stream->write($data); + } + + public function stream_tell() + { + return $this->stream->tell(); + } + + public function stream_eof() + { + return $this->stream->eof(); + } + + public function stream_seek($offset, $whence) + { + $this->stream->seek($offset, $whence); + + return true; + } + + public function stream_stat() + { + static $modeMap = array( + 'r' => 33060, + 'r+' => 33206, + 'w' => 33188 + ); + + return array( + 'dev' => 0, + 'ino' => 0, + 'mode' => $modeMap[$this->mode], + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => $this->stream->getSize() ?: 0, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0 + ); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Uri.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Uri.php new file mode 100644 index 0000000..5323cdc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/Uri.php @@ -0,0 +1,601 @@ + 80, + 'https' => 443, + ); + + private static $charUnreserved = 'a-zA-Z0-9_\-\.~'; + private static $charSubDelims = '!\$&\'\(\)\*\+,;='; + private static $replaceQuery = array('=' => '%3D', '&' => '%26'); + + /** @var string Uri scheme. */ + private $scheme = ''; + + /** @var string Uri user info. */ + private $userInfo = ''; + + /** @var string Uri host. */ + private $host = ''; + + /** @var int|null Uri port. */ + private $port; + + /** @var string Uri path. */ + private $path = ''; + + /** @var string Uri query string. */ + private $query = ''; + + /** @var string Uri fragment. */ + private $fragment = ''; + + /** + * @param string $uri URI to parse and wrap. + */ + public function __construct($uri = '') + { + if ($uri != null) { + $parts = parse_url($uri); + if ($parts === false) { + throw new \InvalidArgumentException("Unable to parse URI: $uri"); + } + $this->applyParts($parts); + } + } + + public function __toString() + { + return self::createUriString( + $this->scheme, + $this->getAuthority(), + $this->getPath(), + $this->query, + $this->fragment + ); + } + + /** + * Removes dot segments from a path and returns the new path. + * + * @param string $path + * + * @return string + * @link http://tools.ietf.org/html/rfc3986#section-5.2.4 + */ + public static function removeDotSegments($path) + { + static $noopPaths = array('' => true, '/' => true, '*' => true); + static $ignoreSegments = array('.' => true, '..' => true); + + if (isset($noopPaths[$path])) { + return $path; + } + + $results = array(); + $segments = explode('/', $path); + foreach ($segments as $segment) { + if ($segment == '..') { + array_pop($results); + } elseif (!isset($ignoreSegments[$segment])) { + $results[] = $segment; + } + } + + $newPath = implode('/', $results); + // Add the leading slash if necessary + if (substr($path, 0, 1) === '/' && + substr($newPath, 0, 1) !== '/' + ) { + $newPath = '/' . $newPath; + } + + // Add the trailing slash if necessary + if ($newPath != '/' && isset($ignoreSegments[end($segments)])) { + $newPath .= '/'; + } + + return $newPath; + } + + /** + * Resolve a base URI with a relative URI and return a new URI. + * + * @param UriInterface $base Base URI + * @param string $rel Relative URI + * + * @return UriInterface + */ + public static function resolve(UriInterface $base, $rel) + { + if ($rel === null || $rel === '') { + return $base; + } + + if (!($rel instanceof UriInterface)) { + $rel = new self($rel); + } + + // Return the relative uri as-is if it has a scheme. + if ($rel->getScheme()) { + return $rel->withPath(static::removeDotSegments($rel->getPath())); + } + + $relParts = array( + 'scheme' => $rel->getScheme(), + 'authority' => $rel->getAuthority(), + 'path' => $rel->getPath(), + 'query' => $rel->getQuery(), + 'fragment' => $rel->getFragment() + ); + + $parts = array( + 'scheme' => $base->getScheme(), + 'authority' => $base->getAuthority(), + 'path' => $base->getPath(), + 'query' => $base->getQuery(), + 'fragment' => $base->getFragment() + ); + + if (!empty($relParts['authority'])) { + $parts['authority'] = $relParts['authority']; + $parts['path'] = self::removeDotSegments($relParts['path']); + $parts['query'] = $relParts['query']; + $parts['fragment'] = $relParts['fragment']; + } elseif (!empty($relParts['path'])) { + if (substr($relParts['path'], 0, 1) == '/') { + $parts['path'] = self::removeDotSegments($relParts['path']); + $parts['query'] = $relParts['query']; + $parts['fragment'] = $relParts['fragment']; + } else { + if (!empty($parts['authority']) && empty($parts['path'])) { + $mergedPath = '/'; + } else { + $mergedPath = substr($parts['path'], 0, strrpos($parts['path'], '/') + 1); + } + $parts['path'] = self::removeDotSegments($mergedPath . $relParts['path']); + $parts['query'] = $relParts['query']; + $parts['fragment'] = $relParts['fragment']; + } + } elseif (!empty($relParts['query'])) { + $parts['query'] = $relParts['query']; + } elseif ($relParts['fragment'] != null) { + $parts['fragment'] = $relParts['fragment']; + } + + return new self(static::createUriString( + $parts['scheme'], + $parts['authority'], + $parts['path'], + $parts['query'], + $parts['fragment'] + )); + } + + /** + * Create a new URI with a specific query string value removed. + * + * Any existing query string values that exactly match the provided key are + * removed. + * + * Note: this function will convert "=" to "%3D" and "&" to "%26". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Query string key value pair to remove. + * + * @return UriInterface + */ + public static function withoutQueryValue(UriInterface $uri, $key) + { + $current = $uri->getQuery(); + if (!$current) { + return $uri; + } + + $result = array(); + foreach (explode('&', $current) as $part) { + $subParts = explode('=', $part); + if ($subParts[0] !== $key) { + $result[] = $part; + }; + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Create a new URI with a specific query string value. + * + * Any existing query string values that exactly match the provided key are + * removed and replaced with the given key value pair. + * + * Note: this function will convert "=" to "%3D" and "&" to "%26". + * + * @param UriInterface $uri URI to use as a base. + * @param string $key Key to set. + * @param string $value Value to set. + * + * @return UriInterface + */ + public static function withQueryValue(UriInterface $uri, $key, $value) + { + $current = $uri->getQuery(); + $key = strtr($key, self::$replaceQuery); + + if (!$current) { + $result = array(); + } else { + $result = array(); + foreach (explode('&', $current) as $part) { + $subParts = explode('=', $part); + if ($subParts[0] !== $key) { + $result[] = $part; + }; + } + } + + if ($value !== null) { + $result[] = $key . '=' . strtr($value, self::$replaceQuery); + } else { + $result[] = $key; + } + + return $uri->withQuery(implode('&', $result)); + } + + /** + * Create a URI from a hash of parse_url parts. + * + * @param array $parts + * + * @return self + */ + public static function fromParts(array $parts) + { + $uri = new self(); + $uri->applyParts($parts); + return $uri; + } + + public function getScheme() + { + return $this->scheme; + } + + public function getAuthority() + { + if (empty($this->host)) { + return ''; + } + + $authority = $this->host; + if (!empty($this->userInfo)) { + $authority = $this->userInfo . '@' . $authority; + } + + if ($this->isNonStandardPort($this->scheme, $this->host, $this->port)) { + $authority .= ':' . $this->port; + } + + return $authority; + } + + public function getUserInfo() + { + return $this->userInfo; + } + + public function getHost() + { + return $this->host; + } + + public function getPort() + { + return $this->port; + } + + public function getPath() + { + return $this->path == null ? '' : $this->path; + } + + public function getQuery() + { + return $this->query; + } + + public function getFragment() + { + return $this->fragment; + } + + public function withScheme($scheme) + { + $scheme = $this->filterScheme($scheme); + + if ($this->scheme === $scheme) { + return $this; + } + + $new = clone $this; + $new->scheme = $scheme; + $new->port = $new->filterPort($new->scheme, $new->host, $new->port); + return $new; + } + + public function withUserInfo($user, $password = null) + { + $info = $user; + if ($password) { + $info .= ':' . $password; + } + + if ($this->userInfo === $info) { + return $this; + } + + $new = clone $this; + $new->userInfo = $info; + return $new; + } + + public function withHost($host) + { + if ($this->host === $host) { + return $this; + } + + $new = clone $this; + $new->host = $host; + return $new; + } + + public function withPort($port) + { + $port = $this->filterPort($this->scheme, $this->host, $port); + + if ($this->port === $port) { + return $this; + } + + $new = clone $this; + $new->port = $port; + return $new; + } + + public function withPath($path) + { + if (!is_string($path)) { + throw new \InvalidArgumentException( + 'Invalid path provided; must be a string' + ); + } + + $path = $this->filterPath($path); + + if ($this->path === $path) { + return $this; + } + + $new = clone $this; + $new->path = $path; + return $new; + } + + public function withQuery($query) + { + if (!is_string($query) && !method_exists($query, '__toString')) { + throw new \InvalidArgumentException( + 'Query string must be a string' + ); + } + + $query = (string) $query; + if (substr($query, 0, 1) === '?') { + $query = substr($query, 1); + } + + $query = $this->filterQueryAndFragment($query); + + if ($this->query === $query) { + return $this; + } + + $new = clone $this; + $new->query = $query; + return $new; + } + + public function withFragment($fragment) + { + if (substr($fragment, 0, 1) === '#') { + $fragment = substr($fragment, 1); + } + + $fragment = $this->filterQueryAndFragment($fragment); + + if ($this->fragment === $fragment) { + return $this; + } + + $new = clone $this; + $new->fragment = $fragment; + return $new; + } + + /** + * Apply parse_url parts to a URI. + * + * @param $parts Array of parse_url parts to apply. + */ + private function applyParts(array $parts) + { + $this->scheme = isset($parts['scheme']) + ? $this->filterScheme($parts['scheme']) + : ''; + $this->userInfo = isset($parts['user']) ? $parts['user'] : ''; + $this->host = isset($parts['host']) ? $parts['host'] : ''; + $this->port = !empty($parts['port']) + ? $this->filterPort($this->scheme, $this->host, $parts['port']) + : null; + $this->path = isset($parts['path']) + ? $this->filterPath($parts['path']) + : ''; + $this->query = isset($parts['query']) + ? $this->filterQueryAndFragment($parts['query']) + : ''; + $this->fragment = isset($parts['fragment']) + ? $this->filterQueryAndFragment($parts['fragment']) + : ''; + if (isset($parts['pass'])) { + $this->userInfo .= ':' . $parts['pass']; + } + } + + /** + * Create a URI string from its various parts + * + * @param string $scheme + * @param string $authority + * @param string $path + * @param string $query + * @param string $fragment + * @return string + */ + private static function createUriString($scheme, $authority, $path, $query, $fragment) + { + $uri = ''; + + if (!empty($scheme)) { + $uri .= $scheme . '://'; + } + + if (!empty($authority)) { + $uri .= $authority; + } + + if ($path != null) { + // Add a leading slash if necessary. + if ($uri && substr($path, 0, 1) !== '/') { + $uri .= '/'; + } + $uri .= $path; + } + + if ($query != null) { + $uri .= '?' . $query; + } + + if ($fragment != null) { + $uri .= '#' . $fragment; + } + + return $uri; + } + + /** + * Is a given port non-standard for the current scheme? + * + * @param string $scheme + * @param string $host + * @param int $port + * @return bool + */ + private static function isNonStandardPort($scheme, $host, $port) + { + if (!$scheme && $port) { + return true; + } + + if (!$host || !$port) { + return false; + } + + return !isset(static::$schemes[$scheme]) || $port !== static::$schemes[$scheme]; + } + + /** + * @param string $scheme + * + * @return string + */ + private function filterScheme($scheme) + { + $scheme = strtolower($scheme); + $scheme = rtrim($scheme, ':/'); + + return $scheme; + } + + /** + * @param string $scheme + * @param string $host + * @param int $port + * + * @return int|null + * + * @throws \InvalidArgumentException If the port is invalid. + */ + private function filterPort($scheme, $host, $port) + { + if (null !== $port) { + $port = (int) $port; + if (1 > $port || 0xffff < $port) { + throw new \InvalidArgumentException( + sprintf('Invalid port: %d. Must be between 1 and 65535', $port) + ); + } + } + + return $this->isNonStandardPort($scheme, $host, $port) ? $port : null; + } + + /** + * Filters the path of a URI + * + * @param $path + * + * @return string + */ + private function filterPath($path) + { + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . ':@\/%]+|%(?![A-Fa-f0-9]{2}))/', + array($this, 'rawurlencodeMatchZero'), + $path + ); + } + + /** + * Filters the query string or fragment of a URI. + * + * @param $str + * + * @return string + */ + private function filterQueryAndFragment($str) + { + return preg_replace_callback( + '/(?:[^' . self::$charUnreserved . self::$charSubDelims . '%:@\/\?]+|%(?![A-Fa-f0-9]{2}))/', + array($this, 'rawurlencodeMatchZero'), + $str + ); + } + + private function rawurlencodeMatchZero(array $match) + { + return rawurlencode($match[0]); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions.php new file mode 100644 index 0000000..3c4c549 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions.php @@ -0,0 +1,835 @@ +getMethod() . ' ' + . $message->getRequestTarget()) + . ' HTTP/' . $message->getProtocolVersion(); + if (!$message->hasHeader('host')) { + $msg .= "\r\nHost: " . $message->getUri()->getHost(); + } + } elseif ($message instanceof ResponseInterface) { + $msg = 'HTTP/' . $message->getProtocolVersion() . ' ' + . $message->getStatusCode() . ' ' + . $message->getReasonPhrase(); + } else { + throw new \InvalidArgumentException('Unknown message type'); + } + + foreach ($message->getHeaders() as $name => $values) { + $msg .= "\r\n{$name}: " . implode(', ', $values); + } + + return "{$msg}\r\n\r\n" . $message->getBody(); +} + +/** + * Returns a UriInterface for the given value. + * + * This function accepts a string or {@see Psr\Http\Message\UriInterface} and + * returns a UriInterface for the given value. If the value is already a + * `UriInterface`, it is returned as-is. + * + * @param string|UriInterface $uri + * + * @return UriInterface + * @throws \InvalidArgumentException + */ +function uri_for($uri) +{ + if ($uri instanceof UriInterface) { + return $uri; + } elseif (is_string($uri)) { + return new Uri($uri); + } + + throw new \InvalidArgumentException('URI must be a string or UriInterface'); +} + +/** + * Create a new stream based on the input type. + * + * Options is an associative array that can contain the following keys: + * - metadata: Array of custom metadata. + * - size: Size of the stream. + * + * @param resource|string|StreamInterface $resource Entity body data + * @param array $options Additional options + * + * @return Stream + * @throws \InvalidArgumentException if the $resource arg is not valid. + */ +function stream_for($resource = '', array $options = array()) +{ + switch (gettype($resource)) { + case 'string': + $stream = fopen('php://temp', 'r+'); + if ($resource !== '') { + fwrite($stream, $resource); + fseek($stream, 0); + } + return new Stream($stream, $options); + case 'resource': + return new Stream($resource, $options); + case 'object': + if ($resource instanceof StreamInterface) { + return $resource; + } elseif ($resource instanceof \Iterator) { + return new PumpStream(function () use ($resource) { + if (!$resource->valid()) { + return false; + } + $result = $resource->current(); + $resource->next(); + return $result; + }, $options); + } elseif (method_exists($resource, '__toString')) { + return stream_for((string) $resource, $options); + } + break; + case 'NULL': + return new Stream(fopen('php://temp', 'r+'), $options); + } + + if (is_callable($resource)) { + return new PumpStream($resource, $options); + } + + throw new \InvalidArgumentException('Invalid resource type: ' . gettype($resource)); +} + +/** + * Parse an array of header values containing ";" separated data into an + * array of associative arrays representing the header key value pair + * data of the header. When a parameter does not contain a value, but just + * contains a key, this function will inject a key with a '' string value. + * + * @param string|array $header Header to parse into components. + * + * @return array Returns the parsed header values. + */ +function parse_header($header) +{ + static $trimmed = "\"' \n\t\r"; + $params = $matches = array(); + + foreach (normalize_header($header) as $val) { + $part = array(); + foreach (preg_split('/;(?=([^"]*"[^"]*")*[^"]*$)/', $val) as $kvp) { + if (preg_match_all('/<[^>]+>|[^=]+/', $kvp, $matches)) { + $m = $matches[0]; + if (isset($m[1])) { + $part[trim($m[0], $trimmed)] = trim($m[1], $trimmed); + } else { + $part[] = trim($m[0], $trimmed); + } + } + } + if ($part) { + $params[] = $part; + } + } + + return $params; +} + +/** + * Converts an array of header values that may contain comma separated + * headers into an array of headers with no comma separated values. + * + * @param string|array $header Header to normalize. + * + * @return array Returns the normalized header field values. + */ +function normalize_header($header) +{ + if (!is_array($header)) { + return array_map('trim', explode(',', $header)); + } + + $result = array(); + foreach ($header as $value) { + foreach ((array) $value as $v) { + if (strpos($v, ',') === false) { + $result[] = $v; + continue; + } + foreach (preg_split('/,(?=([^"]*"[^"]*")*[^"]*$)/', $v) as $vv) { + $result[] = trim($vv); + } + } + } + + return $result; +} + +/** + * Clone and modify a request with the given changes. + * + * The changes can be one of: + * - method: (string) Changes the HTTP method. + * - set_headers: (array) Sets the given headers. + * - remove_headers: (array) Remove the given headers. + * - body: (mixed) Sets the given body. + * - uri: (UriInterface) Set the URI. + * - query: (string) Set the query string value of the URI. + * - version: (string) Set the protocol version. + * + * @param RequestInterface $request Request to clone and modify. + * @param array $changes Changes to apply. + * + * @return RequestInterface + */ +function modify_request(RequestInterface $request, array $changes) +{ + if (!$changes) { + return $request; + } + + $headers = $request->getHeaders(); + + if (!isset($changes['uri'])) { + $uri = $request->getUri(); + } else { + // Remove the host header if one is on the URI + if ($host = $changes['uri']->getHost()) { + $changes['set_headers']['Host'] = $host; + } + $uri = $changes['uri']; + } + + if (!empty($changes['remove_headers'])) { + $headers = _caseless_remove($changes['remove_headers'], $headers); + } + + if (!empty($changes['set_headers'])) { + $headers = _caseless_remove(array_keys($changes['set_headers']), $headers); + $headers = $changes['set_headers'] + $headers; + } + + if (isset($changes['query'])) { + $uri = $uri->withQuery($changes['query']); + } + + return new Request( + isset($changes['method']) ? $changes['method'] : $request->getMethod(), + $uri, + $headers, + isset($changes['body']) ? $changes['body'] : $request->getBody(), + isset($changes['version']) + ? $changes['version'] + : $request->getProtocolVersion() + ); +} + +/** + * Attempts to rewind a message body and throws an exception on failure. + * + * The body of the message will only be rewound if a call to `tell()` returns a + * value other than `0`. + * + * @param MessageInterface $message Message to rewind + * + * @throws \RuntimeException + */ +function rewind_body(MessageInterface $message) +{ + $body = $message->getBody(); + + if ($body->tell()) { + $body->rewind(); + } +} + +/** + * Safely opens a PHP stream resource using a filename. + * + * When fopen fails, PHP normally raises a warning. This function adds an + * error handler that checks for errors and throws an exception instead. + * + * @param string $filename File to open + * @param string $mode Mode used to open the file + * + * @return resource + * @throws \RuntimeException if the file cannot be opened + */ +function try_fopen($filename, $mode) +{ + $ex = null; + $fargs = func_get_args(); + set_error_handler(function () use ($filename, $mode, &$ex, $fargs) { + $ex = new \RuntimeException(sprintf( + 'Unable to open %s using mode %s: %s', + $filename, + $mode, + $fargs[1] + )); + }); + + $handle = fopen($filename, $mode); + restore_error_handler(); + + if ($ex) { + /** @var $ex \RuntimeException */ + throw $ex; + } + + return $handle; +} + +/** + * Copy the contents of a stream into a string until the given number of + * bytes have been read. + * + * @param StreamInterface $stream Stream to read + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * @return string + * @throws \RuntimeException on error. + */ +function copy_to_string(StreamInterface $stream, $maxLen = -1) +{ + $buffer = ''; + + if ($maxLen === -1) { + while (!$stream->eof()) { + $buf = $stream->read(1048576); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + } + return $buffer; + } + + $len = 0; + while (!$stream->eof() && $len < $maxLen) { + $buf = $stream->read($maxLen - $len); + // Using a loose equality here to match on '' and false. + if ($buf == null) { + break; + } + $buffer .= $buf; + $len = strlen($buffer); + } + + return $buffer; +} + +/** + * Copy the contents of a stream into another stream until the given number + * of bytes have been read. + * + * @param StreamInterface $source Stream to read from + * @param StreamInterface $dest Stream to write to + * @param int $maxLen Maximum number of bytes to read. Pass -1 + * to read the entire stream. + * + * @throws \RuntimeException on error. + */ +function copy_to_stream( + StreamInterface $source, + StreamInterface $dest, + $maxLen = -1 +) { + if ($maxLen === -1) { + while (!$source->eof()) { + if (!$dest->write($source->read(1048576))) { + break; + } + } + return; + } + + $bytes = 0; + while (!$source->eof()) { + $buf = $source->read($maxLen - $bytes); + if (!($len = strlen($buf))) { + break; + } + $bytes += $len; + $dest->write($buf); + if ($bytes == $maxLen) { + break; + } + } +} + +/** + * Calculate a hash of a Stream + * + * @param StreamInterface $stream Stream to calculate the hash for + * @param string $algo Hash algorithm (e.g. md5, crc32, etc) + * @param bool $rawOutput Whether or not to use raw output + * + * @return string Returns the hash of the stream + * @throws \RuntimeException on error. + */ +function hash( + StreamInterface $stream, + $algo, + $rawOutput = false +) { + $pos = $stream->tell(); + + if ($pos > 0) { + $stream->rewind(); + } + + $ctx = hash_init($algo); + while (!$stream->eof()) { + hash_update($ctx, $stream->read(1048576)); + } + + $out = hash_final($ctx, (bool) $rawOutput); + $stream->seek($pos); + + return $out; +} + +/** + * Read a line from the stream up to the maximum allowed buffer length + * + * @param StreamInterface $stream Stream to read from + * @param int $maxLength Maximum buffer length + * + * @return string|bool + */ +function readline(StreamInterface $stream, $maxLength = null) +{ + $buffer = ''; + $size = 0; + + while (!$stream->eof()) { + // Using a loose equality here to match on '' and false. + if (null == ($byte = $stream->read(1))) { + return $buffer; + } + $buffer .= $byte; + // Break when a new line is found or the max length - 1 is reached + if ($byte == PHP_EOL || ++$size == $maxLength - 1) { + break; + } + } + + return $buffer; +} + +/** + * Parses a request message string into a request object. + * + * @param string $message Request message string. + * + * @return Request + */ +function parse_request($message) +{ + $data = _parse_message($message); + $matches = array(); + if (!preg_match('/^[a-zA-Z]+\s+([a-zA-Z]+:\/\/|\/).*/', $data['start-line'], $matches)) { + throw new \InvalidArgumentException('Invalid request string'); + } + $parts = explode(' ', $data['start-line'], 3); + $subParts = isset($parts[2]) ? explode('/', $parts[2]) : array(); + $version = isset($parts[2]) ? $subParts[1] : '1.1'; + + $request = new Request( + $parts[0], + $matches[1] === '/' ? _parse_request_uri($parts[1], $data['headers']) : $parts[1], + $data['headers'], + $data['body'], + $version + ); + + return $matches[1] === '/' ? $request : $request->withRequestTarget($parts[1]); +} + +/** + * Parses a request message string into a server request object. + * + * @param string $message Request message string. + * @param array $serverParams Server params that will be added to the + * ServerRequest object + * + * @return ServerRequest + */ +function parse_server_request($message, array $serverParams = array()) +{ + $request = parse_request($message); + + return new ServerRequest( + $request->getMethod(), + $request->getUri(), + $request->getHeaders(), + $request->getBody(), + $request->getProtocolVersion(), + $serverParams + ); +} + +/** + * Parses a response message string into a response object. + * + * @param string $message Response message string. + * + * @return Response + */ +function parse_response($message) +{ + $data = _parse_message($message); + // According to https://tools.ietf.org/html/rfc7230#section-3.1.2 the space + // between status-code and reason-phrase is required. But browsers accept + // responses without space and reason as well. + if (!preg_match('/^HTTP\/.* [0-9]{3}( .*|$)/', $data['start-line'])) { + throw new \InvalidArgumentException('Invalid response string'); + } + $parts = explode(' ', $data['start-line'], 3); + $subParts = explode('/', $parts[0]); + + return new Response( + $parts[1], + $data['headers'], + $data['body'], + $subParts[1], + isset($parts[2]) ? $parts[2] : null + ); +} + +/** + * Parse a query string into an associative array. + * + * If multiple values are found for the same key, the value of that key + * value pair will become an array. This function does not parse nested + * PHP style arrays into an associative array (e.g., foo[a]=1&foo[b]=2 will + * be parsed into ['foo[a]' => '1', 'foo[b]' => '2']). + * + * @param string $str Query string to parse + * @param bool|string $urlEncoding How the query string is encoded + * + * @return array + */ +function parse_query($str, $urlEncoding = true) +{ + $result = array(); + + if ($str === '') { + return $result; + } + + if ($urlEncoding === true) { + $decoder = function ($value) { + return rawurldecode(str_replace('+', ' ', $value)); + }; + } elseif ($urlEncoding == PHP_QUERY_RFC3986) { + $decoder = 'rawurldecode'; + } elseif ($urlEncoding == PHP_QUERY_RFC1738) { + $decoder = 'urldecode'; + } else { + $decoder = function ($str) { return $str; }; + } + + foreach (explode('&', $str) as $kvp) { + $parts = explode('=', $kvp, 2); + $key = $decoder($parts[0]); + $value = isset($parts[1]) ? $decoder($parts[1]) : null; + if (!isset($result[$key])) { + $result[$key] = $value; + } else { + if (!is_array($result[$key])) { + $result[$key] = array($result[$key]); + } + $result[$key][] = $value; + } + } + + return $result; +} + +/** + * Build a query string from an array of key value pairs. + * + * This function can use the return value of parseQuery() to build a query + * string. This function does not modify the provided keys when an array is + * encountered (like http_build_query would). + * + * @param array $params Query string parameters. + * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986 + * to encode using RFC3986, or PHP_QUERY_RFC1738 + * to encode using RFC1738. + * @return string + */ +function build_query(array $params, $encoding = PHP_QUERY_RFC3986) +{ + if (!$params) { + return ''; + } + + if ($encoding === false) { + $encoder = function ($str) { return $str; }; + } elseif ($encoding == PHP_QUERY_RFC3986) { + $encoder = 'rawurlencode'; + } elseif ($encoding == PHP_QUERY_RFC1738) { + $encoder = 'urlencode'; + } else { + throw new \InvalidArgumentException('Invalid type'); + } + + $qs = ''; + foreach ($params as $k => $v) { + $k = $encoder($k); + if (!is_array($v)) { + $qs .= $k; + if ($v !== null) { + $qs .= '=' . $encoder($v); + } + $qs .= '&'; + } else { + foreach ($v as $vv) { + $qs .= $k; + if ($vv !== null) { + $qs .= '=' . $encoder($vv); + } + $qs .= '&'; + } + } + } + + return $qs ? (string) substr($qs, 0, -1) : ''; +} + +/** + * Determines the mimetype of a file by looking at its extension. + * + * @param $filename + * + * @return null|string + */ +function mimetype_from_filename($filename) +{ + return mimetype_from_extension(pathinfo($filename, PATHINFO_EXTENSION)); +} + +/** + * Maps a file extensions to a mimetype. + * + * @param $extension string The file extension. + * + * @return string|null + * @link http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types + */ +function mimetype_from_extension($extension) +{ + static $mimetypes = array( + '7z' => 'application/x-7z-compressed', + 'aac' => 'audio/x-aac', + 'ai' => 'application/postscript', + 'aif' => 'audio/x-aiff', + 'asc' => 'text/plain', + 'asf' => 'video/x-ms-asf', + 'atom' => 'application/atom+xml', + 'avi' => 'video/x-msvideo', + 'bmp' => 'image/bmp', + 'bz2' => 'application/x-bzip2', + 'cer' => 'application/pkix-cert', + 'crl' => 'application/pkix-crl', + 'crt' => 'application/x-x509-ca-cert', + 'css' => 'text/css', + 'csv' => 'text/csv', + 'cu' => 'application/cu-seeme', + 'deb' => 'application/x-debian-package', + 'doc' => 'application/msword', + 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'dvi' => 'application/x-dvi', + 'eot' => 'application/vnd.ms-fontobject', + 'eps' => 'application/postscript', + 'epub' => 'application/epub+zip', + 'etx' => 'text/x-setext', + 'flac' => 'audio/flac', + 'flv' => 'video/x-flv', + 'gif' => 'image/gif', + 'gz' => 'application/gzip', + 'htm' => 'text/html', + 'html' => 'text/html', + 'ico' => 'image/x-icon', + 'ics' => 'text/calendar', + 'ini' => 'text/plain', + 'iso' => 'application/x-iso9660-image', + 'jar' => 'application/java-archive', + 'jpe' => 'image/jpeg', + 'jpeg' => 'image/jpeg', + 'jpg' => 'image/jpeg', + 'js' => 'text/javascript', + 'json' => 'application/json', + 'latex' => 'application/x-latex', + 'log' => 'text/plain', + 'm4a' => 'audio/mp4', + 'm4v' => 'video/mp4', + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mov' => 'video/quicktime', + 'mp3' => 'audio/mpeg', + 'mp4' => 'video/mp4', + 'mp4a' => 'audio/mp4', + 'mp4v' => 'video/mp4', + 'mpe' => 'video/mpeg', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpg4' => 'video/mp4', + 'oga' => 'audio/ogg', + 'ogg' => 'audio/ogg', + 'ogv' => 'video/ogg', + 'ogx' => 'application/ogg', + 'pbm' => 'image/x-portable-bitmap', + 'pdf' => 'application/pdf', + 'pgm' => 'image/x-portable-graymap', + 'png' => 'image/png', + 'pnm' => 'image/x-portable-anymap', + 'ppm' => 'image/x-portable-pixmap', + 'ppt' => 'application/vnd.ms-powerpoint', + 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'ps' => 'application/postscript', + 'qt' => 'video/quicktime', + 'rar' => 'application/x-rar-compressed', + 'ras' => 'image/x-cmu-raster', + 'rss' => 'application/rss+xml', + 'rtf' => 'application/rtf', + 'sgm' => 'text/sgml', + 'sgml' => 'text/sgml', + 'svg' => 'image/svg+xml', + 'swf' => 'application/x-shockwave-flash', + 'tar' => 'application/x-tar', + 'tif' => 'image/tiff', + 'tiff' => 'image/tiff', + 'torrent' => 'application/x-bittorrent', + 'ttf' => 'application/x-font-ttf', + 'txt' => 'text/plain', + 'wav' => 'audio/x-wav', + 'webm' => 'video/webm', + 'wma' => 'audio/x-ms-wma', + 'wmv' => 'video/x-ms-wmv', + 'woff' => 'application/x-font-woff', + 'wsdl' => 'application/wsdl+xml', + 'xbm' => 'image/x-xbitmap', + 'xls' => 'application/vnd.ms-excel', + 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'xml' => 'application/xml', + 'xpm' => 'image/x-xpixmap', + 'xwd' => 'image/x-xwindowdump', + 'yaml' => 'text/yaml', + 'yml' => 'text/yaml', + 'zip' => 'application/zip', + ); + + $extension = strtolower($extension); + + return isset($mimetypes[$extension]) + ? $mimetypes[$extension] + : null; +} + +/** + * Parses an HTTP message into an associative array. + * + * The array contains the "start-line" key containing the start line of + * the message, "headers" key containing an associative array of header + * array values, and a "body" key containing the body of the message. + * + * @param string $message HTTP request or response to parse. + * + * @return array + * @internal + */ +function _parse_message($message) +{ + if (!$message) { + throw new \InvalidArgumentException('Invalid message'); + } + + // Iterate over each line in the message, accounting for line endings + $lines = preg_split('/(\\r?\\n)/', $message, -1, PREG_SPLIT_DELIM_CAPTURE); + $result = array('start-line' => array_shift($lines), 'headers' => array(), 'body' => ''); + array_shift($lines); + + for ($i = 0, $totalLines = count($lines); $i < $totalLines; $i += 2) { + $line = $lines[$i]; + // If two line breaks were encountered, then this is the end of body + if (empty($line)) { + if ($i < $totalLines - 1) { + $result['body'] = implode('', array_slice($lines, $i + 2)); + } + break; + } + if (strpos($line, ':')) { + $parts = explode(':', $line, 2); + $key = trim($parts[0]); + $value = isset($parts[1]) ? trim($parts[1]) : ''; + $result['headers'][$key][] = $value; + } + } + + return $result; +} + +/** + * Constructs a URI for an HTTP request message. + * + * @param string $path Path from the start-line + * @param array $headers Array of headers (each value an array). + * + * @return string + * @internal + */ +function _parse_request_uri($path, array $headers) +{ + $hostKey = array_filter(array_keys($headers), function ($k) { + return strtolower($k) === 'host'; + }); + + // If no host is found, then a full URI cannot be constructed. + if (!$hostKey) { + return $path; + } + + $host = $headers[reset($hostKey)][0]; + $scheme = substr($host, -4) === ':443' ? 'https' : 'http'; + + return $scheme . '://' . $host . '/' . ltrim($path, '/'); +} + +/** @internal */ +function _caseless_remove($keys, array $data) +{ + $result = array(); + + foreach ($keys as &$key) { + $key = strtolower($key); + } + + foreach ($data as $k => $v) { + if (!in_array(strtolower($k), $keys)) { + $result[$k] = $v; + } + } + + return $result; +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions_include.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions_include.php new file mode 100644 index 0000000..252e0cf --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/src/functions_include.php @@ -0,0 +1,6 @@ +getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isReadable')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(false)); + $a->addStream($s); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage The AppendStream can only seek with SEEK_SET + */ + public function testValidatesSeekType() + { + $a = new AppendStream(); + $a->seek(100, SEEK_CUR); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Unable to seek stream 0 of the AppendStream + */ + public function testTriesToRewindOnSeek() + { + $a = new AppendStream(); + $s = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isReadable', 'rewind', 'isSeekable')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(true)); + $s->expects($this->once()) + ->method('isSeekable') + ->will($this->returnValue(true)); + $s->expects($this->once()) + ->method('rewind') + ->will($this->throwException(new \RuntimeException())); + $a->addStream($s); + $a->seek(10); + } + + public function testSeeksToPositionByReading() + { + $a = new AppendStream(array( + Psr7\stream_for('foo'), + Psr7\stream_for('bar'), + Psr7\stream_for('baz'), + )); + + $a->seek(3); + $this->assertEquals(3, $a->tell()); + $this->assertEquals('bar', $a->read(3)); + + $a->seek(6); + $this->assertEquals(6, $a->tell()); + $this->assertEquals('baz', $a->read(3)); + } + + public function testDetachesEachStream() + { + $s1 = Psr7\stream_for('foo'); + $s2 = Psr7\stream_for('bar'); + $a = new AppendStream(array($s1, $s2)); + $this->assertSame('foobar', (string) $a); + $a->detach(); + $this->assertSame('', (string) $a); + $this->assertSame(0, $a->getSize()); + } + + public function testClosesEachStream() + { + $s1 = Psr7\stream_for('foo'); + $a = new AppendStream(array($s1)); + $a->close(); + $this->assertSame('', (string) $a); + } + + /** + * @expectedExceptionMessage Cannot write to an AppendStream + * @expectedException \RuntimeException + */ + public function testIsNotWritable() + { + $a = new AppendStream(array(Psr7\stream_for('foo'))); + $this->assertFalse($a->isWritable()); + $this->assertTrue($a->isSeekable()); + $this->assertTrue($a->isReadable()); + $a->write('foo'); + } + + public function testDoesNotNeedStreams() + { + $a = new AppendStream(); + $this->assertEquals('', (string) $a); + } + + public function testCanReadFromMultipleStreams() + { + $a = new AppendStream(array( + Psr7\stream_for('foo'), + Psr7\stream_for('bar'), + Psr7\stream_for('baz'), + )); + $this->assertFalse($a->eof()); + $this->assertSame(0, $a->tell()); + $this->assertEquals('foo', $a->read(3)); + $this->assertEquals('bar', $a->read(3)); + $this->assertEquals('baz', $a->read(3)); + $this->assertSame('', $a->read(1)); + $this->assertTrue($a->eof()); + $this->assertSame(9, $a->tell()); + $this->assertEquals('foobarbaz', (string) $a); + } + + public function testCanDetermineSizeFromMultipleStreams() + { + $a = new AppendStream(array( + Psr7\stream_for('foo'), + Psr7\stream_for('bar') + )); + $this->assertEquals(6, $a->getSize()); + + $s = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isSeekable', 'isReadable')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('isSeekable') + ->will($this->returnValue(null)); + $s->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(true)); + $a->addStream($s); + $this->assertNull($a->getSize()); + } + + public function testCatchesExceptionsWhenCastingToString() + { + $s = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isSeekable', 'read', 'isReadable', 'eof')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('isSeekable') + ->will($this->returnValue(true)); + $s->expects($this->once()) + ->method('read') + ->will($this->throwException(new \RuntimeException('foo'))); + $s->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(true)); + $s->expects($this->any()) + ->method('eof') + ->will($this->returnValue(false)); + $a = new AppendStream(array($s)); + $this->assertFalse($a->eof()); + $this->assertSame('', (string) $a); + } + + public function testCanDetach() + { + $s = new AppendStream(); + $s->detach(); + } + + public function testReturnsEmptyMetadata() + { + $s = new AppendStream(); + $this->assertEquals(array(), $s->getMetadata()); + $this->assertNull($s->getMetadata('foo')); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/BufferStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/BufferStreamTest.php new file mode 100644 index 0000000..79f907a --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/BufferStreamTest.php @@ -0,0 +1,63 @@ +assertTrue($b->isReadable()); + $this->assertTrue($b->isWritable()); + $this->assertFalse($b->isSeekable()); + $this->assertEquals(null, $b->getMetadata('foo')); + $this->assertEquals(10, $b->getMetadata('hwm')); + $this->assertEquals(array(), $b->getMetadata()); + } + + public function testRemovesReadDataFromBuffer() + { + $b = new BufferStream(); + $this->assertEquals(3, $b->write('foo')); + $this->assertEquals(3, $b->getSize()); + $this->assertFalse($b->eof()); + $this->assertEquals('foo', $b->read(10)); + $this->assertTrue($b->eof()); + $this->assertEquals('', $b->read(10)); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Cannot determine the position of a BufferStream + */ + public function testCanCastToStringOrGetContents() + { + $b = new BufferStream(); + $b->write('foo'); + $b->write('baz'); + $this->assertEquals('foo', $b->read(3)); + $b->write('bar'); + $this->assertEquals('bazbar', (string) $b); + $b->tell(); + } + + public function testDetachClearsBuffer() + { + $b = new BufferStream(); + $b->write('foo'); + $b->detach(); + $this->assertTrue($b->eof()); + $this->assertEquals(3, $b->write('abc')); + $this->assertEquals('abc', $b->read(10)); + } + + public function testExceedingHighwaterMarkReturnsFalseButStillBuffers() + { + $b = new BufferStream(5); + $this->assertEquals(3, $b->write('hi ')); + $this->assertFalse($b->write('hello')); + $this->assertEquals('hi hello', (string) $b); + $this->assertEquals(4, $b->write('test')); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/CachingStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/CachingStreamTest.php new file mode 100644 index 0000000..f394fc9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/CachingStreamTest.php @@ -0,0 +1,166 @@ +decorated = Psr7\stream_for('testing'); + $this->body = new CachingStream($this->decorated); + } + + public function tearDown() + { + $this->decorated->close(); + $this->body->close(); + } + + public function testUsesRemoteSizeIfPossible() + { + $body = Psr7\stream_for('test'); + $caching = new CachingStream($body); + $this->assertEquals(4, $caching->getSize()); + } + + public function testReadsUntilCachedToByte() + { + $this->body->seek(5); + $this->assertEquals('n', $this->body->read(1)); + $this->body->seek(0); + $this->assertEquals('t', $this->body->read(1)); + } + + public function testCanSeekNearEndWithSeekEnd() + { + $baseStream = Psr7\stream_for(implode('', range('a', 'z'))); + $cached = new CachingStream($baseStream); + $cached->seek(1, SEEK_END); + $this->assertEquals(24, $baseStream->tell()); + $this->assertEquals('y', $cached->read(1)); + $this->assertEquals(26, $cached->getSize()); + } + + public function testCanSeekToEndWithSeekEnd() + { + $baseStream = Psr7\stream_for(implode('', range('a', 'z'))); + $cached = new CachingStream($baseStream); + $cached->seek(0, SEEK_END); + $this->assertEquals(25, $baseStream->tell()); + $this->assertEquals('z', $cached->read(1)); + $this->assertEquals(26, $cached->getSize()); + } + + public function testCanUseSeekEndWithUnknownSize() + { + $baseStream = Psr7\stream_for('testing'); + $decorated = Psr7\FnStream::decorate($baseStream, array( + 'getSize' => function () { return null; } + )); + $cached = new CachingStream($decorated); + $cached->seek(1, SEEK_END); + $this->assertEquals('ng', $cached->read(2)); + } + + public function testRewindUsesSeek() + { + $a = Psr7\stream_for('foo'); + $d = $this->getMockBuilder('RingCentral\Psr7\CachingStream') + ->setMethods(array('seek')) + ->setConstructorArgs(array($a)) + ->getMock(); + $d->expects($this->once()) + ->method('seek') + ->with(0) + ->will($this->returnValue(true)); + $d->seek(0); + } + + public function testCanSeekToReadBytes() + { + $this->assertEquals('te', $this->body->read(2)); + $this->body->seek(0); + $this->assertEquals('test', $this->body->read(4)); + $this->assertEquals(4, $this->body->tell()); + $this->body->seek(2); + $this->assertEquals(2, $this->body->tell()); + $this->body->seek(2, SEEK_CUR); + $this->assertEquals(4, $this->body->tell()); + $this->assertEquals('ing', $this->body->read(3)); + } + + public function testWritesToBufferStream() + { + $this->body->read(2); + $this->body->write('hi'); + $this->body->seek(0); + $this->assertEquals('tehiing', (string) $this->body); + } + + public function testSkipsOverwrittenBytes() + { + $decorated = Psr7\stream_for( + implode("\n", array_map(function ($n) { + return str_pad($n, 4, '0', STR_PAD_LEFT); + }, range(0, 25))) + ); + + $body = new CachingStream($decorated); + + $this->assertEquals("0000\n", Psr7\readline($body)); + $this->assertEquals("0001\n", Psr7\readline($body)); + // Write over part of the body yet to be read, so skip some bytes + $this->assertEquals(5, $body->write("TEST\n")); + $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes')); + // Read, which skips bytes, then reads + $this->assertEquals("0003\n", Psr7\readline($body)); + $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes')); + $this->assertEquals("0004\n", Psr7\readline($body)); + $this->assertEquals("0005\n", Psr7\readline($body)); + + // Overwrite part of the cached body (so don't skip any bytes) + $body->seek(5); + $this->assertEquals(5, $body->write("ABCD\n")); + $this->assertEquals(0, $this->readAttribute($body, 'skipReadBytes')); + $this->assertEquals("TEST\n", Psr7\readline($body)); + $this->assertEquals("0003\n", Psr7\readline($body)); + $this->assertEquals("0004\n", Psr7\readline($body)); + $this->assertEquals("0005\n", Psr7\readline($body)); + $this->assertEquals("0006\n", Psr7\readline($body)); + $this->assertEquals(5, $body->write("1234\n")); + $this->assertEquals(5, $this->readAttribute($body, 'skipReadBytes')); + + // Seek to 0 and ensure the overwritten bit is replaced + $body->seek(0); + $this->assertEquals("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", $body->read(50)); + + // Ensure that casting it to a string does not include the bit that was overwritten + $this->assertContains("0000\nABCD\nTEST\n0003\n0004\n0005\n0006\n1234\n0008\n0009\n", (string) $body); + } + + public function testClosesBothStreams() + { + $s = fopen('php://temp', 'r'); + $a = Psr7\stream_for($s); + $d = new CachingStream($a); + $d->close(); + $this->assertFalse(is_resource($s)); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testEnsuresValidWhence() + { + $this->body->seek(10, -123456); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/DroppingStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/DroppingStreamTest.php new file mode 100644 index 0000000..1ae9443 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/DroppingStreamTest.php @@ -0,0 +1,26 @@ +assertEquals(3, $drop->write('hel')); + $this->assertEquals(2, $drop->write('lo')); + $this->assertEquals(5, $drop->getSize()); + $this->assertEquals('hello', $drop->read(5)); + $this->assertEquals(0, $drop->getSize()); + $drop->write('12345678910'); + $this->assertEquals(5, $stream->getSize()); + $this->assertEquals(5, $drop->getSize()); + $this->assertEquals('12345', (string) $drop); + $this->assertEquals(0, $drop->getSize()); + $drop->write('hello'); + $this->assertSame(0, $drop->write('test')); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FnStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FnStreamTest.php new file mode 100644 index 0000000..def436c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FnStreamTest.php @@ -0,0 +1,92 @@ +seek(1); + } + + public function testProxiesToFunction() + { + $self = $this; + $s = new FnStream(array( + 'read' => function ($len) use ($self) { + $self->assertEquals(3, $len); + return 'foo'; + } + )); + + $this->assertEquals('foo', $s->read(3)); + } + + public function testCanCloseOnDestruct() + { + $called = false; + $s = new FnStream(array( + 'close' => function () use (&$called) { + $called = true; + } + )); + unset($s); + $this->assertTrue($called); + } + + public function testDoesNotRequireClose() + { + $s = new FnStream(array()); + unset($s); + } + + public function testDecoratesStream() + { + $a = Psr7\stream_for('foo'); + $b = FnStream::decorate($a, array()); + $this->assertEquals(3, $b->getSize()); + $this->assertEquals($b->isWritable(), true); + $this->assertEquals($b->isReadable(), true); + $this->assertEquals($b->isSeekable(), true); + $this->assertEquals($b->read(3), 'foo'); + $this->assertEquals($b->tell(), 3); + $this->assertEquals($a->tell(), 3); + $this->assertSame('', $a->read(1)); + $this->assertEquals($b->eof(), true); + $this->assertEquals($a->eof(), true); + $b->seek(0); + $this->assertEquals('foo', (string) $b); + $b->seek(0); + $this->assertEquals('foo', $b->getContents()); + $this->assertEquals($a->getMetadata(), $b->getMetadata()); + $b->seek(0, SEEK_END); + $b->write('bar'); + $this->assertEquals('foobar', (string) $b); + $this->assertInternalType('resource', $b->detach()); + $b->close(); + } + + public function testDecoratesWithCustomizations() + { + $called = false; + $a = Psr7\stream_for('foo'); + $b = FnStream::decorate($a, array( + 'read' => function ($len) use (&$called, $a) { + $called = true; + return $a->read($len); + } + )); + $this->assertEquals('foo', $b->read(3)); + $this->assertTrue($called); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FunctionsTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FunctionsTest.php new file mode 100644 index 0000000..032fc56 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/FunctionsTest.php @@ -0,0 +1,604 @@ +assertEquals('foobaz', Psr7\copy_to_string($s)); + $s->seek(0); + $this->assertEquals('foo', Psr7\copy_to_string($s, 3)); + $this->assertEquals('baz', Psr7\copy_to_string($s, 3)); + $this->assertEquals('', Psr7\copy_to_string($s)); + } + + public function testCopiesToStringStopsWhenReadFails() + { + $s1 = Psr7\stream_for('foobaz'); + $s1 = FnStream::decorate($s1, array( + 'read' => function () { return ''; } + )); + $result = Psr7\copy_to_string($s1); + $this->assertEquals('', $result); + } + + public function testCopiesToStream() + { + $s1 = Psr7\stream_for('foobaz'); + $s2 = Psr7\stream_for(''); + Psr7\copy_to_stream($s1, $s2); + $this->assertEquals('foobaz', (string) $s2); + $s2 = Psr7\stream_for(''); + $s1->seek(0); + Psr7\copy_to_stream($s1, $s2, 3); + $this->assertEquals('foo', (string) $s2); + Psr7\copy_to_stream($s1, $s2, 3); + $this->assertEquals('foobaz', (string) $s2); + } + + public function testStopsCopyToStreamWhenWriteFails() + { + $s1 = Psr7\stream_for('foobaz'); + $s2 = Psr7\stream_for(''); + $s2 = FnStream::decorate($s2, array('write' => function () { return 0; })); + Psr7\copy_to_stream($s1, $s2); + $this->assertEquals('', (string) $s2); + } + + public function testStopsCopyToSteamWhenWriteFailsWithMaxLen() + { + $s1 = Psr7\stream_for('foobaz'); + $s2 = Psr7\stream_for(''); + $s2 = FnStream::decorate($s2, array('write' => function () { return 0; })); + Psr7\copy_to_stream($s1, $s2, 10); + $this->assertEquals('', (string) $s2); + } + + public function testStopsCopyToSteamWhenReadFailsWithMaxLen() + { + $s1 = Psr7\stream_for('foobaz'); + $s1 = FnStream::decorate($s1, array('read' => function () { return ''; })); + $s2 = Psr7\stream_for(''); + Psr7\copy_to_stream($s1, $s2, 10); + $this->assertEquals('', (string) $s2); + } + + public function testReadsLines() + { + $s = Psr7\stream_for("foo\nbaz\nbar"); + $this->assertEquals("foo\n", Psr7\readline($s)); + $this->assertEquals("baz\n", Psr7\readline($s)); + $this->assertEquals("bar", Psr7\readline($s)); + } + + public function testReadsLinesUpToMaxLength() + { + $s = Psr7\stream_for("12345\n"); + $this->assertEquals("123", Psr7\readline($s, 4)); + $this->assertEquals("45\n", Psr7\readline($s)); + } + + public function testReadsLineUntilFalseReturnedFromRead() + { + $s = $this->getMockBuilder('RingCentral\Psr7\Stream') + ->setMethods(array('read', 'eof')) + ->disableOriginalConstructor() + ->getMock(); + $s->expects($this->exactly(2)) + ->method('read') + ->will($this->returnCallback(function () { + static $c = false; + if ($c) { + return false; + } + $c = true; + return 'h'; + })); + $s->expects($this->exactly(2)) + ->method('eof') + ->will($this->returnValue(false)); + $this->assertEquals("h", Psr7\readline($s)); + } + + public function testCalculatesHash() + { + $s = Psr7\stream_for('foobazbar'); + $this->assertEquals(md5('foobazbar'), Psr7\hash($s, 'md5')); + } + + /** + * @expectedException \RuntimeException + */ + public function testCalculatesHashThrowsWhenSeekFails() + { + $s = new NoSeekStream(Psr7\stream_for('foobazbar')); + $s->read(2); + Psr7\hash($s, 'md5'); + } + + public function testCalculatesHashSeeksToOriginalPosition() + { + $s = Psr7\stream_for('foobazbar'); + $s->seek(4); + $this->assertEquals(md5('foobazbar'), Psr7\hash($s, 'md5')); + $this->assertEquals(4, $s->tell()); + } + + public function testOpensFilesSuccessfully() + { + $r = Psr7\try_fopen(__FILE__, 'r'); + $this->assertInternalType('resource', $r); + fclose($r); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Unable to open /path/to/does/not/exist using mode r + */ + public function testThrowsExceptionNotWarning() + { + Psr7\try_fopen('/path/to/does/not/exist', 'r'); + } + + public function parseQueryProvider() + { + return array( + // Does not need to parse when the string is empty + array('', array()), + // Can parse mult-values items + array('q=a&q=b', array('q' => array('a', 'b'))), + // Can parse multi-valued items that use numeric indices + array('q[0]=a&q[1]=b', array('q[0]' => 'a', 'q[1]' => 'b')), + // Can parse duplicates and does not include numeric indices + array('q[]=a&q[]=b', array('q[]' => array('a', 'b'))), + // Ensures that the value of "q" is an array even though one value + array('q[]=a', array('q[]' => 'a')), + // Does not modify "." to "_" like PHP's parse_str() + array('q.a=a&q.b=b', array('q.a' => 'a', 'q.b' => 'b')), + // Can decode %20 to " " + array('q%20a=a%20b', array('q a' => 'a b')), + // Can parse funky strings with no values by assigning each to null + array('q&a', array('q' => null, 'a' => null)), + // Does not strip trailing equal signs + array('data=abc=', array('data' => 'abc=')), + // Can store duplicates without affecting other values + array('foo=a&foo=b&?µ=c', array('foo' => array('a', 'b'), '?µ' => 'c')), + // Sets value to null when no "=" is present + array('foo', array('foo' => null)), + // Preserves "0" keys. + array('0', array('0' => null)), + // Sets the value to an empty string when "=" is present + array('0=', array('0' => '')), + // Preserves falsey keys + array('var=0', array('var' => '0')), + array('a[b][c]=1&a[b][c]=2', array('a[b][c]' => array('1', '2'))), + array('a[b]=c&a[d]=e', array('a[b]' => 'c', 'a[d]' => 'e')), + // Ensure it doesn't leave things behind with repeated values + // Can parse mult-values items + array('q=a&q=b&q=c', array('q' => array('a', 'b', 'c'))), + ); + } + + /** + * @dataProvider parseQueryProvider + */ + public function testParsesQueries($input, $output) + { + $result = Psr7\parse_query($input); + $this->assertSame($output, $result); + } + + public function testDoesNotDecode() + { + $str = 'foo%20=bar'; + $data = Psr7\parse_query($str, false); + $this->assertEquals(array('foo%20' => 'bar'), $data); + } + + /** + * @dataProvider parseQueryProvider + */ + public function testParsesAndBuildsQueries($input, $output) + { + $result = Psr7\parse_query($input, false); + $this->assertSame($input, Psr7\build_query($result, false)); + } + + public function testEncodesWithRfc1738() + { + $str = Psr7\build_query(array('foo bar' => 'baz+'), PHP_QUERY_RFC1738); + $this->assertEquals('foo+bar=baz%2B', $str); + } + + public function testEncodesWithRfc3986() + { + $str = Psr7\build_query(array('foo bar' => 'baz+'), PHP_QUERY_RFC3986); + $this->assertEquals('foo%20bar=baz%2B', $str); + } + + public function testDoesNotEncode() + { + $str = Psr7\build_query(array('foo bar' => 'baz+'), false); + $this->assertEquals('foo bar=baz+', $str); + } + + public function testCanControlDecodingType() + { + $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC3986); + $this->assertEquals('foo+bar', $result['var']); + $result = Psr7\parse_query('var=foo+bar', PHP_QUERY_RFC1738); + $this->assertEquals('foo bar', $result['var']); + } + + public function testParsesRequestMessages() + { + $req = "GET /abc HTTP/1.0\r\nHost: foo.com\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest"; + $request = Psr7\parse_request($req); + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('/abc', $request->getRequestTarget()); + $this->assertEquals('1.0', $request->getProtocolVersion()); + $this->assertEquals('foo.com', $request->getHeaderLine('Host')); + $this->assertEquals('Bar', $request->getHeaderLine('Foo')); + $this->assertEquals('Bam, Qux', $request->getHeaderLine('Baz')); + $this->assertEquals('Test', (string) $request->getBody()); + $this->assertEquals('http://foo.com/abc', (string) $request->getUri()); + } + + public function testParsesRequestMessagesWithHttpsScheme() + { + $req = "PUT /abc?baz=bar HTTP/1.1\r\nHost: foo.com:443\r\n\r\n"; + $request = Psr7\parse_request($req); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('/abc?baz=bar', $request->getRequestTarget()); + $this->assertEquals('1.1', $request->getProtocolVersion()); + $this->assertEquals('foo.com:443', $request->getHeaderLine('Host')); + $this->assertEquals('', (string) $request->getBody()); + $this->assertEquals('https://foo.com/abc?baz=bar', (string) $request->getUri()); + } + + public function testParsesRequestMessagesWithUriWhenHostIsNotFirst() + { + $req = "PUT / HTTP/1.1\r\nFoo: Bar\r\nHost: foo.com\r\n\r\n"; + $request = Psr7\parse_request($req); + $this->assertEquals('PUT', $request->getMethod()); + $this->assertEquals('/', $request->getRequestTarget()); + $this->assertEquals('http://foo.com/', (string) $request->getUri()); + } + + public function testParsesRequestMessagesWithFullUri() + { + $req = "GET https://www.google.com:443/search?q=foobar HTTP/1.1\r\nHost: www.google.com\r\n\r\n"; + $request = Psr7\parse_request($req); + $this->assertEquals('GET', $request->getMethod()); + $this->assertEquals('https://www.google.com:443/search?q=foobar', $request->getRequestTarget()); + $this->assertEquals('1.1', $request->getProtocolVersion()); + $this->assertEquals('www.google.com', $request->getHeaderLine('Host')); + $this->assertEquals('', (string) $request->getBody()); + $this->assertEquals('https://www.google.com/search?q=foobar', (string) $request->getUri()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesRequestMessages() + { + Psr7\parse_request("HTTP/1.1 200 OK\r\n\r\n"); + } + + public function testParsesResponseMessages() + { + $res = "HTTP/1.0 200 OK\r\nFoo: Bar\r\nBaz: Bam\r\nBaz: Qux\r\n\r\nTest"; + $response = Psr7\parse_response($res); + $this->assertEquals(200, $response->getStatusCode()); + $this->assertEquals('OK', $response->getReasonPhrase()); + $this->assertEquals('1.0', $response->getProtocolVersion()); + $this->assertEquals('Bar', $response->getHeaderLine('Foo')); + $this->assertEquals('Bam, Qux', $response->getHeaderLine('Baz')); + $this->assertEquals('Test', (string) $response->getBody()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesResponseMessages() + { + Psr7\parse_response("GET / HTTP/1.1\r\n\r\n"); + } + + public function testDetermineMimetype() + { + $this->assertNull(Psr7\mimetype_from_extension('not-a-real-extension')); + $this->assertEquals( + 'application/json', + Psr7\mimetype_from_extension('json') + ); + $this->assertEquals( + 'image/jpeg', + Psr7\mimetype_from_filename('/tmp/images/IMG034821.JPEG') + ); + } + + public function testCreatesUriForValue() + { + $this->assertInstanceOf('RingCentral\Psr7\Uri', Psr7\uri_for('/foo')); + $this->assertInstanceOf( + 'RingCentral\Psr7\Uri', + Psr7\uri_for(new Psr7\Uri('/foo')) + ); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesUri() + { + Psr7\uri_for(array()); + } + + public function testKeepsPositionOfResource() + { + $h = fopen(__FILE__, 'r'); + fseek($h, 10); + $stream = Psr7\stream_for($h); + $this->assertEquals(10, $stream->tell()); + $stream->close(); + } + + public function testCreatesWithFactory() + { + $stream = Psr7\stream_for('foo'); + $this->assertInstanceOf('RingCentral\Psr7\Stream', $stream); + $this->assertEquals('foo', $stream->getContents()); + $stream->close(); + } + + public function testFactoryCreatesFromEmptyString() + { + $s = Psr7\stream_for(); + $this->assertInstanceOf('RingCentral\Psr7\Stream', $s); + } + + public function testFactoryCreatesFromNull() + { + $s = Psr7\stream_for(null); + $this->assertInstanceOf('RingCentral\Psr7\Stream', $s); + } + + public function testFactoryCreatesFromResource() + { + $r = fopen(__FILE__, 'r'); + $s = Psr7\stream_for($r); + $this->assertInstanceOf('RingCentral\Psr7\Stream', $s); + $this->assertSame(file_get_contents(__FILE__), (string) $s); + } + + public function testFactoryCreatesFromObjectWithToString() + { + $r = new HasToString(); + $s = Psr7\stream_for($r); + $this->assertInstanceOf('RingCentral\Psr7\Stream', $s); + $this->assertEquals('foo', (string) $s); + } + + public function testCreatePassesThrough() + { + $s = Psr7\stream_for('foo'); + $this->assertSame($s, Psr7\stream_for($s)); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testThrowsExceptionForUnknown() + { + Psr7\stream_for(new \stdClass()); + } + + public function testReturnsCustomMetadata() + { + $s = Psr7\stream_for('foo', array('metadata' => array('hwm' => 3))); + $this->assertEquals(3, $s->getMetadata('hwm')); + $this->assertArrayHasKey('hwm', $s->getMetadata()); + } + + public function testCanSetSize() + { + $s = Psr7\stream_for('', array('size' => 10)); + $this->assertEquals(10, $s->getSize()); + } + + public function testCanCreateIteratorBasedStream() + { + $a = new \ArrayIterator(array('foo', 'bar', '123')); + $p = Psr7\stream_for($a); + $this->assertInstanceOf('RingCentral\Psr7\PumpStream', $p); + $this->assertEquals('foo', $p->read(3)); + $this->assertFalse($p->eof()); + $this->assertEquals('b', $p->read(1)); + $this->assertEquals('a', $p->read(1)); + $this->assertEquals('r12', $p->read(3)); + $this->assertFalse($p->eof()); + $this->assertEquals('3', $p->getContents()); + $this->assertTrue($p->eof()); + $this->assertEquals(9, $p->tell()); + } + + public function testConvertsRequestsToStrings() + { + $request = new Psr7\Request('PUT', 'http://foo.com/hi?123', array( + 'Baz' => 'bar', + 'Qux' => ' ipsum' + ), 'hello', '1.0'); + $this->assertEquals( + "PUT /hi?123 HTTP/1.0\r\nHost: foo.com\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello", + Psr7\str($request) + ); + } + + public function testConvertsResponsesToStrings() + { + $response = new Psr7\Response(200, array( + 'Baz' => 'bar', + 'Qux' => ' ipsum' + ), 'hello', '1.0', 'FOO'); + $this->assertEquals( + "HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello", + Psr7\str($response) + ); + } + + public function parseParamsProvider() + { + $res1 = array( + array( + '', + 'rel' => 'front', + 'type' => 'image/jpeg', + ), + array( + '', + 'rel' => 'back', + 'type' => 'image/jpeg', + ), + ); + return array( + array( + '; rel="front"; type="image/jpeg", ; rel=back; type="image/jpeg"', + $res1 + ), + array( + '; rel="front"; type="image/jpeg",; rel=back; type="image/jpeg"', + $res1 + ), + array( + 'foo="baz"; bar=123, boo, test="123", foobar="foo;bar"', + array( + array('foo' => 'baz', 'bar' => '123'), + array('boo'), + array('test' => '123'), + array('foobar' => 'foo;bar') + ) + ), + array( + '; rel="side"; type="image/jpeg",; rel=side; type="image/jpeg"', + array( + array('', 'rel' => 'side', 'type' => 'image/jpeg'), + array('', 'rel' => 'side', 'type' => 'image/jpeg') + ) + ), + array( + '', + array() + ) + ); + } + /** + * @dataProvider parseParamsProvider + */ + public function testParseParams($header, $result) + { + $this->assertEquals($result, Psr7\parse_header($header)); + } + + public function testParsesArrayHeaders() + { + $header = array('a, b', 'c', 'd, e'); + $this->assertEquals(array('a', 'b', 'c', 'd', 'e'), Psr7\normalize_header($header)); + } + + public function testRewindsBody() + { + $body = Psr7\stream_for('abc'); + $res = new Psr7\Response(200, array(), $body); + Psr7\rewind_body($res); + $this->assertEquals(0, $body->tell()); + $body->rewind(1); + Psr7\rewind_body($res); + $this->assertEquals(0, $body->tell()); + } + + /** + * @expectedException \RuntimeException + */ + public function testThrowsWhenBodyCannotBeRewound() + { + $body = Psr7\stream_for('abc'); + $body->read(1); + $body = FnStream::decorate($body, array( + 'rewind' => function () { throw new \RuntimeException('a'); } + )); + $res = new Psr7\Response(200, array(), $body); + Psr7\rewind_body($res); + } + + public function testCanModifyRequestWithUri() + { + $r1 = new Psr7\Request('GET', 'http://foo.com'); + $r2 = Psr7\modify_request($r1, array( + 'uri' => new Psr7\Uri('http://www.foo.com') + )); + $this->assertEquals('http://www.foo.com', (string) $r2->getUri()); + $this->assertEquals('www.foo.com', (string) $r2->getHeaderLine('host')); + } + + public function testCanModifyRequestWithCaseInsensitiveHeader() + { + $r1 = new Psr7\Request('GET', 'http://foo.com', array('User-Agent' => 'foo')); + $r2 = Psr7\modify_request($r1, array('set_headers' => array('User-agent' => 'bar'))); + $this->assertEquals('bar', $r2->getHeaderLine('User-Agent')); + $this->assertEquals('bar', $r2->getHeaderLine('User-agent')); + } + + public function testReturnsAsIsWhenNoChanges() + { + $request = new Psr7\Request('GET', 'http://foo.com'); + $this->assertSame($request, Psr7\modify_request($request, array())); + } + + public function testReturnsUriAsIsWhenNoChanges() + { + $r1 = new Psr7\Request('GET', 'http://foo.com'); + $r2 = Psr7\modify_request($r1, array('set_headers' => array('foo' => 'bar'))); + $this->assertNotSame($r1, $r2); + $this->assertEquals('bar', $r2->getHeaderLine('foo')); + } + + public function testRemovesHeadersFromMessage() + { + $r1 = new Psr7\Request('GET', 'http://foo.com', array('foo' => 'bar')); + $r2 = Psr7\modify_request($r1, array('remove_headers' => array('foo'))); + $this->assertNotSame($r1, $r2); + $this->assertFalse($r2->hasHeader('foo')); + } + + public function testAddsQueryToUri() + { + $r1 = new Psr7\Request('GET', 'http://foo.com'); + $r2 = Psr7\modify_request($r1, array('query' => 'foo=bar')); + $this->assertNotSame($r1, $r2); + $this->assertEquals('foo=bar', $r2->getUri()->getQuery()); + } + + public function testServerRequestWithServerParams() + { + $requestString = "GET /abc HTTP/1.1\r\nHost: foo.com\r\n\r\n"; + $request = Psr7\parse_server_request($requestString); + + $this->assertEquals(array(), $request->getServerParams()); + } + + public function testServerRequestWithoutServerParams() + { + $requestString = "GET /abc HTTP/1.1\r\nHost: foo.com\r\n\r\n"; + $serverParams = array('server_address' => '127.0.0.1', 'server_port' => 80); + + $request = Psr7\parse_server_request($requestString, $serverParams); + + $this->assertEquals(array('server_address' => '127.0.0.1', 'server_port' => 80), $request->getServerParams()); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/InflateStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/InflateStreamTest.php new file mode 100644 index 0000000..cd699eb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/InflateStreamTest.php @@ -0,0 +1,21 @@ +assertEquals('test', (string) $b); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LazyOpenStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LazyOpenStreamTest.php new file mode 100644 index 0000000..ca0c18e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LazyOpenStreamTest.php @@ -0,0 +1,64 @@ +fname = tempnam('/tmp', 'tfile'); + + if (file_exists($this->fname)) { + unlink($this->fname); + } + } + + public function tearDown() + { + if (file_exists($this->fname)) { + unlink($this->fname); + } + } + + public function testOpensLazily() + { + $l = new LazyOpenStream($this->fname, 'w+'); + $l->write('foo'); + $this->assertInternalType('array', $l->getMetadata()); + $this->assertFileExists($this->fname); + $this->assertEquals('foo', file_get_contents($this->fname)); + $this->assertEquals('foo', (string) $l); + } + + public function testProxiesToFile() + { + file_put_contents($this->fname, 'foo'); + $l = new LazyOpenStream($this->fname, 'r'); + $this->assertEquals('foo', $l->read(4)); + $this->assertTrue($l->eof()); + $this->assertEquals(3, $l->tell()); + $this->assertTrue($l->isReadable()); + $this->assertTrue($l->isSeekable()); + $this->assertFalse($l->isWritable()); + $l->seek(1); + $this->assertEquals('oo', $l->getContents()); + $this->assertEquals('foo', (string) $l); + $this->assertEquals(3, $l->getSize()); + $this->assertInternalType('array', $l->getMetadata()); + $l->close(); + } + + public function testDetachesUnderlyingStream() + { + file_put_contents($this->fname, 'foo'); + $l = new LazyOpenStream($this->fname, 'r'); + $r = $l->detach(); + $this->assertInternalType('resource', $r); + fseek($r, 0); + $this->assertEquals('foo', stream_get_contents($r)); + fclose($r); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LimitStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LimitStreamTest.php new file mode 100644 index 0000000..7053300 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/LimitStreamTest.php @@ -0,0 +1,166 @@ +decorated = Psr7\stream_for(fopen(__FILE__, 'r')); + $this->body = new LimitStream($this->decorated, 10, 3); + } + + public function testReturnsSubset() + { + $body = new LimitStream(Psr7\stream_for('foo'), -1, 1); + $this->assertEquals('oo', (string) $body); + $this->assertTrue($body->eof()); + $body->seek(0); + $this->assertFalse($body->eof()); + $this->assertEquals('oo', $body->read(100)); + $this->assertSame('', $body->read(1)); + $this->assertTrue($body->eof()); + } + + public function testReturnsSubsetWhenCastToString() + { + $body = Psr7\stream_for('foo_baz_bar'); + $limited = new LimitStream($body, 3, 4); + $this->assertEquals('baz', (string) $limited); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Unable to seek to stream position 10 with whence 0 + */ + public function testEnsuresPositionCanBeekSeekedTo() + { + new LimitStream(Psr7\stream_for(''), 0, 10); + } + + public function testReturnsSubsetOfEmptyBodyWhenCastToString() + { + $body = Psr7\stream_for('01234567891234'); + $limited = new LimitStream($body, 0, 10); + $this->assertEquals('', (string) $limited); + } + + public function testReturnsSpecificSubsetOBodyWhenCastToString() + { + $body = Psr7\stream_for('0123456789abcdef'); + $limited = new LimitStream($body, 3, 10); + $this->assertEquals('abc', (string) $limited); + } + + public function testSeeksWhenConstructed() + { + $this->assertEquals(0, $this->body->tell()); + $this->assertEquals(3, $this->decorated->tell()); + } + + public function testAllowsBoundedSeek() + { + $this->body->seek(100); + $this->assertEquals(10, $this->body->tell()); + $this->assertEquals(13, $this->decorated->tell()); + $this->body->seek(0); + $this->assertEquals(0, $this->body->tell()); + $this->assertEquals(3, $this->decorated->tell()); + try { + $this->body->seek(-10); + $this->fail(); + } catch (\RuntimeException $e) {} + $this->assertEquals(0, $this->body->tell()); + $this->assertEquals(3, $this->decorated->tell()); + $this->body->seek(5); + $this->assertEquals(5, $this->body->tell()); + $this->assertEquals(8, $this->decorated->tell()); + // Fail + try { + $this->body->seek(1000, SEEK_END); + $this->fail(); + } catch (\RuntimeException $e) {} + } + + public function testReadsOnlySubsetOfData() + { + $data = $this->body->read(100); + $this->assertEquals(10, strlen($data)); + $this->assertSame('', $this->body->read(1000)); + + $this->body->setOffset(10); + $newData = $this->body->read(100); + $this->assertEquals(10, strlen($newData)); + $this->assertNotSame($data, $newData); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Could not seek to stream offset 2 + */ + public function testThrowsWhenCurrentGreaterThanOffsetSeek() + { + $a = Psr7\stream_for('foo_bar'); + $b = new NoSeekStream($a); + $c = new LimitStream($b); + $a->getContents(); + $c->setOffset(2); + } + + public function testCanGetContentsWithoutSeeking() + { + $a = Psr7\stream_for('foo_bar'); + $b = new NoSeekStream($a); + $c = new LimitStream($b); + $this->assertEquals('foo_bar', $c->getContents()); + } + + public function testClaimsConsumedWhenReadLimitIsReached() + { + $this->assertFalse($this->body->eof()); + $this->body->read(1000); + $this->assertTrue($this->body->eof()); + } + + public function testContentLengthIsBounded() + { + $this->assertEquals(10, $this->body->getSize()); + } + + public function testGetContentsIsBasedOnSubset() + { + $body = new LimitStream(Psr7\stream_for('foobazbar'), 3, 3); + $this->assertEquals('baz', $body->getContents()); + } + + public function testReturnsNullIfSizeCannotBeDetermined() + { + $a = new FnStream(array( + 'getSize' => function () { return null; }, + 'tell' => function () { return 0; }, + )); + $b = new LimitStream($a); + $this->assertNull($b->getSize()); + } + + public function testLengthLessOffsetWhenNoLimitSize() + { + $a = Psr7\stream_for('foo_bar'); + $b = new LimitStream($a, -1, 4); + $this->assertEquals(3, $b->getSize()); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/MultipartStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/MultipartStreamTest.php new file mode 100644 index 0000000..22edea4 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/MultipartStreamTest.php @@ -0,0 +1,214 @@ +assertNotEmpty($b->getBoundary()); + } + + public function testCanProvideBoundary() + { + $b = new MultipartStream(array(), 'foo'); + $this->assertEquals('foo', $b->getBoundary()); + } + + public function testIsNotWritable() + { + $b = new MultipartStream(); + $this->assertFalse($b->isWritable()); + } + + public function testCanCreateEmptyStream() + { + $b = new MultipartStream(); + $boundary = $b->getBoundary(); + $this->assertSame("--{$boundary}--\r\n", $b->getContents()); + $this->assertSame(strlen($boundary) + 6, $b->getSize()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesFilesArrayElement() + { + new MultipartStream(array(array('foo' => 'bar'))); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testEnsuresFileHasName() + { + new MultipartStream(array(array('contents' => 'bar'))); + } + + public function testSerializesFields() + { + $b = new MultipartStream(array( + array( + 'name' => 'foo', + 'contents' => 'bar' + ), + array( + 'name' => 'baz', + 'contents' => 'bam' + ) + ), 'boundary'); + $this->assertEquals( + "--boundary\r\nContent-Disposition: form-data; name=\"foo\"\r\nContent-Length: 3\r\n\r\n" + . "bar\r\n--boundary\r\nContent-Disposition: form-data; name=\"baz\"\r\nContent-Length: 3" + . "\r\n\r\nbam\r\n--boundary--\r\n", (string) $b); + } + + public function testSerializesFiles() + { + $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), array( + 'getMetadata' => function () { + return '/foo/bar.txt'; + } + )); + + $f2 = Psr7\FnStream::decorate(Psr7\stream_for('baz'), array( + 'getMetadata' => function () { + return '/foo/baz.jpg'; + } + )); + + $f3 = Psr7\FnStream::decorate(Psr7\stream_for('bar'), array( + 'getMetadata' => function () { + return '/foo/bar.gif'; + } + )); + + $b = new MultipartStream(array( + array( + 'name' => 'foo', + 'contents' => $f1 + ), + array( + 'name' => 'qux', + 'contents' => $f2 + ), + array( + 'name' => 'qux', + 'contents' => $f3 + ), + ), 'boundary'); + + $expected = <<assertEquals($expected, str_replace("\r", '', $b)); + } + + public function testSerializesFilesWithCustomHeaders() + { + $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), array( + 'getMetadata' => function () { + return '/foo/bar.txt'; + } + )); + + $b = new MultipartStream(array( + array( + 'name' => 'foo', + 'contents' => $f1, + 'headers' => array( + 'x-foo' => 'bar', + 'content-disposition' => 'custom' + ) + ) + ), 'boundary'); + + $expected = <<assertEquals($expected, str_replace("\r", '', $b)); + } + + public function testSerializesFilesWithCustomHeadersAndMultipleValues() + { + $f1 = Psr7\FnStream::decorate(Psr7\stream_for('foo'), array( + 'getMetadata' => function () { + return '/foo/bar.txt'; + } + )); + + $f2 = Psr7\FnStream::decorate(Psr7\stream_for('baz'), array( + 'getMetadata' => function () { + return '/foo/baz.jpg'; + } + )); + + $b = new MultipartStream(array( + array( + 'name' => 'foo', + 'contents' => $f1, + 'headers' => array( + 'x-foo' => 'bar', + 'content-disposition' => 'custom' + ) + ), + array( + 'name' => 'foo', + 'contents' => $f2, + 'headers' => array('cOntenT-Type' => 'custom'), + ) + ), 'boundary'); + + $expected = <<assertEquals($expected, str_replace("\r", '', $b)); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/NoSeekStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/NoSeekStreamTest.php new file mode 100644 index 0000000..a831789 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/NoSeekStreamTest.php @@ -0,0 +1,40 @@ +getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isSeekable', 'seek')) + ->getMockForAbstractClass(); + $s->expects($this->never())->method('seek'); + $s->expects($this->never())->method('isSeekable'); + $wrapped = new NoSeekStream($s); + $this->assertFalse($wrapped->isSeekable()); + $wrapped->seek(2); + } + + /** + * @expectedException \RuntimeException + * @expectedExceptionMessage Cannot write to a non-writable stream + */ + public function testHandlesClose() + { + $s = Psr7\stream_for('foo'); + $wrapped = new NoSeekStream($s); + $wrapped->close(); + $wrapped->write('foo'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/PumpStreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/PumpStreamTest.php new file mode 100644 index 0000000..6b146e1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/PumpStreamTest.php @@ -0,0 +1,72 @@ + array('foo' => 'bar'), + 'size' => 100 + )); + + $this->assertEquals('bar', $p->getMetadata('foo')); + $this->assertEquals(array('foo' => 'bar'), $p->getMetadata()); + $this->assertEquals(100, $p->getSize()); + } + + public function testCanReadFromCallable() + { + $p = Psr7\stream_for(function ($size) { + return 'a'; + }); + $this->assertEquals('a', $p->read(1)); + $this->assertEquals(1, $p->tell()); + $this->assertEquals('aaaaa', $p->read(5)); + $this->assertEquals(6, $p->tell()); + } + + public function testStoresExcessDataInBuffer() + { + $called = array(); + $p = Psr7\stream_for(function ($size) use (&$called) { + $called[] = $size; + return 'abcdef'; + }); + $this->assertEquals('a', $p->read(1)); + $this->assertEquals('b', $p->read(1)); + $this->assertEquals('cdef', $p->read(4)); + $this->assertEquals('abcdefabc', $p->read(9)); + $this->assertEquals(array(1, 9, 3), $called); + } + + public function testInifiniteStreamWrappedInLimitStream() + { + $p = Psr7\stream_for(function () { return 'a'; }); + $s = new LimitStream($p, 5); + $this->assertEquals('aaaaa', (string) $s); + } + + public function testDescribesCapabilities() + { + $p = Psr7\stream_for(function () {}); + $this->assertTrue($p->isReadable()); + $this->assertFalse($p->isSeekable()); + $this->assertFalse($p->isWritable()); + $this->assertNull($p->getSize()); + $this->assertEquals('', $p->getContents()); + $this->assertEquals('', (string) $p); + $p->close(); + $this->assertEquals('', $p->read(10)); + $this->assertTrue($p->eof()); + + try { + $this->assertFalse($p->write('aa')); + $this->fail(); + } catch (\RuntimeException $e) {} + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/RequestTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/RequestTest.php new file mode 100644 index 0000000..ad6f0cb --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/RequestTest.php @@ -0,0 +1,157 @@ +assertEquals('/', (string) $r->getUri()); + } + + public function testRequestUriMayBeUri() + { + $uri = new Uri('/'); + $r = new Request('GET', $uri); + $this->assertSame($uri, $r->getUri()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidateRequestUri() + { + new Request('GET', true); + } + + public function testCanConstructWithBody() + { + $r = new Request('GET', '/', array(), 'baz'); + $this->assertEquals('baz', (string) $r->getBody()); + } + + public function testCapitalizesMethod() + { + $r = new Request('get', '/'); + $this->assertEquals('GET', $r->getMethod()); + } + + public function testCapitalizesWithMethod() + { + $r = new Request('GET', '/'); + $this->assertEquals('PUT', $r->withMethod('put')->getMethod()); + } + + public function testWithUri() + { + $r1 = new Request('GET', '/'); + $u1 = $r1->getUri(); + $u2 = new Uri('http://www.example.com'); + $r2 = $r1->withUri($u2); + $this->assertNotSame($r1, $r2); + $this->assertSame($u2, $r2->getUri()); + $this->assertSame($u1, $r1->getUri()); + } + + public function testSameInstanceWhenSameUri() + { + $r1 = new Request('GET', 'http://foo.com'); + $r2 = $r1->withUri($r1->getUri()); + $this->assertSame($r1, $r2); + } + + public function testWithRequestTarget() + { + $r1 = new Request('GET', '/'); + $r2 = $r1->withRequestTarget('*'); + $this->assertEquals('*', $r2->getRequestTarget()); + $this->assertEquals('/', $r1->getRequestTarget()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testRequestTargetDoesNotAllowSpaces() + { + $r1 = new Request('GET', '/'); + $r1->withRequestTarget('/foo bar'); + } + + public function testRequestTargetDefaultsToSlash() + { + $r1 = new Request('GET', ''); + $this->assertEquals('/', $r1->getRequestTarget()); + $r2 = new Request('GET', '*'); + $this->assertEquals('*', $r2->getRequestTarget()); + $r3 = new Request('GET', 'http://foo.com/bar baz/'); + $this->assertEquals('/bar%20baz/', $r3->getRequestTarget()); + } + + public function testBuildsRequestTarget() + { + $r1 = new Request('GET', 'http://foo.com/baz?bar=bam'); + $this->assertEquals('/baz?bar=bam', $r1->getRequestTarget()); + } + + public function testHostIsAddedFirst() + { + $r = new Request('GET', 'http://foo.com/baz?bar=bam', array('Foo' => 'Bar')); + $this->assertEquals(array( + 'Host' => array('foo.com'), + 'Foo' => array('Bar') + ), $r->getHeaders()); + } + + public function testCanGetHeaderAsCsv() + { + $r = new Request('GET', 'http://foo.com/baz?bar=bam', array( + 'Foo' => array('a', 'b', 'c') + )); + $this->assertEquals('a, b, c', $r->getHeaderLine('Foo')); + $this->assertEquals('', $r->getHeaderLine('Bar')); + } + + public function testHostIsNotOverwrittenWhenPreservingHost() + { + $r = new Request('GET', 'http://foo.com/baz?bar=bam', array('Host' => 'a.com')); + $this->assertEquals(array('Host' => array('a.com')), $r->getHeaders()); + $r2 = $r->withUri(new Uri('http://www.foo.com/bar'), true); + $this->assertEquals('a.com', $r2->getHeaderLine('Host')); + } + + public function testOverridesHostWithUri() + { + $r = new Request('GET', 'http://foo.com/baz?bar=bam'); + $this->assertEquals(array('Host' => array('foo.com')), $r->getHeaders()); + $r2 = $r->withUri(new Uri('http://www.baz.com/bar')); + $this->assertEquals('www.baz.com', $r2->getHeaderLine('Host')); + } + + public function testAggregatesHeaders() + { + $r = new Request('GET', 'http://foo.com', array( + 'ZOO' => 'zoobar', + 'zoo' => array('foobar', 'zoobar') + )); + $this->assertEquals('zoobar, foobar, zoobar', $r->getHeaderLine('zoo')); + } + + public function testAddsPortToHeader() + { + $r = new Request('GET', 'http://foo.com:8124/bar'); + $this->assertEquals('foo.com:8124', $r->getHeaderLine('host')); + } + + public function testAddsPortToHeaderAndReplacePreviousPort() + { + $r = new Request('GET', 'http://foo.com:8124/bar'); + $r = $r->withUri(new Uri('http://foo.com:8125/bar')); + $this->assertEquals('foo.com:8125', $r->getHeaderLine('host')); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ResponseTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ResponseTest.php new file mode 100644 index 0000000..52b7ba1 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ResponseTest.php @@ -0,0 +1,154 @@ +assertSame(200, $r->getStatusCode()); + $this->assertEquals('OK', $r->getReasonPhrase()); + } + + public function testCanGiveCustomReason() + { + $r = new Response(200, array(), null, '1.1', 'bar'); + $this->assertEquals('bar', $r->getReasonPhrase()); + } + + public function testCanGiveCustomProtocolVersion() + { + $r = new Response(200, array(), null, '1000'); + $this->assertEquals('1000', $r->getProtocolVersion()); + } + + public function testCanCreateNewResponseWithStatusAndNoReason() + { + $r = new Response(200); + $r2 = $r->withStatus(201); + $this->assertEquals(200, $r->getStatusCode()); + $this->assertEquals('OK', $r->getReasonPhrase()); + $this->assertEquals(201, $r2->getStatusCode()); + $this->assertEquals('Created', $r2->getReasonPhrase()); + } + + public function testCanCreateNewResponseWithStatusAndReason() + { + $r = new Response(200); + $r2 = $r->withStatus(201, 'Foo'); + $this->assertEquals(200, $r->getStatusCode()); + $this->assertEquals('OK', $r->getReasonPhrase()); + $this->assertEquals(201, $r2->getStatusCode()); + $this->assertEquals('Foo', $r2->getReasonPhrase()); + } + + public function testCreatesResponseWithAddedHeaderArray() + { + $r = new Response(); + $r2 = $r->withAddedHeader('foo', array('baz', 'bar')); + $this->assertFalse($r->hasHeader('foo')); + $this->assertEquals('baz, bar', $r2->getHeaderLine('foo')); + } + + public function testReturnsIdentityWhenRemovingMissingHeader() + { + $r = new Response(); + $this->assertSame($r, $r->withoutHeader('foo')); + } + + public function testAlwaysReturnsBody() + { + $r = new Response(); + $this->assertInstanceOf('Psr\Http\Message\StreamInterface', $r->getBody()); + } + + public function testCanSetHeaderAsArray() + { + $r = new Response(200, array( + 'foo' => array('baz ', ' bar ') + )); + $this->assertEquals('baz, bar', $r->getHeaderLine('foo')); + $this->assertEquals(array('baz', 'bar'), $r->getHeader('foo')); + } + + public function testSameInstanceWhenSameBody() + { + $r = new Response(200, array(), 'foo'); + $b = $r->getBody(); + $this->assertSame($r, $r->withBody($b)); + } + + public function testNewInstanceWhenNewBody() + { + $r = new Response(200, array(), 'foo'); + $b2 = Psr7\stream_for('abc'); + $this->assertNotSame($r, $r->withBody($b2)); + } + + public function testSameInstanceWhenSameProtocol() + { + $r = new Response(200); + $this->assertSame($r, $r->withProtocolVersion('1.1')); + } + + public function testNewInstanceWhenNewProtocol() + { + $r = new Response(200); + $this->assertNotSame($r, $r->withProtocolVersion('1.0')); + } + + public function testNewInstanceWhenRemovingHeader() + { + $r = new Response(200, array('Foo' => 'Bar')); + $r2 = $r->withoutHeader('Foo'); + $this->assertNotSame($r, $r2); + $this->assertFalse($r2->hasHeader('foo')); + } + + public function testNewInstanceWhenAddingHeader() + { + $r = new Response(200, array('Foo' => 'Bar')); + $r2 = $r->withAddedHeader('Foo', 'Baz'); + $this->assertNotSame($r, $r2); + $this->assertEquals('Bar, Baz', $r2->getHeaderLine('foo')); + } + + public function testNewInstanceWhenAddingHeaderArray() + { + $r = new Response(200, array('Foo' => 'Bar')); + $r2 = $r->withAddedHeader('Foo', array('Baz', 'Qux')); + $this->assertNotSame($r, $r2); + $this->assertEquals(array('Bar', 'Baz', 'Qux'), $r2->getHeader('foo')); + } + + public function testNewInstanceWhenAddingHeaderThatWasNotThereBefore() + { + $r = new Response(200, array('Foo' => 'Bar')); + $r2 = $r->withAddedHeader('Baz', 'Bam'); + $this->assertNotSame($r, $r2); + $this->assertEquals('Bam', $r2->getHeaderLine('Baz')); + $this->assertEquals('Bar', $r2->getHeaderLine('Foo')); + } + + public function testRemovesPreviouslyAddedHeaderOfDifferentCase() + { + $r = new Response(200, array('Foo' => 'Bar')); + $r2 = $r->withHeader('foo', 'Bam'); + $this->assertNotSame($r, $r2); + $this->assertEquals('Bam', $r2->getHeaderLine('Foo')); + } + + public function testBodyConsistent() + { + $r = new Response(200, array(), '0'); + $this->assertEquals('0', (string)$r->getBody()); + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ServerRequestTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ServerRequestTest.php new file mode 100644 index 0000000..4bdfe8e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/ServerRequestTest.php @@ -0,0 +1,85 @@ +request = new ServerRequest('GET', 'http://localhost'); + } + + public function testGetNoAttributes() + { + $this->assertEquals(array(), $this->request->getAttributes()); + } + + public function testWithAttribute() + { + $request = $this->request->withAttribute('hello', 'world'); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('hello' => 'world'), $request->getAttributes()); + } + + public function testGetAttribute() + { + $request = $this->request->withAttribute('hello', 'world'); + + $this->assertNotSame($request, $this->request); + $this->assertEquals('world', $request->getAttribute('hello')); + } + + public function testGetDefaultAttribute() + { + $request = $this->request->withAttribute('hello', 'world'); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(null, $request->getAttribute('hi', null)); + } + + public function testWithoutAttribute() + { + $request = $this->request->withAttribute('hello', 'world'); + $request = $request->withAttribute('test', 'nice'); + + $request = $request->withoutAttribute('hello'); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('test' => 'nice'), $request->getAttributes()); + } + + public function testWithCookieParams() + { + $request = $this->request->withCookieParams(array('test' => 'world')); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('test' => 'world'), $request->getCookieParams()); + } + + public function testWithQueryParams() + { + $request = $this->request->withQueryParams(array('test' => 'world')); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('test' => 'world'), $request->getQueryParams()); + } + + public function testWithUploadedFiles() + { + $request = $this->request->withUploadedFiles(array('test' => 'world')); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('test' => 'world'), $request->getUploadedFiles()); + } + + public function testWithParsedBody() + { + $request = $this->request->withParsedBody(array('test' => 'world')); + + $this->assertNotSame($request, $this->request); + $this->assertEquals(array('test' => 'world'), $request->getParsedBody()); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamDecoratorTraitTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamDecoratorTraitTest.php new file mode 100644 index 0000000..b0c3dc5 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamDecoratorTraitTest.php @@ -0,0 +1,123 @@ +c = fopen('php://temp', 'r+'); + fwrite($this->c, 'foo'); + fseek($this->c, 0); + $this->a = Psr7\stream_for($this->c); + $this->b = new Str($this->a); + } + + public function testCatchesExceptionsWhenCastingToString() + { + $s = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('read')) + ->getMockForAbstractClass(); + $s->expects($this->once()) + ->method('read') + ->will($this->throwException(new \Exception('foo'))); + $msg = ''; + set_error_handler(function ($errNo, $str) use (&$msg) { + $msg = $str; + }); + echo new Str($s); + restore_error_handler(); + $this->assertContains('foo', $msg); + } + + public function testToString() + { + $this->assertEquals('foo', (string)$this->b); + } + + public function testHasSize() + { + $this->assertEquals(3, $this->b->getSize()); + } + + public function testReads() + { + $this->assertEquals('foo', $this->b->read(10)); + } + + public function testCheckMethods() + { + $this->assertEquals($this->a->isReadable(), $this->b->isReadable()); + $this->assertEquals($this->a->isWritable(), $this->b->isWritable()); + $this->assertEquals($this->a->isSeekable(), $this->b->isSeekable()); + } + + public function testSeeksAndTells() + { + $this->b->seek(1); + $this->assertEquals(1, $this->a->tell()); + $this->assertEquals(1, $this->b->tell()); + $this->b->seek(0); + $this->assertEquals(0, $this->a->tell()); + $this->assertEquals(0, $this->b->tell()); + $this->b->seek(0, SEEK_END); + $this->assertEquals(3, $this->a->tell()); + $this->assertEquals(3, $this->b->tell()); + } + + public function testGetsContents() + { + $this->assertEquals('foo', $this->b->getContents()); + $this->assertEquals('', $this->b->getContents()); + $this->b->seek(1); + $this->assertEquals('oo', $this->b->getContents(1)); + } + + public function testCloses() + { + $this->b->close(); + $this->assertFalse(is_resource($this->c)); + } + + public function testDetaches() + { + $this->b->detach(); + $this->assertFalse($this->b->isReadable()); + } + + public function testWrapsMetadata() + { + $this->assertSame($this->b->getMetadata(), $this->a->getMetadata()); + $this->assertSame($this->b->getMetadata('uri'), $this->a->getMetadata('uri')); + } + + public function testWrapsWrites() + { + $this->b->seek(0, SEEK_END); + $this->b->write('foo'); + $this->assertEquals('foofoo', (string)$this->a); + } + + /** + * @expectedException \UnexpectedValueException + */ + public function testThrowsWithInvalidGetter() + { + $this->b->foo; + } + +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamTest.php new file mode 100644 index 0000000..5501805 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamTest.php @@ -0,0 +1,163 @@ +assertTrue($stream->isReadable()); + $this->assertTrue($stream->isWritable()); + $this->assertTrue($stream->isSeekable()); + $this->assertEquals('php://temp', $stream->getMetadata('uri')); + $this->assertInternalType('array', $stream->getMetadata()); + $this->assertEquals(4, $stream->getSize()); + $this->assertFalse($stream->eof()); + $stream->close(); + } + + public function testStreamClosesHandleOnDestruct() + { + $handle = fopen('php://temp', 'r'); + $stream = new Stream($handle); + unset($stream); + $this->assertFalse(is_resource($handle)); + } + + public function testConvertsToString() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertEquals('data', (string) $stream); + $this->assertEquals('data', (string) $stream); + $stream->close(); + } + + public function testGetsContents() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertEquals('', $stream->getContents()); + $stream->seek(0); + $this->assertEquals('data', $stream->getContents()); + $this->assertEquals('', $stream->getContents()); + } + + public function testChecksEof() + { + $handle = fopen('php://temp', 'w+'); + fwrite($handle, 'data'); + $stream = new Stream($handle); + $this->assertFalse($stream->eof()); + $stream->read(4); + $this->assertTrue($stream->eof()); + $stream->close(); + } + + public function testGetSize() + { + $size = filesize(__FILE__); + $handle = fopen(__FILE__, 'r'); + $stream = new Stream($handle); + $this->assertEquals($size, $stream->getSize()); + // Load from cache + $this->assertEquals($size, $stream->getSize()); + $stream->close(); + } + + public function testEnsuresSizeIsConsistent() + { + $h = fopen('php://temp', 'w+'); + $this->assertEquals(3, fwrite($h, 'foo')); + $stream = new Stream($h); + $this->assertEquals(3, $stream->getSize()); + $this->assertEquals(4, $stream->write('test')); + $this->assertEquals(7, $stream->getSize()); + $this->assertEquals(7, $stream->getSize()); + $stream->close(); + } + + public function testProvidesStreamPosition() + { + $handle = fopen('php://temp', 'w+'); + $stream = new Stream($handle); + $this->assertEquals(0, $stream->tell()); + $stream->write('foo'); + $this->assertEquals(3, $stream->tell()); + $stream->seek(1); + $this->assertEquals(1, $stream->tell()); + $this->assertSame(ftell($handle), $stream->tell()); + $stream->close(); + } + + public function testCanDetachStream() + { + $r = fopen('php://temp', 'w+'); + $stream = new Stream($r); + $stream->write('foo'); + $this->assertTrue($stream->isReadable()); + $this->assertSame($r, $stream->detach()); + $stream->detach(); + + $this->assertFalse($stream->isReadable()); + $this->assertFalse($stream->isWritable()); + $this->assertFalse($stream->isSeekable()); + + $self = $this; + + $throws = function ($fn) use ($stream, $self) { + try { + $fn($stream); + $self->fail(); + } catch (\Exception $e) {} + }; + + $throws(function ($stream) { $stream->read(10); }); + $throws(function ($stream) { $stream->write('bar'); }); + $throws(function ($stream) { $stream->seek(10); }); + $throws(function ($stream) { $stream->tell(); }); + $throws(function ($stream) { $stream->eof(); }); + $throws(function ($stream) { $stream->getSize(); }); + $throws(function ($stream) { $stream->getContents(); }); + $this->assertSame('', (string) $stream); + $stream->close(); + } + + public function testCloseClearProperties() + { + $handle = fopen('php://temp', 'r+'); + $stream = new Stream($handle); + $stream->close(); + + $this->assertFalse($stream->isSeekable()); + $this->assertFalse($stream->isReadable()); + $this->assertFalse($stream->isWritable()); + $this->assertNull($stream->getSize()); + $this->assertEmpty($stream->getMetadata()); + } + + public function testDoesNotThrowInToString() + { + $s = \RingCentral\Psr7\stream_for('foo'); + $s = new NoSeekStream($s); + $this->assertEquals('foo', (string) $s); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamWrapperTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamWrapperTest.php new file mode 100644 index 0000000..dd08a83 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/StreamWrapperTest.php @@ -0,0 +1,100 @@ +assertSame('foo', fread($handle, 3)); + $this->assertSame(3, ftell($handle)); + $this->assertSame(3, fwrite($handle, 'bar')); + $this->assertSame(0, fseek($handle, 0)); + $this->assertSame('foobar', fread($handle, 6)); + $this->assertSame('', fread($handle, 1)); + $this->assertTrue(feof($handle)); + + // This fails on HHVM for some reason + if (!defined('HHVM_VERSION')) { + $this->assertEquals(array( + 'dev' => 0, + 'ino' => 0, + 'mode' => 33206, + 'nlink' => 0, + 'uid' => 0, + 'gid' => 0, + 'rdev' => 0, + 'size' => 6, + 'atime' => 0, + 'mtime' => 0, + 'ctime' => 0, + 'blksize' => 0, + 'blocks' => 0, + 0 => 0, + 1 => 0, + 2 => 33206, + 3 => 0, + 4 => 0, + 5 => 0, + 6 => 0, + 7 => 6, + 8 => 0, + 9 => 0, + 10 => 0, + 11 => 0, + 12 => 0, + ), fstat($handle)); + } + + $this->assertTrue(fclose($handle)); + $this->assertSame('foobar', (string) $stream); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testValidatesStream() + { + $stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isReadable', 'isWritable')) + ->getMockForAbstractClass(); + $stream->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(false)); + $stream->expects($this->once()) + ->method('isWritable') + ->will($this->returnValue(false)); + StreamWrapper::getResource($stream); + } + + /** + * @expectedException \PHPUnit_Framework_Error_Warning + */ + public function testReturnsFalseWhenStreamDoesNotExist() + { + fopen('guzzle://foo', 'r'); + } + + public function testCanOpenReadonlyStream() + { + $stream = $this->getMockBuilder('Psr\Http\Message\StreamInterface') + ->setMethods(array('isReadable', 'isWritable')) + ->getMockForAbstractClass(); + $stream->expects($this->once()) + ->method('isReadable') + ->will($this->returnValue(false)); + $stream->expects($this->once()) + ->method('isWritable') + ->will($this->returnValue(true)); + $r = StreamWrapper::getResource($stream); + $this->assertInternalType('resource', $r); + fclose($r); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/UriTest.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/UriTest.php new file mode 100644 index 0000000..b53c97e --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/UriTest.php @@ -0,0 +1,258 @@ +assertEquals( + 'https://michael:test@test.com/path/123?q=abc#test', + (string) $uri + ); + + $this->assertEquals('test', $uri->getFragment()); + $this->assertEquals('test.com', $uri->getHost()); + $this->assertEquals('/path/123', $uri->getPath()); + $this->assertEquals(null, $uri->getPort()); + $this->assertEquals('q=abc', $uri->getQuery()); + $this->assertEquals('https', $uri->getScheme()); + $this->assertEquals('michael:test', $uri->getUserInfo()); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage Unable to parse URI + */ + public function testValidatesUriCanBeParsed() + { + // Due to 5.4.7 "Fixed host recognition when scheme is omitted and a leading component separator is present" this does not work in 5.3 + //new Uri('///'); + throw new \InvalidArgumentException('Unable to parse URI'); + } + + public function testCanTransformAndRetrievePartsIndividually() + { + $uri = new Uri(''); + $uri = $uri->withFragment('#test') + ->withHost('example.com') + ->withPath('path/123') + ->withPort(8080) + ->withQuery('?q=abc') + ->withScheme('http') + ->withUserInfo('user', 'pass'); + + // Test getters. + $this->assertEquals('user:pass@example.com:8080', $uri->getAuthority()); + $this->assertEquals('test', $uri->getFragment()); + $this->assertEquals('example.com', $uri->getHost()); + $this->assertEquals('path/123', $uri->getPath()); + $this->assertEquals(8080, $uri->getPort()); + $this->assertEquals('q=abc', $uri->getQuery()); + $this->assertEquals('http', $uri->getScheme()); + $this->assertEquals('user:pass', $uri->getUserInfo()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testPortMustBeValid() + { + $uri = new Uri(''); + $uri->withPort(100000); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testPathMustBeValid() + { + $uri = new Uri(''); + $uri->withPath(array()); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testQueryMustBeValid() + { + $uri = new Uri(''); + $uri->withQuery(new \stdClass); + } + + public function testAllowsFalseyUrlParts() + { + $url = new Uri('http://a:1/0?0#0'); + $this->assertSame('a', $url->getHost()); + $this->assertEquals(1, $url->getPort()); + $this->assertSame('/0', $url->getPath()); + $this->assertEquals('0', (string) $url->getQuery()); + $this->assertSame('0', $url->getFragment()); + $this->assertEquals('http://a:1/0?0#0', (string) $url); + $url = new Uri(''); + $this->assertSame('', (string) $url); + $url = new Uri('0'); + $this->assertSame('0', (string) $url); + $url = new Uri('/'); + $this->assertSame('/', (string) $url); + } + + /** + * @dataProvider getResolveTestCases + */ + public function testResolvesUris($base, $rel, $expected) + { + $uri = new Uri($base); + $actual = Uri::resolve($uri, $rel); + $this->assertEquals($expected, (string) $actual); + } + + public function getResolveTestCases() + { + return array( + //[self::RFC3986_BASE, 'g:h', 'g:h'], + array(self::RFC3986_BASE, 'g', 'http://a/b/c/g'), + array(self::RFC3986_BASE, './g', 'http://a/b/c/g'), + array(self::RFC3986_BASE, 'g/', 'http://a/b/c/g/'), + array(self::RFC3986_BASE, '/g', 'http://a/g'), + // Due to 5.4.7 "Fixed host recognition when scheme is omitted and a leading component separator is present" this does not work in 5.3 + //array(self::RFC3986_BASE, '//g', 'http://g'), + array(self::RFC3986_BASE, '?y', 'http://a/b/c/d;p?y'), + array(self::RFC3986_BASE, 'g?y', 'http://a/b/c/g?y'), + array(self::RFC3986_BASE, '#s', 'http://a/b/c/d;p?q#s'), + array(self::RFC3986_BASE, 'g#s', 'http://a/b/c/g#s'), + array(self::RFC3986_BASE, 'g?y#s', 'http://a/b/c/g?y#s'), + array(self::RFC3986_BASE, ';x', 'http://a/b/c/;x'), + array(self::RFC3986_BASE, 'g;x', 'http://a/b/c/g;x'), + array(self::RFC3986_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s'), + array(self::RFC3986_BASE, '', self::RFC3986_BASE), + array(self::RFC3986_BASE, '.', 'http://a/b/c/'), + array(self::RFC3986_BASE, './', 'http://a/b/c/'), + array(self::RFC3986_BASE, '..', 'http://a/b/'), + array(self::RFC3986_BASE, '../', 'http://a/b/'), + array(self::RFC3986_BASE, '../g', 'http://a/b/g'), + array(self::RFC3986_BASE, '../..', 'http://a/'), + array(self::RFC3986_BASE, '../../', 'http://a/'), + array(self::RFC3986_BASE, '../../g', 'http://a/g'), + array(self::RFC3986_BASE, '../../../g', 'http://a/g'), + array(self::RFC3986_BASE, '../../../../g', 'http://a/g'), + array(self::RFC3986_BASE, '/./g', 'http://a/g'), + array(self::RFC3986_BASE, '/../g', 'http://a/g'), + array(self::RFC3986_BASE, 'g.', 'http://a/b/c/g.'), + array(self::RFC3986_BASE, '.g', 'http://a/b/c/.g'), + array(self::RFC3986_BASE, 'g..', 'http://a/b/c/g..'), + array(self::RFC3986_BASE, '..g', 'http://a/b/c/..g'), + array(self::RFC3986_BASE, './../g', 'http://a/b/g'), + array(self::RFC3986_BASE, 'foo////g', 'http://a/b/c/foo////g'), + array(self::RFC3986_BASE, './g/.', 'http://a/b/c/g/'), + array(self::RFC3986_BASE, 'g/./h', 'http://a/b/c/g/h'), + array(self::RFC3986_BASE, 'g/../h', 'http://a/b/c/h'), + array(self::RFC3986_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y'), + array(self::RFC3986_BASE, 'g;x=1/../y', 'http://a/b/c/y'), + array('http://u@a/b/c/d;p?q', '.', 'http://u@a/b/c/'), + array('http://u:p@a/b/c/d;p?q', '.', 'http://u:p@a/b/c/'), + //[self::RFC3986_BASE, 'http:g', 'http:g'], + ); + } + + public function testAddAndRemoveQueryValues() + { + $uri = new Uri('http://foo.com/bar'); + $uri = Uri::withQueryValue($uri, 'a', 'b'); + $uri = Uri::withQueryValue($uri, 'c', 'd'); + $uri = Uri::withQueryValue($uri, 'e', null); + $this->assertEquals('a=b&c=d&e', $uri->getQuery()); + + $uri = Uri::withoutQueryValue($uri, 'c'); + $uri = Uri::withoutQueryValue($uri, 'e'); + $this->assertEquals('a=b', $uri->getQuery()); + $uri = Uri::withoutQueryValue($uri, 'a'); + $uri = Uri::withoutQueryValue($uri, 'a'); + $this->assertEquals('', $uri->getQuery()); + } + + public function testGetAuthorityReturnsCorrectPort() + { + // HTTPS non-standard port + $uri = new Uri('https://foo.co:99'); + $this->assertEquals('foo.co:99', $uri->getAuthority()); + + // HTTP non-standard port + $uri = new Uri('http://foo.co:99'); + $this->assertEquals('foo.co:99', $uri->getAuthority()); + + // No scheme + $uri = new Uri('foo.co:99'); + $this->assertEquals('foo.co:99', $uri->getAuthority()); + + // No host or port + $uri = new Uri('http:'); + $this->assertEquals('', $uri->getAuthority()); + + // No host or port + $uri = new Uri('http://foo.co'); + $this->assertEquals('foo.co', $uri->getAuthority()); + } + + public function pathTestProvider() + { + return array( + // Percent encode spaces. + array('http://foo.com/baz bar', 'http://foo.com/baz%20bar'), + // Don't encoding something that's already encoded. + array('http://foo.com/baz%20bar', 'http://foo.com/baz%20bar'), + // Percent encode invalid percent encodings + array('http://foo.com/baz%2-bar', 'http://foo.com/baz%252-bar'), + // Don't encode path segments + array('http://foo.com/baz/bar/bam?a', 'http://foo.com/baz/bar/bam?a'), + array('http://foo.com/baz+bar', 'http://foo.com/baz+bar'), + array('http://foo.com/baz:bar', 'http://foo.com/baz:bar'), + array('http://foo.com/baz@bar', 'http://foo.com/baz@bar'), + array('http://foo.com/baz(bar);bam/', 'http://foo.com/baz(bar);bam/'), + array('http://foo.com/a-zA-Z0-9.-_~!$&\'()*+,;=:@', 'http://foo.com/a-zA-Z0-9.-_~!$&\'()*+,;=:@'), + ); + } + + /** + * @dataProvider pathTestProvider + */ + public function testUriEncodesPathProperly($input, $output) + { + $uri = new Uri($input); + $this->assertEquals((string) $uri, $output); + } + + public function testDoesNotAddPortWhenNoPort() + { + // Due to 5.4.7 "Fixed host recognition when scheme is omitted and a leading component separator is present" this does not work in 5.3 + //$uri = new Uri('//bar'); + //$this->assertEquals('bar', (string) $uri); + //$uri = new Uri('//barx'); + //$this->assertEquals('barx', $uri->getHost()); + } + + public function testAllowsForRelativeUri() + { + $uri = new Uri(); + $uri = $uri->withPath('foo'); + $this->assertEquals('foo', $uri->getPath()); + $this->assertEquals('foo', (string) $uri); + } + + public function testAddsSlashForRelativeUriStringWithHost() + { + $uri = new Uri(); + $uri = $uri->withPath('foo')->withHost('bar.com'); + $this->assertEquals('foo', $uri->getPath()); + $this->assertEquals('bar.com/foo', (string) $uri); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/bootstrap.php b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/bootstrap.php new file mode 100644 index 0000000..ea6a079 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/ringcentral/psr7/tests/bootstrap.php @@ -0,0 +1,13 @@ +setStorageKey($key); + $this->loadData(); + } + + /** + * Get data by key (can be path divided by dots - `.`) or return all if no key present. + * @param null $key + * @param null $default + * @return mixed + */ + public function get($key = null, $default = null) + { + if (is_null($key)) { + + return $this->data; + + } else { + + return Arr::get($this->data, $key); + + } + + } + + /** + * Set data to storage + * + * @param $key + * @param $value + * @return $this + */ + public function set($key, $value) + { + Arr::set($this->data, $key, $value); + $this->dataUpdate[] = $this->splitKeyPath($key)[0]; + + $this->persistData(); + + return $this; + } + + /** + * Is there data in storage + * + * @param $key + * @return bool + */ + public function has($key) + { + //$this->loadData(); + + return Arr::has($this->data, $key); + } + + /** + * Remove data from storage + * @param $key + * @return $this + */ + public function remove($key) + { + // Arrays::forget($this->data, $key); + $this->dataRemove[] = $this->splitKeyPath($key)[0]; + + $this->persistData(); + + return $this; + } + + // --- Internal + + protected function loadData() + { + // Nothing to process + if ($this->dataLoaded) { + return $this; + } + + $data = Capsule::table('tbladdonmodules')->select('setting', 'value')->where('module', $this->getStorageKey())->get(); + + foreach ($data as $row) { + $key = $row->setting; + $value = $row->value; + + // try { + // $value = @json_decode($value); + // } catch (\Exception $e) { + // continue; + // } + + $this->data[ $key ] = $value; + } + + $this->dataLoaded = $this; + + return $this; + } + + protected function persistData() + { + // Nothing to update + // if (empty($this->dataUpdate) || empty($this->dataRemove)) { + // return $this; + // } + + // Skip any duplicates + $this->dataUpdate = array_unique($this->dataUpdate); + $this->dataRemove = array_unique($this->dataRemove); + + $storageKey = $this->getStorageKey(); + + foreach ($this->dataUpdate as $mainKey) { + + if (isset($this->data[$mainKey])) { + + $data = $this->data[$mainKey]; + $row = Capsule::table('tbladdonmodules')->select('id')->where(['module' => $storageKey, 'setting' => $mainKey])->first(); + // Determine method + if (!empty($row->id)) { + // Insert + Capsule::table('tbladdonmodules')->where('id', $row->id)->update(['value' => $data]); + } else { + // Update + Capsule::table('tbladdonmodules')->insert(['module' => $storageKey, 'setting' => $mainKey, 'value' => $data]); + } + + unset($this->data[$mainKey]); + } + } + $this->dataUpdate = []; + + foreach ($this->dataRemove as $mainKey) { + + if (isset($this->data[$mainKey])) { + + Capsule::table('tbladdonmodules')->where([['module', $storageKey], ['setting', $mainKey]])->delete(); + + unset($this->data[$mainKey]); + } + } + + $this->dataRemove = []; + + return $this; + } + + // --- Helpers + + /** + * Get scope for db storage + * + * @return string + */ + protected function getStorageKey() + { + return $this->storageKey; + } + + public function setStorageKey($key) + { + $this->storageKey = $key; + } + + /** + * Get ["main", "sub.path"] from "main.sub.path" string + * @param $key + * @return array + */ + protected function splitKeyPath($key) + { + // It's already main key with subpath items + if (false === strpos($key, '.')) { + return [$key, null]; + } + + $key = explode('.', $key); + + return [$key[ 0 ], join('.', array_slice($key, 1))]; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Gateway/GatewayStorage.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Gateway/GatewayStorage.php new file mode 100644 index 0000000..2ab7d7c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Gateway/GatewayStorage.php @@ -0,0 +1,233 @@ +storageKey = self::STORAGE_KEY; + $this->module = self::SYSTEM_NAME; + $this->loadData(); + } + + /** + * Seta a chave de storage do gateway (seu nome) para acessar seus atributos + * no banco de dados + * @param string $gateway nome do gateway de pagamento + */ + public function setGateway($gateway) + { + $this->storageKey = $gateway; + } + + /** + * Get data by key (can be path divided by dots - `.`) + * @param $key + * @param null $default + * @return mixed + */ + public function get($key, $default = null) + { + $this->loadData(); + + return Arr::get($this->data, $key); + } + + public function getAll() + { + $this->loadData(); + + return $this->data; + } + + /** + * Set data to storage + * + * @param $key + * @param $value + * @return $this + */ + public function set($key, $value) + { + Arr::set($this->data, $key, $value); + $this->dataUpdate[] = $this->splitKeyPath($key)[0]; + + $this->persistData(); + + return $this; + } + + /** + * Is there data in storage + * + * @param $key + * @return bool + */ + public function has($key) + { + $this->loadData(); + + return Arr::has($this->data, $key); + } + + /** + * Remove data from storage + * @param $key + * @return $this + */ + public function remove($key) + { + // Arrays::forget($this->data, $key); + $this->dataRemove[] = $this->splitKeyPath($key)[0]; + + $this->persistData(); + + return $this; + } + + // --- Internal + + protected function loadData() + { + // Nothing to process + if ($this->dataLoaded) { + return $this; + } + + $data = Capsule::table('tblpaymentgateways')->select('setting', 'value')->where('gateway', $this->getStorageKey())->get(); + + foreach ($data as $row) { + $key = $row->setting; + $value = $row->value; + + // try { + // $value = @json_decode($value); + // } catch (\Exception $e) { + // continue; + // } + + $this->data[ $key ] = $value; + } + + // $this->dataLoaded = true; + + return $this; + } + + protected function persistData() + { + // Nothing to update + // if (empty($this->dataUpdate) || empty($this->dataRemove)) { + // return $this; + // } + + // Skip any duplicates + $this->dataUpdate = array_unique($this->dataUpdate); + $this->dataRemove = array_unique($this->dataRemove); + + $storageKey = $this->getStorageKey(); + + foreach ($this->dataUpdate as $mainKey) { + + if (isset($this->data[$mainKey])) { + + $data = $this->data[$mainKey]; + $row = Capsule::table('tblpaymentgateways')->select('id')->where(['gateway' => $storageKey, 'setting' => $mainKey])->first(); + // Determine method + if (!empty($row->id)) { + // Insert + Capsule::table('tblpaymentgateways')->where('id', $row->id)->update(['value' => $data]); + } else { + // Update + Capsule::table('tblpaymentgateways')->insert(['gateway' => $storageKey, 'setting' => $mainKey, 'value' => $data]); + } + + unset($this->data[$mainKey]); + } + } + $this->dataUpdate = []; + + foreach ($this->dataRemove as $mainKey) { + + if (isset($this->data[$mainKey])) { + + Capsule::table('tblpaymentgateways')->where([['gateway', $storageKey], ['setting', $mainKey]])->delete(); + + unset($this->data[$mainKey]); + } + } + + $this->dataRemove = []; + + return $this; + } + + // --- Helpers + + /** + * Get scope for db storage + * + * @return string + */ + protected function getStorageKey() + { + return $this->storageKey; + } + + /** + * Get ["main", "sub.path"] from "main.sub.path" string + * @param $key + * @return array + */ + protected function splitKeyPath($key) + { + // It's already main key with subpath items + if (false === strpos($key, '.')) { + return [$key, null]; + } + + $key = explode('.', $key); + + return [$key[ 0 ], join('.', array_slice($key, 1))]; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Helper/Helper.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Helper/Helper.php new file mode 100644 index 0000000..dc78f5b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/Helper/Helper.php @@ -0,0 +1,61 @@ +_helper = new Helper; + + $this->_smarty = new Smarty; + $this->_smarty->caching = false; + $this->_smarty->compile_check = true; + $this->_smarty->debugging = false; + $this->_smarty->template_dir = $templateDir; + $this->_smarty->compile_dir = $GLOBALS['templates_compiledir']; + // $this->_smarty->cache_dir = dirname(dirname(__DIR__)) . '/templates/cache'; + + // return $this->smarty = $smarty; + } + + // public function getTemplatesDir($file) + // { + // return $this->_helper->getDirectory($file) . "/templates"; + // } + + /** + * Fetch Smarty template + * @param string $template The tpl path/file that will be fetch + * @param array $vars Any Smarty assing variables to the tpl file + * @return string the html Smarty data + */ + public function fetch($file, $vars = array()) + { + + // $templateDir = rtrim($dir ? $dir : $this->getTemplatesDir($file), '/'); + // $this->_smarty->template_dir = $templateDir; + + if (is_array($vars)) { + foreach ($vars as $key => $val) { + $this->_smarty->assign($key, $val); + } + } + + return $this->_smarty->fetch("{$file}.tpl"); + } + + /** + * Display Smarty template + * @param string $template The tpl path/file that will be fetch + * @param array $vars Any Smarty assing variables to the tpl file + * @return string the html Smarty data + */ + public function display($file, $vars = array()) + { + + // $templateDir = rtrim($dir ? $dir : $this->getTemplatesDir($file), '/'); + // $this->_smarty->template_dir = $templateDir; + + + if (is_array($vars)) { + foreach ($vars as $key => $val) { + $this->_smarty->assign($key, $val); + } + } + + return $this->_smarty->display("{$file}.tpl"); + + // return $this->_smarty->display($template.'.tpl', uniqid()); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Exception.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Exception.php new file mode 100644 index 0000000..1f5c71d --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Exception.php @@ -0,0 +1,17 @@ +_query = $query; + $code = (int) $code; + parent::__construct($message, $code, $previous); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/PdoWrapper.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/PdoWrapper.php new file mode 100644 index 0000000..d6e10ab --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/PdoWrapper.php @@ -0,0 +1,46 @@ +getPdo() + ->prepare($query); + $statement->execute($params); + return $statement; + } + + public static function realEscapeString($string) { + return substr(DB::connection()->getPdo()->quote($string), 1, -1); + } + + public static function fetchAssoc($query) { + return $query->fetch(\PDO::FETCH_ASSOC); + } + + public static function fetchArray($query) { + return $query->fetch(\PDO::FETCH_BOTH); + } + + public static function fetchObject($query) { + return $query->fetch(\PDO::FETCH_OBJ); + } + + public static function numRows($query) { + $query->fetch(\PDO::FETCH_BOTH); + return $query->rowCount(); + } + + public static function insertId() { + return DB::connection() + ->getPdo() + ->lastInsertId(); + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Query.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Query.php new file mode 100644 index 0000000..aba76c7 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Query.php @@ -0,0 +1,555 @@ + + */ + public static function useCurrentConnection(){ + //Use by default PDO in WHMCS 6 and 7 + if(class_exists('\Illuminate\Database\Capsule\Manager') && \Illuminate\Database\Capsule\Manager::connection()->getPdo()) + { + self::$usePDO = true; + self::$_instance->connection['default'] = \Illuminate\Database\Capsule\Manager::connection()->getPdo(); + } + else + { + self::$_instance = new self(); + self::$_instance->connection['default'] = false; + } + } + + /** + * Connect DB From File + * + * @param string $file + * @throws main\exception\System + * @return boolean + */ + public static function connectFromFile($file){ + if(!file_exists($file)) + { + throw new main\mtLibs\exceptions\System('DB Connection File does not exits', main\mtLibs\exceptions\Codes::MYSQL_MISING_CONFIG_FILE); + } + + self::$_instance = new self(); + + include $file; + + foreach($config as $connectionName => $config) + { + if ($config['host']) + { + if(!extension_loaded('PDO')) + { + throw new main\mtLibs\exceptions\System('Missing PDO Extension', main\mtLibs\exceptions\Codes::MYSQL_MISING_PDO_EXTENSION); + } + + try{ + self::$_instance->connection[$connectionName] = new \PDO("mysql:host=".$config['host'].";dbname=".$config['name'], $config['user'], $config['pass']); + + self::$_instance->connection[$connectionName]->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); + } catch (\Exception $ex) { + throw new main\mtLibs\exceptions\System('SQL Connection Error',exceptions\Codes::MYSQL_CONNECTION_FAILED); + } + } + } + + return true; + } + + /** + * Disconnect all mysql connection + * + */ + static function dropAllConnection(){ + foreach(self::I()->connection as $name => &$connection) + { + $connection = null; + unset(self::I()->connection[$name]); + } + } + + /** + * Custom MySQL Query + * + * @param string $query + * @param array $params + * @param string $connectionName + * @return result + * @throws main\mtLibs\exceptions\System + */ + static function query($query,array $params=array(), $connectionName = 'default') + { + if(!isset(self::$_instance->connection[$connectionName])) + { + throw new main\mtLibs\exceptions\System("Connection ".$connectionName.' not exits', main\mtLibs\exceptions\Codes::MYSQL_MISING_CONNECTION); + } + + $newParams = array(); + foreach($params as $name => $value) + { + $newParams[':'.$name] = $value; + } + + $params = $newParams; + try{ + $sth = self::$_instance->connection[$connectionName]->prepare($query); + $a = $sth->execute($params); + } catch (\Exception $ex) { + $dQuery = $query; + foreach($params as $n => $v) + { + $dQuery = str_replace($n, "'".$v."'", $dQuery); + } + + throw new Exception('Error in SQL Query:'.$ex->getMessage(),$dQuery,$ex); + } + + if(strpos($query, 'insert') !== false || strpos($query, 'INSERT')!== false ) + { + $id = self::$_instance->connection[$connectionName]->lastInsertId(); + } + else + { + $id = null; + } + + return new Result($sth,$id); + + } + + /** + * Disconnect specifi MySQL socket + * + * @param string $connectionName + */ + static function dropInstance($connectionName = 'default') + { + unset(self::$_instance->connection[$connectionName]); + } + + /** + * Simple Insert Query + * + * @param string $table + * @param array $data + * @param string $connectionName + * @throws \exception\System + * @return int id of new record + */ + static function insert($table,array $data, $connectionName = 'default') + { + $cols = array(); + $valuesLabels = array(); + $values = array(); + $i = 0; + foreach($data as $col => $value) + { + $cols[] = $col; + $colName = 'col'.$i; + $valuesLabels[] = ':'.$colName; + + $values[$colName] = $value; + $i++; + } + + $cols = implode("`,`", $cols); + $valuesLabels = implode(",", $valuesLabels); + + $sql = "INSERT INTO $table (`$cols`) VALUES ($valuesLabels)"; + + $val = self::query($sql,$values,$connectionName)->getID(); + + return $val; + } + + /** + * Simple Insert Query + * + * @param string $table + * @param array $data + * @param string $connectionName + * @throws \exception\System + * @return int id of new record + */ + static function insertOnDuplicateUpdate($table,array $data, array $update, $connectionName = 'default') + { + $cols = array(); + $valuesLabels = array(); + $values = array(); + $i = 0; + foreach($data as $col => $value) + { + $cols[] = $col; + $colName = 'col'.$i; + $valuesLabels[] = ':'.$colName; + + $values[$colName] = $value; + $i++; + } + + $cols = implode("`,`", $cols); + $valuesLabels = implode(",", $valuesLabels); + + + $sql = "INSERT INTO $table (`$cols`) VALUES ($valuesLabels)"; + + $sql .= "ON DUPLICATE KEY UPDATE "; + + $cols = array(); + $valuesLabels = array(); + + foreach($update as $col => $value) + { + $colName = preg_replace("/[^A-Za-z0-9]/", '', $col); + + $cols[] = "`$col` = :$colName:"; + + $values[$colName] = $value; + } + + $sql .= implode(",", $cols); + + $val = self::query($sql,$values,$connectionName)->getID(); + + return $val; + } + + /** + * Simple Update Request + * + * @param string $table + * @param array $data + * @param array $condition + * @param array $conditionValues + * @throws \exception\System + * @return result + */ + static function update($table,array $data,array $condition) + { + $conditionParsed = self::parseConditions($condition,$values); + + $cols = array(); + $valuesLabels = array(); + + foreach($data as $col => $value) + { + $colName = preg_replace("/[^A-Za-z0-9]/", '', $col); + + $cols[] = "`$col` = :$colName"; + + $values[$colName] = $value; + } + + $cols = implode(",", $cols); + + $sql = "UPDATE $table SET $cols "; + + if($conditionParsed) + { + $sql .= " WHERE ".$conditionParsed; + } + + return self::query($sql,$values); + } + + /** + * Simple Delete Request + * + * @param string $table + * @param array $condition + * @param array $conditionValues + * @throws \exception\System + * @return result + */ + static function delete($table,array $condition) + { + $sql = "DELETE FROM $table"; + + $conditionParsed = self::parseConditions($condition,$values); + + if($conditionParsed) + { + $sql .= " WHERE ".$conditionParsed; + } + + return self::query($sql,$values); + } + + /** + * Parse MySQL Conditions + * + * @param type $condition + * @param type $values + * @return type + */ + static function parseConditions($condition,&$values, $prefix = null, &$i = 0){ + $conditionParsed = array(); + + $values = array(); + + foreach($condition as $col => $value) + { + if(is_string($col)) + { + if(is_array($value)) + { + $conditionTmp = array(); + foreach($value as $v) + { + $colName = ':cond'.$i; + $conditionTmp[] = $colName; + $values['cond'.$i] = $v; + $i++; + } + if($prefix) + { + $conditionParsed[] = "`$prefix`.`$col` in (".implode(',',$conditionTmp).')'; + } + else + { + $conditionParsed[] = "`$col` in (".implode(',',$conditionTmp).')'; + } + } + else + { + $colName = ':cond'.$i; + if($prefix) + { + $conditionParsed[] = "`$prefix`.`$col` = $colName"; + } + else + { + $conditionParsed[] = "`$col` = $colName"; + } + + $values['cond'.$i] = $value; + $i++; + } + } + elseif(is_array($value) && isset($value['customQuery'])) + { + $conditionParsed[] = $value['customQuery']; + foreach ($value['params'] as $n => $v) + { + $values[$n] = $v; + } + } + else + { + $conditionParsed[] = $value; + } + + } + + return implode(' AND ', $conditionParsed); + } + + static function formatSelectFields($cols,$prefix = null){ + foreach($cols as $name => &$value) + { + if(!is_int($name)) + { + if($prefix) + { + $value = "`$prefix`.`$name` as '$value'"; + } + else + { + $value = "`$name` as '$value'"; + } + } + else + { + if($prefix) + { + $value = "`$prefix`.`$value`"; + } + else + { + $value = "`$value`"; + } + } + } + unset($value); + + return implode(",", $cols); + } + + static function formatOrderBy($orderBy,$prefix = null){ + if(empty($orderBy)) + { + return; + } + + $tmp = array(); + foreach($orderBy as $col => $vect) + { + if($prefix) + { + $tmp[] = "`$prefix`.`$col` ".(($vect=='ASC'||$vect=='asc')?'ASC':'DESC'); + } + else + { + $tmp[] = "`$col` ".(($vect=='ASC'||$vect=='asc')?'ASC':'DESC'); + } + } + + return " ORDER BY ".implode(',', $tmp); + } + + static function formarLimit($limit,$offset) + { + if($limit) + { + if($offset) + { + return " LIMIT $offset , $limit "; + } + else + { + return " LIMIT 0 , $limit "; + } + } + } + + /** + * Simple Select Query + * + * @param array $cols + * @param string $table + * @param array $conditionValues + * @param array $groupBy + * @param int $limit + * @param int $offset + * @throws \exception\System + * @return result + */ + static function select(array $cols,$table,array $condition = array(),array $orderBy = array(),$limit = null,$offset = 0, $connectionName = 'default') + { + + $cols = self::formatSelectFields($cols); + + $sql = "SELECT $cols FROM $table"; + + $conditionParsed = self::parseConditions($condition,$values); + + if($conditionParsed) + { + $sql .= " WHERE ".$conditionParsed; + } + + $sql .= self::formatOrderBy($orderBy); + + $sql .= self::formarLimit($limit, $offset); + + + return self::query($sql,$values); + } + + /** + * Simple Select Query + * + * @param array $cols + * @param string $table + * @param array $conditionValues + * @param array $groupBy + * @param int $limit + * @param int $offset + * @throws \exception\System + * @return result + */ + static function count($colsName,$table,array $condition = array(),array $orderBy = array(),$limit = null,$offset = 0, $connectionName = 'default') + { + $sql = "SELECT count($colsName) as count FROM $table"; + + $conditionParsed = self::parseConditions($condition,$values); + + if($conditionParsed) + { + $sql .= " WHERE ".$conditionParsed; + } + + if($orderBy) + { + $sql .= " ORDER BY "; + $tmp = array(); + foreach($orderBy as $col => $vect) + { + $tmp[] = "`$col` $vect"; + } + $sql .= implode(',', $tmp); + } + + if($limit) + { + if($offset) + { + $sql .= " LIMIT $offset , $limit "; + } + else + { + $sql .= " LIMIT 0 , $limit "; + } + } + + return self::query($sql,$values)->fetchColumn('count'); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Result.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Result.php new file mode 100644 index 0000000..a75a0bc --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/MySQL/Result.php @@ -0,0 +1,92 @@ +result = $result; + $this->id = $id; + } + + /** + * Fetch one record + * + * @return array + */ + function fetch() + { + return $this->result->fetch(\PDO::FETCH_ASSOC); + } + + /** + * Fetch All Records + * + * @return array + */ + function fetchAll() + { + return $this->result->fetchAll(\PDO::FETCH_ASSOC); + } + + /** + * Fetch One Column From First Record + * + * @param string $name + * @return array + */ + function fetchColumn($name = null) + { + $data = $this->result->fetch(\PDO::FETCH_BOTH); + + if($name) + { + return $data[$name]; + } + else + { + return $data[0]; + } + } + + /** + * Get ID Last Inserted Record + * + * @return int + */ + function getID() + { + return $this->id; + } + +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/Smarty.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/Smarty.php new file mode 100644 index 0000000..f853b17 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/Smarty.php @@ -0,0 +1,137 @@ +_smarty = new \Smarty(); + // register the new Smarty internal resource file + // self::$_instance->_smarty->registerResource('file', new SmartyEncrypt()); + } + + return self::$_instance; + } + + /** + * Set Tempalte Dir + * + * @param string $dir + */ + public function setTemplateDir($dir) + { + if (is_array($dir)) { + throw new Exceptions\System('Wrong Template Path'); + } + self::I()->_templateDIR = $dir; + } + + /** + * Parse Template File + * + * @global string $templates_compiledir + * @param string $template + * @param array $vars + * @param string $customDir + * @return string + * @throws exceptions\System + */ + public function view($template, $vars = array(), $customDir = false) + { + if (is_array($customDir)) { + throw new Exceptions\System('Wrong Template Path'); + } + + global $templates_compiledir; + if ($customDir) { + self::I()->_smarty->template_dir = $customDir; + } else { + self::I()->_smarty->template_dir = self::I()->_templateDIR; + } + + self::I()->_smarty->compile_dir = $templates_compiledir; + self::I()->_smarty->force_compile = 1; + self::I()->_smarty->caching = 0; + + $this->clear(); + + // self::I()->_smarty->assign('MGLANG', Lang::getInstance()); + + if (is_array($vars)) { + foreach ($vars as $key => $val) { + self::I()->_smarty->assign($key, $val); + } + } + + if (is_array(self::I()->_smarty->template_dir)) { + if (strlen(self::I()->_smarty->template_dir[0]) > 3) { + $file = self::I()->_smarty->template_dir[0].DS.$template.'.tpl'; + } else { + $file = $template.'.tpl'; + } + } else { + if (strlen(self::I()->_smarty->template_dir) > 3) { + $file = self::I()->_smarty->template_dir.DS.$template.'.tpl'; + } else { + $file = $template.'.tpl'; + } + } + + + //$file = str_replace('\\', '', $file); + + if (substr($file, 0, 1) == '\\') { + $file = substr($file, 1); + } + + if (!file_exists($file)) { + throw new exceptions\System('Unable to find Template:'.$file); + } + + return self::I()->_smarty->fetch($template.'.tpl', uniqid()); + } + + protected function clear() + { + if (method_exists(self::I()->_smarty, 'clearAllAssign')) { + self::I()->_smarty->clearAllAssign(); + } elseif (method_exists(self::I()->_smarty, 'clear_all_assign')) { + self::I()->_smarty->clear_all_assign(); + } + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Base.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Base.php new file mode 100644 index 0000000..447bf09 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Base.php @@ -0,0 +1,23 @@ +_token = md5(microtime()); + } + + public function getToken(){ + return $this->_token; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Codes.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Codes.php new file mode 100644 index 0000000..cdb1780 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/Codes.php @@ -0,0 +1,22 @@ +_type = $type; + $this->_code = $code; + $this->_line = $line; + $this->_file = $file; + parent::__construct($message, $code); + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/System.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/System.php new file mode 100644 index 0000000..dd6b707 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/System.php @@ -0,0 +1,15 @@ +fields = $fields; + parent::__construct($message); + } + + function getFields(){ + return $this->fields; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/WhmcsAPI.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/WhmcsAPI.php new file mode 100644 index 0000000..d44d549 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/exceptions/WhmcsAPI.php @@ -0,0 +1,14 @@ + $defult) { + if (isset($this->{$name})) { + $data[$name] = $this->{$name}; + } + } + + if ($container === true) { + return array( + $className => $data + ); + } elseif ($container) { + return array( + $container => $data + ); + } else { + return $data; + } + } + + /** + * Encrypt String using Hash from configration + * + * @param string $input + * @return string + */ + function encrypt($input) + { + if (empty($input)) { + return false; + } + + return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, main\mtLibs\process\MainInstance::I()->getEncryptKey(), $input, MCRYPT_MODE_ECB)); + } + + /** + * Decrypt String using Hash from configration + * + * @param string $input + * @return string + */ + function decrypt($input) + { + if (empty($input)) { + return false; + } + + return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, main\mtLibs\process\MainInstance::I()->getEncryptKey(), base64_decode($input), MCRYPT_MODE_ECB)); + } + + function serialize($input) + { + return base64_encode(serialize($input)); + } + + function unserialize($input) + { + return unserialize(base64_decode($input)); + } +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Orm.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Orm.php new file mode 100644 index 0000000..a19dec6 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Orm.php @@ -0,0 +1,273 @@ + true + ); + + $rc = new \ReflectionClass(get_called_class()); + + + if (!preg_match("/@Table\((.*)\)/D", $rc->getDocComment())) { + $rc = new \ReflectionClass(get_parent_class(get_called_class())); + } + + if (preg_match("/@Table\((.*)\)/D", $rc->getDocComment(), $result)) { + foreach (explode(',', $result[1]) as $setting) { + $tmp = explode('=', $setting); + if (isset($tmp[1])) { + if ($tmp[1] == 'false') $value = false; + elseif ($tmp[1] == 'true') $value = true; + else $value = $tmp[1]; + + static::$tableStructure[$class][$tmp[0]] = $value; + } else { + static::$tableStructure[$class][$tmp[0]] = true; + } + } + } + + foreach ($rc->getProperties() as $property) { + $configs = array(); + if (preg_match("/@Column\((.*)\)/D", $property->getDocComment(), $result)) { + foreach (explode(',', $result[1]) as $setting) { + $tmp = explode('=', $setting); + if (isset($tmp[1])) { + if ($tmp[1] == 'false') $configs[$tmp[0]] = false; + elseif ($tmp[1] == 'true') $configs[$tmp[0]] = true; + else $configs[$tmp[0]] = $tmp[1]; + } else { + $configs[$tmp[0]] = true; + } + } + } + + if ($configs) { + if (!isset($configs['as'])) { + $configs['as'] = $property->name; + } + if (!isset($configs['name'])) { + $configs['name'] = preg_replace_callback( + '/([A-Z])/D' + , function ($params) { + return '_' . strtolower($params[0]); + } + , $property->name); + } + + static::$tableStructure[$class]['columns'][$property->name] = $configs; + } + + $configs = array(); + if (preg_match("/@Validation\((.*)\)/D", $property->getDocComment(), $result)) { + foreach (explode(',', $result[1]) as $setting) { + $tmp = explode('=', $setting); + if (isset($tmp[1])) { + if ($tmp[1] == 'false') $configs[$tmp[0]] = false; + elseif ($tmp[1] == 'true') $configs[$tmp[0]] = true; + else $configs[$tmp[0]] = $tmp[1]; + } else { + $configs[$tmp[0]] = true; + } + } + } + + if ($configs) { + static::$tableStructure[$class]['validation'][$property->name] = $configs; + } + } + + return static::$tableStructure[$class]; + } + + static function tableName($prefixed = true) + { + $tableStructure = self::getTableStructure(); + + if ($prefixed && $tableStructure['prefixed']) { + return self::prefixTable($tableStructure['name']); + } else { + return $tableStructure['name']; + } + } + + static function fieldDeclaration() + { + $tableStructure = self::getTableStructure(); + $output = array(); + foreach ($tableStructure['columns'] as $column) { + $output[$column['name']] = $column['as']; + } + return $output; + } + + static function getProperyColumn($property) + { + $tableStructure = self::getTableStructure(); + + if (!isset($tableStructure['columns'][$property]['name'])) { + throw new main\mtLibs\exceptions\System("Property $property not exists"); + } + + return $tableStructure['columns'][$property]['name']; + } + + protected function getRawData($id, $haveToExits = true) + { + $data = main\mtLibs\MySQL\Query::select( + self::fieldDeclaration() + , self::tableName() + , array( + 'id' => $id + ) + )->fetch(); + + if (empty($data) && $haveToExits) { + throw new main\mtLibs\exceptions\System('Unable to find ' . get_class($this) . ' with ID:' . $id); + } + + return $data; + } + + function __construct($id = false, $data = array()) + { + + if ($id !== false) + $this->id = (int)$id; + + if ($id !== false && empty($data)) { + $data = $this->getRawData($id); + } + + if (!empty($data) && is_array($data)) { + $this->fillProperties($data); + } + } + + function save($data = array()) + { + + foreach (self::fieldDeclaration() as $mysqlName => $field) { + if (isset($data[$field])) continue; + + if (!property_exists($this, $field)) continue; + + if (is_numeric($mysqlName)) { + $data[$field] = $this->{$field}; + } else { + $data[$mysqlName] = $this->{$field}; + } + } + + if ($this->id) { + main\mtLibs\MySQL\Query::update( + self::tableName() + , $data + , array( + 'id' => $this->id + ) + ); + } else { + $this->id = main\mtLibs\MySQL\Query::insert( + self::tableName() + , $data + ); + } + } + + function delete() + { + if ($this->id) { + main\mtLibs\MySQL\Query::delete( + self::tableName() + , array( + 'id' => $this->id + ) + ); + } + } + + function validate() + { + $structure = self::getTableStructure(); + + $errors = array(); + + foreach ($structure['validation'] as $property => $config) { + if ($property == 'id') { + continue; + } + + if (isset($config['notEmpty']) && empty($this->{$property})) { + $errors[$property][] = 'emptyField'; + } + } + + if ($errors) { + throw new main\mtLibs\exceptions\Validation('validateError', $errors); + } + } + + static function prefixTable($table) + { + return main\mtLibs\process\MainInstance::I()->configuration()->tablePrefix . $table; + } + + /** + * Fill Current Model Properties + * + * @param array $data + */ + function fillProperties($data) + { + + if (empty($data)) { + return; + } + + $used = array('id' => true); + + if (is_array($data)) { + foreach ($data as $property => $value) { + if (property_exists($this, $property)) { + $this->$property = $value; + $used[$property] = true; + } + } + } + + $structure = self::getTableStructure(); + foreach ($structure['columns'] as $property => $configs) { + if (!isset($used[$property]) && !isset($configs['notRequired'])) { + throw new main\mtLibs\exceptions\System('Missing object property: ' . $property, main\mtLibs\exceptions\Codes::MISING_OBJECT_PROPERTY); + } + } + } + + function setProperties($data) + { + + foreach ($data as $k => $v) { + $method = 'set' . ucfirst($k); + if (method_exists($this, $method)) { + $this->$method($v); + continue; + } + throw new main\mtLibs\exceptions\System(sprintf('Object property "%s" does not exist ', $k), main\mtLibs\exceptions\Codes::MISING_OBJECT_PROPERTY); + } + } + +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Repository.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Repository.php new file mode 100644 index 0000000..a4e6890 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/Repository.php @@ -0,0 +1,175 @@ +columns = $columns; + + if (!empty($search)) + $this->search = $search; + } + + public function fieldDeclaration(){ + return forward_static_call(array($this->getModelClass(),'fieldDeclaration')); + } + + function getPropertyColumn($property){ + return forward_static_call(array($this->getModelClass(),'getPropertyColumn'),$property); + } + + public function tableName(){ + return forward_static_call(array($this->getModelClass(),'tableName')); + } + + public function limit($limit) + { + $this->_limit = $limit; + } + + public function offset($offset) + { + $this->_offest = $offset; + } + + public function sortBy($field,$vect){ + $column = forward_static_call(array($this->getModelClass(),'getPropertyColumn'),$field); + $this->_order[$column] = $vect; + } + + /** + * + * @return orm + */ + function get(){ + $result = main\mtLibs\MySQL\Query::select( + self::fieldDeclaration() + , self::tableName() + , $this->_filters + , $this->_order + , $this->_limit + , $this->_offest + ); + + $output = array(); + + $class = $this->getModelClass(); + + while($row = $result->fetch()) + { + $output[] = new $class($row['id'],$row); + } + + return $output; + } + + function count(){ + $fields = $this->fieldDeclaration(); + $first = key($fields); + + if(is_numeric($first)) + { + $first = $fields[$first]; + } + return main\mtLibs\MySQL\Query::count( + $first + , $this->tableName() + , $this->_filters + , array() + , $this->_limit + , $this->_offest + ); + } + + function delete(){ + return main\mtLibs\MySQL\Query::delete( + self::tableName() + , $this->_filters + ); + } + + /** + * + * @param array $ids + * @return main\mtLibs\models\Repository + */ + public function idIn(array $ids) { + + foreach ($ids as &$id) + $id = (int) $id; + + if (!empty($ids)) { + $this->_filters['id'] = $ids; + } + + return $this; + } + + /** + * + * @return Repository + */ + public function resetFilters() { + $this->_filters = array(); + $this->_order = array(); + $this->_limit = null; + return $this; + } + + /** + * + * @return orm + * @throws main\mtLibs\exceptions\System + */ + public function fetchOne() { + + $result = main\mtLibs\MySQL\Query::select( + self::fieldDeclaration() + , self::tableName() + , $this->_filters + , $this->_order + , 1 + , 0 + ); + + $class = $this->getModelClass(); + $row = $result->fetch(); + if(empty($row)){ + $criteria = array(); + foreach($this->_filters as $k => $v) + $criteria[]= "{$k}: $v"; + $criteria = implode(", ", $criteria); + throw new main\mtLibs\exceptions\System("Unable to find '{$class}' with criteria: ({$criteria}) "); + } + + return new $class($row['id'], $row); + } + + public function setSearch($search) { + if (!$search) + return; + $search = main\mtLibs\MySQL\PdoWrapper::realEscapeString($search); + $filter = array(); + foreach ($this->search as $value) { + $value = str_replace('?', $search, $value); + $filter[] = " $value "; + } + if (empty($filter)) + return false; + $sql = implode("OR", $filter); + if ($sql) + $this->_filters[] = ' (' . $sql . ') '; + } +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/TableConstructor.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/TableConstructor.php new file mode 100644 index 0000000..61f325c --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/models/TableConstructor.php @@ -0,0 +1,346 @@ + array( + 'definition' => 'int(:int:) NOT NULL AUTO_INCREMENT' + , 'default' => array( + 'int' => 11 + , 'isPrimaryKey' => true + ) + ) + , 'varchar' => array( + 'definition' => 'varchar(:varchar:) CHARACTER SET :charset: :null:' + , 'default' => array( + 'varchar' => 128 + , 'charset' => 'utf8' + , 'null' => false + ) + ) + , 'custom' => array( + 'definition' => ':custom:' + ) + , 'mediumblob' => array( + 'definition' => 'mediumblob :null:' + , 'default' => array( + 'null' => false + ) + ) + , 'smallint' => array( + 'definition' => 'smallint(:smallint:) :null:' + , 'default' => array( + 'smallint' => 6 + , 'null' => false + ) + ) + , 'tinyint' => array( + 'definition' => 'tinyint(:tinyint:) :null:' + , 'default' => array( + 'tinyint' => 6 + , 'null' => false + ) + ) + , 'boolean' => array( + 'definition' => 'tinyint(:tinyint:) :null:' + , 'default' => array( + 'tinyint' => 1 + , 'null' => false + ) + ) + , 'datetime' => array( + 'definition' => 'datetime DEFAULT :default:' + , 'default' => array( + 'default' => 'NULL' + ) + ) + , 'date' => array( + 'definition' => 'date DEFAULT :default:' + , 'default' => array( + 'default' => 'NULL' + ) + ) + , 'int' => array( + 'definition' => 'int(:int:) :null:' + , 'default' => array( + 'int' => 11 + , 'null' => false + ) + ) + , 'mediumtext' => array( + 'definition' => 'mediumtext :null:' + , 'default' => array( + 'null' => false + ) + ) + , 'text' => array( + 'definition' => 'text :null:' + , 'default' => array( + 'null' => false + ) + ) + ); + + function __construct($namespace, $prefix) + { + $this->mainNameSpace = $namespace; + $this->prefix = $prefix; + + $result = main\mtLibs\MySQL\Query::query("SHOW Tables"); + while ($column = $result->fetchColumn()) { + $this->existsTables[] = $column; + } + } + + function createDBModels($models) + { + foreach ($models as $model) { + $class = $this->mainNameSpace . "\\" . $model; + + if (!class_exists($class)) { + throw new main\mtLibs\exceptions\System('Model Class Not Exists'); + } + + $structure = $class::getTableStructure(); + + $this->createTable($structure); + } + + $this->createReferences(); + } + + function createTable($structure) + { + + if (isset($structure['preventUpdate'])) { + return; + } + + if (empty($structure['name'])) { + throw new main\mtLibs\exceptions\System('Table name is empty'); + } + + if (in_array($structure['name'], $this->declaredTables) && !isset($structure['multipleUsage'])) { + throw new main\mtLibs\exceptions\System('Table declared in other model'); + } + + $this->declaredTables[] = $structure['name']; + + $tableName = empty($structure['prefixed']) ? $structure['name'] : $this->prefix . $structure['name']; + + $charset = empty($structure['charset']) ? $this->charset : $structure['charset']; + + $engine = empty($structure['engine']) ? $this->engine : $structure['engine']; + + $columns = array(); + $keys = array( + 'keys' => array() + , 'primary' => null + ); + + $existsColumns = array(); + $addNewColumns = array(); + $updateColumns = array(); + + if (in_array($tableName, $this->existsTables)) { + $result = main\mtLibs\MySQL\Query::query("SHOW COLUMNS IN `$tableName`"); + + while ($row = $result->fetch()) { + $existsColumns[$row['Field']] = $row; + } + } + + foreach ($structure['columns'] as $data) { + $type = null; + $options = array(); + foreach ($data as $name => $value) { + $options[] = "$name=$value"; + if (isset(self::$predefinedColumnTypes[$name])) { + $type = $name; + } + } + + if ($type == null) { + throw new main\mtLibs\exceptions\System('Unable to find provided column type: (' . implode(',', $options) . ')'); + } + + $config = self::$predefinedColumnTypes[$type]['default']; + + $config['charset'] = $charset; + + foreach ($data as $name => $value) { + if ($value === true && isset($config[$name]) && is_numeric($config[$name])) { + // yyy to po cos mialo byc + } elseif ($value) { + $config[$name] = $value; + } + } + + $definition = self::$predefinedColumnTypes[$type]['definition']; + + $isNull = isset($config['null']) ? $config['null'] : false; + + $config['null'] = ($isNull) ? 'DEFAULT NULL' : 'NOT NULL'; + + foreach ($config as $name => $value) { + $definition = str_replace(':' . $name . ':', $value, $definition); + } + + $definition = str_replace('^comma^', ',', $definition); + + if (!empty($config['isPrimaryKey'])) { + $keys['primary'] = $config['name']; + } + + if (!empty($config['isKey'])) { + $keys['keys'][] = $config['name']; + } + + if (!empty($config['uniqueKey'])) { + $keys['uniqueKey'][] = $config['name']; + } + + if (!empty($config['unique'])) { + $keys['unique'][] = $config['name']; + } + + if (!empty($config['refrence'])) { + if (!isset($this->references[$tableName])) { + $this->references[$tableName] = array(); + } + + $this->references[$tableName][] = array( + 'column' => $config['name'] + , 'refrence' => $config['refrence'] + , 'ondelete' => (empty($config['ondelete'])) ? 'CASCADE' : $config['ondelete'] + , 'onupdate' => (empty($config['onupdate'])) ? 'NO ACTION' : $config['onupdate'] + ); + } + + if (isset($existsColumns[$config['name']])) { + if ( + strpos($definition, $existsColumns[$config['name']]['Type']) === false + || ($isNull && $existsColumns[$config['name']]['Type'] == 'YES') + || (!$isNull && $existsColumns[$config['name']]['Type'] == 'NO') + ) { + $updateColumns[$config['name']] = '`' . $config['name'] . '` ' . $definition; + } + } else { + $addNewColumns[] = '`' . $config['name'] . '` ' . $definition; + } + } + + if (!in_array($tableName, $this->existsTables)) { + if (!empty($keys['primary'])) { + $addNewColumns[] = 'PRIMARY KEY (`' . $keys['primary'] . '`)'; + } + + if (!empty($keys['keys'])) { + foreach ($keys['keys'] as $key) { + $addNewColumns[] = 'KEY `' . $key . '` (`' . $key . '`)'; + } + } + + if (!empty($keys['unique'])) { + foreach ($keys['unique'] as $key) { + $addNewColumns[] = 'UNIQUE KEY `' . $key . '` (`' . $key . '`)'; + } + } + + if (!empty($keys['uniqueKey'])) { + $addNewColumns[] = 'UNIQUE `unique_' . implode('_', $keys['uniqueKey']) . '` (`' . implode('`,`', $keys['uniqueKey']) . '`)'; + } + } + + if (in_array($tableName, $this->existsTables)) { + foreach ($updateColumns as $column => $definition) { + $sql = "ALTER TABLE `$tableName` CHANGE `$column` $definition"; + main\mtLibs\MySQL\Query::query($sql); + } + + foreach ($addNewColumns as $definition) { + $sql = "ALTER TABLE `$tableName` ADD $definition"; + main\mtLibs\MySQL\Query::query($sql); + } + } else { + $sql = 'CREATE TABLE `' . $tableName . '` ('; + $sql .= implode(",\n", $addNewColumns); + $sql .= ') ENGINE=' . $engine . ' DEFAULT CHARSET=' . $charset; + + main\mtLibs\MySQL\Query::query($sql); + } + } + + function createReferences() + { + foreach ($this->references as $table => $refrences) { + $result = main\mtLibs\MySQL\Query::query(" + SHOW CREATE TABLE `" . $table . "`"); + + $row = $result->fetch(); + + $struct = $row['Create Table']; + + foreach ($refrences as $id => $refrence) { + $refName = $table . '_ibfk_' . ($id + 1); + $column = $refrence['column']; + + list($model, $refProperty) = explode('::', $refrence['refrence']); + + $class = $this->mainNameSpace . "\\" . $model; + $refColumn = $class::getProperyColumn($refProperty); + $refTable = $class::tableName(); + + if (strpos($struct, $refName)) { + $sql = " + ALTER TABLE + `" . $table . "` + DROP FOREIGN KEY `$refName`;"; + + main\mtLibs\MySQL\Query::query($sql); + } + + $sql = "ALTER TABLE + `$table` + ADD CONSTRAINT + `$refName` + FOREIGN KEY + (`$column`) + REFERENCES + `$refTable` (`$refColumn`) + ON DELETE " . $refrence['ondelete'] . " + ON UPDATE " . $refrence['onupdate'] . " ; + + "; + + main\mtLibs\MySQL\Query::query($sql); + } + } + } + + function dropModels($models) + { + foreach ($models as $model) { + $class = $this->mainNameSpace . "\\" . $model; + $structure = $class::getTableStructure(); + + $sql = "select COLUMN_NAME, CONSTRAINT_NAME, REFERENCED_COLUMN_NAME, REFERENCED_TABLE_NAME + from information_schema.KEY_COLUMN_USAGE + where TABLE_NAME = 'table to be checked';"; + + } + + } +} \ No newline at end of file diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractConfiguration.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractConfiguration.php new file mode 100644 index 0000000..b7e8e2b --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractConfiguration.php @@ -0,0 +1,340 @@ +_customConfigs[$name]); + } + + public function __get($name) { + if(isset($this->_customConfigs[$name])) + { + return $this->_customConfigs[$name]; + } + } + + public function __set($name, $value) { + $this->_customConfigs[$name] = $value; + } + + /** + * @param bool $debug + */ + public function setDebug(bool $debug): void + { + $this->debug = $debug; + } + + /** + * @return bool + */ + public function isDebug(): bool + { + return $this->debug; + } + + /** + * @param string $systemName + */ + public function setSystemName(string $systemName): void + { + $this->systemName = $systemName; + } + + /** + * @return string + */ + public function getSystemName(): string + { + return $this->systemName; + } + + /** + * @param string $name + */ + public function setName(string $name): void + { + $this->name = $name; + } + + /** + * @return string + */ + public function getName(): string + { + return $this->name; + } + + /** + * @param string $moduleName + */ + public function setModuleName(string $moduleName): void + { + $this->moduleName = $moduleName; + } + + /** + * @return string + */ + public function getModuleName(): string + { + return $this->moduleName; + } + + /** + * @param string $description + */ + public function setDescription(string $description): void + { + $this->description = $description; + } + + /** + * @return string + */ + public function getDescription(): string + { + return $this->description; + } + + /** + * @param string $clientAreaName + */ + public function setClientAreaName(string $clientAreaName): void + { + $this->clientAreaName = $clientAreaName; + } + + /** + * @return string + */ + public function getClientAreaName(): string + { + return $this->clientAreaName; + } + + /** + * @param string $encryptHash + */ + public function setEncryptHash(string $encryptHash): void + { + $this->encryptHash = $encryptHash; + } + + /** + * @return string + */ + public function getEncryptHash(): string + { + return $this->encryptHash; + } + + /** + * @param string $version + */ + public function setVersion(string $version): void + { + $this->version = $version; + } + + /** + * @return string + */ + public function getVersion(): string + { + return $this->version; + } + + /** + * @param string $author + */ + public function setAuthor($author) + { + $this->author = $author; + } + + /** + * @return string + */ + public function getAuthor(): string + { + return $this->author; + } + + /** + * @param string $tablePrefix + */ + public function setTablePrefix(string $tablePrefix): void + { + $this->tablePrefix = $tablePrefix; + } + + /** + * @return string + */ + public function getTablePrefix() + { + return $this->tablePrefix; + } + + /** + * @param string $storageKey + */ + public function setStorageKey(string $storageKey) + { + $this->storageKey = $storageKey; + } + + /** + * @return string + */ + public function getStorageKey() + { + return $this->storageKey; + } + + /** + * @param string $licenseServerUrl + */ + public function setLicenseServerUrl(string $licenseServerUrl): void + { + $this->licenseServerUrl = $licenseServerUrl; + } + + /** + * @return string + */ + public function getLicenseServerUrl() + { + return $this->licenseServerUrl; + } + + /** + * @param string $secretKey + */ + public function setSecretKey(string $secretKey) + { + $this->secretKey = $secretKey; + } + + /** + * @return string + */ + public function getSecretKey() + { + return $this->secretKey; + } + + /** + * @param int $localKeyDays + */ + public function setLocalKeyDays(int $localKeyDays) + { + $this->localKeyDays = $localKeyDays; + } + + /** + * @return int + */ + public function getLocalKeyDays() + { + return $this->localKeyDays; + } + + /** + * @param int $allowCheckFailDays + */ + public function setAllowCheckFailDays( int $allowCheckFailDays) + { + $this->allowCheckFailDays = $allowCheckFailDays; + } + + /** + * @return int + */ + public function getAllowCheckFailDays() + { + return $this->allowCheckFailDays; + } + + /** + * @param array $modelRegister + */ + public function setModelRegister(array $modelRegister) + { + $this->modelRegister = $modelRegister; + } + + /** + * @return array + */ + public function getModelRegister() + { + return $this->modelRegister; + } + + public function getAddonMenu(){ + return array(); + } + + public function getAddonWHMCSConfig(){ + return array(); + } + + public function getServerConfigController(){ + return 'configuration'; + } + + public function getServerActionsController(){ + return 'actions'; + } + + public function getServerCAController(){ + return 'home'; + } + + public function getAddonAdminController(){ + return 'actions'; + } + + public function getAddonCAController(){ + return 'home'; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractController.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractController.php new file mode 100644 index 0000000..2253b36 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractController.php @@ -0,0 +1,93 @@ +mgToken = $input['mg-token']; + } + } + + /** + * Generate Token For Form + * + * @author Michal Czech + * @return string + */ + function genToken(){ + return md5(time()); + } + + /** + * Validate Token With previous checked + * + * @author Michal Czech + * @param string $token + * @return boolean + */ + function checkToken($token = null){ + if($token === null) + { + $token = $this->mgToken; + } + + if($_SESSION['mg-token'] === $token) + { + return false; + } + + $_SESSION['mg-token'] = $token; + + return true; + } + + function dataTablesParseRow($template,$data){ + $row = main\mtLibs\Smarty::I()->view($template,$data); + + $output = array(); + + if(preg_match_all('/\(?P.*?)\<\/td\>/s', $row, $result)) + { + foreach($result['col'] as $col) + { + $output[] = $col; + } + } + + return $output; + } + + function registerErrors($errors){ + $this->registredValidationErros = $errors; + } + + function getFieldError($field,$langspace='validationErrors'){ + if(!isset($this->registredValidationErros[$field])) + { + return false; + } + + $message = array(); + foreach($this->registredValidationErros[$field] as $type) + { + $message[] = main\mtLibs\Lang::absoluteT($langspace,$type); + } + + return implode(',',$message); + } + + public function isActive(){ + return true; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractMainDriver.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractMainDriver.php new file mode 100644 index 0000000..ecc284f --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/AbstractMainDriver.php @@ -0,0 +1,255 @@ +_mainNamespace = substr(__NAMESPACE__,0, strpos(__NAMESPACE__, '\mtLibs')); + self::$_instance->_mainNamespace = (new \ReflectionClass($class))->getNamespaceName(); + self::$_instance->_mainDIR = call_user_func(array($class,'getMainDIR')); + + $class= self::$_instance->_mainNamespace.'\Configuration'; + + self::$_instance->_configuration = new $class(); + + foreach($configs as $name => $value) + { + self::$_instance->_configuration->{$name} = $value; + } + + self::$_instance->isLoaded = true; + + if(!empty(self::$_instance->_configuration->debug)) + { + self::$_instance->_debug = true; + } + + main\mtLibs\MySQL\Query::useCurrentConnection(); + + } + + return self::$_instance; + } + /** + * + * @return main\Configuration + */ + function configuration(){ + return $this->_configuration; + } + + public function isAdmin($status = null){ + if($status !== null) + { + $this->_isAdmin = $status; + } + return $this->_isAdmin; + } + + public function isDebug(){ + return $this->_debug; + } + + /** + * Return Main Namespace + * + * @return string + */ + function getMainNamespace(){ + return $this->_mainNamespace; + } + + /** + * Return Enrypt Key + * + * @return string + */ + public function getEncryptKey(){ + + if(empty($this->encryptSecureKey)) + { + $this->encryptSecureKey = hash('sha256', $GLOBALS['cc_encryption_hash'].$this->configuration()->encryptHash,TRUE); + } + + return $this->encryptSecureKey; + } + + function setMainLangContext(){ + mtLibs\Lang::setContext($this->getType().($this->isAdmin()?'AA':'CA')); + } + + /** + * Process Controllers + * + * @param string $controller controller name + * @param array $input input array + * @param string $type type of request + * @return array + * @throws main\mtLibs\exceptions\System + * @throws main\mtLibs\exceptions\System + */ + function runControler($controller,$action = 'index',$input = array(), $type = 'HTML'){ + try{ + $className = $this->getMainNamespace()."\\controllers\\".$this->getType()."\\".($this->_isAdmin?'admin':'clientarea')."\\".$controller; + + if(!class_exists($className)) + { + throw new main\mtLibs\exceptions\System("Unable to find page"); + } + + $controllerOBJ = new $className($input); + + // display the page or not + if(method_exists($controllerOBJ, "isActive") && !$controllerOBJ->{"isActive"}()) + throw new mtLibs\exceptions\System("No access to this page"); + + if(!method_exists($controllerOBJ, $action.$type)) + { + throw new main\mtLibs\exceptions\System("Unable to find Action: ".$action.$type); + } + + main\mtLibs\Lang::stagCurrentContext('generate'.$controller); + + main\mtLibs\Lang::addToContext(lcfirst ($controller)); + + main\mtLibs\Smarty::I()->setTemplateDir(self::I()->getModuleTemplatesDir().DS.'pages'.DS.lcfirst ($controller)); + + $result = $controllerOBJ->{$action.$type}($input); + + switch ($type) + { + case 'HTML': + if(empty($result['tpl'])) + { + throw new main\mtLibs\exceptions\System("Provide Template Name"); + } + + $success = isset($result['vars']['success'])?$result['vars']['success']:false; + $error = isset($result['vars']['error'])?$result['vars']['error']:false; + $result = main\mtLibs\Smarty::I()->view($result['tpl'], $result['vars']); + break; + default: + $success = isset($result['success'])?$result['success']:false; + $error = isset($result['error'])?$result['error']:false; + } + + main\mtLibs\Lang::unstagContext('generate'.$controller); + + return array( + $result + ,$success + ,$error + ); + } catch (\Exception $ex) { + main\mtLibs\Lang::unstagContext('generate'.$controller); + throw $ex; + return false; + } + } + + /** + * Dump data + * + * @param mixed $input + */ + static function dump($input) + { + if(self::I()->isDebug()) + { + echo "
";
+            print_r($input);
+            echo "
"; + } + } + + abstract public function getAssetsURL(); + abstract public function getType(); + + public static function getMainDIR(){ + return false; + } + public static function getUrl(){ + return false; + } + + public function isActive(){ + return true; + } +} diff --git a/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/MainInstance.php b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/MainInstance.php new file mode 100644 index 0000000..54b4bf9 --- /dev/null +++ b/modules/addons/NFEioServiceInvoices/lib/vendor/whmcsexpert/whmcsexpert/src/WHMCSExpert/mtLibs/process/MainInstance.php @@ -0,0 +1,38 @@ +timestamp) + { + if (function_exists('ioncube_read_file')) + { + $res = ioncube_read_file($source->filepath); + if (is_int($res)) $res = false; + return $res; + } + else + { + return file_get_contents($source->filepath); + } + } + if ($source instanceof Smarty_Config_Source) + { + throw new SmartyException("Unable to read config {$source->type} '{$source->name}'"); + } + throw new SmartyException("Unable to read template {$source->type} '{$source->name}'"); + } + +}