From 1626ba8771baaa88cdc5fca398c0cf9596c4034b Mon Sep 17 00:00:00 2001 From: Jaroslav Hanslik Date: Fri, 14 Aug 2015 21:52:40 +0200 Subject: [PATCH] added PHP7 scalar and return type hints --- src/Iterators/CachingIterator.php | 14 +++--- src/Utils/ArrayHash.php | 8 ++-- src/Utils/ArrayList.php | 6 +-- src/Utils/Arrays.php | 10 ++--- src/Utils/Callback.php | 12 ++--- src/Utils/DateTime.php | 14 +++--- src/Utils/FileSystem.php | 14 +++--- src/Utils/Html.php | 71 ++++++++++++++---------------- src/Utils/IHtmlString.php | 2 +- src/Utils/ITranslator.php | 2 +- src/Utils/Image.php | 40 ++++++++--------- src/Utils/Json.php | 4 +- src/Utils/ObjectMixin.php | 42 +++++++++--------- src/Utils/Paginator.php | 32 +++++++------- src/Utils/Random.php | 2 +- src/Utils/Reflection.php | 14 +++--- src/Utils/SmartObject.php | 4 +- src/Utils/Strings.php | 70 ++++++++++++++--------------- src/Utils/Validators.php | 34 +++++++------- tests/Utils/Random.generate().phpt | 2 +- 20 files changed, 197 insertions(+), 200 deletions(-) diff --git a/src/Iterators/CachingIterator.php b/src/Iterators/CachingIterator.php index 0de5ca11b..7d4d0f23c 100644 --- a/src/Iterators/CachingIterator.php +++ b/src/Iterators/CachingIterator.php @@ -59,7 +59,7 @@ public function __construct($iterator) * @param int grid width * @return bool */ - public function isFirst($width = NULL) + public function isFirst(int $width = NULL): bool { return $this->counter === 1 || ($width && $this->counter !== 0 && (($this->counter - 1) % $width) === 0); } @@ -70,7 +70,7 @@ public function isFirst($width = NULL) * @param int grid width * @return bool */ - public function isLast($width = NULL) + public function isLast(int $width = NULL): bool { return !$this->hasNext() || ($width && ($this->counter % $width) === 0); } @@ -80,7 +80,7 @@ public function isLast($width = NULL) * Is the iterator empty? * @return bool */ - public function isEmpty() + public function isEmpty(): bool { return $this->counter === 0; } @@ -90,7 +90,7 @@ public function isEmpty() * Is the counter odd? * @return bool */ - public function isOdd() + public function isOdd(): bool { return $this->counter % 2 === 1; } @@ -100,7 +100,7 @@ public function isOdd() * Is the counter even? * @return bool */ - public function isEven() + public function isEven(): bool { return $this->counter % 2 === 0; } @@ -110,7 +110,7 @@ public function isEven() * Returns the counter. * @return int */ - public function getCounter() + public function getCounter(): int { return $this->counter; } @@ -120,7 +120,7 @@ public function getCounter() * Returns the count of elements. * @return int */ - public function count() + public function count(): int { $inner = $this->getInnerIterator(); if ($inner instanceof \Countable) { diff --git a/src/Utils/ArrayHash.php b/src/Utils/ArrayHash.php index 27b9fbc4c..e5356f37d 100644 --- a/src/Utils/ArrayHash.php +++ b/src/Utils/ArrayHash.php @@ -23,7 +23,7 @@ class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \Iterator * @param bool * @return static */ - public static function from($arr, $recursive = TRUE) + public static function from(array $arr, bool $recursive = TRUE): self { $obj = new static; foreach ($arr as $key => $value) { @@ -41,7 +41,7 @@ public static function from($arr, $recursive = TRUE) * Returns an iterator over all items. * @return \RecursiveArrayIterator */ - public function getIterator() + public function getIterator(): \RecursiveArrayIterator { return new \RecursiveArrayIterator((array) $this); } @@ -51,7 +51,7 @@ public function getIterator() * Returns items count. * @return int */ - public function count() + public function count(): int { return count((array) $this); } @@ -84,7 +84,7 @@ public function offsetGet($key) * Determines whether a item exists. * @return bool */ - public function offsetExists($key) + public function offsetExists($key): bool { return isset($this->$key); } diff --git a/src/Utils/ArrayList.php b/src/Utils/ArrayList.php index 5c1f3d11b..b1d50ee7a 100644 --- a/src/Utils/ArrayList.php +++ b/src/Utils/ArrayList.php @@ -26,7 +26,7 @@ class ArrayList implements \ArrayAccess, \Countable, \IteratorAggregate * Returns an iterator over all items. * @return \ArrayIterator */ - public function getIterator() + public function getIterator(): \ArrayIterator { return new \ArrayIterator($this->list); } @@ -36,7 +36,7 @@ public function getIterator() * Returns items count. * @return int */ - public function count() + public function count(): int { return count($this->list); } @@ -83,7 +83,7 @@ public function offsetGet($index) * @param int * @return bool */ - public function offsetExists($index) + public function offsetExists($index): bool { return $index >= 0 && $index < count($this->list); } diff --git a/src/Utils/Arrays.php b/src/Utils/Arrays.php index cb2a4c505..fcec747d6 100644 --- a/src/Utils/Arrays.php +++ b/src/Utils/Arrays.php @@ -68,7 +68,7 @@ public static function &getRef(array &$arr, $key) * Recursively appends elements of remaining keys from the second array to the first. * @return array */ - public static function mergeTree(array $arr1, array $arr2) + public static function mergeTree(array $arr1, array $arr2): array { $res = $arr1 + $arr2; foreach (array_intersect_key($arr1, $arr2) as $k => $v) { @@ -133,7 +133,7 @@ public static function renameKey(array &$arr, $oldKey, $newKey) * Returns array entries that match the pattern. * @return array */ - public static function grep(array $arr, $pattern, $flags = 0) + public static function grep(array $arr, string $pattern, int $flags = 0): array { return Strings::pcre('preg_grep', [$pattern, $arr, $flags]); } @@ -143,7 +143,7 @@ public static function grep(array $arr, $pattern, $flags = 0) * Returns flattened array. * @return array */ - public static function flatten(array $arr, $preserveKeys = FALSE) + public static function flatten(array $arr, bool $preserveKeys = FALSE): array { $res = []; $cb = $preserveKeys @@ -158,7 +158,7 @@ public static function flatten(array $arr, $preserveKeys = FALSE) * Finds whether a variable is a zero-based integer indexed array. * @return bool */ - public static function isList($value) + public static function isList($value): bool { return is_array($value) && (!$value || array_keys($value) === range(0, count($value) - 1)); } @@ -220,7 +220,7 @@ public static function associate(array $arr, $path) * Normalizes to associative array. * @return array */ - public static function normalize(array $arr, $filling = NULL) + public static function normalize(array $arr, $filling = NULL): array { $res = []; foreach ($arr as $k => $v) { diff --git a/src/Utils/Callback.php b/src/Utils/Callback.php index c5d73dce9..e276804da 100644 --- a/src/Utils/Callback.php +++ b/src/Utils/Callback.php @@ -25,7 +25,7 @@ class Callback * @param string method * @return \Closure */ - public static function closure($callable, $m = NULL) + public static function closure($callable, string $m = NULL): \Closure { if ($m !== NULL) { $callable = [$callable, $m]; @@ -82,7 +82,7 @@ public static function invokeArgs($callable, array $args = []) * @param string * @return mixed */ - public static function invokeSafe($function, array $args, $onError) + public static function invokeSafe(string $function, array $args, callable $onError) { $prev = set_error_handler(function ($severity, $message, $file) use ($onError, &$prev, $function) { if ($file === '' && defined('HHVM_VERSION')) { // https://github.com/facebook/hhvm/issues/4625 @@ -108,7 +108,7 @@ public static function invokeSafe($function, array $args, $onError) /** * @return callable */ - public static function check($callable, $syntax = FALSE) + public static function check($callable, bool $syntax = FALSE) { if (!is_callable($callable, $syntax)) { throw new Nette\InvalidArgumentException($syntax @@ -123,7 +123,7 @@ public static function check($callable, $syntax = FALSE) /** * @return string */ - public static function toString($callable) + public static function toString($callable): string { if ($callable instanceof \Closure) { $inner = self::unwrap($callable); @@ -163,7 +163,7 @@ public static function toReflection($callable) /** * @return bool */ - public static function isStatic($callable) + public static function isStatic(callable $callable): bool { return is_array($callable) ? is_string($callable[0]) : is_string($callable); } @@ -174,7 +174,7 @@ public static function isStatic($callable) * @internal * @return callable */ - public static function unwrap(\Closure $closure) + public static function unwrap(\Closure $closure): callable { $r = new \ReflectionFunction($closure); if (substr($r->getName(), -1) === '}') { diff --git a/src/Utils/DateTime.php b/src/Utils/DateTime.php index cb0202678..4e7f556a8 100644 --- a/src/Utils/DateTime.php +++ b/src/Utils/DateTime.php @@ -43,7 +43,7 @@ class DateTime extends \DateTime implements \JsonSerializable * @param string|int|\DateTimeInterface * @return static */ - public static function from($time) + public static function from($time): self { if ($time instanceof \DateTimeInterface) { return new static($time->format('Y-m-d H:i:s.u'), $time->getTimezone()); @@ -64,7 +64,7 @@ public static function from($time) * Creates DateTime object. * @return static */ - public static function fromParts($year, $month, $day, $hour = 0, $minute = 0, $second = 0) + public static function fromParts(int $year, int $month, int $day, int $hour = 0, int $minute = 0, float $second = 0) { $s = sprintf("%04d-%02d-%02d %02d:%02d:%02.5f", $year, $month, $day, $hour, $minute, $second); if (!checkdate($month, $day, $year) || $hour < 0 || $hour > 23 || $minute < 0 || $minute > 59 || $second < 0 || $second >= 60) { @@ -77,7 +77,7 @@ public static function fromParts($year, $month, $day, $hour = 0, $minute = 0, $s /** * @return string */ - public function __toString() + public function __toString(): string { return $this->format('Y-m-d H:i:s'); } @@ -87,7 +87,7 @@ public function __toString() * @param string * @return static */ - public function modifyClone($modify = '') + public function modifyClone(string $modify = ''): self { $dolly = clone $this; return $modify ? $dolly->modify($modify) : $dolly; @@ -95,10 +95,10 @@ public function modifyClone($modify = '') /** - * @param int + * @param int|string * @return static */ - public function setTimestamp($timestamp) + public function setTimestamp($timestamp): self { $zone = $this->getTimezone(); $this->__construct('@' . $timestamp); @@ -144,7 +144,7 @@ public static function createFromFormat($format, $time, $timezone = NULL) * Returns JSON representation in ISO 8601 (used by JavaScript). * @return string */ - public function jsonSerialize() + public function jsonSerialize(): string { return $this->format('c'); } diff --git a/src/Utils/FileSystem.php b/src/Utils/FileSystem.php index ae9937a54..a7060ee24 100644 --- a/src/Utils/FileSystem.php +++ b/src/Utils/FileSystem.php @@ -24,7 +24,7 @@ class FileSystem * @return void * @throws Nette\IOException */ - public static function createDir($dir, $mode = 0777) + public static function createDir(string $dir, int $mode = 0777) { if (!is_dir($dir) && !@mkdir($dir, $mode, TRUE) && !is_dir($dir)) { // @ - dir may already exist throw new Nette\IOException("Unable to create directory '$dir'. " . error_get_last()['message']); @@ -37,7 +37,7 @@ public static function createDir($dir, $mode = 0777) * @return void * @throws Nette\IOException */ - public static function copy($source, $dest, $overwrite = TRUE) + public static function copy(string $source, string $dest, bool $overwrite = TRUE) { if (stream_is_local($source) && !file_exists($source)) { throw new Nette\IOException("File or directory '$source' not found."); @@ -72,7 +72,7 @@ public static function copy($source, $dest, $overwrite = TRUE) * @return void * @throws Nette\IOException */ - public static function delete($path) + public static function delete(string $path) { if (is_file($path) || is_link($path)) { $func = DIRECTORY_SEPARATOR === '\\' && is_dir($path) ? 'rmdir' : 'unlink'; @@ -97,7 +97,7 @@ public static function delete($path) * @throws Nette\IOException * @throws Nette\InvalidStateException if the target file or directory already exist */ - public static function rename($name, $newName, $overwrite = TRUE) + public static function rename(string $name, string $newName, bool $overwrite = TRUE) { if (!$overwrite && file_exists($newName)) { throw new Nette\InvalidStateException("File or directory '$newName' already exists."); @@ -120,7 +120,7 @@ public static function rename($name, $newName, $overwrite = TRUE) * @return string * @throws Nette\IOException */ - public static function read($file) + public static function read(string $file): string { $content = @file_get_contents($file); // @ is escalated to exception if ($content === FALSE) { @@ -135,7 +135,7 @@ public static function read($file) * @return void * @throws Nette\IOException */ - public static function write($file, $content, $mode = 0666) + public static function write(string $file, string $content, int $mode = 0666) { static::createDir(dirname($file)); if (@file_put_contents($file, $content) === FALSE) { // @ is escalated to exception @@ -151,7 +151,7 @@ public static function write($file, $content, $mode = 0666) * Is path absolute? * @return bool */ - public static function isAbsolute($path) + public static function isAbsolute(string $path): bool { return (bool) preg_match('#([a-z]:)?[/\\\\]|[a-z][a-z0-9+.-]*://#Ai', $path); } diff --git a/src/Utils/Html.php b/src/Utils/Html.php index 238b7616a..efc506825 100644 --- a/src/Utils/Html.php +++ b/src/Utils/Html.php @@ -57,7 +57,7 @@ class Html implements \ArrayAccess, \Countable, \IteratorAggregate, IHtmlString * @param array|string element's attributes or plain text content * @return static */ - public static function el($name = NULL, $attrs = NULL) + public static function el(string $name = NULL, $attrs = NULL): self { $el = new static; $parts = explode(' ', (string) $name, 2); @@ -87,7 +87,7 @@ public static function el($name = NULL, $attrs = NULL) * @return static * @throws Nette\InvalidArgumentException */ - public function setName($name, $isEmpty = NULL) + public function setName(string $name, bool $isEmpty = NULL): self { if ($name !== NULL && !is_string($name)) { throw new Nette\InvalidArgumentException(sprintf('Name must be string or NULL, %s given.', gettype($name))); @@ -103,7 +103,7 @@ public function setName($name, $isEmpty = NULL) * Returns element's name. * @return string */ - public function getName() + public function getName(): string { return $this->name; } @@ -113,7 +113,7 @@ public function getName() * Is element empty? * @return bool */ - public function isEmpty() + public function isEmpty(): bool { return $this->isEmpty; } @@ -124,7 +124,7 @@ public function isEmpty() * @param array * @return static */ - public function addAttributes(array $attrs) + public function addAttributes(array $attrs): self { $this->attrs = array_merge($this->attrs, $attrs); return $this; @@ -138,7 +138,7 @@ public function addAttributes(array $attrs) * @param string|bool value option * @return static */ - public function appendAttribute($name, $value, $option = TRUE) + public function appendAttribute(string $name, $value, $option = TRUE) { if (is_array($value)) { $prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : []; @@ -163,7 +163,7 @@ public function appendAttribute($name, $value, $option = TRUE) * @param mixed * @return static */ - public function setAttribute($name, $value) + public function setAttribute(string $name, $value) { $this->attrs[$name] = $value; return $this; @@ -175,7 +175,7 @@ public function setAttribute($name, $value) * @param string * @return mixed */ - public function getAttribute($name) + public function getAttribute(string $name) { return isset($this->attrs[$name]) ? $this->attrs[$name] : NULL; } @@ -186,7 +186,7 @@ public function getAttribute($name) * @param string * @return static */ - public function removeAttribute($name) + public function removeAttribute(string $name) { unset($this->attrs[$name]); return $this; @@ -199,7 +199,7 @@ public function removeAttribute($name) * @param mixed HTML attribute value * @return void */ - public function __set($name, $value) + public function __set(string $name, $value) { $this->attrs[$name] = $value; } @@ -210,7 +210,7 @@ public function __set($name, $value) * @param string HTML attribute name * @return mixed HTML attribute value */ - public function &__get($name) + public function &__get(string $name) { return $this->attrs[$name]; } @@ -221,7 +221,7 @@ public function &__get($name) * @param string HTML attribute name * @return bool */ - public function __isset($name) + public function __isset(string $name): bool { return isset($this->attrs[$name]); } @@ -232,7 +232,7 @@ public function __isset($name) * @param string HTML attribute name * @return void */ - public function __unset($name) + public function __unset(string $name) { unset($this->attrs[$name]); } @@ -244,7 +244,7 @@ public function __unset($name) * @param array (string) HTML attribute value or pair? * @return mixed */ - public function __call($m, $args) + public function __call(string $m, array $args) { $p = substr($m, 0, 3); if ($p === 'get' || $p === 'set' || $p === 'add') { @@ -277,7 +277,7 @@ public function __call($m, $args) * @param array query * @return static */ - public function href($path, $query = NULL) + public function href(string $path, array $query = NULL): self { if ($query) { $query = http_build_query($query, '', '&'); @@ -294,7 +294,7 @@ public function href($path, $query = NULL) * Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'. * @return static */ - public function data($name, $value = NULL) + public function data(string $name, $value = NULL): self { if (func_num_args() === 1) { $this->attrs['data'] = $name; @@ -311,13 +311,10 @@ public function data($name, $value = NULL) * @return static * @throws Nette\InvalidArgumentException */ - public function setHtml($html) + public function setHtml(string $html): self { - if (is_array($html)) { - throw new Nette\InvalidArgumentException(sprintf('Textual content must be a scalar, %s given.', gettype($html))); - } $this->removeChildren(); - $this->children[] = (string) $html; + $this->children[] = $html; return $this; } @@ -326,7 +323,7 @@ public function setHtml($html) * Returns element's HTML content. * @return string */ - public function getHtml() + public function getHtml(): string { $s = ''; foreach ($this->children as $child) { @@ -346,7 +343,7 @@ public function getHtml() * @return static * @throws Nette\InvalidArgumentException */ - public function setText($text) + public function setText($text): self { if (!is_array($text) && !$text instanceof self) { $text = htmlspecialchars((string) $text, ENT_NOQUOTES, 'UTF-8'); @@ -359,7 +356,7 @@ public function setText($text) * Returns element's textual content. * @return string */ - public function getText() + public function getText(): string { return html_entity_decode(strip_tags($this->getHtml()), ENT_QUOTES, 'UTF-8'); } @@ -370,7 +367,7 @@ public function getText() * @param Html|string Html node or raw HTML string * @return static */ - public function addHtml($child) + public function addHtml($child): self { return $this->insert(NULL, $child); } @@ -381,7 +378,7 @@ public function addHtml($child) * @param string plain-text string * @return static */ - public function addText($text) + public function addText(string $text): self { $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8'); return $this->insert(NULL, $text); @@ -394,7 +391,7 @@ public function addText($text) * @param array|string element's attributes or raw HTML string * @return static created element */ - public function create($name, $attrs = NULL) + public function create(string $name, $attrs = NULL): self { $this->insert(NULL, $child = static::el($name, $attrs)); return $child; @@ -409,7 +406,7 @@ public function create($name, $attrs = NULL) * @return static * @throws Nette\InvalidArgumentException */ - public function insert($index, $child, $replace = FALSE) + public function insert($index, $child, bool $replace = FALSE): self { if ($child instanceof self || is_scalar($child)) { if ($index === NULL) { // append @@ -455,7 +452,7 @@ public function offsetGet($index) * @param int * @return bool */ - public function offsetExists($index) + public function offsetExists($index): bool { return isset($this->children[$index]); } @@ -478,7 +475,7 @@ public function offsetUnset($index) * Returns children count. * @return int */ - public function count() + public function count(): int { return count($this->children); } @@ -498,7 +495,7 @@ public function removeChildren() * Iterates over elements. * @return \ArrayIterator */ - public function getIterator() + public function getIterator(): \ArrayIterator { return new \ArrayIterator($this->children); } @@ -508,7 +505,7 @@ public function getIterator() * Returns all children. * @return array */ - public function getChildren() + public function getChildren(): array { return $this->children; } @@ -519,7 +516,7 @@ public function getChildren() * @param int * @return string */ - public function render($indent = NULL) + public function render(int $indent = NULL): string { $s = $this->startTag(); @@ -547,7 +544,7 @@ public function render($indent = NULL) } - public function __toString() + public function __toString(): string { try { return $this->render(); @@ -561,7 +558,7 @@ public function __toString() * Returns element's start tag. * @return string */ - public function startTag() + public function startTag(): string { if ($this->name) { return '<' . $this->name . $this->attributes() . (static::$xhtml && $this->isEmpty ? ' />' : '>'); @@ -576,7 +573,7 @@ public function startTag() * Returns element's end tag. * @return string */ - public function endTag() + public function endTag(): string { return $this->name && !$this->isEmpty ? 'name . '>' : ''; } @@ -587,7 +584,7 @@ public function endTag() * @return string * @internal */ - public function attributes() + public function attributes(): string { if (!is_array($this->attrs)) { return ''; diff --git a/src/Utils/IHtmlString.php b/src/Utils/IHtmlString.php index cd281e6c6..8552ea952 100644 --- a/src/Utils/IHtmlString.php +++ b/src/Utils/IHtmlString.php @@ -16,6 +16,6 @@ interface IHtmlString /** * @return string in HTML format */ - function __toString(); + function __toString(): string; } diff --git a/src/Utils/ITranslator.php b/src/Utils/ITranslator.php index 619e7b8f2..e5ee28e82 100644 --- a/src/Utils/ITranslator.php +++ b/src/Utils/ITranslator.php @@ -22,6 +22,6 @@ interface ITranslator * @param int plural count * @return string */ - function translate($message, $count = NULL); + function translate(string $message, int $count = NULL): string; } diff --git a/src/Utils/Image.php b/src/Utils/Image.php index cbe75aec9..23f259791 100644 --- a/src/Utils/Image.php +++ b/src/Utils/Image.php @@ -132,7 +132,7 @@ class Image * @param int transparency 0..127 * @return array */ - public static function rgb($red, $green, $blue, $transparency = 0) + public static function rgb(int $red, int $green, int $blue, int $transparency = 0): array { return [ 'red' => max(0, min(255, (int) $red)), @@ -151,7 +151,7 @@ public static function rgb($red, $green, $blue, $transparency = 0) * @throws UnknownImageFileException if file not found or file type is not known * @return static */ - public static function fromFile($file, &$format = NULL) + public static function fromFile(string $file, int &$format = NULL): self { if (!extension_loaded('gd')) { throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); @@ -165,7 +165,7 @@ public static function fromFile($file, &$format = NULL) $format = NULL; throw new UnknownImageFileException(is_file($file) ? "Unknown type of file '$file'." : "File '$file' not found."); } - return new static(Callback::invokeSafe('imagecreatefrom' . self::$formats[$format], [$file], function ($message) { + return new static(Callback::invokeSafe('imagecreatefrom' . self::$formats[$format], [$file], function (string $message) { throw new ImageException($message); })); } @@ -178,7 +178,7 @@ public static function fromFile($file, &$format = NULL) * @return static * @throws ImageException */ - public static function fromString($s, &$format = NULL) + public static function fromString(string $s, int &$format = NULL): self { if (!extension_loaded('gd')) { throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); @@ -189,7 +189,7 @@ public static function fromString($s, &$format = NULL) $format = isset(self::$formats[$tmp]) ? $tmp : NULL; } - return new static(Callback::invokeSafe('imagecreatefromstring', [$s], function ($message) { + return new static(Callback::invokeSafe('imagecreatefromstring', [$s], function (string $message) { throw new ImageException($message); })); } @@ -202,7 +202,7 @@ public static function fromString($s, &$format = NULL) * @param array * @return static */ - public static function fromBlank($width, $height, $color = NULL) + public static function fromBlank(int $width, int $height, array $color = NULL): self { if (!extension_loaded('gd')) { throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); @@ -241,7 +241,7 @@ public function __construct($image) * Returns image width. * @return int */ - public function getWidth() + public function getWidth(): int { return imagesx($this->image); } @@ -251,7 +251,7 @@ public function getWidth() * Returns image height. * @return int */ - public function getHeight() + public function getHeight(): int { return imagesy($this->image); } @@ -262,7 +262,7 @@ public function getHeight() * @param resource * @return static */ - protected function setImageResource($image) + protected function setImageResource($image): self { if (!is_resource($image) || get_resource_type($image) !== 'gd') { throw new Nette\InvalidArgumentException('Image is not valid.'); @@ -289,7 +289,7 @@ public function getImageResource() * @param int flags * @return static */ - public function resize($width, $height, $flags = self::FIT) + public function resize($width, $height, int $flags = self::FIT): self { if ($flags & self::EXACT) { return $this->resize($width, $height, self::FILL)->crop('50%', '50%', $width, $height); @@ -323,7 +323,7 @@ public function resize($width, $height, $flags = self::FIT) * @param int flags * @return array */ - public static function calculateSize($srcWidth, $srcHeight, $newWidth, $newHeight, $flags = self::FIT) + public static function calculateSize($srcWidth, $srcHeight, $newWidth, $newHeight, int $flags = self::FIT): array { if (is_string($newWidth) && substr($newWidth, -1) === '%') { $newWidth = (int) round($srcWidth / 100 * abs(substr($newWidth, 0, -1))); @@ -388,7 +388,7 @@ public static function calculateSize($srcWidth, $srcHeight, $newWidth, $newHeigh * @param mixed height in pixels or percent * @return static */ - public function crop($left, $top, $width, $height) + public function crop($left, $top, $width, $height): self { list($r['x'], $r['y'], $r['width'], $r['height']) = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height); @@ -407,7 +407,7 @@ public function crop($left, $top, $width, $height) * @param mixed height in pixels or percent * @return array */ - public static function calculateCutout($srcWidth, $srcHeight, $left, $top, $newWidth, $newHeight) + public static function calculateCutout($srcWidth, $srcHeight, $left, $top, $newWidth, $newHeight): array { if (is_string($newWidth) && substr($newWidth, -1) === '%') { $newWidth = (int) round($srcWidth / 100 * substr($newWidth, 0, -1)); @@ -439,7 +439,7 @@ public static function calculateCutout($srcWidth, $srcHeight, $left, $top, $newW * Sharpen image. * @return static */ - public function sharpen() + public function sharpen(): self { imageconvolution($this->image, [ // my magic numbers ;) [-1, -1, -1], @@ -458,7 +458,7 @@ public function sharpen() * @param int opacity 0..100 * @return static */ - public function place(Image $image, $left = 0, $top = 0, $opacity = 100) + public function place(Image $image, $left = 0, $top = 0, int $opacity = 100): self { $opacity = max(0, min(100, (int) $opacity)); if ($opacity === 0) { @@ -514,7 +514,7 @@ public function place(Image $image, $left = 0, $top = 0, $opacity = 100) * @param int optional image type * @return bool TRUE on success or FALSE on failure. */ - public function save($file = NULL, $quality = NULL, $type = NULL) + public function save(string $file = NULL, int $quality = NULL, int $type = NULL): bool { if ($type === NULL) { $extensions = array_flip(self::$formats) + ['jpg' => self::JPEG]; @@ -553,7 +553,7 @@ public function save($file = NULL, $quality = NULL, $type = NULL) * @param int quality (0..100 for JPEG and WEBP, 0..9 for PNG) * @return string */ - public function toString($type = self::JPEG, $quality = NULL) + public function toString(int $type = self::JPEG, int $quality = NULL): string { ob_start(function () {}); $this->save(NULL, $quality, $type); @@ -565,7 +565,7 @@ public function toString($type = self::JPEG, $quality = NULL) * Outputs image to string. * @return string */ - public function __toString() + public function __toString(): string { try { return $this->toString(); @@ -584,7 +584,7 @@ public function __toString() * @param int quality (0..100 for JPEG and WEBP, 0..9 for PNG) * @return bool TRUE on success or FALSE on failure. */ - public function send($type = self::JPEG, $quality = NULL) + public function send(int $type = self::JPEG, int $quality = NULL): bool { if (!isset(self::$formats[$type])) { throw new Nette\InvalidArgumentException("Unsupported image type '$type'."); @@ -602,7 +602,7 @@ public function send($type = self::JPEG, $quality = NULL) * @return mixed * @throws Nette\MemberAccessException */ - public function __call($name, $args) + public function __call(string $name, array $args) { $function = 'image' . $name; if (!function_exists($function)) { diff --git a/src/Utils/Json.php b/src/Utils/Json.php index ffd8ec65f..b7ac106aa 100644 --- a/src/Utils/Json.php +++ b/src/Utils/Json.php @@ -29,7 +29,7 @@ class Json * @param int accepts Json::PRETTY * @return string */ - public static function encode($value, $options = 0) + public static function encode($value, int $options = 0): string { $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | ($options & self::PRETTY ? JSON_PRETTY_PRINT : 0) @@ -54,7 +54,7 @@ public static function encode($value, $options = 0) * @param int accepts Json::FORCE_ARRAY * @return mixed */ - public static function decode($json, $options = 0) + public static function decode(string $json, int $options = 0) { $forceArray = (bool) ($options & self::FORCE_ARRAY); $value = json_decode($json, $forceArray, 512, JSON_BIGINT_AS_STRING); diff --git a/src/Utils/ObjectMixin.php b/src/Utils/ObjectMixin.php index cc0c215a9..317d17fc9 100644 --- a/src/Utils/ObjectMixin.php +++ b/src/Utils/ObjectMixin.php @@ -30,7 +30,7 @@ class ObjectMixin /** * @throws MemberAccessException */ - public static function strictGet($class, $name) + public static function strictGet(string $class, string $name) { $rc = new \ReflectionClass($class); $hint = self::getSuggestion(array_merge( @@ -44,7 +44,7 @@ public static function strictGet($class, $name) /** * @throws MemberAccessException */ - public static function strictSet($class, $name) + public static function strictSet(string $class, string $name) { $rc = new \ReflectionClass($class); $hint = self::getSuggestion(array_merge( @@ -58,7 +58,7 @@ public static function strictSet($class, $name) /** * @throws MemberAccessException */ - public static function strictCall($class, $method, $additionalMethods = []) + public static function strictCall(string $class, string $method, array $additionalMethods = []) { $hint = self::getSuggestion(array_merge( get_class_methods($class), @@ -76,7 +76,7 @@ public static function strictCall($class, $method, $additionalMethods = []) /** * @throws MemberAccessException */ - public static function strictStaticCall($class, $method) + public static function strictStaticCall(string $class, string $method) { $hint = self::getSuggestion( array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), function ($m) { return $m->isStatic(); }), @@ -97,7 +97,7 @@ public static function strictStaticCall($class, $method) * @return mixed * @throws MemberAccessException */ - public static function call($_this, $name, $args) + public static function call($_this, string $name, array $args) { $class = get_class($_this); $isProp = self::hasProperty($class, $name); @@ -154,7 +154,7 @@ public static function call($_this, $name, $args) * @return void * @throws MemberAccessException */ - public static function callStatic($class, $method, $args) + public static function callStatic(string $class, string $method, array $args) { self::strictStaticCall($class, $method); } @@ -167,7 +167,7 @@ public static function callStatic($class, $method, $args) * @return mixed property value * @throws MemberAccessException if the property is not defined. */ - public static function &get($_this, $name) + public static function &get($_this, string $name) { $class = get_class($_this); $uname = ucfirst($name); @@ -211,7 +211,7 @@ public static function &get($_this, $name) * @return void * @throws MemberAccessException if the property is not defined or is read-only */ - public static function set($_this, $name, $value) + public static function set($_this, string $name, $value) { $class = get_class($_this); $uname = ucfirst($name); @@ -242,7 +242,7 @@ public static function set($_this, $name, $value) * @return void * @throws MemberAccessException */ - public static function remove($_this, $name) + public static function remove($_this, string $name) { $class = get_class($_this); if (!self::hasProperty($class, $name)) { @@ -257,7 +257,7 @@ public static function remove($_this, $name) * @param string property name * @return bool */ - public static function has($_this, $name) + public static function has($_this, string $name): bool { $name = ucfirst($name); $methods = &self::getMethods(get_class($_this)); @@ -272,7 +272,7 @@ public static function has($_this, $name) * Returns array of magic properties defined by annotation @property. * @return array of [name => bit mask] */ - public static function getMagicProperties($class) + public static function getMagicProperties(string $class): array { static $cache; $props = &$cache[$class]; @@ -313,7 +313,7 @@ public static function getMagicProperties($class) /** @internal */ - public static function getMagicProperty($class, $name) + public static function getMagicProperty(string $class, string $name) { $props = self::getMagicProperties($class); return isset($props[$name]) ? $props[$name] : NULL; @@ -327,7 +327,7 @@ public static function getMagicProperty($class, $name) * Returns array of magic methods defined by annotation @method. * @return array */ - public static function getMagicMethods($class) + public static function getMagicMethods(string $class): array { $rc = new \ReflectionClass($class); preg_match_all('~^ @@ -367,7 +367,7 @@ public static function getMagicMethods($class) * @return bool * @internal */ - public static function checkType(&$val, $type) + public static function checkType(&$val, string $type): bool { if (strpos($type, '|') !== FALSE) { $found = NULL; @@ -439,7 +439,7 @@ public static function checkType(&$val, $type) * @param mixed callable * @return void */ - public static function setExtensionMethod($class, $name, $callback) + public static function setExtensionMethod(string $class, string $name, callable $callback) { $name = strtolower($name); self::$extMethods[$name][$class] = Callback::check($callback); @@ -453,7 +453,7 @@ public static function setExtensionMethod($class, $name, $callback) * @param string * @return mixed */ - public static function getExtensionMethod($class, $name) + public static function getExtensionMethod(string $class, string $name) { $list = &self::$extMethods[strtolower($name)]; $cache = &$list[''][$class]; @@ -475,7 +475,7 @@ public static function getExtensionMethod($class, $name) * @param string * @return array */ - public static function getExtensionMethods($class) + public static function getExtensionMethods(string $class): array { $res = []; foreach (array_keys(self::$extMethods) as $name) { @@ -495,7 +495,7 @@ public static function getExtensionMethods($class) * @return string|NULL * @internal */ - public static function getSuggestion(array $possibilities, $value) + public static function getSuggestion(array $possibilities, string $value) { $norm = preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '', $value); $best = NULL; @@ -514,7 +514,7 @@ public static function getSuggestion(array $possibilities, $value) } - private static function parseFullDoc(\ReflectionClass $rc, $pattern) + private static function parseFullDoc(\ReflectionClass $rc, string $pattern): array { do { $doc[] = $rc->getDocComment(); @@ -533,7 +533,7 @@ private static function parseFullDoc(\ReflectionClass $rc, $pattern) * @return bool|'event' * @internal */ - public static function hasProperty($class, $name) + public static function hasProperty(string $class, string $name) { static $cache; $prop = &$cache[$class][$name]; @@ -556,7 +556,7 @@ public static function hasProperty($class, $name) * @return array * @internal */ - public static function &getMethods($class) + public static function &getMethods(string $class): array { static $cache; if (!isset($cache[$class])) { diff --git a/src/Utils/Paginator.php b/src/Utils/Paginator.php index ba43264dc..1647d9c6d 100644 --- a/src/Utils/Paginator.php +++ b/src/Utils/Paginator.php @@ -50,9 +50,9 @@ class Paginator * @param int * @return static */ - public function setPage($page) + public function setPage(int $page): self { - $this->page = (int) $page; + $this->page = $page; return $this; } @@ -61,7 +61,7 @@ public function setPage($page) * Returns current page number. * @return int */ - public function getPage() + public function getPage(): int { return $this->base + $this->getPageIndex(); } @@ -71,7 +71,7 @@ public function getPage() * Returns first page number. * @return int */ - public function getFirstPage() + public function getFirstPage(): int { return $this->base; } @@ -92,9 +92,9 @@ public function getLastPage() * @param int * @return static */ - public function setBase($base) + public function setBase(int $base): self { - $this->base = (int) $base; + $this->base = $base; return $this; } @@ -103,7 +103,7 @@ public function setBase($base) * Returns first page (base) number. * @return int */ - public function getBase() + public function getBase(): int { return $this->base; } @@ -113,7 +113,7 @@ public function getBase() * Returns zero-based page number. * @return int */ - protected function getPageIndex() + protected function getPageIndex(): int { $index = max(0, $this->page - $this->base); return $this->itemCount === NULL ? $index : min($index, max(0, $this->getPageCount() - 1)); @@ -124,7 +124,7 @@ protected function getPageIndex() * Is the current page the first one? * @return bool */ - public function isFirst() + public function isFirst(): bool { return $this->getPageIndex() === 0; } @@ -134,7 +134,7 @@ public function isFirst() * Is the current page the last one? * @return bool */ - public function isLast() + public function isLast(): bool { return $this->itemCount === NULL ? FALSE : $this->getPageIndex() >= $this->getPageCount() - 1; } @@ -155,9 +155,9 @@ public function getPageCount() * @param int * @return static */ - public function setItemsPerPage($itemsPerPage) + public function setItemsPerPage(int $itemsPerPage): self { - $this->itemsPerPage = max(1, (int) $itemsPerPage); + $this->itemsPerPage = max(1, $itemsPerPage); return $this; } @@ -166,7 +166,7 @@ public function setItemsPerPage($itemsPerPage) * Returns the number of items to display on a single page. * @return int */ - public function getItemsPerPage() + public function getItemsPerPage(): int { return $this->itemsPerPage; } @@ -177,9 +177,9 @@ public function getItemsPerPage() * @param int (or NULL as infinity) * @return static */ - public function setItemCount($itemCount) + public function setItemCount(int $itemCount = NULL): self { - $this->itemCount = ($itemCount === FALSE || $itemCount === NULL) ? NULL : max(0, (int) $itemCount); + $this->itemCount = $itemCount === NULL ? NULL : max(0, $itemCount); return $this; } @@ -198,7 +198,7 @@ public function getItemCount() * Returns the absolute index of the first item on current page. * @return int */ - public function getOffset() + public function getOffset(): int { return $this->getPageIndex() * $this->itemsPerPage; } diff --git a/src/Utils/Random.php b/src/Utils/Random.php index b260c55c4..24297c310 100644 --- a/src/Utils/Random.php +++ b/src/Utils/Random.php @@ -25,7 +25,7 @@ class Random * @param string * @return string */ - public static function generate($length = 10, $charlist = '0-9a-z') + public static function generate(int $length = 10, string $charlist = '0-9a-z'): string { $charlist = count_chars(preg_replace_callback('#.-.#', function (array $m) { return implode('', range($m[0][0], $m[0][2])); diff --git a/src/Utils/Reflection.php b/src/Utils/Reflection.php index 131aad282..4f8ecce60 100644 --- a/src/Utils/Reflection.php +++ b/src/Utils/Reflection.php @@ -29,7 +29,7 @@ class Reflection * @param string * @return bool */ - public static function isBuiltinType($type) + public static function isBuiltinType(string $type): bool { return isset(self::$builtinTypes[strtolower($type)]); } @@ -85,7 +85,7 @@ public static function getParameterDefaultValue(\ReflectionParameter $param) * Returns declaring class or trait. * @return \ReflectionClass */ - public static function getPropertyDeclaringClass(\ReflectionProperty $prop) + public static function getPropertyDeclaringClass(\ReflectionProperty $prop): \ReflectionClass { foreach ($prop->getDeclaringClass()->getTraits() as $trait) { if ($trait->hasProperty($prop->getName())) { @@ -100,7 +100,7 @@ public static function getPropertyDeclaringClass(\ReflectionProperty $prop) * Are documentation comments available? * @return bool */ - public static function areCommentsAvailable() + public static function areCommentsAvailable(): bool { static $res; return $res === NULL @@ -112,7 +112,7 @@ public static function areCommentsAvailable() /** * @return string */ - public static function toString(\Reflector $ref) + public static function toString(\Reflector $ref): string { if ($ref instanceof \ReflectionClass) { return $ref->getName(); @@ -136,7 +136,7 @@ public static function toString(\Reflector $ref) * @return string full name * @throws Nette\InvalidArgumentException */ - public static function expandClassName($name, \ReflectionClass $rc) + public static function expandClassName(string $name, \ReflectionClass $rc): string { $lower = strtolower($name); if (empty($name)) { @@ -170,7 +170,7 @@ public static function expandClassName($name, \ReflectionClass $rc) /** * @return array of [alias => class] */ - public static function getUseStatements(\ReflectionClass $class) + public static function getUseStatements(\ReflectionClass $class): array { static $cache = []; if (!isset($cache[$name = $class->getName()])) { @@ -190,7 +190,7 @@ public static function getUseStatements(\ReflectionClass $class) * @param string * @return array of [class => [alias => class, ...]] */ - private static function parseUseStatements($code, $forClass = NULL) + private static function parseUseStatements(string $code, string $forClass = NULL): array { $tokens = token_get_all($code); $namespace = $class = $classLevel = $level = NULL; diff --git a/src/Utils/SmartObject.php b/src/Utils/SmartObject.php index e1ebcc3b6..cd3e49d31 100644 --- a/src/Utils/SmartObject.php +++ b/src/Utils/SmartObject.php @@ -202,7 +202,7 @@ public function __isset($name) * @return Reflection\ClassType|\ReflectionClass * @deprecated */ - public static function getReflection() + public static function getReflection(): \ReflectionClass { trigger_error(get_called_class() . '::getReflection() is deprecated' . ObjectMixin::getSource(), E_USER_DEPRECATED); $class = class_exists(Reflection\ClassType::class) ? Reflection\ClassType::class : \ReflectionClass::class; @@ -214,7 +214,7 @@ public static function getReflection() * @return mixed * @deprecated use Nette\Utils\ObjectMixin::setExtensionMethod() */ - public static function extensionMethod($name, $callback = NULL) + public static function extensionMethod(string $name, $callback = NULL) { if (strpos($name, '::') === FALSE) { $class = get_called_class(); diff --git a/src/Utils/Strings.php b/src/Utils/Strings.php index 2c2948e2d..f22b8615c 100644 --- a/src/Utils/Strings.php +++ b/src/Utils/Strings.php @@ -28,7 +28,7 @@ class Strings * @param string byte stream to check * @return bool */ - public static function checkEncoding($s) + public static function checkEncoding(string $s): bool { return $s === self::fixEncoding($s); } @@ -39,7 +39,7 @@ public static function checkEncoding($s) * @param string byte stream to fix * @return string */ - public static function fixEncoding($s) + public static function fixEncoding(string $s): string { // removes xD800-xDFFF, x110000 and higher return htmlspecialchars_decode(htmlspecialchars($s, ENT_NOQUOTES | ENT_IGNORE, 'UTF-8'), ENT_NOQUOTES); @@ -52,7 +52,7 @@ public static function fixEncoding($s) * @return string * @throws Nette\InvalidArgumentException if code point is not in valid range */ - public static function chr($code) + public static function chr(int $code): string { if ($code < 0 || ($code >= 0xD800 && $code <= 0xDFFF) || $code > 0x10FFFF) { throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.'); @@ -67,7 +67,7 @@ public static function chr($code) * @param string * @return bool */ - public static function startsWith($haystack, $needle) + public static function startsWith(string $haystack, string $needle): bool { return strncmp($haystack, $needle, strlen($needle)) === 0; } @@ -79,7 +79,7 @@ public static function startsWith($haystack, $needle) * @param string * @return bool */ - public static function endsWith($haystack, $needle) + public static function endsWith(string $haystack, string $needle): bool { return strlen($needle) === 0 || substr($haystack, -strlen($needle)) === $needle; } @@ -91,7 +91,7 @@ public static function endsWith($haystack, $needle) * @param string * @return bool */ - public static function contains($haystack, $needle) + public static function contains(string $haystack, string $needle): bool { return strpos($haystack, $needle) !== FALSE; } @@ -104,7 +104,7 @@ public static function contains($haystack, $needle) * @param int in characters (code points) * @return string */ - public static function substring($s, $start, $length = NULL) + public static function substring(string $s, int $start, int $length = NULL): string { if (function_exists('mb_substr')) { return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster @@ -122,7 +122,7 @@ public static function substring($s, $start, $length = NULL) * @param string UTF-8 encoding * @return string */ - public static function normalize($s) + public static function normalize(string $s): string { $s = self::normalizeNewLines($s); @@ -144,7 +144,7 @@ public static function normalize($s) * @param string UTF-8 encoding or 8-bit * @return string */ - public static function normalizeNewLines($s) + public static function normalizeNewLines(string $s): string { return str_replace(["\r\n", "\r"], "\n", $s); } @@ -155,7 +155,7 @@ public static function normalizeNewLines($s) * @param string UTF-8 encoding * @return string ASCII */ - public static function toAscii($s) + public static function toAscii(string $s): string { static $transliterator = NULL; if ($transliterator === NULL && class_exists('Transliterator', FALSE)) { @@ -199,7 +199,7 @@ public static function toAscii($s) * @param bool * @return string */ - public static function webalize($s, $charlist = NULL, $lower = TRUE) + public static function webalize(string $s, string $charlist = NULL, bool $lower = TRUE): string { $s = self::toAscii($s); if ($lower) { @@ -218,7 +218,7 @@ public static function webalize($s, $charlist = NULL, $lower = TRUE) * @param string UTF-8 encoding * @return string */ - public static function truncate($s, $maxLen, $append = "\xE2\x80\xA6") + public static function truncate(string $s, int $maxLen, string $append = "\xE2\x80\xA6"): string { if (self::length($s) > $maxLen) { $maxLen = $maxLen - self::length($append); @@ -243,7 +243,7 @@ public static function truncate($s, $maxLen, $append = "\xE2\x80\xA6") * @param string * @return string */ - public static function indent($s, $level = 1, $chars = "\t") + public static function indent(string $s, int $level = 1, string $chars = "\t"): string { if ($level > 0) { $s = self::replace($s, '#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level)); @@ -257,7 +257,7 @@ public static function indent($s, $level = 1, $chars = "\t") * @param string UTF-8 encoding * @return string */ - public static function lower($s) + public static function lower(string $s): string { return mb_strtolower($s, 'UTF-8'); } @@ -268,7 +268,7 @@ public static function lower($s) * @param string UTF-8 encoding * @return string */ - public static function firstLower($s) + public static function firstLower(string $s): string { return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1); } @@ -279,7 +279,7 @@ public static function firstLower($s) * @param string UTF-8 encoding * @return string */ - public static function upper($s) + public static function upper(string $s): string { return mb_strtoupper($s, 'UTF-8'); } @@ -290,7 +290,7 @@ public static function upper($s) * @param string UTF-8 encoding * @return string */ - public static function firstUpper($s) + public static function firstUpper(string $s): string { return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1); } @@ -301,7 +301,7 @@ public static function firstUpper($s) * @param string UTF-8 encoding * @return string */ - public static function capitalize($s) + public static function capitalize(string $s): string { return mb_convert_case($s, MB_CASE_TITLE, 'UTF-8'); } @@ -314,7 +314,7 @@ public static function capitalize($s) * @param int * @return bool */ - public static function compare($left, $right, $len = NULL) + public static function compare(string $left, string $right, int $len = NULL): bool { if ($len < 0) { $left = self::substring($left, $len, -$len); @@ -332,7 +332,7 @@ public static function compare($left, $right, $len = NULL) * @param string|array * @return string */ - public static function findPrefix(...$strings) + public static function findPrefix(...$strings): string { if (is_array($strings[0])) { $strings = $strings[0]; @@ -358,7 +358,7 @@ public static function findPrefix(...$strings) * @param string * @return int */ - public static function length($s) + public static function length(string $s): int { return function_exists('mb_strlen') ? mb_strlen($s, 'UTF-8') : strlen(utf8_decode($s)); } @@ -370,7 +370,7 @@ public static function length($s) * @param string * @return string */ - public static function trim($s, $charlist = self::TRIM_CHARACTERS) + public static function trim(string $s, string $charlist = self::TRIM_CHARACTERS): string { $charlist = preg_quote($charlist, '#'); return self::replace($s, '#^['.$charlist.']+|['.$charlist.']+\z#u', ''); @@ -384,7 +384,7 @@ public static function trim($s, $charlist = self::TRIM_CHARACTERS) * @param string * @return string */ - public static function padLeft($s, $length, $pad = ' ') + public static function padLeft(string $s, int $length, string $pad = ' '): string { $length = max(0, $length - self::length($s)); $padLen = self::length($pad); @@ -399,7 +399,7 @@ public static function padLeft($s, $length, $pad = ' ') * @param string * @return string */ - public static function padRight($s, $length, $pad = ' ') + public static function padRight(string $s, int $length, string $pad = ' '): string { $length = max(0, $length - self::length($s)); $padLen = self::length($pad); @@ -412,7 +412,7 @@ public static function padRight($s, $length, $pad = ' ') * @param string UTF-8 encoding * @return string */ - public static function reverse($s) + public static function reverse(string $s): string { return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', $s))); } @@ -425,7 +425,7 @@ public static function reverse($s) * @param int negative value means searching from the end * @return string|FALSE returns FALSE if the needle was not found */ - public static function before($haystack, $needle, $nth = 1) + public static function before(string $haystack, string $needle, int $nth = 1) { $pos = self::pos($haystack, $needle, $nth); return $pos === FALSE @@ -441,7 +441,7 @@ public static function before($haystack, $needle, $nth = 1) * @param int negative value means searching from the end * @return string|FALSE returns FALSE if the needle was not found */ - public static function after($haystack, $needle, $nth = 1) + public static function after(string $haystack, string $needle, int $nth = 1) { $pos = self::pos($haystack, $needle, $nth); return $pos === FALSE @@ -457,7 +457,7 @@ public static function after($haystack, $needle, $nth = 1) * @param int negative value means searching from the end * @return int|FALSE offset in characters or FALSE if the needle was not found */ - public static function indexOf($haystack, $needle, $nth = 1) + public static function indexOf(string $haystack, string $needle, int $nth = 1) { $pos = self::pos($haystack, $needle, $nth); return $pos === FALSE @@ -470,7 +470,7 @@ public static function indexOf($haystack, $needle, $nth = 1) * Returns position of $nth occurence of $needle in $haystack. * @return int|FALSE offset in bytes or FALSE if the needle was not found */ - private static function pos($haystack, $needle, $nth = 1) + private static function pos(string $haystack, string $needle, int $nth = 1) { if (!$nth) { return FALSE; @@ -503,7 +503,7 @@ private static function pos($haystack, $needle, $nth = 1) * @param int * @return array */ - public static function split($subject, $pattern, $flags = 0) + public static function split(string $subject, string $pattern, int $flags = 0): array { return self::pcre('preg_split', [$pattern, $subject, -1, $flags | PREG_SPLIT_DELIM_CAPTURE]); } @@ -517,7 +517,7 @@ public static function split($subject, $pattern, $flags = 0) * @param int offset in bytes * @return mixed */ - public static function match($subject, $pattern, $flags = 0, $offset = 0) + public static function match(string $subject, string $pattern, int $flags = 0, int $offset = 0) { if ($offset > strlen($subject)) { return NULL; @@ -536,7 +536,7 @@ public static function match($subject, $pattern, $flags = 0, $offset = 0) * @param int offset in bytes * @return array */ - public static function matchAll($subject, $pattern, $flags = 0, $offset = 0) + public static function matchAll(string $subject, string $pattern, int $flags = 0, int $offset = 0): array { if ($offset > strlen($subject)) { return []; @@ -558,7 +558,7 @@ public static function matchAll($subject, $pattern, $flags = 0, $offset = 0) * @param int * @return string */ - public static function replace($subject, $pattern, $replacement = NULL, $limit = -1) + public static function replace(string $subject, $pattern, $replacement = NULL, int $limit = -1): string { if (is_object($replacement) || is_array($replacement)) { if (!is_callable($replacement, FALSE, $textual)) { @@ -576,7 +576,7 @@ public static function replace($subject, $pattern, $replacement = NULL, $limit = /** @internal */ - public static function pcre($func, $args) + public static function pcre(string $func, array $args) { static $messages = [ PREG_INTERNAL_ERROR => 'Internal error', @@ -586,7 +586,7 @@ public static function pcre($func, $args) PREG_BAD_UTF8_OFFSET_ERROR => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point', 6 => 'Failed due to limited JIT stack space', // PREG_JIT_STACKLIMIT_ERROR ]; - $res = Callback::invokeSafe($func, $args, function ($message) use ($args) { + $res = Callback::invokeSafe($func, $args, function (string $message) use ($args) { // compile-time error, not detectable by preg_last_error throw new RegexpException($message . ' in pattern: ' . implode(' or ', (array) $args[0])); }); diff --git a/src/Utils/Validators.php b/src/Utils/Validators.php index d84cec456..24aa39aa6 100644 --- a/src/Utils/Validators.php +++ b/src/Utils/Validators.php @@ -76,7 +76,7 @@ class Validators * @param string label * @return void */ - public static function assert($value, $expected, $label = 'variable') + public static function assert($value, string $expected, string $label = 'variable') { if (!static::is($value, $expected)) { $expected = str_replace(['|', ':'], [' or ', ' in range '], $expected); @@ -102,7 +102,7 @@ public static function assert($value, $expected, $label = 'variable') * @param string * @return void */ - public static function assertField($arr, $field, $expected = NULL, $label = "item '%' in array") + public static function assertField($arr, string $field, string $expected = NULL, string $label = "item '%' in array") { self::assert($arr, 'array', 'first argument'); if (!array_key_exists($field, $arr)) { @@ -120,7 +120,7 @@ public static function assertField($arr, $field, $expected = NULL, $label = "ite * @param string expected types separated by pipe with optional ranges * @return bool */ - public static function is($value, $expected) + public static function is($value, string $expected): bool { foreach (explode('|', $expected) as $item) { if (substr($item, -2) === '[]') { @@ -165,11 +165,11 @@ public static function is($value, $expected) /** * Finds whether all values are of expected type. - * @param array|\Traversable + * @param iterable * @param string expected types separated by pipe with optional ranges * @return bool */ - public static function everyIs($values, $expected) + public static function everyIs($values, string $expected): bool { if (!self::isIterable($values)) { return FALSE; @@ -197,7 +197,7 @@ public static function isNumber($value) * Finds whether a value is an integer. * @return bool */ - public static function isNumericInt($value) + public static function isNumericInt($value): bool { return is_int($value) || is_string($value) && preg_match('#^-?[0-9]+\z#', $value); } @@ -207,7 +207,7 @@ public static function isNumericInt($value) * Finds whether a string is a floating point number in decimal base. * @return bool */ - public static function isNumeric($value) + public static function isNumeric($value): bool { return is_float($value) || is_int($value) || is_string($value) && preg_match('#^-?[0-9]*[.]?[0-9]+\z#', $value); } @@ -217,7 +217,7 @@ public static function isNumeric($value) * Finds whether a value is a syntactically correct callback. * @return bool */ - public static function isCallable($value) + public static function isCallable($value): bool { return $value && is_callable($value, TRUE); } @@ -228,7 +228,7 @@ public static function isCallable($value) * @param string * @return bool */ - public static function isUnicode($value) + public static function isUnicode($value): bool { return is_string($value) && preg_match('##u', $value); } @@ -238,7 +238,7 @@ public static function isUnicode($value) * Finds whether a value is "falsy". * @return bool */ - public static function isNone($value) + public static function isNone($value): bool { return $value == NULL; // intentionally == } @@ -249,7 +249,7 @@ public static function isNone($value) * @param array * @return bool */ - public static function isList($value) + public static function isList($value): bool { return Arrays::isList($value); } @@ -261,7 +261,7 @@ public static function isList($value) * @param array min and max value pair * @return bool */ - public static function isInRange($value, $range) + public static function isInRange($value, array $range): bool { return (!isset($range[0]) || $range[0] === '' || $value >= $range[0]) && (!isset($range[1]) || $range[1] === '' || $value <= $range[1]); @@ -273,7 +273,7 @@ public static function isInRange($value, $range) * @param string * @return bool */ - public static function isEmail($value) + public static function isEmail(string $value): bool { $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part $alpha = "a-z\x80-\xFF"; // superset of IDN @@ -291,7 +291,7 @@ public static function isEmail($value) * @param string * @return bool */ - public static function isUrl($value) + public static function isUrl(string $value): bool { $alpha = "a-z\x80-\xFF"; return (bool) preg_match("(^ @@ -312,7 +312,7 @@ public static function isUrl($value) * @param string * @return bool */ - public static function isUri($value) + public static function isUri(string $value): bool { return (bool) preg_match('#^[a-z\d+\.-]+:\S+\z#i', $value); } @@ -323,7 +323,7 @@ public static function isUri($value) * @param string * @return bool */ - public static function isType($type) + public static function isType(string $type): bool { return class_exists($type) || interface_exists($type) || trait_exists($type); } @@ -333,7 +333,7 @@ public static function isType($type) * Checks whether the input is a valid PHP identifier. * @return bool */ - public static function isPhpIdentifier($value) + public static function isPhpIdentifier(string $value): bool { return is_string($value) && preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\z#', $value); } diff --git a/tests/Utils/Random.generate().phpt b/tests/Utils/Random.generate().phpt index c099d94b4..10ebf43bc 100644 --- a/tests/Utils/Random.generate().phpt +++ b/tests/Utils/Random.generate().phpt @@ -33,7 +33,7 @@ Assert::exception(function () { // frequency check $phpdbgLog = defined('PHPDBG_VERSION') && @phpdbg_end_oplog(); // memory leak workaround -$length = 1e6; +$length = (int) 1e6; $delta = 0.1; $s = Nette\Utils\Random::generate($length, "\x01-\xFF"); $freq = count_chars($s);