Use root namespace and cleanup

This commit is contained in:
Dennis Eichhorn 2018-05-30 13:40:28 +02:00
parent 37add470eb
commit 1b0d170052
209 changed files with 2261 additions and 3298 deletions

View File

@ -292,7 +292,7 @@ class Account implements ArrayableInterface, \JsonSerializable
/** /**
* Get permissions. * Get permissions.
* *
* @return array * @return PermissionAbstract[]
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@ -603,7 +603,7 @@ class Account implements ArrayableInterface, \JsonSerializable
*/ */
public function __toString() : string public function __toString() : string
{ {
return json_encode($this->toArray()); return \json_encode($this->toArray());
} }
/** /**
@ -630,7 +630,7 @@ class Account implements ArrayableInterface, \JsonSerializable
/** /**
* Json serialize. * Json serialize.
* *
* @return array * @return array<string, mixed>
* *
* @since 1.0.0 * @since 1.0.0
*/ */

View File

@ -189,7 +189,7 @@ class Group implements ArrayableInterface, \JsonSerializable
*/ */
public function __toString() : string public function __toString() : string
{ {
return json_encode($this->toArray()); return \json_encode($this->toArray());
} }
/** /**
@ -209,7 +209,7 @@ class Group implements ArrayableInterface, \JsonSerializable
/** /**
* Json serialize. * Json serialize.
* *
* @return array * @return array<string, mixed>
* *
* @since 1.0.0 * @since 1.0.0
*/ */

View File

@ -77,8 +77,8 @@ 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 (file_exists($file = $path . $class . '.php')) { if (file_exists($file = $path . $class . '.php')) {
@ -102,8 +102,8 @@ 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 (file_exists($file = $path . $class . '.php')) { if (file_exists($file = $path . $class . '.php')) {

View File

@ -77,7 +77,7 @@ abstract class SettingsAbstract implements OptionsInterface
/** /**
* Get option by key. * Get option by key.
* *
* @param string|string[] $columns Column values for filtering * @param string|string[]|int|int[] $columns Column values for filtering
* *
* @return mixed Option value * @return mixed Option value
* *

View File

@ -219,7 +219,7 @@ class FileCache extends ConnectionAbstract
if ($type === CacheValueType::_INT || $type === CacheValueType::_FLOAT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) { if ($type === CacheValueType::_INT || $type === CacheValueType::_FLOAT || $type === CacheValueType::_STRING || $type === CacheValueType::_BOOL) {
return (string) $value; return (string) $value;
} elseif ($type === CacheValueType::_ARRAY) { } elseif ($type === CacheValueType::_ARRAY) {
return json_encode($value); return \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) {
@ -315,7 +315,7 @@ class FileCache extends ConnectionAbstract
$value = substr($raw, $expireEnd + 1); $value = substr($raw, $expireEnd + 1);
break; break;
case CacheValueType::_ARRAY: case CacheValueType::_ARRAY:
$value = json_decode(substr($raw, $expireEnd + 1)); $value = \json_decode(substr($raw, $expireEnd + 1));
break; break;
case CacheValueType::_NULL: case CacheValueType::_NULL:
$value = null; $value = null;
@ -353,7 +353,7 @@ class FileCache extends ConnectionAbstract
if ($expire >= 0) { if ($expire >= 0) {
$created = Directory::created(File::sanitize($key, self::SANITIZE))->getTimestamp(); $created = Directory::created(File::sanitize($key, self::SANITIZE))->getTimestamp();
$now = time(); $now = time();
$raw = file_get_contents($path); $raw = \file_get_contents($path);
$expireStart = strpos($raw, self::DELIM); $expireStart = strpos($raw, self::DELIM);
$expireEnd = strpos($raw, self::DELIM, $expireStart + 1); $expireEnd = strpos($raw, self::DELIM, $expireStart + 1);
$cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1)); $cacheExpire = substr($raw, $expireStart + 1, $expireEnd - ($expireStart + 1));

View File

@ -59,7 +59,7 @@ final class MysqlConnection extends ConnectionAbstract
$this->dbdata = isset($dbdata) ? $dbdata : $this->dbdata; $this->dbdata = isset($dbdata) ? $dbdata : $this->dbdata;
if (!isset($this->dbdata['db'], $this->dbdata['host'], $this->dbdata['port'], $this->dbdata['database'], $this->dbdata['login'], $this->dbdata['password'])) { if (!isset($this->dbdata['db'], $this->dbdata['host'], $this->dbdata['port'], $this->dbdata['database'], $this->dbdata['login'], $this->dbdata['password'])) {
throw new InvalidConnectionConfigException(json_encode($this->dbdata)); throw new InvalidConnectionConfigException(\json_encode($this->dbdata));
} }
$this->close(); $this->close();

View File

@ -58,7 +58,7 @@ final class PostgresConnection extends ConnectionAbstract
$this->dbdata = isset($dbdata) ? $dbdata : $this->dbdata; $this->dbdata = isset($dbdata) ? $dbdata : $this->dbdata;
if (!isset($this->dbdata['db'], $this->dbdata['host'], $this->dbdata['port'], $this->dbdata['database'], $this->dbdata['login'], $this->dbdata['password'])) { if (!isset($this->dbdata['db'], $this->dbdata['host'], $this->dbdata['port'], $this->dbdata['database'], $this->dbdata['login'], $this->dbdata['password'])) {
throw new InvalidConnectionConfigException(json_encode($this->dbdata)); throw new InvalidConnectionConfigException(\json_encode($this->dbdata));
} }
$this->close(); $this->close();

View File

@ -14,7 +14,7 @@ declare(strict_types=1);
namespace phpOMS\DataStorage\Database; namespace phpOMS\DataStorage\Database;
use phpOMS\DataStorage\Database\Connection\ConnectionAbstract; use phpOMS\DataStorage\DataStorageConnectionInterface;
use phpOMS\DataStorage\Database\Query\Builder; use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\DataMapperInterface; use phpOMS\DataStorage\DataMapperInterface;
use phpOMS\Message\RequestAbstract; use phpOMS\Message\RequestAbstract;
@ -37,7 +37,7 @@ class DataMapperAbstract implements DataMapperInterface
/** /**
* Database connection. * Database connection.
* *
* @var ConnectionAbstract * @var DataStorageConnectionInterface
* @since 1.0.0 * @since 1.0.0
*/ */
protected static $db = null; protected static $db = null;
@ -77,7 +77,7 @@ class DataMapperAbstract implements DataMapperInterface
/** /**
* Columns. * Columns.
* *
* @var array * @var array<string, array<string, string>>
* @since 1.0.0 * @since 1.0.0
*/ */
protected static $columns = []; protected static $columns = [];
@ -195,13 +195,13 @@ class DataMapperAbstract implements DataMapperInterface
/** /**
* Set database connection. * Set database connection.
* *
* @param ConnectionAbstract $con Database connection * @param DataStorageConnectionInterface $con Database connection
* *
* @return void * @return void
* *
* @since 1.0.0 * @since 1.0.0
*/ */
public static function setConnection(ConnectionAbstract $con) : void public static function setConnection(DataStorageConnectionInterface $con) : void
{ {
self::$db = $con; self::$db = $con;
} }
@ -402,7 +402,7 @@ class DataMapperAbstract implements DataMapperInterface
$query->prefix(self::$db->getPrefix())->into(static::$table); $query->prefix(self::$db->getPrefix())->into(static::$table);
foreach (static::$columns as $key => $column) { foreach (static::$columns as $key => $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]) || isset(static::$hasOne[$propertyName])) { if (isset(static::$hasMany[$propertyName]) || isset(static::$hasOne[$propertyName])) {
continue; continue;
} }
@ -426,7 +426,7 @@ class DataMapperAbstract implements DataMapperInterface
} elseif ($column['name'] !== static::$primaryField) { } elseif ($column['name'] !== static::$primaryField) {
$tValue = $property->getValue($obj); $tValue = $property->getValue($obj);
if (stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = explode('/', $column['internal']); $path = \explode('/', $column['internal']);
array_shift($path); array_shift($path);
$path = implode('/', $path); $path = implode('/', $path);
@ -476,7 +476,7 @@ class DataMapperAbstract implements DataMapperInterface
$path = $column['internal']; $path = $column['internal'];
if (stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = explode('/', $column['internal']); $path = \explode('/', $column['internal']);
array_shift($path); array_shift($path);
$path = implode('/', $path); $path = implode('/', $path);
@ -890,11 +890,11 @@ class DataMapperAbstract implements DataMapperInterface
} elseif ($type === 'DateTime') { } elseif ($type === 'DateTime') {
return $value->format('Y-m-d H:i:s'); return $value->format('Y-m-d H:i:s');
} elseif ($type === 'Json' || $type === 'jsonSerializable') { } elseif ($type === 'Json' || $type === 'jsonSerializable') {
return json_encode($value); return \json_encode($value);
} elseif ($type === 'Serializable') { } elseif ($type === 'Serializable') {
return $value->serialize(); return $value->serialize();
} elseif ($value instanceof \JsonSerializable) { } elseif ($value instanceof \JsonSerializable) {
return json_encode($value->jsonSerialize()); return \json_encode($value->jsonSerialize());
} elseif (is_object($value) && method_exists($value, 'getId')) { } elseif (is_object($value) && method_exists($value, 'getId')) {
return $value->getId(); return $value->getId();
} }
@ -1118,7 +1118,7 @@ class DataMapperAbstract implements DataMapperInterface
->where(static::$table . '.' . static::$primaryField, '=', $objId); ->where(static::$table . '.' . static::$primaryField, '=', $objId);
foreach (static::$columns as $key => $column) { foreach (static::$columns as $key => $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])
|| isset(static::$hasOne[$propertyName]) || isset(static::$hasOne[$propertyName])
|| $column['internal'] === static::$primaryField || $column['internal'] === static::$primaryField
@ -1147,7 +1147,7 @@ class DataMapperAbstract implements DataMapperInterface
} elseif ($column['name'] !== static::$primaryField) { } elseif ($column['name'] !== static::$primaryField) {
$tValue = $property->getValue($obj); $tValue = $property->getValue($obj);
if (stripos($column['internal'], '/') !== false) { if (stripos($column['internal'], '/') !== false) {
$path = explode('/', $column['internal']); $path = \explode('/', $column['internal']);
array_shift($path); array_shift($path);
$path = implode('/', $path); $path = implode('/', $path);
@ -1480,10 +1480,10 @@ class DataMapperAbstract implements DataMapperInterface
public static function populate(array $result, $obj = null) public static function populate(array $result, $obj = null)
{ {
$class = static::class; $class = static::class;
$class = str_replace('Mapper', '', $class); $class = \str_replace('Mapper', '', $class);
if (empty($result)) { if (empty($result)) {
$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);
@ -1779,7 +1779,7 @@ class DataMapperAbstract implements DataMapperInterface
if (stripos(static::$columns[$column]['internal'], '/') !== false) { if (stripos(static::$columns[$column]['internal'], '/') !== false) {
$hasPath = true; $hasPath = true;
$path = explode('/', static::$columns[$column]['internal']); $path = \explode('/', static::$columns[$column]['internal']);
$refProp = $refClass->getProperty($path[0]); $refProp = $refClass->getProperty($path[0]);
if (!($accessible = $refProp->isPublic())) { if (!($accessible = $refProp->isPublic())) {
@ -1797,7 +1797,7 @@ class DataMapperAbstract implements DataMapperInterface
} }
} }
if (in_array(static::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) { if (\in_array(static::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) {
// todo: what is this or condition for? seems to be wrong if obj null then it doesn't work anyways // todo: what is this or condition for? seems to be wrong if obj null then it doesn't work anyways
if ($value !== null || $refProp->getValue($obj) !== null) { if ($value !== null || $refProp->getValue($obj) !== null) {
settype($value, static::$columns[$column]['type']); settype($value, static::$columns[$column]['type']);
@ -1820,7 +1820,7 @@ class DataMapperAbstract implements DataMapperInterface
$value = ArrayUtils::setArray($path, $aValue, $value, '/', true); $value = ArrayUtils::setArray($path, $aValue, $value, '/', true);
} }
$refProp->setValue($obj, json_decode($value, true)); $refProp->setValue($obj, \json_decode($value, true));
} elseif (static::$columns[$column]['type'] === 'Serializable') { } elseif (static::$columns[$column]['type'] === 'Serializable') {
$member = $refProp->getValue($obj); $member = $refProp->getValue($obj);
$member->unserialize($value); $member->unserialize($value);
@ -1852,18 +1852,18 @@ class DataMapperAbstract implements DataMapperInterface
if (isset(static::$columns[$column]['internal'])) { if (isset(static::$columns[$column]['internal'])) {
$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 (in_array(static::$columns[$column]['type'], ['string', 'int', 'float', 'bool'])) { if (\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 = new \DateTime($value ?? ''); $value = new \DateTime($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);
@ -1949,8 +1949,8 @@ class DataMapperAbstract implements DataMapperInterface
private static function getNullModelObj() private static function getNullModelObj()
{ {
$class = static::class; $class = static::class;
$class = str_replace('Mapper', '', $class); $class = \str_replace('Mapper', '', $class);
$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);
@ -1965,7 +1965,7 @@ class DataMapperAbstract implements DataMapperInterface
* @param int $relations Load relations * @param int $relations Load relations
* @param int $depth Relation depth * @param int $depth Relation depth
* *
* @return mixed * @return array
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@ -2574,7 +2574,7 @@ class DataMapperAbstract implements DataMapperInterface
$result = static::getAll(); $result = static::getAll();
} elseif ($filter === 'list') { } elseif ($filter === 'list') {
$list = $request->getData('list'); $list = $request->getData('list');
$result = static::get(json_decode($list, true)); $result = static::get(\json_decode($list, true));
} else { } else {
$limit = (int) ($request->getData('limit') ?? 1); $limit = (int) ($request->getData('limit') ?? 1);
$from = $request->getData('from') === null ? null : new \DateTime((string) $request->getData('from')); $from = $request->getData('from') === null ? null : new \DateTime((string) $request->getData('from'));

View File

@ -245,7 +245,7 @@ abstract class GrammarAbstract
} }
// todo: move remaining * test also here not just if .* but also if * (should be done in else?) // todo: move remaining * test also here not just if .* but also if * (should be done in else?)
if (count($split = explode('.', $system)) === 2) { if (count($split = \explode('.', $system)) === 2) {
$system = $split[1] === '*' ? $split[1] : $this->compileSystem($split[1]); $system = $split[1] === '*' ? $split[1] : $this->compileSystem($split[1]);
return $this->compileSystem($prefix . $split[0]) . '.' . $system; return $this->compileSystem($prefix . $split[0]) . '.' . $system;

View File

@ -38,7 +38,7 @@ final class Builder extends BuilderAbstract
/** /**
* Columns. * Columns.
* *
* @var array * @var array<string, array<string, string>>
* @since 1.0.0 * @since 1.0.0
*/ */
public $selects = []; public $selects = [];
@ -46,7 +46,7 @@ final class Builder extends BuilderAbstract
/** /**
* Columns. * Columns.
* *
* @var array * @var array<string, array<string, string>>
* @since 1.0.0 * @since 1.0.0
*/ */
public $updates = []; public $updates = [];
@ -486,7 +486,7 @@ final class Builder extends BuilderAbstract
*/ */
public function where($columns, $operator = null, $values = null, $boolean = 'and') : Builder public function where($columns, $operator = null, $values = null, $boolean = 'and') : Builder
{ {
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.');
} }
@ -499,7 +499,7 @@ final class Builder extends BuilderAbstract
$i = 0; $i = 0;
foreach ($columns as $key => $column) { foreach ($columns as $key => $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.');
} }

View File

@ -80,29 +80,29 @@ class HttpSession implements SessionInterface
throw new LockException('HttpSession'); throw new LockException('HttpSession');
} }
if (session_id()) { if (\session_id()) {
session_write_close(); \session_write_close();
} }
if (!is_bool($sid)) { if (!\is_bool($sid)) {
session_id($sid); \session_id($sid);
} }
$this->inactivityInterval = $inactivityInterval; $this->inactivityInterval = $inactivityInterval;
if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) { if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
session_set_cookie_params($liftetime, '/', '', false, true); \session_set_cookie_params($liftetime, '/', '', false, true);
session_start(); \session_start();
} }
if ($this->inactivityInterval > 0 && ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < time())) { if ($this->inactivityInterval > 0 && ($this->inactivityInterval + ($_SESSION['lastActivity'] ?? 0) < \time())) {
$this->destroy(); $this->destroy();
} }
$this->sessionData = $_SESSION; $this->sessionData = $_SESSION;
$_SESSION = null; $_SESSION = null;
$this->sessionData['lastActivity'] = time(); $this->sessionData['lastActivity'] = \time();
$this->sid = session_id(); $this->sid = \session_id();
$this->setCsrfProtection(); $this->setCsrfProtection();
} }
@ -175,7 +175,7 @@ class HttpSession implements SessionInterface
{ {
if (!self::$isLocked) { if (!self::$isLocked) {
$_SESSION = $this->sessionData; $_SESSION = $this->sessionData;
session_write_close(); \session_write_close();
} }
} }
@ -218,9 +218,9 @@ class HttpSession implements SessionInterface
*/ */
private function destroy() : void private function destroy() : void
{ {
session_destroy(); \session_destroy();
$this->sessionData = []; $this->sessionData = [];
session_start(); \session_start();
} }
/** /**

View File

@ -11,7 +11,7 @@
* @link http://website.orange-management.de * @link http://website.orange-management.de
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace phpOMS\Utils\Crawler; namespace phpOMS\DataStorage\Web;
use phpOMs\DataStorage\Database\Query\Builder as DatabaseQueryBuilder; use phpOMs\DataStorage\Database\Query\Builder as DatabaseQueryBuilder;
use phpOMS\Localization\Localization; use phpOMS\Localization\Localization;
@ -26,7 +26,7 @@ use phpOMS\Uri\Http;
* @link http://website.orange-management.de * @link http://website.orange-management.de
* @since 1.0.0 * @since 1.0.0
*/ */
class Builder extends DatabaseQueryBuilder class Builder
{ {
private function download($uri) private function download($uri)

View File

@ -103,9 +103,9 @@ final class Dispatcher
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 (!file_exists($path = __DIR__ . '/../../' . str_replace('\\', '/', $dispatch[0]) . '.php')) { if (!\file_exists($path = __DIR__ . '/../../' . \str_replace('\\', '/', $dispatch[0]) . '.php')) {
throw new PathException($path); throw new PathException($path);
} }
@ -174,7 +174,7 @@ final class Dispatcher
if (!isset($this->controllers[$controller])) { if (!isset($this->controllers[$controller])) {
// If module controller use module manager for initialization // If module controller use module manager for initialization
if (strpos('\Modules\Controller', $controller) === 0) { if (strpos('\Modules\Controller', $controller) === 0) {
$split = explode('\\', $controller); $split = \explode('\\', $controller);
$this->controllers[$controller] = $this->app->moduleManager->get($split[2]); $this->controllers[$controller] = $this->app->moduleManager->get($split[2]);
} else { } else {
$this->controllers[$controller] = new $controller($this->app); $this->controllers[$controller] = new $controller($this->app);

View File

@ -4,7 +4,7 @@
* *
* PHP Version 7.2 * PHP Version 7.2
* *
* @package TBD * @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn * @copyright Dennis Eichhorn
* @license OMS License 1.0 * @license OMS License 1.0
* @version 1.0.0 * @version 1.0.0
@ -12,22 +12,44 @@
*/ */
declare(strict_types=1); declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP; namespace phpOMS\Localization\Defaults;
use phpOMS\Math\Geometry\Shape\D3\Sphere;
/** /**
* City class. * City class.
* *
* @package Framework * @package phpOMS\Localization\Defaults
* @license OMS License 1.0 * @license OMS License 1.0
* @link http://website.orange-management.de * @link http://website.orange-management.de
* @since 1.0.0 * @since 1.0.0
*/ */
class City final class City
{ {
/** /**
* City name * City id.
*
* @var int
* @since 1.0.0
*/
private $id = 0;
/**
* Country code.
*
* @var string
* @since 1.0.0
*/
private $countryCode = '';
/**
* State code.
*
* @var string
* @since 1.0.0
*/
private $state = '';
/**
* City name.
* *
* @var string * @var string
* @since 1.0.0 * @since 1.0.0
@ -35,15 +57,15 @@ class City
private $name = ''; private $name = '';
/** /**
* City longitude * Postal code.
* *
* @var float * @var int
* @since 1.0.0 * @since 1.0.0
*/ */
private $long = 0.0; private $postal = 0;
/** /**
* City latitude * Latitude.
* *
* @var float * @var float
* @since 1.0.0 * @since 1.0.0
@ -51,37 +73,15 @@ class City
private $lat = 0.0; private $lat = 0.0;
/** /**
* Constructor. * Longitude.
* *
* @param float $lat Latitude * @var float
* @param float $long Longitude * @since 1.0.0
* @param string $name City name
*
* @since 1.0.0
*/ */
public function __construct(float $lat = 0, float $long = 0, string $name = '') private $long = 0.0;
{
$this->long = $long;
$this->lat = $lat;
$this->name = $name;
}
/** /**
* Is equals to. * Get city name
*
* @param City $city City
*
* @return bool
*
* @since 1.0.0
*/
public function equals(City $city) : bool
{
return $this->name === $city->getName() && $this->lat === $city->getLatitude() && $this->long === $city->getLatitude();
}
/**
* Get name.
* *
* @return string * @return string
* *
@ -93,39 +93,61 @@ class City
} }
/** /**
* Get latitude. * Get country code
*
* @return string
*
* @since 1.0.0
*/
public function getCountryCode() : string
{
return $this->countryCode;
}
/**
* Get city state
*
* @return string
*
* @since 1.0.0
*/
public function getState() : string
{
return $this->state;
}
/**
* Get city postal
*
* @return int
*
* @since 1.0.0
*/
public function getPostal() : int
{
return $this->postal;
}
/**
* Get city latitude
* *
* @return float * @return float
* *
* @since 1.0.0 * @since 1.0.0
*/ */
public function getLatitude() : float public function getLat() : float
{ {
return $this->lat; return $this->lat;
} }
/** /**
* Distance to city in meter * Get city longitude
*
* @param City $city City
* *
* @return float * @return float
* *
* @since 1.0.0 * @since 1.0.0
*/ */
public function getDistanceTo(City $city) : float public function getLong() : float
{
return Sphere::distance2PointsOnSphere($this->lat, $this->long, $city->getLatitude(), $city->getLongitude());
}
/**
* Get longitude.
*
* @return float
*
* @since 1.0.0
*/
public function getLongitude() : float
{ {
return $this->long; return $this->long;
} }

View File

@ -0,0 +1,64 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
use phpOMS\DataStorage\Database\DataMapperAbstract;
use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\Database\Query\Column;
use phpOMS\DataStorage\Database\RelationType;
/**
* Mapper class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class CityMapper extends DataMapperAbstract
{
/**
* Columns.
*
* @var array<string, array<string, string>>
* @since 1.0.0
*/
protected static $columns = [
'city_id' => ['name' => 'city_id', 'type' => 'int', 'internal' => 'id'],
'city_city' => ['name' => 'city_city', 'type' => 'string', 'internal' => 'name'],
'city_country' => ['name' => 'city_country', 'type' => 'string', 'internal' => 'countryCode'],
'city_state' => ['name' => 'city_state', 'type' => 'string', 'internal' => 'state'],
'city_postal' => ['name' => 'city_postal', 'type' => 'int', 'internal' => 'postal'],
'city_lat' => ['name' => 'city_lat', 'type' => 'float', 'internal' => 'lat'],
'city_long' => ['name' => 'city_long', 'type' => 'float', 'internal' => 'long'],
];
/**
* Primary table.
*
* @var string
* @since 1.0.0
*/
protected static $table = 'city';
/**
* Primary field name.
*
* @var string
* @since 1.0.0
*/
protected static $primaryField = 'city_id';
}

View File

@ -0,0 +1,134 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
/**
* Country class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
final class Country
{
/**
* Country id.
*
* @var int
* @since 1.0.0
*/
private $id = 0;
/**
* Country name.
*
* @var string
* @since 1.0.0
*/
private $name = '';
/**
* Country code.
*
* @var string
* @since 1.0.0
*/
private $code2 = '';
/**
* Country code.
*
* @var string
* @since 1.0.0
*/
private $code3 = '';
/**
* Country code.
*
* @var int
* @since 1.0.0
*/
private $numeric = 0;
/**
* Country subdevision.
*
* @var string
* @since 1.0.0
*/
private $subdevision = '';
/**
* Get country name
*
* @return string
*
* @since 1.0.0
*/
public function getName() : string
{
return $this->name;
}
/**
* Get country code
*
* @return string
*
* @since 1.0.0
*/
public function getCode2() : string
{
return $this->code2;
}
/**
* Get country code
*
* @return string
*
* @since 1.0.0
*/
public function getCode3() : string
{
return $this->code3;
}
/**
* Get country numeric
*
* @return int
*
* @since 1.0.0
*/
public function getNumeric() : int
{
return $this->numeric;
}
/**
* Get country subdevision
*
* @return string
*
* @since 1.0.0
*/
public function getSubdevision() : string
{
return $this->subdevision;
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
use phpOMS\DataStorage\Database\DataMapperAbstract;
use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\Database\Query\Column;
use phpOMS\DataStorage\Database\RelationType;
/**
* Mapper class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class CountryMapper extends DataMapperAbstract
{
/**
* Columns.
*
* @var array<string, array<string, string>>
* @since 1.0.0
*/
protected static $columns = [
'country_id' => ['name' => 'country_id', 'type' => 'int', 'internal' => 'id'],
'country_name' => ['name' => 'country_name', 'type' => 'string', 'internal' => 'name'],
'country_code2' => ['name' => 'country_code2', 'type' => 'string', 'internal' => 'code2'],
'country_code3' => ['name' => 'country_code3', 'type' => 'string', 'internal' => 'code3'],
'country_numeric' => ['name' => 'country_numeric', 'type' => 'int', 'internal' => 'numeric'],
'country_subdevision' => ['name' => 'country_subdevision', 'type' => 'float', 'internal' => 'subdevision'],
];
/**
* Primary table.
*
* @var string
* @since 1.0.0
*/
protected static $table = 'country';
/**
* Primary field name.
*
* @var string
* @since 1.0.0
*/
protected static $primaryField = 'country_id';
}

View File

@ -0,0 +1,134 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
/**
* Currency class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
final class Currency
{
/**
* Currency id.
*
* @var int
* @since 1.0.0
*/
private $id = 0;
/**
* Currency name.
*
* @var string
* @since 1.0.0
*/
private $name = '';
/**
* Currency code.
*
* @var string
* @since 1.0.0
*/
private $code = '';
/**
* Currency code.
*
* @var int
* @since 1.0.0
*/
private $number = 0;
/**
* Currency decimals.
*
* @var int
* @since 1.0.0
*/
private $decimals = 0;
/**
* Currency countries.
*
* @var string
* @since 1.0.0
*/
private $countries = '';
/**
* Get currency name
*
* @return string
*
* @since 1.0.0
*/
public function getName() : string
{
return $this->name;
}
/**
* Get currency code
*
* @return string
*
* @since 1.0.0
*/
public function getCode() : string
{
return $this->code;
}
/**
* Get currency code
*
* @return int
*
* @since 1.0.0
*/
public function getNumber() : int
{
return $this->number;
}
/**
* Get currency decimals
*
* @return int
*
* @since 1.0.0
*/
public function getDecimals() : int
{
return $this->decimals;
}
/**
* Get currency countries
*
* @return string
*
* @since 1.0.0
*/
public function getCountries() : string
{
return $this->countries;
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
use phpOMS\DataStorage\Database\DataMapperAbstract;
use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\Database\Query\Column;
use phpOMS\DataStorage\Database\RelationType;
/**
* Mapper class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class CurrencyMapper extends DataMapperAbstract
{
/**
* Columns.
*
* @var array<string, array<string, string>>
* @since 1.0.0
*/
protected static $columns = [
'currency_id' => ['name' => 'currency_id', 'type' => 'int', 'internal' => 'id'],
'currency_name' => ['name' => 'currency_name', 'type' => 'string', 'internal' => 'name'],
'currency_code' => ['name' => 'currency_code', 'type' => 'string', 'internal' => 'code'],
'currency_number' => ['name' => 'currency_number', 'type' => 'int', 'internal' => 'number'],
'currency_decimal' => ['name' => 'currency_decimal', 'type' => 'int', 'internal' => 'decimal'],
'currency_countries' => ['name' => 'currency_countries', 'type' => 'string', 'internal' => 'countries'],
];
/**
* Primary table.
*
* @var string
* @since 1.0.0
*/
protected static $table = 'currency';
/**
* Primary field name.
*
* @var string
* @since 1.0.0
*/
protected static $primaryField = 'currency_id';
}

View File

@ -0,0 +1,114 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
/**
* iban class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
final class Iban
{
/**
* Iban id.
*
* @var int
* @since 1.0.0
*/
private $id = 0;
/**
* Iban country.
*
* @var string
* @since 1.0.0
*/
private $country = '';
/**
* Iban chars.
*
* @var string
* @since 1.0.0
*/
private $chars = '';
/**
* Iban bban.
*
* @var string
* @since 1.0.0
*/
private $bban = '';
/**
* Iban fields.
*
* @var string
* @since 1.0.0
*/
private $fields = '';
/**
* Get iban country
*
* @return string
*
* @since 1.0.0
*/
public function getCountry() : string
{
return $this->country;
}
/**
* Get iban chars
*
* @return string
*
* @since 1.0.0
*/
public function getChars() : string
{
return $this->chars;
}
/**
* Get iban bban
*
* @return string
*
* @since 1.0.0
*/
public function getBban() : string
{
return $this->bban;
}
/**
* Get iban fields
*
* @return string
*
* @since 1.0.0
*/
public function getFields() : string
{
return $this->fields;
}
}

View File

@ -0,0 +1,62 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
use phpOMS\DataStorage\Database\DataMapperAbstract;
use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\Database\Query\Column;
use phpOMS\DataStorage\Database\RelationType;
/**
* Mapper class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class IbanMapper extends DataMapperAbstract
{
/**
* Columns.
*
* @var array<string, array<string, string>>
* @since 1.0.0
*/
protected static $columns = [
'iban_id' => ['name' => 'iban_id', 'type' => 'int', 'internal' => 'id'],
'iban_country' => ['name' => 'iban_country', 'type' => 'string', 'internal' => 'country'],
'iban_chars' => ['name' => 'iban_chars', 'type' => 'string', 'internal' => 'chars'],
'iban_bban' => ['name' => 'iban_bban', 'type' => 'string', 'internal' => 'bban'],
'iban_fields' => ['name' => 'iban_fields', 'type' => 'string', 'internal' => 'fields'],
];
/**
* Primary table.
*
* @var string
* @since 1.0.0
*/
protected static $table = 'iban';
/**
* Primary field name.
*
* @var string
* @since 1.0.0
*/
protected static $primaryField = 'iban_id';
}

View File

@ -0,0 +1,114 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
/**
* Language class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
final class Language
{
/**
* Language id.
*
* @var int
* @since 1.0.0
*/
private $id = 0;
/**
* Language name.
*
* @var string
* @since 1.0.0
*/
private $name = '';
/**
* Language native.
*
* @var string
* @since 1.0.0
*/
private $native = '';
/**
* Language code.
*
* @var string
* @since 1.0.0
*/
private $code2 = '';
/**
* Language code.
*
* @var string
* @since 1.0.0
*/
private $code3 = '';
/**
* Get language name
*
* @return string
*
* @since 1.0.0
*/
public function getName() : string
{
return $this->name;
}
/**
* Get language native
*
* @return string
*
* @since 1.0.0
*/
public function getNative() : string
{
return $this->native;
}
/**
* Get language code
*
* @return string
*
* @since 1.0.0
*/
public function getCode2() : string
{
return $this->code2;
}
/**
* Get language code
*
* @return string
*
* @since 1.0.0
*/
public function getCode3() : string
{
return $this->code3;
}
}

View File

@ -0,0 +1,62 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package phpOMS\Localization\Defaults
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Localization\Defaults;
use phpOMS\DataStorage\Database\DataMapperAbstract;
use phpOMS\DataStorage\Database\Query\Builder;
use phpOMS\DataStorage\Database\Query\Column;
use phpOMS\DataStorage\Database\RelationType;
/**
* Mapper class.
*
* @package phpOMS\Localization\Defaults
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class LanguageMapper extends DataMapperAbstract
{
/**
* Columns.
*
* @var array<string, array<string, string>>
* @since 1.0.0
*/
protected static $columns = [
'language_id' => ['name' => 'language_id', 'type' => 'int', 'internal' => 'id'],
'language_name' => ['name' => 'language_name', 'type' => 'string', 'internal' => 'name'],
'language_native' => ['name' => 'language_native', 'type' => 'string', 'internal' => 'native'],
'language_639_2T' => ['name' => 'language_639_2T', 'type' => 'string', 'internal' => 'code2'],
'language_639_3' => ['name' => 'language_639_3', 'type' => 'string', 'internal' => 'code3'],
];
/**
* Primary table.
*
* @var string
* @since 1.0.0
*/
protected static $table = 'language';
/**
* Primary field name.
*
* @var string
* @since 1.0.0
*/
protected static $primaryField = 'language_id';
}

View File

@ -106,9 +106,9 @@ final class Money implements \Serializable
*/ */
public static function toInt(string $value, string $thousands = ',', string $decimal = '.') : int public static function toInt(string $value, string $thousands = ',', string $decimal = '.') : int
{ {
$split = explode($decimal, $value); $split = \explode($decimal, $value);
$left = $split[0]; $left = $split[0];
$left = str_replace($thousands, '', $left); $left = \str_replace($thousands, '', $left);
$right = ''; $right = '';
if (count($split) > 1) { if (count($split) > 1) {

View File

@ -119,7 +119,7 @@ final class FileLogger implements LoggerInterface
*/ */
private function createFile() : void private function createFile() : void
{ {
if (!$this->created && !file_exists($this->path)) { if (!$this->created && !\file_exists($this->path)) {
File::create($this->path); File::create($this->path);
$this->created = true; $this->created = true;
} }
@ -186,7 +186,7 @@ final class FileLogger implements LoggerInterface
return false; return false;
} }
$mtime = explode(' ', microtime()); $mtime = \explode(' ', microtime());
$mtime = $mtime[1] + $mtime[0]; $mtime = $mtime[1] + $mtime[0];
self::$timings[$id] = ['start' => $mtime]; self::$timings[$id] = ['start' => $mtime];
@ -205,7 +205,7 @@ final class FileLogger implements LoggerInterface
*/ */
public static function endTimeLog($id = '') : float public static function endTimeLog($id = '') : float
{ {
$mtime = explode(' ', microtime()); $mtime = \explode(' ', microtime());
$mtime = $mtime[1] + $mtime[0]; $mtime = $mtime[1] + $mtime[0];
self::$timings[$id]['end'] = $mtime; self::$timings[$id]['end'] = $mtime;
@ -241,7 +241,7 @@ final class FileLogger implements LoggerInterface
} }
} }
$backtrace = json_encode($backtrace); $backtrace = \json_encode($backtrace);
$replace['{backtrace}'] = $backtrace; $replace['{backtrace}'] = $backtrace;
$replace['{datetime}'] = sprintf('%--19s', (new \DateTime('NOW'))->format('Y-m-d H:i:s')); $replace['{datetime}'] = sprintf('%--19s', (new \DateTime('NOW'))->format('Y-m-d H:i:s'));
@ -382,7 +382,7 @@ final class FileLogger implements LoggerInterface
{ {
$levels = []; $levels = [];
if (!file_exists($this->path)) { if (!\file_exists($this->path)) {
return $levels; return $levels;
} }
@ -418,7 +418,7 @@ final class FileLogger implements LoggerInterface
{ {
$connection = []; $connection = [];
if (!file_exists($this->path)) { if (!\file_exists($this->path)) {
return $connection; return $connection;
} }
@ -457,7 +457,7 @@ final class FileLogger implements LoggerInterface
$logs = []; $logs = [];
$id = 0; $id = 0;
if (!file_exists($this->path)) { if (!\file_exists($this->path)) {
return $logs; return $logs;
} }
@ -506,7 +506,7 @@ final class FileLogger implements LoggerInterface
$log = []; $log = [];
$current = 0; $current = 0;
if (!file_exists($this->path)) { if (!\file_exists($this->path)) {
return $log; return $log;
} }

View File

@ -14,6 +14,8 @@ declare(strict_types=1);
namespace phpOMS\Math\Geometry\Shape\D2; namespace phpOMS\Math\Geometry\Shape\D2;
use phpOMS\Math\Functions\Functions;
/** /**
* Triangle shape. * Triangle shape.
* *
@ -76,4 +78,23 @@ final class Triangle implements D2ShapeInterface
{ {
return 2 * $area / $b; return 2 * $area / $b;
} }
/**
* Calculate the hypothenuse
*
* @param mixed ...$vec Vector of values
*
* @return float
*
* @since 1.0.0
*/
public static function getHypot(...$vec) : float
{
$hypot = 0.0;
foreach ($vec as $val) {
$hypot += $val * $val;
}
return \sqrt($hypot);
}
} }

View File

@ -18,6 +18,8 @@ use phpOMS\Math\Matrix\Exception\InvalidDimensionException;
/** /**
* Cholesky decomposition * Cholesky decomposition
*
* A is syymetric, positive definite then A = L*L'
* *
* @package phpOMS\Math\Matrix * @package phpOMS\Math\Matrix
* @license OMS License 1.0 * @license OMS License 1.0

View File

@ -14,14 +14,347 @@ declare(strict_types=1);
namespace phpOMS\Math\Matrix; namespace phpOMS\Math\Matrix;
use phpOMS\Math\Geometry\Shape\D2\Triangle;
/** /**
* Eigenvalue decomposition * Eigenvalue decomposition
*
* A symmetric then A = V*D*V'
* A not symmetric then (potentially) A = V*D*inverse(V)
* *
* @package phpOMS\Math\Matrix * @package phpOMS\Math\Matrix
* @license OMS License 1.0 * @license OMS License 1.0
* @link http://website.orange-management.de * @link http://website.orange-management.de
* @since 1.0.0 * @since 1.0.0
*/ */
final class EigenValueDecomposition final class EigenvalueDecomposition
{ {
/**
* Dimension m
*
* @var int
* @since 1.0.0
*/
private $m = 0;
/**
* Is symmetric
*
* @var bool
* @since 1.0.0
*/
private $isSymmetric = true;
/**
* A square matrix.
*
* @var array
* @since 1.0.0
*/
private $A = [];
/**
* Eigenvectors
*
* @var array
* @since 1.0.0
*/
private $V = [];
/**
* Eigenvalues
*
* @var array
* @since 1.0.0
*/
private $D = [];
/**
* Eigenvalues
*
* @var array
* @since 1.0.0
*/
private $E = [];
/**
* Hessenberg form
*
* @var array
* @since 1.0.0
*/
private $H = [];
/**
* Non-symmetric storage
*
* @var array
* @since 1.0.0
*/
private $ort = [];
/**
* Constructor.
*
* @param Matrix $M Matrix
*
* @since 1.0.0
*/
public function __construct(Matrix $M)
{
$this->m = $M->getM();
$this->A = $M->toArray();
}
/**
* Housholder tridiagonal form reduction.
*
* @return void
*
* @since 1.0.0
*/
private function tred2() : void
{
for ($j = 0; $j < $this->m; ++$j) {
$this->D[$j] = $this->V[$this->m - 1][$j];
}
for ($i = $this->m - 1; $i > 0; --$i) {
$scale = 0.0;
$h = 0.0;
for ($k = 0; $k < $i; ++$k) {
$scale += \abs($this->D[$k]);
}
if ($scale === 0.0) {
$this->E[$i] = $this->D[$i - 1];
for ($j = 0; $j > $i; ++$j) {
$this->D[$j] = $this->V[$i - 1][$j];
$this->V[$i][$j] = 0.0;
$this->V[$j][$i] = 0.0;
}
} else {
for ($k = 0; $k < $i; ++$k) {
$this->D[$k] /= $scale;
$h += $this->D[$k] * $this->D[$k];
}
$f = $this->D[$i - 1];
$g = \sqrt($h);
if ($f > 0) {
$g = -$g;
}
$this->E[$i] = $scale * $g;
$h -= $f * $g;
$this->D[$i - 1] = $f - $g;
for ($j = 0; $j < $i; ++$j) {
$this->E[$j] = 0.0;
}
for ($j = 0; $j < $i; ++$j) {
$f = $this->D[$j];
$this->V[$j][$i] = $f;
$g = $this->E[$j] + $this->V[$j][$j] * $f;
for ($k = $j + 1; $k <= $i - 1; ++$k) {
$g += $this->V[$k][$j] * $this->D[$k];
$this->E[$k] += $this->V[$k][$j] * $f;
}
$this->E[$j] = $g;
}
$f = 0.0;
for ($j = 0; $j < $i; ++$j) {
$this->E[$j] /= $h;
$f += $this->E[$j] * $this->D[$j];
}
$hh = $f / ($h + $h);
for ($j = 0; $j < $i; ++$j) {
$this->E[$j] -= $hh * $this->D[$j];
}
for ($j = 0; $j < $i; ++$j) {
$f = $this->D[$j];
$g = $this->E[$j];
for ($k = $j; $k <= $i - 1; ++$k) {
$this->V[$k][$j] -= ($f * $this->E[$k] + $g * $this->D[$k]);
}
$this->D[$j] = $this->V[$i - 1][$j];
$this->V[$i][$j] = 0.0;
}
}
$this->D[$i] = $h;
}
for ($i = 0; $i < $this->m - 1; ++$i) {
$this->V[$this->m - 1][$i] = $this->V[$i][$i];
$this->V[$i][$i] = 1.0;
$h = $this->D[$i + 1];
if ($h !== 0.0) {
for ($k = 0; $k <= $i; ++$k) {
$this->D[$k] = $this->V[$k][$i + 1] / $h;
}
for ($j = 0; $j <= $i; ++$j) {
$g = 0.0;
for ($k = 0; $k <= $i; ++$k) {
$g += $this->V[$k][$i + 1] * $this->V[$k][$j];
}
for ($k = 0; $k <= $i; ++$k) {
$this->V[$k][$j] -= $g * $this->D[$k];
}
}
}
for ($k = 0; $k <= $i; ++$k) {
$this->V[$k][$i + 1] = 0.0;
}
}
for ($j = 0; $j < $this->m; ++$j) {
$this->D[$j] = $this->V[$this->m - 1][$j];
$this->V[$this->m - 1][$j] = 0.0;
}
$this->V[$this->m - 1][$j] = 1.0;
$this->E[0] = 0.0;
}
/**
* Symmetric tridiagonal QL
*
* @return void
*
* @since 1.0.0
*/
private function tql2() : void
{
for ($i = 1; $i < $this->m; ++$i) {
$this->E[$i - 1] = $this->E[$i];
}
$this->E[$this->m - 1] = 0.0;
$f = 0.0;
$tst1 = 0.0;
$eps = 0.00001;
for ($l = 0; $l < $this->m; ++$l) {
$tst1 = \max($tst1, \abs($this->D[$l]) + \abs($this->E[$l]));
$m = $l;
while ($m < $this->m) {
if (\abs($this->E[$m]) <= $eps * $tst1) {
break;
}
++$m;
}
if ($m > $l) {
$iter = 0;
do {
$iter = $iter + 1;
$g = $this->D[$l];
$p = ($this->D[$l + 1] - $g) / (2.0 * $this->E[$l]);
$r = Triangle::getHypot($p, 1);
if ($p > 0) {
$r = -$r;
}
$this->D[$l] = $this->E[$l] / ($p + $r);
$this->D[$l + 1] = $this->E[$l] * ($p + $r);
$dl1 = $this->D[$l + 1];
$h = $g - $this->D[$l];
for ($i = $l + 2; $i < $this->m; ++$i) {
$this->D[$i] -= $h;
}
$f += $h;
$p = $this->D[$m];
$c = 1.0;
$c2 = 1.0;
$c3 = 1.0;
$el1 = $this->E[$l + 1];
$s = 0.0;
$s2 = 0.0;
for ($i = $m - 1; $i >= $l; --$i) {
$c3 = $c2;
$c2 = $c;
$s2 = $s;
$g = $c * $this->E[$i];
$h = $c * $p;
$r = Triangle::getHypot($p, $this->E[$i]);
$this->E[$i + 1] = $s * $r;
$s = $this->E[$i] / $r;
$c = $p / $r;
$p = $c * $this->D[$i] - $s * $g;
$this->D[$i + 1] = $h + $s * ($c * $g + $s * $this->D[$i]);
for ($k = 0; $k < $this->m; ++$k) {
$h = $this->V[$k][$i + 1];
$this->V[$k][$i + 1] = $s * $this->V[$k][$i] + $c * $h;
$this->V[$k][$i] = $c * $this->V[$k][$i] - $s * $h;
}
}
$p = -$s * $s2 * $c3 * $el1 * $this->E[$l] / $dl1;
$this->E[$l] = $s * $p;
$this->D[$l] = $c * $p;
} while (\abs($this->E[$l]) > $eps * $tst1);
}
$this->D[$l] += $f;
$this->E[$l] = 0.0;
}
for ($i = 0; $i < $this->m - 1; ++$i) {
$k = $i;
$p = $this->D[$i];
for ($j = $i + 1; $j < $this->m; ++$j) {
if ($this->D[$j] < $p) {
$k = $j;
$p = $this->D[$j];
}
}
if ($k !== $i) {
$this->D[$k] = $this->D[$i];
$this->D[$i] = $p;
for ($j = 0; $j < $this->m; ++$j) {
$p = $this->V[$j][$i];
$this->V[$j][$i] = $this->V[$j][$k];
$this->V[$j][$k] = $p;
}
}
}
}
private function orthes() : void
{
}
public function isSymmetric() : bool
{
return $this->isSymmetric;
}
} }

View File

@ -18,6 +18,8 @@ use phpOMS\Math\Matrix\Exception\InvalidDimensionException;
/** /**
* LU decomposition * LU decomposition
*
* A(piv,:) = L*U
* *
* @package phpOMS\Math\Matrix * @package phpOMS\Math\Matrix
* @license OMS License 1.0 * @license OMS License 1.0
@ -253,8 +255,7 @@ final class LUDecomposition
} }
$n = $B->getN(); $n = $B->getN();
$X = $B->getMatrix($this->piv, 0, $n - 1); $X = $B->getSubMatrixByRows($this->piv, 0, $n - 1)->toArray();
// todo: fix get extract
// Solve L*Y = B(piv,:) // Solve L*Y = B(piv,:)
for ($k = 0; $k < $this->n; ++$k) { for ($k = 0; $k < $this->n; ++$k) {

View File

@ -137,7 +137,7 @@ class Matrix implements \ArrayAccess, \Iterator
/** /**
* Get matrix array. * Get matrix array.
* *
* @return array * @return array<int, array<int, mixed>>
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@ -146,10 +146,121 @@ class Matrix implements \ArrayAccess, \Iterator
return $this->matrix; return $this->matrix;
} }
/**
* Get sub matrix array.
*
* @param int $iRow Start row
* @param int $lRow End row
* @param int $iCol Start col
* @param int $lCol End col
*
* @return Matrix
*
* @since 1.0.0
*/
public function getSubMatrix(int $iRow, int $lRow, int $iCol, int $lCol) : Matrix
{
$X = [[]];
for ($i = $iRow; $i <= $lRow; ++$i) {
for ($j = $iCol; $j <= $lCol; ++$j) {
$X[$i - $iRow][$j - $iCol] = $this->matrix[$i][$j];
}
}
$matrix = new self();
$matrix->setMatrix($X);
return $matrix;
}
/**
* Get sub matrix array.
*
* @param array $rows Row indices
* @param array $cols Row indices
*
* @return Matrix
*
* @since 1.0.0
*/
public function getSubMatrixByColumnsRows(array $rows, array $cols) : Matrix
{
$X = [[]];
$rlength = count($rows);
$clength = count($cols);
for ($i = 0; $i <= $rlength; ++$i) {
for ($j = 0; $j <= $clength; ++$j) {
$X[$i][$j] = $this->matrix[$rows[$i]][$cols[$j]];
}
}
$matrix = new self();
$matrix->setMatrix($X);
return $matrix;
}
/**
* Get sub matrix array.
*
* @param int $iRow Start row
* @param int $lRow End row
* @param array $cols Row indices
*
* @return Matrix
*
* @since 1.0.0
*/
public function getSubMatrixByColumns(int $iRow, int $lRow, array $cols) : Matrix
{
$X = [[]];
$length = count($cols);
for ($i = $iRow; $i <= $lRow; ++$i) {
for ($j = 0; $j <= $length; ++$j) {
$X[$i - $iRow][$j] = $this->matrix[$i][$cols[$j]];
}
}
$matrix = new self();
$matrix->setMatrix($X);
return $matrix;
}
/**
* Get sub matrix array.
*
* @param array $rows Row indices
* @param int $iCol Start col
* @param int $lCol End col
*
* @return Matrix
*
* @since 1.0.0
*/
public function getSubMatrixByRows(array $rows, int $iCol, int $lCol) : Matrix
{
$X = [[]];
$length = count($rows);
for ($i = 0; $i < $length; ++$i) {
for ($j = $iCol; $j <= $lCol; ++$j) {
$X[$i][$j - $iCol] = $this->matrix[$rows[$i]][$j];
}
}
$matrix = new self();
$matrix->setMatrix($X);
return $matrix;
}
/** /**
* Get matrix array. * Get matrix array.
* *
* @return array * @return array<int, array<int, mixed>>
* *
* @since 1.0.0 * @since 1.0.0
*/ */
@ -158,6 +269,18 @@ class Matrix implements \ArrayAccess, \Iterator
return $this->matrix; return $this->matrix;
} }
/**
* Is symmetric.
*
* @return bool
*
* @since 1.0.0
*/
public function isSymmetric() : bool
{
return (new EigenvalueDecomposition($this))->isSymmetric();
}
/** /**
* Get matrix rank. * Get matrix rank.
* *
@ -574,7 +697,7 @@ class Matrix implements \ArrayAccess, \Iterator
/** /**
* Solve matrix * Solve matrix
* *
* @param Matix $B Matrix/Vector b * @param Matrix $B Matrix/Vector b
* *
* @return Matrix * @return Matrix
* *

View File

@ -14,8 +14,13 @@ declare(strict_types=1);
namespace phpOMS\Math\Matrix; namespace phpOMS\Math\Matrix;
use phpOMS\Math\Matrix\Exception\InvalidDimensionException;
use phpOMS\Math\Geometry\Shape\D2\Triangle;
/** /**
* QR decomposition * QR decomposition
*
* For every matrix A = Q*R
* *
* @package phpOMS\Math\Matrix * @package phpOMS\Math\Matrix
* @license OMS License 1.0 * @license OMS License 1.0
@ -24,26 +29,58 @@ namespace phpOMS\Math\Matrix;
*/ */
final class QRDecomposition final class QRDecomposition
{ {
/**
* QR matrix.
*
* @var array[]
* @since 1.0.0
*/
private $QR = []; private $QR = [];
/**
* Dimension m
*
* @var int
* @since 1.0.0
*/
private $m = 0; private $m = 0;
/**
* Dimension n
*
* @var int
* @since 1.0.0
*/
private $n = 0; private $n = 0;
/**
* R diagonal
*
* @var array
* @since 1.0.0
*/
private $Rdiag = []; private $Rdiag = [];
/**
* Constructor.
*
* @param Matrix $M Matrix
*
* @since 1.0.0
*/
public function __construct(Matrix $M) public function __construct(Matrix $M)
{ {
// Initialize. // Initialize.
$this->QR = $M->toArray(); $this->QR = $M->toArray();
$this->m = $M->getRowDimension(); $this->m = $M->getM();
$this->n = $M->getColumnDimension(); $this->n = $M->getN();
// Main loop. // Main loop.
for ($k = 0; $k < $this->n; ++$k) { for ($k = 0; $k < $this->n; ++$k) {
// Compute 2-norm of k-th column without under/overflow. // Compute 2-norm of k-th column without under/overflow.
$nrm = 0.0; $nrm = 0.0;
for ($i = $k; $i < $this->m; ++$i) { for ($i = $k; $i < $this->m; ++$i) {
$nrm = hypo($nrm, $this->QR[$i][$k]); $nrm = Triangle::getHypot($nrm, $this->QR[$i][$k]);
} }
if ($nrm != 0.0) { if ($nrm != 0.0) {
@ -57,6 +94,7 @@ final class QRDecomposition
} }
$this->QR[$k][$k] += 1.0; $this->QR[$k][$k] += 1.0;
// Apply transformation to remaining columns. // Apply transformation to remaining columns.
for ($j = $k + 1; $j < $this->n; ++$j) { for ($j = $k + 1; $j < $this->n; ++$j) {
$s = 0.0; $s = 0.0;
@ -75,6 +113,13 @@ final class QRDecomposition
} }
} }
/**
* Matrix has full rank
*
* @return bool
*
* @since 1.0.0
*/
public function isFullRank() : bool public function isFullRank() : bool
{ {
for ($j = 0; $j < $this->n; ++$j) { for ($j = 0; $j < $this->n; ++$j) {
@ -86,6 +131,13 @@ final class QRDecomposition
return true; return true;
} }
/**
* Get H matrix
*
* @return Matrix
*
* @since 1.0.0
*/
public function getH() : Matrix public function getH() : Matrix
{ {
$H = [[]]; $H = [[]];
@ -101,11 +153,18 @@ final class QRDecomposition
} }
$matrix = new Matrix(); $matrix = new Matrix();
$matrix->setArray($H); $matrix->setMatrix($H);
return $matrix; return $matrix;
} }
/**
* Get R matrix
*
* @return Matrix
*
* @since 1.0.0
*/
public function getR() : Matrix public function getR() : Matrix
{ {
$R = [[]]; $R = [[]];
@ -123,11 +182,18 @@ final class QRDecomposition
} }
$matrix = new Matrix(); $matrix = new Matrix();
$matrix->setArray($R); $matrix->setMatrix($R);
return $matrix; return $matrix;
} }
/**
* Get Q matrix
*
* @return Matrix
*
* @since 1.0.0
*/
public function getQ() : Matrix public function getQ() : Matrix
{ {
$Q = [[]]; $Q = [[]];
@ -144,6 +210,7 @@ final class QRDecomposition
for ($i = $k; $i < $this->m; ++$i) { for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $Q[$i][$j]; $s += $this->QR[$i][$k] * $Q[$i][$j];
} }
$s = -$s / $this->QR[$k][$k]; $s = -$s / $this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) { for ($i = $k; $i < $this->m; ++$i) {
$Q[$i][$j] += $s * $this->QR[$i][$k]; $Q[$i][$j] += $s * $this->QR[$i][$k];
@ -153,21 +220,33 @@ final class QRDecomposition
} }
$matrix = new Matrix(); $matrix = new Matrix();
$matrix->setArray($Q); $matrix->setMatrix($Q);
return $matrix; return $matrix;
} }
/**
* Solve Ax = b
*
* @param Matrix $B Matrix
*
* @return Matrix
*
* @since 1.0.0
*/
public function solve(Matrix $B) : Matrix public function solve(Matrix $B) : Matrix
{ {
if ($B->getRowDimension() !== $this->m) { if ($B->getM() !== $this->m) {
throw new InvalidDimensionException($B->getM());
} }
if (!$this->isFullRank()) { if (!$this->isFullRank()) {
throw new \Exception('Rank');
} }
$nx = $B->getColumnDimension(); $nx = $B->getN();
$X = $B->getArrayCopy(); $X = $B->toArray();
// Compute Y = transpose(Q)*B // Compute Y = transpose(Q)*B
for ($k = 0; $k < $this->n; ++$k) { for ($k = 0; $k < $this->n; ++$k) {
for ($j = 0; $j < $nx; ++$j) { for ($j = 0; $j < $nx; ++$j) {
@ -175,17 +254,20 @@ final class QRDecomposition
for ($i = $k; $i < $this->m; ++$i) { for ($i = $k; $i < $this->m; ++$i) {
$s += $this->QR[$i][$k] * $X[$i][$j]; $s += $this->QR[$i][$k] * $X[$i][$j];
} }
$s = -$s / $this->QR[$k][$k]; $s = -$s / $this->QR[$k][$k];
for ($i = $k; $i < $this->m; ++$i) { for ($i = $k; $i < $this->m; ++$i) {
$X[$i][$j] += $s * $this->QR[$i][$k]; $X[$i][$j] += $s * $this->QR[$i][$k];
} }
} }
} }
// Solve R*X = Y; // Solve R*X = Y;
for ($k = $this->n - 1; $k >= 0; --$k) { for ($k = $this->n - 1; $k >= 0; --$k) {
for ($j = 0; $j < $nx; ++$j) { for ($j = 0; $j < $nx; ++$j) {
$X[$k][$j] /= $this->Rdiag[$k]; $X[$k][$j] /= $this->Rdiag[$k];
} }
for ($i = 0; $i < $k; ++$i) { for ($i = 0; $i < $k; ++$i) {
for ($j = 0; $j < $nx; ++$j) { for ($j = 0; $j < $nx; ++$j) {
$X[$i][$j] -= $X[$k][$j] * $this->QR[$i][$k]; $X[$i][$j] -= $X[$k][$j] * $this->QR[$i][$k];
@ -194,8 +276,8 @@ final class QRDecomposition
} }
$matrix = new Matrix(); $matrix = new Matrix();
$matrix->setArray($X); $matrix->setMatrix($X);
return $matrix; return $matrix->getSubMatrix(0, $this->n - 1, 0, $nx - 1);
} }
} }

View File

@ -1 +0,0 @@

View File

@ -1,30 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization;
/**
* Web module interface.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
interface GeneticAlgorithmInterface
{
public function mutate($a);
public function unfitness($a, $b);
}

View File

@ -1,86 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
use phpOMS\Stdlib\Graph\Graph;
class Dijkstra
{
public static function dijkstra(Graph $graph, $source, $target)
{
$vertices = [];
$neighbours = [];
$graphArray = $graph->getEdges();
foreach ($graphArray as $edge) {
array_push($vertices, $edge[0], $edge[1]);
$neighbours[$edge[0]][] = ["end" => $edge[1], "cost" => $edge[2]];
$neighbours[$edge[1]][] = ["end" => $edge[0], "cost" => $edge[2]];
}
$vertices = array_unique($vertices);
$dist = [];
$previous = [];
foreach ($vertices as $vertex) {
$dist[$vertex] = INF;
$previous[$vertex] = null;
}
$dist[$source] = 0;
$Q = $vertices;
while (count($Q) > 0) {
// TODO - Find faster way to get minimum
$min = INF;
foreach ($Q as $vertex) {
if ($dist[$vertex] < $min) {
$min = $dist[$vertex];
$u = $vertex;
}
}
$Q = array_diff($Q, [$u]);
if ($dist[$u] == INF || $u == $target) {
break;
}
if (isset($neighbours[$u])) {
foreach ($neighbours[$u] as $arr) {
$alt = $dist[$u] + $arr["cost"];
if ($alt < $dist[$arr["end"]]) {
$dist[$arr["end"]] = $alt;
$previous[$arr["end"]] = $u;
}
}
}
}
$path = [];
$u = $target;
while (isset($previous[$u])) {
array_unshift($path, $u);
$u = $previous[$u];
}
array_unshift($path, $u);
return $path;
}
}

View File

@ -1,76 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
/**
* Graph class
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
interface EdgeInterface
{
/**
* Get edge id.
*
* @return mixed
*
* @since 1.0.0
*/
public function getId();
/**
* Get edge weight.
*
* @return mixed
*
* @since 1.0.0
*/
public function getWeight();
/**
* Set weight.
*
* @param mixed $weight Weight of edge
*
* @return void
*
* @since 1.0.0
*/
public function setWeight($weight) : void;
/**
* Get vertices.
*
* @return array
*
* @since 1.0.0
*/
public function getVertices() : array;
/**
* Set vertices.
*
* @param VerticeInterface $a Vertice a
* @param VerticeInterface $b Vertice b
*
* @return void
*
* @since 1.0.0
*/
public function setVertices(VerticeInterface $a, VerticeInterface $b) : void;
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
class FloydWarshall
{
}

View File

@ -1,28 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
/**
* Graph class
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class NullEdge
{
}

View File

@ -1,28 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
/**
* Graph class
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class NullVertice
{
}

View File

@ -1,55 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Graph;
/**
* Graph class
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
interface VerticeInterface
{
/**
* Get vertice id.
*
* @return mixed
*
* @since 1.0.0
*/
public function getId();
/**
* Get edges.
*
* @return array
*
* @since 1.0.0
*/
public function getEdges() : array;
/**
* Add edge.
*
* @param EdgeInterface $edge Edge to add to vertice
*
* @return bool
*
* @since 1.0.0
*/
public function addEdge(EdgeInterface $edge) : bool;
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class Backpack
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class BruteForce
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class GA
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class Item
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class ItemPool
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\Knappsack;
class Population
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class BruteForce
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class GA
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class Population
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class Workday
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class Worker
{
}

View File

@ -1,19 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\ShiftScheduling;
class WorkerPool
{
}

View File

@ -1,110 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP;
/**
* TSP solution with brute force.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class BruteForce
{
/**
* City limit (for factorial calculation).
*
* @var float
* @since 1.0.0
*/
public const LIMIT = 22;
/**
* City pool.
*
* @var CityPool
* @since 1.0.0
*/
private $cityPool = null;
/**
* Constructor.
*
* @param CityPool $pool City pool
*
* @throws \Exception
*
* @since 1.0.0
*/
public function __construct(CityPool $pool)
{
$this->cityPool = $pool;
if ($this->cityPool->count() > self::LIMIT) {
throw new \Exception('Overflow');
}
}
/**
* Calculate best routes.
*
* @param int $limit Amount of best routes
*
* @return Population
*
* @since 1.0.0
*/
public function getSolution(int $limit = 1) : Population
{
$population = new Population($this->cityPool, $limit, true);
$cities = $this->cityPool->getCities();
$this->bruteForce($cities, new Tour($this->cityPool, false), $population);
return $population;
}
/**
* Bruteforce best solutions.
*
* @param array $cities Cities
* @param Tour $tour Current (potential) optimal tour
* @param Population $population Population of tours
*
* @return Population
*
* @since 1.0.0
*/
private function bruteForce(array $cities, Tour $tour, Population $population)
{
if (empty($cities)) {
$population->addTour($tour);
}
$count = count($cities);
for ($i = 0; $i < $count; ++$i) {
$extended = clone $tour;
$extended->addCity($cities[$i]);
unset($cities[$i]);
if ($population->getUnfittest()->getFitness() > $extended->getFitness()) {
continue;
}
$this->bruteForce($cities, $extended, $population);
}
}
}

View File

@ -1,118 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP;
/**
* City pool.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class CityPool implements \Countable
{
/**
* Cities
*
* @var array
* @since 1.0.0
*/
private $cities = [];
/**
* Constructor.
*
* @param City[] $cities Cities
*
* @since 1.0.0
*/
public function __construct(array $cities = [])
{
$this->cities = $cities;
}
/**
* Add city.
*
* @param City $city City
*
* @return void
*
* @since 1.0.0
*/
public function addCity(City $city) : void
{
$this->cities[$city->getName() . $city->getLatitude() . $city->getLongitude()] = $city;
}
/**
* Get city.
*
* @param int $index City index
*
* @return City
*
* @since 1.0.0
*/
public function getCity(int $index) : City
{
return array_values($this->cities)[$index];
}
/**
* Get cities.
*
* @return array
*
* @since 1.0.0
*/
public function getCities() : array
{
return $this->cities;
}
/**
* Has city.
*
* @param City $city City
*
* @return bool
*
* @since 1.0.0
*/
public function hasCity(City $city) : bool
{
foreach ($this->cities as $c) {
if ($c->equals($city)) {
return true;
}
}
return false;
}
/**
* Count cities
*
* @return int
*
* @since 1.0.0
*/
public function count() : int
{
return count($this->cities);
}
}

View File

@ -1,195 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP;
/**
* TSP solution by genetic algorithm.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class GA
{
/**
* Mutation percentage
*
* @var int
* @since 1.0.0
*/
public const MUTATION = 15; /* 1000 = 100% */
/**
* Tournaments
*
* @var int
* @since 1.0.0
*/
public const TOURNAMENT = 5;
/**
* Elitism
*
* @var bool
* @since 1.0.0
*/
public const ELITISM = true;
/**
* City pool
*
* @var CityPool
* @since 1.0.0
*/
private $cityPool = null;
/**
* Constructor.
*
* @param CityPool $pool City pool
*
* @since 1.0.0
*/
public function __construct(CityPool $pool)
{
$this->cityPool = $pool;
}
/**
* Evolve population.
*
* @param Population $population Population to eveolve
*
* @return Population
*
* @since 1.0.0
*/
public function evolvePopulation(Population $population) : Population
{
$shift = self::ELITISM ? 1 : 0;
$newPopulation = new Population($this->cityPool, $count = $population->count(), false);
$newPopulation->add($population->getFittest());
for ($i = $shift; $i < $count; ++$i) {
$parent1 = $this->tournamentSelection($population);
$parent2 = $this->tournamentSelection($population);
$child = $this->crossover($parent1, $parent2);
$newPopulation->set($i, $child);
}
$count2 = $newPopulation->count();
for ($i = $shift; $i < $count2; ++$i) {
$this->mutate($newPopulation->get($i));
}
return $newPopulation;
}
/**
* Find fittest
*
* @param Population $population Population to evaluate
*
* @return Tour
*
* @since 1.0.0
*/
private function tournamentSelection(Population $population) : Tour
{
$tournament = new Population($this->cityPool, self::TOURNAMENT, false);
$populationSize = $population->count() - 1;
for ($i = 0; $i < self::TOURNAMENT; ++$i) {
$tournament->add($population->get(mt_rand(0, $populationSize)));
}
return $tournament->getFittest();
}
/**
* Crossover tours
*
* @param Tour $tour1 Tour 1
* @param Tour $tour2 Tour 2
*
* @return Tour
*
* @since 1.0.0
*/
public function crossover(Tour $tour1, Tour $tour2) : Tour
{
$child = new Tour($this->cityPool, false);
$start = mt_rand(0, $tour1->count() - 1);
$end = mt_rand(0, $tour1->count() - 1);
$count = $child->count(); /* $tour1->count() ???!!!! */
for ($i = 0; $i < $count; ++$i) {
if ($start < $end && $i > $start && $i < $end) {
$child->setCity($i, $tour1->getCity($i));
} elseif ($start > $end && !($i < $start && $i > $end)) {
$child->setCity($i, $tour1->getCity($i));
}
}
$count = $tour2->count();
for ($i = 0; $i < $count; ++$i) {
if (!$child->hasCity($tour2->getCity($i))) {
for ($j = 0; $j < $child->count(); ++$j) {
if ($child->getCity($j) === null) {
$child->setCity($j, $tour2->getCity($i));
break;
}
}
}
}
return $child;
}
/**
* Mutate tour
*
* @param Tour $tour Tour to mutate
*
* @return void
*
* @since 1.0.0
*/
private function mutate(Tour $tour)
{
$count = $tour->count();
for ($pos1 = 0; $pos1 < $count; $pos1++) {
if (mt_rand(0, 1000) < self::MUTATION) {
$pos2 = mt_rand(0, $tour->count() - 1);
/* Could be same pos! */
$city1 = $tour->getCity($pos1);
$city2 = $tour->getCity($pos2);
/* swapping */
$tour->setCity($pos1, $city2);
$tour->setCity($pos2, $city1);
}
}
}
}

View File

@ -1,165 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP;
/**
* Population class.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class Population implements \Countable
{
/**
* Tours
*
* @var array
* @since 1.0.0
*/
private $tours = [];
/**
* Constructor.
*
* @param CityPool $pool City pool
* @param int $size Population size
* @param bool $initialize Initialize with random tours
*
* @since 1.0.0
*/
public function __construct(CityPool $pool, int $size, bool $initialize = false)
{
if ($initialize) {
for ($i = 0; $i < $size; ++$i) {
$this->tours[] = new Tour($pool, true);
}
}
}
/**
* Insert Tour at position.
*
* @param int $index Position to insert at
* @param Tour $tour Tour to insert
*
* @return void
*
* @since 1.0.0
*/
public function insertAt(int $index, Tour $tour) : void
{
$this->tours = array_slice($this->tours, 0, $index) + [$tour] + array_slice($this->tours, $index);
}
/**
* Set tour at position
*
* @param int $index Position to set/replace
* @param Tour $tour Tour to set
*
* @return void
*
* @since 1.0.0
*/
public function set(int $index, Tour $tour) : void
{
$this->tours[$index] = $tour;
asort($this->tours);
}
/**
* Add tour
*
* @param Tour $tour Tour to add
*
* @return void
*
* @since 1.0.0
*/
public function add(Tour $tour) : void
{
$this->tours[] = $tour;
}
/**
* Get tour
*
* @param int $index Index of tour
*
* @return null|Tour
*
* @since 1.0.0
*/
public function get(int $index)
{
return $this->tours[$index] ?? null;
}
/**
* Get fittest tour
*
* @return Tour
*
* @since 1.0.0
*/
public function getFittest() : Tour
{
$fittest = $this->tours[0];
$count = count($this->tours);
for ($i = 1; $i < $count; ++$i) {
if ($fittest->getFitness() <= $this->tours[$i]->getFitness()) {
$fittest = $this->tours[$i];
}
}
return $fittest;
}
/**
* Get unfittest tour
*
* @return Tour
*
* @since 1.0.0
*/
public function getUnfittest() : Tour
{
$unfittest = $this->tours[0];
$count = count($this->tours);
for ($i = 1; $i < $count; ++$i) {
if ($unfittest->getFitness() >= $this->tours[$i]->getFitness()) {
$unfittest = $this->tours[$i];
}
}
return $unfittest;
}
/**
* Get tour count
*
* @return int
*
* @since 1.0.0
*/
public function count() : int
{
return count($this->tours);
}
}

View File

@ -1,200 +0,0 @@
<?php
/**
* Orange Management
*
* PHP Version 7.2
*
* @package TBD
* @copyright Dennis Eichhorn
* @license OMS License 1.0
* @version 1.0.0
* @link http://website.orange-management.de
*/
declare(strict_types=1);
namespace phpOMS\Math\Optimization\TSP;
/**
* Tour class.
*
* @package Framework
* @license OMS License 1.0
* @link http://website.orange-management.de
* @since 1.0.0
*/
class Tour implements \Countable
{
/**
* Cities
*
* @var City[]
* @since 1.0.0
*/
private $cities = [];
/**
* Tour fitness
*
* @var City[]
* @since 1.0.0
*/
private $fitness = 0.0;
/**
* Tour distance
*
* @var City[]
* @since 1.0.0
*/
private $distance = 0.0;
/**
* City pool
*
* @var CityPool
* @since 1.0.0
*/
private $cityPool = null;
/**
* Constructor.
*
* @param CityPool $pool City pool
* @param bool $initialize Initialize with random tours
*
* @since 1.0.0
*/
public function __construct(CityPool $pool, bool $initialize = false)
{
$this->cityPool = $pool;
if ($initialize) {
$this->cities = $this->cityPool->getCities();
shuffle($this->cities);
}
}
/**
* Get city.
*
* @param int $index Index
*
* @return null|City
*
* @since 1.0.0
*/
public function getCity($index)
{
return array_values($this->cities)[$index] ?? null;
}
/**
* Get fitness.
*
* @return float
*
* @since 1.0.0
*/
public function getFitness() : float
{
if ($this->fitness === 0.0 && ($distance = $this->getDistance()) !== 0.0) {
$this->fitness = 1 / $distance;
}
return $this->fitness;
}
/**
* Get tour distance
*
* @return float
*
* @since 1.0.0
*/
public function getDistance() : float
{
if ($this->distance === 0.0) {
$distance = 0.0;
$count = count($this->cities);
for ($i = 0; $i < $count; ++$i) {
$dest = ($i + 1 < $count) ? $this->cities[$i + 1] : $this->cities[0];
$distance += $this->cities[$i]->getDistanceTo($dest);
}
$this->distance = $distance;
}
return $this->distance;
}
/**
* Add city to tour.
*
* @param City $city City
*
* @return void
*
* @since 1.0.0
*/
public function addCity(City $city) : void
{
$this->cities[] = $city;
$this->fitness = 0.0;
$this->distance = 0.0;
}
/**
* Set city
*
* @param int $index Index to set/replace
* @param City $city City
*
* @return void
*
* @since 1.0.0
*/
public function setCity(int $index, City $city) : void
{
$this->cities[$index] = $city;
asort($this->cities);
$this->fitness = 0.0;
$this->distance = 0.0;
}
/**
* Has city.
*
* @param City $city City
*
* @return bool
*
* @since 1.0.0
*/
public function hasCity(City $city) : bool
{
foreach ($this->cities as $c) {
if ($c->equals($city)) {
return true;
}
}
return false;
}
/**
* Get city count
*
* @return int
*
* @since 1.0.0
*/
public function count() : int
{
return count($this->cities);
}
}

View File

@ -41,10 +41,10 @@ class Evaluator
public static function evaluate(string $formula, array $vars) : float public static function evaluate(string $formula, array $vars) : float
{ {
// todo: do i need array_values here? // todo: do i need array_values here?
$formula = str_replace(array_keys($vars), array_values($vars), $formula); $formula = \str_replace(array_keys($vars), array_values($vars), $formula);
// todo: this is horrible in case things like mod etc. need to be supported // todo: this is horrible in case things like mod etc. need to be supported
if (preg_match('#[^0-9\+\-\*\/\(\)]#', $formula)) { if (\preg_match('#[^0-9\+\-\*\/\(\)]#', $formula)) {
throw new \Exception('Bad elements'); throw new \Exception('Bad elements');
} }

View File

@ -15,6 +15,7 @@ declare(strict_types=1);
namespace phpOMS\Math\Stochastic\Distribution; namespace phpOMS\Math\Stochastic\Distribution;
use phpOMS\Math\Functions\Functions; use phpOMS\Math\Functions\Functions;
use phpOMS\Math\Functions\Gamma;
/** /**
* Well known functions class. * Well known functions class.
@ -40,7 +41,7 @@ class PoissonDistribution
*/ */
public static function getPmf(int $k, float $lambda) : float public static function getPmf(int $k, float $lambda) : float
{ {
return exp($k * log($lambda) - $lambda - log(Functions::getGammaInteger($k + 1))); return exp($k * log($lambda) - $lambda - log(Gamma::getGammaInteger($k + 1)));
} }
/** /**

View File

@ -150,7 +150,7 @@ final class Header extends HeaderAbstract
$headers = []; $headers = [];
foreach ($_SERVER as $name => $value) { foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') { if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; $headers[\str_replace(' ', '-', ucwords(strtolower(\str_replace('_', ' ', substr($name, 5)))))] = $value;
} }
} }

View File

@ -126,7 +126,7 @@ final class Request extends RequestAbstract
if (isset($_SERVER['CONTENT_TYPE'])) { if (isset($_SERVER['CONTENT_TYPE'])) {
if (strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) { if (strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
if (($json = json_decode(($input = file_get_contents('php://input')), true)) === false || $json === null) { if (($json = \json_decode(($input = \file_get_contents('php://input')), true)) === false || $json === null) {
throw new \Exception('Is not valid json ' . $input); throw new \Exception('Is not valid json ' . $input);
} }
@ -153,8 +153,8 @@ final class Request extends RequestAbstract
return 'EN'; return 'EN';
} }
$lang = explode(';', $_SERVER['HTTP_ACCEPT_LANGUAGE']); $lang = \explode(';', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = explode('-', $lang[0]); $lang = \explode('-', $lang[0]);
return $lang[0]; return $lang[0];
} }
@ -252,7 +252,7 @@ final class Request extends RequestAbstract
// TODO: maybe replace this with smart media queries... checked gets handled in reverse!!! // TODO: maybe replace this with smart media queries... checked gets handled in reverse!!!
$useragent = $_SERVER['HTTP_USER_AGENT'] ?? ''; $useragent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', $useragent)) { if (\preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i', $useragent) || \preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', $useragent)) {
return true; return true;
} }
@ -388,7 +388,7 @@ final class Request extends RequestAbstract
*/ */
public function getBody() : string public function getBody() : string
{ {
return file_get_contents('php://input'); return \file_get_contents('php://input');
} }
/** /**

View File

@ -106,7 +106,7 @@ final class Response extends ResponseAbstract implements RenderableInterface
foreach ($types as $type) { foreach ($types as $type) {
if (stripos($type, MimeType::M_JSON) !== false) { if (stripos($type, MimeType::M_JSON) !== false) {
return json_encode($this->jsonSerialize()); return \json_encode($this->jsonSerialize());
} }
} }
@ -132,7 +132,7 @@ final class Response extends ResponseAbstract implements RenderableInterface
} elseif (is_string($response) || is_numeric($response)) { } elseif (is_string($response) || is_numeric($response)) {
$render .= $response; $render .= $response;
} elseif (is_array($response)) { } elseif (is_array($response)) {
$render .= json_encode($response); $render .= \json_encode($response);
// TODO: remove this. This should never happen since then someone forgot to set the correct header. it should be json header! // TODO: remove this. This should never happen since then someone forgot to set the correct header. it should be json header!
} else { } else {
throw new \Exception('Wrong response type'); throw new \Exception('Wrong response type');

View File

@ -71,7 +71,7 @@ class Meta implements RenderableInterface
*/ */
public function addKeyword(string $keyword) : void public function addKeyword(string $keyword) : void
{ {
if (!in_array($keyword, $this->keywords)) { if (!\in_array($keyword, $this->keywords)) {
$this->keywords[] = $keyword; $this->keywords[] = $keyword;
} }
} }

View File

@ -81,11 +81,11 @@ final class InfoManager
*/ */
public function load() : void public function load() : void
{ {
if (!file_exists($this->path)) { if (!\file_exists($this->path)) {
throw new PathException($this->path); throw new PathException($this->path);
} }
$this->info = json_decode(file_get_contents($this->path), true); $this->info = \json_decode(file_get_contents($this->path), true);
} }
/** /**
@ -97,11 +97,11 @@ final class InfoManager
*/ */
public function update() : void public function update() : void
{ {
if (!file_exists($this->path)) { if (!\file_exists($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));
} }
/** /**

View File

@ -68,7 +68,7 @@ class InstallerAbstract
$load = $info->getLoad(); $load = $info->getLoad();
foreach ($load as $val) { foreach ($load as $val) {
foreach ($val['pid'] as $pid) { foreach ($val['pid'] as $pid) {
$sth->bindValue(':pid', sha1(str_replace('/', '', $pid)), \PDO::PARAM_STR); $sth->bindValue(':pid', sha1(\str_replace('/', '', $pid)), \PDO::PARAM_STR);
$sth->bindValue(':type', $val['type'], \PDO::PARAM_INT); $sth->bindValue(':type', $val['type'], \PDO::PARAM_INT);
$sth->bindValue(':from', $val['from'], \PDO::PARAM_STR); $sth->bindValue(':from', $val['from'], \PDO::PARAM_STR);
$sth->bindValue(':for', $val['for'], \PDO::PARAM_STR); $sth->bindValue(':for', $val['for'], \PDO::PARAM_STR);
@ -148,7 +148,7 @@ class InstallerAbstract
*/ */
private static function initRoutes(InfoManager $info) : void private static function initRoutes(InfoManager $info) : void
{ {
$directories = new Directory(dirname($info->getPath()) . '/Admin/Routes'); $directories = new Directory(\dirname($info->getPath()) . '/Admin/Routes');
foreach ($directories as $key => $subdir) { foreach ($directories as $key => $subdir) {
if ($subdir instanceof Directory) { if ($subdir instanceof Directory) {
@ -173,15 +173,15 @@ class InstallerAbstract
*/ */
private static function installRoutes(string $destRoutePath, string $srcRoutePath) : void private static function installRoutes(string $destRoutePath, string $srcRoutePath) : void
{ {
if (!file_exists($destRoutePath)) { if (!\file_exists($destRoutePath)) {
file_put_contents($destRoutePath, '<?php return [];'); \file_put_contents($destRoutePath, '<?php return [];');
} }
if (!file_exists($srcRoutePath)) { if (!\file_exists($srcRoutePath)) {
return; return;
} }
if (!file_exists($destRoutePath)) { if (!\file_exists($destRoutePath)) {
throw new PathException($destRoutePath); throw new PathException($destRoutePath);
} }
@ -196,7 +196,7 @@ class InstallerAbstract
$appRoutes = array_merge_recursive($appRoutes, $moduleRoutes); $appRoutes = array_merge_recursive($appRoutes, $moduleRoutes);
file_put_contents($destRoutePath, '<?php return ' . ArrayParser::serializeArray($appRoutes) . ';', LOCK_EX); \file_put_contents($destRoutePath, '<?php return ' . ArrayParser::serializeArray($appRoutes) . ';', LOCK_EX);
} }
/** /**
@ -212,7 +212,7 @@ class InstallerAbstract
*/ */
private static function initHooks(InfoManager $info) : void private static function initHooks(InfoManager $info) : void
{ {
$directories = new Directory(dirname($info->getPath()) . '/Admin/Hooks'); $directories = new Directory(\dirname($info->getPath()) . '/Admin/Hooks');
foreach ($directories as $key => $subdir) { foreach ($directories as $key => $subdir) {
if ($subdir instanceof Directory) { if ($subdir instanceof Directory) {
@ -237,15 +237,15 @@ class InstallerAbstract
*/ */
private static function installHooks(string $destHookPath, string $srcHookPath) : void private static function installHooks(string $destHookPath, string $srcHookPath) : void
{ {
if (!file_exists($destHookPath)) { if (!\file_exists($destHookPath)) {
file_put_contents($destHookPath, '<?php return [];'); \file_put_contents($destHookPath, '<?php return [];');
} }
if (!file_exists($srcHookPath)) { if (!\file_exists($srcHookPath)) {
return; return;
} }
if (!file_exists($destHookPath)) { if (!\file_exists($destHookPath)) {
throw new PathException($destHookPath); throw new PathException($destHookPath);
} }
@ -260,6 +260,6 @@ class InstallerAbstract
$appHooks = array_merge_recursive($appHooks, $moduleHooks); $appHooks = array_merge_recursive($appHooks, $moduleHooks);
file_put_contents($destHookPath, '<?php return ' . ArrayParser::serializeArray($appHooks) . ';', LOCK_EX); \file_put_contents($destHookPath, '<?php return ' . ArrayParser::serializeArray($appHooks) . ';', LOCK_EX);
} }
} }

View File

@ -221,7 +221,7 @@ final class ModuleManager
*/ */
public function isActive(string $module) : bool public function isActive(string $module) : bool
{ {
return in_array($module, $this->getActiveModules(false)); return \in_array($module, $this->getActiveModules(false));
} }
/** /**
@ -241,12 +241,12 @@ final class ModuleManager
for ($i = 0; $i < $c; ++$i) { for ($i = 0; $i < $c; ++$i) {
$path = $this->modulePath . '/' . $files[$i] . '/info.json'; $path = $this->modulePath . '/' . $files[$i] . '/info.json';
if (!file_exists($path)) { if (!\file_exists($path)) {
continue; continue;
// throw new PathException($path); // throw new PathException($path);
} }
$json = json_decode(file_get_contents($path), true); $json = \json_decode(file_get_contents($path), true);
$this->all[$json['name']['internal']] = $json; $this->all[$json['name']['internal']] = $json;
} }
} }
@ -472,7 +472,7 @@ final class ModuleManager
return false; return false;
} }
if (!file_exists($this->modulePath . '/' . $module . '/Admin/Installer.php')) { if (!\file_exists($this->modulePath . '/' . $module . '/Admin/Installer.php')) {
// todo download; // todo download;
return false; return false;
} }

View File

@ -105,11 +105,11 @@ final class PackageManager
*/ */
public function load() : void public function load() : void
{ {
if (!file_exists($this->extractPath)) { if (!\file_exists($this->extractPath)) {
throw new PathException($this->extractPath); throw new PathException($this->extractPath);
} }
$this->info = json_decode(file_get_contents($this->extractPath . '/info.json'), true); $this->info = \json_decode(file_get_contents($this->extractPath . '/info.json'), true);
} }
/** /**
@ -141,7 +141,7 @@ final class PackageManager
continue; continue;
} }
\sodium_crypto_generichash_update($state, file_get_contents($this->extractPath . '/package/' . $file)); \sodium_crypto_generichash_update($state, \file_get_contents($this->extractPath . '/package/' . $file));
} }
return \sodium_crypto_generichash_final(); return \sodium_crypto_generichash_final();

View File

@ -137,6 +137,6 @@ final class Router
*/ */
private function match(string $route, int $routeVerb, string $uri, int $remoteVerb = RouteVerb::GET) : bool private function match(string $route, int $routeVerb, string $uri, int $remoteVerb = RouteVerb::GET) : bool
{ {
return (bool) preg_match('~^' . $route . '$~', $uri) && ($routeVerb === RouteVerb::ANY || $remoteVerb === RouteVerb::ANY || ($remoteVerb & $routeVerb) === $remoteVerb); return (bool) \preg_match('~^' . $route . '$~', $uri) && ($routeVerb === RouteVerb::ANY || $remoteVerb === RouteVerb::ANY || ($remoteVerb & $routeVerb) === $remoteVerb);
} }
} }

View File

@ -76,7 +76,7 @@ final class PhpCode
*/ */
public static function normalizeSource(string $source) : string public static function normalizeSource(string $source) : string
{ {
return str_replace(["\n", "\r\n", "\r", "\t"], ['', '', '', ' '], $source); return \str_replace(["\n", "\r\n", "\r", "\t"], ['', '', '', ' '], $source);
} }
/** /**
@ -90,7 +90,7 @@ final class PhpCode
*/ */
public static function hasUnicode(string $source) : bool public static function hasUnicode(string $source) : bool
{ {
return (bool) preg_match('/[^\x00-\x7f]/', $source); return (bool) \preg_match('/[^\x00-\x7f]/', $source);
} }
/** /**
@ -105,11 +105,11 @@ final class PhpCode
public static function isDisabled(array $functions) : bool public static function isDisabled(array $functions) : bool
{ {
$disabled = ini_get('disable_functions'); $disabled = ini_get('disable_functions');
$disabled = str_replace(' ', '', $disabled); $disabled = \str_replace(' ', '', $disabled);
$disabled = explode(',', $disabled); $disabled = \explode(',', $disabled);
foreach ($functions as $function) { foreach ($functions as $function) {
if (!in_array($function, $disabled)) { if (!\in_array($function, $disabled)) {
return false; return false;
} }
} }
@ -129,7 +129,7 @@ final class PhpCode
public static function hasDeprecatedFunction(string $source) : bool public static function hasDeprecatedFunction(string $source) : bool
{ {
foreach (self::$deprecatedFunctions as $function) { foreach (self::$deprecatedFunctions as $function) {
if (preg_match('/' . $function . '\s*\(/', $source) === 1) { if (\preg_match('/' . $function . '\s*\(/', $source) === 1) {
return true; return true;
} }
} }

View File

@ -98,7 +98,7 @@ class Client extends SocketAbstract
$data = trim($data); $data = trim($data);
if (!empty($data)) { if (!empty($data)) {
$data = explode(' ', $data); $data = \explode(' ', $data);
$this->commands->trigger($data[0], 0, $data); $this->commands->trigger($data[0], 0, $data);
} }
} }

View File

@ -130,27 +130,27 @@ class Server extends SocketAbstract
// todo: different handshake for normal tcp connection // todo: different handshake for normal tcp connection
return true; return true;
if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match)) { if (\preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match)) {
$version = $match[1]; $version = $match[1];
} else { } else {
return false; return false;
} }
if ($version == 13) { if ($version == 13) {
if (preg_match("/GET (.*) HTTP/", $headers, $match)) { if (\preg_match("/GET (.*) HTTP/", $headers, $match)) {
$root = $match[1]; $root = $match[1];
} }
if (preg_match("/Host: (.*)\r\n/", $headers, $match)) { if (\preg_match("/Host: (.*)\r\n/", $headers, $match)) {
$host = $match[1]; $host = $match[1];
} }
if (preg_match("/Origin: (.*)\r\n/", $headers, $match)) { if (\preg_match("/Origin: (.*)\r\n/", $headers, $match)) {
$origin = $match[1]; $origin = $match[1];
} }
$key = ''; $key = '';
if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match)) { if (\preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match)) {
$key = $match[1]; $key = $match[1];
} }

View File

@ -42,7 +42,7 @@ abstract class Enum
{ {
$constants = self::getConstants(); $constants = self::getConstants();
return in_array($value, $constants, true); return \in_array($value, $constants, true);
} }
/** /**

View File

@ -73,7 +73,7 @@ abstract class EnumArray
{ {
$constants = self::getConstants(); $constants = self::getConstants();
return in_array($value, $constants, true); return \in_array($value, $constants, true);
} }
/** /**

View File

@ -75,7 +75,7 @@ class Iban implements \Serializable
*/ */
public static function normalize(string $iban) : string public static function normalize(string $iban) : string
{ {
return strtoupper(str_replace(' ', '', $iban)); return strtoupper(\str_replace(' ', '', $iban));
} }
/** /**
@ -114,9 +114,9 @@ class Iban implements \Serializable
private function getSequence(string $sequence) : string private function getSequence(string $sequence) : string
{ {
$country = $this->getCountry(); $country = $this->getCountry();
$layout = str_replace(' ', '', IbanEnum::getByName('C_' . $country)); $layout = \str_replace(' ', '', IbanEnum::getByName('C_' . $country));
$start = stripos($layout, $sequence); $start = \stripos($layout, $sequence);
$end = strrpos($layout, $sequence); $end = strrpos($layout, $sequence);
if ($start === false) { if ($start === false) {

View File

@ -297,7 +297,7 @@ class Location implements \JsonSerializable, \Serializable
*/ */
public function serialize() : string public function serialize() : string
{ {
return json_encode($this->jsonSerialize()); return \json_encode($this->jsonSerialize());
} }
/** /**

View File

@ -240,7 +240,7 @@ class SmartDateTime extends \DateTime
* *
* @param int $weekStartsWith Day of the week start (0 = Sunday) * @param int $weekStartsWith Day of the week start (0 = Sunday)
* *
* @return array * @return \DateTime[]
* *
* @since 1.0.0 * @since 1.0.0
*/ */

View File

@ -130,7 +130,7 @@ class MultiMap implements \Countable
/* garbage collect values */ /* garbage collect values */
foreach ($this->values as $valueKey => $value) { foreach ($this->values as $valueKey => $value) {
if (!in_array($valueKey, $this->keys)) { if (!\in_array($valueKey, $this->keys)) {
unset($this->values[$valueKey]); unset($this->values[$valueKey]);
} }
} }

View File

@ -184,7 +184,7 @@ class PriorityQueue implements \Countable, \Serializable
*/ */
public function serialize() : string public function serialize() : string
{ {
return json_encode($this->queue); return \json_encode($this->queue);
} }
/** /**
@ -198,7 +198,7 @@ class PriorityQueue implements \Countable, \Serializable
*/ */
public function unserialize($data) public function unserialize($data)
{ {
$this->queue = json_decode($data); $this->queue = \json_decode($data);
$this->count = count($this->queue); $this->count = count($this->queue);
} }
} }

View File

@ -58,23 +58,23 @@ final class FileUtils
{ {
$extension = strtolower($extension); $extension = strtolower($extension);
if (in_array($extension, self::CODE_EXTENSION)) { if (\in_array($extension, self::CODE_EXTENSION)) {
return ExtensionType::CODE; return ExtensionType::CODE;
} elseif (in_array($extension, self::TEXT_EXTENSION)) { } elseif (\in_array($extension, self::TEXT_EXTENSION)) {
return ExtensionType::TEXT; return ExtensionType::TEXT;
} elseif (in_array($extension, self::PRESENTATION_EXTENSION)) { } elseif (\in_array($extension, self::PRESENTATION_EXTENSION)) {
return ExtensionType::PRESENTATION; return ExtensionType::PRESENTATION;
} elseif (in_array($extension, self::PDF_EXTENSION)) { } elseif (\in_array($extension, self::PDF_EXTENSION)) {
return ExtensionType::PDF; return ExtensionType::PDF;
} elseif (in_array($extension, self::ARCHIVE_EXTENSION)) { } elseif (\in_array($extension, self::ARCHIVE_EXTENSION)) {
return ExtensionType::ARCHIVE; return ExtensionType::ARCHIVE;
} elseif (in_array($extension, self::AUDIO_EXTENSION)) { } elseif (\in_array($extension, self::AUDIO_EXTENSION)) {
return ExtensionType::AUDIO; return ExtensionType::AUDIO;
} elseif (in_array($extension, self::VIDEO_EXTENSION)) { } elseif (\in_array($extension, self::VIDEO_EXTENSION)) {
return ExtensionType::VIDEO; return ExtensionType::VIDEO;
} elseif (in_array($extension, self::IMAGE_EXTENSION)) { } elseif (\in_array($extension, self::IMAGE_EXTENSION)) {
return ExtensionType::IMAGE; return ExtensionType::IMAGE;
} elseif (in_array($extension, self::SPREADSHEET_EXTENSION)) { } elseif (\in_array($extension, self::SPREADSHEET_EXTENSION)) {
return ExtensionType::SPREADSHEET; return ExtensionType::SPREADSHEET;
} }
@ -92,11 +92,11 @@ final class FileUtils
*/ */
public static function absolute(string $origPath) : string public static function absolute(string $origPath) : string
{ {
if (!file_exists($origPath)) { if (!\file_exists($origPath)) {
$startsWithSlash = strpos($origPath, '/') === 0 ? '/' : ''; $startsWithSlash = strpos($origPath, '/') === 0 ? '/' : '';
$path = []; $path = [];
$parts = explode('/', $origPath); $parts = \explode('/', $origPath);
foreach ($parts as $part) { foreach ($parts as $part) {
if (empty($part) || $part === '.') { if (empty($part) || $part === '.') {

View File

@ -48,17 +48,17 @@ class Directory extends FileAbstract implements DirectoryInterface
{ {
$list = ftp_nlist($con, LocalFile::parent($path)); $list = ftp_nlist($con, LocalFile::parent($path));
return in_array(LocalFile::name($path), $list); return \in_array(LocalFile::name($path), $list);
} }
public static function ftpCreate($con, string $path, int $permission, bool $recursive) public static function ftpCreate($con, string $path, int $permission, bool $recursive)
{ {
$parts = explode('/', $path); $parts = \explode('/', $path);
ftp_chdir($con, '/' . $parts[0]); ftp_chdir($con, '/' . $parts[0]);
foreach ($parts as $part) { foreach ($parts as $part) {
if (self::ftpExists($con, $part)) { if (self::ftpExists($con, $part)) {
ftp_mkdir($con, $part); ftp_\mkdir($con, $part);
ftp_chdir($con, $part); ftp_chdir($con, $part);
ftp_chmod($con, $permission, $part); ftp_chmod($con, $permission, $part);
} }

View File

@ -62,19 +62,19 @@ class File extends FileAbstract implements FileInterface
public static function ftpConnect(Http $http) public static function ftpConnect(Http $http)
{ {
$con = ftp_connect($http->getBase() . $http->getPath(), $http->getPort()); $con = \ftp_connect($http->getBase() . $http->getPath(), $http->getPort());
ftp_login($con, $http->getUser(), $http->getPass()); \ftp_login($con, $http->getUser(), $http->getPass());
ftp_chdir($con, $http->getPath()); // todo: is this required ? \ftp_chdir($con, $http->getPath()); // todo: is this required ?
return $con; return $con;
} }
public static function ftpExists($con, string $path) public static function ftpExists($con, string $path)
{ {
$list = ftp_nlist($con, LocalFile::dirpath($path)); $list = \ftp_nlist($con, LocalFile::dirpath($path));
return in_array(LocalFile::basename($path), $list); return \in_array(LocalFile::basename($path), $list);
} }
/** /**
@ -85,7 +85,7 @@ class File extends FileAbstract implements FileInterface
$http = new Http($path); $http = new Http($path);
$con = self::ftpConnect($http); $con = self::ftpConnect($http);
if (ftp_pwd($con) !== $http->getPath()) { if (\ftp_pwd($con) !== $http->getPath()) {
return false; return false;
} }
@ -97,23 +97,23 @@ class File extends FileAbstract implements FileInterface
|| (!$exists && ContentPutMode::hasFlag($mode, ContentPutMode::CREATE)) || (!$exists && ContentPutMode::hasFlag($mode, ContentPutMode::CREATE))
) { ) {
if (ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists) { if (ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists) {
file_put_contents($path, file_get_contents($path) . $content, 0, stream_context_create(['ftp' => ['overwrite' => true]])); \file_put_contents($path, \file_get_contents($path) . $content, 0, \stream_context_create(['ftp' => ['overwrite' => true]]));
} elseif (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists) { } elseif (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists) {
file_put_contents($path, $content . file_get_contents($path), 0, stream_context_create(['ftp' => ['overwrite' => true]])); \file_put_contents($path, $content . \file_get_contents($path), 0, \stream_context_create(['ftp' => ['overwrite' => true]]));
} else { } else {
if (!Directory::ftpExists($con, dirname($path))) { if (!Directory::ftpExists($con, \dirname($path))) {
Directory::ftpCreate($con, dirname($path), 0755, true); Directory::ftpCreate($con, \dirname($path), 0755, true);
} }
file_put_contents($path, $content, 0, stream_context_create(['ftp' => ['overwrite' => true]])); \file_put_contents($path, $content, 0, \stream_context_create(['ftp' => ['overwrite' => true]]));
} }
ftp_close($con); \ftp_close($con);
return true; return true;
} }
ftp_close($con); \ftp_close($con);
return false; return false;
} }
@ -123,17 +123,17 @@ class File extends FileAbstract implements FileInterface
*/ */
public static function get(string $path) : string public static function get(string $path) : string
{ {
$temp = fopen('php://temp', 'r+'); $temp = \fopen('php://temp', 'r+');
$http = new Http($path); $http = new Http($path);
$content = ''; $content = '';
$con = self::ftpConnect($http); $con = self::ftpConnect($http);
if (ftp_chdir($con, File::dirpath($path)) && ftp_fget($con, $temp, $path, FTP_BINARY, 0)) { if (\ftp_chdir($con, File::dirpath($path)) && \ftp_fget($con, $temp, $path, FTP_BINARY, 0)) {
rewind($temp); \rewind($temp);
$content = stream_get_contents($temp); $content = \stream_get_contents($temp);
} }
fclose($temp); \fclose($temp);
return $content; return $content;
} }
@ -211,7 +211,7 @@ class File extends FileAbstract implements FileInterface
$changed->setTimestamp(ftp_mdtm($con, $http->getPath())); $changed->setTimestamp(ftp_mdtm($con, $http->getPath()));
fclose($con); \fclose($con);
return $changed; return $changed;
} }
@ -228,9 +228,9 @@ class File extends FileAbstract implements FileInterface
throw new PathException($path); throw new PathException($path);
} }
$size = ftp_size($con, $http->getPath()); $size = \ftp_size($con, $http->getPath());
fclose($con); \fclose($con);
return $size; return $size;
} }
@ -244,7 +244,7 @@ class File extends FileAbstract implements FileInterface
$con = self::ftpConnect($http); $con = self::ftpConnect($http);
$owner = self::parseFtpFileData($con, $path)['user'] ?? ''; $owner = self::parseFtpFileData($con, $path)['user'] ?? '';
fclose($con); \fclose($con);
return (int) $owner; return (int) $owner;
} }
@ -258,7 +258,7 @@ class File extends FileAbstract implements FileInterface
$con = self::ftpConnect($http); $con = self::ftpConnect($http);
$permission = (int) self::parseFtpFileData($con, $path)['permission'] ?? 0; $permission = (int) self::parseFtpFileData($con, $path)['permission'] ?? 0;
fclose($con); \fclose($con);
return $permission; return $permission;
} }
@ -267,10 +267,10 @@ class File extends FileAbstract implements FileInterface
{ {
$items = []; $items = [];
if (is_array($files = ftp_rawlist($con, LocalFile::dirpath($path)))) { if (\is_array($files = \ftp_rawlist($con, LocalFile::dirpath($path)))) {
foreach ($files as $fileData) { foreach ($files as $fileData) {
if (strpos($fileData, self::name($path)) !== false) { if (\strpos($fileData, self::name($path)) !== false) {
$chunks = preg_split("/\s+/", $fileData); $chunks = \preg_split("/\s+/", $fileData);
$items['permission'] = $chunks[0]; $items['permission'] = $chunks[0];
$items['user'] = $chunks[2]; $items['user'] = $chunks[2];
@ -342,17 +342,17 @@ class File extends FileAbstract implements FileInterface
} }
if ($overwrite || !self::exists($to)) { if ($overwrite || !self::exists($to)) {
if (!Directory::exists(dirname($to))) { if (!Directory::exists(\dirname($to))) {
Directory::create(dirname($to), 0755, true); Directory::create(\dirname($to), 0755, true);
} }
$rename = ftp_rename($con, $from, $to); $rename = \ftp_rename($con, $from, $to);
fclose($con); \fclose($con);
return $rename; return $rename;
} }
fclose($con); \fclose($con);
return false; return false;
} }
@ -369,8 +369,8 @@ class File extends FileAbstract implements FileInterface
return false; return false;
} }
ftp_delete($con, $path); \ftp_delete($con, $path);
fclose($con); \fclose($con);
return true; return true;
} }

View File

@ -48,7 +48,7 @@ class FtpStorage extends StorageAbstract
protected static function getClassType(string $path) : string protected static function getClassType(string $path) : string
{ {
return is_dir($path) || (!is_file($path) && stripos($path, '.') === false) ? Directory::class : File::class; return \is_dir($path) || (!is_file($path) && \stripos($path, '.') === false) ? Directory::class : File::class;
} }
/** /**
@ -80,7 +80,7 @@ class FtpStorage extends StorageAbstract
*/ */
public static function create(string $path) : bool public static function create(string $path) : bool
{ {
return stripos($path, '.') === false ? Directory::create($path, 0755, true) : File::create($path); return \stripos($path, '.') === false ? Directory::create($path, 0755, true) : File::create($path);
} }
/** /**

View File

@ -57,7 +57,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function __construct(string $path, string $filter = '*') public function __construct(string $path, string $filter = '*')
{ {
$this->filter = ltrim($filter, '\\/'); $this->filter = \ltrim($filter, '\\/');
parent::__construct($path); parent::__construct($path);
if (file_exists($this->path)) { if (file_exists($this->path)) {
@ -71,18 +71,18 @@ final class Directory extends FileAbstract implements DirectoryInterface
* @param string $path Path * @param string $path Path
* @param string $filter Filter * @param string $filter Filter
* *
* @return array * @return string[]
* *
* @since 1.0.0 * @since 1.0.0
*/ */
public static function list(string $path, string $filter = '*') : array public static function list(string $path, string $filter = '*') : array
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
$list = []; $list = [];
$path = rtrim($path, '\\/'); $path = \rtrim($path, '\\/');
$iterator = new \RecursiveIteratorIterator( $iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST); \RecursiveIteratorIterator::SELF_FIRST);
@ -92,7 +92,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
} }
foreach ($iterator as $item) { foreach ($iterator as $item) {
$list[] = str_replace('\\', '/', $iterator->getSubPathname()); $list[] = \str_replace('\\', '/', $iterator->getSubPathname());
} }
return $list; return $list;
@ -105,23 +105,23 @@ final class Directory extends FileAbstract implements DirectoryInterface
* @param string $extension Extension * @param string $extension Extension
* @param string $exclude Pattern to exclude * @param string $exclude Pattern to exclude
* *
* @return array * @return string[]
* *
* @since 1.0.0 * @since 1.0.0
*/ */
public static function listByExtension(string $path, string $extension = '', string $exclude = '') : array public static function listByExtension(string $path, string $extension = '', string $exclude = '') : array
{ {
$list = []; $list = [];
$path = rtrim($path, '\\/'); $path = \rtrim($path, '\\/');
foreach ($iterator = new \RecursiveIteratorIterator( foreach ($iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST) as $item \RecursiveIteratorIterator::SELF_FIRST) as $item
) { ) {
if ((empty($extension) || $item->getExtension() === $extension) if ((empty($extension) || $item->getExtension() === $extension)
&& (empty($exclude) || (!(bool) preg_match('/' . $exclude . '/', $iterator->getSubPathname()))) && (empty($exclude) || (!(bool) \preg_match('/' . $exclude . '/', $iterator->getSubPathname())))
) { ) {
$list[] = str_replace('\\', '/', $iterator->getSubPathname()); $list[] = \str_replace('\\', '/', $iterator->getSubPathname());
} }
} }
@ -135,9 +135,9 @@ final class Directory extends FileAbstract implements DirectoryInterface
{ {
parent::index(); parent::index();
foreach (glob($this->path . DIRECTORY_SEPARATOR . $this->filter) as $filename) { foreach (\glob($this->path . DIRECTORY_SEPARATOR . $this->filter) as $filename) {
if (!StringUtils::endsWith(trim($filename), '.')) { if (!StringUtils::endsWith(trim($filename), '.')) {
$file = is_dir($filename) ? new self($filename) : new File($filename); $file = \is_dir($filename) ? new self($filename) : new File($filename);
$this->addNode($file); $this->addNode($file);
} }
@ -161,12 +161,12 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function size(string $dir, bool $recursive = true) : int public static function size(string $dir, bool $recursive = true) : int
{ {
if (!file_exists($dir) || !is_readable($dir)) { if (!\file_exists($dir) || !\is_readable($dir)) {
throw new PathException($dir); throw new PathException($dir);
} }
$countSize = 0; $countSize = 0;
$directories = scandir($dir); $directories = \scandir($dir);
foreach ($directories as $key => $filename) { foreach ($directories as $key => $filename) {
if ($filename === ".." || $filename === ".") { if ($filename === ".." || $filename === ".") {
@ -174,10 +174,10 @@ final class Directory extends FileAbstract implements DirectoryInterface
} }
$path = $dir . "/" . $filename; $path = $dir . "/" . $filename;
if (is_dir($path) && $recursive) { if (\is_dir($path) && $recursive) {
$countSize += self::size($path, $recursive); $countSize += self::size($path, $recursive);
} elseif (is_file($path)) { } elseif (\is_file($path)) {
$countSize += filesize($path); $countSize += \filesize($path);
} }
} }
@ -189,22 +189,22 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function count(string $path, bool $recursive = true, array $ignore = []) : int public static function count(string $path, bool $recursive = true, array $ignore = []) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
$size = 0; $size = 0;
$files = scandir($path); $files = \scandir($path);
$ignore[] = '.'; $ignore[] = '.';
$ignore[] = '..'; $ignore[] = '..';
foreach ($files as $t) { foreach ($files as $t) {
if (in_array($t, $ignore)) { if (\in_array($t, $ignore)) {
continue; continue;
} }
if (is_dir(rtrim($path, '/') . '/' . $t)) { if (\is_dir(\rtrim($path, '/') . '/' . $t)) {
if ($recursive) { if ($recursive) {
$size += self::count(rtrim($path, '/') . '/' . $t, true, $ignore); $size += self::count(\rtrim($path, '/') . '/' . $t, true, $ignore);
} }
} else { } else {
$size++; $size++;
@ -219,21 +219,21 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function delete(string $path) : bool public static function delete(string $path) : bool
{ {
$files = scandir($path); $files = \scandir($path);
/* Removing . and .. */ /* Removing . and .. */
unset($files[1]); unset($files[1]);
unset($files[0]); unset($files[0]);
foreach ($files as $file) { foreach ($files as $file) {
if (is_dir($path . '/' . $file)) { if (\is_dir($path . '/' . $file)) {
self::delete($path . '/' . $file); self::delete($path . '/' . $file);
} else { } else {
unlink($path . '/' . $file); \unlink($path . '/' . $file);
} }
} }
rmdir($path); \rmdir($path);
return true; return true;
} }
@ -243,10 +243,10 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function parent(string $path) : string public static function parent(string $path) : string
{ {
$path = explode('/', str_replace('\\', '/', $path)); $path = \explode('/', \str_replace('\\', '/', $path));
array_pop($path); \array_pop($path);
return implode('/', $path); return \implode('/', $path);
} }
/** /**
@ -255,12 +255,12 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function created(string $path) : \DateTime public static function created(string $path) : \DateTime
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
$created = new \DateTime('now'); $created = new \DateTime('now');
$created->setTimestamp(filemtime($path)); $created->setTimestamp(\filemtime($path));
return $created; return $created;
} }
@ -270,12 +270,12 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function changed(string $path) : \DateTime public static function changed(string $path) : \DateTime
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
$changed = new \DateTime(); $changed = new \DateTime();
$changed->setTimestamp(filectime($path)); $changed->setTimestamp(\filectime($path));
return $changed; return $changed;
} }
@ -285,11 +285,11 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function owner(string $path) : int public static function owner(string $path) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return fileowner($path); return \fileowner($path);
} }
/** /**
@ -297,11 +297,11 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function permission(string $path) : int public static function permission(string $path) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return fileperms($path); return \fileperms($path);
} }
/** /**
@ -313,9 +313,9 @@ final class Directory extends FileAbstract implements DirectoryInterface
throw new PathException($from); throw new PathException($from);
} }
if (!file_exists($to)) { if (!\file_exists($to)) {
self::create($to, 0755, true); self::create($to, 0755, true);
} elseif ($overwrite && file_exists($to)) { } elseif ($overwrite && \file_exists($to)) {
self::delete($to); self::delete($to);
} else { } else {
return false; return false;
@ -326,9 +326,9 @@ final class Directory extends FileAbstract implements DirectoryInterface
\RecursiveIteratorIterator::SELF_FIRST) as $item \RecursiveIteratorIterator::SELF_FIRST) as $item
) { ) {
if ($item->isDir()) { if ($item->isDir()) {
mkdir($to . '/' . $iterator->getSubPathname()); \mkdir($to . '/' . $iterator->getSubPathname());
} else { } else {
copy($from . '/' . $iterator->getSubPathname(), $to . '/' . $iterator->getSubPathname()); \copy($from . '/' . $iterator->getSubPathname(), $to . '/' . $iterator->getSubPathname());
} }
} }
@ -344,9 +344,9 @@ final class Directory extends FileAbstract implements DirectoryInterface
throw new PathException($from); throw new PathException($from);
} }
if (!$overwrite && file_exists($to)) { if (!$overwrite && \file_exists($to)) {
return false; return false;
} elseif ($overwrite && file_exists($to)) { } elseif ($overwrite && \file_exists($to)) {
self::delete($to); self::delete($to);
} }
@ -354,7 +354,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
self::create(self::parent($to), 0755, true); self::create(self::parent($to), 0755, true);
} }
rename($from, $to); \rename($from, $to);
return true; return true;
} }
@ -364,7 +364,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function exists(string $path) : bool public static function exists(string $path) : bool
{ {
return file_exists($path); return \file_exists($path);
} }
/** /**
@ -372,7 +372,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function sanitize(string $path, string $replace = '') : string public static function sanitize(string $path, string $replace = '') : string
{ {
return preg_replace('[^\w\s\d\.\-_~,;:\[\]\(\]\/]', $replace, $path); return \preg_replace('[^\w\s\d\.\-_~,;:\[\]\(\]\/]', $replace, $path);
} }
/** /**
@ -398,12 +398,12 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function create(string $path, int $permission = 0755, bool $recursive = false) : bool public static function create(string $path, int $permission = 0755, bool $recursive = false) : bool
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
if (!$recursive && !file_exists(self::parent($path))) { if (!$recursive && !\file_exists(self::parent($path))) {
return false; return false;
} }
mkdir($path, $permission, $recursive); \mkdir($path, $permission, $recursive);
return true; return true;
} }
@ -435,7 +435,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function rewind() public function rewind()
{ {
reset($this->nodes); \reset($this->nodes);
} }
/** /**
@ -443,7 +443,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function current() public function current()
{ {
return current($this->nodes); return \current($this->nodes);
} }
/** /**
@ -451,7 +451,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function key() public function key()
{ {
return key($this->nodes); return \key($this->nodes);
} }
/** /**
@ -459,7 +459,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function next() public function next()
{ {
return next($this->nodes); return \next($this->nodes);
} }
/** /**
@ -467,7 +467,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public function valid() public function valid()
{ {
$key = key($this->nodes); $key = \key($this->nodes);
return ($key !== null && $key !== false); return ($key !== null && $key !== false);
} }
@ -507,7 +507,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function name(string $path) : string public static function name(string $path) : string
{ {
return basename($path); return \basename($path);
} }
/** /**
@ -515,7 +515,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function dirname(string $path) : string public static function dirname(string $path) : string
{ {
return basename($path); return \basename($path);
} }
/** /**
@ -531,7 +531,7 @@ final class Directory extends FileAbstract implements DirectoryInterface
*/ */
public static function basename(string $path) : string public static function basename(string $path) : string
{ {
return basename($path); return \basename($path);
} }
/** /**

View File

@ -44,7 +44,7 @@ final class File extends FileAbstract implements FileInterface
parent::__construct($path); parent::__construct($path);
$this->count = 1; $this->count = 1;
if (file_exists($this->path)) { if (\file_exists($this->path)) {
$this->index(); $this->index();
} }
} }
@ -56,7 +56,7 @@ final class File extends FileAbstract implements FileInterface
{ {
parent::index(); parent::index();
$this->size = filesize($this->path); $this->size = \filesize($this->path);
} }
/** /**
@ -64,7 +64,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function put(string $path, string $content, int $mode = ContentPutMode::REPLACE | ContentPutMode::CREATE) : bool public static function put(string $path, string $content, int $mode = ContentPutMode::REPLACE | ContentPutMode::CREATE) : bool
{ {
$exists = file_exists($path); $exists = \file_exists($path);
if ((ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists) if ((ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists)
|| (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists) || (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists)
@ -72,15 +72,15 @@ final class File extends FileAbstract implements FileInterface
|| (!$exists && ContentPutMode::hasFlag($mode, ContentPutMode::CREATE)) || (!$exists && ContentPutMode::hasFlag($mode, ContentPutMode::CREATE))
) { ) {
if (ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists) { if (ContentPutMode::hasFlag($mode, ContentPutMode::APPEND) && $exists) {
file_put_contents($path, file_get_contents($path) . $content); \file_put_contents($path, \file_get_contents($path) . $content);
} elseif (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists) { } elseif (ContentPutMode::hasFlag($mode, ContentPutMode::PREPEND) && $exists) {
file_put_contents($path, $content . file_get_contents($path)); \file_put_contents($path, $content . \file_get_contents($path));
} else { } else {
if (!Directory::exists(dirname($path))) { if (!Directory::exists(\dirname($path))) {
Directory::create(dirname($path), 0755, true); Directory::create(\dirname($path), 0755, true);
} }
file_put_contents($path, $content); \file_put_contents($path, $content);
} }
return true; return true;
@ -94,11 +94,11 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function get(string $path) : string public static function get(string $path) : string
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return file_get_contents($path); return \file_get_contents($path);
} }
/** /**
@ -138,7 +138,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function exists(string $path) : bool public static function exists(string $path) : bool
{ {
return file_exists($path); return \file_exists($path);
} }
/** /**
@ -146,7 +146,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function parent(string $path) : string public static function parent(string $path) : string
{ {
return Directory::parent(dirname($path)); return Directory::parent(\dirname($path));
} }
/** /**
@ -154,7 +154,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function sanitize(string $path, string $replace = '') : string public static function sanitize(string $path, string $replace = '') : string
{ {
return preg_replace('/[^\w\s\d\.\-_~,;\/\[\]\(\]]/', $replace, $path); return \preg_replace('/[^\w\s\d\.\-_~,;\/\[\]\(\]]/', $replace, $path);
} }
/** /**
@ -162,11 +162,11 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function created(string $path) : \DateTime public static function created(string $path) : \DateTime
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return self::createFileTime(filemtime($path)); return self::createFileTime(\filemtime($path));
} }
/** /**
@ -174,11 +174,11 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function changed(string $path) : \DateTime public static function changed(string $path) : \DateTime
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return self::createFileTime(filemtime($path)); return self::createFileTime(\filemtime($path));
} }
/** /**
@ -203,7 +203,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function size(string $path, bool $recursive = true) : int public static function size(string $path, bool $recursive = true) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -215,11 +215,11 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function owner(string $path) : int public static function owner(string $path) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return fileowner($path); return \fileowner($path);
} }
/** /**
@ -227,11 +227,11 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function permission(string $path) : int public static function permission(string $path) : int
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
throw new PathException($path); throw new PathException($path);
} }
return fileperms($path); return \fileperms($path);
} }
/** /**
@ -245,7 +245,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function dirname(string $path) : string public static function dirname(string $path) : string
{ {
return basename(dirname($path)); return basename(\dirname($path));
} }
/** /**
@ -271,12 +271,12 @@ final class File extends FileAbstract implements FileInterface
throw new PathException($from); throw new PathException($from);
} }
if ($overwrite || !file_exists($to)) { if ($overwrite || !\file_exists($to)) {
if (!Directory::exists(dirname($to))) { if (!Directory::exists(\dirname($to))) {
Directory::create(dirname($to), 0755, true); Directory::create(\dirname($to), 0755, true);
} }
if ($overwrite && file_exists($to)) { if ($overwrite && \file_exists($to)) {
unlink($to); unlink($to);
} }
@ -307,7 +307,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function delete(string $path) : bool public static function delete(string $path) : bool
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
return false; return false;
} }
@ -325,7 +325,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public function getDirName() : string public function getDirName() : string
{ {
return basename(dirname($this->path)); return basename(\dirname($this->path));
} }
/** /**
@ -353,16 +353,16 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function create(string $path) : bool public static function create(string $path) : bool
{ {
if (!file_exists($path)) { if (!\file_exists($path)) {
if (!Directory::exists(dirname($path))) { if (!Directory::exists(\dirname($path))) {
Directory::create(dirname($path), 0755, true); Directory::create(\dirname($path), 0755, true);
} }
if (!is_writable(dirname($path))) { if (!is_writable(\dirname($path))) {
return false; return false;
} }
touch($path); \touch($path);
return true; return true;
} }
@ -375,7 +375,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public function getContent() : string public function getContent() : string
{ {
return file_get_contents($this->path); return \file_get_contents($this->path);
} }
/** /**
@ -407,7 +407,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public function getName() : string public function getName() : string
{ {
return explode('.', $this->name)[0]; return \explode('.', $this->name)[0];
} }
/** /**
@ -415,7 +415,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public function getExtension() : string public function getExtension() : string
{ {
$extension = explode('.', $this->name); $extension = \explode('.', $this->name);
return $extension[1] ?? ''; return $extension[1] ?? '';
} }
@ -465,7 +465,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function name(string $path) : string public static function name(string $path) : string
{ {
return explode('.', basename($path))[0]; return \explode('.', \basename($path))[0];
} }
/** /**
@ -473,7 +473,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function basename(string $path) : string public static function basename(string $path) : string
{ {
return basename($path); return \basename($path);
} }
/** /**
@ -481,7 +481,7 @@ final class File extends FileAbstract implements FileInterface
*/ */
public static function extension(string $path) : string public static function extension(string $path) : string
{ {
$extension = explode('.', basename($path)); $extension = \explode('.', \basename($path));
return $extension[1] ?? ''; return $extension[1] ?? '';
} }

View File

@ -64,7 +64,7 @@ class LocalStorage extends StorageAbstract
*/ */
protected static function getClassType(string $path) : string protected static function getClassType(string $path) : string
{ {
return is_dir($path) || (!is_file($path) && stripos($path, '.') === false) ? Directory::class : File::class; return \is_dir($path) || (!is_file($path) && \stripos($path, '.') === false) ? Directory::class : File::class;
} }
/** /**
@ -72,7 +72,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function put(string $path, string $content, int $mode = 0) : bool public static function put(string $path, string $content, int $mode = 0) : bool
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -84,7 +84,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function get(string $path) : string public static function get(string $path) : string
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -96,7 +96,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function list(string $path, string $filter = '*') : array public static function list(string $path, string $filter = '*') : array
{ {
if (is_file($path)) { if (\is_file($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -108,7 +108,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function create(string $path) : bool public static function create(string $path) : bool
{ {
return stripos($path, '.') === false ? Directory::create($path, 0755, true) : File::create($path); return \stripos($path, '.') === false ? Directory::create($path, 0755, true) : File::create($path);
} }
/** /**
@ -116,7 +116,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function set(string $path, string $content) : bool public static function set(string $path, string $content) : bool
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -128,7 +128,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function append(string $path, string $content) : bool public static function append(string $path, string $content) : bool
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -140,7 +140,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function prepend(string $path, string $content) : bool public static function prepend(string $path, string $content) : bool
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }
@ -152,7 +152,7 @@ class LocalStorage extends StorageAbstract
*/ */
public static function extension(string $path) : string public static function extension(string $path) : string
{ {
if (is_dir($path)) { if (\is_dir($path)) {
throw new PathException($path); throw new PathException($path);
} }

View File

@ -58,7 +58,7 @@ final class SystemUtils
while ($line = fgets($fh)) { while ($line = fgets($fh)) {
$pieces = []; $pieces = [];
if (preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) { if (\preg_match('/^MemTotal:\s+(\d+)\skB$/', $line, $pieces)) {
$mem = $pieces[1] * 1024; $mem = $pieces[1] * 1024;
break; break;
} }
@ -84,8 +84,8 @@ final class SystemUtils
if (stristr(PHP_OS, 'LINUX')) { if (stristr(PHP_OS, 'LINUX')) {
$free = shell_exec('free'); $free = shell_exec('free');
$free = (string) trim($free); $free = (string) trim($free);
$freeArr = explode("\n", $free); $freeArr = \explode("\n", $free);
$mem = explode(" ", $freeArr[1]); $mem = \explode(" ", $freeArr[1]);
$mem = array_values(array_filter($mem)); $mem = array_values(array_filter($mem));
$memUsage = $mem[2] / $mem[1] * 100; $memUsage = $mem[2] / $mem[1] * 100;
} }

View File

@ -28,7 +28,7 @@ final class UnhandledHandler
/** /**
* Exception handler. * Exception handler.
* *
* @param mixed $e Exception * @param \Throwable $e Exception
* *
* @return void * @return void
* *

View File

@ -157,7 +157,7 @@ final class UriFactory
$success = false; $success = false;
foreach (self::$uri as $key => $value) { foreach (self::$uri as $key => $value) {
if (((bool) preg_match('~^' . $pattern . '$~', $key))) { if (((bool) \preg_match('~^' . $pattern . '$~', $key))) {
unset(self::$uri[$key]); unset(self::$uri[$key]);
$success = true; $success = true;
} }
@ -179,16 +179,16 @@ final class UriFactory
*/ */
private static function unique(string $url) : string private static function unique(string $url) : string
{ {
$parts = explode('?', $url); $parts = \explode('?', $url);
if (count($parts) >= 2) { if (count($parts) >= 2) {
$full = $parts[1]; $full = $parts[1];
$pars = explode('&', $full); $pars = \explode('&', $full);
$comps = []; $comps = [];
$length = count($pars); $length = count($pars);
for ($i = 0; $i < $length; ++$i) { for ($i = 0; $i < $length; ++$i) {
$spl = explode('=', $pars[$i]); $spl = \explode('=', $pars[$i]);
if (isset($spl[1])) { if (isset($spl[1])) {
$comps[$spl[0]] = $spl[1]; $comps[$spl[0]] = $spl[1];
@ -200,7 +200,7 @@ final class UriFactory
$pars[] = $key . '=' . $value; $pars[] = $key . '=' . $value;
} }
$url = $parts[0] . (empty($pars) ? '' : '?' . implode('&', $pars)); $url = $parts[0] . (empty($pars) ? '' : '?' . \implode('&', $pars));
} }
return $url; return $url;
@ -227,15 +227,15 @@ final class UriFactory
*/ */
public static function build(string $uri, array $toMatch = []) : string public static function build(string $uri, array $toMatch = []) : string
{ {
$parsed = preg_replace_callback('(\{[\/#\?%@\.\$][a-zA-Z0-9\-]*\})', function ($match) use ($toMatch) { $parsed = \preg_replace_callback('(\{[\/#\?%@\.\$][a-zA-Z0-9\-]*\})', function ($match) use ($toMatch) {
$match = substr($match[0], 1, strlen($match[0]) - 2); $match = \substr($match[0], 1, \strlen($match[0]) - 2);
return $toMatch[$match] ?? self::$uri[$match] ?? $match; return $toMatch[$match] ?? self::$uri[$match] ?? $match;
}, $uri); }, $uri);
// todo: maybe don't do this and adjust unique?! // todo: maybe don't do this and adjust unique?!
if (strpos($parsed, '?')) { if (\strpos($parsed, '?')) {
str_replace('&', '?', $parsed); \str_replace('&', '?', $parsed);
} }
return self::unique($parsed); return self::unique($parsed);

View File

@ -48,7 +48,7 @@ final class ArrayUtils
*/ */
public static function unsetArray(string $path, array $data, string $delim = '/') : array public static function unsetArray(string $path, array $data, string $delim = '/') : array
{ {
$nodes = explode($delim, trim($path, $delim)); $nodes = \explode($delim, trim($path, $delim));
$prevEl = null; $prevEl = null;
$el = &$data; $el = &$data;
@ -86,7 +86,7 @@ final class ArrayUtils
*/ */
public static function setArray(string $path, array $data, $value, string $delim = '/', bool $overwrite = false) : array public static function setArray(string $path, array $data, $value, string $delim = '/', bool $overwrite = false) : array
{ {
$pathParts = explode($delim, trim($path, $delim)); $pathParts = \explode($delim, trim($path, $delim));
$current = &$data; $current = &$data;
foreach ($pathParts as $key) { foreach ($pathParts as $key) {
@ -121,7 +121,7 @@ final class ArrayUtils
*/ */
public static function getArray(string $path, array $data, string $delim = '/') public static function getArray(string $path, array $data, string $delim = '/')
{ {
$pathParts = explode($delim, trim($path, $delim)); $pathParts = \explode($delim, trim($path, $delim));
$current = $data; $current = $data;
foreach ($pathParts as $key) { foreach ($pathParts as $key) {
@ -167,7 +167,7 @@ final class ArrayUtils
/** /**
* Check if any of the needles are in the array * Check if any of the needles are in the array
* *
* @param mixed $needles Needles for search * @param array $needles Needles for search
* @param array $haystack Haystack for search * @param array $haystack Haystack for search
* *
* @return bool * @return bool
@ -177,7 +177,7 @@ final class ArrayUtils
public static function anyInArray(array $needles, array $haystack) : bool public static function anyInArray(array $needles, array $haystack) : bool
{ {
foreach ($needles as $needle) { foreach ($needles as $needle) {
if (in_array($needle, $haystack)) { if (\in_array($needle, $haystack)) {
return true; return true;
} }
} }
@ -188,7 +188,7 @@ final class ArrayUtils
/** /**
* Check if all of the needles are in the array * Check if all of the needles are in the array
* *
* @param mixed $needles Needles for search * @param array $needles Needles for search
* @param array $haystack Haystack for search * @param array $haystack Haystack for search
* *
* @return bool * @return bool
@ -198,7 +198,7 @@ final class ArrayUtils
public static function allInArray(array $needles, array $haystack) : bool public static function allInArray(array $needles, array $haystack) : bool
{ {
foreach ($needles as $needle) { foreach ($needles as $needle) {
if (!in_array($needle, $haystack)) { if (!\in_array($needle, $haystack)) {
return false; return false;
} }
} }

View File

@ -370,7 +370,7 @@ abstract class C128Abstract
* *
* @param string $codeString Code string to render * @param string $codeString Code string to render
* *
* @return array * @return array<string, int>
* *
* @since 1.0.0 * @since 1.0.0
*/ */

View File

@ -125,8 +125,8 @@ class C25 extends C128Abstract
for ($posX = 1; $posX <= $length; $posX += 2) { for ($posX = 1; $posX <= $length; $posX += 2) {
if (isset($temp[$posX], $temp[($posX + 1)])) { if (isset($temp[$posX], $temp[($posX + 1)])) {
$temp1 = explode('-', $temp[$posX]); $temp1 = \explode('-', $temp[$posX]);
$temp2 = explode('-', $temp[($posX + 1)]); $temp2 = \explode('-', $temp[($posX + 1)]);
$count = count($temp1); $count = count($temp1);
for ($posY = 0; $posY < $count; $posY++) { for ($posY = 0; $posY < $count; $posY++) {

View File

@ -40,7 +40,7 @@ final class ColorUtils
* *
* @param int $rgbInt Value to convert * @param int $rgbInt Value to convert
* *
* @return array * @return array<string, int>
* *
* @since 1.0.0 * @since 1.0.0
*/ */

View File

@ -65,7 +65,7 @@ class LZW implements CompressionInterface
*/ */
public function decompress(string $compressed) : string public function decompress(string $compressed) : string
{ {
$compressed = explode(',', $compressed); $compressed = \explode(',', $compressed);
$dictionary = []; $dictionary = [];
$entry = ''; $entry = '';
$dictSize = 256; $dictSize = 256;

View File

@ -47,7 +47,7 @@ class Ip
*/ */
public static function ip2Float(string $ip) : float public static function ip2Float(string $ip) : float
{ {
$split = explode('.', $ip); $split = \explode('.', $ip);
return $split[0] * (256 ** 3) + $split[1] * (256 ** 2) + $split[2] * (256 ** 1) + $split[3]; return $split[0] * (256 ** 3) + $split[1] * (256 ** 2) + $split[2] * (256 ** 1) + $split[3];
} }

View File

@ -80,7 +80,7 @@ final class Dictionary
$count = []; $count = [];
while (isset($source[0])) { while (isset($source[0])) {
$count[] = [substr_count($source, $source[0]), $source[0]]; $count[] = [substr_count($source, $source[0]), $source[0]];
$source = str_replace($source[0], '', $source); $source = \str_replace($source[0], '', $source);
} }
sort($count); sort($count);
@ -144,7 +144,7 @@ final class Dictionary
throw new \InvalidArgumentException('Character already exists'); throw new \InvalidArgumentException('Character already exists');
} }
if (strlen(str_replace('0', '', str_replace('1', '', $value))) !== 0) { if (strlen(\str_replace('0', '', \str_replace('1', '', $value))) !== 0) {
throw new \InvalidArgumentException('Bad formatting.'); throw new \InvalidArgumentException('Bad formatting.');
} }

View File

@ -95,7 +95,7 @@ class Repository
throw new PathException($path); throw new PathException($path);
} }
if (file_exists($this->path . '/.git') && is_dir($this->path . '/.git')) { if (file_exists($this->path . '/.git') && \is_dir($this->path . '/.git')) {
$this->bare = false; $this->bare = false;
} elseif (is_file($this->path . '/config')) { // Is this a bare repo? } elseif (is_file($this->path . '/config')) { // Is this a bare repo?
$parseIni = parse_ini_file($this->path . '/config'); $parseIni = parse_ini_file($this->path . '/config');
@ -171,7 +171,7 @@ class Repository
private function run(string $cmd) : array private function run(string $cmd) : array
{ {
if (strtolower(substr(PHP_OS, 0, 3)) == 'win') { if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
$cmd = 'cd ' . escapeshellarg(dirname(Git::getBin())) $cmd = 'cd ' . escapeshellarg(\dirname(Git::getBin()))
. ' && ' . basename(Git::getBin()) . ' && ' . basename(Git::getBin())
. ' -C ' . escapeshellarg($this->path) . ' ' . ' -C ' . escapeshellarg($this->path) . ' '
. $cmd; . $cmd;
@ -242,12 +242,12 @@ class Repository
*/ */
public function create(string $source = null) : void public function create(string $source = null) : void
{ {
if (!is_dir($this->path) || file_exists($this->path . '/.git')) { if (!is_dir($this->path) || \file_exists($this->path . '/.git')) {
throw new \Exception('Already repository'); throw new \Exception('Already repository');
} }
if ($source !== null) { if ($source !== null) {
stripos($source, '//') !== false ? $this->cloneRemote($source) : $this->cloneFrom($source); \stripos($source, '//') !== false ? $this->cloneRemote($source) : $this->cloneFrom($source);
return; return;
} }
@ -438,8 +438,8 @@ class Repository
{ {
if (empty($this->name)) { if (empty($this->name)) {
$path = $this->getDirectoryPath(); $path = $this->getDirectoryPath();
$path = str_replace('\\', '/', $path); $path = \str_replace('\\', '/', $path);
$path = explode('/', $path); $path = \explode('/', $path);
$this->name = $path[count($path) - ($this->bare ? 1 : 2)]; $this->name = $path[count($path) - ($this->bare ? 1 : 2)];
} }
@ -605,7 +605,7 @@ class Repository
*/ */
public function setDescription(string $description) : void public function setDescription(string $description) : void
{ {
file_put_contents($this->getDirectoryPath(), $description); \file_put_contents($this->getDirectoryPath(), $description);
} }
/** /**
@ -617,7 +617,7 @@ class Repository
*/ */
public function getDescription() : string public function getDescription() : string
{ {
return file_get_contents($this->getDirectoryPath() . '/description'); return \file_get_contents($this->getDirectoryPath() . '/description');
} }
/** /**
@ -657,7 +657,7 @@ class Repository
continue; continue;
} }
if (!file_exists($path = $this->getDirectoryPath() . ($this->bare ? '/' : '/../') . $line)) { if (!\file_exists($path = $this->getDirectoryPath() . ($this->bare ? '/' : '/../') . $line)) {
return 0; return 0;
} }
@ -702,7 +702,7 @@ class Repository
$contributors = []; $contributors = [];
foreach ($lines as $line) { foreach ($lines as $line) {
preg_match('/^[0-9]*/', $line, $matches); \preg_match('/^[0-9]*/', $line, $matches);
$contributor = new Author(substr($line, strlen($matches[0]) + 1)); $contributor = new Author(substr($line, strlen($matches[0]) + 1));
$contributor->setCommitCount($this->getCommitsCount($start, $end)[$contributor->getName()]); $contributor->setCommitCount($this->getCommitsCount($start, $end)[$contributor->getName()]);
@ -741,7 +741,7 @@ class Repository
$commits = []; $commits = [];
foreach ($lines as $line) { foreach ($lines as $line) {
preg_match('/^[0-9]*/', $line, $matches); \preg_match('/^[0-9]*/', $line, $matches);
$commits[substr($line, strlen($matches[0]) + 1)] = (int) $matches[0]; $commits[substr($line, strlen($matches[0]) + 1)] = (int) $matches[0];
} }
@ -779,7 +779,7 @@ class Repository
); );
foreach ($lines as $line) { foreach ($lines as $line) {
$nums = explode(' ', $line); $nums = \explode(' ', $line);
$addremove['added'] += $nums[0]; $addremove['added'] += $nums[0];
$addremove['removed'] += $nums[1]; $addremove['removed'] += $nums[1];
@ -836,7 +836,7 @@ class Repository
$commits = []; $commits = [];
for ($i = 0; $i < $count; ++$i) { for ($i = 0; $i < $count; ++$i) {
$match = preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[$i], $matches); $match = \preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[$i], $matches);
if ($match !== false && $match !== 0) { if ($match !== false && $match !== 0) {
$commit = $this->getCommit($matches[0]); $commit = $this->getCommit($matches[0]);
@ -868,7 +868,7 @@ class Repository
return new Commit(); return new Commit();
} }
preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches); \preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches);
if (!isset($matches[0]) || strlen($matches[0]) !== 40) { if (!isset($matches[0]) || strlen($matches[0]) !== 40) {
throw new \Exception('Invalid commit id'); throw new \Exception('Invalid commit id');
@ -879,8 +879,8 @@ class Repository
} }
// todo: validate if array values are all initialized // todo: validate if array values are all initialized
$author = explode(':', $lines[1]); $author = \explode(':', $lines[1]);
$author = explode('<', trim($author[1])); $author = \explode('<', trim($author[1]));
$date = substr($lines[2], 6); $date = substr($lines[2], 6);
$commit = new Commit($matches[0]); $commit = new Commit($matches[0]);
@ -918,7 +918,7 @@ class Repository
return new Commit(); return new Commit();
} }
preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches); \preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches);
if (!isset($matches[0]) || strlen($matches[0]) !== 40) { if (!isset($matches[0]) || strlen($matches[0]) !== 40) {
throw new \Exception('Invalid commit id'); throw new \Exception('Invalid commit id');

View File

@ -71,7 +71,7 @@ class CsvDatabaseMapper implements IODatabaseMapper
} }
$query = new Builder($this->db); $query = new Builder($this->db);
$query->insert(...$header)->into(str_replace(' ', '', explode($source, '.'))); $query->insert(...$header)->into(\str_replace(' ', '', explode($source, '.')));
while (feof($file)) { while (feof($file)) {
$c = 0; $c = 0;

View File

@ -31,8 +31,8 @@ class Gz implements ArchiveInterface
*/ */
public static function pack($source, string $destination, bool $overwrite = true) : bool public static function pack($source, string $destination, bool $overwrite = true) : bool
{ {
$destination = str_replace('\\', '/', realpath($destination)); $destination = \str_replace('\\', '/', realpath($destination));
if (!$overwrite && file_exists($destination)) { if (!$overwrite && \file_exists($destination)) {
return false; return false;
} }
@ -55,7 +55,7 @@ class Gz implements ArchiveInterface
*/ */
public static function unpack(string $source, string $destination) : bool public static function unpack(string $source, string $destination) : bool
{ {
$destination = str_replace('\\', '/', realpath($destination)); $destination = \str_replace('\\', '/', realpath($destination));
if (file_exists($destination)) { if (file_exists($destination)) {
return false; return false;
} }

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