Page Menu
Home
DevCentral
Search
Configure Global Search
Log In
Files
F3751040
D2493.id6282.diff
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
22 KB
Referenced Files
None
Subscribers
None
D2493.id6282.diff
View Options
diff --git a/src/Collections/BaseCollection.php b/src/Collections/BaseCollection.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/BaseCollection.php
@@ -0,0 +1,26 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Collections;
+
+interface BaseCollection {
+
+ ///
+ /// Constructors
+ ///
+
+ public static function from (iterable $items) : static;
+
+ ///
+ /// Getters
+ ///
+
+ public function toArray () : array;
+
+ ///
+ /// Properties
+ ///
+
+ public function count () : int;
+
+}
diff --git a/src/Collections/BaseMap.php b/src/Collections/BaseMap.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/BaseMap.php
@@ -0,0 +1,17 @@
+<?php
+
+namespace Keruald\OmniTools\Collections;
+
+interface BaseMap {
+
+ public function get (mixed $key) : mixed;
+
+ public function getOr (mixed $key, mixed $defaultValue): mixed;
+
+ public function set (mixed $key, mixed $value) : static;
+
+ public function has (mixed $key) : bool;
+
+ public function contains (mixed $value) : bool;
+
+}
diff --git a/src/Collections/HashMap.php b/src/Collections/HashMap.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/HashMap.php
@@ -0,0 +1,167 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Collections;
+
+use Keruald\OmniTools\Reflection\CallableElement;
+
+use InvalidArgumentException;
+
+/**
+ * An associative array allowing the use of chained
+ *
+ *
+ * This class can be used as a service container,
+ * an application context, to store configuration.
+ */
+class HashMap implements BaseCollection, BaseMap {
+
+ ///
+ /// Properties
+ ///
+
+ private array $map;
+
+ ///
+ /// Constructor
+ ///
+
+ public function __construct (iterable $iterable = []) {
+ if (is_array($iterable)) {
+ $this->map = (array)$iterable;
+ return;
+ }
+
+ foreach ($iterable as $key => $value) {
+ $this->map[$key] = $value;
+ }
+ }
+
+ public static function from (iterable $items) : static {
+ return new self($items);
+ }
+
+ ///
+ /// Interact with map content at key level
+ ///
+
+ public function get (mixed $key) : mixed {
+ if (!array_key_exists($key, $this->map)) {
+ throw new InvalidArgumentException("Key not found.");
+ }
+
+ return $this->map[$key];
+ }
+
+ public function getOr (mixed $key, mixed $defaultValue) : mixed {
+ return $this->map[$key] ?? $defaultValue;
+ }
+
+ public function set (mixed $key, mixed $value) : static {
+ $this->map[$key] = $value;
+
+ return $this;
+ }
+
+ public function has (mixed $key) : bool {
+ return array_key_exists($key, $this->map);
+ }
+
+ public function contains (mixed $value) : bool {
+ return in_array($value, $this->map);
+ }
+
+ ///
+ /// Interact with collection content at collection level
+ ///
+
+ public function count () : int {
+ return count($this->map);
+ }
+
+ public function clear () : self {
+ $this->map = [];
+
+ return $this;
+ }
+
+ /**
+ * Merge the specified map with the current map.
+ *
+ * If a key already exists, the value already set is kept.
+ *
+ * @see update() when you need to update with the new value.
+ */
+ public function merge (iterable $iterable) : self {
+ foreach ($iterable as $key => $value) {
+ $this->map[$key] ??= $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Merge the specified map with the current bag.
+ *
+ * If a key already exists, the value is updated with the new one.
+ *
+ * @see merge() when you need to keep old value.
+ */
+ public function update (iterable $iterable) : self {
+ foreach ($iterable as $key => $value) {
+ $this->map[$key] = $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Gets a copy of the internal map.
+ *
+ * Scalar values (int, strings) are cloned.
+ * Objects are references to a specific objet, not a clone.
+ *
+ * @return array<string, mixed>
+ */
+ public function toArray () : array {
+ return $this->map;
+ }
+
+ ///
+ /// HOF
+ ///
+
+ public function map (callable $callable) : self {
+ return new self(array_map($callable, $this->map));
+ }
+
+ public function filter (callable $callable) : self {
+ $argc = (new CallableElement($callable))->countArguments();
+ if ($argc === 0) {
+ throw new InvalidArgumentException(
+ "Callback should have at least one argument"
+ );
+ }
+ $mode = (int)($argc > 1);
+
+ return new self(
+ array_filter($this->map, $callable, $mode)
+ );
+ }
+
+ public function mapKeys (callable $callable) : self {
+ $mappedMap = [];
+ foreach ($this->map as $key => $value) {
+ $mappedMap[$callable($key)] = $value;
+ }
+
+ return new self($mappedMap);
+ }
+
+ public function filterKeys (callable $callable) : self {
+ return new self(
+ array_filter($this->map, $callable, ARRAY_FILTER_USE_KEY)
+ );
+ }
+
+}
diff --git a/src/Collections/OmniArray.php b/src/Collections/OmniArray.php
deleted file mode 100644
--- a/src/Collections/OmniArray.php
+++ /dev/null
@@ -1,69 +0,0 @@
-<?php
-declare(strict_types=1);
-
-namespace Keruald\OmniTools\Collections;
-
-use Keruald\OmniTools\Strings\Multibyte\OmniString;
-
-class OmniArray {
-
- /**
- * @var array
- */
- private $items = [];
-
- ///
- /// Constructors
- ///
-
- public function __construct (?iterable $items = null) {
- if ($items === null) {
- return;
- }
-
- if (is_array($items)) {
- $this->items = $items;
-
- return;
- }
-
- foreach ($items as $item) {
- $this->items[] = $item;
- }
- }
-
- public static function explode (string $delimiter, string $string,
- int $limit = PHP_INT_MAX) : self {
- return (new OmniString($string))
- ->explode($delimiter, $limit);
- }
-
- ///
- /// Transformation methods
- ///
-
- public function toIntegers () : self {
- array_walk($this->items, ArrayUtilities::toIntegerCallback());
-
- return $this;
- }
-
- public function map (callable $callable) : self {
- $items = array_map($callable, $this->items);
-
- return new self($items);
- }
-
- public function implode(string $delimiter) : OmniString {
- return new OmniString(implode($delimiter, $this->items));
- }
-
- ///
- /// Getters methods
- ///
-
- public function toArray () : array {
- return $this->items;
- }
-
-}
diff --git a/src/Collections/SharedBag.php b/src/Collections/SharedBag.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/SharedBag.php
@@ -0,0 +1,32 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Collections;
+
+/**
+ * A shared bag is a collection of key and values, which implements
+ * a monostate pattern, i.e. there is only one bag, which can be accessed
+ * though an arbitrary amount of SharedBag instances.
+ *
+ * The SharedBag class can be used as:
+ * — shared context, to contain the application configuration
+ * — service locator, to contain application dependencies
+ * — a migration path to store global variables of a legacy application
+ * pending the migration to a collection sharing the same interface
+ *
+ * Such patterns can be discouraged and as such used with architectural care,
+ * as they mainly use SharedBag as global variables, or as an antipattern.
+ */
+class SharedBag {
+
+ private static ?HashMap $bag = null;
+
+ public function getBag() : HashMap {
+ if (self::$bag === null) {
+ self::$bag = new HashMap;
+ }
+
+ return self::$bag;
+ }
+
+}
diff --git a/src/Collections/TraversableUtilities.php b/src/Collections/TraversableUtilities.php
--- a/src/Collections/TraversableUtilities.php
+++ b/src/Collections/TraversableUtilities.php
@@ -4,6 +4,7 @@
namespace Keruald\OmniTools\Collections;
use Countable;
+use InvalidArgumentException;
use ResourceBundle;
use SimpleXMLElement;
use TypeError;
@@ -11,7 +12,7 @@
class TraversableUtilities {
public static function count ($countable) : int {
- if (self::isCountable($countable)) {
+ if (is_countable($countable)) {
return count($countable);
}
@@ -22,6 +23,29 @@
throw new TypeError;
}
+ public static function first (iterable $iterable) : mixed {
+ foreach ($iterable as $value) {
+ return $value;
+ }
+
+ throw new InvalidArgumentException(
+ "Can't call first() on an empty iterable."
+ );
+ }
+
+ public static function firstOr (
+ iterable $iterable, mixed $defaultValue = null
+ ) : mixed {
+ foreach ($iterable as $value) {
+ return $value;
+ }
+
+ return $defaultValue;
+ }
+
+ /**
+ * @deprecated Use \is_countable
+ */
public static function isCountable ($countable) : bool {
if (function_exists('is_countable')) {
// PHP 7.3 has is_countable
diff --git a/src/Collections/Vector.php b/src/Collections/Vector.php
new file mode 100644
--- /dev/null
+++ b/src/Collections/Vector.php
@@ -0,0 +1,206 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Collections;
+
+use Keruald\OmniTools\Reflection\CallableElement;
+use Keruald\OmniTools\Strings\Multibyte\OmniString;
+
+use InvalidArgumentException;
+
+class Vector implements BaseCollection {
+
+ ///
+ /// Properties
+ ///
+
+ private array $items;
+
+ ///
+ /// Constructors
+ ///
+
+ public function __construct (iterable $items = []) {
+ if (is_array($items)) {
+ $this->items = $items;
+ return;
+ }
+
+ foreach ($items as $value) {
+ $this->items[] = $value;
+ }
+ }
+
+ public static function from (iterable $items) : static {
+ return new self($items);
+ }
+
+ ///
+ /// Specialized constructors
+ ///
+
+ /**
+ * Constructs a new instance of a vector by exploding a string
+ * according a specified delimiter.
+ *
+ * @param string $delimiter The substring to find for explosion
+ * @param string $string The string to explode
+ * @param int $limit If specified, the maximum count of vector elements
+ * @return static
+ */
+ public static function explode (string $delimiter, string $string,
+ int $limit = PHP_INT_MAX) : self {
+ // There is some discussion to know if this method belongs
+ // to Vector or OmniString.
+ //
+ // The advantage to keep it here is we can have constructs like:
+ // Vector::explode(",", "1,1,2,3,5,8,13")
+ // ->toIntegers()
+ // >map(function($n) { return $n * $n; })
+ // ->toArray();
+ //
+ // In this chaining, it is clear we manipulate Vector methods.
+
+ return (new OmniString($string))
+ ->explode($delimiter, $limit);
+ }
+
+ ///
+ /// Interact with collection content at key level
+ ///
+
+ public function get (int $key) : mixed {
+ if (!array_key_exists($key, $this->items)) {
+ throw new InvalidArgumentException("Key not found.");
+ }
+
+ return $this->items[$key];
+ }
+
+ public function getOr (int $key, mixed $defaultValue) : mixed {
+ return $this->items[$key] ?? $defaultValue;
+ }
+
+ public function set (int $key, mixed $value) : static {
+ $this->items[$key] = $value;
+
+ return $this;
+ }
+
+ public function contains (mixed $value) : bool {
+ return in_array($value, $this->items);
+ }
+
+
+ ///
+ /// Interact with collection content at collection level
+ ///
+
+ public function count () : int {
+ return count($this->items);
+ }
+
+ public function clear () : self {
+ $this->items = [];
+
+ return $this;
+ }
+
+ /**
+ * Append all elements of the specified iterable
+ * to the current vector.
+ *
+ * If a value already exists, the value is still added
+ * as a duplicate.
+ *
+ * @see update() when you need to only add unique values.
+ */
+ public function append (iterable $iterable) : self {
+ foreach ($iterable as $value) {
+ $this->items[] = $value;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Append all elements of the specified iterable
+ * to the current vector.
+ *
+ * If a value already exists, it is skipped.
+ *
+ * @see append() when you need to always add everything.
+ */
+ public function update (iterable $iterable) : self {
+ foreach ($iterable as $value) {
+ if (!$this->contains($value)) {
+ $this->items[] = $value;
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Gets a copy of the internal vector.
+ *
+ * Scalar values (int, strings) are cloned.
+ * Objects are references to a specific objet, not a clone.
+ *
+ * @return array
+ */
+ public function toArray () : array {
+ return $this->items;
+ }
+
+ ///
+ /// HOF :: generic
+ ///
+
+ public function map (callable $callable) : self {
+ return new self(array_map($callable, $this->items));
+ }
+
+ public function filter (callable $callable) : self {
+ $argc = (new CallableElement($callable))->countArguments();
+
+ if ($argc === 0) {
+ throw new InvalidArgumentException(
+ "Callback should have at least one argument"
+ );
+ }
+
+ $mode = (int)($argc > 1);
+ return new self(array_filter($this->items, $callable, $mode));
+ }
+
+ public function mapKeys (callable $callable) : self {
+ $mappedVector = [];
+ foreach ($this->items as $key => $value) {
+ $mappedVector[$callable($key)] = $value;
+ }
+
+ return new self($mappedVector);
+ }
+
+ public function filterKeys (callable $callable) : self {
+ return new self(
+ array_filter($this->items, $callable, ARRAY_FILTER_USE_KEY)
+ );
+ }
+
+ ///
+ /// HOF :: specialized
+ ///
+
+ public function toIntegers () : self {
+ array_walk($this->items, ArrayUtilities::toIntegerCallback());
+
+ return $this;
+ }
+
+ public function implode(string $delimiter) : OmniString {
+ return new OmniString(implode($delimiter, $this->items));
+ }
+
+}
diff --git a/src/DateTime/DateStamp.php b/src/DateTime/DateStamp.php
--- a/src/DateTime/DateStamp.php
+++ b/src/DateTime/DateStamp.php
@@ -3,7 +3,7 @@
namespace Keruald\OmniTools\DateTime;
-use Keruald\OmniTools\Collections\OmniArray;
+use Keruald\OmniTools\Collections\Vector;
use DateTime;
use InvalidArgumentException;
@@ -47,7 +47,7 @@
public static function parse (string $date) : self {
if (preg_match("/^[0-9]{4}\-[0-1][0-9]\-[0-3][0-9]$/", $date)) {
// YYYY-MM-DD
- $args = OmniArray::explode("-", $date)
+ $args = Vector::explode("-", $date)
->toIntegers()
->toArray();
diff --git a/src/HTTP/URL.php b/src/HTTP/URL.php
--- a/src/HTTP/URL.php
+++ b/src/HTTP/URL.php
@@ -194,11 +194,11 @@
}
public static function normalizeDomain (string $domain) : string {
- return idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
+ return \idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
}
public static function beautifyDomain (string $domain) : string {
- return idn_to_utf8($domain, 0, INTL_IDNA_VARIANT_UTS46);
+ return \idn_to_utf8($domain, 0, INTL_IDNA_VARIANT_UTS46);
}
public function __toString () {
diff --git a/src/Reflection/CallableElement.php b/src/Reflection/CallableElement.php
new file mode 100644
--- /dev/null
+++ b/src/Reflection/CallableElement.php
@@ -0,0 +1,75 @@
+<?php
+declare(strict_types=1);
+
+namespace Keruald\OmniTools\Reflection;
+
+use Closure;
+use http\Exception\InvalidArgumentException;
+use ReflectionException;
+use ReflectionFunction;
+use ReflectionFunctionAbstract;
+use ReflectionMethod;
+
+class CallableElement {
+
+ private ReflectionFunctionAbstract $callable;
+
+ /**
+ * @throws ReflectionException
+ */
+ public function __construct (callable $callable) {
+ $this->callable = self::getReflectionFunction($callable);
+ }
+
+ /**
+ * @throws ReflectionException
+ */
+ private static function getReflectionFunction (callable $callable)
+ : ReflectionFunctionAbstract {
+
+ ///
+ /// Functions
+ ///
+
+ if ($callable instanceof Closure) {
+ return new ReflectionFunction($callable);
+ }
+
+ ///
+ /// Objets and methods
+ ///
+
+ if (is_array($callable)) {
+ return new ReflectionMethod($callable[0], $callable[1]);
+ }
+
+ if (is_object($callable)) {
+ // If __invoke() doesn't exist, the objet isn't a callable.
+ // Calling this method with such object would throw a TypeError
+ // before reaching this par of the code, so it is safe to assume
+ // we can correctly call it.
+ return new ReflectionMethod([$callable, '__invoke']);
+ }
+
+ ///
+ /// Hybrid cases
+ ///
+
+ if (is_string($callable)) {
+ if (!str_contains($callable, "::")) {
+ return new ReflectionFunction($callable);
+ }
+
+ return new ReflectionMethod($callable);
+ }
+
+ throw new InvalidArgumentException(
+ "Callable not recognized: " . gettype($callable)
+ );
+ }
+
+ public function countArguments () : int {
+ return $this->callable->getNumberOfParameters();
+ }
+
+}
diff --git a/src/Strings/Multibyte/OmniString.php b/src/Strings/Multibyte/OmniString.php
--- a/src/Strings/Multibyte/OmniString.php
+++ b/src/Strings/Multibyte/OmniString.php
@@ -3,7 +3,7 @@
namespace Keruald\OmniTools\Strings\Multibyte;
-use Keruald\OmniTools\Collections\OmniArray;
+use Keruald\OmniTools\Collections\Vector;
class OmniString {
@@ -54,11 +54,11 @@
}
public function startsWith (string $start) : bool {
- return StringUtilities::startsWith($this->value, $start);
+ return str_starts_with($this->value, $start);
}
public function endsWith (string $end) : bool {
- return StringUtilities::endsWith($this->value, $end);
+ return str_ends_with($this->value, $end);
}
public function len () : int {
@@ -76,7 +76,7 @@
return $chars;
}
- public function getBigrams () {
+ public function getBigrams () : array {
$bigrams = [];
$len = $this->len();
@@ -92,16 +92,16 @@
///
public function explode (string $delimiter,
- int $limit = PHP_INT_MAX) : OmniArray {
+ int $limit = PHP_INT_MAX) : Vector {
if ($delimiter === "") {
if ($limit < 0) {
- return new OmniArray;
+ return new Vector;
}
- return new OmniArray([$this->value]);
+ return new Vector([$this->value]);
}
- return new OmniArray(explode($delimiter, $this->value, $limit));
+ return new Vector(explode($delimiter, $this->value, $limit));
}
///
@@ -118,7 +118,7 @@
/**
* @param string $value
*/
- public function setValue (string $value) {
+ public function setValue (string $value) : void {
$this->value = $value;
}
diff --git a/src/Strings/Multibyte/StringUtilities.php b/src/Strings/Multibyte/StringUtilities.php
--- a/src/Strings/Multibyte/StringUtilities.php
+++ b/src/Strings/Multibyte/StringUtilities.php
@@ -43,18 +43,27 @@
return false;
}
- public static function startsWith (string $string, string $start) {
+ /**
+ * @deprecated Since PHP 8.0, we can replace by \str_starts_with
+ */
+ public static function startsWith (string $string, string $start) : bool {
$length = mb_strlen($start);
return mb_substr($string, 0, $length) === $start;
}
- public static function endsWith (string $string, string $end) {
+ /**
+ * @deprecated Since PHP 8.0, we can replace by \str_ends_with
+ */
+ public static function endsWith (string $string, string $end) : bool {
$length = mb_strlen($end);
return $length === 0 || mb_substr($string, -$length) === $end;
}
+ /**
+ * @deprecated Since PHP 8.0, we can replace by \str_contains
+ */
public static function contains (string $string, string $needle) : bool {
- return strpos($string, $needle) !== false;
+ return str_contains($string, $needle);
}
/**
diff --git a/tests/Collections/OmniArrayTest.php b/tests/Collections/OmniArrayTest.php
--- a/tests/Collections/OmniArrayTest.php
+++ b/tests/Collections/OmniArrayTest.php
@@ -3,13 +3,13 @@
namespace Keruald\OmniTools\Tests\Collections;
-use Keruald\OmniTools\Collections\OmniArray;
+use Keruald\OmniTools\Collections\Vector;
use PHPUnit\Framework\TestCase;
class OmniArrayTest extends TestCase {
public function testMap () : void {
- $actual = (new OmniArray([1, 2, 3, 4, 5]))
+ $actual = (new Vector([1, 2, 3, 4, 5]))
->map(function ($x) { return $x * $x; })
->toArray();
@@ -17,7 +17,7 @@
}
public function testImplode() : void {
- $actual = (new OmniArray(["a", "b", "c"]))
+ $actual = (new Vector(["a", "b", "c"]))
->implode(".")
->__toString();
@@ -25,7 +25,7 @@
}
public function testImplodeWithoutDelimiter() : void {
- $actual = (new OmniArray(["a", "b", "c"]))
+ $actual = (new Vector(["a", "b", "c"]))
->implode("")
->__toString();
@@ -33,13 +33,13 @@
}
public function testExplode() : void {
- $actual = OmniArray::explode(".", "a.b.c");
+ $actual = Vector::explode(".", "a.b.c");
$this->assertEquals(["a", "b", "c"], $actual->toArray());
}
public function testExplodeWithoutDelimiter() : void {
- $actual = OmniArray::explode("", "a.b.c");
+ $actual = Vector::explode("", "a.b.c");
$this->assertEquals(["a.b.c"], $actual->toArray());
}
File Metadata
Details
Attached
Mime Type
text/plain
Expires
Mon, Nov 18, 05:32 (20 h, 46 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2250312
Default Alt Text
D2493.id6282.diff (22 KB)
Attached To
Mode
D2493: WIP: refresh collections
Attached
Detach File
Event Timeline
Log In to Comment