diff --git a/DataStorage/Cookie/CookieJar.php b/DataStorage/Cookie/CookieJar.php index 3b05fe661..e0b610bcc 100644 --- a/DataStorage/Cookie/CookieJar.php +++ b/DataStorage/Cookie/CookieJar.php @@ -29,14 +29,6 @@ namespace phpOMS\DataStorage\Cookie; */ class CookieJar { - /** - * Cookie values. - * - * @var array - * @since 1.0.0 - */ - private $cookies = []; - /** * Locked. * @@ -44,6 +36,13 @@ class CookieJar * @since 1.0.0 */ private static $isLocked = false; + /** + * Cookie values. + * + * @var array + * @since 1.0.0 + */ + private $cookies = []; /** * Constructor. @@ -56,6 +55,30 @@ class CookieJar $this->cookies = $_COOKIE; } + /** + * Lock + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function lock() + { + self::$isLocked = true; + } + + /** + * Is locked? + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function isLocked() : bool + { + return self::$isLocked; + } + /** * Set pending cookie * @@ -91,6 +114,22 @@ class CookieJar return false; } + /** + * Delete already set cookie + * + * @param string $id Cookie id to remove + * + * @return void + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function delete(string $id) + { + $this->remove($id); + setcookie($id, '', time() - 3600); + } + /** * Remove pending cookie * @@ -112,22 +151,6 @@ class CookieJar return false; } - /** - * Delete already set cookie - * - * @param string $id Cookie id to remove - * - * @return void - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function delete(string $id) - { - $this->remove($id); - setcookie($id, '', time() - 3600); - } - /** * Save cookie * @@ -144,28 +167,4 @@ class CookieJar setcookie($key, $cookie['value'], $cookie['expiry'], $cookie['path'], $cookie['domain'], $cookie['secure'], $cookie['httponly']); } } - - /** - * Lock - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function lock() - { - self::$isLocked = true; - } - - /** - * Is locked? - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function isLocked() : bool - { - return self::$isLocked; - } } diff --git a/DataStorage/Database/DataMapperAbstract.php b/DataStorage/Database/DataMapperAbstract.php index c03e084af..0bbc6d83a 100644 --- a/DataStorage/Database/DataMapperAbstract.php +++ b/DataStorage/Database/DataMapperAbstract.php @@ -409,7 +409,7 @@ class DataMapperAbstract implements DataMapperInterface } elseif ($column['type'] === 'Serializable') { $value = $value->serialize(); } elseif ($column['type'] === 'jsonSerializable') { - $value = $value->jsonSerializable(); + $value = $value->jsonSerializable(); } elseif (is_object($value)) { $value = $value->getId(); } diff --git a/DataStorage/Database/GrammarAbstract.php b/DataStorage/Database/GrammarAbstract.php index 05e5d39c5..c3e716bd3 100644 --- a/DataStorage/Database/GrammarAbstract.php +++ b/DataStorage/Database/GrammarAbstract.php @@ -99,6 +99,21 @@ abstract class GrammarAbstract abstract protected function compileComponents(BuilderAbstract $query) : array; + public function getDateFormat() : string + { + return 'Y-m-d H:i:s'; + } + + public function getTablePrefix() : string + { + return $this->tablePrefix; + } + + public function setTablePrefix(string $prefix) + { + $this->tablePrefix = $prefix; + } + /** * Expressionize elements. * @@ -158,19 +173,4 @@ abstract class GrammarAbstract } } - public function getDateFormat() : string - { - return 'Y-m-d H:i:s'; - } - - public function getTablePrefix() : string - { - return $this->tablePrefix; - } - - public function setTablePrefix(string $prefix) - { - $this->tablePrefix = $prefix; - } - } diff --git a/DataStorage/Database/Schema/Exception/TableException.php b/DataStorage/Database/Schema/Exception/TableException.php index 6151c5108..de2d14a8e 100644 --- a/DataStorage/Database/Schema/Exception/TableException.php +++ b/DataStorage/Database/Schema/Exception/TableException.php @@ -46,7 +46,7 @@ class TableException extends \PDOException /** * Get table name from exception. * - * @param string $message Exception message + * @param string $message Exception message * * @return string * diff --git a/DataStorage/Session/HttpSession.php b/DataStorage/Session/HttpSession.php index 3ddbe54d0..086bd76c5 100644 --- a/DataStorage/Session/HttpSession.php +++ b/DataStorage/Session/HttpSession.php @@ -32,16 +32,6 @@ use phpOMS\Utils\RnG\StringUtils; class HttpSession implements SessionInterface { - private $sessionData = []; - - /** - * Session ID. - * - * @var string|int - * @since 1.0.0 - */ - private $sid = null; - /** * Is session locked/already set. * @@ -49,6 +39,14 @@ class HttpSession implements SessionInterface * @since 1.0.0 */ private static $isLocked = false; + private $sessionData = []; + /** + * Session ID. + * + * @var string|int + * @since 1.0.0 + */ + private $sid = null; /** * Constructor. @@ -100,14 +98,6 @@ class HttpSession implements SessionInterface UriFactory::setQuery('$CSRF', $CSRF); } - /** - * {@inheritdoc} - */ - public function get($key) - { - return $this->sessionData[$key] ?? null; - } - /** * {@inheritdoc} */ @@ -122,6 +112,24 @@ class HttpSession implements SessionInterface return false; } + /** + * {@inheritdoc} + */ + public function get($key) + { + return $this->sessionData[$key] ?? null; + } + + public static function lock() + { + self::$isLocked = true; + } + + public static function isLocked() + { + return self::$isLocked; + } + /** * {@inheritdoc} */ @@ -166,14 +174,4 @@ class HttpSession implements SessionInterface session_write_close(); } - public static function lock() - { - self::$isLocked = true; - } - - public static function isLocked() - { - return self::$isLocked; - } - } diff --git a/Math/Differential/FiniteDifference.php b/Math/Differential/FiniteDifference.php index 039a48bbc..393ba0a21 100644 --- a/Math/Differential/FiniteDifference.php +++ b/Math/Differential/FiniteDifference.php @@ -15,6 +15,7 @@ */ namespace phpOMS\Math\Differential; + use phpOMS\Math\Parser\Evaluator; /** diff --git a/Math/Geometry/ConvexHull/MonotoneChain.php b/Math/Geometry/ConvexHull/MonotoneChain.php index b59920a2d..ccf75f508 100644 --- a/Math/Geometry/ConvexHull/MonotoneChain.php +++ b/Math/Geometry/ConvexHull/MonotoneChain.php @@ -26,10 +26,56 @@ namespace phpOMS\Math\Geometry; * @link http://orange-management.com * @since 1.0.0 * - * @todo: implement vertice class or use vertice class used by graphs? May be usefull in order to give vertices IDs! + * @todo : implement vertice class or use vertice class used by graphs? May be usefull in order to give vertices IDs! */ final class MonotoneChain { + /** + * Create convex hull + * + * @param array $points Points (Point Cloud) + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function createConvexHull(array $points) : array + { + if (($n = count($points)) > 1) { + $k = 0; + $h = []; + + uasort($points, [self::class, 'sort']); + + // Lower hull + for ($i = 0; $i < $n; ++$i) { + while ($k >= 2 && self::cross($h[$k - 2], $h[$k - 1], $points[$i]) <= 0) { + $k--; + } + + $h[$k++] = $points[$i]; + } + + // Upper hull + for ($i = $n - 2, $t = $k + 1; $i >= 0; $i--) { + while ($k >= $t && self::cross($h[$k - 2], $h[$k - 1], $points[$i]) <= 0) { + $k--; + } + + $h[$k++] = $points[$i]; + } + + if ($k > 1) { + $h = array_splice($h, $k - 1); + } + + return $h; + } + + return $points; + } + /** * Counter clock wise turn? * @@ -62,50 +108,4 @@ final class MonotoneChain { return $a['x'] === $b['x'] ? $a['y'] - $b['y'] : $a['x'] - $b['x']; } - - /** - * Create convex hull - * - * @param array $points Points (Point Cloud) - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function createConvexHull(array $points) : array - { - if (($n = count($points)) > 1) { - $k = 0; - $h = []; - - uasort($points, [self::class, 'sort']); - - // Lower hull - for ($i = 0; $i < $n; ++$i) { - while ($k >= 2 && self::cross($h[$k - 2], $h[$k - 1], $points[$i]) <= 0) { - $k--; - } - - $h[$k++] = $points[$i]; - } - - // Upper hull - for ($i = $n - 2, $t = $k + 1; $i >= 0; $i--) { - while ($k >= $t && self::cross($h[$k - 2], $h[$k - 1], $points[$i]) <= 0) { - $k--; - } - - $h[$k++] = $points[$i]; - } - - if ($k > 1) { - $h = array_splice($h, $k - 1); - } - - return $h; - } - - return $points; - } } \ No newline at end of file diff --git a/Math/Matrix/Matrix.php b/Math/Matrix/Matrix.php index a66e20182..69cfae480 100644 --- a/Math/Matrix/Matrix.php +++ b/Math/Matrix/Matrix.php @@ -80,6 +80,176 @@ class Matrix implements \ArrayAccess, \Iterator } } + /** + * Set value. + * + * @param int $m Row + * @param int $n Column + * @param int $value Value + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function set(int $m, int $n, $value) + { + if (!isset($this->matrix[$m][$n])) { + throw new \Exception('Dimension'); + } + + $this->matrix[$m][$n] = $value; + } + + /** + * Get value. + * + * @param int $m Row + * @param int $n Column + * + * @return mixed + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function get(int $m, int $n) + { + if (!isset($this->matrix[$m][$n])) { + throw new \Exception('Dimension'); + } + + return $this->matrix[$m][$n]; + } + + /** + * Transpose matrix. + * + * @return Matrix + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function transpose() : Matrix + { + $matrix = new Matrix($this->n, $this->m); + $matrix->setMatrix(array_map(null, $matrix->getMatrix())); + + return $matrix; + } + + /** + * Get matrix array. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getMatrix() : array + { + return $this->matrix; + } + + /** + * Set matrix array. + * + * @param array $matrix Matrix + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setMatrix(array $matrix) + { + if ($this->m !== count($matrix) || $this->n !== count($matrix[0])) { + throw new \Exception('Dimension'); + } + + $this->matrix = $matrix; + } + + /** + * Subtract right. + * + * @param mixed $value Value + * + * @return Matrix + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function sub($value) : Matrix + { + if ($value instanceOf Matrix) { + return $this->add($this->mult(-1)); + } elseif (is_scalar($value)) { + return $this->add(-$value); + } + + throw new \Exception('Type'); + } + + /** + * Add right. + * + * @param mixed $value Value + * + * @return Matrix + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function add($value) : Matrix + { + if ($value instanceOf Matrix) { + return $this->addMatrix($value); + } elseif (is_scalar($value)) { + return $this->addScalar($value); + } + + throw new \Exception(); + } + + /** + * Add matrix. + * + * @param Matrix $matrix Matrix to add + * + * @return Matrix + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function addMatrix(Matrix $matrix) : Matrix + { + if ($this->m !== $matrix->getM() || $this->n !== $matrix->getN()) { + throw new \Exception('Dimension'); + } + + $matrixArr = $matrix->getMatrix(); + $newMatrixArr = $this->matrix; + + foreach ($newMatrixArr as $i => $vector) { + foreach ($vector as $j => $value) { + $newMatrixArr[$i][$j] += $matrixArr[$i][$j]; + } + } + + $newMatrix = new Matrix($this->m, $this->n); + $newMatrix->setMatrix($newMatrixArr); + + return $newMatrix; + } + /** * Get matrix rows. * @@ -107,94 +277,31 @@ class Matrix implements \ArrayAccess, \Iterator } /** - * Set matrix array. + * Add scalar. * - * @param array $matrix Matrix + * @param mixed $scalar Scalar + * + * @return Matrix * * @throws \Exception * * @since 1.0.0 * @author Dennis Eichhorn */ - public function setMatrix(array $matrix) + private function addScalar($scalar) : Matrix { - if ($this->m !== count($matrix) || $this->n !== count($matrix[0])) { - throw new \Exception('Dimension'); + $newMatrixArr = $this->matrix; + + foreach ($newMatrixArr as $i => $vector) { + foreach ($vector as $j => $value) { + $newMatrixArr[$i][$j] += $scalar; + } } - $this->matrix = $matrix; - } + $newMatrix = new Matrix($this->m, $this->n); + $newMatrix->setMatrix($newMatrixArr); - /** - * Get matrix array. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getMatrix() : array - { - return $this->matrix; - } - - /** - * Set value. - * - * @param int $m Row - * @param int $n Column - * @param int $value Value - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function set(int $m, int $n, $value) - { - if(!isset($this->matrix[$m][$n])) { - throw new \Exception('Dimension'); - } - - $this->matrix[$m][$n] = $value; - } - - /** - * Get value. - * - * @param int $m Row - * @param int $n Column - * - * @return mixed - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function get(int $m, int $n) - { - if(!isset($this->matrix[$m][$n])) { - throw new \Exception('Dimension'); - } - - return $this->matrix[$m][$n]; - } - - /** - * Transpose matrix. - * - * @return Matrix - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function transpose() : Matrix - { - $matrix = new Matrix($this->n, $this->m); - $matrix->setMatrix(array_map(null, $matrix->getMatrix())); - - return $matrix; + return $newMatrix; } /** @@ -290,113 +397,6 @@ class Matrix implements \ArrayAccess, \Iterator return $newMatrix; } - /** - * Add right. - * - * @param mixed $value Value - * - * @return Matrix - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function add($value) : Matrix - { - if ($value instanceOf Matrix) { - return $this->addMatrix($value); - } elseif (is_scalar($value)) { - return $this->addScalar($value); - } - - throw new \Exception(); - } - - /** - * Subtract right. - * - * @param mixed $value Value - * - * @return Matrix - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function sub($value) : Matrix - { - if ($value instanceOf Matrix) { - return $this->add($this->mult(-1)); - } elseif (is_scalar($value)) { - return $this->add(-$value); - } - - throw new \Exception('Type'); - } - - /** - * Add matrix. - * - * @param Matrix $matrix Matrix to add - * - * @return Matrix - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function addMatrix(Matrix $matrix) : Matrix - { - if ($this->m !== $matrix->getM() || $this->n !== $matrix->getN()) { - throw new \Exception('Dimension'); - } - - $matrixArr = $matrix->getMatrix(); - $newMatrixArr = $this->matrix; - - foreach ($newMatrixArr as $i => $vector) { - foreach ($vector as $j => $value) { - $newMatrixArr[$i][$j] += $matrixArr[$i][$j]; - } - } - - $newMatrix = new Matrix($this->m, $this->n); - $newMatrix->setMatrix($newMatrixArr); - - return $newMatrix; - } - - /** - * Add scalar. - * - * @param mixed $scalar Scalar - * - * @return Matrix - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function addScalar($scalar) : Matrix - { - $newMatrixArr = $this->matrix; - - foreach ($newMatrixArr as $i => $vector) { - foreach ($vector as $j => $value) { - $newMatrixArr[$i][$j] += $scalar; - } - } - - $newMatrix = new Matrix($this->m, $this->n); - $newMatrix->setMatrix($newMatrixArr); - - return $newMatrix; - } - /** * Upper triangulize matrix. * @@ -416,6 +416,57 @@ class Matrix implements \ArrayAccess, \Iterator return $matrix; } + /** + * Trianglize matrix. + * + * @param array $arr Matrix to trianglize + * + * @return int Det sign + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function upperTrianglize(array &$arr) : int + { + $n = count($arr); + $sign = 1; + + for ($i = 0; $i < $n; $i++) { + $max = 0; + + for ($j = $i; $j < $n; $j++) { + if (abs($arr[$j][$i]) > abs($arr[$max][$i])) { + $max = $j; + } + } + + if ($max) { + $sign = -$sign; + $temp = $arr[$i]; + $arr[$i] = $arr[$max]; + $arr[$max] = $temp; + } + + if (!$arr[$i][$i]) { + return 0; + } + + for ($j = $i + 1; $j < $n; $j++) { + $r = $arr[$j][$i] / $arr[$i][$i]; + + if (!$r) { + continue; + } + + for ($c = $i; $c < $n; $c++) { + $arr[$j][$c] -= $arr[$i][$c] * $r; + } + } + } + + return $sign; + } + /** * Lower triangulize matrix. * @@ -506,36 +557,6 @@ class Matrix implements \ArrayAccess, \Iterator return $newMatrix; } - /** - * Decompose matrix using cholesky algorithm. - * - * @return Matrix - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function decompositionCholesky() : Matrix - { - $newMatrix = new Matrix($this->n, $this->n); - $newMatrixArr = $newMatrix->getMatrix(); - - for ($i = 0; $i < $this->n; $i++) { - for ($j = 0; $j < $i + 1; $j++) { - $temp = 0; - - for ($c = 0; $c < $j; $c++) { - $temp += $newMatrixArr[$i][$c] * $newMatrixArr[$j][$c]; - } - - $newMatrixArr[$i][$j] = ($i == $j) ? sqrt($this->matrix[$i][$i] - $temp) : (1 / $newMatrixArr[$j][$j] * ($this->matrix[$i][$j] - $temp)); - } - } - - $newMatrix->setMatrix($newMatrixArr); - - return $newMatrix; - } - /** * Diagonalize matrix. * @@ -577,57 +598,6 @@ class Matrix implements \ArrayAccess, \Iterator return $arr; } - /** - * Trianglize matrix. - * - * @param array $arr Matrix to trianglize - * - * @return int Det sign - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function upperTrianglize(array &$arr) : int - { - $n = count($arr); - $sign = 1; - - for ($i = 0; $i < $n; $i++) { - $max = 0; - - for ($j = $i; $j < $n; $j++) { - if (abs($arr[$j][$i]) > abs($arr[$max][$i])) { - $max = $j; - } - } - - if ($max) { - $sign = -$sign; - $temp = $arr[$i]; - $arr[$i] = $arr[$max]; - $arr[$max] = $temp; - } - - if (!$arr[$i][$i]) { - return 0; - } - - for ($j = $i + 1; $j < $n; $j++) { - $r = $arr[$j][$i] / $arr[$i][$i]; - - if (!$r) { - continue; - } - - for ($c = $i; $c < $n; $c++) { - $arr[$j][$c] -= $arr[$i][$c] * $r; - } - } - } - - return $sign; - } - /** * Calculate det. * @@ -663,6 +633,22 @@ class Matrix implements \ArrayAccess, \Iterator return $this->offsetGet($this->position); } + /** + * Offset to retrieve + * @link http://php.net/manual/en/arrayaccess.offsetget.php + * @param mixed $offset

+ * The offset to retrieve. + *

+ * @return mixed Can return all value types. + * @since 5.0.0 + */ + public function offsetGet($offset) + { + $row = (int) ($offset / $this->m); + + return $this->matrix[$row][$offset - $row * $this->n]; + } + /** * Move forward to next element * @link http://php.net/manual/en/iterator.next.php @@ -697,17 +683,6 @@ class Matrix implements \ArrayAccess, \Iterator $this->offsetExists($this->position); } - /** - * Rewind the Iterator to the first element - * @link http://php.net/manual/en/iterator.rewind.php - * @return void Any returned value is ignored. - * @since 5.0.0 - */ - public function rewind() - { - $this->position = 0; - } - /** * Whether a offset exists * @link http://php.net/manual/en/arrayaccess.offsetexists.php @@ -722,23 +697,20 @@ class Matrix implements \ArrayAccess, \Iterator */ public function offsetExists($offset) { - $row = (int) ($offset/$this->m); + $row = (int) ($offset / $this->m); + return isset($this->matrix[$row][$offset - $row * $this->n]); } /** - * Offset to retrieve - * @link http://php.net/manual/en/arrayaccess.offsetget.php - * @param mixed $offset

- * The offset to retrieve. - *

- * @return mixed Can return all value types. + * Rewind the Iterator to the first element + * @link http://php.net/manual/en/iterator.rewind.php + * @return void Any returned value is ignored. * @since 5.0.0 */ - public function offsetGet($offset) + public function rewind() { - $row = (int) ($offset/$this->m); - return $this->matrix[$row][$offset - $row * $this->n]; + $this->position = 0; } /** @@ -755,7 +727,7 @@ class Matrix implements \ArrayAccess, \Iterator */ public function offsetSet($offset, $value) { - $row = (int) ($offset/$this->m); + $row = (int) ($offset / $this->m); $this->matrix[$row][$offset - $row * $this->n] = $value; } @@ -770,7 +742,37 @@ class Matrix implements \ArrayAccess, \Iterator */ public function offsetUnset($offset) { - $row = (int) ($offset/$this->m); + $row = (int) ($offset / $this->m); unset($this->matrix[$row][$offset - $row * $this->n]); } + + /** + * Decompose matrix using cholesky algorithm. + * + * @return Matrix + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function decompositionCholesky() : Matrix + { + $newMatrix = new Matrix($this->n, $this->n); + $newMatrixArr = $newMatrix->getMatrix(); + + for ($i = 0; $i < $this->n; $i++) { + for ($j = 0; $j < $i + 1; $j++) { + $temp = 0; + + for ($c = 0; $c < $j; $c++) { + $temp += $newMatrixArr[$i][$c] * $newMatrixArr[$j][$c]; + } + + $newMatrixArr[$i][$j] = ($i == $j) ? sqrt($this->matrix[$i][$i] - $temp) : (1 / $newMatrixArr[$j][$j] * ($this->matrix[$i][$j] - $temp)); + } + } + + $newMatrix->setMatrix($newMatrixArr); + + return $newMatrix; + } } \ No newline at end of file diff --git a/Math/Number/Integer.php b/Math/Number/Integer.php index 7705f7fe9..ae85cac73 100644 --- a/Math/Number/Integer.php +++ b/Math/Number/Integer.php @@ -44,33 +44,6 @@ class Integer return is_int($value); } - /** - * Greatest common diviser. - * - * @param int $n Number one - * @param int $m Number two - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function greatestCommonDivisor(int $n, int $m) : int - { - while (true) { - if ($n === $m) { - return $m; - } - if ($n > $m) { - $n -= $m; - } else { - $m -= $n; - } - } - - return 1; - } - /** * Trial factorization. * @@ -139,6 +112,33 @@ class Integer return $factor; } + /** + * Greatest common diviser. + * + * @param int $n Number one + * @param int $m Number two + * + * @return int + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function greatestCommonDivisor(int $n, int $m) : int + { + while (true) { + if ($n === $m) { + return $m; + } + if ($n > $m) { + $n -= $m; + } else { + $m -= $n; + } + } + + return 1; + } + /** * Fermat factorization of odd integers. * @@ -154,7 +154,7 @@ class Integer */ public static function fermatFactor(int $value, int $limit = 1000000) : int { - if(($value % 2) !== 0) { + if (($value % 2) !== 0) { throw new \Exception('Only odd integers are allowed'); } diff --git a/Math/Optimization/GaussianElimination.php b/Math/Optimization/GaussianElimination.php index 3269d6b6d..d0d5e49b3 100644 --- a/Math/Optimization/GaussianElimination.php +++ b/Math/Optimization/GaussianElimination.php @@ -29,39 +29,11 @@ use phpOMS\Math\Matrix\Matrix; */ class GaussianElimination { - /** - * Swap rows. - * - * @param array $a Matrix A - * @param array $b Vector b - * @param int $r1 Row 1 - * @param int $r2 Row 2 - * - * @return void - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private static function swapRows(&$a, &$b, int $r1, int $r2) - { - if ($r1 == $r2) { - return; - } - - $tmp = $a[$r1]; - $a[$r1] = $a[$r2]; - $a[$r2] = $tmp; - - $tmp = $b[$r1]; - $b[$r1] = $b[$r2]; - $b[$r2] = $tmp; - } - /** * Solve equation with gaussian elimination. * - * @param Matrix $A Matrix A - * @param Matrix $b Vector b + * @param Matrix $A Matrix A + * @param Matrix $b Vector b * * @return Matrix * @@ -117,4 +89,32 @@ class GaussianElimination return $Y; } + + /** + * Swap rows. + * + * @param array $a Matrix A + * @param array $b Vector b + * @param int $r1 Row 1 + * @param int $r2 Row 2 + * + * @return void + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private static function swapRows(&$a, &$b, int $r1, int $r2) + { + if ($r1 == $r2) { + return; + } + + $tmp = $a[$r1]; + $a[$r1] = $a[$r2]; + $a[$r2] = $tmp; + + $tmp = $b[$r1]; + $b[$r1] = $b[$r2]; + $b[$r2] = $tmp; + } } \ No newline at end of file diff --git a/Math/Optimization/TSP/City.php b/Math/Optimization/TSP/City.php index 62e32accd..c810315f2 100644 --- a/Math/Optimization/TSP/City.php +++ b/Math/Optimization/TSP/City.php @@ -72,29 +72,18 @@ class City } /** - * Get longitude. + * Is equals to. * - * @return float + * @param City $city City + * + * @return bool * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getLongitude() : float + public function equals(City $city) : bool { - return $this->long; - } - - /** - * Get latitude. - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getLatitude() : float - { - return $this->lat; + return $this->name === $city->getName() && $this->lat === $city->getLatitude() && $this->long === $city->getLatitude(); } /** @@ -111,18 +100,16 @@ class City } /** - * Is equals to. + * Get latitude. * - * @param City $city City - * - * @return bool + * @return float * * @since 1.0.0 * @author Dennis Eichhorn */ - public function equals(City $city) : bool + public function getLatitude() : float { - return $this->name === $city->getName() && $this->lat === $city->getLatitude() && $this->long === $city->getLatitude(); + return $this->lat; } /** @@ -139,4 +126,17 @@ class City { return Sphere::distance2PointsOnSphere($this->lat, $this->long, $city->getLatitude(), $city->getLongitude()); } + + /** + * Get longitude. + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getLongitude() : float + { + return $this->long; + } } diff --git a/Math/Optimization/TSP/GA.php b/Math/Optimization/TSP/GA.php index 1a15400c0..a8a782fbb 100644 --- a/Math/Optimization/TSP/GA.php +++ b/Math/Optimization/TSP/GA.php @@ -108,6 +108,28 @@ class GA return $newPopulation; } + /** + * Find fittest + * + * @param Population $population Population to evaluate + * + * @return Tour + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function tournamentSelection(Population $population) : Tour + { + $tournament = new Population($this->cityPool, self::TOURNAMENT, false); + $populationSize = $population->count(); + + for ($i = 0; $i < self::TOURNAMENT; $i++) { + $tournament->add($population->get(mt_rand(0, $populationSize))); + } + + return $tournament->getFittest(); + } + /** * Crossover tours * @@ -181,26 +203,4 @@ class GA } } - /** - * Find fittest - * - * @param Population $population Population to evaluate - * - * @return Tour - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function tournamentSelection(Population $population) : Tour - { - $tournament = new Population($this->cityPool, self::TOURNAMENT, false); - $populationSize = $population->count(); - - for ($i = 0; $i < self::TOURNAMENT; $i++) { - $tournament->add($population->get(mt_rand(0, $populationSize))); - } - - return $tournament->getFittest(); - } - } diff --git a/Math/Optimization/TSP/Tour.php b/Math/Optimization/TSP/Tour.php index 3f6781de4..6b1b64a53 100644 --- a/Math/Optimization/TSP/Tour.php +++ b/Math/Optimization/TSP/Tour.php @@ -112,6 +112,33 @@ class Tour implements \Countable return $this->fitness; } + /** + * Get tour distance + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getDistance() : float + { + if ($this->distance === 0.0) { + $distance = 0.0; + + $count = count($this->cities); + + for ($i = 0; $i < $count; $i++) { + $dest = ($i + 1 < $count) ? $this->cities[$i + 1] : $this->cities[0]; + + $distance += $this->cities[$i]->getDistanceTo($dest); + } + + $this->distance = $distance; + } + + return $this->distance; + } + /** * Add city to tour. * @@ -146,33 +173,6 @@ class Tour implements \Countable $this->distance = 0.0; } - /** - * Get tour distance - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getDistance() : float - { - if ($this->distance === 0.0) { - $distance = 0.0; - - $count = count($this->cities); - - for ($i = 0; $i < $count; $i++) { - $dest = ($i + 1 < $count) ? $this->cities[$i + 1] : $this->cities[0]; - - $distance += $this->cities[$i]->getDistanceTo($dest); - } - - $this->distance = $distance; - } - - return $this->distance; - } - /** * Has city. * diff --git a/Math/Shape/D2/D2ShapeInterface.php b/Math/Shape/D2/D2ShapeInterface.php index 538c6ba1a..93c8f2a75 100644 --- a/Math/Shape/D2/D2ShapeInterface.php +++ b/Math/Shape/D2/D2ShapeInterface.php @@ -30,5 +30,5 @@ use phpOMS\Math\Shape\ShapeInterface; */ interface D2ShapeInterface extends ShapeInterface { - public static function getPerimeter() : float; + public static function getPerimeter() : float; } diff --git a/Math/Shape/D2/Polygon.php b/Math/Shape/D2/Polygon.php index 83291a4b3..cfcc16577 100644 --- a/Math/Shape/D2/Polygon.php +++ b/Math/Shape/D2/Polygon.php @@ -113,6 +113,84 @@ class Polygon implements D2ShapeInterface { } + /** + * Point polygon relative position + * + * @param array $point Point location + * + * @return int + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function pointInPolygon(array $point) : int + { + $length = count($this->coord); + + // Polygon has to start and end with same point + if ($this->coord[0]['x'] !== $this->coord[$length - 1]['x'] || $this->coord[0]['y'] !== $this->coord[$length - 1]['y']) { + $this->coord[] = $this->coord[0]; + } + + // On vertex? + if (self::isOnVertex($point, $this->coord)) { + return 0; + } + + // Inside or ontop? + $countIntersect = 0; + $this->coord_count = count($this->coord); + + // todo: return based on highest possibility not by first match + for ($i = 1; $i < $this->coord_count; $i++) { + $vertex1 = $this->coord[$i - 1]; + $vertex2 = $this->coord[$i]; + + if (abs($vertex1['y'] - $vertex2['y']) < self::EPSILON && abs($vertex1['y'] - $point['y']) < self::EPSILON && $point['x'] > min($vertex1['x'], $vertex2['x']) && $point['x'] < max($vertex1['x'], $vertex2['x'])) { + return 0; // boundary + } + + if ($point['y'] > min($vertex1['y'], $vertex2['y']) && $point['y'] <= max($vertex1['y'], $vertex2['y']) && $point['x'] <= max($vertex1['x'], $vertex2['x']) && abs($vertex1['y'] - $vertex2['y']) >= self::EPSILON) { + $xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x']; + + if (abs($xinters - $point['x']) < self::EPSILON) { + return 0; // boundary + } + + if (abs($vertex1['x'] - $vertex2['x']) < self::EPSILON || $point['x'] < $xinters) { + $countIntersect++; + } + } + } + + if ($countIntersect % 2 != 0) { + return -1; + } + + return 1; + } + + /** + * Is point on vertex? + * + * @param array $point Point location + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private static function isOnVertex(array $point) : bool + { + foreach ($this->coord as $vertex) { + if (abs($point['x'] - $vertex['x']) < self::EPSILON && abs($point['y'] - $vertex['y']) < self::EPSILON) { + return true; + } + } + + return false; + } + /** * Set polygon coordinates. * @@ -281,82 +359,4 @@ class Polygon implements D2ShapeInterface return $this->barycenter; } - - /** - * Point polygon relative position - * - * @param array $point Point location - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function pointInPolygon(array $point) : int - { - $length = count($this->coord); - - // Polygon has to start and end with same point - if ($this->coord[0]['x'] !== $this->coord[$length - 1]['x'] || $this->coord[0]['y'] !== $this->coord[$length - 1]['y']) { - $this->coord[] = $this->coord[0]; - } - - // On vertex? - if (self::isOnVertex($point, $this->coord)) { - return 0; - } - - // Inside or ontop? - $countIntersect = 0; - $this->coord_count = count($this->coord); - - // todo: return based on highest possibility not by first match - for ($i = 1; $i < $this->coord_count; $i++) { - $vertex1 = $this->coord[$i - 1]; - $vertex2 = $this->coord[$i]; - - if (abs($vertex1['y'] - $vertex2['y']) < self::EPSILON && abs($vertex1['y'] - $point['y']) < self::EPSILON && $point['x'] > min($vertex1['x'], $vertex2['x']) && $point['x'] < max($vertex1['x'], $vertex2['x'])) { - return 0; // boundary - } - - if ($point['y'] > min($vertex1['y'], $vertex2['y']) && $point['y'] <= max($vertex1['y'], $vertex2['y']) && $point['x'] <= max($vertex1['x'], $vertex2['x']) && abs($vertex1['y'] - $vertex2['y']) >= self::EPSILON) { - $xinters = ($point['y'] - $vertex1['y']) * ($vertex2['x'] - $vertex1['x']) / ($vertex2['y'] - $vertex1['y']) + $vertex1['x']; - - if (abs($xinters - $point['x']) < self::EPSILON) { - return 0; // boundary - } - - if (abs($vertex1['x'] - $vertex2['x']) < self::EPSILON || $point['x'] < $xinters) { - $countIntersect++; - } - } - } - - if ($countIntersect % 2 != 0) { - return -1; - } - - return 1; - } - - /** - * Is point on vertex? - * - * @param array $point Point location - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private static function isOnVertex(array $point) : bool - { - foreach ($this->coord as $vertex) { - if (abs($point['x'] - $vertex['x']) < self::EPSILON && abs($point['y'] - $vertex['y']) < self::EPSILON) { - return true; - } - } - - return false; - } } diff --git a/Math/Shape/D3/D3ShapeInterface.php b/Math/Shape/D3/D3ShapeInterface.php index 7e9a86058..9686f68c8 100644 --- a/Math/Shape/D3/D3ShapeInterface.php +++ b/Math/Shape/D3/D3ShapeInterface.php @@ -30,5 +30,5 @@ use phpOMS\Math\Shape\ShapeInterface; */ interface D2ShapeInterface extends ShapeInterface { - public static function getVolume() : float; + public static function getVolume() : float; } diff --git a/Math/Shape/D3/Sphere.php b/Math/Shape/D3/Sphere.php index 99cb7503f..18711b2b0 100644 --- a/Math/Shape/D3/Sphere.php +++ b/Math/Shape/D3/Sphere.php @@ -29,6 +29,11 @@ namespace phpOMS\Math\Shape\D3; class Sphere implements D3ShapeInterface { + public function __construct(float $radius) + { + $this->radius = $radius; + } + /** * Calculating the distance between two points on a sphere * @@ -63,19 +68,14 @@ class Sphere implements D3ShapeInterface return $angle * $radius; } - /** - * Volume - * - * @param float $r Radius - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getVolumeByRadius(float $r) + public static function byRadius(float $r) : Sphere { - return 4 / 3 * pi() * $r ** 3; + return new self($r); + } + + public static function byVolume(float $v) : Sphere + { + return new self(self::getRadiusByVolume($v)); } /** @@ -93,19 +93,9 @@ class Sphere implements D3ShapeInterface return pow($V * 3 / (4 * pi()), 1 / 3); } - /** - * Surface area - * - * @param float $r Radius - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getSurfaceByRadius(float $r) + public static function bySurface(float $s) : Sphere { - return 4 * pi() * $r ** 2; + return new self(self::getRadiusBySurface($s)); } /** @@ -123,34 +113,48 @@ class Sphere implements D3ShapeInterface return sqrt($S / (4 * pi())); } - public static function byRadius(float $r) : Sphere + public function getVolume() : float { - return new self($r); - } - - public static function byVolume(float $v) : Sphere - { - return new self(self::getRadiusByVolume($v)); - } - - public static function bySurface(float $s) : Sphere - { - return new self(self::getRadiusBySurface($s)); - } - - public function __construct(float $radius) { - $this->radius = $radius; - } - - public function getVolume() : float { return self::getVolumeByRadius($this->radius); } - public function getRadius() : float { + /** + * Volume + * + * @param float $r Radius + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getVolumeByRadius(float $r) + { + return 4 / 3 * pi() * $r ** 3; + } + + public function getRadius() : float + { return $this->radius; } - public function getSurface() : float { + public function getSurface() : float + { return self::getSurfaceByRadius($this->radius); } + + /** + * Surface area + * + * @param float $r Radius + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getSurfaceByRadius(float $r) + { + return 4 * pi() * $r ** 2; + } } diff --git a/Math/Shape/ShapeInterface.php b/Math/Shape/ShapeInterface.php index 57acd4ccc..3618dfec8 100644 --- a/Math/Shape/ShapeInterface.php +++ b/Math/Shape/ShapeInterface.php @@ -28,5 +28,5 @@ namespace phpOMS\Math\Shape; */ interface ShapeInterface { - public static function getSurface() : float; + public static function getSurface() : float; } diff --git a/Math/Statistic/Average.php b/Math/Statistic/Average.php index a7cbfa1ff..6cf1f4c5b 100644 --- a/Math/Statistic/Average.php +++ b/Math/Statistic/Average.php @@ -77,7 +77,7 @@ class Average { $count = count($x); - return $x[$count - 1] + $h * ($x[$count - 1] - $x[0]) / ($count - 1); + return $x[$count - 1] + $h * ($x[$count - 1] - $x[0]) / ($count - 1); } /** diff --git a/Math/Statistic/Forecast/ForecastIntervalMultiplier.php b/Math/Statistic/Forecast/ForecastIntervalMultiplier.php index 574227dd3..9945b0c3c 100644 --- a/Math/Statistic/Forecast/ForecastIntervalMultiplier.php +++ b/Math/Statistic/Forecast/ForecastIntervalMultiplier.php @@ -14,6 +14,7 @@ * @link http://orange-management.com */ namespace phpOMS\Math\Statistic\Forecast; + use phpOMS\Datatypes\Enum; /** diff --git a/Math/Statistic/Forecast/Forecasts.php b/Math/Statistic/Forecast/Forecasts.php index be28a6eac..b016750e3 100644 --- a/Math/Statistic/Forecast/Forecasts.php +++ b/Math/Statistic/Forecast/Forecasts.php @@ -30,8 +30,8 @@ class Forecast { /** * Get forecast interval. - * - * + * + * * * @param array $observed Dataset * @param array $forecasted Forecasted diff --git a/Math/Statistic/MeasureOfDispersion.php b/Math/Statistic/MeasureOfDispersion.php index c782bc3f3..2663a16a6 100644 --- a/Math/Statistic/MeasureOfDispersion.php +++ b/Math/Statistic/MeasureOfDispersion.php @@ -51,6 +51,73 @@ class MeasureOfDispersion return $start - $end; } + /** + * Calculage empirical variation coefficient. + * + * Example: ([4, 5, 9, 1, 3]) + * + * @param array $values Values + * + * @return float + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function empiricalVariationcoefficient(array $values) : float + { + $mean = Average::arithmeticMean($values); + + if ($mean === 0) { + throw new \Exception('Division zero'); + } + + return self::standardDeviation($values) / $mean; + } + + /** + * Calculage standard deviation. + * + * Example: ([4, 5, 9, 1, 3]) + * + * @param array $values Values + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function standardDeviation(array $values) : float + { + return sqrt(self::sampleVariance($values)); + } + + /** + * Calculage sample variance. + * + * Example: ([4, 5, 9, 1, 3]) + * + * @param array $values Values + * + * @return float + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function sampleVariance(array $values) : float + { + $count = count($values); + + if ($count < 2) { + throw new \Exception('Division zero'); + } + + return $count * self::empiricalVariance($values) / ($count - 1); + } + /** * Calculage empirical variance. * @@ -83,73 +150,6 @@ class MeasureOfDispersion return $sum / ($count - 1); } - /** - * Calculage sample variance. - * - * Example: ([4, 5, 9, 1, 3]) - * - * @param array $values Values - * - * @return float - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function sampleVariance(array $values) : float - { - $count = count($values); - - if ($count < 2) { - throw new \Exception('Division zero'); - } - - return $count * self::empiricalVariance($values) / ($count - 1); - } - - /** - * Calculage standard deviation. - * - * Example: ([4, 5, 9, 1, 3]) - * - * @param array $values Values - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function standardDeviation(array $values) : float - { - return sqrt(self::sampleVariance($values)); - } - - /** - * Calculage empirical variation coefficient. - * - * Example: ([4, 5, 9, 1, 3]) - * - * @param array $values Values - * - * @return float - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function empiricalVariationcoefficient(array $values) : float - { - $mean = Average::arithmeticMean($values); - - if ($mean === 0) { - throw new \Exception('Division zero'); - } - - return self::standardDeviation($values) / $mean; - } - /** * Calculage empirical covariance. * diff --git a/Math/Stochastic/Distribution/BinomialDistribution.php b/Math/Stochastic/Distribution/BinomialDistribution.php index 8806b0638..1fe29f17b 100644 --- a/Math/Stochastic/Distribution/BinomialDistribution.php +++ b/Math/Stochastic/Distribution/BinomialDistribution.php @@ -58,25 +58,6 @@ class BinomialDistribution } } - /** - * Get probability mass function. - * - * Formula: C(n, k) * p^k * (1-p)^(n-k) - * - * @param int $n - * @param int $k - * @param float $p - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getPmf(int $n, int $k, float $p) : float - { - return Functions::binomialCoefficient($n, $k) * pow($p, $k) * pow(1 - $p, $n - $k); - } - /** * Get moment generating function. * @@ -165,6 +146,25 @@ class BinomialDistribution return $sum; } + /** + * Get probability mass function. + * + * Formula: C(n, k) * p^k * (1-p)^(n-k) + * + * @param int $n + * @param int $k + * @param float $p + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getPmf(int $n, int $k, float $p) : float + { + return Functions::binomialCoefficient($n, $k) * pow($p, $k) * pow(1 - $p, $n - $k); + } + /** * Get expected value. * diff --git a/Math/Stochastic/Distribution/ChiSquaredDistribution.php b/Math/Stochastic/Distribution/ChiSquaredDistribution.php index 74ad69fc8..e6f5aa936 100644 --- a/Math/Stochastic/Distribution/ChiSquaredDistribution.php +++ b/Math/Stochastic/Distribution/ChiSquaredDistribution.php @@ -78,25 +78,6 @@ class ChiSquaredDistribution 100 => ['0.995' => 67.328, '0.99' => 70.065, '0.975' => 74.222, '0.95' => 77.929, '0.90' => 82.358, '0.10' => 118.498, '0.05' => 124.342, '0.025' => 129.561, '0.01' => 135.807, '0.005' => 140.169], ]; - /** - * Get degrees of freedom of array. - * - * @param array $values Value matrix or vector (N or NxM) - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getDegreesOfFreedom(array $values) : int - { - if (is_array($first = reset($values))) { - return (count($values) - 1) * (count($first) - 1); - } else { - return count($values) - 1; - } - } - /** * Test hypthesis. * @@ -146,6 +127,25 @@ class ChiSquaredDistribution return ['P' => $P, 'H0' => ($P > $significance), 'df' => $df]; } + /** + * Get degrees of freedom of array. + * + * @param array $values Value matrix or vector (N or NxM) + * + * @return int + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getDegreesOfFreedom(array $values) : int + { + if (is_array($first = reset($values))) { + return (count($values) - 1) * (count($first) - 1); + } else { + return count($values) - 1; + } + } + /** * Get probability density function. * diff --git a/Message/Http/Header.php b/Message/Http/Header.php index eb173cb4c..c1245f024 100644 --- a/Message/Http/Header.php +++ b/Message/Http/Header.php @@ -50,6 +50,69 @@ class Header extends HeaderAbstract $this->set('Content-Type', 'text/html; charset=utf-8'); } + /** + * {@inheritdoc} + */ + public function set(string $key, string $header, bool $overwrite = false) : bool + { + if (self::$isLocked) { + throw new \Exception('Already locked'); + } + + $key = strtolower($key); + + if (!$overwrite && isset($this->header[$key])) { + return false; + } elseif ($overwrite && isset($this->header[$key])) { + if ($this->isSecurityHeader($key)) { + throw new \Exception('Cannot change security headers.'); + } + + unset($this->header[$key]); + } + + if (!isset($this->header[$key])) { + $this->header[$key] = []; + } + + $this->header[$key][] = $header; + + return true; + } + + /** + * Is security header. + * + * @param string $key Header key + * + * @return bool + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function isSecurityHeader(string $key) : bool + { + return $key === 'content-security-policy' || + $key === 'x-xss-protection' || + $key === 'x-content-type-options' || + $key === 'x-frame-options'; + } + + /** + * Get status code. + * + * @return int + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getStatusCode() : int + { + return http_response_code(); + } + /** * Returns all headers. * @@ -114,56 +177,6 @@ class Header extends HeaderAbstract return array_key_exists($key, $this->header); } - /** - * Is security header. - * - * @param string $key Header key - * - * @return bool - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function isSecurityHeader(string $key) : bool - { - return $key === 'content-security-policy' || - $key === 'x-xss-protection' || - $key === 'x-content-type-options' || - $key === 'x-frame-options'; - } - - /** - * {@inheritdoc} - */ - public function set(string $key, string $header, bool $overwrite = false) : bool - { - if (self::$isLocked) { - throw new \Exception('Already locked'); - } - - $key = strtolower($key); - - if (!$overwrite && isset($this->header[$key])) { - return false; - } elseif ($overwrite && isset($this->header[$key])) { - if ($this->isSecurityHeader($key)) { - throw new \Exception('Cannot change security headers.'); - } - - unset($this->header[$key]); - } - - if (!isset($this->header[$key])) { - $this->header[$key] = []; - } - - $this->header[$key][] = $header; - - return true; - } - /** * Push all headers. * @@ -211,19 +224,6 @@ class Header extends HeaderAbstract } } - /** - * Get status code. - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getStatusCode() : int - { - return http_response_code(); - } - /** * Generate predefined header. * @@ -277,12 +277,9 @@ class Header extends HeaderAbstract * @since 1.0.0 * @author Dennis Eichhorn */ - private function generate503() + private function generate407() { - $this->set('HTTP', 'HTTP/1.0 503 Service Temporarily Unavailable'); - $this->set('Status', 'Status: 503 Service Temporarily Unavailable'); - $this->set('Retry-After', 'Retry-After: 300'); - http_response_code(503); + } /** @@ -293,8 +290,11 @@ class Header extends HeaderAbstract * @since 1.0.0 * @author Dennis Eichhorn */ - private function generate407() + private function generate503() { - + $this->set('HTTP', 'HTTP/1.0 503 Service Temporarily Unavailable'); + $this->set('Status', 'Status: 503 Service Temporarily Unavailable'); + $this->set('Retry-After', 'Retry-After: 300'); + http_response_code(503); } } \ No newline at end of file diff --git a/Message/Http/Request.php b/Message/Http/Request.php index db15483c5..f67a218bd 100644 --- a/Message/Http/Request.php +++ b/Message/Http/Request.php @@ -18,10 +18,10 @@ namespace phpOMS\Message\Http; use phpOMS\Localization\L11nManager; use phpOMS\Localization\Localization; use phpOMS\Message\RequestAbstract; +use phpOMS\Router\RouteVerb; use phpOMS\Uri\Http; use phpOMS\Uri\UriFactory; use phpOMS\Uri\UriInterface; -use phpOMS\Router\RouteVerb; /** * Request class. diff --git a/Message/Http/Response.php b/Message/Http/Response.php index e358b9e04..83a08f2a3 100644 --- a/Message/Http/Response.php +++ b/Message/Http/Response.php @@ -15,11 +15,11 @@ */ namespace phpOMS\Message\Http; +use phpOMS\Contract\RenderableInterface; use phpOMS\Localization\L11nManager; use phpOMS\Localization\Localization; -use phpOMS\System\MimeType; -use phpOMS\Contract\RenderableInterface; use phpOMS\Message\ResponseAbstract; +use phpOMS\System\MimeType; use phpOMS\Views\View; /** @@ -174,7 +174,7 @@ class Response extends ResponseAbstract implements RenderableInterface throw new \Exception('Wrong response type'); } } - } catch(\Exception $e) { + } catch (\Exception $e) { // todo: handle exception // need to to try catch for logging. otherwise the json_encode in the logger will have a problem with this $result = []; diff --git a/Message/Mail/Imap.php b/Message/Mail/Imap.php index 61041c7d4..ef61b058d 100644 --- a/Message/Mail/Imap.php +++ b/Message/Mail/Imap.php @@ -63,6 +63,19 @@ class Imap extends Mail parent::__construct(MailType::IMAP); } + public static function decode($content, $encoding) + { + if ($encoding == 3) { + return imap_base64($content); + } else { + if ($encoding == 1) { + return imap_8bit($content); + } else { + return imap_qprint($content); + } + } + } + /** * Destructor. * @@ -125,23 +138,6 @@ class Imap extends Mail return imap_get_quotaroot($this->inbox, "INBOX"); } - /** - * Get inbox overview. - * - * @param string $option Inbox option (imap_search creterias) - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getInboxOverview(string $option = 'ALL') : array - { - $ids = imap_search($this->inbox, $option, SE_FREE, 'UTF-8'); - - return is_array($ids) ? imap_fetch_overview($this->inbox, implode(',', $ids)) : []; - } - /** * Get email. * @@ -175,6 +171,23 @@ class Imap extends Mail return $this->getInboxOverview('ALL'); } + /** + * Get inbox overview. + * + * @param string $option Inbox option (imap_search creterias) + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getInboxOverview(string $option = 'ALL') : array + { + $ids = imap_search($this->inbox, $option, SE_FREE, 'UTF-8'); + + return is_array($ids) ? imap_fetch_overview($this->inbox, implode(',', $ids)) : []; + } + /** * Get all new inbox messages. * @@ -344,17 +357,4 @@ class Imap extends Mail { return $this->getInboxOverview('TEXT "' . $text . '"'); } - - public static function decode($content, $encoding) - { - if ($encoding == 3) { - return imap_base64($content); - } else { - if ($encoding == 1) { - return imap_8bit($content); - } else { - return imap_qprint($content); - } - } - } } diff --git a/Message/Mail/Mail.php b/Message/Mail/Mail.php index 4fe9b4e90..130862ad9 100644 --- a/Message/Mail/Mail.php +++ b/Message/Mail/Mail.php @@ -15,8 +15,6 @@ */ namespace phpOMS\Message\Mail; -use phpOMS\Datatypes\Exception\InvalidEnumValue; - /** * Mail class. * diff --git a/Security/Encryption/Encryption.php b/Security/Encryption/Encryption.php index d55c6c7ec..498d0b7b0 100644 --- a/Security/Encryption/Encryption.php +++ b/Security/Encryption/Encryption.php @@ -190,6 +190,25 @@ class Encryption $this->mode = $mode; } + /** + * Encrypt value. + * + * @param string $value Value to encrypt + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function encrpyt(string $value) : string + { + $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer()); + $value = base64_encode($this->padAndMcrypt($value, $iv)); + $mac = $this->hash($value, $iv = base64_encode($iv)); + + return base64_encode(json_encode(compact('iv', 'value', 'mac'))); + } + /** * Get input vector size. * @@ -277,25 +296,6 @@ class Encryption return hash_hmac('sha256', $iv . $value, $this->key); } - /** - * Encrypt value. - * - * @param string $value Value to encrypt - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function encrpyt(string $value) : string - { - $iv = mcrypt_create_iv($this->getIvSize(), $this->getRandomizer()); - $value = base64_encode($this->padAndMcrypt($value, $iv)); - $mac = $this->hash($value, $iv = base64_encode($iv)); - - return base64_encode(json_encode(compact('iv', 'value', 'mac'))); - } - /** * Decrypt value. * @@ -344,21 +344,6 @@ class Encryption return $payload; } - /** - * Is valid mac. - * - * @param mixed $payload Payload data - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function validMac($payload) : bool - { - return $this->hash($payload['value'], $payload['iv']) == $payload['mac']; - } - /** * Check if payload is valid. * @@ -374,6 +359,21 @@ class Encryption return !is_array($payload) || !isset($payload['iv']) || !isset($payload['value']) || !isset($payload['mac']); } + /** + * Is valid mac. + * + * @param mixed $payload Payload data + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function validMac($payload) : bool + { + return $this->hash($payload['value'], $payload['iv']) == $payload['mac']; + } + /** * Remove padding. * diff --git a/Socket/Client/ClientConnection.php b/Socket/Client/ClientConnection.php index 9dce6201d..d440df019 100644 --- a/Socket/Client/ClientConnection.php +++ b/Socket/Client/ClientConnection.php @@ -50,36 +50,36 @@ class ClientConnection return $this->socket; } - public function getHandshake() - { - return $this->handshake; - } - - public function getPid() - { - return $this->pid; - } - - public function isConnected() - { - return $this->connected; - } - public function setSocket($socket) { $this->socket = $socket; } + public function getHandshake() + { + return $this->handshake; + } + public function setHandshake($handshake) { $this->handshake = $handshake; } + public function getPid() + { + return $this->pid; + } + public function setPid($pid) { $this->pid = $pid; } + public function isConnected() + { + return $this->connected; + } + public function setConnected(bool $connected) { $this->connected = $connected; diff --git a/Socket/Server/Server.php b/Socket/Server/Server.php index 8ee66cdf3..d3603f900 100644 --- a/Socket/Server/Server.php +++ b/Socket/Server/Server.php @@ -18,7 +18,6 @@ namespace phpOMS\Socket\Server; use phpOMS\Socket\Client\ClientConnection; use phpOMS\Socket\CommandManager; use phpOMS\Socket\Packets\PacketManager; - use phpOMS\Socket\SocketAbstract; /** diff --git a/Stdlib/Map/MultiMap.php b/Stdlib/Map/MultiMap.php index 4861facf5..f1d3b3b96 100644 --- a/Stdlib/Map/MultiMap.php +++ b/Stdlib/Map/MultiMap.php @@ -237,12 +237,18 @@ class MultiMap implements \Countable * @since 1.0.0 * @author Dennis Eichhorn */ - private function setSingle($key, $value) : bool + private function setMultiple($key, $value) : bool { - if (isset($this->keys[$key])) { - $this->values[$this->keys[$key]] = $value; + if ($this->orderType !== OrderType::LOOSE) { + $permutation = Permutation::permut($key); - return true; + foreach ($permutation as $permut) { + if ($this->set(implode($permut, ':'), $value)) { + return true; + } + } + } else { + return $this->set(implode($key, ':'), $value); } return false; @@ -259,18 +265,12 @@ class MultiMap implements \Countable * @since 1.0.0 * @author Dennis Eichhorn */ - private function setMultiple($key, $value) : bool + private function setSingle($key, $value) : bool { - if ($this->orderType !== OrderType::LOOSE) { - $permutation = Permutation::permut($key); + if (isset($this->keys[$key])) { + $this->values[$this->keys[$key]] = $value; - foreach ($permutation as $permut) { - if ($this->set(implode($permut, ':'), $value)) { - return true; - } - } - } else { - return $this->set(implode($key, ':'), $value); + return true; } return false; @@ -295,31 +295,6 @@ class MultiMap implements \Countable } } - /** - * Remove value and all sibling keys based on key. - * - * @param mixed $key Key used to identify value - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function removeSingle($key) : bool - { - if (isset($this->keys[$key])) { - $id = $this->keys[$key]; - - unset($this->values[$id]); - - $this->garbageCollect(); - - return true; - } - - return false; - } - /** * Remove value and all sibling keys based on key. * @@ -347,6 +322,31 @@ class MultiMap implements \Countable } } + /** + * Remove value and all sibling keys based on key. + * + * @param mixed $key Key used to identify value + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function removeSingle($key) : bool + { + if (isset($this->keys[$key])) { + $id = $this->keys[$key]; + + unset($this->values[$id]); + + $this->garbageCollect(); + + return true; + } + + return false; + } + /** * Remap key to a different value. * @@ -398,31 +398,6 @@ class MultiMap implements \Countable } } - /** - * Remove key. - * - * This only removes the value if no other key exists for this value. - * - * @param mixed $key Key used to identify value - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function removeKeySingle($key) : bool - { - if (isset($this->keys[$key])) { - unset($this->keys[$key]); - - $this->garbageCollect(); - - return true; - } - - return false; - } - /** * Remove key. * @@ -452,6 +427,31 @@ class MultiMap implements \Countable } } + /** + * Remove key. + * + * This only removes the value if no other key exists for this value. + * + * @param mixed $key Key used to identify value + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function removeKeySingle($key) : bool + { + if (isset($this->keys[$key])) { + unset($this->keys[$key]); + + $this->garbageCollect(); + + return true; + } + + return false; + } + /** * Get all sibling keys. * @@ -472,6 +472,25 @@ class MultiMap implements \Countable } + /** + * Get all sibling keys. + * + * @param mixed $key Key to find siblings for + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getSiblingsMultiple($key) : array + { + if ($this->orderType === OrderType::LOOSE) { + return Permutation::permut($key); + } + + return []; + } + /** * Get all sibling keys. * @@ -499,25 +518,6 @@ class MultiMap implements \Countable return $siblings; } - /** - * Get all sibling keys. - * - * @param mixed $key Key to find siblings for - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getSiblingsMultiple($key) : array - { - if ($this->orderType === OrderType::LOOSE) { - return Permutation::permut($key); - } - - return []; - } - /** * Get all keys. * diff --git a/System/File/Directory.php b/System/File/Directory.php index 3bfc4f2e2..5b36d9c6d 100644 --- a/System/File/Directory.php +++ b/System/File/Directory.php @@ -48,6 +48,69 @@ class Directory extends FileAbstract implements \Iterator, \ArrayAccess */ private $nodes = []; + /** + * Constructor. + * + * @param string $path Path + * @param string $filter Filter + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function __construct(string $path, string $filter = '*') + { + $this->filter = $filter; + parent::__construct($path); + + if (file_exists($this->path)) { + $this->index(); + } + } + + /** + * Index directory. + * + * @return void + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function index() + { + parent::index(); + + foreach (glob($this->path . DIRECTORY_SEPARATOR . $this->filter) as $filename) { + // todo: handle . and ..???!!! + if (is_dir($filename)) { + $file = new Directory($filename); + $file->index(); + } else { + $file = new File($filename); + } + + $this->add($file); + } + } + + /** + * Add file or directory. + * + * @param FileAbstract $file File to add + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function add(FileAbstract $file) : bool + { + $this->count += $file->getCount(); + $this->size += $file->getSize(); + $this->nodes[$this->getName()] = $file; + + return $file->createNode(); + } + /** * Get folder size recursively. * @@ -156,6 +219,29 @@ class Directory extends FileAbstract implements \Iterator, \ArrayAccess return true; } + /** + * Get node by name. + * + * @param string $name File/direcotry name + * + * @return FileAbstract + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function get(string $name) : FileAbstract + { + return $this->nodes[$name] ?? new NullFile(''); + } + + /** + * {@inheritdoc} + */ + public function createNode() : bool + { + return self::createPath($this->path, $this->permission, true); + } + /** * Create directory. * @@ -205,67 +291,6 @@ class Directory extends FileAbstract implements \Iterator, \ArrayAccess return implode('/', $path); } - /** - * Constructor. - * - * @param string $path Path - * @param string $filter Filter - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function __construct(string $path, string $filter = '*') - { - $this->filter = $filter; - parent::__construct($path); - - if (file_exists($this->path)) { - $this->index(); - } - } - - /** - * Get node by name. - * - * @param string $name File/direcotry name - * - * @return FileAbstract - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function get(string $name) : FileAbstract - { - return $this->nodes[$name] ?? new NullFile(''); - } - - /** - * Add file or directory. - * - * @param FileAbstract $file File to add - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function add(FileAbstract $file) : bool - { - $this->count += $file->getCount(); - $this->size += $file->getSize(); - $this->nodes[$this->getName()] = $file; - - return $file->createNode(); - } - - /** - * {@inheritdoc} - */ - public function createNode() : bool - { - return self::createPath($this->path, $this->permission, true); - } - /** * {@inheritdoc} */ @@ -300,32 +325,8 @@ class Directory extends FileAbstract implements \Iterator, \ArrayAccess return false; } - /** - * Index directory. - * - * @return void - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function index() - { - parent::index(); - - foreach (glob($this->path . DIRECTORY_SEPARATOR . $this->filter) as $filename) { - // todo: handle . and ..???!!! - if (is_dir($filename)) { - $file = new Directory($filename); - $file->index(); - } else { - $file = new File($filename); - } - - $this->add($file); - } - } - /* Iterator */ + /** * {@inheritdoc} */ diff --git a/System/File/File.php b/System/File/File.php index 872459181..9d0cff3c8 100644 --- a/System/File/File.php +++ b/System/File/File.php @@ -31,6 +31,47 @@ namespace phpOMS\System\File; class File extends FileAbstract { + /** + * Constructor. + * + * @param string $path Path + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function __construct(string $path) + { + parent::__construct($path); + $this->count = 1; + + if (file_exists($this->path)) { + $this->index(); + } + } + + /** + * Index file. + * + * @return void + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function index() + { + parent::index(); + + $this->size = filesize($this->path); + } + + /** + * {@inheritdoc} + */ + public function createNode() : bool + { + return self::createFile($this->path); + } + /** * Create file. * @@ -56,32 +97,6 @@ class File extends FileAbstract return false; } - /** - * Constructor. - * - * @param string $path Path - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function __construct(string $path) - { - parent::__construct($path); - $this->count = 1; - - if (file_exists($this->path)) { - $this->index(); - } - } - - /** - * {@inheritdoc} - */ - public function createNode() : bool - { - return self::createFile($this->path); - } - /** * {@inheritdoc} */ @@ -115,19 +130,4 @@ class File extends FileAbstract { file_put_contents($this->path, $content); } - - /** - * Index file. - * - * @return void - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function index() - { - parent::index(); - - $this->size = filesize($this->path); - } } \ No newline at end of file diff --git a/Utils/Barcode/C128Abstract.php b/Utils/Barcode/C128Abstract.php index bb1d4d5c0..f43f76a71 100644 --- a/Utils/Barcode/C128Abstract.php +++ b/Utils/Barcode/C128Abstract.php @@ -147,6 +147,23 @@ abstract class C128Abstract $this->setOrientation($orientation); } + /** + * Set barcode height + * + * @param int $size Barcode height + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setSize(int $size) + { + if ($size < 0) { + throw new \OutOfBoundsException($size); + } + + $this->size = $size; + } + /** * Set barcode orientation * @@ -164,19 +181,6 @@ abstract class C128Abstract $this->orientation = $orientation; } - /** - * Set content to encrypt - * - * @param string $content Barcode content - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setContent(string $content) - { - $this->content = $content; - } - /** * Get content * @@ -191,20 +195,31 @@ abstract class C128Abstract } /** - * Set barcode height + * Set content to encrypt * - * @param int $size Barcode height + * @param string $content Barcode content * * @since 1.0.0 * @author Dennis Eichhorn */ - public function setSize(int $size) + public function setContent(string $content) { - if ($size < 0) { - throw new \OutOfBoundsException($size); - } + $this->content = $content; + } - $this->size = $size; + /** + * Get image reference + * + * @return mixed + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function get() + { + $codeString = static::$CODE_START . $this->generateCodeString() . static::$CODE_END; + + return $this->createImage($codeString, 20); } /** @@ -235,21 +250,6 @@ abstract class C128Abstract return $codeString; } - /** - * Get image reference - * - * @return mixed - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function get() - { - $codeString = static::$CODE_START . $this->generateCodeString() . static::$CODE_END; - - return $this->createImage($codeString, 20); - } - /** * Create barcode image * diff --git a/Utils/Converter/Currency.php b/Utils/Converter/Currency.php index 0946f4480..3cce7aaf7 100644 --- a/Utils/Converter/Currency.php +++ b/Utils/Converter/Currency.php @@ -60,6 +60,29 @@ class Currency self::$ecbCurrencies = null; } + /** + * Convert from EUR + * + * @param float $value Value to convert + * @param string $to Output currency + * + * @return float + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function fromEurTo(float $value, string $to) : float + { + $currencies = self::getEcbEuroRates(); + $to = strtoupper($to); + + if (!isset($currencies[$to])) { + throw new \InvalidArgumentException('Currency doesn\'t exists'); + } + + return $value * $currencies[$to]; + } + /** * Get ECB currency rates. * @@ -91,29 +114,6 @@ class Currency return self::$ecbCurrencies; } - /** - * Convert from EUR - * - * @param float $value Value to convert - * @param string $to Output currency - * - * @return float - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function fromEurTo(float $value, string $to) : float - { - $currencies = self::getEcbEuroRates(); - $to = strtoupper($to); - - if (!isset($currencies[$to])) { - throw new \InvalidArgumentException('Currency doesn\'t exists'); - } - - return $value * $currencies[$to]; - } - /** * Convert to EUR * diff --git a/Utils/Converter/Measurement.php b/Utils/Converter/Measurement.php index b851ad0f4..2ae0f42a8 100644 --- a/Utils/Converter/Measurement.php +++ b/Utils/Converter/Measurement.php @@ -38,7 +38,7 @@ class Measurement * * @return float * - * @todo: implement more + * @todo : implement more * * @since 1.0.0 * @author Dennis Eichhorn @@ -114,7 +114,7 @@ class Measurement * * @return float * - * @todo: implement more + * @todo : implement more * * @since 1.0.0 * @author Dennis Eichhorn @@ -985,19 +985,19 @@ class Measurement $value /= 3600; break; case TimeType::DAYS: - $value /= 3600*24; + $value /= 3600 * 24; break; case TimeType::WEEKS: - $value /= 3600*24*7; + $value /= 3600 * 24 * 7; break; case TimeType::MONTH: - $value /= 3600*24*30; + $value /= 3600 * 24 * 30; break; case TimeType::QUARTER: - $value /= 3600*24*90; + $value /= 3600 * 24 * 90; break; case TimeType::QUARTER: - $value /= 3600*24*365; + $value /= 3600 * 24 * 365; break; default: throw new \InvalidArgumentException('Size not supported'); @@ -1016,19 +1016,19 @@ class Measurement $value *= 3600; break; case TimeType::DAYS: - $value *= 3600*24; + $value *= 3600 * 24; break; case TimeType::WEEKS: - $value *= 3600*24*7; + $value *= 3600 * 24 * 7; break; case TimeType::MONTH: - $value *= 3600*24*30; + $value *= 3600 * 24 * 30; break; case TimeType::QUARTER: - $value *= 3600*24*90; + $value *= 3600 * 24 * 90; break; case TimeType::QUARTER: - $value *= 3600*24*365; + $value *= 3600 * 24 * 365; break; default: throw new \InvalidArgumentException('Size not supported'); diff --git a/Utils/Encoding/Huffman/Dictionary.php b/Utils/Encoding/Huffman/Dictionary.php index 6fd6a472a..c577c5602 100644 --- a/Utils/Encoding/Huffman/Dictionary.php +++ b/Utils/Encoding/Huffman/Dictionary.php @@ -67,103 +67,6 @@ final class Dictionary } } - /** - * Get dictionary value by entry - * - * @param string $entry 1 character entry - * - * @return string - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function get(string $entry) : string - { - if (strlen($entry) !== 1) { - throw new \Exception('Must be a character.'); - } - - if (!isset($this->dictionary[$entry])) { - throw new \Exception('Character does not exist'); - } - - return $this->dictionary[$entry]; - } - - /** - * Get dictionary entry and reduce value - * - * @param string $value Dictionary value - * - * @return null|string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getEntry(&$value) - { - $length = strlen($value); - if ($length < $this->min) { - return null; - } - - for ($i = $this->min; $i <= $this->max; ++$i) { - $needle = substr($value, 0, $i); - - foreach ($this->dictionary as $key => $val) { - if ($needle === $val) { - $value = substr($value, $i); - - return $key; - } - } - } - - return null; - } - - /** - * Set dictionary value - * - * @param string $entry 1 character entry - * @param string $value Dictionary value - * - * @return void - * - * @throws - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function set(string $entry, string $value) - { - if (strlen($entry) !== 1) { - throw new \Exception('Must be a character.'); - } - - if (!isset($this->dictionary[$entry])) { - throw new \Exception('Character does not exist'); - } - - if (strlen(str_replace('0', '', str_replace('1', '', $value))) !== 0) { - throw new \Exception('Bad formatting.'); - } - - $length = strlen($value); - - if ($this->min === -1 || $length < $this->min) { - $this->min = $length; - } - - if ($this->max === -1 || $length > $this->max) { - $this->max = $length; - } - - $this->dictionary[$entry] = $value; - } - /** * Generate dictionary from data. * @@ -226,4 +129,101 @@ final class Dictionary } } } + + /** + * Set dictionary value + * + * @param string $entry 1 character entry + * @param string $value Dictionary value + * + * @return void + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function set(string $entry, string $value) + { + if (strlen($entry) !== 1) { + throw new \Exception('Must be a character.'); + } + + if (!isset($this->dictionary[$entry])) { + throw new \Exception('Character does not exist'); + } + + if (strlen(str_replace('0', '', str_replace('1', '', $value))) !== 0) { + throw new \Exception('Bad formatting.'); + } + + $length = strlen($value); + + if ($this->min === -1 || $length < $this->min) { + $this->min = $length; + } + + if ($this->max === -1 || $length > $this->max) { + $this->max = $length; + } + + $this->dictionary[$entry] = $value; + } + + /** + * Get dictionary value by entry + * + * @param string $entry 1 character entry + * + * @return string + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function get(string $entry) : string + { + if (strlen($entry) !== 1) { + throw new \Exception('Must be a character.'); + } + + if (!isset($this->dictionary[$entry])) { + throw new \Exception('Character does not exist'); + } + + return $this->dictionary[$entry]; + } + + /** + * Get dictionary entry and reduce value + * + * @param string $value Dictionary value + * + * @return null|string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getEntry(&$value) + { + $length = strlen($value); + if ($length < $this->min) { + return null; + } + + for ($i = $this->min; $i <= $this->max; ++$i) { + $needle = substr($value, 0, $i); + + foreach ($this->dictionary as $key => $val) { + if ($needle === $val) { + $value = substr($value, $i); + + return $key; + } + } + } + + return null; + } } \ No newline at end of file diff --git a/Utils/Encoding/Huffman/Huffman.php b/Utils/Encoding/Huffman/Huffman.php index 758250182..906e715ec 100644 --- a/Utils/Encoding/Huffman/Huffman.php +++ b/Utils/Encoding/Huffman/Huffman.php @@ -36,19 +36,6 @@ final class Huffman */ private $dictionary = null; - /** - * Set dictionary - * - * @param Dictionary $dictionary Huffman dictionary - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setDictionary(Dictionary $dictionary) - { - $this->dictionary = $dictionary; - } - /** * Remove dictionary * @@ -73,6 +60,19 @@ final class Huffman return $this->dictionary; } + /** + * Set dictionary + * + * @param Dictionary $dictionary Huffman dictionary + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setDictionary(Dictionary $dictionary) + { + $this->dictionary = $dictionary; + } + /** * Encode. * diff --git a/Utils/Encoding/Xor.php b/Utils/Encoding/Xor.php index 8432946e3..75bf966b2 100644 --- a/Utils/Encoding/Xor.php +++ b/Utils/Encoding/Xor.php @@ -29,6 +29,14 @@ namespace phpOMS\Utils\Encoding; final class XorEncoding { + /** + * {@inheritdoc} + */ + public static function decode(string $raw, string $key) : string + { + return self::encode($raw, $key); + } + /** * {@inheritdoc} */ @@ -49,12 +57,4 @@ final class XorEncoding return $result; } - - /** - * {@inheritdoc} - */ - public static function decode(string $raw, string $key) : string - { - return self::encode($raw, $key); - } } \ No newline at end of file diff --git a/Utils/Git/Author.php b/Utils/Git/Author.php index 3ed90dfac..fb80d482d 100644 --- a/Utils/Git/Author.php +++ b/Utils/Git/Author.php @@ -109,6 +109,19 @@ class Author return $this->email; } + /** + * Get commit count + * + * @return int + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getCommitCount() : int + { + return $this->commitCount; + } + /** * Set commit count * @@ -124,19 +137,6 @@ class Author $this->commitCount = $count; } - /** - * Get commit count - * - * @return int - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getCommitCount() : int - { - return $this->commitCount; - } - /** * Set additions count * diff --git a/Utils/Git/Branch.php b/Utils/Git/Branch.php index c1caf713c..e6047c198 100644 --- a/Utils/Git/Branch.php +++ b/Utils/Git/Branch.php @@ -49,19 +49,6 @@ class Branch $this->setName($name); } - /** - * Set branch name - * - * @param string $name Branch name - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setName(string $name) - { - $this->name = escapeshellarg($name); - } - /** * Get name * @@ -74,4 +61,17 @@ class Branch { return $this->name; } + + /** + * Set branch name + * + * @param string $name Branch name + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setName(string $name) + { + $this->name = escapeshellarg($name); + } } \ No newline at end of file diff --git a/Utils/Git/Commit.php b/Utils/Git/Commit.php index ddd9d56ab..6e4f73f35 100644 --- a/Utils/Git/Commit.php +++ b/Utils/Git/Commit.php @@ -143,29 +143,16 @@ class Commit } /** - * Add change. + * Get commit message. * - * @param string $path File path - * @param int $line Line number - * @param string $old Old line - * @param string $new New line - * - * @throws + * @return string * * @since 1.0.0 * @author Dennis Eichhorn */ - private function addChange(string $path, int $line, string $old, string $new) + public function getMessage() : string { - if (!isset($this->files[$path])) { - throw new \Exception(); - } - - if (!isset($this->files[$path][$line])) { - $this->files[$path][$line] = ['old' => $old, 'new' => $new]; - } else { - throw new \Exception(); - } + return $this->message; } /** @@ -183,19 +170,6 @@ class Commit $this->message = $message; } - /** - * Get commit message. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getMessage() : string - { - return $this->message; - } - /** * Get files of this commit. * @@ -230,19 +204,6 @@ class Commit return false; } - /** - * Set commit author. - * - * @param Author $author Commit author - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setAuthor(Author $author) - { - $this->author = $author; - } - /** * Get commit author. * @@ -257,16 +218,16 @@ class Commit } /** - * Set commit branch. + * Set commit author. * - * @param Branch $branch Commit branch + * @param Author $author Commit author * * @since 1.0.0 * @author Dennis Eichhorn */ - public function setBranch(Branch $branch) + public function setAuthor(Author $author) { - $this->branch = $branch; + $this->author = $author; } /** @@ -283,16 +244,16 @@ class Commit } /** - * Set commit tag. + * Set commit branch. * - * @param Tag $tag Commit tag + * @param Branch $branch Commit branch * * @since 1.0.0 * @author Dennis Eichhorn */ - public function setTag(Tag $tag) + public function setBranch(Branch $branch) { - $this->tag = $tag; + $this->branch = $branch; } /** @@ -308,6 +269,19 @@ class Commit return $this->tag; } + /** + * Set commit tag. + * + * @param Tag $tag Commit tag + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setTag(Tag $tag) + { + $this->tag = $tag; + } + /** * Get commit date. * @@ -336,6 +310,19 @@ class Commit $this->date = $date; } + /** + * Get commit repository. + * + * @return Repository + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getRepository() : Repository + { + return $this->repository; + } + /** * Set commit repository. * @@ -350,15 +337,28 @@ class Commit } /** - * Get commit repository. + * Add change. * - * @return Repository + * @param string $path File path + * @param int $line Line number + * @param string $old Old line + * @param string $new New line + * + * @throws * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getRepository() : Repository + private function addChange(string $path, int $line, string $old, string $new) { - return $this->repository; + if (!isset($this->files[$path])) { + throw new \Exception(); + } + + if (!isset($this->files[$path][$line])) { + $this->files[$path][$line] = ['old' => $old, 'new' => $new]; + } else { + throw new \Exception(); + } } } diff --git a/Utils/Git/Git.php b/Utils/Git/Git.php index 93adceb52..a6412b4e1 100644 --- a/Utils/Git/Git.php +++ b/Utils/Git/Git.php @@ -38,38 +38,6 @@ class Git */ protected static $bin = '/usr/bin/git'; - /** - * Set git binary. - * - * @param string $path Git path - * - * @throws PathException - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function setBin(string $path) - { - if (realpath($path) === false) { - throw new PathException($path); - } - - self::$bin = realpath($path); - } - - /** - * Get git binary. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public static function getBin() : string - { - return self::$bin; - } - /** * Test git. * @@ -92,4 +60,36 @@ class Git return trim(proc_close($resource)) !== 127; } + + /** + * Get git binary. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function getBin() : string + { + return self::$bin; + } + + /** + * Set git binary. + * + * @param string $path Git path + * + * @throws PathException + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public static function setBin(string $path) + { + if (realpath($path) === false) { + throw new PathException($path); + } + + self::$bin = realpath($path); + } } diff --git a/Utils/Git/Repository.php b/Utils/Git/Repository.php index 07f36baf6..3f9158b3e 100644 --- a/Utils/Git/Repository.php +++ b/Utils/Git/Repository.php @@ -85,30 +85,6 @@ class Repository $this->branch = $this->getActiveBranch(); } - /** - * Create repository - * - * @param string $source Create repository from source (optional, can be remote) - * @param bool $bare Bare repository - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function create(string $source = null, bool $bare = false) - { - if (!is_dir($this->path) || file_exists($this->path . '/.git')) { - throw new \Exception('Already repository'); - } - - if (isset($source)) { - $this->clone($source); - } else { - $this->init($bare); - } - } - /** * Set repository path. * @@ -142,6 +118,51 @@ class Repository } } + /** + * Get active Branch. + * + * @return Branch + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getActiveBranch() : Branch + { + if (!isset($this->branch)) { + $branches = $this->getBranches(); + $active = preg_grep('/^\*/', $branches); + reset($active); + + $this->branch = new Branch(current($active)); + } + + return $this->branch; + } + + /** + * Get all branches. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getBranches() : array + { + $branches = $this->run('branch'); + $result = []; + + foreach ($branches as $key => $branch) { + $branch = trim($branch, '* '); + + if ($branch !== '') { + $result[] = $branch; + } + } + + return $result; + } + /** * Run git command. * @@ -216,16 +237,27 @@ class Repository } /** - * Get directory path. + * Create repository * - * @return string + * @param string $source Create repository from source (optional, can be remote) + * @param bool $bare Bare repository + * + * @throws \Exception * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getDirectoryPath() : string + public function create(string $source = null, bool $bare = false) { - return $this->bare ? $this->path : $this->path . '/.git'; + if (!is_dir($this->path) || file_exists($this->path . '/.git')) { + throw new \Exception('Already repository'); + } + + if (isset($source)) { + $this->clone($source); + } else { + $this->init($bare); + } } /** @@ -350,30 +382,6 @@ class Repository return implode("\n", $this->run('branch ' . ($force ? '-D' : '-d') . ' ' . $branch->getName())); } - /** - * Get all branches. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getBranches() : array - { - $branches = $this->run('branch'); - $result = []; - - foreach ($branches as $key => $branch) { - $branch = trim($branch, '* '); - - if ($branch !== '') { - $result[] = $branch; - } - } - - return $result; - } - /** * Get repository name. * @@ -394,6 +402,19 @@ class Repository return $this->name; } + /** + * Get directory path. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getDirectoryPath() : string + { + return $this->bare ? $this->path : $this->path . '/.git'; + } + /** * Get all remote branches. * @@ -418,27 +439,6 @@ class Repository return $result; } - /** - * Get active Branch. - * - * @return Branch - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getActiveBranch() : Branch - { - if (!isset($this->branch)) { - $branches = $this->getBranches(); - $active = preg_grep('/^\*/', $branches); - reset($active); - - $this->branch = new Branch(current($active)); - } - - return $this->branch; - } - /** * Checkout. * @@ -603,53 +603,6 @@ class Repository $this->envOptions[$key] = $value; } - /** - * Get commit by id. - * - * @param string $commit Commit id - * - * @return Commit - * - * @throws \Exception - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getCommit(string $commit) : Commit - { - $lines = $this->run('show --name-only ' . escapeshellarg($commit)); - $count = count($lines); - - if (empty($lines)) { - // todo: return null commit - return new Commit(); - } - - preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches); - - if (!isset($matches[0]) || strlen($matches[0]) !== 40) { - throw new \Exception('Invalid commit id'); - } - - $author = explode(':', $lines[1]); - $author = explode('<', trim($author[1])); - $date = substr($lines[2], 6); - - $commit = new Commit($matches[0]); - $commit->setAuthor(new Author(trim($author[0]), rtrim($author[1], '>'))); - $commit->setDate(new \DateTime(trim($date))); - $commit->setMessage($lines[3]); - $commit->setTag(new Tag()); - $commit->setRepository($this); - $commit->setBranch($this->branch); - - for ($i = 4; $i < $count; $i++) { - $commit->addFile($lines[$i]); - } - - return $commit; - } - /** * Count files in repository. * @@ -691,7 +644,7 @@ class Repository $fh = fopen($path = $this->getDirectoryPath() . ($this->bare ? '/' : '/../') . $line, 'r'); - if(!$fh) { + if (!$fh) { throw new PathException($path); } @@ -706,39 +659,6 @@ class Repository return $loc; } - /** - * Count commits. - * - * @param \DateTime $start Start date - * @param \DateTime $end End date - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getCommitsCount(\DateTime $start = null, \DateTime $end = null) : array - { - if (!isset($start)) { - $start = new \DateTime('1970-12-31'); - } - - if (!isset($end)) { - $end = new \DateTime('now'); - } - - $lines = $this->run('shortlog -s -n --since="' . $start->format('Y-m-d') . '" --before="' . $end->format('Y-m-d') . '" --all'); - $commits = []; - - foreach ($lines as $line) { - preg_match('/^[0-9]*/', $line, $matches); - - $commits[substr($line, strlen($matches[0]) + 1)] = (int) $matches[0]; - } - - return $commits; - } - /** * Get contributors. * @@ -779,6 +699,39 @@ class Repository return $contributors; } + /** + * Count commits. + * + * @param \DateTime $start Start date + * @param \DateTime $end End date + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getCommitsCount(\DateTime $start = null, \DateTime $end = null) : array + { + if (!isset($start)) { + $start = new \DateTime('1970-12-31'); + } + + if (!isset($end)) { + $end = new \DateTime('now'); + } + + $lines = $this->run('shortlog -s -n --since="' . $start->format('Y-m-d') . '" --before="' . $end->format('Y-m-d') . '" --all'); + $commits = []; + + foreach ($lines as $line) { + preg_match('/^[0-9]*/', $line, $matches); + + $commits[substr($line, strlen($matches[0]) + 1)] = (int) $matches[0]; + } + + return $commits; + } + /** * Get additions and removals from contributor. * @@ -863,6 +816,53 @@ class Repository return $commits; } + /** + * Get commit by id. + * + * @param string $commit Commit id + * + * @return Commit + * + * @throws \Exception + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getCommit(string $commit) : Commit + { + $lines = $this->run('show --name-only ' . escapeshellarg($commit)); + $count = count($lines); + + if (empty($lines)) { + // todo: return null commit + return new Commit(); + } + + preg_match('/[0-9ABCDEFabcdef]{40}/', $lines[0], $matches); + + if (!isset($matches[0]) || strlen($matches[0]) !== 40) { + throw new \Exception('Invalid commit id'); + } + + $author = explode(':', $lines[1]); + $author = explode('<', trim($author[1])); + $date = substr($lines[2], 6); + + $commit = new Commit($matches[0]); + $commit->setAuthor(new Author(trim($author[0]), rtrim($author[1], '>'))); + $commit->setDate(new \DateTime(trim($date))); + $commit->setMessage($lines[3]); + $commit->setTag(new Tag()); + $commit->setRepository($this); + $commit->setBranch($this->branch); + + for ($i = 4; $i < $count; $i++) { + $commit->addFile($lines[$i]); + } + + return $commit; + } + /** * Get newest commit. * diff --git a/Utils/Git/Tag.php b/Utils/Git/Tag.php index 2ed24a7ad..e4aa91bbb 100644 --- a/Utils/Git/Tag.php +++ b/Utils/Git/Tag.php @@ -57,19 +57,6 @@ class Tag $this->name = escapeshellarg($name); } - /** - * Set tag name - * - * @param string $message Tag message - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setMessage(string $message) - { - $this->message = escapeshellarg($message); - } - /** * Get tag message * @@ -83,6 +70,19 @@ class Tag return $this->message; } + /** + * Set tag name + * + * @param string $message Tag message + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setMessage(string $message) + { + $this->message = escapeshellarg($message); + } + /** * Get tag name * diff --git a/Utils/JobQueue/Job.php b/Utils/JobQueue/Job.php index b97f49560..010c123c0 100644 --- a/Utils/JobQueue/Job.php +++ b/Utils/JobQueue/Job.php @@ -5,7 +5,7 @@ * PHP Version 7.0 * * @category TBD - } + * } * @package TBD * @author OMS Development Team * @author Dennis Eichhorn @@ -29,23 +29,27 @@ namespace phpOMS\Utils\JobQueue; */ class Job { - private $priority = 0.0; - private $callback = null; + private $priority = 0.0; + private $callback = null; - public function __construct($callback, float $priority = 0.0) { - $this->priority = $priority; - $this->callback = $callback; - } + public function __construct($callback, float $priority = 0.0) + { + $this->priority = $priority; + $this->callback = $callback; + } - public function execute() { - $this->callback(); - } + public function execute() + { + $this->callback(); + } - public function getPriority() : float { - return $this->priority; - } + public function getPriority() : float + { + return $this->priority; + } - public function setPriority(float $priority) { - $this->priority = $priority; - } + public function setPriority(float $priority) + { + $this->priority = $priority; + } } \ No newline at end of file diff --git a/Utils/JobQueue/JobQueue.php b/Utils/JobQueue/JobQueue.php index f768d939b..c5a1ff0d9 100644 --- a/Utils/JobQueue/JobQueue.php +++ b/Utils/JobQueue/JobQueue.php @@ -30,106 +30,131 @@ use \phpOMS\Stdlib\Queue\PriorityQueue; */ class JobQueue { - private $queue = null; - private $run = true; - private $suspended = false; - private $isTerminating = true; - private $isDeamonized; + private $queue = null; + private $run = true; + private $suspended = false; + private $isTerminating = true; + private $isDeamonized; - public function __construct() { - $this->queue = new PriorityQueue(); - } + public function __construct() + { + $this->queue = new PriorityQueue(); + } - public function dispatch(Job $job) { - $this->queue->insert($job, $job->getPriority()); - } + public function dispatch(Job $job) + { + $this->queue->insert($job, $job->getPriority()); + } - public function run() { - $this->run = true; - $this->suspended = false; + public function run() + { + $this->run = true; + $this->suspended = false; - if($this->isDeamonized) { - if($pid = pcntl_fork()) { - return $pid; - } + if ($this->isDeamonized) { + if ($pid = pcntl_fork()) { + return $pid; + } - $this->runAsDeamon(); + $this->runAsDeamon(); - if (posix_setsid() < 0 || $pid = pcntl_fork()) { - return; - } - } + if (posix_setsid() < 0 || $pid = pcntl_fork()) { + return; + } + } - while($this->run) { - while(!$this->suspended) - if($this->deamonized) { - // todo: see if still unsuspended and still running (db, file etc) - } + while ($this->run) { + while (!$this->suspended) { + if ($this->deamonized) { + // todo: see if still unsuspended and still running (db, file etc) + } + } - $job = $this->queue->pop(); + $job = $this->queue->pop(); - $this->queue->increaseAll(); - $job['job']->execute(); + $this->queue->increaseAll(); + $job['job']->execute(); - if($this->isTerminating && $this->queue->count() < 1) { - $this->suspended = true; - $this->run = false; - } + if ($this->isTerminating && $this->queue->count() < 1) { + $this->suspended = true; + $this->run = false; + } - sleep(1); - } + sleep(1); + } - sleep(1); - } - } + sleep(1); + } +} - public function setRunning(bool $run = true) { - $this->run = $run; - $this->suspended = $run; - } +public +function setRunning(bool $run = true) +{ + $this->run = $run; + $this->suspended = $run; +} - public function isRunning() : bool { - return $this->run; - } +public +function isRunning() : bool +{ + return $this->run; +} - public function setSuspended(bool $suspended = true) { - $this->suspended = $suspended; - } +public +function setSuspended(bool $suspended = true) +{ + $this->suspended = $suspended; +} - public function isSuspended() : bool { - return $this->suspended; - } +public +function isSuspended() : bool +{ + return $this->suspended; +} - public function isTerminating() : bool { - return $this->isTerminating; - } +public +function isTerminating() : bool +{ + return $this->isTerminating; +} - public function setTerminating(bool $terminating = true) { - $this->isTerminating = $terminating; - } +public +function setTerminating(bool $terminating = true) +{ + $this->isTerminating = $terminating; +} - public function isDeamonized() : bool { - return $this->isDeamonized; - } +public +function isDeamonized() : bool +{ + return $this->isDeamonized; +} - public function setDeamonized(bool $deamonized) { - $this->isDeamonized = $deamonized; - } +public +function setDeamonized(bool $deamonized) +{ + $this->isDeamonized = $deamonized; +} - private function runAsDeamon() { - ob_end_clean(); - fclose(STDIN); - fclose(STDOUT); - fclose(STDERR); +private +function runAsDeamon() +{ + ob_end_clean(); + fclose(STDIN); + fclose(STDOUT); + fclose(STDERR); - function shutdown() { - posix_kill(posix_getpid(), SIGHUP); - } + function shutdown() + { + posix_kill(posix_getpid(), SIGHUP); + } - register_shutdown_function('shutdown'); - } + register_shutdown_function('shutdown'); +} - private function savePid() { - // todo: save pid somewhere for kill - } +private +function savePid() +{ + // todo: save pid somewhere for kill +} } \ No newline at end of file diff --git a/Utils/Parser/Php/ClassParser.php b/Utils/Parser/Php/ClassParser.php index effea4a73..11fe81c5e 100644 --- a/Utils/Parser/Php/ClassParser.php +++ b/Utils/Parser/Php/ClassParser.php @@ -213,6 +213,19 @@ class ClassParser return $this->isAbstract; } + /** + * Get type. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getType() : string + { + return $this->type; + } + /** * Set type. * @@ -231,16 +244,16 @@ class ClassParser } /** - * Get type. + * Get extends. * * @return string * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getType() : string + public function getExtends() : string { - return $this->type; + return $this->extends; } /** @@ -258,19 +271,6 @@ class ClassParser $this->extends = $extends; } - /** - * Get extends. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getExtends() : string - { - return $this->extends; - } - /** * Remove extends. * @@ -284,6 +284,19 @@ class ClassParser $this->extends = ''; } + /** + * Get namespace. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getNamespace() : string + { + return $this->namespace; + } + /** * Set namespace. * @@ -299,19 +312,6 @@ class ClassParser $this->namespace = $namespace; } - /** - * Get namespace. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getNamespace() : string - { - return $this->namespace; - } - /** * Remove namespace. * @@ -366,6 +366,19 @@ class ClassParser return false; } + /** + * Get name. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getName() : string + { + return $this->name; + } + /** * Set name. * @@ -381,19 +394,6 @@ class ClassParser $this->name = $name; } - /** - * Get name. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getName() : string - { - return $this->name; - } - /** * Add implements. * @@ -625,7 +625,7 @@ class ClassParser * Serialize require. * * @param string $keyword Keyword (e.g. include, require, include_once) - * @param array $source Require source + * @param array $source Require source * * @return string * diff --git a/Utils/Parser/Php/FunctionParser.php b/Utils/Parser/Php/FunctionParser.php index 3a50e58da..19f19effd 100644 --- a/Utils/Parser/Php/FunctionParser.php +++ b/Utils/Parser/Php/FunctionParser.php @@ -94,6 +94,19 @@ class FunctionParser */ private $body = ''; + /** + * Get function name. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getName() : string + { + return $this->name; + } + /** * Set function name. * @@ -109,19 +122,6 @@ class FunctionParser $this->name = $name; } - /** - * Get function name. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getName() : string - { - return $this->name; - } - /** * Set function body. * @@ -163,6 +163,19 @@ class FunctionParser $this->body = ''; } + /** + * Get function visibility. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getVisibility() : string + { + return $this->visibility; + } + /** * Set visibility. * @@ -178,19 +191,6 @@ class FunctionParser $this->visibility = $visibility; } - /** - * Get function visibility. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getVisibility() : string - { - return $this->visibility; - } - /** * Set static. * @@ -281,21 +281,6 @@ class FunctionParser return $this->isAbstract; } - /** - * Set return type. - * - * @param string $return Return type - * - * @return void - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function setReturn(string $return) - { - $this->return = $return; - } - /** * Remove return type. * @@ -322,6 +307,21 @@ class FunctionParser return $this->return; } + /** + * Set return type. + * + * @param string $return Return type + * + * @return void + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setReturn(string $return) + { + $this->return = $return; + } + /** * Add parameter to function. * diff --git a/Utils/Parser/Php/MemberParser.php b/Utils/Parser/Php/MemberParser.php index e5d254c25..75b4882d8 100644 --- a/Utils/Parser/Php/MemberParser.php +++ b/Utils/Parser/Php/MemberParser.php @@ -70,6 +70,19 @@ class MemberParser */ private $default = null; + /** + * Get member name. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getName() : string + { + return $this->name; + } + /** * Set member name. * @@ -86,16 +99,16 @@ class MemberParser } /** - * Get member name. + * Get visibility. * * @return string * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getName() : string + public function getVisibility() : string { - return $this->name; + return $this->visibility; } /** @@ -113,19 +126,6 @@ class MemberParser $this->visibility = $visibility; } - /** - * Get visibility. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getVisibility() : string - { - return $this->visibility; - } - /** * Set static. * diff --git a/Utils/TaskSchedule/Interval.php b/Utils/TaskSchedule/Interval.php index 77289de18..b3762679f 100644 --- a/Utils/TaskSchedule/Interval.php +++ b/Utils/TaskSchedule/Interval.php @@ -110,6 +110,26 @@ class Interval implements \Serializable } } + /** + * Unserialize. + * + * @param string $serialized String to unserialize + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function unserialize($serialized) + { + $elements = explode(' ', trim($serialized)); + + $this->minute = $this->parseMinute($elements[0]); + $this->hour = $this->parseHour($elements[1]); + $this->dayOfMonth = $this->parseDayOfMonth($elements[2]); + $this->month = $this->parseMonth($elements[3]); + $this->dayOfWeek = $this->parseDayOfWeek($elements[4]); + $this->year = $this->parseYear($elements[5]); + } + /** * Parse element. * @@ -200,6 +220,19 @@ class Interval implements \Serializable } + /** + * Get start. + * + * @return \DateTime + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getStart() : \DateTime + { + return $this->start; + } + /** * Set start. * @@ -215,19 +248,6 @@ class Interval implements \Serializable $this->start = $start; } - /** - * Get start. - * - * @return \DateTime - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getStart() : \DateTime - { - return $this->start; - } - /** * Get end. * @@ -256,6 +276,19 @@ class Interval implements \Serializable $this->end = $end; } + /** + * Get minute. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getMinute() : array + { + return $this->minute; + } + /** * Set mintue. * @@ -281,6 +314,47 @@ class Interval implements \Serializable } } + /** + * Validate time. + * + * @param array $times Times + * @param int $step Step + * @param int $lowest Lowest limet + * @param int $highest Highest limet + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function validateTime(array $times, int $step, int $lowest, int $highest) : bool + { + foreach ($times as $minute) { + if ($minute > $highest || $minute < $lowest) { + return false; + } + } + + if ($step > $highest || $step < $lowest) { + return false; + } + + return true; + } + + /** + * Get hour. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getHour() : array + { + return $this->hour; + } + /** * Set hour. * @@ -306,6 +380,19 @@ class Interval implements \Serializable } } + /** + * Get day of month. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getDayOfMonth() : array + { + return $this->dayOfMonth; + } + /** * Set day of month. * @@ -337,28 +424,44 @@ class Interval implements \Serializable } /** - * Set month. + * Validate day of month. * - * @param array $month Month - * @param int $step Step - * @param bool $any Any + * @param array $array Element to validate * - * @throws + * @return bool * * @since 1.0.0 * @author Dennis Eichhorn */ - public function setMonth(array $month, int $step = 0, bool $any = false) + private function validateDayOfMonth(array $array) : bool { - if ($this->validateTime($month, $step, 1, 12)) { - $this->month = [ - 'month' => $month, - 'step' => $step, - 'any' => $any, - ]; - } else { - throw new \Exception('Invalid format.'); + foreach ($array['dayOfMonth'] as $dayOfMonth) { + if ($dayOfMonth > 31 || $dayOfMonth < 1) { + return false; + } } + + if ($array['step'] > 31 || $array['step'] < 1) { + return false; + } + if ($array['nearest'] > 31 || $array['nearest'] < 1) { + return false; + } + + return true; + } + + /** + * Get day of week. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getDayOfWeek() : array + { + return $this->dayOfWeek; } /** @@ -389,6 +492,82 @@ class Interval implements \Serializable } } + /** + * Validate day of week. + * + * @param array $array Element to validate + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private function validateDayOfWeek(array $array) : bool + { + foreach ($array['dayOfWeek'] as $dayOfWeek) { + if ($dayOfWeek > 7 || $dayOfWeek < 1) { + return false; + } + } + + if ($array['step'] > 5 || $array['step'] < 1) { + return false; + } + + return true; + } + + /** + * Get month. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getMonth() : array + { + return $this->month; + } + + /** + * Set month. + * + * @param array $month Month + * @param int $step Step + * @param bool $any Any + * + * @throws + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function setMonth(array $month, int $step = 0, bool $any = false) + { + if ($this->validateTime($month, $step, 1, 12)) { + $this->month = [ + 'month' => $month, + 'step' => $step, + 'any' => $any, + ]; + } else { + throw new \Exception('Invalid format.'); + } + } + + /** + * Get year. + * + * @return array + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getYear() : array + { + return $this->year; + } + /** * Set yaer. * @@ -415,165 +594,6 @@ class Interval implements \Serializable } } - /** - * Get minute. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getMinute() : array - { - return $this->minute; - } - - /** - * Get hour. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getHour() : array - { - return $this->hour; - } - - /** - * Get day of month. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getDayOfMonth() : array - { - return $this->dayOfMonth; - } - - /** - * Get day of week. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getDayOfWeek() : array - { - return $this->dayOfWeek; - } - - /** - * Get month. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getMonth() : array - { - return $this->month; - } - - /** - * Get year. - * - * @return array - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getYear() : array - { - return $this->year; - } - - /** - * Validate time. - * - * @param array $times Times - * @param int $step Step - * @param int $lowest Lowest limet - * @param int $highest Highest limet - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function validateTime(array $times, int $step, int $lowest, int $highest) : bool - { - foreach ($times as $minute) { - if ($minute > $highest || $minute < $lowest) { - return false; - } - } - - if ($step > $highest || $step < $lowest) { - return false; - } - - return true; - } - - /** - * Validate day of month. - * - * @param array $array Element to validate - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function validateDayOfMonth(array $array) : bool - { - foreach ($array['dayOfMonth'] as $dayOfMonth) { - if ($dayOfMonth > 31 || $dayOfMonth < 1) { - return false; - } - } - - if ($array['step'] > 31 || $array['step'] < 1) { - return false; - } - if ($array['nearest'] > 31 || $array['nearest'] < 1) { - return false; - } - - return true; - } - - /** - * Validate day of week. - * - * @param array $array Element to validate - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private function validateDayOfWeek(array $array) : bool - { - foreach ($array['dayOfWeek'] as $dayOfWeek) { - if ($dayOfWeek > 7 || $dayOfWeek < 1) { - return false; - } - } - - if ($array['step'] > 5 || $array['step'] < 1) { - return false; - } - - return true; - } - /** * Validate year. * @@ -589,6 +609,26 @@ class Interval implements \Serializable return true; } + /** + * Create string representation. + * + * @return string + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function serialize() + { + $minute = $this->serializeTime($this->minute['minutes'], $this->minute['step']); + $hour = $this->serializeTime($this->hour['hours'], $this->hour['step']); + $dayOfMonth = $this->serializeDayOfMonth(); + $month = $this->serializeTime($this->month['month'], $this->month['step']); + $dayOfWeek = $this->serializeDayOfWeek(); + $year = $this->serializeTime($this->year['year'], $this->year['step']); + + return $minute . ' ' . $hour . ' ' . $dayOfMonth . ' ' . $month . ' ' . $dayOfWeek . ' ' . $year; + } + /** * Create string representation. * @@ -671,44 +711,4 @@ class Interval implements \Serializable return $serialize; } - - /** - * Create string representation. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function serialize() - { - $minute = $this->serializeTime($this->minute['minutes'], $this->minute['step']); - $hour = $this->serializeTime($this->hour['hours'], $this->hour['step']); - $dayOfMonth = $this->serializeDayOfMonth(); - $month = $this->serializeTime($this->month['month'], $this->month['step']); - $dayOfWeek = $this->serializeDayOfWeek(); - $year = $this->serializeTime($this->year['year'], $this->year['step']); - - return $minute . ' ' . $hour . ' ' . $dayOfMonth . ' ' . $month . ' ' . $dayOfWeek . ' ' . $year; - } - - /** - * Unserialize. - * - * @param string $serialized String to unserialize - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function unserialize($serialized) - { - $elements = explode(' ', trim($serialized)); - - $this->minute = $this->parseMinute($elements[0]); - $this->hour = $this->parseHour($elements[1]); - $this->dayOfMonth = $this->parseDayOfMonth($elements[2]); - $this->month = $this->parseMonth($elements[3]); - $this->dayOfWeek = $this->parseDayOfWeek($elements[4]); - $this->year = $this->parseYear($elements[5]); - } } diff --git a/Utils/TaskSchedule/TaskAbstract.php b/Utils/TaskSchedule/TaskAbstract.php index ccac3e21c..0a457ca64 100644 --- a/Utils/TaskSchedule/TaskAbstract.php +++ b/Utils/TaskSchedule/TaskAbstract.php @@ -65,6 +65,19 @@ abstract class TaskAbstract return $this->id; } + /** + * Get interval. + * + * @return Interval + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + public function getInterval() : Interval + { + return $this->interval; + } + /** * Set interval. * @@ -81,16 +94,16 @@ abstract class TaskAbstract } /** - * Get interval. + * Get command. * - * @return Interval + * @return string * * @since 1.0.0 * @author Dennis Eichhorn */ - public function getInterval() : Interval + public function getCommand() : string { - return $this->interval; + return $this->command; } /** @@ -107,17 +120,4 @@ abstract class TaskAbstract { $this->command = $command; } - - /** - * Get command. - * - * @return string - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - public function getCommand() : string - { - return $this->command; - } } diff --git a/Validation/Base/Iban.php b/Validation/Base/Iban.php index 0f87d3031..daa30f336 100644 --- a/Validation/Base/Iban.php +++ b/Validation/Base/Iban.php @@ -14,6 +14,7 @@ * @link http://orange-management.com */ namespace phpOMS\Validation\Base; + use phpOMS\Validation\ValidatorAbstract; @@ -86,36 +87,6 @@ abstract class Iban extends ValidatorAbstract return true; } - /** - * Validate checksum - * - * @param string $iban Iban to validate - * - * @return bool - * - * @since 1.0.0 - * @author Dennis Eichhorn - */ - private static function validateChecksum(string $iban) : bool - { - $chars = ['a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17, 'i' => 18, - 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23, 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, - 's' => 28, 't' => 29, 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35,]; - $moved = substr($iban, 4) . substr($iban, 0, 4); - $movedArray = str_split($moved); - $new = ''; - - foreach ($movedArray as $key => $value) { - if (!is_numeric($movedArray[$key])) { - $movedArray[$key] = $chars[$movedArray[$key]]; - } - - $new .= $movedArray[$key]; - } - - return bcmod($new, '97') == 1; - } - /** * Validate positions that should have zeros * @@ -173,4 +144,34 @@ abstract class Iban extends ValidatorAbstract return true; } + + /** + * Validate checksum + * + * @param string $iban Iban to validate + * + * @return bool + * + * @since 1.0.0 + * @author Dennis Eichhorn + */ + private static function validateChecksum(string $iban) : bool + { + $chars = ['a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15, 'g' => 16, 'h' => 17, 'i' => 18, + 'j' => 19, 'k' => 20, 'l' => 21, 'm' => 22, 'n' => 23, 'o' => 24, 'p' => 25, 'q' => 26, 'r' => 27, + 's' => 28, 't' => 29, 'u' => 30, 'v' => 31, 'w' => 32, 'x' => 33, 'y' => 34, 'z' => 35,]; + $moved = substr($iban, 4) . substr($iban, 0, 4); + $movedArray = str_split($moved); + $new = ''; + + foreach ($movedArray as $key => $value) { + if (!is_numeric($movedArray[$key])) { + $movedArray[$key] = $chars[$movedArray[$key]]; + } + + $new .= $movedArray[$key]; + } + + return bcmod($new, '97') == 1; + } } diff --git a/Validation/Base/IbanErrorType.php b/Validation/Base/IbanErrorType.php index 2bac52769..ea03453e6 100644 --- a/Validation/Base/IbanErrorType.php +++ b/Validation/Base/IbanErrorType.php @@ -14,6 +14,7 @@ * @link http://orange-management.com */ namespace phpOMS\Validation\Base; + use phpOMS\Datatypes\Enum; /**