From 825825071c04d9e002d68e6f23211a99351fa93d Mon Sep 17 00:00:00 2001 From: Riddick Date: Mon, 30 Sep 2024 15:17:02 +0200 Subject: [PATCH] Create Bag support class (#95) --- src/support/firehub.Bag.php | 103 ++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/support/firehub.Bag.php diff --git a/src/support/firehub.Bag.php b/src/support/firehub.Bag.php new file mode 100644 index 000000000..10abb173f --- /dev/null +++ b/src/support/firehub.Bag.php @@ -0,0 +1,103 @@ + + * @copyright 2024 FireHub Web Application Framework + * @license OSL Open Source License version 3 + * + * @package Core\Support + * + * @version GIT: $Id$ Blob checksum. + */ + +namespace FireHub\Core\Support; + +use FireHub\Core\Base\ { + Init, Trait\Concrete +}; +use FireHub\Core\Support\Contracts\HighLevel\ReadCollectable; +use FireHub\Core\Support\LowLevel\ { + Arr, Cls +}; + +/** + * ### Bag list + * @since 1.0.0 + */ +abstract class Bag implements Init { + + /** + * ### FireHub initial concrete trait + * @since 1.0.0 + */ + use Concrete; + + /** + * ### Constructor + * @since 1.0.0 + * + * @uses \FireHub\Core\Support\Contracts\HighLevel\ReadCollectable::all() To get collectable as an array. + * @uses \FireHub\Core\Support\Bag::fillContent() To fill bag properties. + * + * @param array>|\FireHub\Core\Support\Contracts\HighLevel\ReadCollectable> $content

+ * Bag content. + *

+ * + * @return void + */ + final public function __construct (array|ReadCollectable $content) { + + /** @phpstan-ignore-next-line */ + $this->fillContent($content instanceof ReadCollectable ? $content->all() : $content); + + } + + /** + * ### Adapt key names + * @since 1.0.0 + * + * @return array List of adapted key names, with a list like ['new key name', 'old key name']. + */ + protected function adapt ():array { + + return []; + + } + + /** + * ### Fill bag properties + * @since 1.0.0 + * + * @uses \FireHub\Core\Support\LowLevel\Arr::search() Search adapt key. + * @uses \FireHub\Core\Support\Bag::adapt() Adapt key names. + * @uses \FireHub\Core\Support\Str::from() To create a new string from raw string. + * @uses \FireHub\Core\Support\Str::toLower() To lowercase all bag content. + * @uses \FireHub\Core\Support\Str::string() To print string. + * @uses \FireHub\Core\Support\LowLevel\Cls::propertyExist() To check if bag content value exists. + * + * @param array> $array

+ * Bag content. + *

+ * + * @return void + */ + private function fillContent (array $array):void { + + foreach ($array as $key => $value) { + + $adapt = Arr::search($key, $this->adapt()); + + if ($adapt) $key = $adapt; + + $key = Str::from($key)->toLower()->string(); + + /** @phpstan-ignore-next-line */ + if (Cls::propertyExist($this, $key)) $this->$key = $value; + + } + + } + +} \ No newline at end of file