Skip to content

Class: Nether\Object\Datastore

Bob Magic II edited this page Aug 13, 2022 · 14 revisions

This class is a wrapper for arrays to allow datasets to be treated as both arrays and objects with chainable helper methods.

Implements ArrayAccess, Iterator, Countable

On the surface Datastore objects can be treated like normal arrays. To start with you give it an array of data you want to work with or nothing to start with an empty dataset.

$Dataset = [
	'Captain'         => 'Benjamin Sisko',
	'Chief Engineer'  => 'Miles O\'Brien',
	'Science Officer' => 'Jadzia Dax'
];

$Data = new Nether\Object\Datastore($Dataset);
print_r($Data);
Nether\Object\Datastore Object
(
    [Captain] => Benjamin Sisko
    [Chief Engineer] => Miles O'Brien
    [Science Officer] => Jadzia Dax
)
var_dump($Data['Captain']);

foreach($Data as $Key => $Val)
printf('%s: %s%s', $Key, $Val, PHP_EOL);
string(14) "Benjamin Sisko"

Captain: Benjamin Sisko
Chief Engineer: Miles O'Brien
Science Officer: Jadzia Dax

General Methods

Count(): int

Return how many items are in this dataset.


Each(callable $Func, ?array $Argv)

  • $Func(mixed $Value, mixed $Key, Datastore $Data, ...): void

Run this function once for every item in this dataset. If additional arguments are supplied they will be added. Best for just looping over the dataset when not needing to alter it.


Get(int|string $Key): mixed

Get whatever is stored under this key.


GetRef(int|string $Key): &mixed

Same as Get but returns a reference of the value. Note that PHP requires you also use the reference operator on your side of the request as like a means to confirm that is what you really wanted, it seems.

$RefToVal = &$Datastore->GetRef('Whatevs');

Additionally it is wise to use HasKey() before GetRef() since NULL cannot be returned from functions that return references, an exception will be thrown if you attempt to GetRef something that does not exist in your dataset.


GetFirstKey(): mixed

Returns what the key name is for the first item in this dataset via array_key_first.


GetLastKey(): mixed

Returns what the key name is for the first item in this dataset via array_key_last.


HasKey(int|string $Key): bool

Returns if the key specified for exists in the dataset.


HasValue(mixed $Val, bool $Strict=FALSE): bool

Returns if the value specified is found in the dataset.


IsFirstKey(mixed $Key): bool

Returns if the key you specified is the first item item of this dataset.


IsLastKey(mixed $Key): bool

Returns if the key you specified is the last item item of this dataset.


Keys(): array

Returns an array listing all the keys of this dataset via array_keys.


Values(): array

Returns a new array with fresh indexing via array_values.


Manipulation API

Chainable Methods


Clear(): self

Dump the dataset, starting anew.


Filter(callable $Func): self

  • $Func(mixed $Val): bool
  • See Also: Distill()

Modify this Datastore filtering the data with the specified callable. The callable gets the current item in question and should return TRUE to keep this item or FALSE to filter it out.


Push(mixed $Val, mixed $Key=NULL): self

  • See Also: Shove()

Add a new item to the end of this dataset. If a key is specified it will be set under that key rather than appended.


Reindex(): self

  • See Also: Revalue()

Reindexes this dataset to remove any gaps from the numeric keys. String keys are preserved as they were.


Remap(callable $Func): self

  • $Func(mixed $Val): mixed
  • See Also: Map()

This works the same as Map except instead of returning a new Datastore, it will modify this one in-place.


RemapKeys(callable $Func): self

  • $Func(mixed $Key, mixed $Val, Datastore $Self): mixed
  • See Also: MapKeys()

This works the same as MapKeys, except instead of returning a new Datastore, it will modify this one in-place.


Remove(mixed $Key): self

Remove the specified item from the dataset.


Revalue(): self

  • See Also: Values()

Renumbers the entire dataset using array_values. Removes all gaps in numbering and all keys will be numeric.


Shove(mixed $Key, mixed $Value): self

  • See Also: Push()

Store this value under this key.


Shuffle(): self

Randomize this dataset in-place.


Sort(callable $Func): self

  • $Func(mixed $A, mixed $B): int

Sorts this dataset using the given function.


Unshift(mixed $Value): self

Prepends the given value to the beginning of the dataset.


Value Returning Methods

Accumulate(mixed $Initial, callable $Func): mixed

  • $Func(mixed $Carry, mixed $Value): mixed

Relay an initial value through the entire array and get the result. Basically the telephone game. The callable should return a value that then gets passed to the next item in that array.

The trick to remembering the argument order for both the API call and the callback function is to remember they are the same. So if you can remember that the callback's first argument is the accumulator, then remember the API call's first argument is the initial value.


Distill(callable $Func): Datastore

  • $Func(mixed $Val): bool
  • See Also: Filter()

Return a new Datastore that is the result of filtering this one with the specified callable. The callable gets the current item in question and should return TRUE to keep this item or FALSE to filter it out.


Join(string $Delimiter): string

Collapse this dataset into a string via join - you should make sure that your dataset only contains things that PHP will be able to join before doing it, just like you would using join or implode.


Map(callable $Func): Datastore

  • $Func(mixed $Val): mixed
  • See Also: Remap()

Return a new Datastore that is the result of mapping this one via array_map. Can be used to simplify or replace items in the dataset. The callable gets the current item and should return what that item should be after this.


MapKeys(callable $Func): Datastore

  • $Func(mixed $Key, mixed $Val, Datastore $Self): array<NewKey, $Value>
  • See Also: RemapKeys()

This will return a new datastore that can potentially have its data keys completely remapped using the supplied callable. This means you can "move" data from one key to another. Given a dataset that has [ 'One'=>1 ], a callable that consumes this and returns [ 'Uno'=>1 ] will have the data moved, meaning One will no longer exist, with Uno containing the value.

$Data = new Nether\Object\Datastore([ 'One'=> 1, 'Two'=> 2 ]);
$Data->RemapKeys(function(mixed $Key, mixed $Val){
	$Key = match($Key) {
		'One'=> 'Uno',
		'Two'=> 'Dos'
	};

	return [ $Key=> $Val ];
});

print_r($Data);

// Nether\Object\Datastore Object
// (
//    [Uno] => 1
//    [Dos] => 2
// )

Pop(): mixed

Removes then returns the last item in the dataset.


Shift(): mixed

Shifts the first item off the dataset and returns it.


Merging API

// todo - documentation


File API

Read(string $Filename): self

Read a file into this datastore. It supports files of two formats: JSON and PHP's Serialize having been written to disk.


Write(string $Filename): self

Write the contents of this datastore to disk. By default it will write a dump of PHP's Serialise, but if the filename ends with .json or you manually set the format to JSON then it writes JSON.


GetFormat(): int

SetFormat(int $Format): self

There are two supported which are class constants.

  • Datastore::FormatPHP = 1
  • Datastore::FormatJSON = 2