Automated formatting changes

This commit is contained in:
Formatter Bot 2021-10-11 20:04:39 +00:00
parent ba7f68f69f
commit 4ce8879933
417 changed files with 3521 additions and 3521 deletions

View File

@ -255,7 +255,7 @@ class Account implements \JsonSerializable, ArrayableInterface
throw new \InvalidArgumentException(); throw new \InvalidArgumentException();
} }
$this->email = \mb_strtolower($email); $this->email = mb_strtolower($email);
} }
/** /**
@ -347,7 +347,7 @@ class Account implements \JsonSerializable, ArrayableInterface
*/ */
public function generatePassword(string $password) : void public function generatePassword(string $password) : void
{ {
$temp = \password_hash($password, \PASSWORD_BCRYPT); $temp = password_hash($password, \PASSWORD_BCRYPT);
if ($temp === false) { if ($temp === false) {
throw new \Exception('Internal password_hash error.'); // @codeCoverageIgnore throw new \Exception('Internal password_hash error.'); // @codeCoverageIgnore
@ -377,7 +377,7 @@ class Account implements \JsonSerializable, ArrayableInterface
*/ */
public function __toString() : string public function __toString() : string
{ {
return (string) \json_encode($this->toArray()); return (string) json_encode($this->toArray());
} }
/** /**

View File

@ -130,7 +130,7 @@ class Group implements \JsonSerializable, ArrayableInterface
*/ */
public function __toString() : string public function __toString() : string
{ {
return (string) \json_encode($this->toArray()); return (string) json_encode($this->toArray());
} }
/** /**

View File

@ -72,7 +72,7 @@ trait PermissionHandlingTrait
{ {
foreach ($permissions as $permission) { foreach ($permissions as $permission) {
if (\is_array($permission)) { if (\is_array($permission)) {
$this->permissions = \array_merge($this->permissions, $permission); $this->permissions = array_merge($this->permissions, $permission);
} else { } else {
$this->permissions[] = $permission; $this->permissions[] = $permission;
} }
@ -155,7 +155,7 @@ trait PermissionHandlingTrait
int $component = null int $component = null
) : bool ) : bool
{ {
$app = $app !== null ? \strtolower($app) : $app; $app = $app !== null ? strtolower($app) : $app;
foreach ($this->permissions as $p) { foreach ($this->permissions as $p) {
if ($p->hasPermission($permission, $unit, $app, $module, $type, $element, $component)) { if ($p->hasPermission($permission, $unit, $app, $module, $type, $element, $component)) {

View File

@ -65,8 +65,8 @@ final class BasicOcr
$Xtrain = $this->readImages($dataPath, $limit); $Xtrain = $this->readImages($dataPath, $limit);
$ytrain = $this->readLabels($labelPath, $limit); $ytrain = $this->readLabels($labelPath, $limit);
$this->Xtrain = \array_merge($this->Xtrain, $Xtrain); $this->Xtrain = array_merge($this->Xtrain, $Xtrain);
$this->ytrain = \array_merge($this->ytrain, $ytrain); $this->ytrain = array_merge($this->ytrain, $ytrain);
} }
/** /**
@ -81,50 +81,50 @@ final class BasicOcr
*/ */
private function readImages(string $path, int $limit = 0) : array private function readImages(string $path, int $limit = 0) : array
{ {
if (!\is_file($path)) { if (!is_file($path)) {
throw new PathException($path); throw new PathException($path);
} }
$fp = \fopen($path, 'r'); $fp = fopen($path, 'r');
if ($fp === false) { if ($fp === false) {
throw new PathException($path); // @codeCoverageIgnore throw new PathException($path); // @codeCoverageIgnore
} }
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$magicNumber = $unpack[1]; $magicNumber = $unpack[1];
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$numberOfImages = $unpack[1]; $numberOfImages = $unpack[1];
if ($limit > 0) { if ($limit > 0) {
$numberOfImages = \min($numberOfImages, $limit); $numberOfImages = min($numberOfImages, $limit);
} }
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$numberOfRows = $unpack[1]; $numberOfRows = $unpack[1];
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$numberOfColumns = $unpack[1]; $numberOfColumns = $unpack[1];
$images = []; $images = [];
for ($i = 0; $i < $numberOfImages; ++$i) { for ($i = 0; $i < $numberOfImages; ++$i) {
if (($read = \fread($fp, $numberOfRows * $numberOfColumns)) === false if (($read = fread($fp, $numberOfRows * $numberOfColumns)) === false
|| ($unpack = \unpack('C*', $read)) === false || ($unpack = unpack('C*', $read)) === false
) { ) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$images[] = \array_values($unpack); $images[] = array_values($unpack);
} }
\fclose($fp); fclose($fp);
return $images; return $images;
} }
@ -141,38 +141,38 @@ final class BasicOcr
*/ */
private function readLabels(string $path, int $limit = 0) : array private function readLabels(string $path, int $limit = 0) : array
{ {
if (!\is_file($path)) { if (!is_file($path)) {
throw new PathException($path); throw new PathException($path);
} }
$fp = \fopen($path, 'r'); $fp = fopen($path, 'r');
if ($fp === false) { if ($fp === false) {
throw new PathException($path); // @codeCoverageIgnore throw new PathException($path); // @codeCoverageIgnore
} }
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$magicNumber = $unpack[1]; $magicNumber = $unpack[1];
if (($read = \fread($fp, 4)) === false || ($unpack = \unpack('N', $read)) === false) { if (($read = fread($fp, 4)) === false || ($unpack = unpack('N', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$numberOfLabels = $unpack[1]; $numberOfLabels = $unpack[1];
if ($limit > 0) { if ($limit > 0) {
$numberOfLabels = \min($numberOfLabels, $limit); $numberOfLabels = min($numberOfLabels, $limit);
} }
$labels = []; $labels = [];
for ($i = 0; $i < $numberOfLabels; ++$i) { for ($i = 0; $i < $numberOfLabels; ++$i) {
if (($read = \fread($fp, 1)) === false || ($unpack = \unpack('C', $read)) === false) { if (($read = fread($fp, 1)) === false || ($unpack = unpack('C', $read)) === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$labels[] = $unpack[1]; $labels[] = $unpack[1];
} }
\fclose($fp); fclose($fp);
return $labels; return $labels;
} }
@ -190,9 +190,9 @@ final class BasicOcr
$predictedLabels = []; $predictedLabels = [];
foreach ($Xtest as $sample) { foreach ($Xtest as $sample) {
$distances = $this->getDistances($Xtrain, $sample); $distances = $this->getDistances($Xtrain, $sample);
\asort($distances); asort($distances);
$keys = \array_keys($distances); $keys = array_keys($distances);
$candidateLabels = []; $candidateLabels = [];
for ($i = 0; $i < $k; ++$i) { for ($i = 0; $i < $k; ++$i) {
@ -200,7 +200,7 @@ final class BasicOcr
} }
// find best match // find best match
$countedCandidates = \array_count_values($candidateLabels); $countedCandidates = array_count_values($candidateLabels);
foreach ($candidateLabels as $i => $label) { foreach ($candidateLabels as $i => $label) {
$predictedLabels[] = [ $predictedLabels[] = [

View File

@ -215,8 +215,8 @@ final class Kmeans
*/ */
private function kpp(array $points, int $n) : array private function kpp(array $points, int $n) : array
{ {
$clusters = [clone $points[\mt_rand(0, \count($points) - 1)]]; $clusters = [clone $points[mt_rand(0, \count($points) - 1)]];
$d = \array_fill(0, $n, 0.0); $d = array_fill(0, $n, 0.0);
for ($i = 1; $i < $n; ++$i) { for ($i = 1; $i < $n; ++$i) {
$sum = 0; $sum = 0;
@ -226,7 +226,7 @@ final class Kmeans
$sum += $d[$key]; $sum += $d[$key];
} }
$sum *= \mt_rand(0, \mt_getrandmax()) / \mt_getrandmax(); $sum *= mt_rand(0, mt_getrandmax()) / mt_getrandmax();
foreach ($d as $key => $di) { foreach ($d as $key => $di) {
$sum -= $di; $sum -= $di;

View File

@ -18,8 +18,8 @@ namespace phpOMS\Algorithm\Clustering;
/** /**
* Point interface. * Point interface.
* *
* @property int $group Group * @property int $group Group
* @property string $name Name * @property string $name Name
* *
* @package phpOMS\Algorithm\Clustering; * @package phpOMS\Algorithm\Clustering;
* @license OMS License 1.0 * @license OMS License 1.0

View File

@ -65,7 +65,7 @@ final class MinimumCoinProblem
&& $subRes + 1 < $table[$i] && $subRes + 1 < $table[$i]
) { ) {
$table[$i] = $subRes + 1; $table[$i] = $subRes + 1;
$usedCoins[$i] = $coins[$j] === null ? ($usedCoins[$i] ?? []) : \array_merge($usedCoins[$i - $coins[$j]] ?? [], [$coins[$j]]); $usedCoins[$i] = $coins[$j] === null ? ($usedCoins[$i] ?? []) : array_merge($usedCoins[$i - $coins[$j]] ?? [], [$coins[$j]]);
} }
} }
} }

View File

@ -114,7 +114,7 @@ final class Weighted
return $jobs; return $jobs;
} }
\usort($jobs, [self::class, 'sortByEnd']); usort($jobs, [self::class, 'sortByEnd']);
$valueTable = [$jobs[0]->getValue()]; $valueTable = [$jobs[0]->getValue()];
@ -128,7 +128,7 @@ final class Weighted
if ($l != -1) { if ($l != -1) {
$value += $valueTable[$l]; $value += $valueTable[$l];
$jList = \array_merge($resultTable[$l], $jList); $jList = array_merge($resultTable[$l], $jList);
} }
if ($value > $valueTable[$i - 1]) { if ($value > $valueTable[$i - 1]) {

View File

@ -55,7 +55,7 @@ final class Bounded
// @var int<0, max> $maxCost // @var int<0, max> $maxCost
$maxCost = (int) $backpack->getMaxCost(); $maxCost = (int) $backpack->getMaxCost();
$mm = \array_fill(0, ($maxCost + 1), 0); $mm = array_fill(0, ($maxCost + 1), 0);
$m = []; $m = [];
$m[0] = $mm; $m[0] = $mm;

View File

@ -62,7 +62,7 @@ final class Continuous
*/ */
public static function solve(array $items, BackpackInterface $backpack) : BackpackInterface public static function solve(array $items, BackpackInterface $backpack) : BackpackInterface
{ {
\usort($items, ['self', 'continuousComparator']); usort($items, ['self', 'continuousComparator']);
$availableSpace = $backpack->getMaxCost(); $availableSpace = $backpack->getMaxCost();
@ -73,7 +73,7 @@ final class Continuous
$backpack->addItem( $backpack->addItem(
$item['item'], $item['item'],
$quantity = \min($item['quantity'], $availableSpace / $item['item']->getCost()) $quantity = min($item['quantity'], $availableSpace / $item['item']->getCost())
); );
$availableSpace -= $quantity * $item['item']->getCost(); $availableSpace -= $quantity * $item['item']->getCost();

View File

@ -48,10 +48,10 @@ class MazeGenerator
public static function random(int $width, int $height) : array public static function random(int $width, int $height) : array
{ {
$n = $height * $width - 1; $n = $height * $width - 1;
$horizontal = \array_fill(0, $height, []); $horizontal = array_fill(0, $height, []);
$vertical = \array_fill(0, $height, []); $vertical = array_fill(0, $height, []);
$pos = [\mt_rand(0, $height) - 1, \mt_rand(0, $width) - 1]; $pos = [mt_rand(0, $height) - 1, mt_rand(0, $width) - 1];
$path = [$pos]; $path = [$pos];
$unvisited = []; $unvisited = [];
@ -82,7 +82,7 @@ class MazeGenerator
if (!empty($neighbors)) { if (!empty($neighbors)) {
--$n; --$n;
$next = $neighbors[\mt_rand(0, \count($neighbors) - 1)]; $next = $neighbors[mt_rand(0, \count($neighbors) - 1)];
$unvisited[$next[0] + 1][$next[1] + 1] = false; $unvisited[$next[0] + 1][$next[1] + 1] = false;
if ($next[0] === $pos[0]) { if ($next[0] === $pos[0]) {
@ -94,7 +94,7 @@ class MazeGenerator
$path[] = $next; $path[] = $next;
$pos = $next; $pos = $next;
} else { } else {
$pos = \array_pop($path); $pos = array_pop($path);
if ($pos === null) { if ($pos === null) {
break; // @codeCoverageIgnore break; // @codeCoverageIgnore
@ -111,7 +111,7 @@ class MazeGenerator
if ($j % 4 === 0) { if ($j % 4 === 0) {
$line[$j] = '+'; // 9 $line[$j] = '+'; // 9
} else { } else {
$line[$j] = $i > 0 && ($vertical[$i / 2 - 1][(int) \floor($j / 4)] ?? false) ? ' ' : '-'; // 9 $line[$j] = $i > 0 && ($vertical[$i / 2 - 1][(int) floor($j / 4)] ?? false) ? ' ' : '-'; // 9
} }
} }
} else { } else {

View File

@ -79,7 +79,7 @@ final class AStar implements PathFinderInterface
continue; continue;
} }
$ng = $node->getG() + (($neighbor->getX() - $node->getX() === 0 || $neighbor->getY() - $node->getY() === 0) ? 1 : \sqrt(2)); $ng = $node->getG() + (($neighbor->getX() - $node->getX() === 0 || $neighbor->getY() - $node->getY() === 0) ? 1 : sqrt(2));
if (!$neighbor->isOpened() || $ng < $neighbor->getG()) { if (!$neighbor->isOpened() || $ng < $neighbor->getG()) {
$neighbor->setG($ng); $neighbor->setG($ng);

View File

@ -183,9 +183,9 @@ final class JumpPointSearch implements PathFinderInterface
$py = $node->parent->getY(); $py = $node->parent->getY();
/** @var int $dx */ /** @var int $dx */
$dx = ($x - $px) / \max(\abs($x - $px), 1); $dx = ($x - $px) / max(abs($x - $px), 1);
/** @var int $dy */ /** @var int $dy */
$dy = ($y - $py) / \max(\abs($y - $py), 1); $dy = ($y - $py) / max(abs($y - $py), 1);
$neighbors = []; $neighbors = [];
if ($dx !== 0) { if ($dx !== 0) {
@ -241,9 +241,9 @@ final class JumpPointSearch implements PathFinderInterface
$py = $node->parent->getY(); $py = $node->parent->getY();
/** @var int $dx */ /** @var int $dx */
$dx = ($x - $px) / \max(\abs($x - $px), 1); $dx = ($x - $px) / max(abs($x - $px), 1);
/** @var int $dy */ /** @var int $dy */
$dy = ($y - $py) / \max(\abs($y - $py), 1); $dy = ($y - $py) / max(abs($y - $py), 1);
$neighbors = []; $neighbors = [];
if ($dx !== 0 && $dy !== 0) { if ($dx !== 0 && $dy !== 0) {
@ -319,9 +319,9 @@ final class JumpPointSearch implements PathFinderInterface
$py = $node->parent->getY(); $py = $node->parent->getY();
/** @var int $dx */ /** @var int $dx */
$dx = ($x - $px) / \max(\abs($x - $px), 1); $dx = ($x - $px) / max(abs($x - $px), 1);
/** @var int $dy */ /** @var int $dy */
$dy = ($y - $py) / \max(\abs($y - $py), 1); $dy = ($y - $py) / max(abs($y - $py), 1);
$neighbors = []; $neighbors = [];
if ($dx !== 0 && $dy !== 0) { if ($dx !== 0 && $dy !== 0) {
@ -393,9 +393,9 @@ final class JumpPointSearch implements PathFinderInterface
$py = $node->parent->getY(); $py = $node->parent->getY();
/** @var int $dx */ /** @var int $dx */
$dx = ($x - $px) / \max(\abs($x - $px), 1); $dx = ($x - $px) / max(abs($x - $px), 1);
/** @var int $dy */ /** @var int $dy */
$dy = ($y - $py) / \max(\abs($y - $py), 1); $dy = ($y - $py) / max(abs($y - $py), 1);
$neighbors = []; $neighbors = [];
if ($dx !== 0 && $dy !== 0) { if ($dx !== 0 && $dy !== 0) {

View File

@ -104,7 +104,7 @@ class Path
$dx = $this->nodes[$i - 1]->getX() - $this->nodes[$i]->getX(); $dx = $this->nodes[$i - 1]->getX() - $this->nodes[$i]->getX();
$dy = $this->nodes[$i - 1]->getY() - $this->nodes[$i]->getY(); $dy = $this->nodes[$i - 1]->getY() - $this->nodes[$i]->getY();
$dist += \sqrt($dx * $dx + $dy * $dy); $dist += sqrt($dx * $dx + $dy * $dy);
} }
return $dist; return $dist;
@ -149,7 +149,7 @@ class Path
$coord1 = $reverse[$i + 1]; $coord1 = $reverse[$i + 1];
$interpolated = $this->interpolate($coord0, $coord1); $interpolated = $this->interpolate($coord0, $coord1);
$expanded = \array_merge($expanded, $interpolated); $expanded = array_merge($expanded, $interpolated);
} }
$expanded[] = $reverse[$length - 1]; $expanded[] = $reverse[$length - 1];
@ -174,8 +174,8 @@ class Path
*/ */
private function interpolate(Node $node1, Node $node2) : array private function interpolate(Node $node1, Node $node2) : array
{ {
$dx = \abs($node2->getX() - $node1->getX()); $dx = abs($node2->getX() - $node1->getX());
$dy = \abs($node2->getY() - $node1->getY()); $dy = abs($node2->getY() - $node1->getY());
$sx = ($node1->getX() < $node2->getX()) ? 1 : -1; $sx = ($node1->getX() < $node2->getX()) ? 1 : -1;
$sy = ($node1->getY() < $node2->getY()) ? 1 : -1; $sy = ($node1->getY() < $node2->getY()) ? 1 : -1;

View File

@ -48,7 +48,7 @@ final class BitonicSort implements SortInterface
$first = self::sort(\array_slice($list, 0, (int) ($n / 2)), SortOrder::ASC); $first = self::sort(\array_slice($list, 0, (int) ($n / 2)), SortOrder::ASC);
$second = self::sort(\array_slice($list, (int) ($n / 2)), SortOrder::DESC); $second = self::sort(\array_slice($list, (int) ($n / 2)), SortOrder::DESC);
return self::merge(\array_merge($first, $second), $order); return self::merge(array_merge($first, $second), $order);
} }
/** /**
@ -81,6 +81,6 @@ final class BitonicSort implements SortInterface
$first = self::merge(\array_slice($list, 0, (int) ($n / 2)), $order); $first = self::merge(\array_slice($list, 0, (int) ($n / 2)), $order);
$second = self::merge(\array_slice($list, (int) ($n / 2)), $order); $second = self::merge(\array_slice($list, (int) ($n / 2)), $order);
return \array_merge($first, $second); return array_merge($first, $second);
} }
} }

View File

@ -50,7 +50,7 @@ final class BucketSort
} }
foreach ($list as $element) { foreach ($list as $element) {
$buckets[(int) \floor(($bucketCount - 1) * $element->getValue() / $M)][] = $element; $buckets[(int) floor(($bucketCount - 1) * $element->getValue() / $M)][] = $element;
} }
$sorted = []; $sorted = [];
@ -58,6 +58,6 @@ final class BucketSort
$sorted[] = $algo::sort($bucket, SortOrder::ASC); $sorted[] = $algo::sort($bucket, SortOrder::ASC);
} }
return $order === SortOrder::ASC ? \array_merge(...$sorted) : \array_reverse(\array_merge(...$sorted), false); return $order === SortOrder::ASC ? array_merge(...$sorted) : array_reverse(array_merge(...$sorted), false);
} }
} }

View File

@ -49,7 +49,7 @@ final class CombSort implements SortInterface
} }
while (!$sorted) { while (!$sorted) {
$gap = (int) \floor($gap / $shrink); $gap = (int) floor($gap / $shrink);
if ($gap < 2) { if ($gap < 2) {
$gap = 1; $gap = 1;

View File

@ -46,7 +46,7 @@ final class IntroSort implements SortInterface
return InsertionSort::sort($clone, $order); return InsertionSort::sort($clone, $order);
} }
if ($size > \log(\count($list)) * 2) { if ($size > log(\count($list)) * 2) {
return HeapSort::sort($clone, $order); return HeapSort::sort($clone, $order);
} }

View File

@ -45,7 +45,7 @@ final class TimSort implements SortInterface
for ($lo = 0; $lo < $n; $lo += self::BLOCKS) { for ($lo = 0; $lo < $n; $lo += self::BLOCKS) {
// insertion sort // insertion sort
$hi = \min($lo + 31, $n - 1); $hi = min($lo + 31, $n - 1);
for ($j = $lo + 1; $j <= $hi; ++$j) { for ($j = $lo + 1; $j <= $hi; ++$j) {
$temp = $list[$j]; $temp = $list[$j];
$c = $j - 1; $c = $j - 1;
@ -63,7 +63,7 @@ final class TimSort implements SortInterface
for ($lo = 0; $lo < $n; $lo += 2 * $size) { for ($lo = 0; $lo < $n; $lo += 2 * $size) {
// merge sort // merge sort
$mi = $lo + $size - 1; $mi = $lo + $size - 1;
$hi = \min($lo + 2 * $size - 1, $n - 1); $hi = min($lo + 2 * $size - 1, $n - 1);
$n1 = $mi - $lo + 1; $n1 = $mi - $lo + 1;
$n2 = $hi - $mi; $n2 = $hi - $mi;

View File

@ -35,21 +35,21 @@ use phpOMS\Router\RouterInterface;
* is restricted to write once in order to prevent manipulation * is restricted to write once in order to prevent manipulation
* and afterwards read only. * and afterwards read only.
* *
* @property string $appName * @property string $appName
* @property int $orgId * @property int $orgId
* @property \phpOMS\DataStorage\Database\DatabasePool $dbPool * @property \phpOMS\DataStorage\Database\DatabasePool $dbPool
* @property \phpOMS\Localization\L11nManager $l11nManager * @property \phpOMS\Localization\L11nManager $l11nManager
* @property \phpOMS\Localization\Localization $l11nServer * @property \phpOMS\Localization\Localization $l11nServer
* @property \phpOMS\Router\RouterInterface $router * @property \phpOMS\Router\RouterInterface $router
* @property \phpOMS\DataStorage\Session\SessionInterface $sessionManager * @property \phpOMS\DataStorage\Session\SessionInterface $sessionManager
* @property \phpOMS\DataStorage\Cookie\CookieJar $cookieJar * @property \phpOMS\DataStorage\Cookie\CookieJar $cookieJar
* @property \phpOMS\Module\ModuleManager $moduleManager * @property \phpOMS\Module\ModuleManager $moduleManager
* @property \phpOMS\Dispatcher\Dispatcher $dispatcher * @property \phpOMS\Dispatcher\Dispatcher $dispatcher
* @property \phpOMS\DataStorage\Cache\CachePool $cachePool * @property \phpOMS\DataStorage\Cache\CachePool $cachePool
* @property \phpOMS\Config\SettingsInterface $appSettings * @property \phpOMS\Config\SettingsInterface $appSettings
* @property \phpOMS\Event\EventManager $eventManager * @property \phpOMS\Event\EventManager $eventManager
* @property \phpOMS\Account\AccountManager $accountManager * @property \phpOMS\Account\AccountManager $accountManager
* @property \phpOMS\Log\FileLogger $logger * @property \phpOMS\Log\FileLogger $logger
* *
* @package phpOMS\Application * @package phpOMS\Application
* @license OMS License 1.0 * @license OMS License 1.0

View File

@ -80,14 +80,14 @@ final class ApplicationInfo
*/ */
public function load() : void public function load() : void
{ {
if (!\is_file($this->path)) { if (!is_file($this->path)) {
throw new PathException($this->path); throw new PathException($this->path);
} }
$contents = \file_get_contents($this->path); $contents = file_get_contents($this->path);
/** @var array{name:array{id:int, internal:string, external:string}, category:string, vision:string, requirements:array, creator:array{name:string, website:string}, description:string, directory:string, dependencies:array<string, string>} $info */ /** @var array{name:array{id:int, internal:string, external:string}, category:string, vision:string, requirements:array, creator:array{name:string, website:string}, description:string, directory:string, dependencies:array<string, string>} $info */
$info = \json_decode($contents === false ? '[]' : $contents, true); $info = json_decode($contents === false ? '[]' : $contents, true);
$this->info = $info === false ? [] : $info; $this->info = $info === false ? [] : $info;
} }
@ -100,11 +100,11 @@ final class ApplicationInfo
*/ */
public function update() : void public function update() : void
{ {
if (!\is_file($this->path)) { if (!is_file($this->path)) {
throw new PathException($this->path); throw new PathException($this->path);
} }
\file_put_contents($this->path, \json_encode($this->info, \JSON_PRETTY_PRINT)); file_put_contents($this->path, json_encode($this->info, \JSON_PRETTY_PRINT));
} }
/** /**
@ -120,7 +120,7 @@ final class ApplicationInfo
*/ */
public function set(string $path, mixed $data, string $delim = '/') : void public function set(string $path, mixed $data, string $delim = '/') : void
{ {
if (!\is_scalar($data) && !\is_array($data) && !($data instanceof \JsonSerializable)) { if (!is_scalar($data) && !\is_array($data) && !($data instanceof \JsonSerializable)) {
throw new \InvalidArgumentException('Type of $data "' . \gettype($data) . '" is not supported.'); throw new \InvalidArgumentException('Type of $data "' . \gettype($data) . '" is not supported.');
} }

View File

@ -70,7 +70,7 @@ final class ApplicationManager
*/ */
private function loadInfo(string $appPath) : ApplicationInfo private function loadInfo(string $appPath) : ApplicationInfo
{ {
$path = \realpath($appPath); $path = realpath($appPath);
if ($path === false) { if ($path === false) {
throw new PathException($appPath); throw new PathException($appPath);
} }
@ -94,15 +94,15 @@ final class ApplicationManager
*/ */
public function install(string $source, string $destination, string $theme = 'Default') : bool public function install(string $source, string $destination, string $theme = 'Default') : bool
{ {
$destination = \rtrim($destination, '\\/'); $destination = rtrim($destination, '\\/');
$source = \rtrim($source, '/\\'); $source = rtrim($source, '/\\');
if (!\is_dir(\dirname($destination))) { if (!is_dir(\dirname($destination))) {
Directory::create(\dirname($destination), 0755, true); Directory::create(\dirname($destination), 0755, true);
} }
if (!\is_dir($source) || ($path = \realpath($destination)) === false if (!is_dir($source) || ($path = realpath($destination)) === false
|| !\is_file($source . '/Admin/Installer.php') || !is_file($source . '/Admin/Installer.php')
) { ) {
return false; return false;
} }
@ -114,10 +114,10 @@ final class ApplicationManager
$this->installFiles($source, $destination); $this->installFiles($source, $destination);
$this->replacePlaceholder($destination); $this->replacePlaceholder($destination);
$classPath = \substr($path . '/Admin/Installer', (int) \strlen((string) \realpath(__DIR__ . '/../../'))); $classPath = substr($path . '/Admin/Installer', (int) \strlen((string) realpath(__DIR__ . '/../../')));
// @var class-string<InstallerAbstract> $class // @var class-string<InstallerAbstract> $class
$class = \str_replace('/', '\\', $classPath); $class = str_replace('/', '\\', $classPath);
$class::install($this->app->dbPool, $info, $this->app->appSettings); $class::install($this->app->dbPool, $info, $this->app->appSettings);
return true; return true;
@ -137,8 +137,8 @@ final class ApplicationManager
*/ */
public function uninstall(string $source) : bool public function uninstall(string $source) : bool
{ {
$source = \rtrim($source, '/\\'); $source = rtrim($source, '/\\');
if (($path = \realpath($source)) === false || !\is_file($source . '/Admin/Uninstaller.php')) { if (($path = realpath($source)) === false || !is_file($source . '/Admin/Uninstaller.php')) {
return false; return false;
} }
@ -146,10 +146,10 @@ final class ApplicationManager
$info = $this->loadInfo($source . '/info.json'); $info = $this->loadInfo($source . '/info.json');
$this->installed[$info->getInternalName()] = $info; $this->installed[$info->getInternalName()] = $info;
$classPath = \substr($path . '/Admin/Uninstaller', (int) \strlen((string) \realpath(__DIR__ . '/../../'))); $classPath = substr($path . '/Admin/Uninstaller', (int) \strlen((string) realpath(__DIR__ . '/../../')));
// @var class-string<UninstallerAbstract> $class // @var class-string<UninstallerAbstract> $class
$class = \str_replace('/', '\\', $classPath); $class = str_replace('/', '\\', $classPath);
$class::uninstall($this->app->dbPool, $info, $this->app->appSettings); $class::uninstall($this->app->dbPool, $info, $this->app->appSettings);
$this->uninstallFiles($source); $this->uninstallFiles($source);
@ -176,13 +176,13 @@ final class ApplicationManager
return; return;
} }
if (($path = \realpath($appPath)) === false) { if (($path = realpath($appPath)) === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
// @var class-string<InstallerAbstract> $class // @var class-string<InstallerAbstract> $class
$classPath = \substr($path . '/Admin/Installer', (int) \strlen((string) \realpath(__DIR__ . '/../../'))); $classPath = substr($path . '/Admin/Installer', (int) \strlen((string) realpath(__DIR__ . '/../../')));
$class = \str_replace('/', '\\', $classPath); $class = str_replace('/', '\\', $classPath);
/** @var $class InstallerAbstract */ /** @var $class InstallerAbstract */
$class::reInit($info); $class::reInit($info);
@ -233,14 +233,14 @@ final class ApplicationManager
public function getInstalledApplications(bool $useCache = true, string $basePath = __DIR__ . '/../../Web') : array public function getInstalledApplications(bool $useCache = true, string $basePath = __DIR__ . '/../../Web') : array
{ {
if (empty($this->installed) || !$useCache) { if (empty($this->installed) || !$useCache) {
$apps = \scandir($basePath); $apps = scandir($basePath);
if ($apps === false) { if ($apps === false) {
return $this->installed; // @codeCoverageIgnore return $this->installed; // @codeCoverageIgnore
} }
foreach ($apps as $app) { foreach ($apps as $app) {
if ($app === '.' || $app === '..' || !\is_file($basePath . '/' . $app . '/info.json')) { if ($app === '.' || $app === '..' || !is_file($basePath . '/' . $app . '/info.json')) {
continue; continue;
} }
@ -293,16 +293,16 @@ final class ApplicationManager
{ {
$files = Directory::list($destination, '*', true); $files = Directory::list($destination, '*', true);
foreach ($files as $file) { foreach ($files as $file) {
if (!\is_file($destination . '/' . $file)) { if (!is_file($destination . '/' . $file)) {
continue; continue;
} }
$content = \file_get_contents($destination . '/' . $file); $content = file_get_contents($destination . '/' . $file);
if ($content === false) { if ($content === false) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }
\file_put_contents($destination . '/' . $file, \str_replace('{APPNAME}', \basename($destination), $content)); file_put_contents($destination . '/' . $file, str_replace('{APPNAME}', basename($destination), $content));
} }
} }
} }

View File

@ -68,21 +68,21 @@ abstract class InstallerAbstract
*/ */
public static function installTheme(string $destination, string $theme) : void public static function installTheme(string $destination, string $theme) : void
{ {
if (!\is_dir($path = $destination . '/Themes/' . $theme)) { if (!is_dir($path = $destination . '/Themes/' . $theme)) {
return; return;
} }
$dirs = \scandir($path); $dirs = scandir($path);
if ($dirs === false) { if ($dirs === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
foreach ($dirs as $dir) { foreach ($dirs as $dir) {
if (!\is_dir($path. '/' . $dir) || $dir === '.' || $dir === '..') { if (!is_dir($path. '/' . $dir) || $dir === '.' || $dir === '..') {
continue; continue;
} }
if (\is_dir($destination . '/' . $dir)) { if (is_dir($destination . '/' . $dir)) {
Directory::delete($destination . '/' . $dir); Directory::delete($destination . '/' . $dir);
} }
@ -107,16 +107,16 @@ abstract class InstallerAbstract
protected static function createTables(DatabasePool $dbPool, ApplicationInfo $info) : void protected static function createTables(DatabasePool $dbPool, ApplicationInfo $info) : void
{ {
$path = static::PATH . '/Install/db.json'; $path = static::PATH . '/Install/db.json';
if (!\is_file($path)) { if (!is_file($path)) {
return; return;
} }
$content = \file_get_contents($path); $content = file_get_contents($path);
if ($content === false) { if ($content === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$definitions = \json_decode($content, true); $definitions = json_decode($content, true);
foreach ($definitions as $definition) { foreach ($definitions as $definition) {
SchemaBuilder::createFromSchema($definition, $dbPool->get('schema'))->execute(); SchemaBuilder::createFromSchema($definition, $dbPool->get('schema'))->execute();
} }
@ -134,14 +134,14 @@ abstract class InstallerAbstract
*/ */
protected static function activate(DatabasePool $dbPool, ApplicationInfo $info) : void protected static function activate(DatabasePool $dbPool, ApplicationInfo $info) : void
{ {
if (($path = \realpath(static::PATH)) === false) { if (($path = realpath(static::PATH)) === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$classPath = \substr($path . '/Status', (int) \strlen((string) \realpath(__DIR__ . '/../../'))); $classPath = substr($path . '/Status', (int) \strlen((string) realpath(__DIR__ . '/../../')));
// @var class-string<StatusAbstract> $class // @var class-string<StatusAbstract> $class
$class = \str_replace('/', '\\', $classPath); $class = str_replace('/', '\\', $classPath);
if (!Autoloader::exists($class)) { if (!Autoloader::exists($class)) {
throw new \UnexpectedValueException($class); // @codeCoverageIgnore throw new \UnexpectedValueException($class); // @codeCoverageIgnore
@ -161,14 +161,14 @@ abstract class InstallerAbstract
*/ */
public static function reInit(ApplicationInfo $info) : void public static function reInit(ApplicationInfo $info) : void
{ {
if (($path = \realpath(static::PATH)) === false) { if (($path = realpath(static::PATH)) === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$classPath = \substr($path . '/Status', (int) \strlen((string) \realpath(__DIR__ . '/../../'))); $classPath = substr($path . '/Status', (int) \strlen((string) realpath(__DIR__ . '/../../')));
// @var class-string<StatusAbstract> $class // @var class-string<StatusAbstract> $class
$class = \str_replace('/', '\\', $classPath); $class = str_replace('/', '\\', $classPath);
if (!Autoloader::exists($class)) { if (!Autoloader::exists($class)) {
throw new \UnexpectedValueException($class); // @codeCoverageIgnore throw new \UnexpectedValueException($class); // @codeCoverageIgnore

View File

@ -101,19 +101,19 @@ abstract class StatusAbstract
*/ */
protected static function installRoutesHooks(string $destRoutePath, string $srcRoutePath) : void protected static function installRoutesHooks(string $destRoutePath, string $srcRoutePath) : void
{ {
if (!\is_file($srcRoutePath)) { if (!is_file($srcRoutePath)) {
return; return;
} }
if (!\is_file($destRoutePath)) { if (!is_file($destRoutePath)) {
\file_put_contents($destRoutePath, '<?php return [];'); file_put_contents($destRoutePath, '<?php return [];');
} }
if (!\is_file($destRoutePath)) { if (!is_file($destRoutePath)) {
throw new PathException($destRoutePath); // @codeCoverageIgnore throw new PathException($destRoutePath); // @codeCoverageIgnore
} }
if (!\is_writable($destRoutePath)) { if (!is_writable($destRoutePath)) {
throw new PermissionException($destRoutePath); // @codeCoverageIgnore throw new PermissionException($destRoutePath); // @codeCoverageIgnore
} }
@ -122,9 +122,9 @@ abstract class StatusAbstract
/** @noinspection PhpIncludeInspection */ /** @noinspection PhpIncludeInspection */
$srcRoutes = include $srcRoutePath; $srcRoutes = include $srcRoutePath;
$appRoutes = \array_merge_recursive($appRoutes, $srcRoutes); $appRoutes = array_merge_recursive($appRoutes, $srcRoutes);
\file_put_contents($destRoutePath, '<?php return ' . ArrayParser::serializeArray($appRoutes) . ';', \LOCK_EX); file_put_contents($destRoutePath, '<?php return ' . ArrayParser::serializeArray($appRoutes) . ';', \LOCK_EX);
} }
/** /**
@ -139,7 +139,7 @@ abstract class StatusAbstract
*/ */
public static function clearRoutes() : void public static function clearRoutes() : void
{ {
\file_put_contents(static::PATH . '/../Routes.php', '<?php return [];', \LOCK_EX); file_put_contents(static::PATH . '/../Routes.php', '<?php return [];', \LOCK_EX);
} }
/** /**
@ -154,6 +154,6 @@ abstract class StatusAbstract
*/ */
public static function clearHooks() : void public static function clearHooks() : void
{ {
\file_put_contents(static::PATH . '/../Hooks.php', '<?php return [];', \LOCK_EX); file_put_contents(static::PATH . '/../Hooks.php', '<?php return [];', \LOCK_EX);
} }
} }

View File

@ -85,16 +85,16 @@ abstract class UninstallerAbstract
public static function dropTables(DatabasePool $dbPool, ApplicationInfo $info) : void public static function dropTables(DatabasePool $dbPool, ApplicationInfo $info) : void
{ {
$path = static::PATH . '/Install/db.json'; $path = static::PATH . '/Install/db.json';
if (!\is_file($path)) { if (!is_file($path)) {
return; return;
} }
$content = \file_get_contents($path); $content = file_get_contents($path);
if ($content === false) { if ($content === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$definitions = \json_decode($content, true); $definitions = json_decode($content, true);
$builder = new SchemaBuilder($dbPool->get('schema')); $builder = new SchemaBuilder($dbPool->get('schema'));
foreach ($definitions as $name => $definition) { foreach ($definitions as $name => $definition) {

View File

@ -14,7 +14,7 @@ declare(strict_types=1);
namespace phpOMS; namespace phpOMS;
\spl_autoload_register('\phpOMS\Autoloader::defaultAutoloader'); spl_autoload_register('\phpOMS\Autoloader::defaultAutoloader');
/** /**
* Autoloader class. * Autoloader class.
@ -72,11 +72,11 @@ final class Autoloader
public static function findPaths(string $class) : array public static function findPaths(string $class) : array
{ {
$found = []; $found = [];
$class = \ltrim($class, '\\'); $class = ltrim($class, '\\');
$class = \str_replace(['_', '\\'], '/', $class); $class = str_replace(['_', '\\'], '/', $class);
foreach (self::$paths as $path) { foreach (self::$paths as $path) {
if (\is_file($file = $path . $class . '.php')) { if (is_file($file = $path . $class . '.php')) {
$found[] = $file; $found[] = $file;
} }
} }
@ -99,11 +99,11 @@ final class Autoloader
*/ */
public static function defaultAutoloader(string $class) : void public static function defaultAutoloader(string $class) : void
{ {
$class = \ltrim($class, '\\'); $class = ltrim($class, '\\');
$class = \str_replace(['_', '\\'], '/', $class); $class = str_replace(['_', '\\'], '/', $class);
foreach (self::$paths as $path) { foreach (self::$paths as $path) {
if (\is_file($file = $path . $class . '.php')) { if (is_file($file = $path . $class . '.php')) {
include $file; include $file;
return; return;
@ -124,11 +124,11 @@ final class Autoloader
*/ */
public static function exists(string $class) : bool public static function exists(string $class) : bool
{ {
$class = \ltrim($class, '\\'); $class = ltrim($class, '\\');
$class = \str_replace(['_', '\\'], '/', $class); $class = str_replace(['_', '\\'], '/', $class);
foreach (self::$paths as $path) { foreach (self::$paths as $path) {
if (\is_file($path . $class . '.php')) { if (is_file($path . $class . '.php')) {
return true; return true;
} }
} }
@ -150,14 +150,14 @@ final class Autoloader
public static function invalidate(string $class) : bool public static function invalidate(string $class) : bool
{ {
if (!\extension_loaded('zend opcache') if (!\extension_loaded('zend opcache')
|| !\opcache_is_script_cached($class) || !opcache_is_script_cached($class)
|| \opcache_get_status() === false || opcache_get_status() === false
) { ) {
return false; return false;
} }
\opcache_invalidate($class); opcache_invalidate($class);
\opcache_compile_file($class); opcache_compile_file($class);
return true; return true;
} }

View File

@ -186,7 +186,7 @@ final class Depreciation
*/ */
public static function getGeometicProgressiveDepreciationRate(float $start, float $residual, int $duration) : float public static function getGeometicProgressiveDepreciationRate(float $start, float $residual, int $duration) : float
{ {
return (1 - \pow($residual / $start, 1 / $duration)); return (1 - pow($residual / $start, 1 / $duration));
} }
/** /**
@ -244,7 +244,7 @@ final class Depreciation
*/ */
public static function getGeometicDegressiveDepreciationRate(float $start, float $residual, int $duration) : float public static function getGeometicDegressiveDepreciationRate(float $start, float $residual, int $duration) : float
{ {
return (1 - \pow($residual / $start, 1 / $duration)); return (1 - pow($residual / $start, 1 / $duration));
} }
/** /**

View File

@ -56,7 +56,7 @@ final class FinanceFormulas
*/ */
public static function getAnnualPercentageYield(float $r, int $n) : float public static function getAnnualPercentageYield(float $r, int $n) : float
{ {
return \pow(1 + $r / $n, $n) - 1; return pow(1 + $r / $n, $n) - 1;
} }
/** /**
@ -73,7 +73,7 @@ final class FinanceFormulas
*/ */
public static function getStateAnnualInterestRateOfAPY(float $apy, int $n) : float public static function getStateAnnualInterestRateOfAPY(float $apy, int $n) : float
{ {
return (\pow($apy + 1, 1 / $n) - 1) * $n; return (pow($apy + 1, 1 / $n) - 1) * $n;
} }
/** /**
@ -89,7 +89,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueOfAnnuity(float $P, float $r, int $n) : float public static function getFutureValueOfAnnuity(float $P, float $r, int $n) : float
{ {
return $P * (\pow(1 + $r, $n) - 1) / $r; return $P * (pow(1 + $r, $n) - 1) / $r;
} }
/** /**
@ -105,7 +105,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfPeriodsOfFVA(float $fva, float $P, float $r) : int public static function getNumberOfPeriodsOfFVA(float $fva, float $P, float $r) : int
{ {
return (int) \round(\log($fva / $P * $r + 1) / \log(1 + $r)); return (int) round(log($fva / $P * $r + 1) / log(1 + $r));
} }
/** /**
@ -121,7 +121,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodicPaymentOfFVA(float $fva, float $r, int $n) : float public static function getPeriodicPaymentOfFVA(float $fva, float $r, int $n) : float
{ {
return $fva / ((\pow(1 + $r, $n) - 1) / $r); return $fva / ((pow(1 + $r, $n) - 1) / $r);
} }
/** /**
@ -137,7 +137,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueOfAnnuityConinuousCompounding(float $cf, float $r, int $t) : float public static function getFutureValueOfAnnuityConinuousCompounding(float $cf, float $r, int $t) : float
{ {
return $cf * (\exp($r * $t) - 1) / (\exp($r) - 1); return $cf * (exp($r * $t) - 1) / (exp($r) - 1);
} }
/** /**
@ -153,7 +153,7 @@ final class FinanceFormulas
*/ */
public static function getCashFlowOfFVACC(float $fvacc, float $r, int $t) : float public static function getCashFlowOfFVACC(float $fvacc, float $r, int $t) : float
{ {
return $fvacc / ((\exp($r * $t) - 1) / (\exp($r) - 1)); return $fvacc / ((exp($r * $t) - 1) / (exp($r) - 1));
} }
/** /**
@ -169,7 +169,7 @@ final class FinanceFormulas
*/ */
public static function getTimeOfFVACC(float $fvacc, float $cf, float $r) : int public static function getTimeOfFVACC(float $fvacc, float $cf, float $r) : int
{ {
return (int) \round(\log($fvacc / $cf * (\exp($r) - 1) + 1) / $r); return (int) round(log($fvacc / $cf * (exp($r) - 1) + 1) / $r);
} }
/** /**
@ -185,7 +185,7 @@ final class FinanceFormulas
*/ */
public static function getAnnuityPaymentPV(float $pv, float $r, int $n) : float public static function getAnnuityPaymentPV(float $pv, float $r, int $n) : float
{ {
return $r * $pv / (1 - \pow(1 + $r, -$n)); return $r * $pv / (1 - pow(1 + $r, -$n));
} }
/** /**
@ -201,7 +201,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfAPPV(float $p, float $pv, float $r) : int public static function getNumberOfAPPV(float $p, float $pv, float $r) : int
{ {
return (int) \round(-\log(-($r * $pv / $p - 1)) / \log(1 + $r)); return (int) round(-log(-($r * $pv / $p - 1)) / log(1 + $r));
} }
/** /**
@ -217,7 +217,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueOfAPPV(float $p, float $r, int $n) : float public static function getPresentValueOfAPPV(float $p, float $r, int $n) : float
{ {
return $p / $r * (1 - \pow(1 + $r, -$n)); return $p / $r * (1 - pow(1 + $r, -$n));
} }
/** /**
@ -233,7 +233,7 @@ final class FinanceFormulas
*/ */
public static function getAnnuityPaymentFV(float $fv, float $r, int $n) : float public static function getAnnuityPaymentFV(float $fv, float $r, int $n) : float
{ {
return $r * $fv / (\pow(1 + $r, $n) - 1); return $r * $fv / (pow(1 + $r, $n) - 1);
} }
/** /**
@ -249,7 +249,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfAPFV(float $p, float $fv, float $r) : int public static function getNumberOfAPFV(float $p, float $fv, float $r) : int
{ {
return (int) \round(\log($fv * $r / $p + 1) / \log(1 + $r)); return (int) round(log($fv * $r / $p + 1) / log(1 + $r));
} }
/** /**
@ -265,7 +265,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueOfAPFV(float $p, float $r, int $n) : float public static function getFutureValueOfAPFV(float $p, float $r, int $n) : float
{ {
return $p / $r * (\pow(1 + $r, $n) - 1); return $p / $r * (pow(1 + $r, $n) - 1);
} }
/** /**
@ -280,7 +280,7 @@ final class FinanceFormulas
*/ */
public static function getAnnutiyPaymentFactorPV(float $r, int $n) : float public static function getAnnutiyPaymentFactorPV(float $r, int $n) : float
{ {
return $r / (1 - \pow(1 + $r, -$n)); return $r / (1 - pow(1 + $r, -$n));
} }
/** /**
@ -295,7 +295,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfAPFPV(float $p, float $r) : int public static function getNumberOfAPFPV(float $p, float $r) : int
{ {
return (int) \round(-\log(-($r / $p - 1)) / \log(1 + $r)); return (int) round(-log(-($r / $p - 1)) / log(1 + $r));
} }
/** /**
@ -311,7 +311,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueOfAnnuity(float $P, float $r, int $n) : float public static function getPresentValueOfAnnuity(float $P, float $r, int $n) : float
{ {
return $P * (1 - \pow(1 + $r, -$n)) / $r; return $P * (1 - pow(1 + $r, -$n)) / $r;
} }
/** /**
@ -327,7 +327,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfPeriodsOfPVA(float $pva, float $P, float $r) : int public static function getNumberOfPeriodsOfPVA(float $pva, float $P, float $r) : int
{ {
return (int) \round(-\log(-($pva / $P * $r - 1)) / \log(1 + $r)); return (int) round(-log(-($pva / $P * $r - 1)) / log(1 + $r));
} }
/** /**
@ -343,7 +343,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodicPaymentOfPVA(float $pva, float $r, int $n) : float public static function getPeriodicPaymentOfPVA(float $pva, float $r, int $n) : float
{ {
return $pva / ((1 - \pow(1 + $r, -$n)) / $r); return $pva / ((1 - pow(1 + $r, -$n)) / $r);
} }
/** /**
@ -358,7 +358,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueAnnuityFactor(float $r, int $n) : float public static function getPresentValueAnnuityFactor(float $r, int $n) : float
{ {
return (1 - \pow(1 + $r, -$n)) / $r; return (1 - pow(1 + $r, -$n)) / $r;
} }
/** /**
@ -373,7 +373,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfPVAF(float $p, float $r) : int public static function getPeriodsOfPVAF(float $p, float $r) : int
{ {
return (int) \round(-\log(-($p * $r - 1)) / \log(1 + $r)); return (int) round(-log(-($p * $r - 1)) / log(1 + $r));
} }
/** /**
@ -389,7 +389,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueOfAnnuityDue(float $P, float $r, int $n) : float public static function getPresentValueOfAnnuityDue(float $P, float $r, int $n) : float
{ {
return $P + $P * ((1 - \pow(1 + $r, -($n - 1))) / $r); return $P + $P * ((1 - pow(1 + $r, -($n - 1))) / $r);
} }
/** /**
@ -407,7 +407,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodicPaymentOfPVAD(float $PV, float $r, int $n) : float public static function getPeriodicPaymentOfPVAD(float $PV, float $r, int $n) : float
{ {
return $PV * $r / (1 - \pow(1 + $r, -$n)) * 1 / (1 + $r); return $PV * $r / (1 - pow(1 + $r, -$n)) * 1 / (1 + $r);
} }
/** /**
@ -423,7 +423,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfPVAD(float $PV, float $P, float $r) : int public static function getPeriodsOfPVAD(float $PV, float $P, float $r) : int
{ {
return (int) \round(-(\log(-($PV - $P) / $P * $r + 1) / \log(1 + $r) - 1)); return (int) round(-(log(-($PV - $P) / $P * $r + 1) / log(1 + $r) - 1));
} }
/** /**
@ -439,7 +439,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueOfAnnuityDue(float $P, float $r, int $n) : float public static function getFutureValueOfAnnuityDue(float $P, float $r, int $n) : float
{ {
return (1 + $r) * $P * (\pow(1 + $r, $n) - 1) / $r; return (1 + $r) * $P * (pow(1 + $r, $n) - 1) / $r;
} }
/** /**
@ -455,7 +455,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodicPaymentOfFVAD(float $FV, float $r, int $n) : float public static function getPeriodicPaymentOfFVAD(float $FV, float $r, int $n) : float
{ {
return $FV / ((1 + $r) * ((\pow(1 + $r, $n) - 1) / $r)); return $FV / ((1 + $r) * ((pow(1 + $r, $n) - 1) / $r));
} }
/** /**
@ -471,7 +471,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfFVAD(float $FV, float $P, float $r) : int public static function getPeriodsOfFVAD(float $FV, float $P, float $r) : int
{ {
return (int) \round(\log($FV / (1 + $r) / $P * $r + 1) / \log(1 + $r)); return (int) round(log($FV / (1 + $r) / $P * $r + 1) / log(1 + $r));
} }
/** /**
@ -547,7 +547,7 @@ final class FinanceFormulas
*/ */
public static function getCompoundInterest(float $P, float $r, int $n) : float public static function getCompoundInterest(float $P, float $r, int $n) : float
{ {
return $P * (\pow(1 + $r, $n) - 1); return $P * (pow(1 + $r, $n) - 1);
} }
/** /**
@ -563,7 +563,7 @@ final class FinanceFormulas
*/ */
public static function getPrincipalOfCompundInterest(float $C, float $r, int $n) : float public static function getPrincipalOfCompundInterest(float $C, float $r, int $n) : float
{ {
return $C / (\pow(1 + $r, $n) - 1); return $C / (pow(1 + $r, $n) - 1);
} }
/** /**
@ -579,7 +579,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfCompundInterest(float $P, float $C, float $r) : float public static function getPeriodsOfCompundInterest(float $P, float $C, float $r) : float
{ {
return \log($C / $P + 1) / \log(1 + $r); return log($C / $P + 1) / log(1 + $r);
} }
/** /**
@ -595,7 +595,7 @@ final class FinanceFormulas
*/ */
public static function getContinuousCompounding(float $P, float $r, int $t) : float public static function getContinuousCompounding(float $P, float $r, int $t) : float
{ {
return $P * \exp($r * $t); return $P * exp($r * $t);
} }
/** /**
@ -611,7 +611,7 @@ final class FinanceFormulas
*/ */
public static function getPrincipalOfContinuousCompounding(float $C, float $r, int $t) : float public static function getPrincipalOfContinuousCompounding(float $C, float $r, int $t) : float
{ {
return $C / \exp($r * $t); return $C / exp($r * $t);
} }
/** /**
@ -627,7 +627,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfContinuousCompounding(float $P, float $C, float $r) : float public static function getPeriodsOfContinuousCompounding(float $P, float $C, float $r) : float
{ {
return \log($C / $P) / $r; return log($C / $P) / $r;
} }
/** /**
@ -643,7 +643,7 @@ final class FinanceFormulas
*/ */
public static function getRateOfContinuousCompounding(float $P, float $C, float $t) : float public static function getRateOfContinuousCompounding(float $P, float $C, float $t) : float
{ {
return \log($C / $P) / $t; return log($C / $P) / $t;
} }
/** /**
@ -748,7 +748,7 @@ final class FinanceFormulas
*/ */
public static function getDiscountedPaybackPeriod(float $CF, float $O1, float $r) : float public static function getDiscountedPaybackPeriod(float $CF, float $O1, float $r) : float
{ {
return \log(1 / (1 - $O1 * $r / $CF)) / \log(1 + $r); return log(1 / (1 - $O1 * $r / $CF)) / log(1 + $r);
} }
/** /**
@ -762,7 +762,7 @@ final class FinanceFormulas
*/ */
public static function getDoublingTime(float $r) : float public static function getDoublingTime(float $r) : float
{ {
return \log(2) / \log(1 + $r); return log(2) / log(1 + $r);
} }
/** /**
@ -776,7 +776,7 @@ final class FinanceFormulas
*/ */
public static function getDoublingRate(float $t) : float public static function getDoublingRate(float $t) : float
{ {
return \exp(\log(2) / $t) - 1; return exp(log(2) / $t) - 1;
} }
/** /**
@ -790,7 +790,7 @@ final class FinanceFormulas
*/ */
public static function getDoublingTimeContinuousCompounding(float $r) : float public static function getDoublingTimeContinuousCompounding(float $r) : float
{ {
return \log(2) / $r; return log(2) / $r;
} }
/** /**
@ -804,7 +804,7 @@ final class FinanceFormulas
*/ */
public static function getDoublingContinuousCompoundingRate(float $t) : float public static function getDoublingContinuousCompoundingRate(float $t) : float
{ {
return \log(2) / $t; return log(2) / $t;
} }
/** /**
@ -820,7 +820,7 @@ final class FinanceFormulas
*/ */
public static function getEquivalentAnnualAnnuity(float $NPV, float $r, int $n) : float public static function getEquivalentAnnualAnnuity(float $NPV, float $r, int $n) : float
{ {
return $r * $NPV / (1 - \pow(1 + $r, -$n)); return $r * $NPV / (1 - pow(1 + $r, -$n));
} }
/** /**
@ -836,7 +836,7 @@ final class FinanceFormulas
*/ */
public static function getPeriodsOfEAA(float $C, float $NPV, float $r) : int public static function getPeriodsOfEAA(float $C, float $NPV, float $r) : int
{ {
return (int) \round(-\log(1 - $r * $NPV / $C) / \log(1 + $r)); return (int) round(-log(1 - $r * $NPV / $C) / log(1 + $r));
} }
/** /**
@ -852,7 +852,7 @@ final class FinanceFormulas
*/ */
public static function getNetPresentValueOfEAA(float $C, float $r, int $n) : float public static function getNetPresentValueOfEAA(float $C, float $r, int $n) : float
{ {
return $C * (1 - \pow(1 + $r, -$n)) / $r; return $C * (1 - pow(1 + $r, -$n)) / $r;
} }
/** /**
@ -908,7 +908,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValue(float $C, float $r, int $n) : float public static function getFutureValue(float $C, float $r, int $n) : float
{ {
return $C * \pow(1 + $r, $n); return $C * pow(1 + $r, $n);
} }
/** /**
@ -924,7 +924,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueContinuousCompounding(float $PV, float $r, int $t) : float public static function getFutureValueContinuousCompounding(float $PV, float $r, int $t) : float
{ {
return $PV * \exp($r * $t); return $PV * exp($r * $t);
} }
/** /**
@ -944,7 +944,7 @@ final class FinanceFormulas
*/ */
public static function getFutureValueFactor(float $r, int $n) : float public static function getFutureValueFactor(float $r, int $n) : float
{ {
return \pow(1 + $r, $n); return pow(1 + $r, $n);
} }
/** /**
@ -977,7 +977,7 @@ final class FinanceFormulas
*/ */
public static function getGrowingAnnuityFV(float $P, float $r, float $g, int $n) : float public static function getGrowingAnnuityFV(float $P, float $r, float $g, int $n) : float
{ {
return $P * (\pow(1 + $r, $n) - \pow(1 + $g, $n)) / ($r - $g); return $P * (pow(1 + $r, $n) - pow(1 + $g, $n)) / ($r - $g);
} }
/** /**
@ -994,7 +994,7 @@ final class FinanceFormulas
*/ */
public static function getGrowingAnnuityPaymentPV(float $PV, float $r, float $g, int $n) : float public static function getGrowingAnnuityPaymentPV(float $PV, float $r, float $g, int $n) : float
{ {
return $PV * ($r - $g) / (1 - \pow((1 + $g) / (1 + $r), $n)); return $PV * ($r - $g) / (1 - pow((1 + $g) / (1 + $r), $n));
} }
/** /**
@ -1011,7 +1011,7 @@ final class FinanceFormulas
*/ */
public static function getGrowingAnnuityPaymentFV(float $FV, float $r, float $g, int $n) : float public static function getGrowingAnnuityPaymentFV(float $FV, float $r, float $g, int $n) : float
{ {
return $FV * ($r - $g) / (\pow(1 + $r, $n) - \pow(1 + $g, $n)); return $FV * ($r - $g) / (pow(1 + $r, $n) - pow(1 + $g, $n));
} }
/** /**
@ -1028,7 +1028,7 @@ final class FinanceFormulas
*/ */
public static function getGrowingAnnuityPV(float $P, float $r, float $g, int $n) : float public static function getGrowingAnnuityPV(float $P, float $r, float $g, int $n) : float
{ {
return $P / ($r - $g) * (1 - \pow((1 + $g) / (1 + $r), $n)); return $P / ($r - $g) * (1 - pow((1 + $g) / (1 + $r), $n));
} }
/** /**
@ -1100,7 +1100,7 @@ final class FinanceFormulas
$npv = -$C[0]; $npv = -$C[0];
for ($i = 1; $i < $count; ++$i) { for ($i = 1; $i < $count; ++$i) {
$npv += $C[$i] / \pow(1 + $r, $i); $npv += $C[$i] / pow(1 + $r, $i);
} }
return $npv; return $npv;
@ -1149,7 +1149,7 @@ final class FinanceFormulas
*/ */
public static function getNumberOfPeriodsPVFV(float $FV, float $PV, float $r) : float public static function getNumberOfPeriodsPVFV(float $FV, float $PV, float $r) : float
{ {
return \log($FV / $PV) / \log(1 + $r); return log($FV / $PV) / log(1 + $r);
} }
/** /**
@ -1195,7 +1195,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValue(float $C, float $r, int $n) : float public static function getPresentValue(float $C, float $r, int $n) : float
{ {
return $C / \pow(1 + $r, $n); return $C / pow(1 + $r, $n);
} }
/** /**
@ -1211,7 +1211,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueContinuousCompounding(float $C, float $r, int $t) : float public static function getPresentValueContinuousCompounding(float $C, float $r, int $t) : float
{ {
return $C / \exp($r * $t); return $C / exp($r * $t);
} }
/** /**
@ -1226,7 +1226,7 @@ final class FinanceFormulas
*/ */
public static function getPresentValueFactor(float $r, int $n) : float public static function getPresentValueFactor(float $r, int $n) : float
{ {
return 1 / \pow(1 + $r, $n); return 1 / pow(1 + $r, $n);
} }
/** /**
@ -1410,7 +1410,7 @@ final class FinanceFormulas
*/ */
public static function getSimpleInterestTime(float $I, float $P, float $r) : int public static function getSimpleInterestTime(float $I, float $P, float $r) : int
{ {
return (int) \round($I / ($P * $r)); return (int) round($I / ($P * $r));
} }
/** /**

View File

@ -51,7 +51,7 @@ final class Loan
*/ */
public static function getPaymentsOnBalloonLoan(float $PV, float $r, int $n, float $balloon = 0.0) : float public static function getPaymentsOnBalloonLoan(float $PV, float $r, int $n, float $balloon = 0.0) : float
{ {
return ($PV - $balloon / \pow(1 + $r, $n)) * $r / (1 - \pow(1 + $r, -$n)); return ($PV - $balloon / pow(1 + $r, $n)) * $r / (1 - pow(1 + $r, -$n));
} }
/** /**
@ -68,7 +68,7 @@ final class Loan
*/ */
public static function getBalloonBalanceOfLoan(float $PV, float $P, float $r, int $n) : float public static function getBalloonBalanceOfLoan(float $PV, float $P, float $r, int $n) : float
{ {
return $PV * \pow(1 + $r, $n) - $P * (\pow(1 + $r, $n) - 1) / $r; return $PV * pow(1 + $r, $n) - $P * (pow(1 + $r, $n) - 1) / $r;
} }
/** /**
@ -84,7 +84,7 @@ final class Loan
*/ */
public static function getLoanPayment(float $PV, float $r, int $n) : float public static function getLoanPayment(float $PV, float $r, int $n) : float
{ {
return $r * $PV / (1 - \pow(1 + $r, -$n)); return $r * $PV / (1 - pow(1 + $r, -$n));
} }
/** /**
@ -101,7 +101,7 @@ final class Loan
*/ */
public static function getRemainingBalanceLoan(float $PV, float $P, float $r, int $n) : float public static function getRemainingBalanceLoan(float $PV, float $P, float $r, int $n) : float
{ {
return $PV * \pow(1 + $r, $n) - $P * (\pow(1 + $r, $n) - 1) / $r; return $PV * pow(1 + $r, $n) - $P * (pow(1 + $r, $n) - 1) / $r;
} }
/** /**

View File

@ -50,7 +50,7 @@ final class Lorenzkurve
$i = 1; $i = 1;
$n = \count($data); $n = \count($data);
\sort($data); sort($data);
foreach ($data as $key => $value) { foreach ($data as $key => $value) {
$sum1 += $i * $value; $sum1 += $i * $value;

View File

@ -363,7 +363,7 @@ final class StockBonds
*/ */
public static function getZeroCouponBondValue(float $F, float $r, int $t) : float public static function getZeroCouponBondValue(float $F, float $r, int $t) : float
{ {
return $F / \pow(1 + $r, $t); return $F / pow(1 + $r, $t);
} }
/** /**
@ -379,6 +379,6 @@ final class StockBonds
*/ */
public static function getZeroCouponBondEffectiveYield(float $F, float $PV, int $n) : float public static function getZeroCouponBondEffectiveYield(float $F, float $PV, int $n) : float
{ {
return \pow($F / $PV, 1 / $n) - 1; return pow($F / $PV, 1 / $n) - 1;
} }
} }

View File

@ -85,7 +85,7 @@ final class ArticleCorrelationAffinity
// sort correlations // sort correlations
foreach ($possibleItems as $item) { foreach ($possibleItems as $item) {
\arsort($this->affinity[$item]); arsort($this->affinity[$item]);
} }
} }

View File

@ -57,10 +57,10 @@ final class CustomerValue
public static function getMRR(array $revenues, int $periods = 12, float $lowerCutoff = 0.1, float $upperCutoff = 0.0) : float public static function getMRR(array $revenues, int $periods = 12, float $lowerCutoff = 0.1, float $upperCutoff = 0.0) : float
{ {
if ($lowerCutoff === 0.0 && $upperCutoff === 0.0) { if ($lowerCutoff === 0.0 && $upperCutoff === 0.0) {
return \array_sum($revenues) / $periods; return array_sum($revenues) / $periods;
} }
\sort($revenues); sort($revenues);
$sum = 0.0; $sum = 0.0;
foreach ($revenues as $revenue) { foreach ($revenues as $revenue) {

View File

@ -71,7 +71,7 @@ final class Metrics
*/ */
public static function getCoefficientOfRetention(float $retentionRate, float $rc, int $t) : float public static function getCoefficientOfRetention(float $retentionRate, float $rc, int $t) : float
{ {
return 1 / $t * \log($rc - $retentionRate); return 1 / $t * log($rc - $retentionRate);
} }
/** /**
@ -87,7 +87,7 @@ final class Metrics
*/ */
public static function predictCustomerRetention(float $rc, float $r, int $t) : float public static function predictCustomerRetention(float $rc, float $r, int $t) : float
{ {
return $rc * (1 - \exp(-$r * $t)); return $rc * (1 - exp(-$r * $t));
} }
/** /**
@ -103,7 +103,7 @@ final class Metrics
*/ */
public static function customerActiveProbability(int $purchases, int $periods, int $lastPurchase) : float public static function customerActiveProbability(int $purchases, int $periods, int $lastPurchase) : float
{ {
return \pow($lastPurchase / $periods, $purchases); return pow($lastPurchase / $periods, $purchases);
} }
/** /**
@ -163,7 +163,7 @@ final class Metrics
for ($i = 1; $i < $count + 1; ++$i) { for ($i = 1; $i < $count + 1; ++$i) {
$newP = $newP->mult($P); $newP = $newP->mult($P);
$profit = $profit->add($newP->mult($G)->mult(1 / \pow(1 + $discountRate, $i))); $profit = $profit->add($newP->mult($G)->mult(1 / pow(1 + $discountRate, $i)));
} }
return $profit; return $profit;
@ -246,7 +246,7 @@ final class Metrics
$count = \count($purchaseProbability); $count = \count($purchaseProbability);
for ($i = 0; $i < $count; ++$i) { for ($i = 0; $i < $count; ++$i) {
$matrix[$i] = \array_fill(0, $count, 0); $matrix[$i] = array_fill(0, $count, 0);
$matrix[$i][0] = $purchaseProbability[$i]; $matrix[$i][0] = $purchaseProbability[$i];
$matrix[$i][ $matrix[$i][

View File

@ -51,7 +51,7 @@ final class Metrics
*/ */
public static function abcScore(int $a, int $b, int $c) : int public static function abcScore(int $a, int $b, int $c) : int
{ {
return (int) \sqrt($a * $a + $b * $b + $c * $c); return (int) sqrt($a * $a + $b * $b + $c * $c);
} }
/** /**

View File

@ -54,10 +54,10 @@ final class MarketShareEstimation
{ {
$sum = 0.0; $sum = 0.0;
for ($i = 0; $i < $participants; ++$i) { for ($i = 0; $i < $participants; ++$i) {
$sum += 1 / \pow($i + 1, $modifier); $sum += 1 / pow($i + 1, $modifier);
} }
return (int) \round(\pow(1 / ($marketShare * $sum), 1 / $modifier)); return (int) round(pow(1 / ($marketShare * $sum), 1 / $modifier));
} }
/** /**
@ -77,9 +77,9 @@ final class MarketShareEstimation
{ {
$sum = 0.0; $sum = 0.0;
for ($i = 0; $i < $participants; ++$i) { for ($i = 0; $i < $participants; ++$i) {
$sum += 1 / \pow($i + 1, $modifier); $sum += 1 / pow($i + 1, $modifier);
} }
return (1 / \pow($rank, $modifier)) / $sum; return (1 / pow($rank, $modifier)) / $sum;
} }
} }

View File

@ -96,7 +96,7 @@ final class CachePool implements DataStoragePoolInterface
} }
if (empty($key)) { if (empty($key)) {
return \reset($this->pool); return reset($this->pool);
} }
return $this->pool[$key]; return $this->pool[$key];

View File

@ -96,13 +96,13 @@ final class FileCache extends ConnectionAbstract
Directory::create($data[0], 0766, true); Directory::create($data[0], 0766, true);
} }
if (\realpath($data[0]) === false) { if (realpath($data[0]) === false) {
$this->status = CacheStatus::FAILURE; $this->status = CacheStatus::FAILURE;
throw new InvalidConnectionConfigException((string) \json_encode($this->dbdata)); throw new InvalidConnectionConfigException((string) json_encode($this->dbdata));
} }
$this->status = CacheStatus::OK; $this->status = CacheStatus::OK;
$this->con = \realpath($data[0]); $this->con = realpath($data[0]);
} }
/** /**
@ -114,7 +114,7 @@ final class FileCache extends ConnectionAbstract
return false; return false;
} }
\array_map('unlink', \glob($this->con . '/*')); array_map('unlink', glob($this->con . '/*'));
return true; return true;
} }
@ -155,14 +155,14 @@ final class FileCache extends ConnectionAbstract
$path = Directory::sanitize((string) $key, self::SANITIZE); $path = Directory::sanitize((string) $key, self::SANITIZE);
$fp = \fopen($this->con . '/' . \trim($path, '/') . '.cache', 'w+'); $fp = fopen($this->con . '/' . trim($path, '/') . '.cache', 'w+');
if (\flock($fp, \LOCK_EX)) { if (flock($fp, \LOCK_EX)) {
\ftruncate($fp, 0); ftruncate($fp, 0);
\fwrite($fp, $this->build($value, $expire)); fwrite($fp, $this->build($value, $expire));
\fflush($fp); fflush($fp);
\flock($fp, \LOCK_UN); flock($fp, \LOCK_UN);
} }
\fclose($fp); fclose($fp);
} }
/** /**
@ -177,14 +177,14 @@ final class FileCache extends ConnectionAbstract
$path = $this->getPath($key); $path = $this->getPath($key);
if (!File::exists($path)) { if (!File::exists($path)) {
$fp = \fopen($path, 'w+'); $fp = fopen($path, 'w+');
if (\flock($fp, \LOCK_EX)) { if (flock($fp, \LOCK_EX)) {
\ftruncate($fp, 0); ftruncate($fp, 0);
\fwrite($fp, $this->build($value, $expire)); fwrite($fp, $this->build($value, $expire));
\fflush($fp); fflush($fp);
\flock($fp, \LOCK_UN); flock($fp, \LOCK_UN);
} }
\fclose($fp); fclose($fp);
return true; return true;
} }
@ -227,13 +227,13 @@ final class FileCache extends ConnectionAbstract
if ($type === CacheValueType::_INT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) { if ($type === CacheValueType::_INT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) {
return (string) $value; return (string) $value;
} elseif ($type === CacheValueType::_FLOAT) { } elseif ($type === CacheValueType::_FLOAT) {
return \rtrim(\rtrim(\number_format($value, 5, '.', ''), '0'), '.'); return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
} elseif ($type === CacheValueType::_ARRAY) { } elseif ($type === CacheValueType::_ARRAY) {
return (string) \json_encode($value); return (string) json_encode($value);
} elseif ($type === CacheValueType::_SERIALIZABLE) { } elseif ($type === CacheValueType::_SERIALIZABLE) {
return \get_class($value) . self::DELIM . $value->serialize(); return \get_class($value) . self::DELIM . $value->serialize();
} elseif ($type === CacheValueType::_JSONSERIALIZABLE) { } elseif ($type === CacheValueType::_JSONSERIALIZABLE) {
return \get_class($value) . self::DELIM . ((string) \json_encode($value->jsonSerialize())); return \get_class($value) . self::DELIM . ((string) json_encode($value->jsonSerialize()));
} elseif ($type === CacheValueType::_NULL) { } elseif ($type === CacheValueType::_NULL) {
return ''; return '';
} }
@ -252,10 +252,10 @@ final class FileCache extends ConnectionAbstract
*/ */
private function getExpire(string $raw) : int private function getExpire(string $raw) : int
{ {
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
return (int) \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); return (int) substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
} }
/** /**
@ -273,26 +273,26 @@ final class FileCache extends ConnectionAbstract
} }
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
if ($expire >= 0 && $created + $expire < $now) { if ($expire >= 0 && $created + $expire < $now) {
return null; return null;
} }
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
} }
$type = (int) $raw[0]; $type = (int) $raw[0];
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
if ($expireStart < 0 || $expireEnd < 0) { if ($expireStart < 0 || $expireEnd < 0) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
} }
$cacheExpire = \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) { if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) {
@ -319,22 +319,22 @@ final class FileCache extends ConnectionAbstract
{ {
switch ($type) { switch ($type) {
case CacheValueType::_INT: case CacheValueType::_INT:
return (int) \substr($raw, $expireEnd + 1); return (int) substr($raw, $expireEnd + 1);
case CacheValueType::_FLOAT: case CacheValueType::_FLOAT:
return (float) \substr($raw, $expireEnd + 1); return (float) substr($raw, $expireEnd + 1);
case CacheValueType::_BOOL: case CacheValueType::_BOOL:
return (bool) \substr($raw, $expireEnd + 1); return (bool) substr($raw, $expireEnd + 1);
case CacheValueType::_STRING: case CacheValueType::_STRING:
return \substr($raw, $expireEnd + 1); return substr($raw, $expireEnd + 1);
case CacheValueType::_ARRAY: case CacheValueType::_ARRAY:
$array = \substr($raw, $expireEnd + 1); $array = substr($raw, $expireEnd + 1);
return \json_decode($array === false ? '[]' : $array, true); return json_decode($array === false ? '[]' : $array, true);
case CacheValueType::_NULL: case CacheValueType::_NULL:
return null; return null;
case CacheValueType::_JSONSERIALIZABLE: case CacheValueType::_JSONSERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $expireEnd); $namespaceStart = (int) strpos($raw, self::DELIM, $expireEnd);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
@ -342,16 +342,16 @@ final class FileCache extends ConnectionAbstract
return new $namespace(); return new $namespace();
case CacheValueType::_SERIALIZABLE: case CacheValueType::_SERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $expireEnd); $namespaceStart = (int) strpos($raw, self::DELIM, $expireEnd);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
} }
$obj = new $namespace(); $obj = new $namespace();
$obj->unserialize(\substr($raw, $namespaceEnd + 1)); $obj->unserialize(substr($raw, $namespaceEnd + 1));
return $obj; return $obj;
default: default:
@ -381,8 +381,8 @@ final class FileCache extends ConnectionAbstract
if ($expire >= 0) { if ($expire >= 0) {
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
@ -392,7 +392,7 @@ final class FileCache extends ConnectionAbstract
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
if (($cacheExpire >= 0 && $created + $cacheExpire < $now) if (($cacheExpire >= 0 && $created + $cacheExpire < $now)
|| ($cacheExpire >= 0 && \abs($now - $created) > $expire) || ($cacheExpire >= 0 && abs($now - $created) > $expire)
) { ) {
File::delete($path); File::delete($path);
@ -418,26 +418,26 @@ final class FileCache extends ConnectionAbstract
} }
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
if ($expire >= 0 && $created + $expire < $now) { if ($expire >= 0 && $created + $expire < $now) {
return false; return false;
} }
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$type = (int) $raw[0]; $type = (int) $raw[0];
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
if ($expireStart < 0 || $expireEnd < 0) { if ($expireStart < 0 || $expireEnd < 0) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$cacheExpire = \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) { if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) {
@ -460,22 +460,22 @@ final class FileCache extends ConnectionAbstract
} }
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$type = (int) $raw[0]; $type = (int) $raw[0];
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
if ($expireStart < 0 || $expireEnd < 0) { if ($expireStart < 0 || $expireEnd < 0) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$cacheExpire = \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
$val = $this->reverseValue($type, $raw, $expireEnd); $val = $this->reverseValue($type, $raw, $expireEnd);
@ -495,22 +495,22 @@ final class FileCache extends ConnectionAbstract
} }
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$type = (int) $raw[0]; $type = (int) $raw[0];
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
if ($expireStart < 0 || $expireEnd < 0) { if ($expireStart < 0 || $expireEnd < 0) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
$cacheExpire = \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
$val = $this->reverseValue($type, $raw, $expireEnd); $val = $this->reverseValue($type, $raw, $expireEnd);
@ -544,26 +544,26 @@ final class FileCache extends ConnectionAbstract
foreach ($files as $path) { foreach ($files as $path) {
$path = $this->con . '/' . $path; $path = $this->con . '/' . $path;
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
if ($expire >= 0 && $created + $expire < $now) { if ($expire >= 0 && $created + $expire < $now) {
continue; continue;
} }
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }
$type = (int) $raw[0]; $type = (int) $raw[0];
$expireStart = (int) \strpos($raw, self::DELIM); $expireStart = (int) strpos($raw, self::DELIM);
$expireEnd = (int) \strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = (int) strpos($raw, self::DELIM, $expireStart + 1);
if ($expireStart < 0 || $expireEnd < 0) { if ($expireStart < 0 || $expireEnd < 0) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }
$cacheExpire = \substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) { if ($cacheExpire >= 0 && $created + $cacheExpire + ($expire > 0 ? $expire : 0) < $now) {
@ -600,8 +600,8 @@ final class FileCache extends ConnectionAbstract
if ($expire >= 0) { if ($expire >= 0) {
$created = File::created($path)->getTimestamp(); $created = File::created($path)->getTimestamp();
$now = \time(); $now = time();
$raw = \file_get_contents($path); $raw = file_get_contents($path);
if ($raw === false) { if ($raw === false) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
@ -611,7 +611,7 @@ final class FileCache extends ConnectionAbstract
$cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire; $cacheExpire = ($cacheExpire === -1) ? $created : (int) $cacheExpire;
if (($cacheExpire >= 0 && $created + $cacheExpire < $now) if (($cacheExpire >= 0 && $created + $cacheExpire < $now)
|| ($cacheExpire >= 0 && \abs($now - $created) > $expire) || ($cacheExpire >= 0 && abs($now - $created) > $expire)
) { ) {
File::delete($path); File::delete($path);
@ -645,7 +645,7 @@ final class FileCache extends ConnectionAbstract
} }
$dir = new Directory($this->con); $dir = new Directory($this->con);
$now = \time(); $now = time();
foreach ($dir as $file) { foreach ($dir as $file) {
if ($file instanceof File) { if ($file instanceof File) {
@ -673,14 +673,14 @@ final class FileCache extends ConnectionAbstract
$path = $this->getPath($key); $path = $this->getPath($key);
if (File::exists($path)) { if (File::exists($path)) {
$fp = \fopen($path, 'w+'); $fp = fopen($path, 'w+');
if (\flock($fp, \LOCK_EX)) { if (flock($fp, \LOCK_EX)) {
\ftruncate($fp, 0); ftruncate($fp, 0);
\fwrite($fp, $this->build($value, $expire)); fwrite($fp, $this->build($value, $expire));
\fflush($fp); fflush($fp);
\flock($fp, \LOCK_UN); flock($fp, \LOCK_UN);
} }
\fclose($fp); fclose($fp);
return true; return true;
} }
@ -700,6 +700,6 @@ final class FileCache extends ConnectionAbstract
private function getPath(int | string $key) : string private function getPath(int | string $key) : string
{ {
$path = Directory::sanitize((string) $key, self::SANITIZE); $path = Directory::sanitize((string) $key, self::SANITIZE);
return $this->con . '/' . \trim($path, '/') . '.cache'; return $this->con . '/' . trim($path, '/') . '.cache';
} }
} }

View File

@ -77,7 +77,7 @@ final class MemCached extends ConnectionAbstract
if (!isset($this->dbdata['host'], $this->dbdata['port'])) { if (!isset($this->dbdata['host'], $this->dbdata['port'])) {
$this->status = CacheStatus::FAILURE; $this->status = CacheStatus::FAILURE;
throw new InvalidConnectionConfigException((string) \json_encode($this->dbdata)); throw new InvalidConnectionConfigException((string) json_encode($this->dbdata));
} }
$this->con->addServer($this->dbdata['host'], $this->dbdata['port']); $this->con->addServer($this->dbdata['host'], $this->dbdata['port']);
@ -94,11 +94,11 @@ final class MemCached extends ConnectionAbstract
return; return;
} }
if (!(\is_scalar($value) || $value === null || \is_array($value) || $value instanceof \JsonSerializable || $value instanceof \Serializable)) { if (!(is_scalar($value) || $value === null || \is_array($value) || $value instanceof \JsonSerializable || $value instanceof \Serializable)) {
throw new \InvalidArgumentException(); throw new \InvalidArgumentException();
} }
$this->con->set((string) $key, $value, \max($expire, 0)); $this->con->set((string) $key, $value, max($expire, 0));
} }
/** /**
@ -110,11 +110,11 @@ final class MemCached extends ConnectionAbstract
return false; return false;
} }
if (!(\is_scalar($value) || $value === null || \is_array($value) || $value instanceof \JsonSerializable || $value instanceof \Serializable)) { if (!(is_scalar($value) || $value === null || \is_array($value) || $value instanceof \JsonSerializable || $value instanceof \Serializable)) {
throw new \InvalidArgumentException(); throw new \InvalidArgumentException();
} }
return $this->con->add((string) $key, $value, \max($expire, 0)); return $this->con->add((string) $key, $value, max($expire, 0));
} }
/** /**
@ -202,11 +202,11 @@ final class MemCached extends ConnectionAbstract
$values = []; $values = [];
foreach ($keys as $key) { foreach ($keys as $key) {
if (\preg_match('/' . $pattern . '/', $key) === 1) { if (preg_match('/' . $pattern . '/', $key) === 1) {
$result = $this->con->get($key); $result = $this->con->get($key);
if (\is_string($result)) { if (\is_string($result)) {
$type = (int) $result[0]; $type = (int) $result[0];
$start = (int) \strpos($result, self::DELIM); $start = (int) strpos($result, self::DELIM);
$result = $this->reverseValue($type, $result, $start); $result = $this->reverseValue($type, $result, $start);
} }
@ -232,22 +232,22 @@ final class MemCached extends ConnectionAbstract
{ {
switch ($type) { switch ($type) {
case CacheValueType::_INT: case CacheValueType::_INT:
return (int) \substr($raw, $expireEnd + 1); return (int) substr($raw, $expireEnd + 1);
case CacheValueType::_FLOAT: case CacheValueType::_FLOAT:
return (float) \substr($raw, $expireEnd + 1); return (float) substr($raw, $expireEnd + 1);
case CacheValueType::_BOOL: case CacheValueType::_BOOL:
return (bool) \substr($raw, $expireEnd + 1); return (bool) substr($raw, $expireEnd + 1);
case CacheValueType::_STRING: case CacheValueType::_STRING:
return \substr($raw, $expireEnd + 1); return substr($raw, $expireEnd + 1);
case CacheValueType::_ARRAY: case CacheValueType::_ARRAY:
$array = \substr($raw, $expireEnd + 1); $array = substr($raw, $expireEnd + 1);
return \json_decode($array === false ? '[]' : $array, true); return json_decode($array === false ? '[]' : $array, true);
case CacheValueType::_NULL: case CacheValueType::_NULL:
return null; return null;
case CacheValueType::_JSONSERIALIZABLE: case CacheValueType::_JSONSERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $expireEnd); $namespaceStart = (int) strpos($raw, self::DELIM, $expireEnd);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
@ -255,16 +255,16 @@ final class MemCached extends ConnectionAbstract
return new $namespace(); return new $namespace();
case CacheValueType::_SERIALIZABLE: case CacheValueType::_SERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $expireEnd); $namespaceStart = (int) strpos($raw, self::DELIM, $expireEnd);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; // @codeCoverageIgnore return null; // @codeCoverageIgnore
} }
$obj = new $namespace(); $obj = new $namespace();
$obj->unserialize(\substr($raw, $namespaceEnd + 1)); $obj->unserialize(substr($raw, $namespaceEnd + 1));
return $obj; return $obj;
default: default:
@ -283,7 +283,7 @@ final class MemCached extends ConnectionAbstract
$keys = $this->con->getAllKeys(); $keys = $this->con->getAllKeys();
foreach ($keys as $key) { foreach ($keys as $key) {
if (\preg_match('/' . $pattern . '/', $key) === 1) { if (preg_match('/' . $pattern . '/', $key) === 1) {
$this->con->delete($key); $this->con->delete($key);
} }
} }
@ -334,7 +334,7 @@ final class MemCached extends ConnectionAbstract
return false; return false;
} }
return $this->con->replace((string) $key, $value, \max($expire, 0)); return $this->con->replace((string) $key, $value, max($expire, 0));
} }
/** /**
@ -347,7 +347,7 @@ final class MemCached extends ConnectionAbstract
} }
$stat = $this->con->getStats(); $stat = $this->con->getStats();
$temp = \reset($stat); $temp = reset($stat);
$stats = []; $stats = [];
$stats['status'] = $this->status; $stats['status'] = $this->status;

View File

@ -70,7 +70,7 @@ final class RedisCache extends ConnectionAbstract
if (!isset($this->dbdata['host'], $this->dbdata['port'], $this->dbdata['db'])) { if (!isset($this->dbdata['host'], $this->dbdata['port'], $this->dbdata['db'])) {
$this->status = CacheStatus::FAILURE; $this->status = CacheStatus::FAILURE;
throw new InvalidConnectionConfigException((string) \json_encode($this->dbdata)); throw new InvalidConnectionConfigException((string) json_encode($this->dbdata));
} }
$this->con->connect($this->dbdata['host'], $this->dbdata['port']); $this->con->connect($this->dbdata['host'], $this->dbdata['port']);
@ -148,7 +148,7 @@ final class RedisCache extends ConnectionAbstract
if (\is_string($result)) { if (\is_string($result)) {
$type = (int) $result[0]; $type = (int) $result[0];
$start = (int) \strpos($result, self::DELIM); $start = (int) strpos($result, self::DELIM);
$result = $this->reverseValue($type, $result, $start); $result = $this->reverseValue($type, $result, $start);
} }
@ -224,11 +224,11 @@ final class RedisCache extends ConnectionAbstract
$values = []; $values = [];
foreach ($keys as $key) { foreach ($keys as $key) {
if (\preg_match('/' . $pattern . '/', $key) === 1) { if (preg_match('/' . $pattern . '/', $key) === 1) {
$result = $this->con->get((string) $key); $result = $this->con->get((string) $key);
if (\is_string($result)) { if (\is_string($result)) {
$type = (int) $result[0]; $type = (int) $result[0];
$start = (int) \strpos($result, self::DELIM); $start = (int) strpos($result, self::DELIM);
$result = $this->reverseValue($type, $result, $start); $result = $this->reverseValue($type, $result, $start);
} }
@ -250,7 +250,7 @@ final class RedisCache extends ConnectionAbstract
$keys = $this->con->keys('*'); $keys = $this->con->keys('*');
foreach ($keys as $key) { foreach ($keys as $key) {
if (\preg_match('/' . $pattern . '/', $key) === 1) { if (preg_match('/' . $pattern . '/', $key) === 1) {
$this->con->del($key); $this->con->del($key);
} }
} }
@ -381,13 +381,13 @@ final class RedisCache extends ConnectionAbstract
if ($type === CacheValueType::_INT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) { if ($type === CacheValueType::_INT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) {
return (string) $value; return (string) $value;
} elseif ($type === CacheValueType::_FLOAT) { } elseif ($type === CacheValueType::_FLOAT) {
return \rtrim(\rtrim(\number_format($value, 5, '.', ''), '0'), '.'); return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
} elseif ($type === CacheValueType::_ARRAY) { } elseif ($type === CacheValueType::_ARRAY) {
return (string) \json_encode($value); return (string) json_encode($value);
} elseif ($type === CacheValueType::_SERIALIZABLE) { } elseif ($type === CacheValueType::_SERIALIZABLE) {
return \get_class($value) . self::DELIM . $value->serialize(); return \get_class($value) . self::DELIM . $value->serialize();
} elseif ($type === CacheValueType::_JSONSERIALIZABLE) { } elseif ($type === CacheValueType::_JSONSERIALIZABLE) {
return \get_class($value) . self::DELIM . ((string) \json_encode($value->jsonSerialize())); return \get_class($value) . self::DELIM . ((string) json_encode($value->jsonSerialize()));
} elseif ($type === CacheValueType::_NULL) { } elseif ($type === CacheValueType::_NULL) {
return ''; return '';
} }
@ -410,22 +410,22 @@ final class RedisCache extends ConnectionAbstract
{ {
switch ($type) { switch ($type) {
case CacheValueType::_INT: case CacheValueType::_INT:
return (int) \substr($raw, $start + 1); return (int) substr($raw, $start + 1);
case CacheValueType::_FLOAT: case CacheValueType::_FLOAT:
return (float) \substr($raw, $start + 1); return (float) substr($raw, $start + 1);
case CacheValueType::_BOOL: case CacheValueType::_BOOL:
return (bool) \substr($raw, $start + 1); return (bool) substr($raw, $start + 1);
case CacheValueType::_STRING: case CacheValueType::_STRING:
return \substr($raw, $start + 1); return substr($raw, $start + 1);
case CacheValueType::_ARRAY: case CacheValueType::_ARRAY:
$array = \substr($raw, $start + 1); $array = substr($raw, $start + 1);
return \json_decode($array === false ? '[]' : $array, true); return json_decode($array === false ? '[]' : $array, true);
case CacheValueType::_NULL: case CacheValueType::_NULL:
return null; return null;
case CacheValueType::_JSONSERIALIZABLE: case CacheValueType::_JSONSERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $start); $namespaceStart = (int) strpos($raw, self::DELIM, $start);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; return null;
@ -433,16 +433,16 @@ final class RedisCache extends ConnectionAbstract
return new $namespace(); return new $namespace();
case CacheValueType::_SERIALIZABLE: case CacheValueType::_SERIALIZABLE:
$namespaceStart = (int) \strpos($raw, self::DELIM, $start); $namespaceStart = (int) strpos($raw, self::DELIM, $start);
$namespaceEnd = (int) \strpos($raw, self::DELIM, $namespaceStart + 1); $namespaceEnd = (int) strpos($raw, self::DELIM, $namespaceStart + 1);
$namespace = \substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1); $namespace = substr($raw, $namespaceStart + 1, $namespaceEnd - $namespaceStart - 1);
if ($namespace === false) { if ($namespace === false) {
return null; return null;
} }
$obj = new $namespace(); $obj = new $namespace();
$obj->unserialize(\substr($raw, $namespaceEnd + 1)); $obj->unserialize(substr($raw, $namespaceEnd + 1));
return $obj; return $obj;
default: default:

View File

@ -145,8 +145,8 @@ final class CookieJar
} }
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
if (!\headers_sent()) { if (!headers_sent()) {
\setcookie($id, '', \time() - 3600); setcookie($id, '', time() - 3600);
return true; return true;
} }
@ -195,7 +195,7 @@ final class CookieJar
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
foreach ($this->cookies as $key => $cookie) { foreach ($this->cookies as $key => $cookie) {
\setcookie($key, $cookie['value'], [ setcookie($key, $cookie['value'], [
'expires' => $cookie['expires'], 'expires' => $cookie['expires'],
'path' => $cookie['path'], 'path' => $cookie['path'],
'domain' => $cookie['domain'], 'domain' => $cookie['domain'],

View File

@ -516,7 +516,7 @@ class DataMapperAbstract implements DataMapperInterface
$objId = $id; $objId = $id;
} else { } else {
$objId = self::createModelArray($obj); $objId = self::createModelArray($obj);
\settype($objId, static::$columns[static::$primaryField]['type']); settype($objId, static::$columns[static::$primaryField]['type']);
$obj[static::$columns[static::$primaryField]['internal']] = $objId; $obj[static::$columns[static::$primaryField]['internal']] = $objId;
} }
@ -545,7 +545,7 @@ class DataMapperAbstract implements DataMapperInterface
$query->into(static::$table); $query->into(static::$table);
foreach (static::$columns as $column) { foreach (static::$columns as $column) {
$propertyName = \stripos($column['internal'], '/') !== false ? \explode('/', $column['internal'])[0] : $column['internal']; $propertyName = stripos($column['internal'], '/') !== false ? explode('/', $column['internal'])[0] : $column['internal'];
if (isset(static::$hasMany[$propertyName])) { if (isset(static::$hasMany[$propertyName])) {
continue; continue;
} }
@ -570,8 +570,8 @@ class DataMapperAbstract implements DataMapperInterface
$query->insert($column['name'])->value($value); $query->insert($column['name'])->value($value);
} elseif ($column['name'] !== static::$primaryField || !empty($tValue)) { } elseif ($column['name'] !== static::$primaryField || !empty($tValue)) {
if (\stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = \substr($column['internal'], \stripos($column['internal'], '/') + 1); $path = substr($column['internal'], stripos($column['internal'], '/') + 1);
$tValue = ArrayUtils::getArray($path, $tValue, '/'); $tValue = ArrayUtils::getArray($path, $tValue, '/');
} }
@ -598,13 +598,13 @@ class DataMapperAbstract implements DataMapperInterface
$sth = self::$db->con->prepare($query->toSql()); $sth = self::$db->con->prepare($query->toSql());
$sth->execute(); $sth->execute();
} catch (\Throwable $t) { } catch (\Throwable $t) {
\var_dump($t->getMessage()); var_dump($t->getMessage());
\var_dump($a = $query->toSql()); var_dump($a = $query->toSql());
return -1; return -1;
} }
$objId = empty($id = self::getObjectId($obj, $refClass)) ? self::$db->con->lastInsertId() : $id; $objId = empty($id = self::getObjectId($obj, $refClass)) ? self::$db->con->lastInsertId() : $id;
\settype($objId, static::$columns[static::$primaryField]['type']); settype($objId, static::$columns[static::$primaryField]['type']);
return $objId; return $objId;
} }
@ -629,8 +629,8 @@ class DataMapperAbstract implements DataMapperInterface
} }
$path = $column['internal']; $path = $column['internal'];
if (\stripos($column['internal'], '/') === 0) { if (stripos($column['internal'], '/') === 0) {
$path = \ltrim($column['internal'], '/'); $path = ltrim($column['internal'], '/');
} }
$property = ArrayUtils::getArray($column['internal'], $obj, '/'); $property = ArrayUtils::getArray($column['internal'], $obj, '/');
@ -709,7 +709,7 @@ class DataMapperAbstract implements DataMapperInterface
$propertyName = static::$columns[static::$primaryField]['internal']; $propertyName = static::$columns[static::$primaryField]['internal'];
$refProp = $refClass->getProperty($propertyName); $refProp = $refClass->getProperty($propertyName);
\settype($objId, static::$columns[static::$primaryField]['type']); settype($objId, static::$columns[static::$primaryField]['type']);
if (!$refProp->isPublic()) { if (!$refProp->isPublic()) {
$refProp->setAccessible(true); $refProp->setAccessible(true);
$refProp->setValue($obj, $objId); $refProp->setValue($obj, $objId);
@ -837,7 +837,7 @@ class DataMapperAbstract implements DataMapperInterface
} }
$objsIds = []; $objsIds = [];
$relReflectionClass = !empty($values) ? new \ReflectionClass(\reset($values)) : null; $relReflectionClass = !empty($values) ? new \ReflectionClass(reset($values)) : null;
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
if (!\is_object($value)) { if (!\is_object($value)) {
@ -1100,8 +1100,8 @@ class DataMapperAbstract implements DataMapperInterface
foreach ($objsIds as $src) { foreach ($objsIds as $src) {
if (\is_object($src)) { if (\is_object($src)) {
$mapper = (\stripos($mapper = \get_class($src), '\Null') !== false $mapper = (stripos($mapper = \get_class($src), '\Null') !== false
? \str_replace('\Null', '\\', $mapper) ? str_replace('\Null', '\\', $mapper)
: $mapper) : $mapper)
. 'Mapper'; . 'Mapper';
@ -1117,8 +1117,8 @@ class DataMapperAbstract implements DataMapperInterface
$sth->execute(); $sth->execute();
} }
} catch (\Throwable $e) { } catch (\Throwable $e) {
\var_dump($e->getMessage()); var_dump($e->getMessage());
\var_dump($relQuery->toSql()); var_dump($relQuery->toSql());
} }
} }
@ -1147,10 +1147,10 @@ class DataMapperAbstract implements DataMapperInterface
} elseif ($type === 'DateTime' || $type === 'DateTimeImmutable') { } elseif ($type === 'DateTime' || $type === 'DateTimeImmutable') {
return $value === null ? null : $value->format(self::$datetimeFormat); return $value === null ? null : $value->format(self::$datetimeFormat);
} elseif ($type === 'Json' || $value instanceof \JsonSerializable) { } elseif ($type === 'Json' || $value instanceof \JsonSerializable) {
return (string) \json_encode($value); return (string) json_encode($value);
} elseif ($type === 'Serializable') { } elseif ($type === 'Serializable') {
return $value->serialize(); return $value->serialize();
} elseif (\is_object($value) && \method_exists($value, 'getId')) { } elseif (\is_object($value) && method_exists($value, 'getId')) {
return $value->getId(); return $value->getId();
} }
@ -1200,7 +1200,7 @@ class DataMapperAbstract implements DataMapperInterface
/** @var self $mapper */ /** @var self $mapper */
$mapper = static::$hasMany[$propertyName]['mapper']; $mapper = static::$hasMany[$propertyName]['mapper'];
$relReflectionClass = new \ReflectionClass(\reset($values)); $relReflectionClass = new \ReflectionClass(reset($values));
$objsIds[$propertyName] = []; $objsIds[$propertyName] = [];
foreach ($values as $key => &$value) { foreach ($values as $key => &$value) {
@ -1331,8 +1331,8 @@ class DataMapperAbstract implements DataMapperInterface
$many = self::getHasManyRaw($objId); $many = self::getHasManyRaw($objId);
foreach (static::$hasMany as $propertyName => $rel) { foreach (static::$hasMany as $propertyName => $rel) {
$removes = \array_diff($many[$propertyName], \array_keys($objsIds[$propertyName] ?? [])); $removes = array_diff($many[$propertyName], array_keys($objsIds[$propertyName] ?? []));
$adds = \array_diff(\array_keys($objsIds[$propertyName] ?? []), $many[$propertyName]); $adds = array_diff(array_keys($objsIds[$propertyName] ?? []), $many[$propertyName]);
if (!empty($removes)) { if (!empty($removes)) {
self::deleteRelationTable($propertyName, $removes, $objId); self::deleteRelationTable($propertyName, $removes, $objId);
@ -1498,7 +1498,7 @@ class DataMapperAbstract implements DataMapperInterface
->where(static::$table . '.' . static::$primaryField, '=', $objId); ->where(static::$table . '.' . static::$primaryField, '=', $objId);
foreach (static::$columns as $column) { foreach (static::$columns as $column) {
$propertyName = \stripos($column['internal'], '/') !== false ? \explode('/', $column['internal'])[0] : $column['internal']; $propertyName = stripos($column['internal'], '/') !== false ? explode('/', $column['internal'])[0] : $column['internal'];
if (isset(static::$hasMany[$propertyName]) if (isset(static::$hasMany[$propertyName])
|| $column['internal'] === static::$primaryField || $column['internal'] === static::$primaryField
|| ($column['readonly'] ?? false === true) || ($column['readonly'] ?? false === true)
@ -1540,8 +1540,8 @@ class DataMapperAbstract implements DataMapperInterface
*/ */
$query->set([static::$table . '.' . $column['name'] => $value]); $query->set([static::$table . '.' . $column['name'] => $value]);
} elseif ($column['name'] !== static::$primaryField) { } elseif ($column['name'] !== static::$primaryField) {
if (\stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = \substr($column['internal'], \stripos($column['internal'], '/') + 1); $path = substr($column['internal'], stripos($column['internal'], '/') + 1);
$tValue = ArrayUtils::getArray($path, $tValue, '/'); $tValue = ArrayUtils::getArray($path, $tValue, '/');
} }
@ -1587,8 +1587,8 @@ class DataMapperAbstract implements DataMapperInterface
} }
$path = $column['internal']; $path = $column['internal'];
if (\stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = \substr($column['internal'], \stripos($column['internal'], '/') + 1); $path = substr($column['internal'], stripos($column['internal'], '/') + 1);
//$path = \ltrim($column['internal'], '/'); //$path = \ltrim($column['internal'], '/');
} }
@ -1757,7 +1757,7 @@ class DataMapperAbstract implements DataMapperInterface
/** @var self $mapper */ /** @var self $mapper */
$mapper = static::$hasMany[$propertyName]['mapper']; $mapper = static::$hasMany[$propertyName]['mapper'];
$objsIds = []; $objsIds = [];
$relReflectionClass = !empty($values) ? new \ReflectionClass(\reset($values)) : null; $relReflectionClass = !empty($values) ? new \ReflectionClass(reset($values)) : null;
foreach ($values as $key => &$value) { foreach ($values as $key => &$value) {
if (!\is_object($value)) { if (!\is_object($value)) {
@ -1921,7 +1921,7 @@ class DataMapperAbstract implements DataMapperInterface
public static function delete(mixed $obj, int $relations = RelationType::REFERENCE) : mixed public static function delete(mixed $obj, int $relations = RelationType::REFERENCE) : mixed
{ {
// @todo: only do this if RelationType !== NONE // @todo: only do this if RelationType !== NONE
if (\is_scalar($obj)) { if (is_scalar($obj)) {
$obj = static::get($obj); $obj = static::get($obj);
} }
@ -2296,17 +2296,17 @@ class DataMapperAbstract implements DataMapperInterface
$aValue = []; $aValue = [];
$arrayPath = ''; $arrayPath = '';
if (\stripos($def['internal'], '/') !== false) { if (stripos($def['internal'], '/') !== false) {
$hasPath = true; $hasPath = true;
$path = \explode('/', $def['internal']); $path = explode('/', $def['internal']);
$refProp = $refClass->getProperty($path[0]); $refProp = $refClass->getProperty($path[0]);
if (!($isPublic = $refProp->isPublic())) { if (!($isPublic = $refProp->isPublic())) {
$refProp->setAccessible(true); $refProp->setAccessible(true);
} }
\array_shift($path); array_shift($path);
$arrayPath = \implode('/', $path); $arrayPath = implode('/', $path);
$aValue = $isPublic ? $obj->{$path[0]} : $refProp->getValue($obj); $aValue = $isPublic ? $obj->{$path[0]} : $refProp->getValue($obj);
} else { } else {
$refProp = $refClass->getProperty($def['internal']); $refProp = $refClass->getProperty($def['internal']);
@ -2347,7 +2347,7 @@ class DataMapperAbstract implements DataMapperInterface
$refProp->setValue($obj, $value); $refProp->setValue($obj, $value);
} elseif (\in_array($def['type'], ['string', 'int', 'float', 'bool'])) { } elseif (\in_array($def['type'], ['string', 'int', 'float', 'bool'])) {
if ($value !== null || $refProp->getValue($obj) !== null) { if ($value !== null || $refProp->getValue($obj) !== null) {
\settype($value, $def['type']); settype($value, $def['type']);
} }
if ($hasPath) { if ($hasPath) {
@ -2374,7 +2374,7 @@ class DataMapperAbstract implements DataMapperInterface
$value = ArrayUtils::setArray($arrayPath, $aValue, $value, '/', true); $value = ArrayUtils::setArray($arrayPath, $aValue, $value, '/', true);
} }
$refProp->setValue($obj, \json_decode($value, true)); $refProp->setValue($obj, json_decode($value, true));
} elseif ($def['type'] === 'Serializable') { } elseif ($def['type'] === 'Serializable') {
$member = $isPublic ? $obj->{$def['internal']} : $refProp->getValue($obj); $member = $isPublic ? $obj->{$def['internal']} : $refProp->getValue($obj);
@ -2403,17 +2403,17 @@ class DataMapperAbstract implements DataMapperInterface
$aValue = null; $aValue = null;
$arrayPath = '/'; $arrayPath = '/';
if (\stripos($member, '/') !== false) { if (stripos($member, '/') !== false) {
$hasPath = true; $hasPath = true;
$path = \explode('/', $member); $path = explode('/', $member);
$refProp = $refClass->getProperty($path[0]); $refProp = $refClass->getProperty($path[0]);
if (!($isPublic = $refProp->isPublic())) { if (!($isPublic = $refProp->isPublic())) {
$refProp->setAccessible(true); $refProp->setAccessible(true);
} }
\array_shift($path); array_shift($path);
$arrayPath = \implode('/', $path); $arrayPath = implode('/', $path);
$aValue = $isPublic ? $obj->{$path[0]} : $refProp->getValue($obj); $aValue = $isPublic ? $obj->{$path[0]} : $refProp->getValue($obj);
} else { } else {
$refProp = $refClass->getProperty($member); $refProp = $refClass->getProperty($member);
@ -2425,7 +2425,7 @@ class DataMapperAbstract implements DataMapperInterface
if (\in_array($def['mapper']::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) { if (\in_array($def['mapper']::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) {
if ($value !== null || $refProp->getValue($obj) !== null) { if ($value !== null || $refProp->getValue($obj) !== null) {
\settype($value, $def['mapper']::$columns[$column]['type']); settype($value, $def['mapper']::$columns[$column]['type']);
} }
if ($hasPath) { if ($hasPath) {
@ -2452,7 +2452,7 @@ class DataMapperAbstract implements DataMapperInterface
$value = ArrayUtils::setArray($arrayPath, $aValue, $value, '/', true); $value = ArrayUtils::setArray($arrayPath, $aValue, $value, '/', true);
} }
$refProp->setValue($obj, \json_decode($value, true)); $refProp->setValue($obj, json_decode($value, true));
} elseif ($def['mapper']::$columns[$column]['type'] === 'Serializable') { } elseif ($def['mapper']::$columns[$column]['type'] === 'Serializable') {
$member = $isPublic ? $obj->{$member} : $refProp->getValue($obj); $member = $isPublic ? $obj->{$member} : $refProp->getValue($obj);
$member->unserialize($value); $member->unserialize($value);
@ -2489,11 +2489,11 @@ class DataMapperAbstract implements DataMapperInterface
$value = $result[$alias]; $value = $result[$alias];
$path = static::$columns[$column]['internal']; $path = static::$columns[$column]['internal'];
if (\stripos($path, '/') !== false) { if (stripos($path, '/') !== false) {
$path = \explode('/', $path); $path = explode('/', $path);
\array_shift($path); array_shift($path);
$path = \implode('/', $path); $path = implode('/', $path);
} }
if (isset(static::$ownsOne[$def['internal']])) { if (isset(static::$ownsOne[$def['internal']])) {
@ -2505,13 +2505,13 @@ class DataMapperAbstract implements DataMapperInterface
static::$belongsTo[$def['internal']]['mapper']::fillRelationsArray($value, self::$relations, $depth - 1); static::$belongsTo[$def['internal']]['mapper']::fillRelationsArray($value, self::$relations, $depth - 1);
} elseif (\in_array(static::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) { } elseif (\in_array(static::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) {
\settype($value, static::$columns[$column]['type']); settype($value, static::$columns[$column]['type']);
} elseif (static::$columns[$column]['type'] === 'DateTime') { } elseif (static::$columns[$column]['type'] === 'DateTime') {
$value = $value === null ? null : new \DateTime($value); $value = $value === null ? null : new \DateTime($value);
} elseif (static::$columns[$column]['type'] === 'DateTimeImmutable') { } elseif (static::$columns[$column]['type'] === 'DateTimeImmutable') {
$value = $value === null ? null : new \DateTimeImmutable($value); $value = $value === null ? null : new \DateTimeImmutable($value);
} elseif (static::$columns[$column]['type'] === 'Json') { } elseif (static::$columns[$column]['type'] === 'Json') {
$value = \json_decode($value, true); $value = json_decode($value, true);
} }
$obj = ArrayUtils::setArray($path, $obj, $value, '/', true); $obj = ArrayUtils::setArray($path, $obj, $value, '/', true);
@ -2529,13 +2529,13 @@ class DataMapperAbstract implements DataMapperInterface
$path = $member; $path = $member;
if (\in_array($def['mapper']::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) { if (\in_array($def['mapper']::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) {
\settype($value, $def['mapper']::$columns[$column]['type']); settype($value, $def['mapper']::$columns[$column]['type']);
} elseif ($def['mapper']::$columns[$column]['type'] === 'DateTime') { } elseif ($def['mapper']::$columns[$column]['type'] === 'DateTime') {
$value = $value === null ? null : new \DateTime($value); $value = $value === null ? null : new \DateTime($value);
} elseif ($def['mapper']::$columns[$column]['type'] === 'DateTimeImmutable') { } elseif ($def['mapper']::$columns[$column]['type'] === 'DateTimeImmutable') {
$value = $value === null ? null : new \DateTimeImmutable($value); $value = $value === null ? null : new \DateTimeImmutable($value);
} elseif ($def['mapper']::$columns[$column]['type'] === 'Json') { } elseif ($def['mapper']::$columns[$column]['type'] === 'Json') {
$value = \json_decode($value, true); $value = json_decode($value, true);
} }
$obj = ArrayUtils::setArray($path, $obj, $value, '/', true); $obj = ArrayUtils::setArray($path, $obj, $value, '/', true);
@ -2728,7 +2728,7 @@ class DataMapperAbstract implements DataMapperInterface
if ($countResulsts === 0) { if ($countResulsts === 0) {
return self::createNullModel(); return self::createNullModel();
} elseif ($countResulsts === 1) { } elseif ($countResulsts === 1) {
return \reset($obj); return reset($obj);
} }
return $obj; return $obj;
@ -2789,7 +2789,7 @@ class DataMapperAbstract implements DataMapperInterface
if ($countResulsts === 0) { if ($countResulsts === 0) {
return []; return [];
} elseif ($countResulsts === 1) { } elseif ($countResulsts === 1) {
return \reset($obj); return reset($obj);
} }
return $obj; return $obj;
@ -2805,7 +2805,7 @@ class DataMapperAbstract implements DataMapperInterface
self::clear(); self::clear();
return \count($obj) === 1 ? \reset($obj) : $obj; return \count($obj) === 1 ? reset($obj) : $obj;
} }
/** /**
@ -2892,7 +2892,7 @@ class DataMapperAbstract implements DataMapperInterface
{ {
$result = self::get(null, $relations, $depth); $result = self::get(null, $relations, $depth);
if (\is_object($result) && \stripos(\get_class($result), '\Null') !== false) { if (\is_object($result) && stripos(\get_class($result), '\Null') !== false) {
return []; return [];
} }
@ -2913,7 +2913,7 @@ class DataMapperAbstract implements DataMapperInterface
{ {
$result = self::getArray(null, $relations, $depth); $result = self::getArray(null, $relations, $depth);
return !\is_array(\reset($result)) ? [$result] : $result; return !\is_array(reset($result)) ? [$result] : $result;
} }
/** /**
@ -2977,7 +2977,7 @@ class DataMapperAbstract implements DataMapperInterface
{ {
$result = self::get(null, $relations, $depth, null, $query); $result = self::get(null, $relations, $depth, null, $query);
if (\is_object($result) && \stripos(\get_class($result), '\Null') !== false) { if (\is_object($result) && stripos(\get_class($result), '\Null') !== false) {
return []; return [];
} }
@ -3097,7 +3097,7 @@ class DataMapperAbstract implements DataMapperInterface
public static function getRaw(mixed $keys, int $relations = RelationType::ALL, int $depth = 3, string $ref = null, Builder $query = null) : array public static function getRaw(mixed $keys, int $relations = RelationType::ALL, int $depth = 3, string $ref = null, Builder $query = null) : array
{ {
$comparison = \is_array($keys) && \count($keys) > 1 ? 'in' : '='; $comparison = \is_array($keys) && \count($keys) > 1 ? 'in' : '=';
$keys = $comparison === 'in' ? $keys : \reset($keys); $keys = $comparison === 'in' ? $keys : reset($keys);
$query ??= self::getQuery(null, [], $relations, $depth); $query ??= self::getQuery(null, [], $relations, $depth);
$hasBy = $ref === null ? false : isset(static::$columns[self::getColumnByMember($ref)]); $hasBy = $ref === null ? false : isset(static::$columns[self::getColumnByMember($ref)]);
@ -3163,8 +3163,8 @@ class DataMapperAbstract implements DataMapperInterface
} }
} catch (\Throwable $t) { } catch (\Throwable $t) {
$results = false; $results = false;
\var_dump($query->toSql()); var_dump($query->toSql());
\var_dump($t->getMessage()); var_dump($t->getMessage());
} }
return $results === false ? [] : $results; return $results === false ? [] : $results;
@ -3195,7 +3195,7 @@ class DataMapperAbstract implements DataMapperInterface
$result = $sth->fetchAll(\PDO::FETCH_NUM); $result = $sth->fetchAll(\PDO::FETCH_NUM);
} }
return $result === false ? [] : \array_column($result, 0); return $result === false ? [] : array_column($result, 0);
} }
/** /**
@ -3237,7 +3237,7 @@ class DataMapperAbstract implements DataMapperInterface
->from($value['table']) ->from($value['table'])
->where($value['table'] . '.' . $value['self'], '=', $primaryKey); ->where($value['table'] . '.' . $value['self'], '=', $primaryKey);
if ($value['mapper']::getTable() !== $value['table']) { if ($value['table'] !== $value['mapper']::getTable()) {
$query->leftJoin($value['mapper']::getTable()) $query->leftJoin($value['mapper']::getTable())
->on($value['table'] . '.' . $src, '=', $value['mapper']::getTable() . '.' . $value['mapper']::getPrimaryField()); ->on($value['table'] . '.' . $src, '=', $value['mapper']::getTable() . '.' . $value['mapper']::getPrimaryField());
} }
@ -3656,7 +3656,7 @@ class DataMapperAbstract implements DataMapperInterface
*/ */
private static function isNullModel(mixed $obj) : bool private static function isNullModel(mixed $obj) : bool
{ {
return \is_object($obj) && \strpos(\get_class($obj), '\Null') !== false; return \is_object($obj) && strpos(\get_class($obj), '\Null') !== false;
} }
/** /**
@ -3670,11 +3670,11 @@ class DataMapperAbstract implements DataMapperInterface
*/ */
private static function createNullModel(mixed $id = null) : mixed private static function createNullModel(mixed $id = null) : mixed
{ {
$class = empty(static::$model) ? \substr(static::class, 0, -6) : static::$model; $class = empty(static::$model) ? substr(static::class, 0, -6) : static::$model;
$parts = \explode('\\', $class); $parts = explode('\\', $class);
$name = $parts[$c = (\count($parts) - 1)]; $name = $parts[$c = (\count($parts) - 1)];
$parts[$c] = 'Null' . $name; $parts[$c] = 'Null' . $name;
$class = \implode('\\', $parts); $class = implode('\\', $parts);
return $id !== null ? new $class($id) : new $class(); return $id !== null ? new $class($id) : new $class();
} }
@ -3688,7 +3688,7 @@ class DataMapperAbstract implements DataMapperInterface
*/ */
private static function createBaseModel() : mixed private static function createBaseModel() : mixed
{ {
$class = empty(static::$model) ? \substr(static::class, 0, -6) : static::$model; $class = empty(static::$model) ? substr(static::class, 0, -6) : static::$model;
/** /**
* @todo Orange-Management/phpOMS#67 * @todo Orange-Management/phpOMS#67
@ -3707,7 +3707,7 @@ class DataMapperAbstract implements DataMapperInterface
*/ */
private static function getModelName() : string private static function getModelName() : string
{ {
return empty(static::$model) ? \substr(static::class, 0, -6) : static::$model; return empty(static::$model) ? substr(static::class, 0, -6) : static::$model;
} }
} }

View File

@ -75,7 +75,7 @@ final class DatabasePool implements DataStoragePoolInterface
} }
if (empty($key)) { if (empty($key)) {
return \reset($this->pool); return reset($this->pool);
} }
return $this->pool[$key]; return $this->pool[$key];

View File

@ -123,9 +123,9 @@ abstract class GrammarAbstract
*/ */
public function compileQuery(BuilderAbstract $query) : string public function compileQuery(BuilderAbstract $query) : string
{ {
return \trim( return trim(
\implode(' ', implode(' ',
\array_filter( array_filter(
$this->compileComponents($query), $this->compileComponents($query),
function ($value) { function ($value) {
return (string) $value !== ''; return (string) $value !== '';
@ -159,7 +159,7 @@ abstract class GrammarAbstract
/* Loop all possible query components and if they exist compile them. */ /* Loop all possible query components and if they exist compile them. */
foreach ($components as $component) { foreach ($components as $component) {
if (isset($query->{$component}) && !empty($query->{$component})) { if (isset($query->{$component}) && !empty($query->{$component})) {
$sql[$component] = $this->{'compile' . \ucfirst($component)}($query, $query->{$component}); $sql[$component] = $this->{'compile' . ucfirst($component)}($query, $query->{$component});
} }
} }
@ -219,7 +219,7 @@ abstract class GrammarAbstract
} }
} }
return \rtrim($expression, ', '); return rtrim($expression, ', ');
} }
/** /**
@ -239,7 +239,7 @@ abstract class GrammarAbstract
$identifierEnd = $this->systemIdentifierEnd; $identifierEnd = $this->systemIdentifierEnd;
foreach ($this->specialKeywords as $keyword) { foreach ($this->specialKeywords as $keyword) {
if (\strrpos($system, $keyword, -\strlen($system)) !== false) { if (strrpos($system, $keyword, -\strlen($system)) !== false) {
$identifierStart = ''; $identifierStart = '';
$identifierEnd = ''; $identifierEnd = '';
@ -247,7 +247,7 @@ abstract class GrammarAbstract
} }
} }
$split = \explode('.', $system); $split = explode('.', $system);
$fullSystem = ''; $fullSystem = '';
foreach ($split as $key => $system) { foreach ($split as $key => $system) {
@ -257,6 +257,6 @@ abstract class GrammarAbstract
. ($system !== '*' ? $identifierEnd : ''); . ($system !== '*' ? $identifierEnd : '');
} }
return \ltrim($fullSystem, '.'); return ltrim($fullSystem, '.');
} }
} }

View File

@ -389,12 +389,12 @@ class Builder extends BuilderAbstract
$dependencies[$table] = []; $dependencies[$table] = [];
foreach ($this->ons[$table] as $on) { foreach ($this->ons[$table] as $on) {
if (\stripos($on['column'], '.')) { if (stripos($on['column'], '.')) {
$dependencies[$table][] = \explode('.', $on['column'])[0]; $dependencies[$table][] = explode('.', $on['column'])[0];
} }
if (\stripos($on['value'], '.')) { if (stripos($on['value'], '.')) {
$dependencies[$table][] = \explode('.', $on['value'])[0]; $dependencies[$table][] = explode('.', $on['value'])[0];
} }
} }
} }
@ -438,7 +438,7 @@ class Builder extends BuilderAbstract
} }
$this->type = QueryType::RAW; $this->type = QueryType::RAW;
$this->raw = \rtrim($raw, ';'); $this->raw = rtrim($raw, ';');
return $this; return $this;
} }
@ -459,14 +459,14 @@ class Builder extends BuilderAbstract
return true; return true;
} }
$raw = \strtolower($raw); $raw = strtolower($raw);
if (\stripos($raw, 'insert') !== false if (stripos($raw, 'insert') !== false
|| \stripos($raw, 'update') !== false || stripos($raw, 'update') !== false
|| \stripos($raw, 'drop') !== false || stripos($raw, 'drop') !== false
|| \stripos($raw, 'delete') !== false || stripos($raw, 'delete') !== false
|| \stripos($raw, 'create') !== false || stripos($raw, 'create') !== false
|| \stripos($raw, 'alter') !== false || stripos($raw, 'alter') !== false
) { ) {
return false; return false;
} }
@ -554,7 +554,7 @@ class Builder extends BuilderAbstract
$i = 0; $i = 0;
foreach ($columns as $column) { foreach ($columns as $column) {
if (isset($operator[$i]) && !\in_array(\strtolower($operator[$i]), self::OPERATORS)) { if (isset($operator[$i]) && !\in_array(strtolower($operator[$i]), self::OPERATORS)) {
throw new \InvalidArgumentException('Unknown operator: "' . $operator[$i] . '"'); throw new \InvalidArgumentException('Unknown operator: "' . $operator[$i] . '"');
} }
@ -977,9 +977,9 @@ class Builder extends BuilderAbstract
*/ */
public function value(mixed $value) : self public function value(mixed $value) : self
{ {
\end($this->values); end($this->values);
$key = \key($this->values); $key = key($this->values);
$key ??= 0; $key ??= 0;
if (\is_array($value)) { if (\is_array($value)) {
@ -988,7 +988,7 @@ class Builder extends BuilderAbstract
$this->values[$key][] = $value; $this->values[$key][] = $value;
} }
\reset($this->values); reset($this->values);
return $this; return $this;
} }
@ -1020,7 +1020,7 @@ class Builder extends BuilderAbstract
*/ */
public function set(mixed $set) : self public function set(mixed $set) : self
{ {
$this->sets[\key($set)] = \current($set); $this->sets[key($set)] = current($set);
return $this; return $this;
} }
@ -1307,7 +1307,7 @@ class Builder extends BuilderAbstract
*/ */
public function on(string | array $columns, string | array $operator = null, string | array $values = null, string | array $boolean = 'and', string $table = null) : self public function on(string | array $columns, string | array $operator = null, string | array $values = null, string | array $boolean = 'and', string $table = null) : self
{ {
if ($operator !== null && !\is_array($operator) && !\in_array(\strtolower($operator), self::OPERATORS)) { if ($operator !== null && !\is_array($operator) && !\in_array(strtolower($operator), self::OPERATORS)) {
throw new \InvalidArgumentException('Unknown operator.'); throw new \InvalidArgumentException('Unknown operator.');
} }
@ -1320,10 +1320,10 @@ class Builder extends BuilderAbstract
$joinCount = \count($this->joins) - 1; $joinCount = \count($this->joins) - 1;
$i = 0; $i = 0;
$table ??= \array_keys($this->joins)[$joinCount]; $table ??= array_keys($this->joins)[$joinCount];
foreach ($columns as $column) { foreach ($columns as $column) {
if (isset($operator[$i]) && !\in_array(\strtolower($operator[$i]), self::OPERATORS)) { if (isset($operator[$i]) && !\in_array(strtolower($operator[$i]), self::OPERATORS)) {
throw new \InvalidArgumentException('Unknown operator.'); throw new \InvalidArgumentException('Unknown operator.');
} }
@ -1408,8 +1408,8 @@ class Builder extends BuilderAbstract
$sth->execute(); $sth->execute();
} catch (\Throwable $t) { } catch (\Throwable $t) {
\var_dump($t->getMessage()); var_dump($t->getMessage());
\var_dump($this->toSql()); var_dump($this->toSql());
$sth = null; $sth = null;
} }
@ -1459,7 +1459,7 @@ class Builder extends BuilderAbstract
} elseif ($column instanceof \Serializable) { } elseif ($column instanceof \Serializable) {
return $column->serialize(); return $column->serialize();
} elseif ($column instanceof self) { } elseif ($column instanceof self) {
return \md5($column->toSql()); return md5($column->toSql());
} }
throw new \Exception(); throw new \Exception();

View File

@ -249,7 +249,7 @@ class Grammar extends GrammarAbstract
$expression = ''; $expression = '';
if (!$first) { if (!$first) {
$expression = ' ' . \strtoupper($element['boolean']) . ' '; $expression = ' ' . strtoupper($element['boolean']) . ' ';
} }
if (\is_string($element['column'])) { if (\is_string($element['column'])) {
@ -257,14 +257,14 @@ class Grammar extends GrammarAbstract
} elseif ($element['column'] instanceof \Closure) { } elseif ($element['column'] instanceof \Closure) {
$expression .= $element['column'](); $expression .= $element['column']();
} elseif ($element['column'] instanceof Where) { } elseif ($element['column'] instanceof Where) {
$where = \rtrim($this->compileWhereQuery($element['column']), ';'); $where = rtrim($this->compileWhereQuery($element['column']), ';');
$expression .= '(' . (\stripos($where, 'WHERE ') === 0 ? \substr($where, 6) : $where) . ')'; $expression .= '(' . (stripos($where, 'WHERE ') === 0 ? substr($where, 6) : $where) . ')';
} elseif ($element['column'] instanceof Builder) { } elseif ($element['column'] instanceof Builder) {
$expression .= '(' . \rtrim($element['column']->toSql(), ';') . ')'; $expression .= '(' . rtrim($element['column']->toSql(), ';') . ')';
} }
if (isset($element['value'])) { if (isset($element['value'])) {
$expression .= ' ' . \strtoupper($element['operator']) . ' ' . $this->compileValue($query, $element['value']); $expression .= ' ' . strtoupper($element['operator']) . ' ' . $this->compileValue($query, $element['value']);
} elseif ($element['value'] === null && !($element['column'] instanceof Builder)) { } elseif ($element['value'] === null && !($element['column'] instanceof Builder)) {
$operator = $element['operator'] === '=' ? 'IS' : 'IS NOT'; $operator = $element['operator'] === '=' ? 'IS' : 'IS NOT';
$expression .= ' ' . $operator . ' ' . $this->compileValue($query, $element['value']); $expression .= ' ' . $operator . ' ' . $this->compileValue($query, $element['value']);
@ -340,7 +340,7 @@ class Grammar extends GrammarAbstract
$values .= $this->compileValue($query, $val) . ', '; $values .= $this->compileValue($query, $val) . ', ';
} }
return '(' . \rtrim($values, ', ') . ')'; return '(' . rtrim($values, ', ') . ')';
} elseif ($value instanceof \DateTime) { } elseif ($value instanceof \DateTime) {
return $query->quote($value->format($this->datetimeFormat)); return $query->quote($value->format($this->datetimeFormat));
} elseif ($value === null) { } elseif ($value === null) {
@ -348,13 +348,13 @@ class Grammar extends GrammarAbstract
} elseif (\is_bool($value)) { } elseif (\is_bool($value)) {
return (string) ((int) $value); return (string) ((int) $value);
} elseif (\is_float($value)) { } elseif (\is_float($value)) {
return \rtrim(\rtrim(\number_format($value, 5, '.', ''), '0'), '.'); return rtrim(rtrim(number_format($value, 5, '.', ''), '0'), '.');
} elseif ($value instanceof Column) { } elseif ($value instanceof Column) {
return '(' . \rtrim($this->compileColumnQuery($value), ';') . ')'; return '(' . rtrim($this->compileColumnQuery($value), ';') . ')';
} elseif ($value instanceof Builder) { } elseif ($value instanceof Builder) {
return '(' . \rtrim($value->toSql(), ';') . ')'; return '(' . rtrim($value->toSql(), ';') . ')';
} elseif ($value instanceof \JsonSerializable) { } elseif ($value instanceof \JsonSerializable) {
$encoded = \json_encode($value); $encoded = json_encode($value);
return $encoded ? $encoded : 'NULL'; return $encoded ? $encoded : 'NULL';
} elseif ($value instanceof \Serializable) { } elseif ($value instanceof \Serializable) {
@ -418,13 +418,13 @@ class Grammar extends GrammarAbstract
} elseif ($join['table'] instanceof \Closure) { } elseif ($join['table'] instanceof \Closure) {
$expression .= $join['table']() . (\is_string($join['alias']) ? ' as ' . $join['alias'] : ''); $expression .= $join['table']() . (\is_string($join['alias']) ? ' as ' . $join['alias'] : '');
} elseif ($join['table'] instanceof Builder) { } elseif ($join['table'] instanceof Builder) {
$expression .= '(' . \rtrim($join['table']->toSql(), ';') . ')' . (\is_string($join['alias']) ? ' as ' . $join['alias'] : ''); $expression .= '(' . rtrim($join['table']->toSql(), ';') . ')' . (\is_string($join['alias']) ? ' as ' . $join['alias'] : '');
} }
$expression .= $this->compileOn($query, $query->ons[$join['alias'] ?? $table]) . ' '; $expression .= $this->compileOn($query, $query->ons[$join['alias'] ?? $table]) . ' ';
} }
$expression = \rtrim($expression, ', '); $expression = rtrim($expression, ', ');
return $expression; return $expression;
} }
@ -472,12 +472,12 @@ class Grammar extends GrammarAbstract
$expression = ''; $expression = '';
if (!$first) { if (!$first) {
$expression = ' ' . \strtoupper($element['boolean']) . ' '; $expression = ' ' . strtoupper($element['boolean']) . ' ';
} }
if (\is_string($element['column'])) { if (\is_string($element['column'])) {
// handle bug when no table is specified in the where column // handle bug when no table is specified in the where column
if (\count($query->from) === 1 && \stripos($element['column'], '.') === false) { if (\count($query->from) === 1 && stripos($element['column'], '.') === false) {
$element['column'] = $query->from[0] . '.' . $element['column']; $element['column'] = $query->from[0] . '.' . $element['column'];
} }
@ -487,11 +487,11 @@ class Grammar extends GrammarAbstract
} elseif ($element['column'] instanceof Builder) { } elseif ($element['column'] instanceof Builder) {
$expression .= '(' . $element['column']->toSql() . ')'; $expression .= '(' . $element['column']->toSql() . ')';
} elseif ($element['column'] instanceof Where) { } elseif ($element['column'] instanceof Where) {
$expression .= '(' . \rtrim($this->compileWhereQuery($element['column']), ';') . ')'; $expression .= '(' . rtrim($this->compileWhereQuery($element['column']), ';') . ')';
} }
if (isset($element['value'])) { if (isset($element['value'])) {
$expression .= ' ' . \strtoupper($element['operator']) . ' ' . $this->compileSystem($element['value']); $expression .= ' ' . strtoupper($element['operator']) . ' ' . $this->compileSystem($element['value']);
} else { } else {
$operator = $element['operator'] === '=' ? 'IS' : 'IS NOT'; $operator = $element['operator'] === '=' ? 'IS' : 'IS NOT';
$expression .= ' ' . $operator . ' ' . $this->compileValue($query, $element['value']); $expression .= ' ' . $operator . ' ' . $this->compileValue($query, $element['value']);
@ -518,7 +518,7 @@ class Grammar extends GrammarAbstract
$expression .= $this->compileSystem($group) . ', '; $expression .= $this->compileSystem($group) . ', ';
} }
$expression = \rtrim($expression, ', '); $expression = rtrim($expression, ', ');
return 'GROUP BY ' . $expression; return 'GROUP BY ' . $expression;
} }
@ -542,7 +542,7 @@ class Grammar extends GrammarAbstract
$expression .= $this->compileSystem($column) . ' ' . $order . ', '; $expression .= $this->compileSystem($column) . ' ' . $order . ', ';
} }
$expression = \rtrim($expression, ', '); $expression = rtrim($expression, ', ');
if ($expression === '') { if ($expression === '') {
return ''; return '';
@ -612,7 +612,7 @@ class Grammar extends GrammarAbstract
return ''; return '';
} }
return '(' . \rtrim($cols, ', ') . ')'; return '(' . rtrim($cols, ', ') . ')';
} }
/** /**
@ -637,7 +637,7 @@ class Grammar extends GrammarAbstract
return ''; return '';
} }
return 'VALUES ' . \rtrim($vals, ', '); return 'VALUES ' . rtrim($vals, ', ');
} }
/** /**
@ -664,6 +664,6 @@ class Grammar extends GrammarAbstract
return ''; return '';
} }
return 'SET ' . \rtrim($vals, ', '); return 'SET ' . rtrim($vals, ', ');
} }
} }

View File

@ -77,7 +77,7 @@ class MysqlGrammar extends Grammar
->from('information_schema.tables') ->from('information_schema.tables')
->where('table_schema', '=', $query->getConnection()->getDatabase()); ->where('table_schema', '=', $query->getConnection()->getDatabase());
return \rtrim($builder->toSql(), ';'); return rtrim($builder->toSql(), ';');
} }
/** /**
@ -98,7 +98,7 @@ class MysqlGrammar extends Grammar
->where('table_schema', '=', $query->getConnection()->getDatabase()) ->where('table_schema', '=', $query->getConnection()->getDatabase())
->andWhere('table_name', '=', $table); ->andWhere('table_name', '=', $table);
return \rtrim($builder->toSql(), ';'); return rtrim($builder->toSql(), ';');
} }
/** /**
@ -150,7 +150,7 @@ class MysqlGrammar extends Grammar
} }
} }
return '(' . \ltrim(\rtrim($fieldQuery . $keys, ','), ' ') . ')'; return '(' . ltrim(rtrim($fieldQuery . $keys, ','), ' ') . ')';
} }
/** /**

View File

@ -65,7 +65,7 @@ class SchemaMapper
$tables = []; $tables = [];
foreach ($tNames as $name) { foreach ($tNames as $name) {
$tables[] = \array_values($name)[0]; $tables[] = array_values($name)[0];
} }
return $tables; return $tables;
@ -103,7 +103,7 @@ class SchemaMapper
$fields = []; $fields = [];
foreach ($tNames as $name) { foreach ($tNames as $name) {
$fields[] = \array_values($name); $fields[] = array_values($name);
} }
return $fields; return $fields;

View File

@ -73,33 +73,33 @@ class FileSession implements SessionInterface
*/ */
public function __construct(int $liftetime = 3600, string $sid = '', int $inactivityInterval = 0) public function __construct(int $liftetime = 3600, string $sid = '', int $inactivityInterval = 0)
{ {
if (\session_id()) { if (session_id()) {
\session_write_close(); // @codeCoverageIgnore session_write_close(); // @codeCoverageIgnore
} }
if ($sid !== '') { if ($sid !== '') {
\session_id((string) $sid); session_id((string) $sid);
} }
$this->inactivityInterval = $inactivityInterval; $this->inactivityInterval = $inactivityInterval;
if (\session_status() !== \PHP_SESSION_ACTIVE && !\headers_sent()) { if (session_status() !== \PHP_SESSION_ACTIVE && !headers_sent()) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
\session_set_cookie_params($liftetime, '/', '', false, true); session_set_cookie_params($liftetime, '/', '', false, true);
\session_start(); session_start();
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} }
if ($this->inactivityInterval > 0 if ($this->inactivityInterval > 0
&& ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < \time()) && ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < time())
) { ) {
$this->destroy(); // @codeCoverageIgnore $this->destroy(); // @codeCoverageIgnore
} }
$this->sessionData = $_SESSION ?? []; $this->sessionData = $_SESSION ?? [];
$_SESSION = null; $_SESSION = null;
$this->sessionData['lastActivity'] = \time(); $this->sessionData['lastActivity'] = time();
$this->sid = (string) \session_id(); $this->sid = (string) session_id();
} }
/** /**
@ -154,7 +154,7 @@ class FileSession implements SessionInterface
} }
$_SESSION = $this->sessionData; $_SESSION = $this->sessionData;
\session_write_close(); session_write_close();
return true; return true;
} }
@ -199,10 +199,10 @@ class FileSession implements SessionInterface
*/ */
private function destroy() : void private function destroy() : void
{ {
if (\session_status() !== \PHP_SESSION_NONE) { if (session_status() !== \PHP_SESSION_NONE) {
\session_destroy(); session_destroy();
$this->sessionData = []; $this->sessionData = [];
\session_start(); session_start();
} }
} }

View File

@ -45,8 +45,8 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
{ {
$this->savePath = $path; $this->savePath = $path;
if (\realpath($path) === false) { if (realpath($path) === false) {
\mkdir($path, 0755, true); mkdir($path, 0755, true);
} }
} }
@ -59,7 +59,7 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
*/ */
public function create_sid() : string public function create_sid() : string
{ {
return ($sid = \session_create_id('s-')) === false ? '' : $sid; return ($sid = session_create_id('s-')) === false ? '' : $sid;
} }
/** /**
@ -76,7 +76,7 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
{ {
$this->savePath = $savePath; $this->savePath = $savePath;
return \is_dir($this->savePath); return is_dir($this->savePath);
} }
/** /**
@ -102,11 +102,11 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
*/ */
public function read($id) public function read($id)
{ {
if (!\is_file($this->savePath . '/sess_' . $id)) { if (!is_file($this->savePath . '/sess_' . $id)) {
return ''; return '';
} }
return (string) \file_get_contents($this->savePath . '/sess_' . $id); return (string) file_get_contents($this->savePath . '/sess_' . $id);
} }
/** /**
@ -121,7 +121,7 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
*/ */
public function write($id, $data) public function write($id, $data)
{ {
return \file_put_contents($this->savePath . '/sess_' . $id, $data) === false ? false : true; return file_put_contents($this->savePath . '/sess_' . $id, $data) === false ? false : true;
} }
/** /**
@ -136,8 +136,8 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
public function destroy($id) public function destroy($id)
{ {
$file = $this->savePath . '/sess_' . $id; $file = $this->savePath . '/sess_' . $id;
if (\is_file($file)) { if (is_file($file)) {
\unlink($file); unlink($file);
} }
return true; return true;
@ -154,15 +154,15 @@ final class FileSessionHandler implements \SessionHandlerInterface, \SessionIdIn
*/ */
public function gc($maxlifetime) public function gc($maxlifetime)
{ {
$files = \glob("{$this->savePath}/sess_*"); $files = glob("{$this->savePath}/sess_*");
if ($files === false) { if ($files === false) {
return false; return false;
} }
foreach ($files as $file) { foreach ($files as $file) {
if (\filemtime($file) + $maxlifetime < \time() && \is_file($file)) { if (filemtime($file) + $maxlifetime < time() && is_file($file)) {
\unlink($file); unlink($file);
} }
} }

View File

@ -74,19 +74,19 @@ final class HttpSession implements SessionInterface
*/ */
public function __construct(int $liftetime = 3600, string $sid = '', int $inactivityInterval = 0) public function __construct(int $liftetime = 3600, string $sid = '', int $inactivityInterval = 0)
{ {
if (\session_id()) { if (session_id()) {
\session_write_close(); // @codeCoverageIgnore session_write_close(); // @codeCoverageIgnore
} }
if ($sid !== '') { if ($sid !== '') {
\session_id((string) $sid); // @codeCoverageIgnore session_id((string) $sid); // @codeCoverageIgnore
} }
$this->inactivityInterval = $inactivityInterval; $this->inactivityInterval = $inactivityInterval;
if (\session_status() !== \PHP_SESSION_ACTIVE && !\headers_sent()) { if (session_status() !== \PHP_SESSION_ACTIVE && !headers_sent()) {
// @codeCoverageIgnoreStart // @codeCoverageIgnoreStart
\session_set_cookie_params([ session_set_cookie_params([
'lifetime' => $liftetime, 'lifetime' => $liftetime,
'path' => '/', 'path' => '/',
'domain' => '', 'domain' => '',
@ -94,18 +94,18 @@ final class HttpSession implements SessionInterface
'httponly' => true, 'httponly' => true,
'samesite' => 'Strict', 'samesite' => 'Strict',
]); ]);
\session_start(); session_start();
// @codeCoverageIgnoreEnd // @codeCoverageIgnoreEnd
} }
if ($this->inactivityInterval > 0 && ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < \time())) { if ($this->inactivityInterval > 0 && ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < time())) {
$this->destroy(); // @codeCoverageIgnore $this->destroy(); // @codeCoverageIgnore
} }
$this->sessionData = $_SESSION ?? []; $this->sessionData = $_SESSION ?? [];
$_SESSION = null; $_SESSION = null;
$this->sessionData['lastActivity'] = \time(); $this->sessionData['lastActivity'] = time();
$this->sid = (string) \session_id(); $this->sid = (string) session_id();
$this->setCsrfProtection(); $this->setCsrfProtection();
} }
@ -122,7 +122,7 @@ final class HttpSession implements SessionInterface
$this->set('UID', 0, false); $this->set('UID', 0, false);
if (($csrf = $this->get('CSRF')) === null) { if (($csrf = $this->get('CSRF')) === null) {
$csrf = \bin2hex(\random_bytes(32)); $csrf = bin2hex(random_bytes(32));
$this->set('CSRF', $csrf, false); $this->set('CSRF', $csrf, false);
} }
@ -181,7 +181,7 @@ final class HttpSession implements SessionInterface
} }
$_SESSION = $this->sessionData; $_SESSION = $this->sessionData;
\session_write_close(); session_write_close();
return true; return true;
} }
@ -226,10 +226,10 @@ final class HttpSession implements SessionInterface
*/ */
private function destroy() : void private function destroy() : void
{ {
if (\session_status() !== \PHP_SESSION_NONE) { if (session_status() !== \PHP_SESSION_NONE) {
\session_destroy(); session_destroy();
$this->sessionData = []; $this->sessionData = [];
\session_start(); session_start();
} }
} }

View File

@ -68,7 +68,7 @@ final class Dispatcher implements DispatcherInterface
if (\is_array($controller) && isset($controller['dest'])) { if (\is_array($controller) && isset($controller['dest'])) {
if (!empty($controller['data'])) { if (!empty($controller['data'])) {
$data = \array_merge( $data = array_merge(
empty($data) ? [] : $data, empty($data) ? [] : $data,
\is_array($controller['data']) ? $controller['data'] : [$controller['data']] \is_array($controller['data']) ? $controller['data'] : [$controller['data']]
); );
@ -112,7 +112,7 @@ final class Dispatcher implements DispatcherInterface
private function dispatchString(string $controller, array $data = null) : array private function dispatchString(string $controller, array $data = null) : array
{ {
$views = []; $views = [];
$dispatch = \explode(':', $controller); $dispatch = explode(':', $controller);
if (!Autoloader::exists($dispatch[0]) && !isset($this->controllers[$dispatch[0]])) { if (!Autoloader::exists($dispatch[0]) && !isset($this->controllers[$dispatch[0]])) {
throw new PathException($dispatch[0]); throw new PathException($dispatch[0]);

View File

@ -104,7 +104,7 @@ final class EventManager implements \Countable
*/ */
public function importFromFile(string $path) : bool public function importFromFile(string $path) : bool
{ {
if (!\is_file($path)) { if (!is_file($path)) {
return false; return false;
} }
@ -169,18 +169,18 @@ final class EventManager implements \Countable
*/ */
public function triggerSimilar(string $group, string $id = '', mixed $data = null) : bool public function triggerSimilar(string $group, string $id = '', mixed $data = null) : bool
{ {
$groupIsRegex = \stripos($group, '/') === 0; $groupIsRegex = stripos($group, '/') === 0;
$idIsRegex = \stripos($id, '/') === 0; $idIsRegex = stripos($id, '/') === 0;
$groups = []; $groups = [];
foreach ($this->groups as $groupName => $value) { foreach ($this->groups as $groupName => $value) {
$groupNameIsRegex = \stripos($groupName, '/') === 0; $groupNameIsRegex = stripos($groupName, '/') === 0;
if ($groupIsRegex) { if ($groupIsRegex) {
if (\preg_match($group, $groupName) === 1) { if (preg_match($group, $groupName) === 1) {
$groups[$groupName] = []; $groups[$groupName] = [];
} }
} elseif ($groupNameIsRegex && \preg_match($groupName, $group) === 1) { } elseif ($groupNameIsRegex && preg_match($groupName, $group) === 1) {
$groups[$groupName] = []; $groups[$groupName] = [];
} elseif ($groupName === $group) { } elseif ($groupName === $group) {
$groups[$groupName] = []; $groups[$groupName] = [];
@ -189,13 +189,13 @@ final class EventManager implements \Countable
foreach ($groups as $groupName => $groupValues) { foreach ($groups as $groupName => $groupValues) {
foreach ($this->groups[$groupName] as $idName => $value) { foreach ($this->groups[$groupName] as $idName => $value) {
$idNameIsRegex = \stripos($idName, '/') === 0; $idNameIsRegex = stripos($idName, '/') === 0;
if ($idIsRegex) { if ($idIsRegex) {
if (\preg_match($id, $idName) === 1) { if (preg_match($id, $idName) === 1) {
$groups[$groupName][] = $idName; $groups[$groupName][] = $idName;
} }
} elseif ($idNameIsRegex && \preg_match($idName, $id) === 1) { } elseif ($idNameIsRegex && preg_match($idName, $id) === 1) {
$groups[$groupName][] = $id; $groups[$groupName][] = $id;
} elseif ($idName === $id) { } elseif ($idName === $id) {
$groups[$groupName] = []; $groups[$groupName] = [];

View File

@ -107,7 +107,7 @@ final class L11nManager
*/ */
public function loadLanguageFile(string $from, string $file) : void public function loadLanguageFile(string $from, string $file) : void
{ {
if (!\is_file($file)) { if (!is_file($file)) {
return; return;
} }
@ -135,7 +135,7 @@ final class L11nManager
*/ */
public function loadLanguageFromFile(string $language, string $from, string $file) : void public function loadLanguageFromFile(string $language, string $from, string $file) : void
{ {
if (!\is_file($file)) { if (!is_file($file)) {
return; return;
} }
@ -219,7 +219,7 @@ final class L11nManager
*/ */
public function getHtml(string $code, string $module, string $theme, string $translation) : string public function getHtml(string $code, string $module, string $theme, string $translation) : string
{ {
return \htmlspecialchars($this->getText($code, $module, $theme, $translation)); return htmlspecialchars($this->getText($code, $module, $theme, $translation));
} }
/** /**
@ -235,7 +235,7 @@ final class L11nManager
*/ */
public function getNumeric(Localization $l11n, int | float $numeric, string $format = null) : string public function getNumeric(Localization $l11n, int | float $numeric, string $format = null) : string
{ {
return \number_format( return number_format(
$numeric, $numeric,
$l11n->getPrecision()[$format ?? 'medium'], $l11n->getPrecision()[$format ?? 'medium'],
$l11n->getDecimal(), $l11n->getDecimal(),
@ -256,7 +256,7 @@ final class L11nManager
*/ */
public function getPercentage(Localization $l11n, float $percentage, string $format = null) : string public function getPercentage(Localization $l11n, float $percentage, string $format = null) : string
{ {
return \number_format( return number_format(
$percentage, $l11n->getPrecision()[$format ?? 'medium'], $percentage, $l11n->getPrecision()[$format ?? 'medium'],
$l11n->getDecimal(), $l11n->getDecimal(),
$l11n->getThousands() $l11n->getThousands()
@ -282,7 +282,7 @@ final class L11nManager
$symbol ??= $l11n->getCurrency(); $symbol ??= $l11n->getCurrency();
if (\is_float($currency)) { if (\is_float($currency)) {
$currency = (int) ($currency * \pow(10, Money::MAX_DECIMALS)); $currency = (int) ($currency * pow(10, Money::MAX_DECIMALS));
} }
if (!empty($symbol)) { if (!empty($symbol)) {

View File

@ -248,37 +248,37 @@ class Localization implements \JsonSerializable
*/ */
public function loadFromLanguage(string $langCode, string $countryCode = '*') : void public function loadFromLanguage(string $langCode, string $countryCode = '*') : void
{ {
$langCode = \strtolower($langCode); $langCode = strtolower($langCode);
$countryCode = \strtoupper($countryCode); $countryCode = strtoupper($countryCode);
if ($countryCode !== '*' if ($countryCode !== '*'
&& !\is_file(self::DEFINITIONS_PATH . $langCode . '_' . $countryCode . '.json') && !is_file(self::DEFINITIONS_PATH . $langCode . '_' . $countryCode . '.json')
) { ) {
$countryCode = ''; $countryCode = '';
} }
$files = \glob(self::DEFINITIONS_PATH . $langCode . '_' . $countryCode . '*'); $files = glob(self::DEFINITIONS_PATH . $langCode . '_' . $countryCode . '*');
if ($files === false) { if ($files === false) {
$files = []; // @codeCoverageIgnore $files = []; // @codeCoverageIgnore
} }
foreach ($files as $file) { foreach ($files as $file) {
$fileContent = \file_get_contents($file); $fileContent = file_get_contents($file);
if ($fileContent === false) { if ($fileContent === false) {
break; // @codeCoverageIgnore break; // @codeCoverageIgnore
} }
$this->importLocale(\json_decode($fileContent, true)); $this->importLocale(json_decode($fileContent, true));
return; return;
} }
$fileContent = \file_get_contents(self::DEFINITIONS_PATH . 'en_US.json'); $fileContent = file_get_contents(self::DEFINITIONS_PATH . 'en_US.json');
if ($fileContent === false) { if ($fileContent === false) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$this->importLocale(\json_decode($fileContent, true)); $this->importLocale(json_decode($fileContent, true));
} }
/** /**
@ -398,7 +398,7 @@ class Localization implements \JsonSerializable
*/ */
public function setLanguage(string $language) : void public function setLanguage(string $language) : void
{ {
$language = \strtolower($language); $language = strtolower($language);
if (!ISO639x1Enum::isValidValue($language)) { if (!ISO639x1Enum::isValidValue($language)) {
throw new InvalidEnumValue($language); throw new InvalidEnumValue($language);

View File

@ -100,11 +100,11 @@ final class FileLogger implements LoggerInterface
*/ */
public function __construct(string $lpath, bool $verbose = false) public function __construct(string $lpath, bool $verbose = false)
{ {
$path = \realpath(empty($lpath) ? __DIR__ . '/../../' : $lpath); $path = realpath(empty($lpath) ? __DIR__ . '/../../' : $lpath);
$this->verbose = $verbose; $this->verbose = $verbose;
$this->path = \is_dir($lpath) || \strpos($lpath, '.') === false $this->path = is_dir($lpath) || strpos($lpath, '.') === false
? \rtrim($path !== false ? $path : $lpath, '/') . '/' . \date('Y-m-d') . '.log' ? rtrim($path !== false ? $path : $lpath, '/') . '/' . date('Y-m-d') . '.log'
: $lpath; : $lpath;
} }
@ -117,7 +117,7 @@ final class FileLogger implements LoggerInterface
*/ */
private function createFile() : void private function createFile() : void
{ {
if (!$this->created && !\is_file($this->path)) { if (!$this->created && !is_file($this->path)) {
File::create($this->path); File::create($this->path);
$this->created = true; $this->created = true;
} }
@ -153,7 +153,7 @@ final class FileLogger implements LoggerInterface
public function __destruct() public function __destruct()
{ {
if (\is_resource($this->fp)) { if (\is_resource($this->fp)) {
\fclose($this->fp); fclose($this->fp);
} }
} }
@ -180,7 +180,7 @@ final class FileLogger implements LoggerInterface
*/ */
public static function startTimeLog(string $id = '') : bool public static function startTimeLog(string $id = '') : bool
{ {
self::$timings[$id] = ['start' => \microtime(true), 'end' => 0.0, 'time' => 0.0]; self::$timings[$id] = ['start' => microtime(true), 'end' => 0.0, 'time' => 0.0];
return true; return true;
} }
@ -196,7 +196,7 @@ final class FileLogger implements LoggerInterface
*/ */
public static function endTimeLog(string $id = '') : float public static function endTimeLog(string $id = '') : float
{ {
$mtime = \microtime(true); $mtime = microtime(true);
self::$timings[$id]['end'] = $mtime; self::$timings[$id]['end'] = $mtime;
self::$timings[$id]['time'] = $mtime - self::$timings[$id]['start']; self::$timings[$id]['time'] = $mtime - self::$timings[$id]['start'];
@ -222,7 +222,7 @@ final class FileLogger implements LoggerInterface
$replace['{' . $key . '}'] = $val; $replace['{' . $key . '}'] = $val;
} }
$backtrace = \debug_backtrace(); $backtrace = debug_backtrace();
// Removing sensitive config data from logging // Removing sensitive config data from logging
foreach ($backtrace as $key => $value) { foreach ($backtrace as $key => $value) {
@ -231,18 +231,18 @@ final class FileLogger implements LoggerInterface
} }
} }
$backtrace = \json_encode($backtrace); $backtrace = json_encode($backtrace);
$replace['{backtrace}'] = $backtrace; $replace['{backtrace}'] = $backtrace;
$replace['{datetime}'] = \sprintf('%--19s', (new \DateTimeImmutable('NOW'))->format('Y-m-d H:i:s')); $replace['{datetime}'] = sprintf('%--19s', (new \DateTimeImmutable('NOW'))->format('Y-m-d H:i:s'));
$replace['{level}'] = \sprintf('%--12s', $level); $replace['{level}'] = sprintf('%--12s', $level);
$replace['{path}'] = $_SERVER['REQUEST_URI'] ?? 'REQUEST_URI'; $replace['{path}'] = $_SERVER['REQUEST_URI'] ?? 'REQUEST_URI';
$replace['{ip}'] = \sprintf('%--15s', $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0'); $replace['{ip}'] = sprintf('%--15s', $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0');
$replace['{version}'] = \sprintf('%--15s', \PHP_VERSION); $replace['{version}'] = sprintf('%--15s', \PHP_VERSION);
$replace['{os}'] = \sprintf('%--15s', \PHP_OS); $replace['{os}'] = sprintf('%--15s', \PHP_OS);
$replace['{line}'] = \sprintf('%--15s', $context['line'] ?? '?'); $replace['{line}'] = sprintf('%--15s', $context['line'] ?? '?');
return \strtr($message, $replace); return strtr($message, $replace);
} }
/** /**
@ -261,17 +261,17 @@ final class FileLogger implements LoggerInterface
} }
$this->createFile(); $this->createFile();
if (!\is_writable($this->path)) { if (!is_writable($this->path)) {
return; // @codeCoverageIgnore return; // @codeCoverageIgnore
} }
$this->fp = \fopen($this->path, 'a'); $this->fp = fopen($this->path, 'a');
if ($this->fp !== false && \flock($this->fp, \LOCK_EX)) { if ($this->fp !== false && flock($this->fp, \LOCK_EX)) {
\fwrite($this->fp, $message . "\n"); fwrite($this->fp, $message . "\n");
\fflush($this->fp); fflush($this->fp);
\flock($this->fp, \LOCK_UN); flock($this->fp, \LOCK_UN);
\fclose($this->fp); fclose($this->fp);
$this->fp = false; $this->fp = false;
} }
} }
@ -372,36 +372,36 @@ final class FileLogger implements LoggerInterface
{ {
$levels = []; $levels = [];
if (!\is_file($this->path)) { if (!is_file($this->path)) {
return $levels; return $levels;
} }
$this->fp = \fopen($this->path, 'r'); $this->fp = fopen($this->path, 'r');
if ($this->fp === false) { if ($this->fp === false) {
return $levels; // @codeCoverageIgnore return $levels; // @codeCoverageIgnore
} }
\fseek($this->fp, 0); fseek($this->fp, 0);
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
while ($line !== false && $line !== null) { while ($line !== false && $line !== null) {
if (\count($line) < 2) { if (\count($line) < 2) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }
$line[1] = \trim($line[1]); $line[1] = trim($line[1]);
if (!isset($levels[$line[1]])) { if (!isset($levels[$line[1]])) {
$levels[$line[1]] = 0; $levels[$line[1]] = 0;
} }
++$levels[$line[1]]; ++$levels[$line[1]];
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
} }
\fseek($this->fp, 0, \SEEK_END); fseek($this->fp, 0, \SEEK_END);
\fclose($this->fp); fclose($this->fp);
return $levels; return $levels;
} }
@ -419,37 +419,37 @@ final class FileLogger implements LoggerInterface
{ {
$connection = []; $connection = [];
if (!\is_file($this->path)) { if (!is_file($this->path)) {
return $connection; return $connection;
} }
$this->fp = \fopen($this->path, 'r'); $this->fp = fopen($this->path, 'r');
if ($this->fp === false) { if ($this->fp === false) {
return $connection; // @codeCoverageIgnore return $connection; // @codeCoverageIgnore
} }
\fseek($this->fp, 0); fseek($this->fp, 0);
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
while ($line !== false && $line !== null) { while ($line !== false && $line !== null) {
if (\count($line) < 3) { if (\count($line) < 3) {
continue; // @codeCoverageIgnore continue; // @codeCoverageIgnore
} }
$line[2] = \trim($line[2]); $line[2] = trim($line[2]);
if (!isset($connection[$line[2]])) { if (!isset($connection[$line[2]])) {
$connection[$line[2]] = 0; $connection[$line[2]] = 0;
} }
++$connection[$line[2]]; ++$connection[$line[2]];
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
} }
\fseek($this->fp, 0, \SEEK_END); fseek($this->fp, 0, \SEEK_END);
\fclose($this->fp); fclose($this->fp);
\asort($connection); asort($connection);
return \array_slice($connection, 0, $limit); return \array_slice($connection, 0, $limit);
} }
@ -469,19 +469,19 @@ final class FileLogger implements LoggerInterface
$logs = []; $logs = [];
$id = 0; $id = 0;
if (!\is_file($this->path)) { if (!is_file($this->path)) {
return $logs; return $logs;
} }
$this->fp = \fopen($this->path, 'r'); $this->fp = fopen($this->path, 'r');
if ($this->fp === false) { if ($this->fp === false) {
return $logs; // @codeCoverageIgnore return $logs; // @codeCoverageIgnore
} }
\fseek($this->fp, 0); fseek($this->fp, 0);
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
while ($line !== false && $line !== null) { while ($line !== false && $line !== null) {
if ($limit < 1) { if ($limit < 1) {
break; break;
@ -490,25 +490,25 @@ final class FileLogger implements LoggerInterface
++$id; ++$id;
if ($offset > 0) { if ($offset > 0) {
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
--$offset; --$offset;
continue; continue;
} }
foreach ($line as &$value) { foreach ($line as &$value) {
$value = \trim($value); $value = trim($value);
} }
$logs[$id] = $line; $logs[$id] = $line;
--$limit; --$limit;
$line = \fgetcsv($this->fp, 0, ';'); $line = fgetcsv($this->fp, 0, ';');
} }
\fseek($this->fp, 0, \SEEK_END); fseek($this->fp, 0, \SEEK_END);
\fclose($this->fp); fclose($this->fp);
return $logs; return $logs;
} }
@ -527,19 +527,19 @@ final class FileLogger implements LoggerInterface
$log = []; $log = [];
$current = 0; $current = 0;
if (!\is_file($this->path)) { if (!is_file($this->path)) {
return $log; return $log;
} }
$this->fp = \fopen($this->path, 'r'); $this->fp = fopen($this->path, 'r');
if ($this->fp === false) { if ($this->fp === false) {
return $log; // @codeCoverageIgnore return $log; // @codeCoverageIgnore
} }
\fseek($this->fp, 0); fseek($this->fp, 0);
while (($line = \fgetcsv($this->fp, 0, ';')) !== false && $current <= $id) { while (($line = fgetcsv($this->fp, 0, ';')) !== false && $current <= $id) {
++$current; ++$current;
if ($current < $id || $line === null) { if ($current < $id || $line === null) {
@ -547,14 +547,14 @@ final class FileLogger implements LoggerInterface
} }
foreach ($line as $value) { foreach ($line as $value) {
$log[] = \trim($value); $log[] = trim($value);
} }
break; break;
} }
\fseek($this->fp, 0, \SEEK_END); fseek($this->fp, 0, \SEEK_END);
\fclose($this->fp); fclose($this->fp);
return $log; return $log;
} }
@ -573,7 +573,7 @@ final class FileLogger implements LoggerInterface
public function console(string $message, bool $verbose = true, array $context = []) : void public function console(string $message, bool $verbose = true, array $context = []) : void
{ {
if (empty($context)) { if (empty($context)) {
$message = \date('[Y-m-d H:i:s] ') . $message . "\r\n"; $message = date('[Y-m-d H:i:s] ') . $message . "\r\n";
} }
if ($verbose) { if ($verbose) {

View File

@ -71,7 +71,7 @@ final class Beta
return 0.0; return 0.0;
} }
$bGamma = \exp(-self::logBeta($p, $q) + $p * \log($x) + $q * \log(1.0 - $x)); $bGamma = exp(-self::logBeta($p, $q) + $p * log($x) + $q * log(1.0 - $x));
// this uses the symmetry of the beta function // this uses the symmetry of the beta function
return ($x < ($p + 1.0) / ($p + $q + 2.0) return ($x < ($p + 1.0) / ($p + $q + 2.0)
@ -99,7 +99,7 @@ final class Beta
$pMinus = $p - 1.0; $pMinus = $p - 1.0;
$h = 1.0 - $pqSum * $x / $pPlus; $h = 1.0 - $pqSum * $x / $pPlus;
if (\abs($h) < 1.18e-37) { if (abs($h) < 1.18e-37) {
$h = 1.18e-37; $h = 1.18e-37;
} }
@ -112,33 +112,33 @@ final class Beta
$m2 = 2 * $m; $m2 = 2 * $m;
$d = $m * ($q - $m) * $x / (($pMinus + $m2) * ($p + $m2)); $d = $m * ($q - $m) * $x / (($pMinus + $m2) * ($p + $m2));
$h = 1.0 + $d * $h; $h = 1.0 + $d * $h;
if (\abs($h) < 1.18e-37) { if (abs($h) < 1.18e-37) {
$h = 1.18e-37; $h = 1.18e-37;
} }
$h = 1.0 / $h; $h = 1.0 / $h;
$c = 1.0 + $d / $c; $c = 1.0 + $d / $c;
if (\abs($c) < 1.18e-37) { if (abs($c) < 1.18e-37) {
$c = 1.18e-37; $c = 1.18e-37;
} }
$frac *= $h * $c; $frac *= $h * $c;
$d = -($p + $m) * ($pqSum + $m) * $x / (($p + $m2) * ($pPlus + $m2)); $d = -($p + $m) * ($pqSum + $m) * $x / (($p + $m2) * ($pPlus + $m2));
$h = 1.0 + $d * $h; $h = 1.0 + $d * $h;
if (\abs($h) < 1.18e-37) { if (abs($h) < 1.18e-37) {
$h = 1.18e-37; $h = 1.18e-37;
} }
$h = 1.0 / $h; $h = 1.0 / $h;
$c = 1.0 + $d / $c; $c = 1.0 + $d / $c;
if (\abs($c) < 1.18e-37) { if (abs($c) < 1.18e-37) {
$c = 1.18e-37; $c = 1.18e-37;
} }
$delta = $h * $c; $delta = $h * $c;
$frac *= $delta; $frac *= $delta;
++$m; ++$m;
} while ($m < 1000000 && \abs($delta - 1.0) > 8.88e-16); } while ($m < 1000000 && abs($delta - 1.0) > 8.88e-16);
return $frac; return $frac;
} }
@ -172,6 +172,6 @@ final class Beta
*/ */
public static function beta(float $p, float $q) : float public static function beta(float $p, float $q) : float
{ {
return \exp(self::logBeta($p, $q)); return exp(self::logBeta($p, $q));
} }
} }

View File

@ -90,6 +90,6 @@ final class Fibonacci
*/ */
public static function binet(int $n) : int public static function binet(int $n) : int
{ {
return (int) (((1 + \sqrt(5)) ** $n - (1 - \sqrt(5)) ** $n) / (2 ** $n * \sqrt(5))); return (int) (((1 + sqrt(5)) ** $n - (1 - sqrt(5)) ** $n) / (2 ** $n * sqrt(5)));
} }
} }

View File

@ -73,11 +73,11 @@ final class Functions
*/ */
public static function binomialCoefficient(int $n, int $k) : int public static function binomialCoefficient(int $n, int $k) : int
{ {
$max = \max([$k, $n - $k]); $max = max([$k, $n - $k]);
$min = \min([$k, $n - $k]); $min = min([$k, $n - $k]);
$fact = 1; $fact = 1;
$range = \array_reverse(\range(1, $min)); $range = array_reverse(range(1, $min));
for ($i = $max + 1; $i < $n + 1; ++$i) { for ($i = $max + 1; $i < $n + 1; ++$i) {
$div = 1; $div = 1;
@ -232,7 +232,7 @@ final class Functions
*/ */
public static function getRelativeDegree(int $value, int $length, int $start = 0) : int public static function getRelativeDegree(int $value, int $length, int $start = 0) : int
{ {
return \abs(self::mod($value - $start, $length)); return abs(self::mod($value - $start, $length));
} }
/** /**
@ -249,7 +249,7 @@ final class Functions
*/ */
public static function getErf(float $value) : float public static function getErf(float $value) : float
{ {
if (\abs($value) > 2.2) { if (abs($value) > 2.2) {
return 1 - self::getErfc($value); return 1 - self::getErfc($value);
} }
@ -268,9 +268,9 @@ final class Functions
$sum += $term / (2 * $i + 1); $sum += $term / (2 * $i + 1);
++$i; ++$i;
} while ($sum !== 0.0 && \abs($term / $sum) > 0.0000001); } while ($sum !== 0.0 && abs($term / $sum) > 0.0000001);
return 2 / \sqrt(\M_PI) * $sum; return 2 / sqrt(\M_PI) * $sum;
} }
/** /**
@ -287,7 +287,7 @@ final class Functions
*/ */
public static function getErfc(float $value) : float public static function getErfc(float $value) : float
{ {
if (\abs($value) <= 2.2) { if (abs($value) <= 2.2) {
return 1 - self::getErf($value); return 1 - self::getErf($value);
} }
@ -311,9 +311,9 @@ final class Functions
$n += 0.5; $n += 0.5;
$q1 = $q2; $q1 = $q2;
$q2 = $b / $d; $q2 = $b / $d;
} while (\abs($q1 - $q2) / $q2 > 0.0000001); } while (abs($q1 - $q2) / $q2 > 0.0000001);
return 1 / \sqrt(\M_PI) * \exp(-$value * $value) * $q2; return 1 / sqrt(\M_PI) * exp(-$value * $value) * $q2;
} }
/** /**
@ -332,8 +332,8 @@ final class Functions
public static function generalizedHypergeometricFunction(array $a, array $b, float $z) : float public static function generalizedHypergeometricFunction(array $a, array $b, float $z) : float
{ {
$sum = 0.0; $sum = 0.0;
$aProd = \array_fill(0, 20, []); $aProd = array_fill(0, 20, []);
$bProd = \array_fill(0, 20, []); $bProd = array_fill(0, 20, []);
for ($n = 0; $n < 20; ++$n) { for ($n = 0; $n < 20; ++$n) {
foreach ($a as $key => $value) { foreach ($a as $key => $value) {
@ -352,7 +352,7 @@ final class Functions
} }
} }
$temp = \array_product($aProd[$n]) / \array_product($bProd[$n]); $temp = array_product($aProd[$n]) / array_product($bProd[$n]);
$sum += $temp * $z ** $n / self::fact($n); $sum += $temp * $z ** $n / self::fact($n);
} }

View File

@ -45,7 +45,7 @@ final class Gamma
*/ */
public static function gamma(int | float $z) : float public static function gamma(int | float $z) : float
{ {
return \exp(self::logGamma($z)); return exp(self::logGamma($z));
} }
/** /**
@ -71,7 +71,7 @@ final class Gamma
public static function lanczosApproximationReal(int | float $z) : float public static function lanczosApproximationReal(int | float $z) : float
{ {
if ($z < 0.5) { if ($z < 0.5) {
return \M_PI / (\sin(\M_PI * $z) * self::lanczosApproximationReal(1 - $z)); return \M_PI / (sin(\M_PI * $z) * self::lanczosApproximationReal(1 - $z));
} }
--$z; --$z;
@ -82,7 +82,7 @@ final class Gamma
$a += self::LANCZOSAPPROXIMATION[$i] / ($z + $i); $a += self::LANCZOSAPPROXIMATION[$i] / ($z + $i);
} }
return \sqrt(2 * \M_PI) * \pow($t, $z + 0.5) * \exp(-$t) * $a; return sqrt(2 * \M_PI) * pow($t, $z + 0.5) * exp(-$t) * $a;
} }
/** /**
@ -96,7 +96,7 @@ final class Gamma
*/ */
public static function stirlingApproximation(int | float $x) : float public static function stirlingApproximation(int | float $x) : float
{ {
return \sqrt(2.0 * \M_PI / $x) * \pow($x / \M_E, $x); return sqrt(2.0 * \M_PI / $x) * pow($x / \M_E, $x);
} }
/** /**
@ -111,10 +111,10 @@ final class Gamma
public static function spougeApproximation(int | float $z) : float public static function spougeApproximation(int | float $z) : float
{ {
$k1_fact = 1.0; $k1_fact = 1.0;
$c = [\sqrt(2.0 * \M_PI)]; $c = [sqrt(2.0 * \M_PI)];
for ($k = 1; $k < 12; ++$k) { for ($k = 1; $k < 12; ++$k) {
$c[$k] = \exp(12 - $k) * \pow(12 - $k, $k - 0.5) / $k1_fact; $c[$k] = exp(12 - $k) * pow(12 - $k, $k - 0.5) / $k1_fact;
$k1_fact *= -$k; $k1_fact *= -$k;
} }
@ -123,7 +123,7 @@ final class Gamma
$accm += $c[$k] / ($z + $k); $accm += $c[$k] / ($z + $k);
} }
$accm *= \exp(-$z - 12) * \pow($z + 12, $z + 0.5); $accm *= exp(-$z - 12) * pow($z + 12, $z + 0.5);
return $accm / $z; return $accm / $z;
} }
@ -149,14 +149,14 @@ final class Gamma
$y = $z; $y = $z;
$temp = $z + 5.5 - ($z + 0.5) * \log($z + 5.5); $temp = $z + 5.5 - ($z + 0.5) * log($z + 5.5);
$sum = 1.000000000190015; $sum = 1.000000000190015;
for ($i = 0; $i < 6; ++$i) { for ($i = 0; $i < 6; ++$i) {
$sum += $approx[$i] / ++$y; $sum += $approx[$i] / ++$y;
} }
return -$temp + \log(\sqrt(2 * \M_PI) * $sum / $z); return -$temp + log(sqrt(2 * \M_PI) * $sum / $z);
} }
/** /**
@ -187,7 +187,7 @@ final class Gamma
*/ */
public static function incompleteGammaFirst(float $a, float $x) : float public static function incompleteGammaFirst(float $a, float $x) : float
{ {
return self::regularizedGamma($a, $x) * \exp(self::logGamma($a)); return self::regularizedGamma($a, $x) * exp(self::logGamma($a));
} }
/** /**
@ -202,7 +202,7 @@ final class Gamma
*/ */
public static function incompleteGammaSecond(float $a, float $x) : float public static function incompleteGammaSecond(float $a, float $x) : float
{ {
return \exp(self::logGamma($a)) - self::regularizedGamma($a, $x) * \exp(self::logGamma($a)); return exp(self::logGamma($a)) - self::regularizedGamma($a, $x) * exp(self::logGamma($a));
} }
/** /**
@ -252,7 +252,7 @@ final class Gamma
$sum += $del; $sum += $del;
if ($del < $sum * 2.22e-16) { if ($del < $sum * 2.22e-16) {
return $sum * \exp(-$x + $a * \log($x) - self::logGamma($a)); return $sum * exp(-$x + $a * log($x) - self::logGamma($a));
} }
} }
@ -280,17 +280,17 @@ final class Gamma
$h = $d; $h = $d;
$del = 0.0; $del = 0.0;
for ($i = 1; $i < 150 && \abs($del - 1.0) > 2.22e-16; ++$i) { for ($i = 1; $i < 150 && abs($del - 1.0) > 2.22e-16; ++$i) {
$an = - $i * ($i - $a); $an = - $i * ($i - $a);
$b += 2.0; $b += 2.0;
$d = $an * $d + $b; $d = $an * $d + $b;
$c = $b + $an / $c; $c = $b + $an / $c;
if (\abs($c) < 1.18e-37) { if (abs($c) < 1.18e-37) {
$c = 1.18e-37; $c = 1.18e-37;
} }
if (\abs($d) < 1.18e-37) { if (abs($d) < 1.18e-37) {
$d = 1.18e-37; $d = 1.18e-37;
} }
@ -299,6 +299,6 @@ final class Gamma
$h *= $del; $h *= $del;
} }
return \exp(-$x + $a * \log($x) - self::logGamma($a)) * $h; return exp(-$x + $a * log($x) - self::logGamma($a)) * $h;
} }
} }

View File

@ -49,7 +49,7 @@ final class MonotoneChain
return $points; return $points;
} }
\uasort($points, [self::class, 'sort']); uasort($points, [self::class, 'sort']);
$k = 0; $k = 0;
$result = []; $result = [];
@ -72,7 +72,7 @@ final class MonotoneChain
$result[$k++] = $points[$i]; $result[$k++] = $points[$i];
} }
\ksort($result); ksort($result);
/** @return array<int, array{x:int|float, y:int|float}> */ /** @return array<int, array{x:int|float, y:int|float}> */
return \array_slice($result, 0, $k - 1); return \array_slice($result, 0, $k - 1);

View File

@ -63,7 +63,7 @@ final class Circle implements D2ShapeInterface
*/ */
public static function getRadiusBySurface(float $surface) : float public static function getRadiusBySurface(float $surface) : float
{ {
return \sqrt($surface / \M_PI); return sqrt($surface / \M_PI);
} }
/** /**

View File

@ -61,6 +61,6 @@ final class Ellipse implements D2ShapeInterface
*/ */
public static function getPerimeter(float $a, float $b) : float public static function getPerimeter(float $a, float $b) : float
{ {
return \M_PI * ($a + $b) * (3 * ($a - $b) ** 2 / (($a + $b) ** 2 * (\sqrt(-3 * ($a - $b) ** 2 / (($a + $b) ** 2) + 4) + 10)) + 1); return \M_PI * ($a + $b) * (3 * ($a - $b) ** 2 / (($a + $b) ** 2 * (sqrt(-3 * ($a - $b) ** 2 / (($a + $b) ** 2) + 4) + 10)) + 1);
} }
} }

View File

@ -106,26 +106,26 @@ final class Polygon implements D2ShapeInterface
$vertex1 = $polygon[$i - 1]; $vertex1 = $polygon[$i - 1];
$vertex2 = $polygon[$i]; $vertex2 = $polygon[$i];
if (\abs($vertex1['y'] - $vertex2['y']) < self::EPSILON if (abs($vertex1['y'] - $vertex2['y']) < self::EPSILON
&& \abs($vertex1['y'] - $point['y']) < self::EPSILON && abs($vertex1['y'] - $point['y']) < self::EPSILON
&& $point['x'] > \min($vertex1['x'], $vertex2['x']) && $point['x'] > min($vertex1['x'], $vertex2['x'])
&& $point['x'] < \max($vertex1['x'], $vertex2['x']) && $point['x'] < max($vertex1['x'], $vertex2['x'])
) { ) {
return 0; // boundary return 0; // boundary
} }
if ($point['y'] > \min($vertex1['y'], $vertex2['y']) if ($point['y'] > min($vertex1['y'], $vertex2['y'])
&& $point['y'] <= \max($vertex1['y'], $vertex2['y']) && $point['y'] <= max($vertex1['y'], $vertex2['y'])
&& $point['x'] <= \max($vertex1['x'], $vertex2['x']) && $point['x'] <= max($vertex1['x'], $vertex2['x'])
&& \abs($vertex1['y'] - $vertex2['y']) >= self::EPSILON && abs($vertex1['y'] - $vertex2['y']) >= self::EPSILON
) { ) {
$xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x']; $xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x'];
if (\abs($xinters - $point['x']) < self::EPSILON) { if (abs($xinters - $point['x']) < self::EPSILON) {
return 0; // boundary return 0; // boundary
} }
if (\abs($vertex1['x'] - $vertex2['x']) < self::EPSILON || $point['x'] < $xinters) { if (abs($vertex1['x'] - $vertex2['x']) < self::EPSILON || $point['x'] < $xinters) {
++$countIntersect; ++$countIntersect;
} }
} }
@ -151,7 +151,7 @@ final class Polygon implements D2ShapeInterface
private static function isOnVertex(array $point, array $polygon) : bool private static function isOnVertex(array $point, array $polygon) : bool
{ {
foreach ($polygon as $vertex) { foreach ($polygon as $vertex) {
if (\abs($point['x'] - $vertex['x']) < self::EPSILON && \abs($point['y'] - $vertex['y']) < self::EPSILON) { if (abs($point['x'] - $vertex['x']) < self::EPSILON && abs($point['y'] - $vertex['y']) < self::EPSILON) {
return true; return true;
} }
} }
@ -192,7 +192,7 @@ final class Polygon implements D2ShapeInterface
*/ */
public function getSurface() : float public function getSurface() : float
{ {
return \abs($this->getSignedSurface()); return abs($this->getSignedSurface());
} }
/** /**
@ -227,10 +227,10 @@ final class Polygon implements D2ShapeInterface
public function getPerimeter() : float public function getPerimeter() : float
{ {
$count = \count($this->coord); $count = \count($this->coord);
$perimeter = \sqrt(($this->coord[0]['x'] - $this->coord[$count - 1]['x']) ** 2 + ($this->coord[0]['y'] - $this->coord[$count - 1]['y']) ** 2); $perimeter = sqrt(($this->coord[0]['x'] - $this->coord[$count - 1]['x']) ** 2 + ($this->coord[0]['y'] - $this->coord[$count - 1]['y']) ** 2);
for ($i = 0; $i < $count - 1; ++$i) { for ($i = 0; $i < $count - 1; ++$i) {
$perimeter += \sqrt(($this->coord[$i + 1]['x'] - $this->coord[$i]['x']) ** 2 + ($this->coord[$i + 1]['y'] - $this->coord[$i]['y']) ** 2); $perimeter += sqrt(($this->coord[$i + 1]['x'] - $this->coord[$i]['x']) ** 2 + ($this->coord[$i + 1]['y'] - $this->coord[$i]['y']) ** 2);
} }
return $perimeter; return $perimeter;
@ -278,7 +278,7 @@ final class Polygon implements D2ShapeInterface
*/ */
public static function getRegularAreaByLength(float $length, int $sides) : float public static function getRegularAreaByLength(float $length, int $sides) : float
{ {
return $length ** 2 * $sides / (4 * \tan(\M_PI / $sides)); return $length ** 2 * $sides / (4 * tan(\M_PI / $sides));
} }
/** /**
@ -293,6 +293,6 @@ final class Polygon implements D2ShapeInterface
*/ */
public static function getRegularAreaByRadius(float $r, int $sides) : float public static function getRegularAreaByRadius(float $r, int $sides) : float
{ {
return $r ** 2 * $sides * \tan(\M_PI / $sides); return $r ** 2 * $sides * tan(\M_PI / $sides);
} }
} }

View File

@ -39,8 +39,8 @@ final class Quadrilateral implements D2ShapeInterface
public static function getSurfaceFromSidesAndAngle(float $a, float $b, float $c, float $d, float $alpha) : float public static function getSurfaceFromSidesAndAngle(float $a, float $b, float $c, float $d, float $alpha) : float
{ {
$s = ($a + $b + $c + $d) / 2; $s = ($a + $b + $c + $d) / 2;
$gamma = \acos(($c ** 2 + $d ** 2 - $a ** 2 - $b ** 2 + 2 * $a * $b * \cos(\deg2rad($alpha))) / (2 * $c * $d)); $gamma = acos(($c ** 2 + $d ** 2 - $a ** 2 - $b ** 2 + 2 * $a * $b * cos(deg2rad($alpha))) / (2 * $c * $d));
return \sqrt(($s - $a) * ($s - $b) * ($s - $c) * ($s - $d) - $a * $b * $c * $d * \cos((\deg2rad($alpha) + $gamma) / 2) ** 2); return sqrt(($s - $a) * ($s - $b) * ($s - $c) * ($s - $d) - $a * $b * $c * $d * cos((deg2rad($alpha) + $gamma) / 2) ** 2);
} }
} }

View File

@ -66,6 +66,6 @@ final class Rectangle implements D2ShapeInterface
*/ */
public static function getDiagonal(float $a, float $b) : float public static function getDiagonal(float $a, float $b) : float
{ {
return \sqrt($a * $a + $b * $b); return sqrt($a * $a + $b * $b);
} }
} }

View File

@ -92,6 +92,6 @@ final class Triangle implements D2ShapeInterface
$hypot += $val * $val; $hypot += $val * $val;
} }
return \sqrt($hypot); return sqrt($hypot);
} }
} }

View File

@ -51,7 +51,7 @@ final class Cone implements D3ShapeInterface
*/ */
public static function getSurface(float $r, float $h) : float public static function getSurface(float $r, float $h) : float
{ {
return \M_PI * $r * ($r + \sqrt($h ** 2 + $r ** 2)); return \M_PI * $r * ($r + sqrt($h ** 2 + $r ** 2));
} }
/** /**
@ -66,7 +66,7 @@ final class Cone implements D3ShapeInterface
*/ */
public static function getSlantHeight(float $r, float $h) : float public static function getSlantHeight(float $r, float $h) : float
{ {
return \sqrt($h ** 2 + $r ** 2); return sqrt($h ** 2 + $r ** 2);
} }
/** /**

View File

@ -53,7 +53,7 @@ final class RectangularPyramid implements D3ShapeInterface
*/ */
public static function getSurface(float $a, float $b, float $h) : float public static function getSurface(float $a, float $b, float $h) : float
{ {
return $a * $b + $a * \sqrt(($b / 2) ** 2 + $h ** 2) + $b * \sqrt(($a / 2) ** 2 + $h ** 2); return $a * $b + $a * sqrt(($b / 2) ** 2 + $h ** 2) + $b * sqrt(($a / 2) ** 2 + $h ** 2);
} }
/** /**
@ -69,6 +69,6 @@ final class RectangularPyramid implements D3ShapeInterface
*/ */
public static function getLateralSurface(float $a, float $b, float $h) : float public static function getLateralSurface(float $a, float $b, float $h) : float
{ {
return $a * \sqrt(($b / 2) ** 2 + $h ** 2) + $b * \sqrt(($a / 2) ** 2 + $h ** 2); return $a * sqrt(($b / 2) ** 2 + $h ** 2) + $b * sqrt(($a / 2) ** 2 + $h ** 2);
} }
} }

View File

@ -59,18 +59,18 @@ final class Sphere implements D3ShapeInterface
*/ */
public static function distance2PointsOnSphere(float $latStart, float $longStart, float $latEnd, float $longEnd, float $radius = 6371000.0) : float public static function distance2PointsOnSphere(float $latStart, float $longStart, float $latEnd, float $longEnd, float $radius = 6371000.0) : float
{ {
$latFrom = \deg2rad($latStart); $latFrom = deg2rad($latStart);
$lonFrom = \deg2rad($longStart); $lonFrom = deg2rad($longStart);
$latTo = \deg2rad($latEnd); $latTo = deg2rad($latEnd);
$lonTo = \deg2rad($longEnd); $lonTo = deg2rad($longEnd);
//$latDelta = $latTo - $latFrom; //$latDelta = $latTo - $latFrom;
$lonDelta = $lonTo - $lonFrom; $lonDelta = $lonTo - $lonFrom;
$a = \pow(\cos($latTo) * \sin($lonDelta), 2) + \pow(\cos($latFrom) * \sin($latTo) - \sin($latFrom) * \cos($latTo) * \cos($lonDelta), 2); $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
$b = \sin($latFrom) * \sin($latTo) + \cos($latFrom) * \cos($latTo) * \cos($lonDelta); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);
$angle = \atan2(\sqrt($a), $b); $angle = atan2(sqrt($a), $b);
// Approximation (very good for short distances) // Approximation (very good for short distances)
// $angle = 2 * asin(\sqrt(\pow(\sin($latDelta / 2), 2) + \cos($latFrom) * \cos($latTo) * \pow(\sin($lonDelta / 2), 2))); // $angle = 2 * asin(\sqrt(\pow(\sin($latDelta / 2), 2) + \cos($latFrom) * \cos($latTo) * \pow(\sin($lonDelta / 2), 2)));
@ -116,7 +116,7 @@ final class Sphere implements D3ShapeInterface
*/ */
public static function getRadiusByVolume(float $v) : float public static function getRadiusByVolume(float $v) : float
{ {
return \pow($v * 3 / (4 * \M_PI), 1 / 3); return pow($v * 3 / (4 * \M_PI), 1 / 3);
} }
/** /**
@ -147,7 +147,7 @@ final class Sphere implements D3ShapeInterface
*/ */
public static function getRadiusBySurface(float $S) : float public static function getRadiusBySurface(float $S) : float
{ {
return \sqrt($S / (4 * \M_PI)); return sqrt($S / (4 * \M_PI));
} }
/** /**

View File

@ -35,7 +35,7 @@ final class Tetrahedron implements D3ShapeInterface
*/ */
public static function getVolume(float $a) : float public static function getVolume(float $a) : float
{ {
return $a ** 3 / (6 * \sqrt(2)); return $a ** 3 / (6 * sqrt(2));
} }
/** /**
@ -49,7 +49,7 @@ final class Tetrahedron implements D3ShapeInterface
*/ */
public static function getSurface(float $a) : float public static function getSurface(float $a) : float
{ {
return \sqrt(3) * $a ** 2; return sqrt(3) * $a ** 2;
} }
/** /**
@ -63,6 +63,6 @@ final class Tetrahedron implements D3ShapeInterface
*/ */
public static function getFaceArea(float $a) : float public static function getFaceArea(float $a) : float
{ {
return \sqrt(3) / 4 * $a ** 2; return sqrt(3) / 4 * $a ** 2;
} }
} }

View File

@ -73,7 +73,7 @@ final class CholeskyDecomposition
if ($i === $j) { if ($i === $j) {
if ($sum >= 0) { if ($sum >= 0) {
$this->L[$i][$i] = \sqrt($sum); $this->L[$i][$i] = sqrt($sum);
} else { } else {
$this->isSpd = false; $this->isSpd = false;
} }

View File

@ -159,7 +159,7 @@ final class EigenvalueDecomposition
$h = 0.0; $h = 0.0;
for ($k = 0; $k < $i; ++$k) { for ($k = 0; $k < $i; ++$k) {
$scale += \abs($this->D[$k]); $scale += abs($this->D[$k]);
} }
if ($scale == 0) { if ($scale == 0) {
@ -176,7 +176,7 @@ final class EigenvalueDecomposition
} }
$f = $this->D[$i - 1]; $f = $this->D[$i - 1];
$g = $f > 0 ? -\sqrt($h) : \sqrt($h); $g = $f > 0 ? -sqrt($h) : sqrt($h);
$this->E[$i] = $scale * $g; $this->E[$i] = $scale * $g;
$h -= $f * $g; $h -= $f * $g;
@ -282,11 +282,11 @@ final class EigenvalueDecomposition
$eps = 0.00001; $eps = 0.00001;
for ($l = 0; $l < $this->m; ++$l) { for ($l = 0; $l < $this->m; ++$l) {
$tst1 = \max($tst1, \abs($this->D[$l]) + \abs($this->E[$l])); $tst1 = max($tst1, abs($this->D[$l]) + abs($this->E[$l]));
$m = $l; $m = $l;
while ($m < $this->m) { while ($m < $this->m) {
if (\abs($this->E[$m]) <= $eps * $tst1) { if (abs($this->E[$m]) <= $eps * $tst1) {
break; break;
} }
@ -344,7 +344,7 @@ final class EigenvalueDecomposition
$p = -$s * $s2 * $c3 * $el1 * $this->E[$l] / $dl1; $p = -$s * $s2 * $c3 * $el1 * $this->E[$l] / $dl1;
$this->E[$l] = $s * $p; $this->E[$l] = $s * $p;
$this->D[$l] = $c * $p; $this->D[$l] = $c * $p;
} while (\abs($this->E[$l]) > $eps * $tst1); } while (abs($this->E[$l]) > $eps * $tst1);
} }
$this->D[$l] += $f; $this->D[$l] += $f;
@ -391,7 +391,7 @@ final class EigenvalueDecomposition
$scale = 0.0; $scale = 0.0;
for ($i = $m; $i <= $high; ++$i) { for ($i = $m; $i <= $high; ++$i) {
$scale += \abs($this->H[$i][$m - 1]); $scale += abs($this->H[$i][$m - 1]);
} }
if ($scale != 0) { if ($scale != 0) {
@ -401,7 +401,7 @@ final class EigenvalueDecomposition
$h += $this->ort[$i] * $this->ort[$i]; $h += $this->ort[$i] * $this->ort[$i];
} }
$g = $this->ort[$m] > 0 ? -\sqrt($h) : \sqrt($h); $g = $this->ort[$m] > 0 ? -sqrt($h) : sqrt($h);
$h -= $this->ort[$m] * $g; $h -= $this->ort[$m] * $g;
$this->ort[$m] -= $g; $this->ort[$m] -= $g;
@ -478,7 +478,7 @@ final class EigenvalueDecomposition
$r = 0.0; $r = 0.0;
$d = 0.0; $d = 0.0;
if (\abs($yr) > \abs($yi)) { if (abs($yr) > abs($yi)) {
$r = $yi / $yr; $r = $yi / $yr;
$d = $yr + $r * $yi; $d = $yr + $r * $yi;
@ -521,8 +521,8 @@ final class EigenvalueDecomposition
$this->E[$i] = 0.0; $this->E[$i] = 0.0;
} }
for ($j = \max($i - 1, 0); $j < $nn; ++$j) { for ($j = max($i - 1, 0); $j < $nn; ++$j) {
$norm += \abs($this->H[$i][$j]); $norm += abs($this->H[$i][$j]);
} }
} }
@ -530,12 +530,12 @@ final class EigenvalueDecomposition
while ($n >= $low) { while ($n >= $low) {
$l = $n; $l = $n;
while ($l > $low) { while ($l > $low) {
$s = \abs($this->H[$l - 1][$l - 1]) + \abs($this->H[$l][$l]); $s = abs($this->H[$l - 1][$l - 1]) + abs($this->H[$l][$l]);
if ($s == 0) { if ($s == 0) {
$s = $norm; $s = $norm;
} }
if (\abs($this->H[$l][$l - 1]) < $eps * $s) { if (abs($this->H[$l][$l - 1]) < $eps * $s) {
break; break;
} }
@ -553,7 +553,7 @@ final class EigenvalueDecomposition
$w = $this->H[$n][$n - 1] * $this->H[$n - 1][$n]; $w = $this->H[$n][$n - 1] * $this->H[$n - 1][$n];
$p = ($this->H[$n - 1][$n - 1] - $this->H[$n][$n]) / 2.0; $p = ($this->H[$n - 1][$n - 1] - $this->H[$n][$n]) / 2.0;
$q = $p * $p + $w; $q = $p * $p + $w;
$z = \sqrt(\abs($q)); $z = sqrt(abs($q));
$this->H[$n][$n] += $exshift; $this->H[$n][$n] += $exshift;
$this->H[$n - 1][$n - 1] += $exshift; $this->H[$n - 1][$n - 1] += $exshift;
@ -568,10 +568,10 @@ final class EigenvalueDecomposition
$this->E[$n] = 0.0; $this->E[$n] = 0.0;
$x = $this->H[$n][$n - 1]; $x = $this->H[$n][$n - 1];
$s = \abs($x) + \abs($z); $s = abs($x) + abs($z);
$p = $x / $s; $p = $x / $s;
$q = $z / $s; $q = $z / $s;
$r = \sqrt($p * $p + $q * $q); $r = sqrt($p * $p + $q * $q);
$p /= $r; $p /= $r;
$q /= $r; $q /= $r;
@ -617,7 +617,7 @@ final class EigenvalueDecomposition
$this->H[$i][$i] -= $x; $this->H[$i][$i] -= $x;
} }
$s = \abs($this->H[$n][$n - 1]) + \abs($this->H[$n - 1][$n - 2]); $s = abs($this->H[$n][$n - 1]) + abs($this->H[$n - 1][$n - 2]);
$x = 0.75 * $s; $x = 0.75 * $s;
$y = $x; $y = $x;
$w = -0.4375 * $s * $s; $w = -0.4375 * $s * $s;
@ -628,7 +628,7 @@ final class EigenvalueDecomposition
$s = $s * $s + $w; $s = $s * $s + $w;
if ($s > 0) { if ($s > 0) {
$s = $y < $x ? -\sqrt($s) : \sqrt($s); $s = $y < $x ? -sqrt($s) : sqrt($s);
$s = $x - $w / (($y - $x) / 2.0 + $s); $s = $x - $w / (($y - $x) / 2.0 + $s);
for ($i = $low; $i <= $n; ++$i) { for ($i = $low; $i <= $n; ++$i) {
@ -650,13 +650,13 @@ final class EigenvalueDecomposition
$p = ($r * $s - $w) / $this->H[$m + 1][$m] + $this->H[$m][$m + 1]; $p = ($r * $s - $w) / $this->H[$m + 1][$m] + $this->H[$m][$m + 1];
$q = $this->H[$m + 1][$m + 1] - $z - $r - $s; $q = $this->H[$m + 1][$m + 1] - $z - $r - $s;
$r = $this->H[$m + 2][$m + 1]; $r = $this->H[$m + 2][$m + 1];
$s = \abs($p) + \abs($q) + \abs($r); $s = abs($p) + abs($q) + abs($r);
$p /= $s; $p /= $s;
$q /= $s; $q /= $s;
$r /= $s; $r /= $s;
if ($m === $l if ($m === $l
|| \abs($this->H[$m][$m - 1]) * (\abs($q) + \abs($r)) < $eps * (\abs($p) * (\abs($this->H[$m - 1][$m - 1]) + \abs($z) + \abs($this->H[$m + 1][$m + 1]))) || abs($this->H[$m][$m - 1]) * (abs($q) + abs($r)) < $eps * (abs($p) * (abs($this->H[$m - 1][$m - 1]) + abs($z) + abs($this->H[$m + 1][$m + 1])))
) { ) {
break; break;
} }
@ -679,7 +679,7 @@ final class EigenvalueDecomposition
$p = $this->H[$k][$k - 1]; $p = $this->H[$k][$k - 1];
$q = $this->H[$k + 1][$k - 1]; $q = $this->H[$k + 1][$k - 1];
$r = ($notlast ? $this->H[$k + 2][$k - 1] : 0.0); $r = ($notlast ? $this->H[$k + 2][$k - 1] : 0.0);
$x = \abs($p) + \abs($q) + \abs($r); $x = abs($p) + abs($q) + abs($r);
if ($x == 0) { if ($x == 0) {
continue; continue;
@ -690,7 +690,7 @@ final class EigenvalueDecomposition
$r /= $x; $r /= $x;
} }
$s = $p < 0 ? -\sqrt($p * $p + $q * $q + $r * $r) : \sqrt($p * $p + $q * $q + $r * $r); $s = $p < 0 ? -sqrt($p * $p + $q * $q + $r * $r) : sqrt($p * $p + $q * $q + $r * $r);
if ($s == 0) { if ($s == 0) {
continue; continue;
@ -720,7 +720,7 @@ final class EigenvalueDecomposition
$this->H[$k + 1][$j] = $this->H[$k + 1][$j] - $p * $y; $this->H[$k + 1][$j] = $this->H[$k + 1][$j] - $p * $y;
} }
$min = \min($n, $k + 3); $min = min($n, $k + 3);
for ($i = 0; $i <= $min; ++$i) { for ($i = 0; $i <= $min; ++$i) {
$p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k + 1]; $p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k + 1];
@ -781,10 +781,10 @@ final class EigenvalueDecomposition
$q = ($this->D[$i] - $p) * ($this->D[$i] - $p) + $this->E[$i] * $this->E[$i]; $q = ($this->D[$i] - $p) * ($this->D[$i] - $p) + $this->E[$i] * $this->E[$i];
$t = ($x * $s - $z * $r) / $q; $t = ($x * $s - $z * $r) / $q;
$this->H[$i][$n] = $t; $this->H[$i][$n] = $t;
$this->H[$i + 1][$n] = \abs($x) > \abs($z) ? (-$r - $w * $t) / $x : (-$s - $y * $t) / $z; $this->H[$i + 1][$n] = abs($x) > abs($z) ? (-$r - $w * $t) / $x : (-$s - $y * $t) / $z;
} }
$t = \abs($this->H[$i][$n]); $t = abs($this->H[$i][$n]);
if (($eps * $t) * $t > 1) { if (($eps * $t) * $t > 1) {
for ($j = $i; $j <= $n; ++$j) { for ($j = $i; $j <= $n; ++$j) {
$this->H[$j][$n] = $this->H[$j][$n] / $t; $this->H[$j][$n] = $this->H[$j][$n] / $t;
@ -795,7 +795,7 @@ final class EigenvalueDecomposition
} elseif ($q < 0) { } elseif ($q < 0) {
$l = $n - 1; $l = $n - 1;
if (\abs($this->H[$n][$n - 1]) > \abs($this->H[$n - 1][$n])) { if (abs($this->H[$n][$n - 1]) > abs($this->H[$n - 1][$n])) {
$this->H[$n - 1][$n - 1] = $q / $this->H[$n][$n - 1]; $this->H[$n - 1][$n - 1] = $q / $this->H[$n][$n - 1];
$this->H[$n - 1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n - 1]; $this->H[$n - 1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n - 1];
} else { } else {
@ -836,7 +836,7 @@ final class EigenvalueDecomposition
$vi = ($this->D[$i] - $p) * 2.0 * $q; $vi = ($this->D[$i] - $p) * 2.0 * $q;
if ($vr == 0 & $vi == 0) { if ($vr == 0 & $vi == 0) {
$vr = $eps * $norm * (\abs($w) + \abs($q) + \abs($x) + \abs($y) + \abs($z)); $vr = $eps * $norm * (abs($w) + abs($q) + abs($x) + abs($y) + abs($z));
} }
$this->cdiv($x * $r - $z * $ra + $q * $sa, $x * $s - $z * $sa - $q * $ra, $vr, $vi); $this->cdiv($x * $r - $z * $ra + $q * $sa, $x * $s - $z * $sa - $q * $ra, $vr, $vi);
@ -844,7 +844,7 @@ final class EigenvalueDecomposition
$this->H[$i][$n - 1] = $this->cdivr; $this->H[$i][$n - 1] = $this->cdivr;
$this->H[$i][$n] = $this->cdivi; $this->H[$i][$n] = $this->cdivi;
if (\abs($x) > (\abs($z) + \abs($q))) { if (abs($x) > (abs($z) + abs($q))) {
$this->H[$i + 1][$n - 1] = (-$ra - $w * $this->H[$i][$n - 1] + $q * $this->H[$i][$n]) / $x; $this->H[$i + 1][$n - 1] = (-$ra - $w * $this->H[$i][$n - 1] + $q * $this->H[$i][$n]) / $x;
$this->H[$i + 1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n - 1]) / $x; $this->H[$i + 1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n - 1]) / $x;
} else { } else {
@ -854,7 +854,7 @@ final class EigenvalueDecomposition
} }
} }
$t = \max(\abs($this->H[$i][$n - 1]), \abs($this->H[$i][$n])); $t = max(abs($this->H[$i][$n - 1]), abs($this->H[$i][$n]));
if (($eps * $t) * $t > 1) { if (($eps * $t) * $t > 1) {
for ($j = $i; $j <= $n; ++$j) { for ($j = $i; $j <= $n; ++$j) {
$this->H[$j][$n - 1] = $this->H[$j][$n - 1] / $t; $this->H[$j][$n - 1] = $this->H[$j][$n - 1] / $t;
@ -878,7 +878,7 @@ final class EigenvalueDecomposition
for ($i = $low; $i <= $high; ++$i) { for ($i = $low; $i <= $high; ++$i) {
$z = 0.0; $z = 0.0;
$min = \min($j, $high); $min = min($j, $high);
for ($k = $low; $k <= $min; ++$k) { for ($k = $low; $k <= $min; ++$k) {
$z += $this->V[$i][$k] * $this->H[$k][$j]; $z += $this->V[$i][$k] * $this->H[$k][$j];
} }

View File

@ -96,7 +96,7 @@ final class LUDecomposition
for ($i = 0; $i < $this->m; ++$i) { for ($i = 0; $i < $this->m; ++$i) {
$LUrowi = $this->LU[$i]; $LUrowi = $this->LU[$i];
$kmax = \min($i, $j); $kmax = min($i, $j);
$s = 0.0; $s = 0.0;
for ($k = 0; $k < $kmax; ++$k) { for ($k = 0; $k < $kmax; ++$k) {
@ -107,7 +107,7 @@ final class LUDecomposition
$p = $j; $p = $j;
for ($i = $j + 1; $i < $this->m; ++$i) { for ($i = $j + 1; $i < $this->m; ++$i) {
if (\abs($LUcolj[$i]) > \abs($LUcolj[$p])) { if (abs($LUcolj[$i]) > abs($LUcolj[$p])) {
$p = $i; $p = $i;
} }
} }

View File

@ -75,7 +75,7 @@ class Matrix implements \ArrayAccess, \Iterator
$this->m = $m; $this->m = $m;
for ($i = 0; $i < $m; ++$i) { for ($i = 0; $i < $m; ++$i) {
$this->matrix[$i] = \array_fill(0, $n, 0); $this->matrix[$i] = array_fill(0, $n, 0);
} }
} }
@ -149,7 +149,7 @@ class Matrix implements \ArrayAccess, \Iterator
public function transpose() : self public function transpose() : self
{ {
$matrix = new self($this->n, $this->m); $matrix = new self($this->n, $this->m);
$matrix->setMatrix(\array_map(null, ...$this->matrix)); $matrix->setMatrix(array_map(null, ...$this->matrix));
return $matrix; return $matrix;
} }
@ -322,11 +322,11 @@ class Matrix implements \ArrayAccess, \Iterator
$nDim = $this->n; $nDim = $this->n;
$rank = 0; $rank = 0;
$selected = \array_fill(0, $mDim, false); $selected = array_fill(0, $mDim, false);
for ($i = 0; $i < $nDim; ++$i) { for ($i = 0; $i < $nDim; ++$i) {
for ($j = 0; $j < $mDim; ++$j) { for ($j = 0; $j < $mDim; ++$j) {
if (!$selected[$j] && \abs($matrix[$j][$i]) > 0.0001) { if (!$selected[$j] && abs($matrix[$j][$i]) > 0.0001) {
break; break;
} }
} }
@ -342,7 +342,7 @@ class Matrix implements \ArrayAccess, \Iterator
} }
for ($k = 0; $k < $mDim; ++$k) { for ($k = 0; $k < $mDim; ++$k) {
if ($k !== $j && \abs($matrix[$k][$i]) > 0.0001) { if ($k !== $j && abs($matrix[$k][$i]) > 0.0001) {
for ($p = $i + 1; $p < $nDim; ++$p) { for ($p = $i + 1; $p < $nDim; ++$p) {
$matrix[$k][$p] -= $matrix[$j][$p] * $matrix[$k][$i]; $matrix[$k][$p] -= $matrix[$j][$p] * $matrix[$k][$i];
} }
@ -384,7 +384,7 @@ class Matrix implements \ArrayAccess, \Iterator
*/ */
public function sub(int | float | self $value) : self public function sub(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->addScalar(-$value); return $this->addScalar(-$value);
} }
@ -402,7 +402,7 @@ class Matrix implements \ArrayAccess, \Iterator
*/ */
public function add(int | float | self $value) : self public function add(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->addScalar($value); return $this->addScalar($value);
} }
@ -499,7 +499,7 @@ class Matrix implements \ArrayAccess, \Iterator
*/ */
public function mult(int | float | self $value) : self public function mult(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->multScalar($value); return $this->multScalar($value);
} }
@ -606,7 +606,7 @@ class Matrix implements \ArrayAccess, \Iterator
$max = 0; $max = 0;
for ($j = $i; $j < $n; ++$j) { for ($j = $i; $j < $n; ++$j) {
if (\abs($arr[$j][$i]) > \abs($arr[$max][$i])) { if (abs($arr[$j][$i]) > abs($arr[$max][$i])) {
$max = $j; $max = $j;
} }
} }

View File

@ -117,8 +117,8 @@ final class Complex
public function sqrt() : self public function sqrt() : self
{ {
return new self( return new self(
\sqrt(($this->re + \sqrt($this->re ** 2 + $this->im ** 2)) / 2), sqrt(($this->re + sqrt($this->re ** 2 + $this->im ** 2)) / 2),
($this->im <=> 0) * \sqrt((-$this->re + \sqrt($this->re ** 2 + $this->im ** 2)) / 2) ($this->im <=> 0) * sqrt((-$this->re + sqrt($this->re ** 2 + $this->im ** 2)) / 2)
); );
} }
@ -131,7 +131,7 @@ final class Complex
*/ */
public function abs() : int | float public function abs() : int | float
{ {
return \sqrt($this->re ** 2 + $this->im ** 2); return sqrt($this->re ** 2 + $this->im ** 2);
} }
/** /**
@ -225,7 +225,7 @@ final class Complex
*/ */
public function add(int | float | self $value) : self public function add(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->addScalar($value); return $this->addScalar($value);
} }
@ -271,7 +271,7 @@ final class Complex
*/ */
public function sub(int | float | self $value) : self public function sub(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->subScalar($value); return $this->subScalar($value);
} }
@ -317,7 +317,7 @@ final class Complex
*/ */
public function mult(int | float | self $value) : self public function mult(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->multScalar($value); return $this->multScalar($value);
} }
@ -368,7 +368,7 @@ final class Complex
*/ */
public function div(int | float | self $value) : self public function div(int | float | self $value) : self
{ {
if (\is_numeric($value)) { if (is_numeric($value)) {
return $this->divScalar($value); return $this->divScalar($value);
} }
@ -417,12 +417,12 @@ final class Complex
*/ */
public function render(int $precision = 2) : string public function render(int $precision = 2) : string
{ {
return ($this->re !== 0 ? \number_format($this->re, $precision) : '') return ($this->re !== 0 ? number_format($this->re, $precision) : '')
. ($this->im > 0 && $this->re !== 0 ? ' +' : '') . ($this->im > 0 && $this->re !== 0 ? ' +' : '')
. ($this->im < 0 && $this->re !== 0 ? ' -' : '') . ($this->im < 0 && $this->re !== 0 ? ' -' : '')
. ($this->im !== 0 ? ( . ($this->im !== 0 ? (
($this->re !== 0 ? ' ' : '') . \number_format( ($this->re !== 0 ? ' ' : '') . number_format(
($this->im < 0 && $this->re === 0 ? $this->im : \abs($this->im)), $precision ($this->im < 0 && $this->re === 0 ? $this->im : abs($this->im)), $precision
) . 'i' ) . 'i'
) : ''); ) : '');
} }

View File

@ -126,8 +126,8 @@ final class Integer
*/ */
public static function greatestCommonDivisor(int $n, int $m) : int public static function greatestCommonDivisor(int $n, int $m) : int
{ {
$n = \abs($n); $n = abs($n);
$m = \abs($m); $m = abs($m);
while ($n !== $m) { while ($n !== $m) {
if ($n > $m) { if ($n > $m) {
@ -158,7 +158,7 @@ final class Integer
throw new \InvalidArgumentException('Only odd integers are allowed'); throw new \InvalidArgumentException('Only odd integers are allowed');
} }
$a = (int) \ceil(\sqrt($value)); $a = (int) ceil(sqrt($value));
$b2 = ($a * $a - $value); $b2 = ($a * $a - $value);
$i = 1; $i = 1;
@ -168,6 +168,6 @@ final class Integer
$b2 = ($a * $a - $value); $b2 = ($a * $a - $value);
} }
return [(int) \round($a - \sqrt($b2)), (int) \round($a + \sqrt($b2))]; return [(int) round($a - sqrt($b2)), (int) round($a + sqrt($b2))];
} }
} }

View File

@ -68,14 +68,14 @@ final class Numbers
public static function isSelfdescribing(int $n) : bool public static function isSelfdescribing(int $n) : bool
{ {
$n = (string) $n; $n = (string) $n;
$split = \str_split($n); $split = str_split($n);
if ($split === false) { if ($split === false) {
return false; // @codeCoverageIgnore return false; // @codeCoverageIgnore
} }
foreach ($split as $place => $value) { foreach ($split as $place => $value) {
if (\substr_count($n, (string) $place) != $value) { if (substr_count($n, (string) $place) != $value) {
return false; return false;
} }
} }
@ -94,7 +94,7 @@ final class Numbers
*/ */
public static function isSquare(int $n) : bool public static function isSquare(int $n) : bool
{ {
return \abs(((int) \sqrt($n)) * ((int) \sqrt($n)) - $n) < 0.001; return abs(((int) sqrt($n)) * ((int) sqrt($n)) - $n) < 0.001;
} }
/** /**

View File

@ -45,7 +45,7 @@ final class Prime
*/ */
public static function isMersenne(int $n) : bool public static function isMersenne(int $n) : bool
{ {
$mersenne = \log($n + 1, 2); $mersenne = log($n + 1, 2);
return $mersenne - (int) $mersenne < 0.00001; return $mersenne - (int) $mersenne < 0.00001;
} }
@ -93,8 +93,8 @@ final class Prime
} }
for ($i = 0; $i < $k; ++$i) { for ($i = 0; $i < $k; ++$i) {
$a = \mt_rand(2, $n - 1); $a = mt_rand(2, $n - 1);
$x = \bcpowmod((string) $a, (string) $d, (string) $n); $x = bcpowmod((string) $a, (string) $d, (string) $n);
if ($x == 1 || $x == $n - 1) { if ($x == 1 || $x == $n - 1) {
continue; continue;
@ -105,12 +105,12 @@ final class Prime
return false; return false;
} }
$mul = \bcmul($x, $x); $mul = bcmul($x, $x);
if ($mul === null) { if ($mul === null) {
return false; return false;
} }
$x = \bcmod($mul, (string) $n); $x = bcmod($mul, (string) $n);
if ($x == 1 || $x === null) { if ($x == 1 || $x === null) {
return false; return false;
} }
@ -138,8 +138,8 @@ final class Prime
public static function sieveOfEratosthenes(int $n) : array public static function sieveOfEratosthenes(int $n) : array
{ {
$number = 2; $number = 2;
$range = \range(2, $n); $range = range(2, $n);
$primes = \array_combine($range, $range); $primes = array_combine($range, $range);
if ($primes === false) { if ($primes === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
@ -154,10 +154,10 @@ final class Prime
unset($primes[$i]); unset($primes[$i]);
} }
$number = \next($primes); $number = next($primes);
} }
return \array_values($primes); return array_values($primes);
} }
/** /**
@ -177,7 +177,7 @@ final class Prime
return true; return true;
} }
$sqrtN = \sqrt($n); $sqrtN = sqrt($n);
while ($i <= $sqrtN) { while ($i <= $sqrtN) {
if ($n % $i === 0) { if ($n % $i === 0) {
return false; return false;

View File

@ -157,7 +157,7 @@ final class CubicSplineInterpolation implements InterpolationInterface
} }
} }
$xPos = \max($xPos - 1, 0); $xPos = max($xPos - 1, 0);
$h = $x - $this->points[$xPos]['x']; $h = $x - $this->points[$xPos]['x'];
if ($x < $this->points[0]['x']) { if ($x < $this->points[0]['x']) {

View File

@ -109,7 +109,7 @@ final class LinearInterpolation implements InterpolationInterface
} }
} }
$xPos = \max($xPos - 1, 0); $xPos = max($xPos - 1, 0);
$h = $x - $this->points[$xPos]['x']; $h = $x - $this->points[$xPos]['x'];
if ($x < $this->points[0]['x']) { if ($x < $this->points[0]['x']) {

View File

@ -37,8 +37,8 @@ final class Evaluator
*/ */
public static function evaluate(string $equation) : ?float public static function evaluate(string $equation) : ?float
{ {
if (\substr_count($equation, '(') !== \substr_count($equation, ')') if (substr_count($equation, '(') !== substr_count($equation, ')')
|| \preg_match('#[^0-9\+\-\*\/\(\)\ \^\.]#', $equation) || preg_match('#[^0-9\+\-\*\/\(\)\ \^\.]#', $equation)
) { ) {
return null; return null;
} }
@ -47,11 +47,11 @@ final class Evaluator
$postfix = self::shuntingYard($equation); $postfix = self::shuntingYard($equation);
foreach ($postfix as $i => $value) { foreach ($postfix as $i => $value) {
if (\is_numeric($value)) { if (is_numeric($value)) {
$stack[] = $value; $stack[] = $value;
} else { } else {
$a = self::parseValue(\array_pop($stack) ?? 0); $a = self::parseValue(array_pop($stack) ?? 0);
$b = self::parseValue(\array_pop($stack) ?? 0); $b = self::parseValue(array_pop($stack) ?? 0);
if ($value === '+') { if ($value === '+') {
$stack[] = $a + $b; $stack[] = $a + $b;
@ -67,9 +67,9 @@ final class Evaluator
} }
} }
$result = \array_pop($stack); $result = array_pop($stack);
return \is_numeric($result) ? (float) $result : null; return is_numeric($result) ? (float) $result : null;
} }
/** /**
@ -85,7 +85,7 @@ final class Evaluator
{ {
return !\is_string($value) return !\is_string($value)
? $value ? $value
: (\stripos($value, '.') === false ? (int) $value : (float) $value); : (stripos($value, '.') === false ? (int) $value : (float) $value);
} }
/** /**
@ -109,46 +109,46 @@ final class Evaluator
]; ];
$output = []; $output = [];
$equation = \str_replace(' ', '', $equation); $equation = str_replace(' ', '', $equation);
$equation = \preg_split('/([\+\-\*\/\^\(\)])/', $equation, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE); $equation = preg_split('/([\+\-\*\/\^\(\)])/', $equation, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE);
if ($equation === false) { if ($equation === false) {
return []; // @codeCoverageIgnore return []; // @codeCoverageIgnore
} }
$equation = \array_filter($equation, function($n) { $equation = array_filter($equation, function($n) {
return $n !== ''; return $n !== '';
}); });
foreach ($equation as $i => $token) { foreach ($equation as $i => $token) {
if (\is_numeric($token)) { if (is_numeric($token)) {
$output[] = $token; $output[] = $token;
} elseif (\strpbrk($token, '^*/+-') !== false) { } elseif (strpbrk($token, '^*/+-') !== false) {
$o1 = $token; $o1 = $token;
$o2 = \end($stack); $o2 = end($stack);
while ($o2 !== false && \strpbrk($o2, '^*/+-') !== false while ($o2 !== false && strpbrk($o2, '^*/+-') !== false
&& (($operators[$o1]['order'] === -1 && $operators[$o1]['precedence'] <= $operators[$o2]['precedence']) && (($operators[$o1]['order'] === -1 && $operators[$o1]['precedence'] <= $operators[$o2]['precedence'])
|| ($operators[$o1]['order'] === 1 && $operators[$o1]['precedence'] < $operators[$o2]['precedence'])) || ($operators[$o1]['order'] === 1 && $operators[$o1]['precedence'] < $operators[$o2]['precedence']))
) { ) {
$output[] = \array_pop($stack); $output[] = array_pop($stack);
$o2 = \end($stack); $o2 = end($stack);
} }
$stack[] = $o1; $stack[] = $o1;
} elseif ($token === '(') { } elseif ($token === '(') {
$stack[] = $token; $stack[] = $token;
} elseif ($token === ')') { } elseif ($token === ')') {
while (\end($stack) !== '(') { while (end($stack) !== '(') {
$output[] = \array_pop($stack); $output[] = array_pop($stack);
} }
\array_pop($stack); array_pop($stack);
} }
} }
while (\count($stack) > 0) { while (\count($stack) > 0) {
$output[] = \array_pop($stack); $output[] = array_pop($stack);
} }
/** @var string[] $output */ /** @var string[] $output */

View File

@ -189,12 +189,12 @@ final class Average
} }
if ($offset > 0) { if ($offset > 0) {
\sort($values); sort($values);
$values = \array_slice($values, $offset, -$offset); $values = \array_slice($values, $offset, -$offset);
$count -= $offset * 2; $count -= $offset * 2;
} }
return \array_sum($values) / $count; return array_sum($values) / $count;
} }
/** /**
@ -212,14 +212,14 @@ final class Average
public static function mode(array $values, int $offset = 0) : float public static function mode(array $values, int $offset = 0) : float
{ {
if ($offset > 0) { if ($offset > 0) {
\sort($values); sort($values);
$values = \array_slice($values, $offset, -$offset); $values = \array_slice($values, $offset, -$offset);
} }
$count = \array_count_values($values); $count = array_count_values($values);
$best = \max($count); $best = max($count);
return (float) (\array_keys($count, $best)[0] ?? 0.0); return (float) (array_keys($count, $best)[0] ?? 0.0);
} }
/** /**
@ -236,14 +236,14 @@ final class Average
*/ */
public static function median(array $values, int $offset = 0) : float public static function median(array $values, int $offset = 0) : float
{ {
\sort($values); sort($values);
if ($offset > 0) { if ($offset > 0) {
$values = \array_slice($values, $offset, -$offset); $values = \array_slice($values, $offset, -$offset);
} }
$count = \count($values); $count = \count($values);
$middleval = (int) \floor(($count - 1) / 2); $middleval = (int) floor(($count - 1) / 2);
if ($count % 2) { if ($count % 2) {
$median = $values[$middleval]; $median = $values[$middleval];
@ -278,12 +278,12 @@ final class Average
} }
if ($offset > 0) { if ($offset > 0) {
\sort($values); sort($values);
$values = \array_slice($values, $offset, -$offset); $values = \array_slice($values, $offset, -$offset);
$count -= $offset * 2; $count -= $offset * 2;
} }
return \pow(\array_product($values), 1 / $count); return pow(array_product($values), 1 / $count);
} }
/** /**
@ -308,7 +308,7 @@ final class Average
} }
if ($offset > 0) { if ($offset > 0) {
\sort($values); sort($values);
$values = \array_slice($values, $offset, -$offset); $values = \array_slice($values, $offset, -$offset);
$count -= $offset * 2; $count -= $offset * 2;
} }
@ -345,7 +345,7 @@ final class Average
} }
if ($offset > 0) { if ($offset > 0) {
\sort($angles); sort($angles);
$angles = \array_slice($angles, $offset, -$offset); $angles = \array_slice($angles, $offset, -$offset);
$count -= $offset * 2; $count -= $offset * 2;
} }
@ -354,14 +354,14 @@ final class Average
$x = 0; $x = 0;
for ($i = 0; $i < $count; ++$i) { for ($i = 0; $i < $count; ++$i) {
$x += \cos(\deg2rad($angles[$i])); $x += cos(deg2rad($angles[$i]));
$y += \sin(\deg2rad($angles[$i])); $y += sin(deg2rad($angles[$i]));
} }
$x /= $count; $x /= $count;
$y /= $count; $y /= $count;
return \rad2deg(\atan2($y, $x)); return rad2deg(atan2($y, $x));
} }
/** /**
@ -384,7 +384,7 @@ final class Average
} }
if ($offset > 0) { if ($offset > 0) {
\sort($angles); sort($angles);
$angles = \array_slice($angles, $offset, -$offset); $angles = \array_slice($angles, $offset, -$offset);
$count -= $offset * 2; $count -= $offset * 2;
} }
@ -393,13 +393,13 @@ final class Average
$coss = 0.0; $coss = 0.0;
foreach ($angles as $a) { foreach ($angles as $a) {
$sins += \sin(\deg2rad($a)); $sins += sin(deg2rad($a));
$coss += \cos(\deg2rad($a)); $coss += cos(deg2rad($a));
} }
$avgsin = $sins / (0.0 + $count); $avgsin = $sins / (0.0 + $count);
$avgcos = $coss / (0.0 + $count); $avgcos = $coss / (0.0 + $count);
$avgang = \rad2deg(\atan2($avgsin, $avgcos)); $avgang = rad2deg(atan2($avgsin, $avgcos));
while ($avgang < 0.0) { while ($avgang < 0.0) {
$avgang += 360.0; $avgang += 360.0;

View File

@ -50,8 +50,8 @@ final class Basic
$freaquency = []; $freaquency = [];
$sum = 1; $sum = 1;
if (!($isArray = \is_array(\reset($values)))) { if (!($isArray = \is_array(reset($values)))) {
$sum = \array_sum($values); $sum = array_sum($values);
} }
foreach ($values as $value) { foreach ($values as $value) {

View File

@ -139,7 +139,7 @@ final class Error
{ {
$deviation = 0.0; $deviation = 0.0;
foreach ($observed as $key => $value) { foreach ($observed as $key => $value) {
$deviation += \abs($value - $forecasted[$key]); $deviation += abs($value - $forecasted[$key]);
} }
return $deviation / \count($observed); return $deviation / \count($observed);
@ -171,7 +171,7 @@ final class Error
*/ */
public static function getRootMeanSquaredError(array $errors) : float public static function getRootMeanSquaredError(array $errors) : float
{ {
return \sqrt(Average::arithmeticMean(ArrayUtils::power($errors, 2))); return sqrt(Average::arithmeticMean(ArrayUtils::power($errors, 2)));
} }
/** /**
@ -259,7 +259,7 @@ final class Error
$error = []; $error = [];
foreach ($observed as $key => $value) { foreach ($observed as $key => $value) {
$error[] = \abs($value - $forecasted[$key]) / ($value + $forecasted[$key]) / 2; $error[] = abs($value - $forecasted[$key]) / ($value + $forecasted[$key]) / 2;
} }
return Average::arithmeticMean($error); return Average::arithmeticMean($error);
@ -348,7 +348,7 @@ final class Error
$count = \count($observed); $count = \count($observed);
for ($i = 0 + $m; $i < $count; ++$i) { for ($i = 0 + $m; $i < $count; ++$i) {
$sum += \abs($observed[$i] - $observed[$i - $m]); $sum += abs($observed[$i] - $observed[$i - $m]);
} }
return $sum; return $sum;

View File

@ -36,7 +36,7 @@ final class LevelLogRegression extends RegressionAbstract
} }
for ($i = 0; $i < $c; ++$i) { for ($i = 0; $i < $c; ++$i) {
$x[$i] = \log($x[$i]); $x[$i] = log($x[$i]);
} }
return parent::getRegression($x, $y); return parent::getRegression($x, $y);

View File

@ -36,7 +36,7 @@ final class LogLevelRegression extends RegressionAbstract
} }
for ($i = 0; $i < $c; ++$i) { for ($i = 0; $i < $c; ++$i) {
$y[$i] = \log($y[$i]); $y[$i] = log($y[$i]);
} }
return parent::getRegression($x, $y); return parent::getRegression($x, $y);

View File

@ -36,8 +36,8 @@ final class LogLogRegression extends RegressionAbstract
} }
for ($i = 0; $i < $c; ++$i) { for ($i = 0; $i < $c; ++$i) {
$x[$i] = \log($x[$i]); $x[$i] = log($x[$i]);
$y[$i] = \log($y[$i]); $y[$i] = log($y[$i]);
} }
return parent::getRegression($x, $y); return parent::getRegression($x, $y);

View File

@ -48,7 +48,7 @@ final class PolynomialRegression
$xm = Average::arithmeticMean($x); $xm = Average::arithmeticMean($x);
$ym = Average::arithmeticMean($y); $ym = Average::arithmeticMean($y);
$r = \range(0, $n - 1); $r = range(0, $n - 1);
$xTemp = []; $xTemp = [];
foreach ($r as $e) { foreach ($r as $e) {

View File

@ -74,7 +74,7 @@ abstract class RegressionAbstract
$sum += $errors[$i] ** 2; $sum += $errors[$i] ** 2;
} }
return \sqrt($sum / $count); return sqrt($sum / $count);
} }
/** /**
@ -99,7 +99,7 @@ abstract class RegressionAbstract
$sum += $errors[$i] ** 2; $sum += $errors[$i] ** 2;
} }
return \sqrt($sum / ($count - 2)); return sqrt($sum / ($count - 2));
} }
/** /**
@ -127,7 +127,7 @@ abstract class RegressionAbstract
$sum += ($x[$i] - $meanX) ** 2; $sum += ($x[$i] - $meanX) ** 2;
} }
$interval = $multiplier * \sqrt($mse + $mse / $count + $mse * ($fX - $meanX) ** 2 / $sum); $interval = $multiplier * sqrt($mse + $mse / $count + $mse * ($fX - $meanX) ** 2 / $sum);
return [$fY - $interval, $fY + $interval]; return [$fY - $interval, $fY + $interval];
} }

View File

@ -50,9 +50,9 @@ final class MeasureOfDispersion
*/ */
public static function range(array $values) : float public static function range(array $values) : float
{ {
\sort($values); sort($values);
$end = \end($values); $end = end($values);
$start = \reset($values); $start = reset($values);
return $end - $start; return $end - $start;
} }
@ -108,7 +108,7 @@ final class MeasureOfDispersion
++$valueCount; ++$valueCount;
} }
return \sqrt($sum / ($valueCount - 1)); return sqrt($sum / ($valueCount - 1));
} }
/** /**
@ -137,7 +137,7 @@ final class MeasureOfDispersion
++$valueCount; ++$valueCount;
} }
return \sqrt($sum / $valueCount); return sqrt($sum / $valueCount);
} }
/** /**
@ -300,7 +300,7 @@ final class MeasureOfDispersion
/** @var int $count */ /** @var int $count */
$count /= 2; $count /= 2;
\sort($x); sort($x);
$Q1 = Average::median(\array_slice($x, 0, $count)); $Q1 = Average::median(\array_slice($x, 0, $count));
$Q3 = Average::median(\array_slice($x, -$count, $count)); $Q3 = Average::median(\array_slice($x, -$count, $count));
@ -368,7 +368,7 @@ final class MeasureOfDispersion
$sum = 0.0; $sum = 0.0;
foreach ($x as $xi) { foreach ($x as $xi) {
$sum += \abs($xi - $mean); $sum += abs($xi - $mean);
} }
return $sum / (\count($x) - $offset); return $sum / (\count($x) - $offset);
@ -388,7 +388,7 @@ final class MeasureOfDispersion
$mean = $mean !== null ? $mean : Average::arithmeticMean($x); $mean = $mean !== null ? $mean : Average::arithmeticMean($x);
foreach ($x as $key => $value) { foreach ($x as $key => $value) {
$x[$key] = \abs($value - $mean); $x[$key] = abs($value - $mean);
} }
return $x; return $x;

View File

@ -147,7 +147,7 @@ final class BernoulliDistribution
*/ */
public static function getStandardDeviation(float $p) : float public static function getStandardDeviation(float $p) : float
{ {
return \sqrt(self::getVariance($p)); return sqrt(self::getVariance($p));
} }
/** /**
@ -162,7 +162,7 @@ final class BernoulliDistribution
*/ */
public static function getMgf(float $p, float $t) : float public static function getMgf(float $p, float $t) : float
{ {
return (1 - $p) + $p * \exp($t); return (1 - $p) + $p * exp($t);
} }
/** /**
@ -176,7 +176,7 @@ final class BernoulliDistribution
*/ */
public static function getSkewness(float $p) : float public static function getSkewness(float $p) : float
{ {
return (1 - 2 * $p) / \sqrt($p * (1 - $p)); return (1 - 2 * $p) / sqrt($p * (1 - $p));
} }
/** /**
@ -190,7 +190,7 @@ final class BernoulliDistribution
*/ */
public static function getEntropy(float $p) : float public static function getEntropy(float $p) : float
{ {
return -(1 - $p) * \log(1 - $p) - $p * \log($p); return -(1 - $p) * log(1 - $p) - $p * log($p);
} }
/** /**

View File

@ -91,7 +91,7 @@ final class BetaDistribution
*/ */
public static function getStandardDeviation(float $alpha, float $beta) : float public static function getStandardDeviation(float $alpha, float $beta) : float
{ {
return \sqrt(self::getVariance($alpha, $beta)); return sqrt(self::getVariance($alpha, $beta));
} }
/** /**
@ -106,7 +106,7 @@ final class BetaDistribution
*/ */
public static function getSkewness(float $alpha, float $beta) : float public static function getSkewness(float $alpha, float $beta) : float
{ {
return 2 * ($beta - $alpha) * \sqrt($alpha + $beta + 1) / (($alpha + $beta + 2) * \sqrt($alpha * $beta)); return 2 * ($beta - $alpha) * sqrt($alpha + $beta + 1) / (($alpha + $beta + 2) * sqrt($alpha * $beta));
} }
/** /**
@ -164,7 +164,7 @@ final class BetaDistribution
*/ */
public static function getPdf(float $x, float $alpha, float $beta) : float public static function getPdf(float $x, float $alpha, float $beta) : float
{ {
return \pow($x, $alpha - 1) * \pow(1 - $x, $beta - 1) / Beta::beta($alpha, $beta); return pow($x, $alpha - 1) * pow(1 - $x, $beta - 1) / Beta::beta($alpha, $beta);
} }
/** /**

View File

@ -38,7 +38,7 @@ final class BinomialDistribution
*/ */
public static function getMode(int $n, float $p) : float public static function getMode(int $n, float $p) : float
{ {
return \floor(($n + 1) * $p); return floor(($n + 1) * $p);
} }
/** /**
@ -54,7 +54,7 @@ final class BinomialDistribution
*/ */
public static function getMgf(int $n, float $t, float $p) : float public static function getMgf(int $n, float $t, float $p) : float
{ {
return \pow(1 - $p + $p * \exp($t), $n); return pow(1 - $p + $p * exp($t), $n);
} }
/** /**
@ -69,7 +69,7 @@ final class BinomialDistribution
*/ */
public static function getSkewness(int $n, float $p) : float public static function getSkewness(int $n, float $p) : float
{ {
return (1 - 2 * $p) / \sqrt($n * $p * (1 - $p)); return (1 - 2 * $p) / sqrt($n * $p * (1 - $p));
} }
/** /**
@ -139,7 +139,7 @@ final class BinomialDistribution
*/ */
public static function getPmf(int $n, int $k, float $p) : float public static function getPmf(int $n, int $k, float $p) : float
{ {
return Functions::binomialCoefficient($n, $k) * \pow($p, $k) * \pow(1 - $p, $n - $k); return Functions::binomialCoefficient($n, $k) * pow($p, $k) * pow(1 - $p, $n - $k);
} }
/** /**
@ -154,7 +154,7 @@ final class BinomialDistribution
*/ */
public static function getMedian(int $n, float $p) : float public static function getMedian(int $n, float $p) : float
{ {
return \floor($n * $p); return floor($n * $p);
} }
/** /**
@ -199,6 +199,6 @@ final class BinomialDistribution
*/ */
public static function getStandardDeviation(int $n, float $p) : float public static function getStandardDeviation(int $n, float $p) : float
{ {
return \sqrt(self::getVariance($n, $p)); return sqrt(self::getVariance($n, $p));
} }
} }

View File

@ -53,7 +53,7 @@ final class CauchyDistribution
*/ */
public static function getCdf(float $x, float $x0, float $gamma) : float public static function getCdf(float $x, float $x0, float $gamma) : float
{ {
return 1 / \M_PI * \atan(($x - $x0) / $gamma) + 0.5; return 1 / \M_PI * atan(($x - $x0) / $gamma) + 0.5;
} }
/** /**
@ -95,6 +95,6 @@ final class CauchyDistribution
*/ */
public static function getEntropy(float $gamma) : float public static function getEntropy(float $gamma) : float
{ {
return \log(4 * \M_PI * $gamma); return log(4 * \M_PI * $gamma);
} }
} }

View File

@ -138,7 +138,7 @@ final class ChiSquaredDistribution
*/ */
public static function getDegreesOfFreedom(array $values) : int public static function getDegreesOfFreedom(array $values) : int
{ {
if (\is_array($first = \reset($values))) { if (\is_array($first = reset($values))) {
return (\count($values) - 1) * (\count($first) - 1); return (\count($values) - 1) * (\count($first) - 1);
} else { } else {
return \count($values) - 1; return \count($values) - 1;
@ -163,7 +163,7 @@ final class ChiSquaredDistribution
throw new \OutOfBoundsException('Out of bounds'); throw new \OutOfBoundsException('Out of bounds');
} }
return 1 / (\pow(2, $df / 2) * Gamma::gamma($df / 2)) * \pow($x, $df / 2 - 1) * \exp(-$x / 2); return 1 / (pow(2, $df / 2) * Gamma::gamma($df / 2)) * pow($x, $df / 2 - 1) * exp(-$x / 2);
} }
/** /**
@ -192,7 +192,7 @@ final class ChiSquaredDistribution
*/ */
public static function getMode(int $df) : int public static function getMode(int $df) : int
{ {
return \max($df - 2, 0); return max($df - 2, 0);
} }
/** /**
@ -248,7 +248,7 @@ final class ChiSquaredDistribution
*/ */
public static function getStandardDeviation(int $df) : float public static function getStandardDeviation(int $df) : float
{ {
return \sqrt(self::getVariance($df)); return sqrt(self::getVariance($df));
} }
/** /**
@ -269,7 +269,7 @@ final class ChiSquaredDistribution
throw new \OutOfBoundsException('Out of bounds'); throw new \OutOfBoundsException('Out of bounds');
} }
return \pow(1 - 2 * $t, -$df / 2); return pow(1 - 2 * $t, -$df / 2);
} }
/** /**
@ -283,7 +283,7 @@ final class ChiSquaredDistribution
*/ */
public static function getSkewness(int $df) : float public static function getSkewness(int $df) : float
{ {
return \sqrt(8 / $df); return sqrt(8 / $df);
} }
/** /**

View File

@ -36,7 +36,7 @@ final class ExponentialDistribution
*/ */
public static function getPdf(float $x, float $lambda) : float public static function getPdf(float $x, float $lambda) : float
{ {
return $x >= 0 ? $lambda * \exp(-$lambda * $x) : 0; return $x >= 0 ? $lambda * exp(-$lambda * $x) : 0;
} }
/** /**
@ -51,7 +51,7 @@ final class ExponentialDistribution
*/ */
public static function getCdf(float $x, float $lambda) : float public static function getCdf(float $x, float $lambda) : float
{ {
return $x >= 0 ? 1 - 1 / \exp($lambda * $x) : 0; return $x >= 0 ? 1 - 1 / exp($lambda * $x) : 0;
} }
/** /**
@ -91,7 +91,7 @@ final class ExponentialDistribution
*/ */
public static function getMedian(float $lambda) : float public static function getMedian(float $lambda) : float
{ {
return 1 / $lambda * \log(2); return 1 / $lambda * log(2);
} }
/** /**
@ -105,7 +105,7 @@ final class ExponentialDistribution
*/ */
public static function getVariance(float $lambda) : float public static function getVariance(float $lambda) : float
{ {
return \pow($lambda, -2); return pow($lambda, -2);
} }
/** /**
@ -119,7 +119,7 @@ final class ExponentialDistribution
*/ */
public static function getStandardDeviation(float $lambda) : float public static function getStandardDeviation(float $lambda) : float
{ {
return \sqrt(self::getVariance($lambda)); return sqrt(self::getVariance($lambda));
} }
/** /**

View File

@ -38,7 +38,7 @@ final class FDistribution
*/ */
public static function getPdf(float $x, int $d1, int $d2) : float public static function getPdf(float $x, int $d1, int $d2) : float
{ {
return \sqrt((\pow($d1 * $x, $d1) * ($d2 ** $d2)) / \pow($d1 * $x + $d2, $d1 + $d2)) return sqrt((pow($d1 * $x, $d1) * ($d2 ** $d2)) / pow($d1 * $x + $d2, $d1 + $d2))
/ ($x * Beta::beta($d1 / 2, $d2 / 2)); / ($x * Beta::beta($d1 / 2, $d2 / 2));
} }
@ -127,7 +127,7 @@ final class FDistribution
*/ */
public static function getStandardDeviation(int $d1, int $d2) : float public static function getStandardDeviation(int $d1, int $d2) : float
{ {
return \sqrt(self::getVariance($d1, $d2)); return sqrt(self::getVariance($d1, $d2));
} }
/** /**
@ -146,7 +146,7 @@ final class FDistribution
return 0.0; return 0.0;
} }
return (2 * $d1 + $d2 - 2) * \sqrt(8 * ($d2 - 4)) return (2 * $d1 + $d2 - 2) * sqrt(8 * ($d2 - 4))
/ (($d2 - 6) * \sqrt($d1 * ($d1 + $d2 - 2))); / (($d2 - 6) * sqrt($d1 * ($d1 + $d2 - 2)));
} }
} }

View File

@ -38,7 +38,7 @@ final class GammaDistribution
*/ */
public static function getPdfScale(float $x, float $k, float $theta) : float public static function getPdfScale(float $x, float $k, float $theta) : float
{ {
return 1 / (Gamma::gamma($k) * $theta ** $k) * \pow($x, $k - 1) * \exp(-$x / $theta); return 1 / (Gamma::gamma($k) * $theta ** $k) * pow($x, $k - 1) * exp(-$x / $theta);
} }
/** /**
@ -54,7 +54,7 @@ final class GammaDistribution
*/ */
public static function getPdfRate(float $x, float $alpha, float $beta) : float public static function getPdfRate(float $x, float $alpha, float $beta) : float
{ {
return $beta ** $alpha / Gamma::gamma($alpha) * \pow($x, $alpha - 1) * \exp(-$beta * $x); return $beta ** $alpha / Gamma::gamma($alpha) * pow($x, $alpha - 1) * exp(-$beta * $x);
} }
/** /**
@ -70,7 +70,7 @@ final class GammaDistribution
*/ */
public static function getPdfIntegerScale(float $x, int $k, float $theta) : float public static function getPdfIntegerScale(float $x, int $k, float $theta) : float
{ {
return 1 / (Gamma::getGammaInteger($k) * $theta ** $k) * \pow($x, $k - 1) * \exp(-$x / $theta); return 1 / (Gamma::getGammaInteger($k) * $theta ** $k) * pow($x, $k - 1) * exp(-$x / $theta);
} }
/** /**
@ -86,7 +86,7 @@ final class GammaDistribution
*/ */
public static function getPdfIntegerRate(float $x, int $alpha, float $beta) : float public static function getPdfIntegerRate(float $x, int $alpha, float $beta) : float
{ {
return $beta ** $alpha / Gamma::getGammaInteger($alpha) * \pow($x, $alpha - 1) * \exp(-$beta * $x); return $beta ** $alpha / Gamma::getGammaInteger($alpha) * pow($x, $alpha - 1) * exp(-$beta * $x);
} }
/** /**
@ -192,7 +192,7 @@ final class GammaDistribution
*/ */
public static function getSkewness(float $k) : float public static function getSkewness(float $k) : float
{ {
return 2 / \sqrt($k); return 2 / sqrt($k);
} }
/** /**
@ -236,7 +236,7 @@ final class GammaDistribution
*/ */
public static function getStandardDeviationScale(float $k, float $theta) : float public static function getStandardDeviationScale(float $k, float $theta) : float
{ {
return \sqrt(self::getVarianceScale($k, $theta)); return sqrt(self::getVarianceScale($k, $theta));
} }
/** /**
@ -266,7 +266,7 @@ final class GammaDistribution
*/ */
public static function getStandardDeviationRate(float $alpha, float $beta) : float public static function getStandardDeviationRate(float $alpha, float $beta) : float
{ {
return \sqrt(self::getVarianceRate($alpha, $beta)); return sqrt(self::getVarianceRate($alpha, $beta));
} }
/** /**
@ -282,7 +282,7 @@ final class GammaDistribution
*/ */
public static function getMgfScale(float $k, float $t, float $theta) : float public static function getMgfScale(float $k, float $t, float $theta) : float
{ {
return \pow(1 - $theta * $t, -$k); return pow(1 - $theta * $t, -$k);
} }
/** /**
@ -298,6 +298,6 @@ final class GammaDistribution
*/ */
public static function getMgfRate(float $t, float $alpha, float $beta) : float public static function getMgfRate(float $t, float $alpha, float $beta) : float
{ {
return \pow(1 - $t / $beta, -$alpha); return pow(1 - $t / $beta, -$alpha);
} }
} }

View File

@ -36,7 +36,7 @@ final class GeometricDistribution
*/ */
public static function getPmf(float $p, int $k) : float public static function getPmf(float $p, int $k) : float
{ {
return \pow(1 - $p, $k - 1) * $p; return pow(1 - $p, $k - 1) * $p;
} }
/** /**
@ -51,7 +51,7 @@ final class GeometricDistribution
*/ */
public static function getCdf(float $p, int $k) : float public static function getCdf(float $p, int $k) : float
{ {
return 1 - \pow(1 - $p, $k); return 1 - pow(1 - $p, $k);
} }
/** /**
@ -91,7 +91,7 @@ final class GeometricDistribution
*/ */
public static function getMedian(float $p) : float public static function getMedian(float $p) : float
{ {
return \ceil(-1 / (\log(1 - $p, 2))); return ceil(-1 / (log(1 - $p, 2)));
} }
/** /**
@ -119,7 +119,7 @@ final class GeometricDistribution
*/ */
public static function getStandardDeviation(float $p) : float public static function getStandardDeviation(float $p) : float
{ {
return \sqrt(self::getVariance($p)); return sqrt(self::getVariance($p));
} }
/** /**
@ -134,9 +134,9 @@ final class GeometricDistribution
*/ */
public static function getMgf(float $p, float $t) : float public static function getMgf(float $p, float $t) : float
{ {
return $t < -\log(1 - $p) return $t < -log(1 - $p)
? $p * \exp($t) / (1 - (1 - $p) * \exp($t)) ? $p * exp($t) / (1 - (1 - $p) * exp($t))
: $p / (1 - (1 - $p) * \exp($t)); : $p / (1 - (1 - $p) * exp($t));
} }
/** /**
@ -150,7 +150,7 @@ final class GeometricDistribution
*/ */
public static function getSkewness(float $lambda) : float public static function getSkewness(float $lambda) : float
{ {
return (2 - $lambda) / \sqrt(1 - $lambda); return (2 - $lambda) / sqrt(1 - $lambda);
} }
/** /**

Some files were not shown because too many files have changed in this diff Show More