Upgrade to 3.9.0

This commit is contained in:
Bastian Allgeier
2023-01-17 14:50:16 +01:00
parent 0ebe0c7b16
commit 6e5c9d1f48
132 changed files with 1664 additions and 1254 deletions

View File

@@ -114,9 +114,16 @@ class A
// the element needs to exist and also needs to be an array; otherwise
// we cannot find the remaining keys within it (invalid array structure)
if (isset($array[$currentKey]) === true && is_array($array[$currentKey]) === true) {
if (
isset($array[$currentKey]) === true &&
is_array($array[$currentKey]) === true
) {
// $keys only holds the remaining keys that have not been shifted off yet
return static::get($array[$currentKey], implode('.', $keys), $default);
return static::get(
$array[$currentKey],
implode('.', $keys),
$default
);
}
}
@@ -127,7 +134,11 @@ class A
// if the input array uses a completely nested structure,
// recursively progress layer by layer
if (is_array($array[$firstKey]) === true) {
return static::get($array[$firstKey], implode('.', $keys), $default);
return static::get(
$array[$firstKey],
implode('.', $keys),
$default
);
}
// the $firstKey element was found, but isn't an array, so we cannot
@@ -146,6 +157,7 @@ class A
if (is_string($value) === true) {
return $value;
}
return implode($separator, $value);
}
@@ -251,6 +263,7 @@ class A
public static function pluck(array $array, string $key): array
{
$output = [];
foreach ($array as $a) {
if (isset($a[$key]) === true) {
$output[] = $a[$key];
@@ -396,12 +409,12 @@ class A
*/
public static function fill(array $array, int $limit, $fill = 'placeholder'): array
{
if (count($array) < $limit) {
$diff = $limit - count($array);
for ($x = 0; $x < $diff; $x++) {
$array[] = $fill;
}
$diff = $limit - count($array);
for ($x = 0; $x < $diff; $x++) {
$array[] = $fill;
}
return $array;
}
@@ -467,13 +480,7 @@ class A
*/
public static function missing(array $array, array $required = []): array
{
$missing = [];
foreach ($required as $r) {
if (isset($array[$r]) === false) {
$missing[] = $r;
}
}
return $missing;
return array_values(array_diff($required, array_keys($array)));
}
/**

View File

@@ -1464,7 +1464,8 @@ Collection::$filters['date <='] = [
*/
Collection::$filters['date between'] = Collection::$filters['date ..'] = [
'validator' => function ($value, $test) {
return V::date($value, '>=', $test[0]) &&
V::date($value, '<=', $test[1]);
return
V::date($value, '>=', $test[0]) &&
V::date($value, '<=', $test[1]);
}
];

View File

@@ -19,24 +19,18 @@ use ReflectionFunction;
*/
class Controller
{
protected $function;
public function __construct(Closure $function)
public function __construct(protected Closure $function)
{
$this->function = $function;
}
public function arguments(array $data = []): array
{
$info = new ReflectionFunction($this->function);
$args = [];
foreach ($info->getParameters() as $parameter) {
$name = $parameter->getName();
$args[] = $data[$name] ?? null;
}
return $args;
return A::map(
$info->getParameters(),
fn ($parameter) => $data[$parameter->getName()] ?? null
);
}
public function call($bind = null, $data = [])
@@ -44,7 +38,7 @@ class Controller
$args = $this->arguments($data);
if ($bind === null) {
return call_user_func($this->function, ...$args);
return ($this->function)(...$args);
}
return $this->function->call($bind, ...$args);

View File

@@ -435,10 +435,7 @@ class Dom
{
$allowedNamespaces = $options['allowedNamespaces'];
$localName = $node->localName;
if ($compare === null) {
$compare = fn ($expected, $real): bool => $expected === $real;
}
$compare ??= fn ($expected, $real): bool => $expected === $real;
// if the configuration does not define namespace URIs or if the
// currently checked node is from the special `xml:` namespace
@@ -709,9 +706,7 @@ class Dom
// ensure that the document is encoded as UTF-8
// unless a different encoding was specified in
// the input or before exporting
if ($this->doc->encoding === null) {
$this->doc->encoding = 'UTF-8';
}
$this->doc->encoding ??= 'UTF-8';
return trim($this->doc->saveXML());
}

View File

@@ -25,10 +25,8 @@ class Escape
{
/**
* The internal singleton escaper instance
*
* @var \Laminas\Escaper\Escaper
*/
protected static $escaper;
protected static Escaper|null $escaper;
/**
* Escape common HTML attributes data
@@ -44,11 +42,8 @@ class Escape
* <div attr=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...>content</div>
* <div attr='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'>content</div>
* <div attr="...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">content</div>
*
* @param string $string
* @return string
*/
public static function attr($string)
public static function attr(string $string): string
{
return static::escaper()->escapeHtmlAttr($string);
}
@@ -65,21 +60,16 @@ class Escape
* <style>selector { property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...; } </style>
* <style>selector { property : "...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."; } </style>
* <span style="property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">text</span>
*
* @param string $string
* @return string
*/
public static function css($string)
public static function css(string $string): string
{
return static::escaper()->escapeCss($string);
}
/**
* Get the escaper instance (and create if needed)
*
* @return \Laminas\Escaper\Escaper
*/
protected static function escaper()
protected static function escaper(): Escaper
{
return static::$escaper ??= new Escaper('utf-8');
}
@@ -95,11 +85,8 @@ class Escape
*
* <body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>
* <div>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</div>
*
* @param string $string
* @return string
*/
public static function html($string)
public static function html(string $string): string
{
return static::escaper()->escapeHtml($string);
}
@@ -113,11 +100,8 @@ class Escape
* <script>alert('...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...')</script>
* <script>x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'</script>
* <div onmouseover="x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'"</div>
*
* @param string $string
* @return string
*/
public static function js($string)
public static function js(string $string): string
{
return static::escaper()->escapeJs($string);
}
@@ -129,11 +113,8 @@ class Escape
* This should not be used to escape an entire URI.
*
* <a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">link</a>
*
* @param string $string
* @return string
*/
public static function url($string)
public static function url(string $string): string
{
return rawurlencode($string);
}
@@ -151,11 +132,8 @@ class Escape
* & is replaced with &amp;
* < is replaced with &lt;
* > is replaced with &gt;
*
* @param string $string
* @return string
*/
public static function xml($string)
public static function xml(string $string): string
{
return htmlspecialchars($string, ENT_QUOTES | ENT_XML1, 'UTF-8');
}

View File

@@ -19,17 +19,13 @@ class Html extends Xml
{
/**
* An internal store for an HTML entities translation table
*
* @var array
*/
public static $entities;
public static array|null $entities;
/**
* List of HTML tags that can be used inline
*
* @var array
*/
public static $inlineList = [
public static array $inlineList = [
'b',
'i',
'small',
@@ -144,6 +140,11 @@ class Html extends Xml
return $value === true ? strtolower($name) : null;
}
// HTML attribute names are case-insensitive
if (is_string($name) === true) {
$name = strtolower($name);
}
// all other cases can share the XML variant
$attr = parent::attr($name, $value);
@@ -375,7 +376,7 @@ class Html extends Xml
return trim($rel . ' noopener noreferrer', ' ');
}
return $rel;
return $rel ?: null;
}
/**
@@ -389,13 +390,11 @@ class Html extends Xml
* @param int $level Indentation level
* @return string The generated HTML
*/
public static function tag(string $name, $content = '', array $attr = null, string $indent = null, int $level = 0): string
public static function tag(string $name, $content = '', array $attr = [], string $indent = null, int $level = 0): string
{
// treat an explicit `null` value as an empty tag
// as void tags are already covered below
if ($content === null) {
$content = '';
}
$content ??= '';
// force void elements to be self-closing
if (static::isVoid($name) === true) {
@@ -629,7 +628,7 @@ class Html extends Xml
}
// build the full video src URL
$src = $src . $query->toString(true);
$src .= $query->toString(true);
// render the iframe
return static::iframe($src, static::videoAttr($attr));

View File

@@ -41,7 +41,7 @@ class I18n
* The fallback locale or a
* list of fallback locales
*
* @var string|array|\Closure
* @var string|array|\Closure|null
*/
public static $fallback = ['en'];
@@ -54,8 +54,6 @@ class I18n
/**
* Returns the list of fallback locales
*
* @return array
*/
public static function fallbacks(): array
{
@@ -77,9 +75,7 @@ class I18n
* Returns singular or plural
* depending on the given number
*
* @param int $count
* @param bool $none If true, 'none' will be returned if the count is 0
* @return string
*/
public static function form(int $count, bool $none = false): string
{
@@ -92,23 +88,17 @@ class I18n
/**
* Formats a number
*
* @param int|float $number
* @param string $locale
* @return string
*/
public static function formatNumber($number, string $locale = null): string
public static function formatNumber(int|float $number, string $locale = null): string
{
$locale ??= static::locale();
$formatter = static::decimalNumberFormatter($locale);
$number = $formatter?->format($number) ?? $number;
$locale ??= static::locale();
$formatter = static::decimalNumberFormatter($locale);
$number = $formatter?->format($number) ?? $number;
return (string)$number;
}
/**
* Returns the locale code
*
* @return string
*/
public static function locale(): string
{
@@ -126,25 +116,22 @@ class I18n
/**
* Translates a given message
* according to the currently set locale
*
* @param string|array $key
* @param string|array|null $fallback
* @param string|null $locale
* @return string|array|null
*/
public static function translate($key, $fallback = null, string $locale = null)
{
public static function translate(
string|array|null $key,
string|array $fallback = null,
string $locale = null
): string|array|Closure|null {
$locale ??= static::locale();
if (is_array($key) === true) {
// try to use actual locale
if (isset($key[$locale]) === true) {
return $key[$locale];
if ($result = $key[$locale] ?? null) {
return $result;
}
// try to use language code, e.g. `es` when locale is `es_ES`
$lang = Str::before($locale, '_');
if (isset($key[$lang]) === true) {
return $key[$lang];
if ($result = $key[Str::before($locale, '_')] ?? null) {
return $result;
}
// use global wildcard as i18n key
if (isset($key['*']) === true) {
@@ -152,16 +139,18 @@ class I18n
}
// use fallback
if (is_array($fallback) === true) {
return $fallback[$locale] ??
$fallback['en'] ??
reset($fallback);
return
$fallback[$locale] ??
$fallback['en'] ??
reset($fallback);
}
return $fallback;
}
if ($translation = static::translation($locale)[$key] ?? null) {
return $translation;
// $key is a string
if ($result = static::translation($locale)[$key] ?? null) {
return $result;
}
if ($fallback !== null) {
@@ -174,8 +163,8 @@ class I18n
continue;
}
if ($translation = static::translation($fallback)[$key] ?? null) {
return $translation;
if ($result = static::translation($fallback)[$key] ?? null) {
return $result;
}
}
@@ -192,8 +181,12 @@ class I18n
* @param string|null $locale
* @return string
*/
public static function template(string $key, $fallback = null, array|null $replace = null, string|null $locale = null): string
{
public static function template(
string $key,
string|array $fallback = null,
array|null $replace = null,
string|null $locale = null
): string {
if (is_array($fallback) === true) {
$replace = $fallback;
$fallback = null;
@@ -271,11 +264,7 @@ class I18n
* defined, the template that is defined last in the translation array is used
* - Translation is a callback with a `$count` argument: Returns the callback return value
*
* @param string $key
* @param int $count
* @param string|null $locale
* @param bool $formatNumber If set to `false`, the count is not formatted
* @return mixed
*/
public static function translateCount(string $key, int $count, string $locale = null, bool $formatNumber = true)
{

View File

@@ -16,23 +16,20 @@ use IteratorAggregate;
* @copyright Bastian Allgeier
* @license https://opensource.org/licenses/MIT
*
* @psalm-suppress MissingTemplateParam Implementing template params in this class would
* require implementing them throughout the code base
* https://github.com/getkirby/kirby/pull/4886#pullrequestreview-1203577545
* @psalm-suppress MissingTemplateParam Implementing template params
* in this class would require
* implementing them throughout
* the code base: https://github.com/getkirby/kirby/pull/4886#pullrequestreview-1203577545
*/
class Iterator implements IteratorAggregate
{
/**
* The data array
*
* @var array
*/
public $data = [];
public array $data = [];
/**
* Constructor
*
* @param array $data
*/
public function __construct(array $data = [])
{
@@ -41,8 +38,6 @@ class Iterator implements IteratorAggregate
/**
* Get an iterator for the items.
*
* @return \ArrayIterator
*/
public function getIterator(): ArrayIterator
{
@@ -51,18 +46,14 @@ class Iterator implements IteratorAggregate
/**
* Returns the current key
*
* @return string
*/
public function key()
public function key(): int|string|null
{
return key($this->data);
}
/**
* Returns an array of all keys
*
* @return array
*/
public function keys(): array
{
@@ -71,8 +62,6 @@ class Iterator implements IteratorAggregate
/**
* Returns the current element
*
* @return mixed
*/
public function current()
{
@@ -82,8 +71,6 @@ class Iterator implements IteratorAggregate
/**
* Moves the cursor to the previous element
* and returns it
*
* @return mixed
*/
public function prev()
{
@@ -93,8 +80,6 @@ class Iterator implements IteratorAggregate
/**
* Moves the cursor to the next element
* and returns it
*
* @return mixed
*/
public function next()
{
@@ -104,15 +89,13 @@ class Iterator implements IteratorAggregate
/**
* Moves the cursor to the first element
*/
public function rewind()
public function rewind(): void
{
reset($this->data);
}
/**
* Checks if the current element is valid
*
* @return bool
*/
public function valid(): bool
{
@@ -121,8 +104,6 @@ class Iterator implements IteratorAggregate
/**
* Counts all elements
*
* @return int
*/
public function count(): int
{
@@ -135,7 +116,7 @@ class Iterator implements IteratorAggregate
* @param mixed $needle the element to search for
* @return int|false the index (int) of the element or false
*/
public function indexOf($needle)
public function indexOf($needle): int|false
{
return array_search($needle, array_values($this->data));
}
@@ -144,9 +125,9 @@ class Iterator implements IteratorAggregate
* Tries to find the key for the given element
*
* @param mixed $needle the element to search for
* @return string|false the name of the key or false
* @return int|string|false the name of the key or false
*/
public function keyOf($needle)
public function keyOf($needle): int|string|false
{
return array_search($needle, $this->data);
}
@@ -155,18 +136,16 @@ class Iterator implements IteratorAggregate
* Checks by key if an element is included
*
* @param mixed $key
* @return bool
*/
public function has($key): bool
{
return isset($this->data[$key]);
return isset($this->data[$key]) === true;
}
/**
* Checks if the current key is set
*
* @param mixed $key the key to check
* @return bool
*/
public function __isset($key): bool
{
@@ -175,8 +154,6 @@ class Iterator implements IteratorAggregate
/**
* Simplified var_dump output
*
* @return array
*/
public function __debugInfo(): array
{

View File

@@ -28,25 +28,17 @@ class Locale
/**
* Converts a normalized locale array to an array with the
* locale constants replaced with their string representations
*
* @param array $locale
* @return array
*/
public static function export(array $locale): array
{
$return = [];
$constants = static::supportedConstants(true);
// replace the keys in the locale data array with the locale names
$return = [];
foreach ($locale as $key => $value) {
if (isset($constants[$key]) === true) {
// the key is a valid constant,
// replace it with its string representation
$return[$constants[$key]] = $value;
} else {
// not found, keep it as-is
$return[$key] = $value;
}
// use string representation for key
// if it is a valid constant
$return[$constants[$key] ?? $key] = $value;
}
return $return;
@@ -63,7 +55,7 @@ class Locale
* @throws \Kirby\Exception\Exception If the locale cannot be determined
* @throws \Kirby\Exception\InvalidArgumentException If the provided locale category is invalid
*/
public static function get($category = LC_ALL)
public static function get(int|string $category = LC_ALL): array|string
{
$normalizedCategory = static::normalizeConstant($category);
@@ -105,11 +97,10 @@ class Locale
* string keys to a normalized constant => value array
*
* @param array|string $locale
* @return array
*/
public static function normalize($locale): array
{
if (is_array($locale)) {
if (is_array($locale) === true) {
// replace string constant keys with the constant values
$convertedLocale = [];
foreach ($locale as $key => $value) {
@@ -129,11 +120,8 @@ class Locale
/**
* Sets the PHP locale with a locale string or
* an array with constant or string keys
*
* @param array|string $locale
* @return void
*/
public static function set($locale): void
public static function set(array|string $locale): void
{
$locale = static::normalize($locale);
@@ -154,13 +142,13 @@ class Locale
/**
* Tries to convert an `LC_*` constant name
* to its constant value
*
* @param int|string $constant
* @return int|string
*/
protected static function normalizeConstant($constant)
protected static function normalizeConstant(int|string $constant): int|string
{
if (is_string($constant) === true && Str::startsWith($constant, 'LC_') === true) {
if (
is_string($constant) === true &&
Str::startsWith($constant, 'LC_') === true
) {
return constant($constant);
}
@@ -173,7 +161,6 @@ class Locale
* that are actually supported on this system
*
* @param bool $withAll If set to `true`, `LC_ALL` is returned as well
* @return array
*/
protected static function supportedConstants(bool $withAll = false): array
{

View File

@@ -19,8 +19,6 @@ class Obj extends stdClass
{
/**
* Constructor
*
* @param array $data
*/
public function __construct(array $data = [])
{
@@ -31,10 +29,6 @@ class Obj extends stdClass
/**
* Magic getter
*
* @param string $property
* @param array $arguments
* @return mixed
*/
public function __call(string $property, array $arguments)
{
@@ -43,8 +37,6 @@ class Obj extends stdClass
/**
* Improved `var_dump` output
*
* @return array
*/
public function __debugInfo(): array
{
@@ -53,9 +45,6 @@ class Obj extends stdClass
/**
* Magic property getter
*
* @param string $property
* @return mixed
*/
public function __get(string $property)
{
@@ -65,19 +54,15 @@ class Obj extends stdClass
/**
* Gets one or multiple properties of the object
*
* @param string|array $property
* @param mixed $fallback If multiple properties are requested:
* Associative array of fallback values per key
* @return mixed
*/
public function get($property, $fallback = null)
public function get(string|array $property, $fallback = null)
{
if (is_array($property)) {
if ($fallback === null) {
$fallback = [];
}
$fallback ??= [];
if (!is_array($fallback)) {
if (is_array($fallback) === false) {
throw new InvalidArgumentException('The fallback value must be an array when getting multiple properties');
}
@@ -93,8 +78,6 @@ class Obj extends stdClass
/**
* Converts the object to an array
*
* @return array
*/
public function toArray(): array
{
@@ -116,9 +99,6 @@ class Obj extends stdClass
/**
* Converts the object to a json string
*
* @param mixed ...$arguments
* @return string
*/
public function toJson(...$arguments): string
{

View File

@@ -389,9 +389,7 @@ class Pagination
// ensure that page is set to something, otherwise
// generate "default page" based on other params
if ($this->page === null) {
$this->page = $this->firstPage();
}
$this->page ??= $this->firstPage();
// allow a page value of 1 even if there are no pages;
// otherwise the exception will get thrown for this pretty common case

View File

@@ -3,6 +3,7 @@
namespace Kirby\Toolkit;
use Closure;
use Kirby\Cms\Helpers;
use Kirby\Exception\BadMethodCallException;
use Kirby\Exception\InvalidArgumentException;
@@ -18,7 +19,6 @@ use Kirby\Exception\InvalidArgumentException;
* @license https://opensource.org/licenses/MIT
*
* @deprecated 3.8.2 Use `Kirby\Query\Query` instead
* // TODO: throw warnings in 3.9.0
* // TODO: Remove in 3.10.0
*/
class Query
@@ -57,6 +57,8 @@ class Query
{
$this->query = $query;
$this->data = $data;
Helpers::deprecated('The `Toolkit\Query` class has been deprecated and will be removed in a future version. Use `Query\Query` instead: Kirby\Query\Query::factory($query)->resolve($data).');
}
/**

View File

@@ -15,19 +15,12 @@ namespace Kirby\Toolkit;
*/
class Silo
{
/**
* @var array
*/
public static $data = [];
/**
* Setter for new data.
*
* @param string|array $key
* @param mixed $value
* @return array
* Setter for new data
*/
public static function set($key, $value = null): array
public static function set(string|array $key, $value = null): array
{
if (is_array($key) === true) {
return static::$data = array_merge(static::$data, $key);
@@ -37,12 +30,7 @@ class Silo
return static::$data;
}
/**
* @param string|array $key
* @param mixed $default
* @return mixed
*/
public static function get($key = null, $default = null)
public static function get(string|array $key = null, $default = null)
{
if ($key === null) {
return static::$data;
@@ -53,9 +41,6 @@ class Silo
/**
* Removes an item from the data array
*
* @param string|null $key
* @return array
*/
public static function remove(string $key = null): array
{

View File

@@ -25,17 +25,13 @@ class Str
{
/**
* Language translation table
*
* @var array
*/
public static $language = [];
public static array $language = [];
/**
* Ascii translation table
*
* @var array
*/
public static $ascii = [
public static array $ascii = [
'/°|₀/' => '0',
'/¹|₁/' => '1',
'/²|₂/' => '2',
@@ -117,10 +113,8 @@ class Str
/**
* Default settings for class methods
*
* @var array
*/
public static $defaults = [
public static array $defaults = [
'slug' => [
'separator' => '-',
'allowed' => 'a-z0-9'
@@ -130,9 +124,6 @@ class Str
/**
* Parse accepted values and their quality from an
* accept string like an Accept or Accept-Language header
*
* @param string $input
* @return array
*/
public static function accepted(string $input): array
{
@@ -174,11 +165,6 @@ class Str
/**
* Returns the rest of the string after the given substring or character
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function after(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -192,13 +178,9 @@ class Str
}
/**
* Removes the given substring or character only from the start of the string
* Removes the given substring or character
* only from the start of the string
* @since 3.7.0
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function afterStart(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -215,9 +197,6 @@ class Str
/**
* Convert a string to 7-bit ASCII.
*
* @param string $string
* @return string
*/
public static function ascii(string $string): string
{
@@ -238,11 +217,6 @@ class Str
/**
* Returns the beginning of a string before the given substring or character
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function before(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -258,11 +232,6 @@ class Str
/**
* Removes the given substring or character only from the end of the string
* @since 3.7.0
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function beforeEnd(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -279,11 +248,6 @@ class Str
/**
* Returns everything between two strings from the first occurrence of a given string
*
* @param string $string
* @param string $start
* @param string $end
* @return string
*/
public static function between(string $string = null, string $start, string $end): string
{
@@ -294,7 +258,6 @@ class Str
* Converts a string to camel case
*
* @param string $value The string to convert
* @return string
*/
public static function camel(string $value = null): string
{
@@ -303,11 +266,6 @@ class Str
/**
* Checks if a str contains another string
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return bool
*/
public static function contains(string $string = null, string $needle, bool $caseInsensitive = false): bool
{
@@ -323,12 +281,9 @@ class Str
* Convert timestamp to date string
* according to locale settings
*
* @param int|null $time
* @param string|\IntlDateFormatter|null $format
* @param string $handler date, intl or strftime
* @return string|int
*/
public static function date(int|null $time = null, $format = null, string $handler = 'date')
public static function date(int|null $time = null, string|IntlDateFormatter $format = null, string $handler = 'date'): string|int|false
{
if (is_null($format) === true) {
return $time;
@@ -365,18 +320,11 @@ class Str
/**
* Converts a string to a different encoding
*
* @param string $string
* @param string $targetEncoding
* @param string $sourceEncoding (optional)
* @return string
*/
public static function convert($string, $targetEncoding, $sourceEncoding = null)
public static function convert(string $string, string $targetEncoding, string $sourceEncoding = null): string
{
// detect the source encoding if not passed as third argument
if ($sourceEncoding === null) {
$sourceEncoding = static::encoding($string);
}
$sourceEncoding ??= static::encoding($string);
// no need to convert if the target encoding is the same
if (strtolower($sourceEncoding) === strtolower($targetEncoding)) {
@@ -388,9 +336,6 @@ class Str
/**
* Encode a string (used for email addresses)
*
* @param string $string
* @return string
*/
public static function encode(string $string): string
{
@@ -407,22 +352,18 @@ class Str
/**
* Tries to detect the string encoding
*
* @param string $string
* @return string
*/
public static function encoding(string $string): string
{
return mb_detect_encoding($string, 'UTF-8, ISO-8859-1, windows-1251', true);
return mb_detect_encoding(
$string,
'UTF-8, ISO-8859-1, windows-1251',
true
);
}
/**
* Checks if a string ends with the passed needle
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return bool
*/
public static function endsWith(string $string = null, string $needle, bool $caseInsensitive = false): bool
{
@@ -499,11 +440,8 @@ class Str
/**
* Convert the value to a float with a decimal
* point, no matter what the locale setting is
*
* @param string|int|float $value
* @return string
*/
public static function float($value): string
public static function float(string|int|float|null $value): string
{
// make sure $value is not null
$value ??= '';
@@ -520,11 +458,6 @@ class Str
/**
* Returns the rest of the string starting from the given character
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function from(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -542,9 +475,7 @@ class Str
* @since 3.7.0
*
* @param string $string The string to increment
* @param string $separator
* @param int $first Starting number
* @return string
*/
public static function increment(string $string, string $separator = '-', int $first = 1): string
{
@@ -561,9 +492,6 @@ class Str
/**
* Convert a string to kebab case.
*
* @param string $value
* @return string
*/
public static function kebab(string $value = null): string
{
@@ -572,9 +500,6 @@ class Str
/**
* A UTF-8 safe version of strlen()
*
* @param string $string
* @return int
*/
public static function length(string $string = null): int
{
@@ -583,9 +508,6 @@ class Str
/**
* A UTF-8 safe version of strtolower()
*
* @param string $string
* @return string
*/
public static function lower(string $string = null): string
{
@@ -594,10 +516,6 @@ class Str
/**
* Safe ltrim alternative
*
* @param string $string
* @param string $trim
* @return string
*/
public static function ltrim(string $string, string $trim = ' '): string
{
@@ -607,12 +525,8 @@ class Str
/**
* Get a character pool with various possible combinations
*
* @param string|array $type
* @param bool $array
* @return string|array
*/
public static function pool($type, bool $array = true)
public static function pool(string|array $type, bool $array = true): string|array
{
$pool = [];
@@ -638,12 +552,9 @@ class Str
* Returns the position of a needle in a string
* if it can be found
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return int|bool
* @throws \Kirby\Exception\InvalidArgumentException for empty $needle
*/
public static function position(string $string = null, string $needle, bool $caseInsensitive = false)
public static function position(string $string = null, string $needle, bool $caseInsensitive = false): int|bool
{
if ($needle === '') {
throw new InvalidArgumentException('The needle must not be empty');
@@ -660,10 +571,6 @@ class Str
/**
* Runs a string query.
* Check out the Query class for more information.
*
* @param string $query
* @param array $data
* @return string|null
*/
public static function query(string $query, array $data = [])
{
@@ -675,15 +582,11 @@ class Str
*
* @param int $length The length of the random string
* @param string $type Pool type (type of allowed characters)
* @return string
*/
public static function random(int $length = null, string $type = 'alphaNum')
public static function random(int $length = null, string $type = 'alphaNum'): string|false
{
if ($length === null) {
$length = random_int(5, 10);
}
$pool = static::pool($type, false);
$length ??= random_int(5, 10);
$pool = static::pool($type, false);
// catch invalid pools
if (!$pool) {
@@ -883,10 +786,17 @@ class Str
*
* @return string The filled-in and partially escaped string
*/
public static function safeTemplate(string $string = null, array $data = [], array $options = []): string
{
$callback = ($options['callback'] ?? null) instanceof Closure ? $options['callback'] : null;
public static function safeTemplate(
string $string = null,
array $data = [],
array $options = []
): string {
$fallback = $options['fallback'] ?? null;
$callback = $options['callback'] ?? null;
if ($callback instanceof Closure === false) {
$callback = null;
}
// replace and escape
$string = static::template($string, $data, [
@@ -957,8 +867,7 @@ class Str
* @author Based on the work of Antal Áron
* @copyright Original Copyright (c) 2017, Antal Áron
* @license https://github.com/antalaron/mb-similar-text/blob/master/LICENSE MIT License
* @param string $first
* @param string $second
*
* @param bool $caseInsensitive If `true`, strings are compared case-insensitively
* @return array matches: Number of matching chars in both strings
* percent: Similarity in percent
@@ -1033,8 +942,12 @@ class Str
* @param int $maxlength The maximum length of the slug
* @return string The safe string
*/
public static function slug(string $string = null, string $separator = null, string $allowed = null, int $maxlength = 128): string
{
public static function slug(
string $string = null,
string $separator = null,
string $allowed = null,
int $maxlength = 128
): string {
$separator ??= static::$defaults['slug']['separator'];
$allowed ??= static::$defaults['slug']['allowed'];
@@ -1063,10 +976,6 @@ class Str
/**
* Convert a string to snake case.
*
* @param string $value
* @param string $delimiter
* @return string
*/
public static function snake(string $value = null, string $delimiter = '_'): string
{
@@ -1088,7 +997,7 @@ class Str
* @param int $length The min length of values.
* @return array An array of found values
*/
public static function split($string, string $separator = ',', int $length = 1): array
public static function split(string|array|null $string, string $separator = ',', int $length = 1): array
{
if (is_array($string) === true) {
return $string;
@@ -1112,11 +1021,6 @@ class Str
/**
* Checks if a string starts with the passed needle
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return bool
*/
public static function startsWith(string $string = null, string $needle, bool $caseInsensitive = false): bool
{
@@ -1132,7 +1036,6 @@ class Str
* @since 3.7.0
*
* @param string $value The string to convert
* @return string
*/
public static function studly(string $value = null): string
{
@@ -1141,11 +1044,6 @@ class Str
/**
* A UTF-8 safe version of substr()
*
* @param string $string
* @param int $start
* @param int $length
* @return string
*/
public static function substr(string $string = null, int $start = 0, int $length = null): string
{
@@ -1173,12 +1071,19 @@ class Str
* - end: end placeholder
* @return string The filled-in string
*/
public static function template(string $string = null, array $data = [], array $options = []): string
{
$fallback = $options['fallback'] ?? null;
$callback = ($options['callback'] ?? null) instanceof Closure ? $options['callback'] : null;
public static function template(
string $string = null,
array $data = [],
array $options = []
): string {
$start = (string)($options['start'] ?? '{{');
$end = (string)($options['end'] ?? '}}');
$fallback = $options['fallback'] ?? null;
$callback = $options['callback'] ?? null;
if ($callback instanceof Closure === false) {
$callback = null;
}
// make sure $string is string
$string ??= '';
@@ -1219,9 +1124,6 @@ class Str
/**
* Converts a filesize string with shortcuts
* like M, G or K to an integer value
*
* @param string $size
* @return int
*/
public static function toBytes(string $size): int
{
@@ -1229,26 +1131,18 @@ class Str
$last = strtolower($size[strlen($size)-1] ?? '');
$size = (int)$size;
switch ($last) {
case 'g':
$size *= 1024;
// no break
case 'm':
$size *= 1024;
// no break
case 'k':
$size *= 1024;
}
$size *= match ($last) {
'g' => 1024 * 1024 * 1024,
'm' => 1024 * 1024,
'k' => 1024,
default => 1
};
return $size;
}
/**
* Convert the string to the given type
*
* @param string $string
* @param mixed $type
* @return mixed
*/
public static function toType($string, $type)
{
@@ -1267,10 +1161,6 @@ class Str
/**
* Safe trim alternative
*
* @param string $string
* @param string $trim
* @return string
*/
public static function trim(string $string, string $trim = ' '): string
{
@@ -1279,20 +1169,16 @@ class Str
/**
* A UTF-8 safe version of ucfirst()
*
* @param string $string
* @return string
*/
public static function ucfirst(string $string = null): string
{
return static::upper(static::substr($string, 0, 1)) . static::lower(static::substr($string, 1));
$first = static::substr($string, 0, 1);
$rest = static::substr($string, 1);
return static::upper($first) . static::lower($rest);
}
/**
* A UTF-8 safe version of ucwords()
*
* @param string $string
* @return string
*/
public static function ucwords(string $string = null): string
{
@@ -1308,9 +1194,6 @@ class Str
* // output: some uber crazy stuff
*
* </code>
*
* @param string $string
* @return string The html string
*/
public static function unhtml(string $string = null): string
{
@@ -1319,11 +1202,6 @@ class Str
/**
* Returns the beginning of a string until the given character
*
* @param string $string
* @param string $needle
* @param bool $caseInsensitive
* @return string
*/
public static function until(string $string, string $needle, bool $caseInsensitive = false): string
{
@@ -1338,9 +1216,6 @@ class Str
/**
* A UTF-8 safe version of strotoupper()
*
* @param string $string
* @return string
*/
public static function upper(string $string = null): string
{
@@ -1351,8 +1226,6 @@ class Str
* Creates a compliant v4 UUID
* Taken from: https://github.com/symfony/polyfill
* @since 3.7.0
*
* @return string
*/
public static function uuid(): string
{
@@ -1381,9 +1254,6 @@ class Str
* The widont function makes sure that there are no
* typographical widows at the end of a paragraph
* that's a single word in the last line
*
* @param string $string
* @return string
*/
public static function widont(string $string = null): string
{
@@ -1411,7 +1281,6 @@ class Str
* @param string $string String to wrap
* @param string $before String to prepend
* @param string|null $after String to append (if different from `$before`)
* @return string
*/
public static function wrap(string $string, string $before, string $after = null): string
{

View File

@@ -19,9 +19,6 @@ class Tpl
/**
* Renders the template
*
* @param string|null $file
* @param array $data
* @return string
* @throws Throwable
*/
public static function load(string|null $file = null, array $data = []): string

View File

@@ -24,22 +24,15 @@ class V
{
/**
* An array with all installed validators
*
* @var array
*/
public static $validators = [];
public static array $validators = [];
/**
* Validates the given input with all passed rules
* and returns an array with all error messages.
* The array will be empty if the input is valid
*
* @param mixed $input
* @param array $rules
* @param array $messages
* @return array
*/
public static function errors($input, array $rules, $messages = []): array
public static function errors($input, array $rules, array $messages = []): array
{
$errors = static::value($input, $rules, $messages, false);
@@ -50,11 +43,6 @@ class V
* Runs a number of validators on a set of data and
* checks if the data is invalid
* @since 3.7.0
*
* @param array $data
* @param array $rules
* @param array $messages
* @return array
*/
public static function invalid(array $data = [], array $rules = [], array $messages = []): array
{
@@ -119,10 +107,6 @@ class V
* Creates a useful error message for the given validator
* and the arguments. This is used mainly internally
* to create error messages
*
* @param string $validatorName
* @param mixed ...$params
* @return string|null
*/
public static function message(string $validatorName, ...$params): string|null
{
@@ -162,8 +146,6 @@ class V
/**
* Return the list of all validators
*
* @return array
*/
public static function validators(): array
{
@@ -174,14 +156,8 @@ class V
* Validate a single value against
* a set of rules, using all registered
* validators
*
* @param mixed $value
* @param array $rules
* @param array $messages
* @param bool $fail
* @return bool|array
*/
public static function value($value, array $rules, array $messages = [], bool $fail = true)
public static function value($value, array $rules, array $messages = [], bool $fail = true): bool|array
{
$errors = [];
@@ -214,10 +190,6 @@ class V
* Validate an input array against
* a set of rules, using all registered
* validators
*
* @param array $input
* @param array $rules
* @return bool
*/
public static function input(array $input, array $rules): bool
{
@@ -252,10 +224,6 @@ class V
/**
* Calls an installed validator and passes all arguments
*
* @param string $method
* @param array $arguments
* @return bool
*/
public static function __callStatic(string $method, array $arguments): bool
{
@@ -301,8 +269,9 @@ V::$validators = [
* Checks for numbers within the given range
*/
'between' => function ($value, $min, $max): bool {
return V::min($value, $min) === true &&
V::max($value, $max) === true;
return
V::min($value, $min) === true &&
V::max($value, $max) === true;
},
/**
@@ -415,8 +384,9 @@ V::$validators = [
* Checks for a valid filename
*/
'filename' => function ($value): bool {
return V::match($value, '/^[a-z0-9@._-]+$/i') === true &&
V::min($value, 2) === true;
return
V::match($value, '/^[a-z0-9@._-]+$/i') === true &&
V::min($value, 2) === true;
},
/**

View File

@@ -19,23 +19,16 @@ class View
{
/**
* The absolute path to the view file
*
* @var string
*/
protected $file;
protected string $file;
/**
* The view data
*
* @var array
*/
protected $data = [];
protected array $data = [];
/**
* Creates a new view object
*
* @param string $file
* @param array $data
*/
public function __construct(string $file, array $data = [])
{
@@ -46,8 +39,6 @@ class View
/**
* Returns the view's data array
* without globals.
*
* @return array
*/
public function data(): array
{
@@ -56,8 +47,6 @@ class View
/**
* Checks if the template file exists
*
* @return bool
*/
public function exists(): bool
{
@@ -66,18 +55,14 @@ class View
/**
* Returns the view file
*
* @return string|false
*/
public function file()
public function file(): string
{
return $this->file;
}
/**
* Creates an error message for the missing view exception
*
* @return string
*/
protected function missingViewMessage(): string
{
@@ -86,8 +71,6 @@ class View
/**
* Renders the view
*
* @return string
*/
public function render(): string
{
@@ -115,9 +98,7 @@ class View
}
/**
* Alias for View::render()
*
* @return string
* @see ::render()
*/
public function toString(): string
{
@@ -127,8 +108,6 @@ class View
/**
* Magic string converter to enable
* converting view objects to string
*
* @return string
*/
public function __toString(): string
{

View File

@@ -2,6 +2,7 @@
namespace Kirby\Toolkit;
use Kirby\Cms\Helpers;
use SimpleXMLElement;
/**
@@ -17,10 +18,8 @@ class Xml
{
/**
* HTML to XML conversion table for entities
*
* @var array
*/
public static $entities = [
public static array|null $entities = [
'&nbsp;' => '&#160;', '&iexcl;' => '&#161;', '&cent;' => '&#162;', '&pound;' => '&#163;', '&curren;' => '&#164;', '&yen;' => '&#165;', '&brvbar;' => '&#166;', '&sect;' => '&#167;',
'&uml;' => '&#168;', '&copy;' => '&#169;', '&ordf;' => '&#170;', '&laquo;' => '&#171;', '&not;' => '&#172;', '&shy;' => '&#173;', '&reg;' => '&#174;', '&macr;' => '&#175;',
'&deg;' => '&#176;', '&plusmn;' => '&#177;', '&sup2;' => '&#178;', '&sup3;' => '&#179;', '&acute;' => '&#180;', '&micro;' => '&#181;', '&para;' => '&#182;', '&middot;' => '&#183;',
@@ -71,7 +70,7 @@ class Xml
* If used with a `$name` array, this can be set to `false` to disable attribute sorting.
* @return string|null The generated XML attributes string
*/
public static function attr($name, $value = null): string|null
public static function attr(string|array $name, $value = null): string|null
{
if (is_array($name) === true) {
if ($value !== false) {
@@ -80,26 +79,43 @@ class Xml
$attributes = [];
foreach ($name as $key => $val) {
$a = static::attr($key, $val);
if (is_int($key) === true) {
$key = $val;
$val = true;
}
if ($a) {
$attributes[] = $a;
if ($attribute = static::attr($key, $val)) {
$attributes[] = $attribute;
}
}
return implode(' ', $attributes);
}
// TODO: In 3.10, treat $value === '' to render as name=""
if ($value === null || $value === '' || $value === []) {
// TODO: Remove in 3.10
// @codeCoverageIgnoreStart
if ($value === '') {
Helpers::deprecated('Passing an empty string as value to `Xml::attr()` has been deprecated. In a future version, passing an empty string won\'t omit the attribute anymore but render it with an empty value. To omit the attribute, please pass `null`.');
}
// @codeCoverageIgnoreEnd
return null;
}
// TODO: In 3.10, add deprecation message for space = empty attribute
// TODO: In 3.11, render space as space
if ($value === ' ') {
return strtolower($name) . '=""';
return $name . '=""';
}
if (is_bool($value) === true) {
return $value === true ? strtolower($name) . '="' . strtolower($name) . '"' : null;
if ($value === true) {
return $name . '="' . $name . '"';
}
if ($value === false) {
return null;
}
if (is_array($value) === true) {
@@ -115,7 +131,7 @@ class Xml
$value = static::encode($value);
}
return strtolower($name) . '="' . $value . '"';
return $name . '="' . $value . '"';
}
/**
@@ -133,8 +149,13 @@ class Xml
* @param int $level The indentation level (used internally)
* @return string The XML string
*/
public static function create($props, string $name = 'root', bool $head = true, string $indent = ' ', int $level = 0): string
{
public static function create(
array|string $props,
string $name = 'root',
bool $head = true,
string $indent = ' ',
int $level = 0
): string {
if (is_array($props) === true) {
if (A::isAssociative($props) === true) {
// a tag with attributes or named children
@@ -177,7 +198,7 @@ class Xml
} else {
// scalar value
$result = static::tag($name, $props, null, $indent, $level);
$result = static::tag($name, $props, [], $indent, $level);
}
if ($head === true) {
@@ -194,17 +215,10 @@ class Xml
* echo Xml::decode('some &uuml;ber <em>crazy</em> stuff');
* // output: some über crazy stuff
* ```
*
* @param string|null $string
* @return string
*/
public static function decode(string|null $string): string
{
if ($string === null) {
$string = '';
}
$string = strip_tags($string);
$string = strip_tags($string ?? '');
return html_entity_decode($string, ENT_COMPAT, 'utf-8');
}
@@ -219,9 +233,7 @@ class Xml
* // output: some &#252;ber crazy stuff
* ```
*
* @param string|null $string
* @param bool $html True = Convert to HTML-safe first
* @return string
*/
public static function encode(string|null $string, bool $html = true): string
{
@@ -242,8 +254,6 @@ class Xml
/**
* Returns the HTML-to-XML entity translation table
*
* @return array
*/
public static function entities(): array
{
@@ -253,7 +263,6 @@ class Xml
/**
* Parses an XML string and returns an array
*
* @param string $xml
* @return array|null Parsed array or `null` on error
*/
public static function parse(string $xml): array|null
@@ -271,11 +280,9 @@ class Xml
* Breaks a SimpleXMLElement down into a simpler tree
* structure of arrays and strings
*
* @param \SimpleXMLElement $element
* @param bool $collectName Whether the element name should be collected (for the root element)
* @return array|string
*/
public static function simplify(SimpleXMLElement $element, bool $collectName = true)
public static function simplify(SimpleXMLElement $element, bool $collectName = true): array|string
{
// get all XML namespaces of the whole document to iterate over later;
// we don't need the global namespace (empty string) in the list
@@ -365,7 +372,7 @@ class Xml
* @param int $level Indentation level
* @return string The generated XML
*/
public static function tag(string $name, $content = '', array $attr = null, string|null $indent = null, int $level = 0): string
public static function tag(string $name, $content = '', array $attr = [], string $indent = null, int $level = 0): string
{
$attr = static::attr($attr);
$start = '<' . $name . ($attr ? ' ' . $attr : '') . '>';
@@ -394,9 +401,6 @@ class Xml
/**
* Properly encodes tag contents
*
* @param mixed $value
* @return string|null
*/
public static function value($value): string|null
{