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 epoch and a timezone field.
$callback = function($value, $key){
if(is_a('\Hazaar\Date', $value)){
$value = new Map([
'datetime' => $value->timestamp(),
'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.
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 $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
public __construct({Array})
object to use as default values.
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 |
__isset
Magic method to test if an element exists.
public __isset({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
__set
Magic method to allow -> access to when setting a new kay value.
public __set({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | |
$value | mixed |
__unset
Magic method to remove an element.
public __unset({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
__toString
Magic method to convert the map to a string. See Map::toString();.
public __toString({Array})
__sleep
public __sleep({Array})
_
public _({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$array | mixed | |
$args | Map |
populate
Populate sets up the array with initial values.
public populate({Array})
- 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 | 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})
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 | Map | the array being merged in |
commit
Commit any changes to be the new default values.
public commit({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$recursive | boolean | recurse through any child Map objects and also commit them |
clear
Clear all values from the array.
public clear({Array})
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({Array})
reset
Reset the Map back to its default values.
public reset({Array})
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({Array})
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({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool |
has
Test if an element exists in the Map object.
public has({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
read
Read will return either the value stored with the specified key, or the default value. This is
public read({Array})
essentially same as doing:
$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({Array})
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
public hasChanges({Array})
values but any new elements added or any elements being removed.
getChanges
Return an array of element value changes that have been made to this Map.
public getChanges({Array})
hasRemoves
Test if any values have been removed.
public hasRemoves({Array})
getRemoves
Return a list of keys that have been removed.
public getRemoves({Array})
hasNew
Test if there are any new elements in the Map.
public hasNew({Array})
getNew
Return any new elements in the Map.
public getNew({Array})
extend
Extend the Map using elements from another Map or Array.
public extend({Array})
pop
Pop an element off of the Map.
public pop({Array})
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 |
push
Push an element on to the end of the Map.
public push({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$value | mixed |
shift
Shift an element off of the front of the Map.
public shift({Array})
unshift
Push an element on to the front of the Map.
public unshift({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$value | mixed |
addOutputFilter
Set an output filter callback to modify objects as they are being returned.
public addOutputFilter({Array})
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 | 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({Array})
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 | 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})
Parameters
Parameter | Type | Description |
---|---|---|
$filters_def | array | |
$recurse | bool |
get
Get a reference to a Map value by key. If an output filters are set they will be executed
public get({Array})
before the element is returned here. 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 |
__get
Magic method to allow -> access to key values. Calls Map::get().
public __get({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
set
Set key value. Filters are applied/executed at this point for element types specified in the 'in'
public set({Array})
filter definition.
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | |
$value | mixed | |
$merge_arrays | bool |
del
Remove an element from the Map object.
public del({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
offsetExists
public offsetExists({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | mixed |
offsetGet
public offsetGet({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | mixed |
offsetSet
public offsetSet({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | mixed | |
$value | mixed |
offsetUnset
public offsetUnset({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | mixed |
each
Iterates over each element in the map and returns the current key-value pair.
public each({Array})
current
Return the current element in the Map.
public current({Array})
key
Return the current key from the Map.
public key({Array})
next
Move to the next element in the Map.
public next({Array})
rewind
Set the internal pointer the first element.
public rewind({Array})
valid
Test that an element exists at the current internal pointer position.
public valid({Array})
isNull
Test if a child value is true NULL. This is the correct way to test for null on a Map object as
public isNull({Array})
it will correctly return true for elements that don't exist.
Parameters
Parameter | Type | Description |
---|---|---|
$key | string |
toString
Convert the map to a string. This is for compatibility with certain other functions that
public toString({Array})
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.
toArray
Return the Map as a standard Array.
public toArray({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool | |
$filter | bool |
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({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | |
$ignorenulls | bool |
toJSON
Return a valid JSON string representation of the Map.
public toJSON({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$ignorenulls | bool | |
$flags | int | |
$depth | int |
find
Find elements based on search criteria.
public find({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$criteria | array |
findOne
Find a sub element based on search criteria.
public findOne({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$criteria | array | |
$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. |
contains
Searches a numeric keyed array for a value that is contained within it and returns true if it
public contains({Array})
exists.
Parameters
Parameter | Type | Description |
---|---|---|
$value | mixed | The value to search for |
search
public search({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$value | mixed |
modify
Modify multiple elements in one go. Unlike extends this will only modify a value that already
public modify({Array})
exists in the Map.
Parameters
Parameter | Type | Description |
---|---|---|
$values | Map |
enhance
Enhance is the compliment of modify. It will only update values if they DON'T already exist.
public enhance({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$values | Map | array or Map of values to add |
remove
Remove an element from the Map based on search criteria.
public remove({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$criteria | array |
sum
Return a total of all numeric values in the Map.
public sum({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$criteria | Map | |
$fields | array | 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 |
filter
public filter({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$func | \Closure | |
$mode | int |
keys
Returns an array of key names currently in this Map object.
public keys({Array})
values
Returns an array of values currently in this Map object.
public values({Array})
lock
Lock the map so that it's values can not be accidentally changed.
public lock({Array})
unlock
Unlock the map so that it's values can be changed.
public unlock({Array})
implode
public implode({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$glue | string |
flatten
Flatten the Map into a string.
public flatten({Array})
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 | array | an array of keys to ignore |
exportAll
public exportAll({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$element | mixed | |
$export_as_json | bool |
toDotNotation
Convert to dot notation.
public toDotNotation({Array})
Converts/reduces a multidimensional array into a single dimensional array with keys in dot-notation.
fromJSON
Populate or extend the object values from a JSON string.
public fromJSON({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$json | string | |
$merge | bool |
fromDotNotation
Convert to Map from dot notation.
public fromDotNotation({Array})
Converts/reduces a single dimensional array with keys in dot-notation and expands it into a multi-dimensional array.
Parameters
Parameter | Type | Description |
---|---|---|
$array | Map | |
$merge | bool |
update
Updates the Map with values in the supplied array if they exist.
public update({Array})
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 | Map | The values to update |
decode
Decodes the value associated with the given key.
public decode({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | the key to decode the value for |
execFilter
Execute a filter on the given element.
private execFilter({Array})
Parameters
Parameter | Type | Description |
---|---|---|
$key | string | The name of the key to pass to the callback |
$elem | mixed | The element that we are executing the callback on |
$direction | string | The filter direction identified ('in' or 'out') |
Generated by Hazaar API Doc Generator