diff --git a/Account/NullAccount.php b/Account/NullAccount.php index 471fb8e4a..c11f5f1d4 100755 --- a/Account/NullAccount.php +++ b/Account/NullAccount.php @@ -24,4 +24,11 @@ namespace phpOMS\Account; */ final class NullAccount extends Account { + /** + * {@inheritdoc} + */ + public function jsonSerialize() : mixed + { + return ['id' => $this->id]; + } } diff --git a/Ai/Ocr/Tesseract/TesseractOcr.php b/Ai/Ocr/Tesseract/TesseractOcr.php index 87a2f1e26..7193e756e 100755 --- a/Ai/Ocr/Tesseract/TesseractOcr.php +++ b/Ai/Ocr/Tesseract/TesseractOcr.php @@ -87,7 +87,7 @@ final class TesseractOcr */ public function parseImage(string $image, array $languages = ['eng'], int $psm = 3, int $oem = 3) : string { - $temp = \tempnam(\sys_get_temp_dir(), 'ocr_'); + $temp = \tempnam(\sys_get_temp_dir(), 'oms_ocr_'); if ($temp === false) { return ''; } @@ -107,15 +107,24 @@ final class TesseractOcr : $temp; if (!\is_file($filepath)) { + // @codeCoverageIgnoreStart + \unlink($temp); + return ''; + // @codeCoverageIgnoreEnd } $parsed = \file_get_contents($filepath); if ($parsed === false) { + // @codeCoverageIgnoreStart + \unlink($temp); + return ''; + // @codeCoverageIgnoreEnd } \unlink($filepath); + \unlink($temp); return \trim($parsed); } diff --git a/DataStorage/Database/GrammarAbstract.php b/DataStorage/Database/GrammarAbstract.php index dd84dec70..322c2494d 100755 --- a/DataStorage/Database/GrammarAbstract.php +++ b/DataStorage/Database/GrammarAbstract.php @@ -194,16 +194,8 @@ abstract class GrammarAbstract foreach ($elements as $key => $element) { if (\is_string($element)) { - // @note: Replaced $this->compileSystem with $element - // This causes problems for tables or columns which use keywords such as count, - // but they are rare and should be handled somewhere else if it actually is such a case - if (\in_array($element, ['group', 'id', 'where', 'order'])) { - $expression .= $this->compileSystem($element) - . (\is_string($key) ? ' as ' . $key : '') . ', '; - } else { - $expression .= $element - . (\is_string($key) ? ' as ' . $key : '') . ', '; - } + $expression .= $this->compileSystem($element) + . (\is_string($key) ? ' as ' . $key : '') . ', '; } elseif ($element instanceof \Closure) { $expression .= $element() . (\is_string($key) ? ' as ' . $key : '') . ', '; } elseif ($element instanceof BuilderAbstract) { diff --git a/DataStorage/Database/Mapper/WriteMapper.php b/DataStorage/Database/Mapper/WriteMapper.php index b6177680f..7afea280c 100755 --- a/DataStorage/Database/Mapper/WriteMapper.php +++ b/DataStorage/Database/Mapper/WriteMapper.php @@ -258,13 +258,13 @@ final class WriteMapper extends DataMapperAbstract */ private function createHasMany(\ReflectionClass $refClass, object $obj, mixed $objId) : void { - foreach ($this->mapper::HAS_MANY as $propertyName => $rel) { + foreach ($this->mapper::HAS_MANY as $propertyName => $_) { if (!isset($this->mapper::HAS_MANY[$propertyName]['mapper'])) { throw new InvalidMapperException(); // @codeCoverageIgnore } $property = $refClass->getProperty($propertyName); - if (!($isPublic = $property->isPublic())) { + if (!$property->isPublic()) { $values = $property->getValue($obj); } else { $values = $obj->{$propertyName}; diff --git a/DataStorage/Database/Query/Grammar/Grammar.php b/DataStorage/Database/Query/Grammar/Grammar.php index d1f5f795b..94204ef6b 100755 --- a/DataStorage/Database/Query/Grammar/Grammar.php +++ b/DataStorage/Database/Query/Grammar/Grammar.php @@ -280,6 +280,7 @@ class Grammar extends GrammarAbstract } if (\is_string($element['column'])) { + // @todo: check if column contains special name which needs to be escaped $expression .= $this->compileSystem($element['column']); } elseif ($element['column'] instanceof \Closure) { $expression .= $element['column'](); @@ -311,7 +312,7 @@ class Grammar extends GrammarAbstract */ protected function compileWhereQuery(Where $where) : string { - return $where->toSql()[0]; + return $where->toSql(); } /** @@ -325,7 +326,7 @@ class Grammar extends GrammarAbstract */ protected function compileFromQuery(From $from) : string { - return $from->toSql()[0]; + return $from->toSql(); } /** @@ -478,7 +479,8 @@ class Grammar extends GrammarAbstract $expression = ''; foreach ($groups as $group) { - $expression .= $this->compileSystem($group) . ', '; + // @todo: check special names + $expression .= $group . ', '; } $expression = \rtrim($expression, ', '); @@ -570,6 +572,8 @@ class Grammar extends GrammarAbstract return ''; } + // @todo: check special names + $cols = '('; for ($i = 0; $i < $count; ++$i) { $cols .= $this->compileSystem($columns[$i]) . ', '; diff --git a/Image/Kernel.php b/Image/Kernel.php index 50347fbdf..44828f9f3 100755 --- a/Image/Kernel.php +++ b/Image/Kernel.php @@ -124,11 +124,11 @@ final class Kernel } } - $newR = \max(0, \min(255, $newR)); - $newG = \max(0, \min(255, $newG)); - $newB = \max(0, \min(255, $newB)); + $newR = (int) \max(0, \min(255, $newR)); + $newG = (int) \max(0, \min(255, $newG)); + $newB = (int) \max(0, \min(255, $newB)); - \imagesetpixel($im, $x, $y, (int) (($newR << 16) + ($newG << 8) | $newB)); + \imagesetpixel($im, $x, $y, (int) (($newR << 16) | ($newG << 8) | $newB)); } } } diff --git a/Localization/BaseStringL11n.php b/Localization/BaseStringL11n.php index c063318bc..787c783cf 100755 --- a/Localization/BaseStringL11n.php +++ b/Localization/BaseStringL11n.php @@ -99,6 +99,7 @@ class BaseStringL11n implements \JsonSerializable $this->content = $content; $this->language = $language; $this->country = $country; + $this->type = new NullBaseStringL11nType(); } /** diff --git a/Localization/ISO3166NameEnum.php b/Localization/ISO3166NameEnum.php index 6eb569502..d9836a316 100755 --- a/Localization/ISO3166NameEnum.php +++ b/Localization/ISO3166NameEnum.php @@ -527,4 +527,6 @@ class ISO3166NameEnum extends Enum public const _XXK = 'Kosovo'; public const _XXX = 'XXX'; + + use ISO3166RegionTrait; } diff --git a/Localization/ISO639CountryTrait.php b/Localization/ISO639CountryTrait.php index 49fd399e8..9d54a5c78 100755 --- a/Localization/ISO639CountryTrait.php +++ b/Localization/ISO639CountryTrait.php @@ -38,6 +38,8 @@ trait ISO639CountryTrait switch (\strtoupper($country)) { case ISO3166TwoEnum::_AFG: return [self::_PS, self::_UZ, self::_TK]; + case ISO3166TwoEnum::_ATA: + return [self::_RU, self::_EN]; case ISO3166TwoEnum::_ALA: return [self::_SV]; case ISO3166TwoEnum::_ALB: @@ -95,7 +97,7 @@ trait ISO639CountryTrait case ISO3166TwoEnum::_BWA: return [self::_EN, self::_TN]; case ISO3166TwoEnum::_BVT: - return []; + return [self::_NO]; case ISO3166TwoEnum::_BRA: return [self::_PT]; case ISO3166TwoEnum::_IOT: @@ -308,6 +310,8 @@ trait ISO639CountryTrait return [self::_FR]; case ISO3166TwoEnum::_MLT: return [self::_MT, self::_EN]; + case ISO3166TwoEnum::_MKD: + return [self::_MK]; case ISO3166TwoEnum::_MHL: return [self::_MH, self::_EN]; case ISO3166TwoEnum::_MTQ: diff --git a/Log/FileLogger.php b/Log/FileLogger.php index 7be384019..616fce8f1 100755 --- a/Log/FileLogger.php +++ b/Log/FileLogger.php @@ -100,7 +100,7 @@ final class FileLogger implements LoggerInterface */ public function __construct(string $lpath = '', bool $verbose = false) { - $path = \realpath(empty($lpath) ? __DIR__ . '/../../' : $lpath); + $path = \realpath(empty($lpath) ? __DIR__ . '/../../Logs/' : $lpath); $this->verbose = $verbose; $this->path = \is_dir($lpath) || \strpos($lpath, '.') === false diff --git a/Message/Http/HttpHeader.php b/Message/Http/HttpHeader.php index 44511e282..832d98430 100755 --- a/Message/Http/HttpHeader.php +++ b/Message/Http/HttpHeader.php @@ -277,831 +277,206 @@ final class HttpHeader extends HeaderAbstract { switch ($code) { case RequestStatusCode::R_100: - $this->generate100(); + $this->set('', 'HTTP/1.0 100 Continue'); + $this->set('Status', '100 Continue'); break; case RequestStatusCode::R_102: - $this->generate102(); + $this->set('', 'HTTP/1.0 102 Processing'); + $this->set('Status', '102 Processing'); break; case RequestStatusCode::R_200: - $this->generate200(); + $this->set('', 'HTTP/1.0 200 OK'); + $this->set('Status', '200 OK'); break; case RequestStatusCode::R_201: - $this->generate201(); + $this->set('', 'HTTP/1.0 201 Created'); + $this->set('Status', '201 Created'); break; case RequestStatusCode::R_202: - $this->generate202(); + $this->set('', 'HTTP/1.0 202 Accepted'); + $this->set('Status', '202 Accepted'); break; case RequestStatusCode::R_204: - $this->generate204(); + $this->set('', 'HTTP/1.0 204 No Content'); + $this->set('Status', '204 No Content'); break; case RequestStatusCode::R_205: - $this->generate205(); + $this->set('', 'HTTP/1.0 205 Reset Content'); + $this->set('Status', '205 Reset Content'); break; case RequestStatusCode::R_206: - $this->generate206(); + $this->set('', 'HTTP/1.0 206 Partial Content'); + $this->set('Status', '206 Partial Content'); break; case RequestStatusCode::R_301: - $this->generate301(); + $this->set('', 'HTTP/1.0 301 Moved Permanently'); + $this->set('Status', '301 Moved Permanently'); break; case RequestStatusCode::R_302: - $this->generate302(); + $this->set('', 'HTTP/1.0 302 Found'); + $this->set('Status', '302 Found'); break; case RequestStatusCode::R_303: - $this->generate303(); + $this->set('', 'HTTP/1.0 303 See Other'); + $this->set('Status', '303 See Other'); break; case RequestStatusCode::R_304: - $this->generate304(); + $this->set('', 'HTTP/1.0 304 Not Modified'); + $this->set('Status', '304 Not Modified'); break; case RequestStatusCode::R_307: - $this->generate307(); + $this->set('', 'HTTP/1.0 307 Temporary Redirect'); + $this->set('Status', '307 Temporary Redirect'); break; case RequestStatusCode::R_308: - $this->generate308(); + $this->set('', 'HTTP/1.0 308 Permanent Redirect'); + $this->set('Status', '308 Permanent Redirect'); break; case RequestStatusCode::R_400: - $this->generate400(); + $this->set('', 'HTTP/1.0 400 Bad Request'); + $this->set('Status', '400 Bad Request'); break; case RequestStatusCode::R_401: - $this->generate401(); + $this->set('', 'HTTP/1.0 401 Unauthorized'); + $this->set('Status', '401 Unauthorized'); break; case RequestStatusCode::R_402: - $this->generate402(); + $this->set('', 'HTTP/1.0 402 Payment Required'); + $this->set('Status', '402 Payment Required'); break; case RequestStatusCode::R_403: - $this->generate403(); + $this->set('', 'HTTP/1.0 403 Forbidden'); + $this->set('Status', '403 Forbidden'); break; case RequestStatusCode::R_404: - $this->generate404(); + $this->set('', 'HTTP/1.0 404 Not Found'); + $this->set('Status', '404 Not Found'); break; case RequestStatusCode::R_405: - $this->generate405(); + $this->set('', 'HTTP/1.0 405 Method Not Allowed'); + $this->set('Status', '405 Method Not Allowed'); break; case RequestStatusCode::R_406: - $this->generate406(); + $this->set('', 'HTTP/1.0 406 Not acceptable'); + $this->set('Status', '406 Not acceptable'); break; case RequestStatusCode::R_407: - $this->generate407(); + $this->set('', 'HTTP/1.0 407 Proxy Authentication Required'); + $this->set('Status', '407 Proxy Authentication Required'); break; case RequestStatusCode::R_408: - $this->generate408(); + $this->set('', 'HTTP/1.0 408 Request Timeout'); + $this->set('Status', '408 Request Timeout'); break; case RequestStatusCode::R_409: - $this->generate409(); + $this->set('', 'HTTP/1.0 409 Conflict'); + $this->set('Status', '409 Conflict'); break; case RequestStatusCode::R_410: - $this->generate410(); + $this->set('', 'HTTP/1.0 410 Gone'); + $this->set('Status', '410 Gone'); break; case RequestStatusCode::R_411: - $this->generate411(); + $this->set('', 'HTTP/1.0 411 Length Required'); + $this->set('Status', '411 Length Required'); break; case RequestStatusCode::R_412: - $this->generate412(); + $this->set('', 'HTTP/1.0 412 Precondition Failed'); + $this->set('Status', '412 Precondition Failed'); break; case RequestStatusCode::R_413: - $this->generate413(); + $this->set('', 'HTTP/1.0 413 Request Entity Too Large'); + $this->set('Status', '413 Request Entity Too Large'); break; case RequestStatusCode::R_414: - $this->generate414(); + $this->set('', 'HTTP/1.0 414 Request-URI Too Long'); + $this->set('Status', '414 Request-URI Too Long'); break; case RequestStatusCode::R_415: - $this->generate415(); + $this->set('', 'HTTP/1.0 415 Unsupported Media Type'); + $this->set('Status', '415 Unsupported Media Type'); break; case RequestStatusCode::R_416: - $this->generate416(); + $this->set('', 'HTTP/1.0 416 Requested Range Not Satisfiable'); + $this->set('Status', '416 Requested Range Not Satisfiable'); break; case RequestStatusCode::R_417: - $this->generate417(); + $this->set('', 'HTTP/1.0 417 Expectation Failed'); + $this->set('Status', '417 Expectation Failed'); break; case RequestStatusCode::R_421: - $this->generate421(); + $this->set('', 'HTTP/1.0 421 Misdirected Request'); + $this->set('Status', '421 Misdirected Request'); break; case RequestStatusCode::R_422: - $this->generate422(); + $this->set('', 'HTTP/1.0 422 Unprocessable Entity'); + $this->set('Status', '422 Unprocessable Entity'); break; case RequestStatusCode::R_423: - $this->generate423(); + $this->set('', 'HTTP/1.0 423 Locked'); + $this->set('Status', '423 Locked'); break; case RequestStatusCode::R_424: - $this->generate424(); + $this->set('', 'HTTP/1.0 424 Failed Dependency'); + $this->set('Status', '424 Failed Dependency'); + break; + case RequestStatusCode::R_425: + $this->set('', 'HTTP/1.0 425 Too Early'); + $this->set('Status', '425 Too Early'); break; case RequestStatusCode::R_426: - $this->generate426(); + $this->set('', 'HTTP/1.0 426 Upgrade Required'); + $this->set('Status', '426 Upgrade Required'); break; case RequestStatusCode::R_428: - $this->generate428(); + $this->set('', 'HTTP/1.0 428 Precondition Required'); + $this->set('Status', '428 Precondition Required'); break; case RequestStatusCode::R_429: - $this->generate429(); + $this->set('', 'HTTP/1.0 429 Too Many Requests'); + $this->set('Status', '429 Too Many Requests'); break; case RequestStatusCode::R_431: - $this->generate431(); + $this->set('', 'HTTP/1.0 431 Request Header Fields Too Large'); + $this->set('Status', '431 Request Header Fields Too Large'); break; case RequestStatusCode::R_451: - $this->generate451(); - break; - case RequestStatusCode::R_500: - $this->generate500(); + $this->set('', 'HTTP/1.0 451 Unavailable For Legal Reasons'); + $this->set('Status', '451 Unavailable For Legal Reasons'); break; case RequestStatusCode::R_501: - $this->generate501(); + $this->set('', 'HTTP/1.0 501 Not Implemented'); + $this->set('Status', '501 Not Implemented'); break; case RequestStatusCode::R_502: - $this->generate502(); + $this->set('', 'HTTP/1.0 502 Bad Gateway'); + $this->set('Status', '502 Bad Gateway'); break; case RequestStatusCode::R_503: - $this->generate503(); + $this->set('', 'HTTP/1.0 503 Service Temporarily Unavailable'); + $this->set('Status', '503 Service Temporarily Unavailable'); + $this->set('Retry-After', 'Retry-After: 300'); break; case RequestStatusCode::R_504: - $this->generate504(); + $this->set('', 'HTTP/1.0 504 Gateway Timeout'); + $this->set('Status', '504 Gateway Timeout'); break; case RequestStatusCode::R_507: - $this->generate507(); + $this->set('', 'HTTP/1.0 507 Insufficient Storage'); + $this->set('Status', '507 Insufficient Storage'); break; case RequestStatusCode::R_508: - $this->generate508(); + $this->set('', 'HTTP/1.0 508 Loop Detected'); + $this->set('Status', '508 Loop Detected'); break; case RequestStatusCode::R_511: - $this->generate511(); + $this->set('', 'HTTP/1.0 511 Network Authentication Required'); + $this->set('Status', '511 Network Authentication Required'); break; + case RequestStatusCode::R_500: default: - $this->generate500(); + $this->set('', 'HTTP/1.0 500 Internal Server Error'); + $this->set('Status', '500 Internal Server Error'); } } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate100() : void - { - $this->set('', 'HTTP/1.0 100 Continue'); - $this->set('Status', '100 Continue'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate102() : void - { - $this->set('', 'HTTP/1.0 102 Processing'); - $this->set('Status', '102 Processing'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate200() : void - { - $this->set('', 'HTTP/1.0 200 OK'); - $this->set('Status', '200 OK'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate201() : void - { - $this->set('', 'HTTP/1.0 201 Created'); - $this->set('Status', '201 Created'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate202() : void - { - $this->set('', 'HTTP/1.0 202 Accepted'); - $this->set('Status', '202 Accepted'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate204() : void - { - $this->set('', 'HTTP/1.0 204 No Content'); - $this->set('Status', '204 No Content'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate205() : void - { - $this->set('', 'HTTP/1.0 205 Reset Content'); - $this->set('Status', '205 Reset Content'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate206() : void - { - $this->set('', 'HTTP/1.0 206 Partial Content'); - $this->set('Status', '206 Partial Content'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate301() : void - { - $this->set('', 'HTTP/1.0 301 Moved Permanently'); - $this->set('Status', '301 Moved Permanently'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate302() : void - { - $this->set('', 'HTTP/1.0 302 Found'); - $this->set('Status', '302 Found'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate303() : void - { - $this->set('', 'HTTP/1.0 303 See Other'); - $this->set('Status', '303 See Other'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate304() : void - { - $this->set('', 'HTTP/1.0 304 Not Modified'); - $this->set('Status', '304 Not Modified'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate307() : void - { - $this->set('', 'HTTP/1.0 307 Temporary Redirect'); - $this->set('Status', '307 Temporary Redirect'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate308() : void - { - $this->set('', 'HTTP/1.0 308 Permanent Redirect'); - $this->set('Status', '308 Permanent Redirect'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate400() : void - { - $this->set('', 'HTTP/1.0 400 Bad Request'); - $this->set('Status', '400 Bad Request'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate401() : void - { - $this->set('', 'HTTP/1.0 401 Unauthorized'); - $this->set('Status', '401 Unauthorized'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate402() : void - { - $this->set('', 'HTTP/1.0 402 Payment Required'); - $this->set('Status', '402 Payment Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate403() : void - { - $this->set('', 'HTTP/1.0 403 Forbidden'); - $this->set('Status', '403 Forbidden'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate404() : void - { - $this->set('', 'HTTP/1.0 404 Not Found'); - $this->set('Status', '404 Not Found'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate405() : void - { - $this->set('', 'HTTP/1.0 405 Method Not Allowed'); - $this->set('Status', '405 Method Not Allowed'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate406() : void - { - $this->set('', 'HTTP/1.0 406 Not acceptable'); - $this->set('Status', '406 Not acceptable'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate407() : void - { - $this->set('', 'HTTP/1.0 407 Proxy Authentication Required'); - $this->set('Status', '407 Proxy Authentication Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate408() : void - { - $this->set('', 'HTTP/1.0 408 Request Timeout'); - $this->set('Status', '408 Request Timeout'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate409() : void - { - $this->set('', 'HTTP/1.0 409 Conflict'); - $this->set('Status', '409 Conflict'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate410() : void - { - $this->set('', 'HTTP/1.0 410 Gone'); - $this->set('Status', '410 Gone'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate411() : void - { - $this->set('', 'HTTP/1.0 411 Length Required'); - $this->set('Status', '411 Length Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate412() : void - { - $this->set('', 'HTTP/1.0 412 Precondition Failed'); - $this->set('Status', '412 Precondition Failed'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate413() : void - { - $this->set('', 'HTTP/1.0 413 Request Entity Too Large'); - $this->set('Status', '413 Request Entity Too Large'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate414() : void - { - $this->set('', 'HTTP/1.0 414 Request-URI Too Long'); - $this->set('Status', '414 Request-URI Too Long'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate415() : void - { - $this->set('', 'HTTP/1.0 415 Unsupported Media Type'); - $this->set('Status', '415 Unsupported Media Type'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate416() : void - { - $this->set('', 'HTTP/1.0 416 Requested Range Not Satisfiable'); - $this->set('Status', '416 Requested Range Not Satisfiable'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate417() : void - { - $this->set('', 'HTTP/1.0 417 Expectation Failed'); - $this->set('Status', '417 Expectation Failed'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate421() : void - { - $this->set('', 'HTTP/1.0 421 Misdirected Request'); - $this->set('Status', '421 Misdirected Request'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate422() : void - { - $this->set('', 'HTTP/1.0 422 Unprocessable Entity'); - $this->set('Status', '422 Unprocessable Entity'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate423() : void - { - $this->set('', 'HTTP/1.0 423 Locked'); - $this->set('Status', '423 Locked'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate424() : void - { - $this->set('', 'HTTP/1.0 424 Failed Dependency'); - $this->set('Status', '424 Failed Dependency'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate425() : void - { - $this->set('', 'HTTP/1.0 425 Too Early'); - $this->set('Status', '425 Too Early'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate426() : void - { - $this->set('', 'HTTP/1.0 426 Upgrade Required'); - $this->set('Status', '426 Upgrade Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate428() : void - { - $this->set('', 'HTTP/1.0 428 Precondition Required'); - $this->set('Status', '428 Precondition Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate429() : void - { - $this->set('', 'HTTP/1.0 429 Too Many Requests'); - $this->set('Status', '429 Too Many Requests'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate431() : void - { - $this->set('', 'HTTP/1.0 431 Request Header Fields Too Large'); - $this->set('Status', '431 Request Header Fields Too Large'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate451() : void - { - $this->set('', 'HTTP/1.0 451 Unavailable For Legal Reasons'); - $this->set('Status', '451 Unavailable For Legal Reasons'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate500() : void - { - $this->set('', 'HTTP/1.0 500 Internal Server Error'); - $this->set('Status', '500 Internal Server Error'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate501() : void - { - $this->set('', 'HTTP/1.0 501 Not Implemented'); - $this->set('Status', '501 Not Implemented'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate502() : void - { - $this->set('', 'HTTP/1.0 502 Bad Gateway'); - $this->set('Status', '502 Bad Gateway'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate503() : void - { - $this->set('', 'HTTP/1.0 503 Service Temporarily Unavailable'); - $this->set('Status', '503 Service Temporarily Unavailable'); - $this->set('Retry-After', 'Retry-After: 300'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate504() : void - { - $this->set('', 'HTTP/1.0 504 Gateway Timeout'); - $this->set('Status', '504 Gateway Timeout'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate507() : void - { - $this->set('', 'HTTP/1.0 507 Insufficient Storage'); - $this->set('Status', '507 Insufficient Storage'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate508() : void - { - $this->set('', 'HTTP/1.0 508 Loop Detected'); - $this->set('Status', '508 Loop Detected'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate511() : void - { - $this->set('', 'HTTP/1.0 511 Network Authentication Required'); - $this->set('Status', '511 Network Authentication Required'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate598() : void - { - $this->set('', 'HTTP/1.0 598 Network read timeout error'); - $this->set('Status', '598 Network read timeout error'); - } - - /** - * Generate predefined header. - * - * @return void - * - * @since 1.0.0 - */ - private function generate599() : void - { - $this->set('', 'HTTP/1.0 599 Network connect timeout error'); - $this->set('Status', '599 Network connect timeout error'); - } } diff --git a/Model/Message/Notify.php b/Model/Message/Notify.php index 96dfa6f70..1e89ca3b6 100755 --- a/Model/Message/Notify.php +++ b/Model/Message/Notify.php @@ -15,6 +15,7 @@ declare(strict_types=1); namespace phpOMS\Model\Message; use phpOMS\Contract\SerializableInterface; +use phpOMS\Message\NotificationLevel; /** * Notify class. @@ -72,7 +73,7 @@ final class Notify implements \JsonSerializable, SerializableInterface * @var string * @since 1.0.0 */ - public string $level = NotifyType::INFO; + public string $level = NotificationLevel::INFO; /** * Constructor. @@ -82,7 +83,7 @@ final class Notify implements \JsonSerializable, SerializableInterface * * @since 1.0.0 */ - public function __construct(string $msg = '', string $level = NotifyType::INFO) + public function __construct(string $msg = '', string $level = NotificationLevel::INFO) { $this->message = $msg; $this->level = $level; diff --git a/Security/EncryptionHelper.php b/Security/EncryptionHelper.php index 75bfaff5f..ccf033c84 100755 --- a/Security/EncryptionHelper.php +++ b/Security/EncryptionHelper.php @@ -70,8 +70,8 @@ final class EncryptionHelper public static function encryptFile(string $in, string $out, string $keyHex) : bool { - $fpSource = \fopen($in, 'r+'); - $fpEncoded = \fopen($out . '.tmp', 'w'); + $fpSource = \fopen($in, 'rb'); + $fpEncoded = \fopen($out . '.tmp', 'wb'); if ($fpSource === false || $fpEncoded === false) { return false; @@ -80,10 +80,13 @@ final class EncryptionHelper $secretKey = \sodium_hex2bin($keyHex); $nonce = \random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); - while (($buffer = \fgets($fpSource, 4096)) !== false) { - $ciphertext = \sodium_crypto_secretbox($buffer, $nonce, $keyHex); + \fwrite($fpEncoded, $nonce); - \fwrite($fpEncoded, $ciphertext); + while (!\feof($fpSource)) { + $buffer = \fread($fpSource, 4096); + $ciphertext = \sodium_crypto_secretbox($buffer, $nonce, $secretKey); + + fwrite($fpEncoded, $ciphertext); } \fclose($fpSource); @@ -144,22 +147,26 @@ final class EncryptionHelper public static function decryptFile(string $in, string $out, string $keyHex) : bool { - $fpSource = \fopen($in, 'r+'); - $fpDecoded = \fopen($out . '.tmp', 'w'); + $fpSource = \fopen($in, 'rb'); + $fpDecoded = \fopen($out . '.tmp', 'wb'); if ($fpSource === false || $fpDecoded === false) { return false; } $secretKey = \sodium_hex2bin($keyHex); + $nonce = \fread($fpSource, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); - while (($buffer = \fgets($fpSource, 4096)) !== false) { - $ciphertext = \sodium_base642bin($buffer, SODIUM_BASE64_VARIANT_ORIGINAL); - $nonce = \mb_substr($ciphertext, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); - $ciphertext = \mb_substr($ciphertext, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); + while (!\feof($fpSource)) { + $buffer = \fread($fpSource, 4096); + $ciphertext = \mb_substr($buffer, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); $plaintext = \sodium_crypto_secretbox_open($ciphertext, $nonce, $secretKey); + if ($plaintext === false) { + return false; + } + \fwrite($fpDecoded, $plaintext); } diff --git a/Stdlib/Graph/Graph.php b/Stdlib/Graph/Graph.php index b87c13b8c..be37c22c1 100755 --- a/Stdlib/Graph/Graph.php +++ b/Stdlib/Graph/Graph.php @@ -38,7 +38,7 @@ class Graph * @var bool * @since 1.0.0 */ - protected bool $isDirected = false; + public bool $isDirected = false; /** * Set node to graph. @@ -628,6 +628,9 @@ class Graph foreach ($this->nodes as $node) { $visited[$node->getId()] = false; + } + + foreach ($this->nodes as $node) { $this->longestPathDfs($node, $visited, $path, $longestPath); } @@ -875,21 +878,18 @@ class Graph */ public function getDiameter() : int { - $diameter = 0; + $paths = $this->getFloydWarshallShortestPath(); + $count = []; - foreach ($this->nodes as $node1) { - foreach ($this->nodes as $node2) { - if ($node1 === $node2) { - continue; - } - - /** @var int $diameter */ - $diameter = \max($diameter, $this->getFloydWarshallShortestPath()); - } + if (empty($paths)) { + return 0; } - /** @var int $diameter */ - return $diameter; + foreach ($paths as $path) { + $count[] = \count($path); + } + + return \max($count); } /** @@ -994,7 +994,7 @@ class Graph : $edge->node1; } - if ($next->isEqual($previous)) { + if ($previous !== null && $next->isEqual($previous)) { continue; } @@ -1197,20 +1197,13 @@ class Graph * * @since 1.0.0 */ - public function isBipartite(int | string | Node $node1) : bool + public function isBipartite() : bool { - if (!($node1 instanceof Node)) { - $node1 = $this->getNode($node1); - } - - if ($node1 === null) { - return true; - } - foreach ($this->nodes as $node) { $colors[$node->getId()] = 0; } + $node1 = \reset($this->nodes); $colors[$node1->getId()] = 1; $stack = []; diff --git a/Utils/Barcode/TwoDAbstract.php b/Utils/Barcode/TwoDAbstract.php index fcee72db7..f857dc50b 100755 --- a/Utils/Barcode/TwoDAbstract.php +++ b/Utils/Barcode/TwoDAbstract.php @@ -115,10 +115,10 @@ abstract class TwoDAbstract extends CodeAbstract $matrixDimension = \max(\count($codeArray), \count(\reset($codeArray))); $imageDimension = \max($this->dimension['width'], $this->dimension['width']); - $multiplier = (int) ($imageDimension - 2 * $this->margin) / $matrixDimension; + $multiplier = (int) (($imageDimension - 2 * $this->margin) / $matrixDimension); - $dimensions['width'] = $matrixDimension * $multiplier + 2 * $this->margin; - $dimensions['height'] = $matrixDimension * $multiplier + 2 * $this->margin; + $dimensions['width'] = (int) ($matrixDimension * $multiplier + 2 * $this->margin); + $dimensions['height'] = (int) ($matrixDimension * $multiplier + 2 * $this->margin); return $dimensions; } diff --git a/Utils/Converter/Currency.php b/Utils/Converter/Currency.php index 2567238ea..55984b164 100755 --- a/Utils/Converter/Currency.php +++ b/Utils/Converter/Currency.php @@ -80,7 +80,7 @@ final class Currency $to = \strtoupper($to); if (!isset($currencies[$to])) { - throw new \InvalidArgumentException('Currency doesn\'t exists'); + return -1.0; } return $value * $currencies[$to]; @@ -147,7 +147,7 @@ final class Currency $from = \strtoupper($from); if (!isset($currencies[$from])) { - throw new \InvalidArgumentException('Currency doesn\'t exists'); + return -1.0; } return $value / $currencies[$from]; @@ -172,8 +172,10 @@ final class Currency $from = \strtoupper($from); $to = \strtoupper($to); - if ((!isset($currencies[$from]) && $from !== ISO4217CharEnum::_EUR) || (!isset($currencies[$to]) && $to !== ISO4217CharEnum::_EUR)) { - throw new \InvalidArgumentException('Currency doesn\'t exists'); + if ((!isset($currencies[$from]) && $from !== ISO4217CharEnum::_EUR) + || (!isset($currencies[$to]) && $to !== ISO4217CharEnum::_EUR) + ) { + return -1.0; } if ($from !== ISO4217CharEnum::_EUR) { diff --git a/Utils/Git/Commit.php b/Utils/Git/Commit.php index 235cc8e79..6ccba4680 100755 --- a/Utils/Git/Commit.php +++ b/Utils/Git/Commit.php @@ -30,7 +30,7 @@ class Commit * @var string * @since 1.0.0 */ - private string $id = ''; + public string $id = ''; /** * Author. diff --git a/Utils/ImageUtils.php b/Utils/ImageUtils.php index 1e68af7d8..362a7ef54 100755 --- a/Utils/ImageUtils.php +++ b/Utils/ImageUtils.php @@ -119,9 +119,7 @@ final class ImageUtils /** @var array $imageDim */ $imageDim = \getimagesize($srcPath); - if ((($imageDim[0] ?? -1) >= $width && ($imageDim[1] ?? -1) >= $height) - || ($imageDim[0] === 0 || $imageDim[1] === 0) - ) { + if ($imageDim[0] === 0 || $imageDim[1] === 0) { return; } @@ -155,6 +153,13 @@ final class ImageUtils throw new \InvalidArgumentException(); } + if (\stripos($srcPath, '.png')) { + \imagealphablending($dst, false); + $transparent = \imagecolorallocatealpha($dst, 0, 0, 0, 127); + \imagefill($dst, 0, 0, $transparent); + \imagesavealpha($dst, true); + } + \imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $imageDim[0], $imageDim[1]); if (\stripos($srcPath, '.jpg') || \stripos($srcPath, '.jpeg')) { @@ -211,7 +216,7 @@ final class ImageUtils $newDim = [\max($imageDim1[0], $imageDim2[0]), \max($imageDim1[1], $imageDim2[1])]; - $diff = empty($out) ? -1 : $out; + $diff = empty($out) ? -1 : $diff; $dst = false; $red = 0; @@ -243,10 +248,12 @@ final class ImageUtils } } + $diffArea = 5; $difference = 0; for ($i = 0; $i < $newDim[0]; ++$i) { for ($j = 0; $j < $newDim[1]; ++$j) { + // Dimension difference if ($i >= $imageDim1[0] || $j >= $imageDim1[1]) { if ($diff === 0) { /** @var \GdImage $dst */ @@ -271,6 +278,7 @@ final class ImageUtils continue; } + // Dimension difference if ($i >= $imageDim2[0] || $j >= $imageDim2[1]) { if ($diff === 0) { /** @var \GdImage $dst */ @@ -295,10 +303,14 @@ final class ImageUtils continue; } + // Get average color at current pixel position with a 10 pixel area + $color1Avg = self::getAverageColor($src1, $i, $j, $imageDim2[0], $imageDim2[1], $diffArea); + $color2Avg = self::getAverageColor($src2, $i, $j, $newDim[0], $newDim[1], $diffArea); + $color1 = \imagecolorat($src1, $i, $j); $color2 = \imagecolorat($src2, $i, $j); - if ($color1 !== $color2 && $color1 !== false && $color2 !== false) { + if (\abs($color1Avg - $color2Avg) / $color1Avg > 0.05 && $color1Avg > 0 && $color2Avg > 0) { ++$difference; if ($diff === 0) { @@ -329,4 +341,27 @@ final class ImageUtils return $difference; } + + private static function getAverageColor($src, $x, $y, $width, $height, $area = 10) : int + { + $colors = []; + + for ($i = $x - $area; $i < $x + $area; ++$i) { + for ($j = $y - $area; $j < $y + $area; ++$j) { + if ($i < 0 || $j < 0 || $i >= $width || $j >= $height) { + continue; + } + + $color = \imagecolorat($src, $i, $j); + + if ($color === false) { + continue; + } + + $colors[] = $color; + } + } + + return (int) (\array_sum($colors) / \count($colors)); + } } diff --git a/Utils/Parser/Pdf/PdfParser.php b/Utils/Parser/Pdf/PdfParser.php index 4008e9a2f..c82876938 100755 --- a/Utils/Parser/Pdf/PdfParser.php +++ b/Utils/Parser/Pdf/PdfParser.php @@ -58,7 +58,7 @@ class PdfParser $text = ''; $tmpDir = \sys_get_temp_dir(); - $out = \tempnam($tmpDir, 'pdf_'); + $out = \tempnam($tmpDir, 'oms_pdf_'); if ($out === false) { return ''; } @@ -79,7 +79,7 @@ class PdfParser } if (\strlen($text) < 256) { - $out = \tempnam($tmpDir, 'pdf_'); + $out = \tempnam($tmpDir, 'oms_pdf_'); if ($out === false) { return ''; } @@ -95,6 +95,8 @@ class PdfParser $files = \glob($out . '*'); if ($files === false) { + \unlink($out); + return $text === false ? '' : $text; } @@ -124,6 +126,8 @@ class PdfParser \unlink($file); } + + \unlink($out); } return $text; diff --git a/Utils/TaskSchedule/Cron.php b/Utils/TaskSchedule/Cron.php index b52172c4d..566c0b3ba 100755 --- a/Utils/TaskSchedule/Cron.php +++ b/Utils/TaskSchedule/Cron.php @@ -38,6 +38,8 @@ class Cron extends SchedulerAbstract } if (!empty($this->getAllByName($task->getId()))) { + \unlink($path); + return; } diff --git a/Utils/TaskSchedule/TaskAbstract.php b/Utils/TaskSchedule/TaskAbstract.php index 43f279734..9e0433eaa 100755 --- a/Utils/TaskSchedule/TaskAbstract.php +++ b/Utils/TaskSchedule/TaskAbstract.php @@ -30,7 +30,7 @@ abstract class TaskAbstract * @var string * @since 1.0.0 */ - protected string $id = ''; + public string $id = ''; /** * Command used for creating the task diff --git a/Validation/Finance/EUVat.php b/Validation/Finance/EUVat.php index 8b90a1647..32ff67a43 100644 --- a/Validation/Finance/EUVat.php +++ b/Validation/Finance/EUVat.php @@ -58,7 +58,6 @@ final class EUVat extends ValidatorAbstract 'SWE' => '/^(SE)([0-9]{10}[0-9]{2})$/i', 'SVN' => '/^(SI)([0-9]{8})$/', 'SVK' => '/^(SK)([0-9][10])$/', - 'HRV' => '/^(HR)([0-9][11])$/', ]; /** diff --git a/tests/Account/AccountTest.php b/tests/Account/AccountTest.php index e2da188b8..fd1931d62 100755 --- a/tests/Account/AccountTest.php +++ b/tests/Account/AccountTest.php @@ -222,6 +222,18 @@ final class AccountTest extends \PHPUnit\Framework\TestCase self::assertTrue($account->hasPermission(PermissionType::NONE)); } + public function testGroupPmerissionExists() : void + { + $account = new Account(); + $group = new NullGroup(2); + + $perm = new class() extends PermissionAbstract {}; + $perm->addPermission(PermissionType::CREATE); + + $group->addPermission($perm); + $account->hasPermission(PermissionType::READ); + } + /** * @testdox Account permissions can be removed * @covers phpOMS\Account\Account diff --git a/tests/Account/NullAccountTest.php b/tests/Account/NullAccountTest.php index 3746adc71..e0412f588 100755 --- a/tests/Account/NullAccountTest.php +++ b/tests/Account/NullAccountTest.php @@ -44,4 +44,10 @@ final class NullAccountTest extends \PHPUnit\Framework\TestCase $null = new NullAccount(2); self::assertEquals(2, $null->getId()); } + + public function testJsonSerialization() : void + { + $null = new NullAccount(2); + self::assertEquals(['id' => 2], $null->jsonSerialize()); + } } diff --git a/tests/Account/NullGroupTest.php b/tests/Account/NullGroupTest.php index c1b9ea38a..8f1ea6457 100755 --- a/tests/Account/NullGroupTest.php +++ b/tests/Account/NullGroupTest.php @@ -44,4 +44,10 @@ final class NullGroupTest extends \PHPUnit\Framework\TestCase $null = new NullGroup(2); self::assertEquals(2, $null->getId()); } + + public function testJsonSerialization() : void + { + $null = new NullGroup(2); + self::assertEquals(['id' => 2], $null->jsonSerialize()); + } } diff --git a/tests/Account/PermissionAbstractTest.php b/tests/Account/PermissionAbstractTest.php index bd35914b1..3f13a0c77 100755 --- a/tests/Account/PermissionAbstractTest.php +++ b/tests/Account/PermissionAbstractTest.php @@ -188,6 +188,26 @@ final class PermissionAbstractTest extends \PHPUnit\Framework\TestCase self::assertFalse($perm1->isEqual($perm2)); } + public function testFullPermissions() : void + { + $perm = new class() extends PermissionAbstract {}; + + $perm->addPermission(PermissionType::READ); + $perm->addPermission(PermissionType::CREATE); + $perm->addPermission(PermissionType::MODIFY); + $perm->addPermission(PermissionType::DELETE); + $perm->addPermission(PermissionType::PERMISSION); + + self::assertEquals( + PermissionType::READ + | PermissionType::CREATE + | PermissionType::MODIFY + | PermissionType::DELETE + | PermissionType::PERMISSION, + $perm->getPermission() + ); + } + /** * @testdox Correct permissions are validated * @covers phpOMS\Account\PermissionAbstract diff --git a/tests/Ai/Ocr/3.jpg b/tests/Ai/Ocr/3.jpg new file mode 100644 index 000000000..43412d209 Binary files /dev/null and b/tests/Ai/Ocr/3.jpg differ diff --git a/tests/Ai/Ocr/BasicOcrTest.php b/tests/Ai/Ocr/BasicOcrTest.php index 6c7dad458..ad4181d93 100755 --- a/tests/Ai/Ocr/BasicOcrTest.php +++ b/tests/Ai/Ocr/BasicOcrTest.php @@ -42,6 +42,27 @@ final class BasicOcrTest extends \PHPUnit\Framework\TestCase ); } + public function testCustomMnistFiles() : void + { + $ocr = new BasicOcr(); + $ocr->trainWith(__DIR__ . '/train-images-idx3-ubyte', __DIR__ . '/train-labels-idx1-ubyte', 1000); + + if (\is_file(__DIR__ . '/test-image-ubyte')) { + \unlink(__DIR__ . '/test-image-ubyte'); + \unlink(__DIR__ . '/test-label-ubyte'); + } + + BasicOcr::imagesToMNIST([__DIR__ . '/3.jpg'], __DIR__ . '/test-image-ubyte', 28); + BasicOcr::labelsToMNIST(['3'], __DIR__ . '/test-label-ubyte'); + + self::assertEquals(3, $ocr->matchImage(__DIR__ . '/test-image-ubyte', 3, 5)[0]['label']); + + if (\is_file(__DIR__ . '/test-image-ubyte')) { + \unlink(__DIR__ . '/test-image-ubyte'); + \unlink(__DIR__ . '/test-label-ubyte'); + } + } + /** * @covers phpOMS\Ai\Ocr\BasicOcr * @group framework diff --git a/tests/Ai/Ocr/Tesseract/TesseractOcrTest.php b/tests/Ai/Ocr/Tesseract/TesseractOcrTest.php index db6534b9b..65dccd40a 100755 --- a/tests/Ai/Ocr/Tesseract/TesseractOcrTest.php +++ b/tests/Ai/Ocr/Tesseract/TesseractOcrTest.php @@ -18,6 +18,7 @@ use phpOMS\Ai\Ocr\Tesseract\TesseractOcr; use phpOMS\Image\Kernel; use phpOMS\Image\Skew; use phpOMS\Image\Thresholding; +use phpOMS\System\File\PathException; /** * @internal @@ -67,6 +68,13 @@ final class TesseractOcrTest extends \PHPUnit\Framework\TestCase self::assertGreaterThan(0.5, $m2); } + public function testInvalidOcrPath() : void + { + $this->expectException(PathException::class); + + $ocr = new TesseractOcr('/invalid/path'); + } + /** * @covers phpOMS\Ai\Ocr\Tesseract\TesseractOcr * @group framework diff --git a/tests/Api/EUVAT/EUVATBffOnlineTest.php b/tests/Api/EUVAT/EUVATBffOnlineTest.php index 4a681942a..a4fd47552 100755 --- a/tests/Api/EUVAT/EUVATBffOnlineTest.php +++ b/tests/Api/EUVAT/EUVATBffOnlineTest.php @@ -35,4 +35,12 @@ final class EUVATBffOnlineTest extends \PHPUnit\Framework\TestCase self::assertEquals(0, $status['status']); self::assertEquals('B', $status['vat']); } + + public function testValidateQualifiedInvalidId() : void + { + $status = EUVATBffOnline::validateQualified('DE123456789', 'DE123456789', 'TestName', 'TestStreet', 'TestCity', 'TestPostcode'); + + self::assertEquals(0, $status['status']); + self::assertEquals('B', $status['vat']); + } } diff --git a/tests/Api/EUVAT/EUVATViesTest.php b/tests/Api/EUVAT/EUVATViesTest.php index 76efd5cea..d35b9df6f 100755 --- a/tests/Api/EUVAT/EUVATViesTest.php +++ b/tests/Api/EUVAT/EUVATViesTest.php @@ -35,4 +35,12 @@ final class EUVATViesTest extends \PHPUnit\Framework\TestCase self::assertEquals(0, $status['status']); self::assertEquals('B', $status['vat']); } + + public function testValidateQualifiedInvalidId() : void + { + $status = EUVATVies::validateQualified('DE123456789', 'DE123456789', 'TestName', 'TestStreet', 'TestCity', 'TestPostcode'); + + self::assertEquals(0, $status['status']); + self::assertEquals('B', $status['vat']); + } } diff --git a/tests/Business/Finance/ForensicsTest.php b/tests/Business/Finance/ForensicsTest.php new file mode 100644 index 000000000..86e86c34b --- /dev/null +++ b/tests/Business/Finance/ForensicsTest.php @@ -0,0 +1,62 @@ +string, \end($found)->string); } + public function testFind2() : void + { + $model1 = clone $this->model; + $model2 = clone $this->model; + $model3 = clone $this->model; + + $model1->string = 'abc'; + $model2->string = 'abcdef'; + $model3->string = 'zyx'; + + BaseModelMapper::create()->execute($model1); + BaseModelMapper::create()->execute($model2); + BaseModelMapper::create()->execute($model3); + + $list = BaseModelMapper::find( + search: 'abc', + mapper: BaseModelMapper::getAll(), + searchFields: ['string'] + ); + + self::assertEquals(2, \count($list)); + } + /** * @covers phpOMS\DataStorage\Database\Mapper\DataMapperAbstract * @covers phpOMS\DataStorage\Database\Mapper\DataMapperFactory diff --git a/tests/DataStorage/Database/Query/BuilderTest.php b/tests/DataStorage/Database/Query/BuilderTest.php index fa22d4797..ce6d69347 100755 --- a/tests/DataStorage/Database/Query/BuilderTest.php +++ b/tests/DataStorage/Database/Query/BuilderTest.php @@ -117,8 +117,12 @@ final class BuilderTest extends \PHPUnit\Framework\TestCase { $con = new MysqlConnection($GLOBALS['CONFIG']['db']['core']['masters']['admin']); + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + $query = new Builder($con); - $sql = 'SELECT `a`.`test` FROM `a` as b WHERE `a`.`test` = 1 ORDER BY \rand() LIMIT 1;'; + $sql = 'SELECT [a].[test] FROM [a] as b WHERE [a].[test] = 1 ORDER BY \rand() LIMIT 1;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->random('a.test')->fromAs('a', 'b')->where('a.test', '=', 1)->toSql()); } @@ -126,8 +130,12 @@ final class BuilderTest extends \PHPUnit\Framework\TestCase { $con = new PostgresConnection($GLOBALS['CONFIG']['db']['core']['postgresql']['admin']); + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + $query = new Builder($con); - $sql = 'SELECT "a"."test" FROM "a" as b ORDER BY RANDOM() LIMIT 1;'; + $sql = 'SELECT [a].[test] FROM [a] as b ORDER BY RANDOM() LIMIT 1;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->random('a.test')->fromAs('a', 'b')->where('a.test', '=', 1)->toSql()); } @@ -135,8 +143,12 @@ final class BuilderTest extends \PHPUnit\Framework\TestCase { $con = new SQLiteConnection($GLOBALS['CONFIG']['db']['core']['sqlite']['admin']); + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + $query = new Builder($con); - $sql = 'SELECT `a`.`test` FROM `a` as b ORDER BY RANDOM() LIMIT 1;'; + $sql = 'SELECT [a].[test] FROM [a] as b ORDER BY RANDOM() LIMIT 1;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->random('a.test')->fromAs('a', 'b')->where('a.test', '=', 1)->toSql()); } @@ -144,8 +156,12 @@ final class BuilderTest extends \PHPUnit\Framework\TestCase { $con = new SqlServerConnection($GLOBALS['CONFIG']['db']['core']['mssql']['admin']); + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + $query = new Builder($con); $sql = 'SELECT TOP 1 [a].[test] FROM [a] as b ORDER BY IDX FETCH FIRST 1 ROWS ONLY;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->random('a.test')->fromAs('a', 'b')->where('a.test', '=', 1)->toSql()); } diff --git a/tests/DataStorage/Database/Schema/BuilderTest.php b/tests/DataStorage/Database/Schema/BuilderTest.php index e029776a1..169330f6b 100755 --- a/tests/DataStorage/Database/Schema/BuilderTest.php +++ b/tests/DataStorage/Database/Schema/BuilderTest.php @@ -15,6 +15,9 @@ declare(strict_types=1); namespace phpOMS\tests\DataStorage\Database\Schema; use phpOMS\DataStorage\Database\Connection\MysqlConnection; +use phpOMS\DataStorage\Database\Connection\PostgresConnection; +use phpOMS\DataStorage\Database\Connection\SQLiteConnection; +use phpOMS\DataStorage\Database\Connection\SqlServerConnection; use phpOMS\DataStorage\Database\Schema\Builder; /** @@ -24,68 +27,130 @@ use phpOMS\DataStorage\Database\Schema\Builder; */ final class BuilderTest extends \PHPUnit\Framework\TestCase { - protected MysqlConnection $con; - - /** - * {@inheritdoc} - */ - protected function setUp() : void + public function dbConnectionProvider() : array { - $this->con = new MysqlConnection($GLOBALS['CONFIG']['db']['core']['masters']['admin']); + $cons = [ + [new MysqlConnection($GLOBALS['CONFIG']['db']['core']['masters']['admin'])], + [new PostgresConnection($GLOBALS['CONFIG']['db']['core']['postgresql']['admin'])], + [new SQLiteConnection($GLOBALS['CONFIG']['db']['core']['sqlite']['admin'])], + [new SqlServerConnection($GLOBALS['CONFIG']['db']['core']['mssql']['admin'])], + ]; + + $cons[0][0]->connect(); + $cons[1][0]->connect(); + $cons[2][0]->connect(); + $cons[3][0]->connect(); + + return $cons; } /** * @testdox Mysql database drop forms a valid query * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlDrop() : void + public function testMysqlDrop($con) : void { - $query = new Builder($this->con); - $sql = 'DROP DATABASE `test`;'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'DROP DATABASE [test];'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->dropDatabase('test')->toSql()); } /** * @testdox Mysql table drop forms a valid query * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlDropTable() : void + public function testMysqlDropTable($con) : void { - $query = new Builder($this->con); - $sql = 'DROP TABLE `test`;'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'DROP TABLE [test];'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->dropTable('test')->toSql()); } /** * @testdox Mysql show tables form a valid query * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlShowTables() : void + public function testMysqlShowTables($con) : void { - $query = new Builder($this->con); - $sql = 'SELECT `table_name` FROM `information_schema`.`tables` WHERE `table_schema` = \'' . $GLOBALS['CONFIG']['db']['core']['masters']['admin']['database']. '\';'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'SELECT [table_name] FROM [information_schema].[tables] WHERE [table_schema] = \'' . $GLOBALS['CONFIG']['db']['core']['masters']['admin']['database']. '\';'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->selectTables()->toSql()); } /** * @testdox Mysql show fields form a valid query * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlShowFields() : void + public function testMysqlShowFields($con) : void { - $query = new Builder($this->con); - $sql = 'SELECT * FROM `information_schema`.`columns` WHERE `table_schema` = \'' . $GLOBALS['CONFIG']['db']['core']['masters']['admin']['database']. '\' AND `table_name` = \'test\';'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'SELECT * FROM [information_schema].[columns] WHERE [table_schema] = \'' . $GLOBALS['CONFIG']['db']['core']['masters']['admin']['database']. '\' AND table_name = \'test\';'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals($sql, $query->selectFields('test')->toSql()); } /** * @testdox Mysql create tables form a valid query * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlCreateTable() : void + public function testMysqlCreateTable($con) : void { - $query = new Builder($this->con); - $sql = 'CREATE TABLE IF NOT EXISTS `user_roles` (`user_id` INT AUTO_INCREMENT, `role_id` VARCHAR(10) DEFAULT \'1\' NULL, PRIMARY KEY (`user_id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`ext1_id`), FOREIGN KEY (`role_id`) REFERENCES `roles` (`ext2_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'CREATE TABLE IF NOT EXISTS [user_roles] (user_id INT AUTO_INCREMENT, role_id VARCHAR(10) DEFAULT \'1\' NULL, PRIMARY KEY (user_id), FOREIGN KEY (user_id) REFERENCES users (ext1_id), FOREIGN KEY (role_id) REFERENCES roles (ext2_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals( $sql, $query->createTable('user_roles') @@ -95,28 +160,51 @@ final class BuilderTest extends \PHPUnit\Framework\TestCase ); } - public function testMysqlAlter() : void - {/* - $query = new Builder($this->con); - $sql = 'CREATE TABLE IF NOT EXISTS `user_roles` (`user_id` INT NOT NULL AUTO_INCREMENT, `role_id` VARCHAR(10) DEFAULT \'1\' NULL, PRIMARY KEY (`user_id`), FOREIGN KEY (`user_id`) REFERENCES `users` (`ext1_id`), FOREIGN KEY (`role_id`) REFERENCES `roles` (`ext2_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;'; + /* + public function testMysqlAlter($con) : void + { + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'CREATE TABLE IF NOT EXISTS user_roles (user_id INT NOT NULL AUTO_INCREMENT, role_id VARCHAR(10) DEFAULT \'1\' NULL, PRIMARY KEY (user_id), FOREIGN KEY (user_id) REFERENCES users (ext1_id), FOREIGN KEY (role_id) REFERENCES roles (ext2_id)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1;'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals( $sql, $query->createTable('user_roles') ->field('user_id', 'INT', null, false, true, false, true, 'users', 'ext1_id') ->field('role_id', 'VARCHAR(10)', '1', true, false, false, false, 'roles', 'ext2_id') ->toSql() - );*/ + ); } + */ /** * @testdox The grammar correctly deletes a table * @covers phpOMS\DataStorage\Database\Schema\Grammar\MysqlGrammar * @group framework + * @dataProvider dbConnectionProvider */ - public function testMysqlCreateFromSchema() : void + public function testMysqlCreateFromSchema($con) : void { - $query = new Builder($this->con); - $sql = 'DROP TABLE `test`, `test_foreign`;'; + if (!$con->isInitialized()) { + self::markTestSkipped(); + + return; + } + + $iS = $con->getGrammar()->systemIdentifierStart; + $iE = $con->getGrammar()->systemIdentifierEnd; + + $query = new Builder($con); + $sql = 'DROP TABLE [test], [test_foreign];'; + $sql = \str_replace(['[', ']'], [$iS, $iE], $sql); self::assertEquals( $sql, diff --git a/tests/Image/KernelTest.php b/tests/Image/KernelTest.php index fe137285b..ec145ad5e 100755 --- a/tests/Image/KernelTest.php +++ b/tests/Image/KernelTest.php @@ -27,6 +27,7 @@ final class KernelTest extends \PHPUnit\Framework\TestCase /** * @testdox The kernel can be applied to an image which is then stored in a new file * @group framework + * @group slow * @covers phpOMS\Image\Kernel */ public function testKernel() : void @@ -34,9 +35,11 @@ final class KernelTest extends \PHPUnit\Framework\TestCase Kernel::convolve(__DIR__ . '/img1.png', __DIR__ . '/test_img1_sharpen.png', Kernel::KERNEL_SHARPEN); Kernel::convolve(__DIR__ . '/img1.png', __DIR__ . '/test_img1_blur.png', Kernel::KERNEL_GAUSSUAN_BLUR_3); Kernel::convolve(__DIR__ . '/img1.png', __DIR__ . '/test_img1_emboss.png', Kernel::KERNEL_EMBOSS); + Kernel::convolve(__DIR__ . '/img1.png', __DIR__ . '/test_img1_unsharpen.png', Kernel::KERNEL_UNSHARP_MASKING); self::assertTrue(\is_file(__DIR__ . '/test_img1_sharpen.png')); self::assertTrue(\is_file(__DIR__ . '/test_img1_blur.png')); self::assertTrue(\is_file(__DIR__ . '/test_img1_emboss.png')); + self::assertTrue(\is_file(__DIR__ . '/test_img1_unsharpen.png')); } } diff --git a/tests/Image/SkewTest.php b/tests/Image/SkewTest.php index 4783d6601..ed06ac051 100755 --- a/tests/Image/SkewTest.php +++ b/tests/Image/SkewTest.php @@ -27,21 +27,19 @@ final class SkewTest extends \PHPUnit\Framework\TestCase /** * @testdox A image can be automatically unskewed * @group framework + * @group slow * @covers phpOMS\Image\Skew */ public function testSkew() : void { - /* Disabled because of very slow performance (244 seconds) */ - self::markTestSkipped(); - Skew::autoRotate( - __DIR__ . '/binary_tilted.png', - __DIR__ . '/test_binary_untilted.png', + __DIR__ . '/tilted.jpg', + __DIR__ . '/test_binary_untilted.jpg', 10, [150, 75], [1700, 900] ); - self::assertTrue(\is_file(__DIR__ . '/test_binary_untilted.png')); + self::assertTrue(\is_file(__DIR__ . '/test_binary_untilted.jpg')); } } diff --git a/tests/Image/test_binary_untilted.jpg b/tests/Image/test_binary_untilted.jpg new file mode 100644 index 000000000..fb70e8ed1 Binary files /dev/null and b/tests/Image/test_binary_untilted.jpg differ diff --git a/tests/Image/test_img1_unsharpen.png b/tests/Image/test_img1_unsharpen.png new file mode 100644 index 000000000..468cf877b Binary files /dev/null and b/tests/Image/test_img1_unsharpen.png differ diff --git a/tests/Image/tilted.jpg b/tests/Image/tilted.jpg new file mode 100644 index 000000000..d8c573695 Binary files /dev/null and b/tests/Image/tilted.jpg differ diff --git a/tests/Localization/Defaults/CountryTest.php b/tests/Localization/Defaults/CountryTest.php index bc0200949..aa775b980 100755 --- a/tests/Localization/Defaults/CountryTest.php +++ b/tests/Localization/Defaults/CountryTest.php @@ -39,7 +39,6 @@ final class CountryTest extends \PHPUnit\Framework\TestCase self::assertEquals('', $obj->getCode3()); self::assertEquals(0, $obj->getNumeric()); self::assertEquals('', $obj->getSubdevision()); - self::assertEquals('', $obj->getRegion()); self::assertFalse($obj->isDeveloped()); } } diff --git a/tests/Localization/ISO3166CharEnumTest.php b/tests/Localization/ISO3166CharEnumTest.php index 9511779c9..d7ab4ed58 100755 --- a/tests/Localization/ISO3166CharEnumTest.php +++ b/tests/Localization/ISO3166CharEnumTest.php @@ -54,4 +54,20 @@ final class ISO3166CharEnumTest extends \PHPUnit\Framework\TestCase { self::assertEquals(ISO3166CharEnum::getConstants(), \array_unique(ISO3166CharEnum::getConstants())); } + + public function testRegion() : void + { + $regions = [ + 'europe', 'asia', 'america', 'oceania', 'africa', 'eu', 'euro', + 'north-europe', 'south-europe', 'east-europe', 'west-europe', + 'middle-east', 'south-america', 'north-america', 'central-asia', + 'south-asia', 'southeast-asia', 'east-asia', 'west-asia', + 'central-africa', 'east-africa', 'north-africa', 'south-africa', + 'west-africe', 'australia', 'polynesia', 'melanesia', 'antarctica', + ]; + + foreach ($regions as $region) { + self::assertGreaterThan(0, \count(ISO3166CharEnum::getRegion($region))); + } + } } diff --git a/tests/Localization/ISO3166NameEnumTest.php b/tests/Localization/ISO3166NameEnumTest.php index 8f9c8e03f..071bbce5f 100755 --- a/tests/Localization/ISO3166NameEnumTest.php +++ b/tests/Localization/ISO3166NameEnumTest.php @@ -34,4 +34,20 @@ final class ISO3166NameEnumTest extends \PHPUnit\Framework\TestCase $enum = ISO3166NameEnum::getConstants(); self::assertEquals(\count($enum), \count(\array_unique($enum))); } + + public function testRegion() : void + { + $regions = [ + 'europe', 'asia', 'america', 'oceania', 'africa', 'eu', 'euro', + 'north-europe', 'south-europe', 'east-europe', 'west-europe', + 'middle-east', 'south-america', 'north-america', 'central-asia', + 'south-asia', 'southeast-asia', 'east-asia', 'west-asia', + 'central-africa', 'east-africa', 'north-africa', 'south-africa', + 'west-africe', 'australia', 'polynesia', 'melanesia', 'antarctica', + ]; + + foreach ($regions as $region) { + self::assertGreaterThan(0, \count(ISO3166NameEnum::getRegion($region))); + } + } } diff --git a/tests/Localization/ISO3166NumEnumTest.php b/tests/Localization/ISO3166NumEnumTest.php index bd48ca253..732a579b2 100755 --- a/tests/Localization/ISO3166NumEnumTest.php +++ b/tests/Localization/ISO3166NumEnumTest.php @@ -44,4 +44,20 @@ final class ISO3166NumEnumTest extends \PHPUnit\Framework\TestCase self::assertTrue($ok); } + + public function testRegion() : void + { + $regions = [ + 'europe', 'asia', 'america', 'oceania', 'africa', 'eu', 'euro', + 'north-europe', 'south-europe', 'east-europe', 'west-europe', + 'middle-east', 'south-america', 'north-america', 'central-asia', + 'south-asia', 'southeast-asia', 'east-asia', 'west-asia', + 'central-africa', 'east-africa', 'north-africa', 'south-africa', + 'west-africe', 'australia', 'polynesia', 'melanesia', 'antarctica', + ]; + + foreach ($regions as $region) { + self::assertGreaterThan(0, \count(ISO3166NumEnum::getRegion($region))); + } + } } diff --git a/tests/Localization/ISO3166TwoEnumTest.php b/tests/Localization/ISO3166TwoEnumTest.php index 0683cd181..c580a3685 100755 --- a/tests/Localization/ISO3166TwoEnumTest.php +++ b/tests/Localization/ISO3166TwoEnumTest.php @@ -54,4 +54,20 @@ final class ISO3166TwoEnumTest extends \PHPUnit\Framework\TestCase { self::assertEquals(ISO3166TwoEnum::getConstants(), \array_unique(ISO3166TwoEnum::getConstants())); } + + public function testRegion() : void + { + $regions = [ + 'europe', 'asia', 'america', 'oceania', 'africa', 'eu', 'euro', + 'north-europe', 'south-europe', 'east-europe', 'west-europe', + 'middle-east', 'south-america', 'north-america', 'central-asia', + 'south-asia', 'southeast-asia', 'east-asia', 'west-asia', + 'central-africa', 'east-africa', 'north-africa', 'south-africa', + 'west-africe', 'australia', 'polynesia', 'melanesia', 'antarctica', + ]; + + foreach ($regions as $region) { + self::assertGreaterThan(0, \count(ISO3166TwoEnum::getRegion($region))); + } + } } diff --git a/tests/Localization/ISO639EnumTest.php b/tests/Localization/ISO639EnumTest.php index 638123965..7948f1f57 100755 --- a/tests/Localization/ISO639EnumTest.php +++ b/tests/Localization/ISO639EnumTest.php @@ -16,6 +16,7 @@ namespace phpOMS\tests\Localization; require_once __DIR__ . '/../Autoloader.php'; +use phpOMS\Localization\ISO3166TwoEnum; use phpOMS\Localization\ISO639Enum; /** @@ -34,4 +35,13 @@ final class ISO639EnumTest extends \PHPUnit\Framework\TestCase $enum = ISO639Enum::getConstants(); self::assertEquals(\count($enum), \count(\array_unique($enum))); } + + public function testLanguage() : void + { + $enum = ISO3166TwoEnum::getConstants(); + + foreach ($enum as $code) { + self::assertGreaterThan(0, \count(ISO639Enum::languageFromCountry($code)), 'Failed for code: ' . $code); + } + } } diff --git a/tests/Localization/ISO639x1EnumTest.php b/tests/Localization/ISO639x1EnumTest.php index 8e13fcd24..bcabb5f21 100755 --- a/tests/Localization/ISO639x1EnumTest.php +++ b/tests/Localization/ISO639x1EnumTest.php @@ -16,6 +16,7 @@ namespace phpOMS\tests\Localization; require_once __DIR__ . '/../Autoloader.php'; +use phpOMS\Localization\ISO3166TwoEnum; use phpOMS\Localization\ISO639x1Enum; /** @@ -54,4 +55,13 @@ final class ISO639x1EnumTest extends \PHPUnit\Framework\TestCase { self::assertEquals(ISO639x1Enum::getConstants(), \array_unique(ISO639x1Enum::getConstants())); } + + public function testLanguage() : void + { + $enum = ISO3166TwoEnum::getConstants(); + + foreach ($enum as $code) { + self::assertGreaterThan(0, \count(ISO639x1Enum::languageFromCountry($code)), 'Failed for code: ' . $code); + } + } } diff --git a/tests/Localization/ISO639x2EnumTest.php b/tests/Localization/ISO639x2EnumTest.php index 61acab688..758bc8705 100755 --- a/tests/Localization/ISO639x2EnumTest.php +++ b/tests/Localization/ISO639x2EnumTest.php @@ -16,6 +16,7 @@ namespace phpOMS\tests\Localization; require_once __DIR__ . '/../Autoloader.php'; +use phpOMS\Localization\ISO3166TwoEnum; use phpOMS\Localization\ISO639x2Enum; /** @@ -54,4 +55,13 @@ final class ISO639x2EnumTest extends \PHPUnit\Framework\TestCase { self::assertEquals(ISO639x2Enum::getConstants(), \array_unique(ISO639x2Enum::getConstants())); } + + public function testLanguage() : void + { + $enum = ISO3166TwoEnum::getConstants(); + + foreach ($enum as $code) { + self::assertGreaterThan(0, \count(ISO639x2Enum::languageFromCountry($code)), 'Failed for code: ' . $code); + } + } } diff --git a/tests/Localization/LanguageDetection/LanguageTest.php b/tests/Localization/LanguageDetection/LanguageTest.php new file mode 100644 index 000000000..6db2a4676 --- /dev/null +++ b/tests/Localization/LanguageDetection/LanguageTest.php @@ -0,0 +1,44 @@ +detect($content)->bestResults()->close(); + + self::assertEquals($language, \array_keys($detected)[0] ?? ''); + } + } +} diff --git a/tests/Localization/LanguageDetection/languages/de.txt b/tests/Localization/LanguageDetection/languages/de.txt new file mode 100644 index 000000000..ce1b9b646 --- /dev/null +++ b/tests/Localization/LanguageDetection/languages/de.txt @@ -0,0 +1 @@ +Im Anfang schuf Gott den Himmel und die Erde.Und die Erde war wüst und leer, und es lag Finsternis auf der Tiefe, und der Geist Gottes schwebte über den Wassern.Und Gott sprach: Es werde Licht! Und es ward Licht.Und Gott sah, daß das Licht gut war; da schied Gott das Licht von der Finsternis;und Gott nannte das Licht Tag, und die Finsternis Nacht. Und es ward Abend, und es ward Morgen: der erste Tag.Und Gott sprach: Es soll eine Feste entstehen inmitten der Wasser, die bilde eine Scheidewand zwischen den Gewässern!Und Gott machte die Feste und schied das Wasser unter der Feste von dem Wasser über der Feste, daß es so ward.Und Gott nannte die Feste Himmel. Und es ward Abend, und es ward Morgen: der zweite Tag.Und Gott sprach: Es sammle sich das Wasser unter dem Himmel an einen Ort, daß man das Trockene sehe! Und es geschah also.Und Gott nannte das Trockene Land; aber die Sammlung der Wasser nannte er Meer. Und Gott sah, daß es gut war.Und Gott sprach: Es lasse die Erde grünes Gras sprossen und Gewächs, das Samen trägt, fruchtbare Bäume, deren jeder seine besondere Art Früchte bringt, in welcher ihr Same sei auf Erden! Und es geschah also.Und die Erde brachte hervor Gras und Gewächs, das Samen trägt nach seiner Art, und Bäume, welche Früchte bringen, in welchen ihr Same ist nach ihrer Art. Und Gott sah, daß es gut war.Und es ward Abend, und es ward Morgen: der dritte Tag.Und Gott sprach: Es seien Lichter an der Himmelsfeste, zur Unterscheidung von Tag und Nacht, die sollen zur Bestimmung der Zeiten und der Tage und Jahre dienen,und zu Leuchtern an der Himmelsfeste, daß sie die Erde beleuchten! Und es geschah also.Und Gott machte die zwei großen Lichter, das große Licht zur Beherrschung des Tages und das kleinere Licht zur Beherrschung der Nacht; dazu die Sterne.Und Gott setzte sie an die Himmelsfeste, damit sie die Erde beleuchtetenund den Tag und die Nacht beherrschten und Licht und Finsternis unterschieden. Und Gott sah, daß es gut war.Und es ward Abend, und es ward Morgen: der vierte Tag.Und Gott sprach: Das Wasser soll wimmeln von einer Fülle lebendiger Wesen, und es sollen Vögel fliegen über die Erde, an der Himmelsfeste dahin!Und Gott schuf die großen Fische und alles, was da lebt und webt, wovon das Wasser wimmelt, nach ihren Gattungen, dazu allerlei Vögel nach ihren Gattungen. Und Gott sah, daß es gut war.Und Gott segnete sie und sprach: Seid fruchtbar und mehret euch und füllet das Wasser im Meere, und das Geflügel mehre sich auf Erden!Und es ward Abend, und es ward Morgen: der fünfte Tag.Und Gott sprach: Die Erde bringe hervor lebendige Wesen nach ihrer Art, Vieh, Gewürm und Tiere des Feldes nach ihrer Art! Und es geschah also.Und Gott machte die Tiere des Feldes nach ihrer Art und das Vieh nach seiner Art. Und Gott sah, daß es gut war.Und Gott sprach: Wir wollen Menschen machen nach unserm Bild uns ähnlich; die sollen herrschen über die Fische im Meer und über die Vögel des Himmels und über das Vieh auf der ganzen Erde, auch über alles, was auf Erden kriecht!Und Gott schuf den Menschen ihm zum Bilde, zum Bilde Gottes schuf er ihn; männlich und weiblich schuf er sie.Und Gott segnete sie und sprach zu ihnen: Seid fruchtbar und mehret euch und füllet die Erde und machet sie euch untertan und herrschet über die Fische im Meer und über die Vögel des Himmels und über alles Lebendige, was auf Erden kriecht!Und Gott sprach: Siehe, ich habe euch alles Gewächs auf Erden gegeben, das Samen trägt, auch alle Bäume, an welchen Früchte sind, die Samen tragen; sie sollen euch zur Nahrung dienen;aber allen Tieren der Erde und allen Vögeln des Himmels und allem, was auf Erden kriecht, allem, was eine lebendige Seele hat, habe ich alles grüne Kraut zur Nahrung gegeben. Und es geschah also.Und Gott sah an alles, was er gemacht hatte, und siehe, es war sehr gut. Und es ward Abend, und es ward Morgen: der sechste Tag.Also waren Himmel und Erde vollendet samt ihrem ganzen Heer,so daß Gott am siebenten Tage sein Werk vollendet hatte, das er gemacht; und er ruhte am siebenten Tage von allen seinen Werken, die er gemacht hatte.Und Gott segnete den siebenten Tag und heiligte ihn, denn an demselbigen ruhte er von all seinem Werk, das Gott schuf, als er es machte.Dies ist die Entstehung des Himmels und der Erde, zur Zeit, als Gott der HERR Himmel und Erde schuf.Es war aber noch kein Strauch des Feldes auf Erden, noch irgend ein grünes Kraut auf dem Felde gewachsen; denn Gott der HERR hatte noch nicht regnen lassen auf Erden, und es war kein Mensch vorhanden, um das Land zu bebauen.Aber ein Dunst stieg auf von der Erde und befeuchtete die ganze Erdoberfläche.Da bildete Gott der HERR den Menschen, Staub von der Erde, und blies den Odem des Lebens in seine Nase, und also ward der Mensch eine lebendige Seele.Und Gott der HERR pflanzte einen Garten in Eden gegen Morgen und setzte den Menschen darein, den er gemacht hatte.Und Gott der HERR ließ allerlei Bäume aus der Erde hervorsprossen, lieblich anzusehen und gut zur Nahrung, und den Baum des Lebens mitten im Garten und den Baum der Erkenntnis des Guten und Bösen.Und ein Strom ging aus von Eden, zu wässern den Garten; von dort aber teilte er sich und ward zu vier Hauptströmen.Der erste heißt Pison; das ist der, welcher das ganze Land Chavila umfließt, woselbst das Gold ist;und das Gold desselbigen Landes ist gut; dort kommt auch das Bedolach vor und der Edelstein Schoham.Der zweite Strom heißt Gichon; das ist der, welcher das ganze Land Kusch umfließt.Der dritte Strom heißt Hidekel; das ist der, welcher östlich von Assur fließt. Der vierte Strom ist der Euphrat.Und Gott der HERR nahm den Menschen und setzte ihn in den Garten Eden, daß er ihn bauete und bewahrete.Und Gott der HERR gebot dem Menschen und sprach: Du sollst essen von allen Bäumen des Gartens;aber von dem Baum der Erkenntnis des Guten und des Bösen sollst du nicht essen; denn welchen Tages du davon issest, mußt du unbedingt sterben!Und Gott der HERR sprach: Es ist nicht gut, daß der Mensch allein sei; ich will ihm eine Gehilfin machen, die ihm entspricht!Und Gott der HERR bildete aus Erde alle Tiere des Feldes und alle Vögel des Himmels und brachte sie zu dem Menschen, daß er sähe, wie er sie nennen würde, und damit jedes lebendige Wesen den Namen trage, den der Mensch ihm gäbe.Da gab der Mensch einem jeglichen Vieh und Vogel und allen Tieren des Feldes Namen; aber für den Menschen fand sich keine Gehilfin, die ihm entsprochen hätte.Da ließ Gott der HERR einen tiefen Schlaf auf den Menschen fallen; und während er schlief, nahm er eine seiner Rippen und verschloß deren Stelle mit Fleisch.Und Gott der HERR baute aus der Rippe, die er von dem Menschen genommen hatte, ein Weib und brachte sie zu ihm.Da sprach der Mensch: Das ist nun einmal Bein von meinem Bein und Fleisch von meinem Fleisch! Die soll Männin heißen; denn sie ist dem Mann entnommen!Darum wird der Mensch seinen Vater und seine Mutter verlassen und seinem Weibe anhangen, daß sie zu einem Fleische werden.Und sie waren beide nackt, der Mensch und sein Weib, und schämten sich nicht.Aber die Schlange war listiger als alle Tiere des Feldes, die Gott der HERR gemacht hatte; und sie sprach zum Weibe: Hat Gott wirklich gesagt, ihr dürft nicht essen von jedem Baum im Garten?Da sprach das Weib zur Schlange: Wir essen von der Frucht der Bäume im Garten;aber von der Frucht des Baumes mitten im Garten hat Gott gesagt: Esset nicht davon und rührt sie auch nicht an, damit ihr nicht sterbet!Da sprach die Schlange zum Weibe: Ihr werdet sicherlich nicht sterben!Sondern Gott weiß: welchen Tages ihr davon esset, werden eure Augen aufgetan und ihr werdet sein wie Gott und wissen, was gut und böse ist.Als nun das Weib sah, daß von dem Baume gut zu essen wäre und daß er eine Lust für die Augen und ein wertvoller Baum wäre, weil er klug machte, da nahm sie von dessen Frucht und aß und gab zugleich auch ihrem Mann davon, und er aß.Da wurden ihrer beider Augen aufgetan, und sie wurden gewahr, daß sie nackt waren; und sie banden Feigenblätter um und machten sich Schürzen.Und sie hörten die Stimme Gottes, des HERRN, der im Garten wandelte beim Wehen des Abendwindes; und der Mensch und sein Weib versteckten sich vor dem Angesicht Gottes des HERRN hinter die Bäume des Gartens.Da rief Gott der HERR dem Menschen und sprach: Wo bist du?Er sprach: Ich hörte deine Stimme im Garten und \ No newline at end of file diff --git a/tests/Localization/LanguageDetection/languages/en.txt b/tests/Localization/LanguageDetection/languages/en.txt new file mode 100644 index 000000000..10440d30a --- /dev/null +++ b/tests/Localization/LanguageDetection/languages/en.txt @@ -0,0 +1 @@ +At the first God made the heaven and the earth.And the earth was waste and without form; and it was dark on the face of the deep: and the Spirit of God was moving on the face of the waters.And God said, Let there be light: and there was light.And God, looking on the light, saw that it was good: and God made a division between the light and the dark,Naming the light, Day, and the dark, Night. And there was evening and there was morning, the first day.And God said, Let there be a solid arch stretching over the waters, parting the waters from the waters.And God made the arch for a division between the waters which were under the arch and those which were over it: and it was so.And God gave the arch the name of Heaven. And there was evening and there was morning, the second day.And God said, Let the waters under the heaven come together in one place, and let the dry land be seen: and it was so.And God gave the dry land the name of Earth; and the waters together in their place were named Seas: and God saw that it was good.And God said, Let grass come up on the earth, and plants producing seed, and fruit-trees giving fruit, in which is their seed, after their sort: and it was so.And grass came up on the earth, and every plant producing seed of its sort, and every tree producing fruit, in which is its seed, of its sort: and God saw that it was good.And there was evening and there was morning, the third day.And God said, Let there be lights in the arch of heaven, for a division between the day and the night, and let them be for signs, and for marking the changes of the year, and for days and for years:And let them be for lights in the arch of heaven to give light on the earth: and it was so.And God made the two great lights: the greater light to be the ruler of the day, and the smaller light to be the ruler of the night: and he made the stars.And God put them in the arch of heaven, to give light on the earth;To have rule over the day and the night, and for a division between the light and the dark: and God saw that it was good.And there was evening and there was morning, the fourth day.And God said, Let the waters be full of living things, and let birds be in flight over the earth under the arch of heaven.And God made great sea-beasts, and every sort of living and moving thing with which the waters were full, and every sort of winged bird: and God saw that it was good.And God gave them his blessing, saying, Be fertile and have increase, making all the waters of the seas full, and let the birds be increased in the earth.And there was evening and there was morning, the fifth day.And God said, Let the earth give birth to all sorts of living things, cattle and all things moving on the earth, and beasts of the earth after their sort: and it was so.And God made the beast of the earth after its sort, and the cattle after their sort, and everything moving on the face of the earth after its sort: and God saw that it was good.And God said, Let us make man in our image, like us: and let him have rule over the fish of the sea and over the birds of the air and over the cattle and over all the earth and over every living thing which goes flat on the earth.And God made man in his image, in the image of God he made him: male and female he made them.And God gave them his blessing and said to them, Be fertile and have increase, and make the earth full and be masters of it; be rulers over the fish of the sea and over the birds of the air and over every living thing moving on the earth.And God said, See, I have given you every plant producing seed, on the face of all the earth, and every tree which has fruit producing seed: they will be for your food:And to every beast of the earth and to every bird of the air and every living thing moving on the face of the earth I have given every green plant for food: and it was so.And God saw everything which he had made and it was very good. And there was evening and there was morning, the sixth day.And the heaven and the earth and all things in them were complete.And on the seventh day God came to the end of all his work; and on the seventh day he took his rest from all the work which he had done.And God gave his blessing to the seventh day and made it holy: because on that day he took his rest from all the work which he had made and done.These are the generations of the heaven and the earth when they were made.In the day when the Lord God made earth and heaven there were no plants of the field on the earth, and no grass had come up: for the Lord God had not sent rain on the earth and there was no man to do work on the land.But a mist went up from the earth, watering all the face of the land.And the Lord God made man from the dust of the earth, breathing into him the breath of life: and man became a living soul.And the Lord God made a garden in the east, in Eden; and there he put the man whom he had made.And out of the earth the Lord made every tree to come, delighting the eye and good for food; and in the middle of the garden, the tree of life and the tree of the knowledge of good and evil.And a river went out of Eden giving water to the garden; and from there it was parted and became four streams.The name of the first is Pishon, which goes round about all the land of Havilah where there is gold.And the gold of that land is good: there is bdellium and the onyx stone.And the name of the second river is Gihon: this river goes round all the land of Cush.And the name of the third river is Tigris, which goes to the east of Assyria. And the fourth river is Euphrates.And the Lord God took the man and put him in the garden of Eden to do work in it and take care of it.And the Lord God gave the man orders, saying, You may freely take of the fruit of every tree of the garden:But of the fruit of the tree of the knowledge of good and evil you may not take; for on the day when you take of it, death will certainly come to you.And the Lord God said, It is not good for the man to be by himself: I will make one like himself as a help to himAnd from the earth the Lord God made every beast of the field and every bird of the air, and took them to the man to see what names he would give them: and whatever name he gave to any living thing, that was its name.And the man gave names to all cattle and to the birds of the air and to every beast of the field; but Adam had no one like himself as a help.And the Lord God sent a deep sleep on the man, and took one of the bones from his side while he was sleeping, joining up the flesh again in its place:And the bone which the Lord God had taken from the man he made into a woman, and took her to the man.And the man said, This is now bone of my bone and flesh of my flesh: let her name be Woman because she was taken out of Man.For this cause will a man go away from his father and his mother and be joined to his wife; and they will be one flesh.And the man and his wife were without clothing, and they had no sense of shame.Now the snake was wiser than any beast of the field which the Lord God had made. And he said to the woman, Has God truly said that you may not take of the fruit of any tree in the garden?And the woman said, We may take of the fruit of the trees in the garden:But of the fruit of the tree in the middle of the garden, God has said, If you take of it or put your hands on it, death will come to you.And the snake said, Death will not certainly come to you:For God sees that on the day when you take of its fruit, your eyes will be open, and you will be as gods, having knowledge of good and evil.And when the woman saw that the tree was good for food, and a delight to the eyes, and to be desired to make one wise, she took of its fruit, and gave it to her husband.And their eyes were open and they were conscious that they had no clothing and they made themselves coats of leaves stitched together.And there came to them the sound of the Lord God walking in the garden in the evening wind: and the man and his wife went to a secret place among the trees of the garden, away from the eyes of the Lord God.And the voice of the Lord God came to the man, saying, Where are you?And he said, Hearing your voice in the garden I was full of fear, because I was without clothing: and I kept myself from your eyes.And he said, Who gave you the knowledge that you were without clothing? Have you taken of the fruit of the tree which I said you were not to take?And the man said, The woman whom you gave to be with me, she gave me the fruit of the tree and I took it.And the Lord God said to the woman, What have you done? And the woman said, I was tricked by the deceit of the snake and I took it.And the Lord God said to the snake, Because you have done this you are cursed more than all cattle and every beast of the field; you will go flat on the earth, and dust will be your food all the days of your life:And there will be war between you and the woman and between your seed and her seed: by him will your head be crushed and by you his foot will be wounded.To the woman he said, Great will be your pain in \ No newline at end of file diff --git a/tests/Localization/LanguageDetection/languages/es.txt b/tests/Localization/LanguageDetection/languages/es.txt new file mode 100644 index 000000000..492f44488 --- /dev/null +++ b/tests/Localization/LanguageDetection/languages/es.txt @@ -0,0 +1 @@ +EN el principio crió Dios los cielos y la tierra.Y la tierra estaba desordenada y vacía, y las tinieblas estaban sobre la haz del abismo, y el Espíritu de Dios se movía sobre la haz de las aguas.Y dijo Dios: Sea la luz: y fué la luz.Y vió Dios que la luz era buena: y apartó Dios la luz de las tinieblas.Y llamó Dios á la luz Día, y á las tinieblas llamó Noche: y fué la tarde y la mañana un día.Y dijo Dios: Haya expansión en medio de las aguas, y separe las aguas de las aguas.E hizo Dios la expansión, y apartó las aguas que estaban debajo de la expansión, de las aguas que estaban sobre la expansión: y fué así.Y llamó Dios á la expansión Cielos: y fué la tarde y la mañana el día segundo.Y dijo Dios: Júntense las aguas que están debajo de los cielos en un lugar, y descúbrase la seca: y fué así.Y llamó Dios á la seca Tierra, y á la reunión de las aguas llamó Mares: y vió Dios que era bueno.Y dijo Dios: Produzca la tierra hierba verde, hierba que dé simiente; árbol de fruto que dé fruto según su género, que su simiente esté en él, sobre la tierra: y fué así.Y produjo la tierra hierba verde, hierba que da simiente según su naturaleza, y árbol que da fruto, cuya simiente está en él, según su género: y vió Dios que era bueno.Y fué la tarde y la mañana el día tercero.Y dijo Dios: Sean lumbreras en la expansión de los cielos para apartar el día y la noche: y sean por señales, y para las estaciones, y para días y años;Y sean por lumbreras en la expansión de los cielos para alumbrar sobre la tierra: y fue.E hizo Dios las dos grandes lumbreras; la lumbrera mayor para que señorease en el día, y la lumbrera menor para que señorease en la noche: hizo también las estrellas.Y púsolas Dios en la expansión de los cielos, para alumbrar sobre la tierra,Y para señorear en el día y en la noche, y para apartar la luz y las tinieblas: y vió Dios que era bueno.Y fué la tarde y la mañana el día cuarto.Y dijo Dios: Produzcan las aguas reptil de ánima viviente, y aves que vuelen sobre la tierra, en la abierta expansión de los cielos.Y crió Dios las grandes ballenas, y toda cosa viva que anda arrastrando, que las aguas produjeron según su género, y toda ave alada según su especie: y vió Dios que era bueno.Y Dios los bendijo diciendo: Fructificad y multiplicad, y henchid las aguas en los mares, y las aves se multipliquen en la tierra.Y fué la tarde y la mañana el día quinto.Y dijo Dios: Produzca la tierra seres vivientes según su género, bestias y serpientes y animales de la tierra según su especie: y fué así.E hizo Dios animales de la tierra según su género, y ganado según su género, y todo animal que anda arrastrando sobre la tierra según su especie: y vió Dios que era bueno.Y dijo Dios: Hagamos al hombre á nuestra imagen, conforme á nuestra semejanza; y señoree en los peces de la mar, y en las aves de los cielos, y en las bestias, y en toda la tierra, y en todo animal que anda arrastrando sobre la tierra.Y crió Dios al hombre á su imagen, á imagen de Dios lo crió; varón y hembra los crió.Y los bendijo Dios; y díjoles Dios: Fructificad y multiplicad, y henchid la tierra, y sojuzgadla, y señoread en los peces de la mar, y en las aves de los cielos, y en todas las bestias que se mueven sobre la tierra.Y dijo Dios: He aquí que os he dado toda hierba que da simiente, que está sobre la haz de toda la tierra; y todo árbol en que hay fruto de árbol que da simiente, seros ha para comer.Y á toda bestia de la tierra, y á todas las aves de los cielos, y á todo lo que se mueve sobre la tierra, en que hay vida, toda hierba verde les será para comer: y fué así.Y vió Dios todo lo que había hecho, y he aquí que era bueno en gran manera. Y fué la tarde y la mañana el día sexto.Y FUERON acabados los cielos y la tierra, y todo su ornamento.Y acabó Dios en el día séptimo su obra que hizo, y reposó el día séptimo de toda su obra que había hecho.Y bendijo Dios al día séptimo, y santificólo, porque en él reposó de toda su obra que había Dios criado y hecho.Estos son los orígenes de los cielos y de la tierra cuando fueron criados, el día que Jehová Dios hizo la tierra y los cielos,Y toda planta del campo antes que fuese en la tierra, y toda hierba del campo antes que naciese: porque aun no había Jehová Dios hecho llover sobre la tierra, ni había hombre para que labrase la tierra;Mas subía de la tierra un vapor, que regaba toda la faz de la tierra.Formó, pues, Jehová Dios al hombre del polvo de la tierra, y alentó en su nariz soplo de vida; y fué el hombre en alma viviente.Y había Jehová Dios plantado un huerto en Edén al oriente, y puso allí al hombre que había formado.Y había Jehová Dios hecho nacer de la tierra todo árbol delicioso á la vista, y bueno para comer: también el árbol de vida en medio del huerto, y el árbol de ciencia del bien y del mal.Y salía de Edén un río para regar el huerto, y de allí se repartía en cuatro ramales.El nombre del uno era Pisón: éste es el que cerca toda la tierra de Havilah, donde hay oro:Y el oro de aquella tierra es bueno: hay allí también bdelio y piedra cornerina.El nombre del segundo río es Gihón: éste es el que rodea toda la tierra de Etiopía.Y el nombre del tercer río es Hiddekel: éste es el que va delante de Asiria. Y el cuarto río es el Eufrates.Tomó, pues, Jehová Dios al hombre, y le puso en el huerto de Edén, para que lo labrara y lo guardase.Y mandó Jehová Dios al hombre, diciendo: De todo árbol del huerto comerás;Mas del árbol de ciencia del bien y del mal no comerás de él; porque el día que de él comieres, morirás.Y dijo Jehová Dios: No es bueno que el hombre esté solo; haréle ayuda idónea para él.Formó, pues, Jehová Dios de la tierra toda bestia del campo, y toda ave de los cielos, y trájolas á Adam, para que viese cómo les había de llamar; y todo lo que Adam llamó á los animales vivientes, ese es su nombre.Y puso Adam nombres á toda bestia y ave de los cielos y á todo animal del campo: mas para Adam no halló ayuda que estuviese idónea para él.Y Jehová Dios hizo caer sueño sobre Adam, y se quedó dormido: entonces tomó una de sus costillas, y cerró la carne en su lugar;Y de la costilla que Jehová Dios tomó del hombre, hizo una mujer, y trájola al hombre.Y dijo Adam: Esto es ahora hueso de mis huesos, y carne de mi carne: ésta será llamada Varona, porque del varón fué tomada.Por tanto, dejará el hombre á su padre y á su madre, y allegarse ha á su mujer, y serán una sola carne.Y estaban ambos desnudos, Adam y su mujer, y no se avergonzaban.EMPERO la serpiente era astuta, más que todos los animales del campo que Jehová Dios había hecho; la cual dijo á la mujer: ¿Conque Dios os ha dicho: No comáis de todo árbol del huerto?Y la mujer respondió á la serpiente: Del fruto de los árboles del huerto comemos;Mas del fruto del árbol que está en medio del huerto dijo Dios: No comeréis de él, ni le tocaréis, porque no muráis.Entonces la serpiente dijo á la mujer: No moriréis;Mas sabe Dios que el día que comiereis de él, serán abiertos vuestros ojos, y seréis como dioses sabiendo el bien y el mal.Y vió la mujer que el árbol era bueno para comer, y que era agradable á los ojos, y árbol codiciable para alcanzar la sabiduría; y tomó de su fruto, y comió; y dió también á su marido, el cual comió así como ella.Y fueron abiertos los ojos de entrambos, y conocieron que estaban desnudos: entonces cosieron hojas de higuera, y se hicieron delantales.Y oyeron la voz de Jehová Dios que se paseaba en el huerto al aire del día: y escondióse el hombre y su mujer de la presencia de Jehová Dios entre los árboles del huerto.Y llamó Jehová Dios al hombre, y le dijo: ¿Dónde estás tú?Y él respondió: Oí tu voz en el huerto, y tuve miedo, porque estaba desnudo; y escondíme.Y díjole: ¿Quién te enseñó que estabas desnudo? ¿Has comido del árbol de que yo te mandé no comieses?Y el hombre respondió: La mujer que me diste por compañera me dió del árbol, y yo comí.Entonces Jehová Dios dijo á la mujer: ¿Qué es lo que has hecho? Y dijo la mujer: La serpiente me engañó, y comí.Y Jehová Dios dijo á la serpiente: Por cuanto esto hiciste, maldita serás entre todas las bestias y entre todos los animales del campo; sobre tu pecho andarás, y polvo comerás todos los días de tu vida:Y enemistad pondré entre ti y la mujer, y entre tu simiente y la simiente suya; ésta te herirá en la cabeza, y tú le herirás en el calcañar.A la mujer dijo: Multiplicaré en gran manera tus dolores y tus preñeces; con dolor parirás los hijos; y á tu marido será tu deseo, y él se enseñoreará de ti.Y al hombre dijo: Por cuanto obedeciste á la voz de tu mujer, y comiste del árbol de que te mandé diciendo, No comerás de él; maldita será la tierra por amor de ti; con dolor comerás de ella todos los días de tu vida;Espinos y cardos te producirá, y comerás hierba del campo;En el sudor \ No newline at end of file diff --git a/tests/Localization/LanguageDetection/languages/fr.txt b/tests/Localization/LanguageDetection/languages/fr.txt new file mode 100644 index 000000000..ae7624b87 --- /dev/null +++ b/tests/Localization/LanguageDetection/languages/fr.txt @@ -0,0 +1 @@ +Dieu, au commencement, créa les cieux et la terre;en une masse fluide et sans forme, et les ténèbres étaient à la surface de l'espace, et le Souffle de Dieu en agitait les eaux.Et Dieu dit: Que la lumière soit; et son rayonnement fut.Et Dieu vit que la lumière était gracieuse; et Dieu démêla la lumière d'avec les ténèbres.Et Dieu invita la lumière gracieuse; mais il convoqua les ténèbres à se replier. Et il y eut un soir, et il y eut un matin; ce fut le premier jour.Puis Dieu dit: Qu'il y ait un firmament entre les eaux; et qu'il sépare les eaux d'avec les vapeurs.Et Dieu fit le firmament, et sépara les eaux qui sont au-dessous du firmament, d'avec les vapeurs qui sont au-dessus du firmament; et cela fut ainsi.Et Dieu nomma le firmament, cieux. Et il y eut un soir, et il y eut un matin; ce fut le second jour.Puis Dieu dit: Que les eaux qui sont au-dessous des cieux se rassemblent en un seul lieu, et que le Continent paraisse; et cela fut ainsi.Et Dieu nomma le Continent, Terre; et il nomma l'amas des eaux, Océan; et Dieu vit que cela était bon.Puis Dieu dit: Que la terre pousse de la végétation, des herbes portant semence, des arbres fruitiers portant du fruit selon leur espèce, qui aient leur semence en eux-mêmes sur la terre; et cela fut ainsi.Et la terre produisit de la végétation, des herbes portant semence selon leur espèce, et des arbres portant du fruit, qui avaient leur semence en eux-mêmes, selon leur espèce; et Dieu vit que cela était bon.Et il y eut un soir, et il y eut un matin; ce fut le troisième jour.Puis Dieu dit: Qu'il y ait des luminaires dans l'étendue des cieux, pour séparer le jour d’avec la nuit, et qu'ils servent de signes, et pour les saisons, et pour les jours, et pour les années;Et qu'ils servent de luminaires dans l'étendue des cieux, pour éclairer la terre; et cela fut ainsi.Et Dieu fit les deux grands luminaires; le grand luminaire, pour dominer sur le jour, et le petit luminaire, pour dominer sur la nuit; il fit aussi les étoiles.Et Dieu les mit dans l'expansion des cieux, pour éclairer la terre;Et pour dominer sur le jour et sur la nuit, et pour séparer la lumière d'avec les ténèbres; et Dieu vit que cela était bon.Et il y eut un soir, et il y eut un matin; ce fut le quatrième jour.Puis Dieu dit: Que les eaux produisent en abondance des créatures animées qui ont la vie; et que des oiseaux volent sur la terre dans le firmament de l'étendue des cieux.Et Dieu créa les grands poissons, et toutes les créatures vivantes qui se meuvent, dont les eaux foisonnèrent, selon leurs espèces, et tout oiseau ailé, selon son espèce; et Dieu vit que cela était bon.Et Dieu les bénit, en disant: Croissez et multipliez, et remplissez les eaux dans les mers; et que les oiseaux multiplient sur la terre.Et il y eut un soir, et il y eut un matin; ce fut le cinquième jour.Puis Dieu dit: Que la terre produise des créatures vivantes selon leur espèce, bétail, reptiles (Sauriens - Dinosaures) et animaux de la terre selon leur espèce; et cela fut ainsi.Et Dieu fit les animaux de la terre selon leur espèce, le bétail selon son espèce, et tous les reptiles du sol selon leur espèce; et Dieu vit que cela était bon.Puis Dieu dit: Que l'homme soit désigné l’image unique, avec une ressemblance distinctive, et qu'il domine sur les poissons de la mer, et sur les oiseaux des cieux, et sur le bétail, et sur toute la terre, et sur tous les reptiles qui rampent sur la terre.Et Dieu créa l'homme à son image; il le créa à l'image de Dieu; il les créa mâle et femelle.Et Dieu les bénit; et Dieu leur dit: Croissez et multipliez, et remplissez la terre, et maîtrisez-la, et dominez sur les poissons de la mer et sur les oiseaux des cieux, et sur tout animal qui se meut sur la terre.Et Dieu dit: Voici je vous ai donné toute herbe portant semence, qui est à la surface de toute la terre, et tout arbre qui a en soi du fruit d'arbre portant semence; ce sera votre nourritureEt à tous les animaux des champs, et à tous les oiseaux des cieux, et à tout ce qui se meut sur la terre, qui a en soi la vie, j'ai donné toute herbe verte pour nourriture; et cela fut ainsi.Et Dieu vit tout ce qu'il avait fait, et voici, c'était très bon. Et il y eut un soir, et il y eut un matin; ce fut le sixième jour.Ainsi furent achevés les cieux et la terre, et toute leur multitude.Et Dieu eut achevé au septième jour son oeuvre qu'il avait faite; et il se reposa au septième jour de toute son oeuvre qu'il avait faite.Et Dieu bénit le septième jour, et le sanctifia, parce qu'en ce jour-là il se reposa de toute son oeuvre, pour l'accomplissement de laquelle Dieu avait créé et faite.Telles sont les générations des cieux et de la terre, quand ils furent créés, lorsque l’Éternel Dieu fit la terre et les cieux.Or aucun arbrisseau des champs n'était encore sur la terre, et aucune herbe des champs ne germait encore; car l'Éternel Dieu n'avait point fait pleuvoir sur la terre, et il n'y avait point d'homme pour maîtriser la terre;Mais une vapeur montait de la terre, et arrosait toute la surface du sol.Et l'Éternel Dieu forma l'homme de la poussière de la terre, et souffla dans ses narines un esprit de vie; et l'homme devint une âme vivanteEt l'Éternel Dieu détermina l’Enceinte de sa Grâce qui le précédait, et y mit l'homme qu'il avait formé.Et l'Éternel Dieu fit surgir de la résolution de sa Grâce toute sorte d’assurances gracieuses à la perception, et favorables à recevoir; l’assurance de la Vie au milieu de l’Enceinte, et l’assurance de la connaissance du bien et du mal.Et un fleuve sortait de la Grâce pour saturer l’Enceinte; et de là il se divisait et formait quatre principes.Le nom du premier est Croissance (Pishon); c'est celui qui entoure le pays de la Confiance (Havila), où se trouve la prospérité (or).Et la prospérité (or) de cette région est gracieuse; là se trouve la Sanctification (bdellion), et la pureté de l’édification (pierre d'onyx).Le nom du second fleuve est Épreuve (Guihon); c'est celui qui entoure toute la région des passions (Cush).Le nom du troisième fleuve est Diligence (Hiddékel); c'est celui qui va vers le devant de la droiture (l'Assyrie). Et le quatrième fleuve, c'est la Rémunération (l'Euphrate).L'Éternel Dieu prit donc l'homme et le plaça dans l’Enceinte de sa Grâce, pour la posséder et pour la préserver.Et l'Éternel Dieu commanda à l'homme, en disant: Tu peux accueillir librement toutes les assurances de l'Enceinte.Mais, quant à l’assurance de la connaissance du bien et du mal, tu n’en recevras point; car au jour où tu t’en procurera, certainement tu mourras de dépérissement.Et l'Éternel Dieu dit: Il n'est pas convenable que l'homme soit seul; je lui ferai une assistance pour l’aider.Et l'Éternel Dieu forma de la terre une descendance de l’homme, une multitude d’êtres vivants à l’image d’Adam dans l’expansion de l’existence sublime de la connaissance de Dieu; et il les fit venir vers Adam, pour qu’il considère leurs accomplissements, et que la position qu'Adam donnerait à chacun des êtres vivants, fût son obligation.Et Adam donna des positions à tous les Perceptifs, sublimes en connaissance, parmi tous les êtres vivants dans l’expansion de l’existence; mais, pour l'homme, il n’existait point d'aide qui lui correspondait.Et l'Éternel Dieu produisit une torpeur profonde qui languissait sur Adam; et il prit cette inclination d’Adam, et l’entoura de chair.Et l'Éternel Dieu forma une existence de l’inclination qu'il avait prise d'Adam, et forma son existence charnelle et la fit demeurer avec Adam.Et Adam dit: Celle-ci est enfin la substance de ma puissance, et l'enchantement de ma chair. On la nommera l’Existence, mon Épouse (ISHA), car elle a été prise du Vivant, son Époux (ISH).C'est pourquoi le Vivant laissera son père (son origine) et sa mère (sa source), et se joindra à son épouse, et ils seront une seule chair.Or Adam et sa femme étaient tous deux rusés, et ils ne s’en relâchaient point.Or, ce raisonnement rusé était extrêmement subtil dans tous les êtres vivants en expansion d’existence que l'Éternel Dieu avait faits; et il dit en la femme: Quoi! Dieu aurait-il dit: Vous ne possèderez point de toutes les assurances de l’Enceinte?Et la femme répliqua à ce raisonnement rusé: Nous recevons la grâce des assurances de l’Enceinte;Mais quant à l’avantage de l’assurance de l’indépendance qui est au milieu de l'Enceinte, Dieu a dit: Vous n’en possèderez point, et vous n’en saisirez point, de peur que vous ne mouriez.Alors le raisonnement dit en la femme: Vous ne mourrez nullement;Mais Dieu sait qu'au jour où vous en possèderez, vos yeux s'ouvriront, et vous serez comme des dieux, connaissant le bien et le mal.Et la femme vit que l’avantage de cette assurance était favorable à la réception de son existence, et qu'elle était gracieuse à la perception, et que cette assurance était désirable pour devenir intelligent; et elle prit de son avantage et le reçu, et en donna aussi à son mari auprès d'elle, et il l’accepta.Et les yeux de tous deux s'ouvrirent; et ils connurent qu'ils étaient découverts; et ils lièrent les élévations de l’outrage ensemble, et se firent des restrictions.Et ils entendirent l’appel irrésistible de l'Éternel \ No newline at end of file diff --git a/tests/Localization/LanguageDetection/languages/ru.txt b/tests/Localization/LanguageDetection/languages/ru.txt new file mode 100644 index 000000000..1c68bcad3 --- /dev/null +++ b/tests/Localization/LanguageDetection/languages/ru.txt @@ -0,0 +1 @@ +В начале сотворил Бог небо и землю.Земля же была безвидна и пуста, и тьма над бездною, и Дух Божий носился над водою.И сказал Бог: да будет свет. И сталсвет.И увидел Бог свет, что он хорош, и отделил Бог свет от тьмы.И назвал Бог свет днем, а тьму ночью. И был вечер, и было утро: день один.И сказал Бог: да будет твердь посреди воды, и да отделяет она воду от воды.И создал Бог твердь, и отделил воду, которая подтвердью, от воды, которая над твердью. И стало так.И назвал Бог твердь небом. И был вечер, и было утро: день второй.И сказал Бог: да соберется вода, которая под небом, в одно место, и да явится суша. И стало так.И назвал Бог сушу землею, а собрание вод назвал морями. И увидел Бог, что это хорошо.И сказал Бог: да произрастит земля зелень, траву, сеющую семя дерево плодовитое, приносящее по роду своему плод, в котором семя его на земле. И стало так.И произвела земля зелень, траву, сеющую семя по роду ее, и дерево, приносящее плод, в котором семя его по роду его. И увидел Бог, что это хорошо.И был вечер, и было утро: день третий.И сказал Бог: да будут светила на тверди небесной для отделения дня от ночи, и для знамений, и времен, и дней, и годов;и да будут они светильниками на тверди небесной, чтобы светить на землю. И стало так.И создал Бог два светила великие: светило большее, для управления днем, и светило меньшее, для управления ночью, и звезды;и поставил их Бог на тверди небесной, чтобы светить на землю,и управлять днем и ночью, и отделять свет от тьмы. И увидел Бог, что это хорошо.И был вечер, и было утро: день четвертый.И сказал Бог: да произведет вода пресмыкающихся, душу живую; и птицы да полетят над землею, по тверди небесной.И сотворил Бог рыб больших и всякую душу животных пресмыкающихся, которых произвела вода, по роду их, и всякую птицу пернатую по роду ее. И увидел Бог, что это хорошо.И благословил их Бог, говоря: плодитесь и размножайтесь, и наполняйте воды в морях, и птицы да размножаются на земле.И был вечер, и было утро: день пятый.И сказал Бог: да произведет земля душу живую по роду ее, скотов, и гадов, и зверей земных по роду их. И стало так.И создал Бог зверей земных по роду их, и скот по роду его, и всехгадов земных по роду их. И увидел Бог, что это хорошо.И сказал Бог: сотворим человека по образу Нашему по подобию Нашему,и да владычествуют они над рыбами морскими, и над птицами небесными, и над скотом, и над всею землею, и над всеми гадами, пресмыкающимися по земле.И сотворил Бог человека по образу Своему, по образу Божию сотворил его; мужчину и женщину сотворил их.И благословил их Бог, и сказал им Бог: плодитесь и размножайтесь, и наполняйте землю, и обладайте ею, и владычествуйте над рыбами морскими и над птицами небесными, и над всяким животным, пресмыкающимся по земле.И сказал Бог: вот, Я дал вам всякую траву, сеющую семя, какая есть на всей земле, и всякое дерево, у которого плод древесный, сеющий семя; – вам сие будет в пищу;а всем зверям земным, и всем птицам небесным, и всякому пресмыкающемуся по земле, вкотором душа живая, дал Я всю зелень травную в пищу. И стало так.И увидел Бог все, что Он создал, и вот, хорошо весьма. И был вечер, и было утро: день шестой.Так совершены небо и земля и все воинство их.И совершил Бог к седьмому дню дела Свои, которые Он делал, и почил в день седьмый от всех дел Своих, которые делал.И благословил Бог седьмой день, и освятил его, ибо в оный почил от всех дел Своих, которые Бог творил и созидал.Вот происхождение неба и земли, при сотворении их, в то время, когда Господь Бог создал землю и небо,и всякий полевой кустарник, которого еще не было на земле, и всякую полевую траву, которая еще не росла, ибо Господь Бог не посылал дождя на землю, и не было человека для возделывания земли,но пар поднимался с земли и орошал все лице земли.И создал Господь Бог человека из праха земного, и вдунул в лице его дыхание жизни, и стал человек душею живою.И насадил Господь Бог рай в Едеме на востоке, и поместил там человека, которого создал.И произрастил Господь Бог из земли всякое дерево, приятное на вид и хорошее для пищи, и дерево жизни посреди рая, и дерево познания добра и зла.Из Едема выходила река для орошения рая; и потом разделялась на четыре реки.Имя одной Фисон: она обтекает всю землю Хавила, ту, где золото;и золото той земли хорошее; там бдолах и камень оникс.Имя второй реки Гихон: она обтекает всю землю Куш.Имя третьей реки Хиддекель: она протекает пред Ассириею. Четвертая река Евфрат.И взял Господь Бог человека, и поселил его в саду Едемском, чтобы возделывать его и хранить его.И заповедал Господь Бог человеку, говоря: от всякого дерева в саду ты будешь есть,а от дерева познания добра и зла не ешь от него, ибо в день, в который ты вкусишь от него, смертью умрешь.И сказал Господь Бог: не хорошо быть человеку одному; сотворим ему помощника, соответственного ему.Господь Бог образовал из земли всех животных полевых и всех птицнебесных, и привел к человеку, чтобы видеть, как он назовет их, и чтобы, как наречет человек всякую душу живую, так и было имя ей.И нарек человек имена всем скотам и птицам небесным и всем зверямполевым; но для человека не нашлось помощника, подобного ему.И навел Господь Бог на человека крепкий сон; и, когда он уснул,взял одно из ребр его, и закрыл то место плотию.И создал Господь Бог из ребра, взятого у человека, жену, и привел ее к человеку.И сказал человек: вот, это кость от костей моих и плоть от плоти моей; она будет называться женою, ибо взята от мужа.Потому оставит человек отца своего и мать свою и прилепится к жене своей; и будут одна плоть.И были оба наги, Адам и жена его, и не стыдились.Змей был хитрее всех зверей полевых, которых создал Господь Бог. И сказал змей жене: подлинно ли сказал Бог: не ешьте ни от какого дерева в раю?И сказала жена змею: плоды с дерев мы можем есть,только плодов дерева, которое среди рая, сказал Бог, не ешьте их и не прикасайтесь к ним, чтобы вам не умереть.И сказал змей жене: нет, не умрете,но знает Бог, что в день, в который вы вкусите их, откроются глаза ваши, и вы будете, как боги, знающие добро и зло.И увидела жена, что дерево хорошо для пищи, и что оно приятно дляглаз и вожделенно, потому что дает знание; и взяла плодов его и ела; и дала также мужу своему, и он ел.И открылись глаза у них обоих, и узнали они, что наги, и сшили смоковные листья, и сделали себе опоясания.И услышали голос Господа Бога, ходящего в раю во время прохлады дня; и скрылся Адам и жена его от лица Господа Бога между деревьями рая.И воззвал Господь Бог к Адаму и сказал ему: где ты?Он сказал: голос Твой я услышал в раю, и убоялся, потому что я наг, и скрылся.И сказал: кто сказал тебе, что ты наг? не ел ли ты от дерева, с которого Я запретил тебе есть?Адам сказал: жена, которую Ты мне дал, она дала мне от дерева, и я ел.И сказал Господь Бог жене: что ты это сделала? Жена сказала: змей обольстил меня, и я ела.И сказал Господь Бог змею: за то, что ты сделал это, проклят ты пред всеми скотами и пред всеми зверями полевыми; ты будешь ходить на чреве твоем, и будешь есть прах во все днижизни твоей;и вражду положу между тобою и между женою, и между семенем твоим и между семенем ее; оно будет поражать тебя в голову, а ты будешь жалить его в пяту.Жене сказал: умножая умножу скорбь твою в беременности твоей; в болезни будешь рождать детей; и к мужу твоему влечение твое, и он будет господствовать над тобою.Адаму же сказал: за то, что ты послушал голоса жены твоей и ел от дерева, о котором Я заповедал тебе, сказав: не ешь от него, проклята земля за тебя; со скорбью будешь питаться от нее во все дни жизни твоей;терния и волчцы произрастит она тебе; и будешь питаться полевою травою;в поте лица твоего будешь есть хлеб, доколе не возвратишься в землю, из которой ты взят, ибо прах ты и в прах возвратишься.И нарек Адам имя жене своей: Ева, ибо она стала матерью всех живущих.И сделал Господь Бог Адаму и жене его одежды кожаные и одел их.И сказал Господь Бог: вот, Адам стал как один из Нас, зная добро и зло; и теперь как бы не простер он руки своей, и не взял также от дерева жизни, и не вкусил, и не стал жить вечно.И выслал его Господь Бог из сада Едемского, чтобы возделывать землю, из которой он взят.И изгнал Адама, и поставил на востоке у сада Едемского Херувима и пламенный меч обращающийся, чтобы охранять путь к дереву жизни.Адам познал Еву, жену свою; и она зачала, и родила Каина, и сказала: приобрела я человека от Господа.И еще родила брата его, Авеля. И был Авель пастырь овец, а Каин был земледелец.Спустя несколько времени, Каин принес от плодов земли дар Господу,и Авель также принес от первородных стада своего и от тука их. И призрел Господь на Авеля и на дар его,а на Каина и на дар его не призрел. Каин сильно огорчился, и поникло лице его.И сказал Господь Каину: почему ты огорчился? и отчего поникло лице твое?если делаешь доброе, то не поднимаешь ли лица? а если не делаешь доброго, то у дверей грех лежит; он влечет тебя к себе, но ты господствуй над ним.И сказал Каин Авелю, брату своему. И когда они были в поле, восстал Каин на Авеля, брата своего, и убил его.И сказал Господь Каину: где Авель, брат твой? Он сказал: не знаю; \ No newline at end of file diff --git a/tests/Message/Http/HttpHeaderTest.php b/tests/Message/Http/HttpHeaderTest.php index 08a7ab938..bd5e29068 100755 --- a/tests/Message/Http/HttpHeaderTest.php +++ b/tests/Message/Http/HttpHeaderTest.php @@ -189,23 +189,11 @@ final class HttpHeaderTest extends \PHPUnit\Framework\TestCase */ public function testHeaderGeneration() : void { - $this->header->generate(RequestStatusCode::R_403); - self::assertEquals(403, \http_response_code()); - - $this->header->generate(RequestStatusCode::R_404); - self::assertEquals(404, \http_response_code()); - - $this->header->generate(RequestStatusCode::R_406); - self::assertEquals(406, \http_response_code()); - - $this->header->generate(RequestStatusCode::R_407); - self::assertEquals(407, \http_response_code()); - - $this->header->generate(RequestStatusCode::R_503); - self::assertEquals(503, \http_response_code()); - - $this->header->generate(RequestStatusCode::R_500); - self::assertEquals(500, \http_response_code()); + $consts = RequestStatusCode::getConstants(); + foreach ($consts as $status) { + $this->header->generate($status); + self::assertTrue(\stripos($this->header->get('status')[0], (string) $status) !== false); + } } public function testGetAllHeaders() : void @@ -215,11 +203,11 @@ final class HttpHeaderTest extends \PHPUnit\Framework\TestCase $tmp = $_SERVER; $_SERVER = \json_decode($dummyHeaders, true); - self::assertEquals('127.0.0.1', $this->header->getAllHeaders()['Host']); + self::assertEquals('127.0.0.1', $this->header->getAllHeaders()['host'] ?? ''); // If headers are loaded once, only the cached version is used! $_SERVER = \json_decode('{"HTTP_HOST": "invalid"}', true); - self::assertEquals('127.0.0.1', $this->header->getAllHeaders()['Host']); + self::assertEquals('127.0.0.1', $this->header->getAllHeaders()['host'] ?? ''); $_SERVER = $tmp; } diff --git a/tests/Security/EncryptionHelperTest.php b/tests/Security/EncryptionHelperTest.php new file mode 100644 index 000000000..652f6f259 --- /dev/null +++ b/tests/Security/EncryptionHelperTest.php @@ -0,0 +1,83 @@ + "O'reilly", + 'c' => [ + 'd' => 2, + 'f' => [ + 'g' => "O'reilly", + ], + ], + ], + Guard::unslash( + [ + 'a' => "O\'reilly", + 'c' => [ + 'd' => 2, + 'f' => [ + 'g' => "O\'reilly", + ], + ], + ] + ) + ); + } +} diff --git a/tests/Security/decrypted.txt.tmp b/tests/Security/decrypted.txt.tmp new file mode 100644 index 000000000..e69de29bb diff --git a/tests/Security/encrytped.txt b/tests/Security/encrytped.txt new file mode 100644 index 000000000..ad66a64a7 --- /dev/null +++ b/tests/Security/encrytped.txt @@ -0,0 +1 @@ +k 'M㧄F&Aj4{,e=uQ[G#HX \ No newline at end of file diff --git a/tests/Security/plain.txt b/tests/Security/plain.txt new file mode 100644 index 000000000..273c1a9ff --- /dev/null +++ b/tests/Security/plain.txt @@ -0,0 +1 @@ +This is a test. \ No newline at end of file diff --git a/tests/Stdlib/Graph/GraphTest.php b/tests/Stdlib/Graph/GraphTest.php index 920d3a02c..ae81f9cf8 100755 --- a/tests/Stdlib/Graph/GraphTest.php +++ b/tests/Stdlib/Graph/GraphTest.php @@ -74,7 +74,16 @@ final class GraphTest extends \PHPUnit\Framework\TestCase */ public function testDirectedOutput() : void { - self::assertFalse($this->graph->isDirected()); + $node0 = new Node('0'); + $node1 = new Node('1'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + + $node0->setNodeRelative($node1, isDirected: true); + + $this->graph->isDirected = false; + self::assertTrue($this->graph->isDirected()); } /** @@ -320,6 +329,8 @@ final class GraphTest extends \PHPUnit\Framework\TestCase $this->graph->setNodeRelative($node2, $node3, true); $this->graph->setNodeRelative($node1, $node3, true); + $this->graph->isDirected = true; + self::assertFalse($this->graph->hasCycle()); $node3->setNodeRelative($node1); @@ -592,6 +603,86 @@ final class GraphTest extends \PHPUnit\Framework\TestCase self::assertCount(3, $path); } + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 6 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testShortestPathFloydWarshall() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + $node6 = new Node('6'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + $this->graph->setNode($node6); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + $paths = $this->graph->getFloydWarshallShortestPath($node0, $node5); + self::assertGreaterThan(1, $paths); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 6 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testLongestPathsDfs() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + $node6 = new Node('6'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + $this->graph->setNode($node6); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + $paths = $this->graph->longestPath($node0, $node5); + self::assertGreaterThan(1, $paths); + } + /** * 1 - 3 - 5 * / |\ / @@ -680,8 +771,6 @@ final class GraphTest extends \PHPUnit\Framework\TestCase */ public function testDiameter() : void { - self::markTestIncomplete(); - $node0 = new Node('0'); $node1 = new Node('1'); $node2 = new Node('2'); @@ -704,6 +793,213 @@ final class GraphTest extends \PHPUnit\Framework\TestCase $node3->setNodeRelative($node5); $node4->setNodeRelative($node5); - self::assertEquals(0, $this->graph->getDiameter()); + self::assertGreaterThan(3, $this->graph->getDiameter()); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testGirth() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + self::assertGreaterThan(3, $this->graph->getGirth()); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testCircuitRank() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + self::assertGreaterThan(2, $this->graph->getCircuitRank()); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testStronglyConnected() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + self::assertTrue($this->graph->isStronglyConnected()); + } + + /** + * 0 - 1 - 2 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testInvalidStronglyConnected() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + + $node0->setNodeRelative($node1); + $node1->setNodeRelative($node2); + + self::assertFalse($this->graph->isStronglyConnected()); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testBipartite() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + self::assertTrue($this->graph->isBipartite()); + } + + /** + * 1 - 3 - 5 + * / |\ / + * 0 | \ / + * \ | \ / + * 2 4 + * + * @covers phpOMS\Stdlib\Graph\Graph + * @group framework + */ + public function testTriangles() : void + { + $node0 = new Node('0'); + $node1 = new Node('1'); + $node2 = new Node('2'); + $node3 = new Node('3'); + $node4 = new Node('4'); + $node5 = new Node('5'); + + $this->graph->setNode($node0); + $this->graph->setNode($node1); + $this->graph->setNode($node2); + $this->graph->setNode($node3); + $this->graph->setNode($node4); + $this->graph->setNode($node5); + + $node0->setNodeRelative($node1); + $node0->setNodeRelative($node2); + $node1->setNodeRelative($node2); + $node1->setNodeRelative($node3); + $node1->setNodeRelative($node4); + $node3->setNodeRelative($node5); + $node4->setNodeRelative($node5); + + self::assertTrue($this->graph->hasTriangles()); } } diff --git a/tests/Utils/ArrayUtilsTest.php b/tests/Utils/ArrayUtilsTest.php index 2e9fc8903..0990aadc7 100755 --- a/tests/Utils/ArrayUtilsTest.php +++ b/tests/Utils/ArrayUtilsTest.php @@ -242,8 +242,8 @@ final class ArrayUtilsTest extends \PHPUnit\Framework\TestCase */ public function testArgHas() : void { - if (ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? null) !== null) { - self::assertGreaterThan(0, ArrayUtils::hasArg('--configuration', $_SERVER['argv'] ?? null)); + if (ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? []) !== null) { + self::assertGreaterThan(0, ArrayUtils::hasArg('--configuration', $_SERVER['argv'] ?? [])); } } @@ -254,7 +254,7 @@ final class ArrayUtilsTest extends \PHPUnit\Framework\TestCase */ public function testInvalidArgHas() : void { - self::assertEquals(-1, ArrayUtils::hasArg('--testNull', $_SERVER['argv'] ?? null)); + self::assertEquals(-1, ArrayUtils::hasArg('--testNull', $_SERVER['argv'] ?? [])); } /** @@ -264,8 +264,8 @@ final class ArrayUtilsTest extends \PHPUnit\Framework\TestCase */ public function testArgGet() : void { - if (ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? null) !== null) { - self::assertTrue(\stripos(ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? null), '.xml') !== false); + if (ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? []) !== null) { + self::assertTrue(\stripos(ArrayUtils::getArg('--configuration', $_SERVER['argv'] ?? []), '.xml') !== false); } } @@ -276,7 +276,7 @@ final class ArrayUtilsTest extends \PHPUnit\Framework\TestCase */ public function testInvalidArgGet() : void { - self::assertNull(ArrayUtils::getArg('--testNull', $_SERVER['argv'] ?? null)); + self::assertNull(ArrayUtils::getArg('--testNull', $_SERVER['argv'] ?? [])); } /** diff --git a/tests/Utils/Barcode/DatamatrixTest.php b/tests/Utils/Barcode/DatamatrixTest.php index 794c46297..fa3020cbd 100755 --- a/tests/Utils/Barcode/DatamatrixTest.php +++ b/tests/Utils/Barcode/DatamatrixTest.php @@ -14,13 +14,53 @@ declare(strict_types=1); namespace phpOMS\tests\Utils\Barcode; +use phpOMS\Utils\Barcode\Datamatrix; + /** * @internal */ final class DatamatrixTest extends \PHPUnit\Framework\TestCase { - public function testPlaceholder() : void + protected function setUp() : void { - self::markTestIncomplete(); + if (!\extension_loaded('gd')) { + $this->markTestSkipped( + 'The GD extension is not available.' + ); + } + } + + /** + * @covers phpOMS\Utils\Barcode\Datamatrix + * @group framework + */ + public function testImagePng() : void + { + $path = __DIR__ . '/datamatrix.png'; + if (\is_file($path)) { + \unlink($path); + } + + $img = new Datamatrix('https://jingga.app', 200, 50); + $img->saveToPngFile($path); + + self::assertFileExists($path); + } + + /** + * @covers phpOMS\Utils\Barcode\Datamatrix + * @group framework + */ + public function testImageJpg() : void + { + $path = __DIR__ . '/datamatrix.jpg'; + if (\is_file($path)) { + \unlink($path); + } + + $img = new Datamatrix('https://jingga.app', 200, 50); + $img->saveToJpgFile($path); + + self::assertFileExists($path); } } diff --git a/tests/Utils/Barcode/QRTest.php b/tests/Utils/Barcode/QRTest.php index ad88bf89d..524d659b0 100755 --- a/tests/Utils/Barcode/QRTest.php +++ b/tests/Utils/Barcode/QRTest.php @@ -14,13 +14,53 @@ declare(strict_types=1); namespace phpOMS\tests\Utils\Barcode; +use phpOMS\Utils\Barcode\QR; + /** * @internal */ final class QRTest extends \PHPUnit\Framework\TestCase { - public function testPlaceholder() : void + protected function setUp() : void { - self::markTestIncomplete(); + if (!\extension_loaded('gd')) { + $this->markTestSkipped( + 'The GD extension is not available.' + ); + } + } + + /** + * @covers phpOMS\Utils\Barcode\QR + * @group framework + */ + public function testImagePng() : void + { + $path = __DIR__ . '/qr.png'; + if (\is_file($path)) { + \unlink($path); + } + + $img = new QR('https://jingga.app', 200, 200); + $img->saveToPngFile($path); + + self::assertFileExists($path); + } + + /** + * @covers phpOMS\Utils\Barcode\QR + * @group framework + */ + public function testImageJpg() : void + { + $path = __DIR__ . '/qr.jpg'; + if (\is_file($path)) { + \unlink($path); + } + + $img = new QR('https://jingga.app', 200, 200); + $img->saveToJpgFile($path); + + self::assertFileExists($path); } } diff --git a/tests/Utils/Barcode/datamatrix.jpg b/tests/Utils/Barcode/datamatrix.jpg new file mode 100644 index 000000000..506195b73 Binary files /dev/null and b/tests/Utils/Barcode/datamatrix.jpg differ diff --git a/tests/Utils/Barcode/datamatrix.png b/tests/Utils/Barcode/datamatrix.png new file mode 100644 index 000000000..8d7bd896e Binary files /dev/null and b/tests/Utils/Barcode/datamatrix.png differ diff --git a/tests/Utils/Barcode/qr.jpg b/tests/Utils/Barcode/qr.jpg new file mode 100644 index 000000000..1b30d6089 Binary files /dev/null and b/tests/Utils/Barcode/qr.jpg differ diff --git a/tests/Utils/Barcode/qr.png b/tests/Utils/Barcode/qr.png new file mode 100644 index 000000000..a2874af83 Binary files /dev/null and b/tests/Utils/Barcode/qr.png differ diff --git a/tests/Utils/Converter/CurrencyTest.php b/tests/Utils/Converter/CurrencyTest.php index 73f863af6..5922c823d 100755 --- a/tests/Utils/Converter/CurrencyTest.php +++ b/tests/Utils/Converter/CurrencyTest.php @@ -92,9 +92,7 @@ final class CurrencyTest extends \PHPUnit\Framework\TestCase */ public function testInvalidFromEur() : void { - $this->expectException(\InvalidArgumentException::class); - - Currency::fromEurTo(1, 'ERROR'); + self::assertLessThan(0, Currency::fromEurTo(1, 'ERROR')); } /** @@ -104,9 +102,7 @@ final class CurrencyTest extends \PHPUnit\Framework\TestCase */ public function testInvalidToEur() : void { - $this->expectException(\InvalidArgumentException::class); - - Currency::fromToEur(1, 'ERROR'); + self::assertLessThan(0, Currency::fromToEur(1, 'ERROR')); } /** @@ -116,8 +112,6 @@ final class CurrencyTest extends \PHPUnit\Framework\TestCase */ public function testInvalidConvert() : void { - $this->expectException(\InvalidArgumentException::class); - - Currency::convertCurrency(1, 'ERROR', 'TEST'); + self::assertLessThan(0, Currency::convertCurrency(1, 'ERROR', 'TEST')); } } diff --git a/tests/Utils/ImageUtilsTest.php b/tests/Utils/ImageUtilsTest.php index 81371b08a..fb821d3e6 100755 --- a/tests/Utils/ImageUtilsTest.php +++ b/tests/Utils/ImageUtilsTest.php @@ -25,6 +25,32 @@ use phpOMS\Utils\ImageUtils; */ final class ImageUtilsTest extends \PHPUnit\Framework\TestCase { + public function testLightness() : void + { + self::assertEquals(0.0, ImageUtils::lightness(0)); + self::assertEquals(1.0, ImageUtils::lightness(16777216)); + } + + public function testLightnessFromRgb() : void + { + self::assertEquals(0.0, ImageUtils::lightnessFromRgb(0, 0, 0)); + self::assertEquals(1.0, ImageUtils::lightnessFromRgb(255, 255, 255)); + } + + public function testResize() : void + { + ImageUtils::resize(__DIR__ . '/logo.png', __DIR__ . '/logo_resized.png', 256, 256); + self::assertTrue(\is_file(__DIR__ . '/logo_resized.png')); + } + + public function testDifference() : void + { + $diff = ImageUtils::difference(__DIR__ . '/img1.png', __DIR__ . '/img2.png', __DIR__ . '/diff1.png', 0); + $diff = ImageUtils::difference(__DIR__ . '/img1.png', __DIR__ . '/img2.png', __DIR__ . '/diff2.png', 1); + + self::assertGreaterThan(0, $diff); + } + /** * @testdox Base64 image data can be decoded to an image * @covers phpOMS\Utils\ImageUtils diff --git a/tests/Utils/diff1.png b/tests/Utils/diff1.png new file mode 100644 index 000000000..cfb531542 Binary files /dev/null and b/tests/Utils/diff1.png differ diff --git a/tests/Utils/diff2.png b/tests/Utils/diff2.png new file mode 100644 index 000000000..271d21639 Binary files /dev/null and b/tests/Utils/diff2.png differ diff --git a/tests/Utils/img1.png b/tests/Utils/img1.png new file mode 100644 index 000000000..548b5e4f9 Binary files /dev/null and b/tests/Utils/img1.png differ diff --git a/tests/Utils/img2.png b/tests/Utils/img2.png new file mode 100644 index 000000000..d9705d257 Binary files /dev/null and b/tests/Utils/img2.png differ diff --git a/tests/Utils/logo_resized.png b/tests/Utils/logo_resized.png new file mode 100644 index 000000000..31a4f5706 Binary files /dev/null and b/tests/Utils/logo_resized.png differ diff --git a/tests/phpunit_no_coverage.xml b/tests/phpunit_no_coverage.xml index 7d26b9823..d485ca45f 100755 --- a/tests/phpunit_no_coverage.xml +++ b/tests/phpunit_no_coverage.xml @@ -15,6 +15,7 @@ *Testapp* ./vendor ../vendor + ../Localization/LanguageDetection/resources @@ -32,6 +33,7 @@ volume maybe + slow