1
0
mirror of https://github.com/freescout-helpdesk/freescout.git synced 2025-01-31 20:11:38 +01:00

PHP 8.1 compatibility

This commit is contained in:
FreeScout 2022-02-03 09:43:12 -08:00
parent 345cdb2702
commit 9e8ebe17ea
6 changed files with 570 additions and 363 deletions

View File

@ -1,357 +0,0 @@
<?php
namespace Zttp;
class Zttp
{
static function __callStatic($method, $args)
{
return PendingZttpRequest::new()->{$method}(...$args);
}
}
class PendingZttpRequest
{
function __construct()
{
$this->beforeSendingCallbacks = collect(function ($request, $options) {
$this->cookies = $options['cookies'];
});
$this->bodyFormat = 'json';
$this->options = [
'http_errors' => false,
];
}
static function new(...$args)
{
return new self(...$args);
}
function withOptions($options)
{
return tap($this, function ($request) use ($options) {
return $this->options = array_merge_recursive($this->options, $options);
});
}
function withoutRedirecting()
{
return tap($this, function ($request) {
return $this->options = array_merge_recursive($this->options, [
'allow_redirects' => false,
]);
});
}
function withoutVerifying()
{
return tap($this, function ($request) {
return $this->options = array_merge_recursive($this->options, [
'verify' => false,
]);
});
}
function asJson()
{
return $this->bodyFormat('json')->contentType('application/json');
}
function asFormParams()
{
return $this->bodyFormat('form_params')->contentType('application/x-www-form-urlencoded');
}
function asMultipart()
{
return $this->bodyFormat('multipart');
}
function bodyFormat($format)
{
return tap($this, function ($request) use ($format) {
$this->bodyFormat = $format;
});
}
function contentType($contentType)
{
return $this->withHeaders(['Content-Type' => $contentType]);
}
function accept($header)
{
return $this->withHeaders(['Accept' => $header]);
}
function withHeaders($headers)
{
return tap($this, function ($request) use ($headers) {
return $this->options = array_merge_recursive($this->options, [
'headers' => $headers,
]);
});
}
function withBasicAuth($username, $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options = array_merge_recursive($this->options, [
'auth' => [$username, $password],
]);
});
}
function withDigestAuth($username, $password)
{
return tap($this, function ($request) use ($username, $password) {
return $this->options = array_merge_recursive($this->options, [
'auth' => [$username, $password, 'digest'],
]);
});
}
function withCookies($cookies)
{
return tap($this, function($request) use ($cookies) {
return $this->options = array_merge_recursive($this->options, [
'cookies' => $cookies,
]);
});
}
function timeout($seconds)
{
return tap($this, function () use ($seconds) {
$this->options['timeout'] = $seconds;
});
}
function beforeSending($callback)
{
return tap($this, function () use ($callback) {
$this->beforeSendingCallbacks[] = $callback;
});
}
function get($url, $queryParams = [])
{
return $this->send('GET', $url, [
'query' => $queryParams,
]);
}
function post($url, $params = [])
{
return $this->send('POST', $url, [
$this->bodyFormat => $params,
]);
}
function patch($url, $params = [])
{
return $this->send('PATCH', $url, [
$this->bodyFormat => $params,
]);
}
function put($url, $params = [])
{
return $this->send('PUT', $url, [
$this->bodyFormat => $params,
]);
}
function delete($url, $params = [])
{
return $this->send('DELETE', $url, [
$this->bodyFormat => $params,
]);
}
function send($method, $url, $options)
{
try {
return tap(new ZttpResponse($this->buildClient()->request($method, $url, $this->mergeOptions([
'query' => $this->parseQueryParams($url),
'on_stats' => function ($transferStats) {
$this->transferStats = $transferStats;
}
], $options))), function($response) {
$response->cookies = $this->cookies;
$response->transferStats = $this->transferStats;
});
} catch (\GuzzleHttp\Exception\ConnectException $e) {
throw new ConnectionException($e->getMessage(), 0, $e);
}
}
function buildClient()
{
return new \GuzzleHttp\Client([
'handler' => $this->buildHandlerStack(),
'cookies' => true,
]);
}
function buildHandlerStack()
{
return tap(\GuzzleHttp\HandlerStack::create(), function ($stack) {
$stack->push($this->buildBeforeSendingHandler());
});
}
function buildBeforeSendingHandler()
{
return function ($handler) {
return function ($request, $options) use ($handler) {
return $handler($this->runBeforeSendingCallbacks($request, $options), $options);
};
};
}
function runBeforeSendingCallbacks($request, $options)
{
return tap($request, function ($request) use ($options) {
$this->beforeSendingCallbacks->each->__invoke(new ZttpRequest($request), $options);
});
}
function mergeOptions(...$options)
{
return array_merge_recursive($this->options, ...$options);
}
function parseQueryParams($url)
{
return tap([], function (&$query) use ($url) {
parse_str(parse_url($url, PHP_URL_QUERY) ?: '', $query);
});
}
}
class ZttpRequest
{
function __construct($request)
{
$this->request = $request;
}
function url()
{
return (string) $this->request->getUri();
}
function method()
{
return $this->request->getMethod();
}
function body()
{
return (string) $this->request->getBody();
}
function headers()
{
return collect($this->request->getHeaders())->mapWithKeys(function ($values, $header) {
return [$header => $values[0]];
})->all();
}
}
class ZttpResponse
{
use \Illuminate\Support\Traits\Macroable {
__call as macroCall;
}
function __construct($response)
{
$this->response = $response;
}
function body()
{
return (string) $this->response->getBody();
}
function json()
{
return json_decode($this->response->getBody(), true);
}
function header($header)
{
return $this->response->getHeaderLine($header);
}
function headers()
{
return collect($this->response->getHeaders())->mapWithKeys(function ($v, $k) {
return [$k => $v[0]];
})->all();
}
function status()
{
return $this->response->getStatusCode();
}
function effectiveUri()
{
return $this->transferStats->getEffectiveUri();
}
function isSuccess()
{
return $this->status() >= 200 && $this->status() < 300;
}
function isOk()
{
return $this->isSuccess();
}
function isRedirect()
{
return $this->status() >= 300 && $this->status() < 400;
}
function isClientError()
{
return $this->status() >= 400 && $this->status() < 500;
}
function isServerError()
{
return $this->status() >= 500;
}
function cookies()
{
return $this->cookies;
}
function __toString()
{
return $this->body();
}
function __call($method, $args)
{
if (static::hasMacro($method)) {
return $this->macroCall($method, $args);
}
return $this->response->{$method}(...$args);
}
}
class ConnectionException extends \Exception {}
function tap($value, $callback) {
$callback($value);
return $value;
}

View File

@ -0,0 +1,342 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Descriptor;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\Helper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
/**
* Text descriptor.
*
* @author Jean-François Simon <contact@jfsimon.fr>
*
* @internal
*/
class TextDescriptor extends Descriptor
{
/**
* {@inheritdoc}
*/
protected function describeInputArgument(InputArgument $argument, array $options = [])
{
if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($argument->getDefault()));
} else {
$default = '';
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : Helper::strlen($argument->getName());
$spacingWidth = $totalWidth - \strlen($argument->getName());
$this->writeText(sprintf(' <info>%s</info> %s%s%s',
$argument->getName(),
str_repeat(' ', $spacingWidth),
// + 4 = 2 spaces before <info>, 2 spaces after </info>
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $argument->getDescription()),
$default
), $options);
}
/**
* {@inheritdoc}
*/
protected function describeInputOption(InputOption $option, array $options = [])
{
if ($option->acceptValue() && null !== $option->getDefault() && (!\is_array($option->getDefault()) || \count($option->getDefault()))) {
$default = sprintf('<comment> [default: %s]</comment>', $this->formatDefaultValue($option->getDefault()));
} else {
$default = '';
}
$value = '';
if ($option->acceptValue()) {
$value = '='.strtoupper($option->getName());
if ($option->isValueOptional()) {
$value = '['.$value.']';
}
}
$totalWidth = isset($options['total_width']) ? $options['total_width'] : $this->calculateTotalWidthForOptions([$option]);
$synopsis = sprintf('%s%s',
$option->getShortcut() ? sprintf('-%s, ', $option->getShortcut()) : ' ',
sprintf('--%s%s', $option->getName(), $value)
);
$spacingWidth = $totalWidth - Helper::strlen($synopsis);
$this->writeText(sprintf(' <info>%s</info> %s%s%s%s',
$synopsis,
str_repeat(' ', $spacingWidth),
// + 4 = 2 spaces before <info>, 2 spaces after </info>
preg_replace('/\s*[\r\n]\s*/', "\n".str_repeat(' ', $totalWidth + 4), $option->getDescription()),
$default,
$option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
), $options);
}
/**
* {@inheritdoc}
*/
protected function describeInputDefinition(InputDefinition $definition, array $options = [])
{
$totalWidth = $this->calculateTotalWidthForOptions($definition->getOptions());
foreach ($definition->getArguments() as $argument) {
$totalWidth = max($totalWidth, Helper::strlen($argument->getName()));
}
if ($definition->getArguments()) {
$this->writeText('<comment>Arguments:</comment>', $options);
$this->writeText("\n");
foreach ($definition->getArguments() as $argument) {
$this->describeInputArgument($argument, array_merge($options, ['total_width' => $totalWidth]));
$this->writeText("\n");
}
}
if ($definition->getArguments() && $definition->getOptions()) {
$this->writeText("\n");
}
if ($definition->getOptions()) {
$laterOptions = [];
$this->writeText('<comment>Options:</comment>', $options);
foreach ($definition->getOptions() as $option) {
if (\strlen($option->getShortcut() ?: '') > 1) {
$laterOptions[] = $option;
continue;
}
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
foreach ($laterOptions as $option) {
$this->writeText("\n");
$this->describeInputOption($option, array_merge($options, ['total_width' => $totalWidth]));
}
}
}
/**
* {@inheritdoc}
*/
protected function describeCommand(Command $command, array $options = [])
{
$command->getSynopsis(true);
$command->getSynopsis(false);
$command->mergeApplicationDefinition(false);
$this->writeText('<comment>Usage:</comment>', $options);
foreach (array_merge([$command->getSynopsis(true)], $command->getAliases(), $command->getUsages()) as $usage) {
$this->writeText("\n");
$this->writeText(' '.OutputFormatter::escape($usage), $options);
}
$this->writeText("\n");
$definition = $command->getNativeDefinition();
if ($definition->getOptions() || $definition->getArguments()) {
$this->writeText("\n");
$this->describeInputDefinition($definition, $options);
$this->writeText("\n");
}
if ($help = $command->getProcessedHelp()) {
$this->writeText("\n");
$this->writeText('<comment>Help:</comment>', $options);
$this->writeText("\n");
$this->writeText(' '.str_replace("\n", "\n ", $help), $options);
$this->writeText("\n");
}
}
/**
* {@inheritdoc}
*/
protected function describeApplication(Application $application, array $options = [])
{
$describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
$description = new ApplicationDescription($application, $describedNamespace);
if (isset($options['raw_text']) && $options['raw_text']) {
$width = $this->getColumnWidth($description->getCommands());
foreach ($description->getCommands() as $command) {
$this->writeText(sprintf("%-{$width}s %s", $command->getName(), $command->getDescription()), $options);
$this->writeText("\n");
}
} else {
if ('' != $help = $application->getHelp()) {
$this->writeText("$help\n\n", $options);
}
$this->writeText("<comment>Usage:</comment>\n", $options);
$this->writeText(" command [options] [arguments]\n\n", $options);
$this->describeInputDefinition(new InputDefinition($application->getDefinition()->getOptions()), $options);
$this->writeText("\n");
$this->writeText("\n");
$commands = $description->getCommands();
$namespaces = $description->getNamespaces();
if ($describedNamespace && $namespaces) {
// make sure all alias commands are included when describing a specific namespace
$describedNamespaceInfo = reset($namespaces);
foreach ($describedNamespaceInfo['commands'] as $name) {
$commands[$name] = $description->getCommand($name);
}
}
// calculate max. width based on available commands per namespace
$width = $this->getColumnWidth(\call_user_func_array('array_merge', array_map(function ($namespace) use ($commands) {
return array_intersect($namespace['commands'], array_keys($commands));
}, array_values($namespaces))));
if ($describedNamespace) {
$this->writeText(sprintf('<comment>Available commands for the "%s" namespace:</comment>', $describedNamespace), $options);
} else {
$this->writeText('<comment>Available commands:</comment>', $options);
}
foreach ($namespaces as $namespace) {
$namespace['commands'] = array_filter($namespace['commands'], function ($name) use ($commands) {
return isset($commands[$name]);
});
if (!$namespace['commands']) {
continue;
}
if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
$this->writeText("\n");
$this->writeText(' <comment>'.$namespace['id'].'</comment>', $options);
}
foreach ($namespace['commands'] as $name) {
$this->writeText("\n");
$spacingWidth = $width - Helper::strlen($name);
$command = $commands[$name];
$commandAliases = $name === $command->getName() ? $this->getCommandAliasesText($command) : '';
$this->writeText(sprintf(' <info>%s</info>%s%s', $name, str_repeat(' ', $spacingWidth), $commandAliases.$command->getDescription()), $options);
}
}
$this->writeText("\n");
}
}
/**
* {@inheritdoc}
*/
private function writeText($content, array $options = [])
{
$this->write(
isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
isset($options['raw_output']) ? !$options['raw_output'] : true
);
}
/**
* Formats command aliases to show them in the command description.
*
* @return string
*/
private function getCommandAliasesText(Command $command)
{
$text = '';
$aliases = $command->getAliases();
if ($aliases) {
$text = '['.implode('|', $aliases).'] ';
}
return $text;
}
/**
* Formats input option/argument default value.
*
* @param mixed $default
*
* @return string
*/
private function formatDefaultValue($default)
{
if (\INF === $default) {
return 'INF';
}
if (\is_string($default)) {
$default = OutputFormatter::escape($default);
} elseif (\is_array($default)) {
foreach ($default as $key => $value) {
if (\is_string($value)) {
$default[$key] = OutputFormatter::escape($value);
}
}
}
return str_replace('\\\\', '\\', json_encode($default, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE));
}
/**
* @param (Command|string)[] $commands
*
* @return int
*/
private function getColumnWidth(array $commands)
{
$widths = [];
foreach ($commands as $command) {
if ($command instanceof Command) {
$widths[] = Helper::strlen($command->getName());
foreach ($command->getAliases() as $alias) {
$widths[] = Helper::strlen($alias);
}
} else {
$widths[] = Helper::strlen($command);
}
}
return $widths ? max($widths) + 2 : 0;
}
/**
* @param InputOption[] $options
*
* @return int
*/
private function calculateTotalWidthForOptions(array $options)
{
$totalWidth = 0;
foreach ($options as $option) {
// "-" + shortcut + ", --" + name
$nameLength = 1 + max(Helper::strlen($option->getShortcut()), 1) + 4 + Helper::strlen($option->getName());
if ($option->acceptValue()) {
$valueLength = 1 + Helper::strlen($option->getName()); // = + value
$valueLength += $option->isValueOptional() ? 2 : 0; // [ + ]
$nameLength += $valueLength;
}
$totalWidth = max($totalWidth, $nameLength);
}
return $totalWidth;
}
}

View File

@ -0,0 +1,138 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Helper;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
/**
* Helper is the base class for all helper classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class Helper implements HelperInterface
{
protected $helperSet = null;
/**
* {@inheritdoc}
*/
public function setHelperSet(HelperSet $helperSet = null)
{
$this->helperSet = $helperSet;
}
/**
* {@inheritdoc}
*/
public function getHelperSet()
{
return $this->helperSet;
}
/**
* Returns the length of a string, using mb_strwidth if it is available.
*
* @param string $string The string to check its length
*
* @return int The length of the string
*/
public static function strlen($string)
{
if (false === $encoding = mb_detect_encoding($string ?: '', null, true)) {
return \strlen($string);
}
return mb_strwidth($string ?: '', $encoding);
}
/**
* Returns the subset of a string, using mb_substr if it is available.
*
* @param string $string String to subset
* @param int $from Start offset
* @param int|null $length Length to read
*
* @return string The string subset
*/
public static function substr($string, $from, $length = null)
{
if (false === $encoding = mb_detect_encoding($string ?: '', null, true)) {
return substr($string, $from, $length);
}
return mb_substr($string, $from, $length, $encoding);
}
public static function formatTime($secs)
{
static $timeFormats = [
[0, '< 1 sec'],
[1, '1 sec'],
[2, 'secs', 1],
[60, '1 min'],
[120, 'mins', 60],
[3600, '1 hr'],
[7200, 'hrs', 3600],
[86400, '1 day'],
[172800, 'days', 86400],
];
foreach ($timeFormats as $index => $format) {
if ($secs >= $format[0]) {
if ((isset($timeFormats[$index + 1]) && $secs < $timeFormats[$index + 1][0])
|| $index == \count($timeFormats) - 1
) {
if (2 == \count($format)) {
return $format[1];
}
return floor($secs / $format[2]).' '.$format[1];
}
}
}
}
public static function formatMemory($memory)
{
if ($memory >= 1024 * 1024 * 1024) {
return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
}
if ($memory >= 1024 * 1024) {
return sprintf('%.1f MiB', $memory / 1024 / 1024);
}
if ($memory >= 1024) {
return sprintf('%d KiB', $memory / 1024);
}
return sprintf('%d B', $memory);
}
public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
{
return self::strlen(self::removeDecoration($formatter, $string));
}
public static function removeDecoration(OutputFormatterInterface $formatter, $string)
{
$isDecorated = $formatter->isDecorated();
$formatter->setDecorated(false);
// remove <...> formatting
$string = $formatter->format($string);
// remove already formatted characters
$string = preg_replace("/\033\[[^m]*m/", '', $string);
$formatter->setDecorated($isDecorated);
return $string;
}
}

View File

@ -0,0 +1,80 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Finder\Iterator;
/**
* SortableIterator applies a sort on a given Iterator.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SortableIterator implements \IteratorAggregate
{
const SORT_BY_NAME = 1;
const SORT_BY_TYPE = 2;
const SORT_BY_ACCESSED_TIME = 3;
const SORT_BY_CHANGED_TIME = 4;
const SORT_BY_MODIFIED_TIME = 5;
private $iterator;
private $sort;
/**
* @param \Traversable $iterator The Iterator to filter
* @param int|callable $sort The sort type (SORT_BY_NAME, SORT_BY_TYPE, or a PHP callback)
*
* @throws \InvalidArgumentException
*/
public function __construct(\Traversable $iterator, $sort)
{
$this->iterator = $iterator;
if (self::SORT_BY_NAME === $sort) {
$this->sort = function ($a, $b) {
return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
};
} elseif (self::SORT_BY_TYPE === $sort) {
$this->sort = function ($a, $b) {
if ($a->isDir() && $b->isFile()) {
return -1;
} elseif ($a->isFile() && $b->isDir()) {
return 1;
}
return strcmp($a->getRealpath() ?: $a->getPathname(), $b->getRealpath() ?: $b->getPathname());
};
} elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getATime() - $b->getATime();
};
} elseif (self::SORT_BY_CHANGED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getCTime() - $b->getCTime();
};
} elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
$this->sort = function ($a, $b) {
return $a->getMTime() - $b->getMTime();
};
} elseif (\is_callable($sort)) {
$this->sort = $sort;
} else {
throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
}
}
public function getIterator(): \Traversable
{
$array = iterator_to_array($this->iterator, true);
uasort($array, $this->sort);
return new \ArrayIterator($array);
}
}

View File

@ -134,7 +134,8 @@
"GuzzleHttp\\": "compat/guzzlehttp/guzzle/src/",
"GuzzleHttp\\Cookie\\": "compat/guzzlehttp/guzzle/src/Cookie/",
"Ramsey\\Uuid\\": "compat/ramsey/uuid/src/",
"Rap2hpoutre\\LaravelLogViewer\\": "compat/rap2hpoutre/laravel-log-viewer/src/Rap2hpoutre/LaravelLogViewer/"
"Rap2hpoutre\\LaravelLogViewer\\": "compat/rap2hpoutre/laravel-log-viewer/src/Rap2hpoutre/LaravelLogViewer/",
"Symfony\\Component\\Console\\Descriptor\\": "compat/symfony/console/Descriptor"
},
"exclude-from-classmap": [
"vendor/axn/laravel-laroute/src/Routes/Collection.php",
@ -229,7 +230,10 @@
"vendor/guzzlehttp/guzzle/src/Cookie/CookieJar.php",
"vendor/ramsey/uuid/src/Uuid.php",
"vendor/laravel/framework/src/Illuminate/Routing/Router.php",
"vendor/rap2hpoutre/laravel-log-viewer/src/Rap2hpoutre/LaravelLogViewer/LaravelLogViewer.php"
"vendor/rap2hpoutre/laravel-log-viewer/src/Rap2hpoutre/LaravelLogViewer/LaravelLogViewer.php",
"vendor/symfony/console/Descriptor/TextDescriptor.php",
"vendor/symfony/console/Helper/Helper.php",
"vendor/symfony/finder/Iterator/SortableIterator.php"
]
},
"autoload-dev": {

8
composer.lock generated
View File

@ -4972,12 +4972,12 @@
},
"type": "library",
"autoload": {
"psr-4": {
"DeepCopy\\": "src/DeepCopy/"
},
"files": [
"src/DeepCopy/deep_copy.php"
]
],
"psr-4": {
"DeepCopy\\": "src/DeepCopy/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [