Map
Map
Enhanced array access class.
The Map class acts similar to a normal PHP Array but extends it's functionality considerably. You are able to reset a Map to default values, easily extend using another Map or Array, have more simplified access to array key functions, as well as output to various formats such as Array or JSON.
Example
$map = new Hazaar\Map();
$map->depth0->depth1->depth2 = ['foo', 'bar'];
echo $map->toJson();
The above example will print the JSON string:
{ "depth0" : { "depth1" : { "depth2" : [ "foo", "bar" ] } } }
Filters
Filters are callback functions or class methods that are executed upon a get/set call. There are two methods used for applying filters.
- Map::addInputFilter() - Executes the filter when the element is added to the Map (set).
- Map::addOutputFilter() - Executes the filter when the element is read from the Map (get).
The method executed is passed two arguments, the value and the key, in that order. The method must return the value that it wants to be used or stored.
Using Filters
Here is an example of using an input filter to convert a Date object into an array of MongoDate and a timezone field.
$callback = function($value, $key){
if(is_a('\Hazaar\Date', $value)){
$value = new Map([
'datetime' => new MongoDate($value),
'timezone' => $value['timezone']
]);
}
return $value;
}
$map->addInputFilter($callback, '\Hazaar\Date', true);
Here is an example of using an output filter to convert an array with two elements back into a Date object.
$callback = funcion($value, $key){
if(Map::is_array($value) && isset('datetime', $value) && isset('timezone', $value)){
$value = new \Hazaar\Date($value['datetime'], $value['timezone']);
}
return $value;
}
$map->addInputFilter($callback, '\Hazaar\Map', true);
The second parameter to the addInputFilter/addOutputFilter methods is a class condition, meaning that the callback will only be called on objects of that type (uses is_a() internally).
The third parameter says that you want the filter to be applied to all child Map elements as well. This is a very powerful feature that will allow type modification of any element at any depth of the Map.
- Full name:
\Hazaar\Map
- This class implements:
\ArrayAccess
,\Iterator
,\Countable
Properties
defaults
Holds the original child objects and values.
protected array $defaults
elements
Holds the active elements.
protected array $elements
current
The current value for array access returned by Map::each().
protected mixed $current
locked
Allows the map to be locked so that it's values are not accidentally changed.
protected bool $locked
filter
Optional filter definition to modify objects as they are set or get.
private array<string,array<string,mixed>[]> $filter
Filters are an array with the following keys:
- callback - The method to execute. Can be a PHP callback definition or function name.
- class - A class name or array of class names that that the callback will be executed on. Null means all elements.
- recurse - Whether this filter should be recursively added to new and existing child elements
Methods
__construct
The Map constructor sets up the default state of the Map. You can pass an array or another Map object to use as default values.
public __construct(mixed $defaults = [], mixed $extend = [], array<string,array<string,mixed>[]> $filter_def = []): mixed
In the constructor you can also optionally extend the defaults. This is useful for when you have a default set of values that may or may not exist in the extended array.
Example
$config = ['enabled' => true];
$map = new Hazaar\Map([
'enabled' => false,
'label' => 'Test Map'
], $config);
var_dump($map->toArray());
This will output the following text:
array (size=2)
'enabled' => boolean true
'label' => string 'Test Map' (length=8)
!!! notice If the input arguments are strings then the Map class will try and figure out what kind of string it is and either convert from JSON or unserialize the string.
Parameters:
Parameter | Type | Description |
---|---|---|
$defaults | mixed | Default values will set the default state of the Map |
$extend | mixed | Extend the default values overwriting existing key values and creating new ones |
$filter_def | array<string,array<string,mixed>[]> | Optional filter definition |
__isset
Magic method to test if an element exists.
public __isset(string $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
Return Value:
true if the element exists, false otherwise
__set
Magic method to allow -> access to when setting a new kay value.
public __set(string $key, mixed $value): void
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | |
$value | mixed |
__unset
Magic method to remove an element.
public __unset(string $key): void
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
__toString
Magic method to convert the map to a string. See Map::toString();.
public __toString(): string
__sleep
public __sleep(): array
_
public static _(mixed $array, null|array|\Hazaar\Map $args): mixed
- This method is static.
Parameters:
Parameter | Type | Description |
---|---|---|
$array | mixed | |
$args | null|array|\Hazaar\Map |
populate
Populate sets up the array with initial values.
public populate(array|\Hazaar\Map $defaults, bool $erase = true): \Hazaar\Map
- This can be used to construct the initial array after it has been instatiated.
- It can also be used to reset an array with different values.
Input filters are also applied at this point so that default elements can also be modified.
!!! warning This method will overwrite ALL values currently in the Map.
Parameters:
Parameter | Type | Description |
---|---|---|
$defaults | array|\Hazaar\Map | map or Array of values to initialise the Map with |
$erase | bool | If TRUE resets the default values. If FALSE, then the existing defaults are kept but will be overwritten by any new values or created if they do not already exist. Use this to add new default values after the object has been created. |
merge
Merge this Map and new values into a new Map.
public merge(array|\Hazaar\Map $array): \Hazaar\Map
This is similar to Map::populate() except that the existing values will be removed first and new values will be added and/or overwrite those existing values.
Parameters:
Parameter | Type | Description |
---|---|---|
$array | array|\Hazaar\Map | the array being merged in |
commit
Commit any changes to be the new default values.
public commit(bool $recursive = true): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$recursive | bool | recurse through any child Map objects and also commit them |
Return Value:
True on success. False otherwise.
clear
Clear all values from the array.
public clear(): void
It is still possible to reset the array back to it's default state after doing this.
isEmpty
Check whether the map object is empty or not.
public isEmpty(): bool
reset
Reset the Map back to its default values.
public reset(bool $recursive = false): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$recursive | bool |
cancel
The cancel method will flush the default elements so that all elements are considered new or changed.
public cancel(bool $recursive = true): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$recursive | bool |
count
Countable interface method. This method is called when a call to count() is made on this object.
public count(bool $ignorenulls = false): int
Parameters:
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool |
Return Value:
the number of elements in this Map
has
Test if an element exists in the Map object.
public has(string $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
Return Value:
true if the element exists, false otherwise
read
Read will return either the value stored with the specified key, or the default value. This is essentially same as doing:
public read(string $key, mixed $default, bool $insert = false): mixed
$value = ($map->has('key')?$map->key:$default);
It has the added benefits however, of being more streamlined and also allowing the value to be added automatically if it doesn't exist.
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | |
$default | mixed | |
$insert | bool |
getDefault
Get the default value for a value stored in the Map object.
public getDefault(string $key): mixed
This is useful for getting the original value of a value that has changed. Such as an original index number or other identifier.
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
hasChanges
Test if there are any changes to this Map object. Changes include not just changes to element values but any new elements added or any elements being removed.
public hasChanges(): bool
Return Value:
true if there are any changes/additions/removal of elements, false otherwise
getChanges
Return an array of element value changes that have been made to this Map.
public getChanges(): \Hazaar\Map
Return Value:
An Map of changed elements
hasRemoves
Test if any values have been removed.
public hasRemoves(): bool
Return Value:
True if one or more values have been removed. False otherwise.
getRemoves
Return a list of keys that have been removed.
public getRemoves(): \Hazaar\Map
Return Value:
a Map of key names that have been removed from this Map
hasNew
Test if there are any new elements in the Map.
public hasNew(): bool
Return Value:
true if there are new elements, false otherwise
getNew
Return any new elements in the Map.
public getNew(): \Hazaar\Map
Return Value:
An map of only new elements in the Map
extend
Extend the Map using elements from another Map or Array.
public extend(): \Hazaar\Map
pop
Pop an element off of the Map.
public pop(string $key = null): mixed
This will by default pop an element off the end of an array. However this method allows for an element key to be specified which will pop that specific element off the Map.
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | Optionally specify the array element to pop off |
Return Value:
The element in the last position of the Map
push
Push an element on to the end of the Map.
public push(mixed $value): int
Parameters:
Parameter | Type | Description |
---|---|---|
$value | mixed |
shift
Shift an element off of the front of the Map.
public shift(): mixed
Return Value:
The element in the first position of the Map
unshift
Push an element on to the front of the Map.
public unshift(mixed $value): int
Parameters:
Parameter | Type | Description |
---|---|---|
$value | mixed |
addOutputFilter
Set an output filter callback to modify objects as they are being returned.
public addOutputFilter(callable $callback, bool $filterRecurse = false, ?string $filterField = null, string[]|string $filterType = null): void
Parameters:
Parameter | Type | Description |
---|---|---|
$callback | callable | the function to execute on get |
$filterRecurse | bool | All children will have the same filter applied |
$filterField | ?string | |
$filterType | string[]|string | a class name or array of class names to run the callback on |
addInputFilter
Set an input filter callback to modify objects as they are being set.
public addInputFilter(callable $callback, bool $filterRecurse = false, ?string $filterField = null, string[]|string $filterType = null): void
Parameters:
Parameter | Type | Description |
---|---|---|
$callback | callable | the function to execute on set |
$filterRecurse | bool | All children will have the same filter applied |
$filterField | ?string | |
$filterType | string[]|string | a class name or array of class names to run the callback on |
applyFilters
Apply a filter array to be used for input/output filters.
public applyFilters(array<string,mixed> $filters_def, bool $recurse = true): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$filters_def | array<string,mixed> | the filter definition |
$recurse | bool |
Return Value:
true if the filter was valid, false otherwise
get
Get a reference to a Map value by key. If an output filters are set they will be executed before the element is returned here.
public get(?string $key, mixed $default = null, bool $create = false): mixed
Filters are applied/executed only for element types specified in the 'out' filter definition.
!!! warning Note that when using an output filter the value will NOT be returned by reference meaning in-place modifications will not work.
Parameters:
Parameter | Type | Description |
---|---|---|
$key | ?string | |
$default | mixed | |
$create | bool |
Return Value:
Value at key $key
__get
Magic method to allow -> access to key values. Calls Map::get().
public __get(string $key): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
Return Value:
Value at key $key
set
Set key value. Filters are applied/executed at this point for element types specified in the 'in' filter definition.
public set(?string $key, mixed $value, bool $merge_arrays = false): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | ?string | |
$value | mixed | |
$merge_arrays | bool |
del
Remove an element from the Map object.
public del(string $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
offsetExists
public offsetExists(mixed $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | mixed |
offsetGet
public offsetGet(mixed $key): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$key | mixed |
offsetSet
public offsetSet(mixed $key, mixed $value): void
Parameters:
Parameter | Type | Description |
---|---|---|
$key | mixed | |
$value | mixed |
offsetUnset
public offsetUnset(mixed $key): void
Parameters:
Parameter | Type | Description |
---|---|---|
$key | mixed |
each
Iterates over each element in the map and returns the current key-value pair.
public each(): mixed
Return Value:
returns an associative array with the current key and value, or false if there are no more elements
current
Return the current element in the Map.
public current(): mixed
key
Return the current key from the Map.
public key(): mixed
next
Move to the next element in the Map.
public next(): void
rewind
Set the internal pointer the first element.
public rewind(): void
valid
Test that an element exists at the current internal pointer position.
public valid(): bool
isNull
Test if a child value is true NULL. This is the correct way to test for null on a Map object as it will correctly return true for elements that don't exist.
public isNull(string $key): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string |
toString
Convert the map to a string. This is for compatibility with certain other functions that may attempt to use these objects as a string. If the map contains any elements it will return '%Map', otherwise it will return an empty string.
public toString(): string
toArray
Return the Map as a standard Array.
public toArray(bool $ignorenulls = false, bool $filter = true): array
Parameters:
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool | |
$filter | bool |
Return Value:
The Map object as an array
getArray
This is get() and toArray() all in one with the added benefit of checking if $key is a \Hazaar\Map and only calling toArray() if it is.
public getArray(string $key, bool $ignorenulls = false): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | |
$ignorenulls | bool |
toJSON
Return a valid JSON string representation of the Map.
public toJSON(bool $ignorenulls = false, int $flags, int $depth = 512): string
Parameters:
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool | |
$flags | int | |
$depth | int |
Return Value:
The Map as a JSON string
find
Find elements based on search criteria.
public find(array<string,mixed> $criteria): \Hazaar\Map
Parameters:
Parameter | Type | Description |
---|---|---|
$criteria | array<string,mixed> | search criteria in the format of key => value |
Return Value:
a Map of elements that satisfied the search criteria
findOne
Find a sub element based on search criteria.
public findOne(array<string,mixed> $criteria, string $field = null): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$criteria | array<string,mixed> | search criteria in the format of key => value |
$field | string | Return a single field. If the field does not exist returns null. This allows us to safely return a single field in a single line in cases where nothing is found. |
Return Value:
The first element that matches the criteria
contains
Searches a numeric keyed array for a value that is contained within it and returns true if it exists.
public contains(mixed $value): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$value | mixed | The value to search for |
search
public search(mixed $value): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$value | mixed |
modify
Modify multiple elements in one go. Unlike extends this will only modify a value that already exists in the Map.
public modify(array<string,mixed>|\Hazaar\Map $values): void
Parameters:
Parameter | Type | Description |
---|---|---|
$values | array<string,mixed>|\Hazaar\Map | map of values to update |
enhance
Enhance is the compliment of modify. It will only update values if they DON'T already exist.
public enhance(array|\Hazaar\Map $values): void
Parameters:
Parameter | Type | Description |
---|---|---|
$values | array|\Hazaar\Map | array or Map of values to add |
remove
Remove an element from the Map based on search criteria.
public remove(array<string,mixed> $criteria): bool
Parameters:
Parameter | Type | Description |
---|---|---|
$criteria | array<string,mixed> | an array of ssearch criteria that must be met for the element to be removed |
Return Value:
true if something is removed, false otherwise
sum
Return a total of all numeric values in the Map.
public sum(array<string,mixed> $criteria = null, string[] $fields = [], bool $recursive = false): float
Parameters:
Parameter | Type | Description |
---|---|---|
$criteria | array<string,mixed> | search criteria that must be met for the value to be included |
$fields | string[] | The fields to use for the sum. If omitted all numeric fields will be summed. If a string is specified then a single field will be used. Also, an Array can be used to allow multiple fields. |
$recursive | bool | set true if you need to recurse into child elements and add them to the sum |
Return Value:
Sum of all numeric values
filter
public filter(\Closure $func, int $mode): void
Parameters:
Parameter | Type | Description |
---|---|---|
$func | \Closure | |
$mode | int |
keys
Returns an array of key names currently in this Map object.
public keys(): string[]
Return Value:
An array of key names
values
Returns an array of values currently in this Map object.
public values(): array
Return Value:
An array of values
lock
Lock the map so that it's values can not be accidentally changed.
public lock(): void
unlock
Unlock the map so that it's values can be changed.
public unlock(): void
implode
public implode(string $glue = ''): string
Parameters:
Parameter | Type | Description |
---|---|---|
$glue | string |
flatten
Flatten the Map into a string.
public flatten(string $inner_glue = '=', string $outer_glue = ' ', string[] $ignore = []): string
This method will flatten the Map into a string. The inner glue is used to separate the key and value pairs and the outer glue is used to separate each pair.
Parameters:
Parameter | Type | Description |
---|---|---|
$inner_glue | string | the glue to use between the key and value |
$outer_glue | string | the glue to use between each key/value pair |
$ignore | string[] | an array of keys to ignore |
Return Value:
The flattened Map as a string
exportAll
Export all objects/arrays/Maps as an array.
public static exportAll(mixed $element, bool $export_as_json = false): mixed
If an element is an object it will be checked for an __export() method which if it exists the resulting array from that method will be used as the array representation of the element. If the method does not exist then the resulting array will be an array of the public object member variables only.
- This method is static.
Parameters:
Parameter | Type | Description |
---|---|---|
$element | mixed | The root element to convert into an array |
$export_as_json | bool | instead of returning an array, return a JSON string of the array |
toDotNotation
Convert to dot notation.
public toDotNotation(): \Hazaar\Map
Converts/reduces a multidimensional array into a single dimensional array with keys in dot-notation.
Return Value:
The Map object as a dot notation Map
fromJSON
Populate or extend the object values from a JSON string.
public fromJSON(string $json, bool $merge = false): \Hazaar\Map
Parameters:
Parameter | Type | Description |
---|---|---|
$json | string | |
$merge | bool |
fromDotNotation
Convert to Map from dot notation.
public fromDotNotation(array|\Hazaar\Map $array, bool $merge = false): \Hazaar\Map
Converts/reduces a single dimensional array with keys in dot-notation and expands it into a multi-dimensional array.
Parameters:
Parameter | Type | Description |
---|---|---|
$array | array|\Hazaar\Map | |
$merge | bool |
update
Updates the Map with values in the supplied array if they exist.
public update(array|\Hazaar\Map $values): \Hazaar\Map
This method will update existing values in the current Map object with the values in the supplied $value array or Map. If the values do not already exist in the current Map object, no new values will be created.
Parameters:
Parameter | Type | Description |
---|---|---|
$values | array|\Hazaar\Map | The values to update |
decode
Decodes the value associated with the given key.
public decode(string $key): mixed
Parameters:
Parameter | Type | Description |
---|---|---|
$key | string | the key to decode the value for |
Return Value:
the decoded value
Automatically generated on 2024-11-14