\Hazaar
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 = array(‘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(array( ‘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.

Tags

Since

1.0.0

Summary
Methods Properties Constants
del
get
has
in
key
pop
set
sum
No constants
Properties
$current
$current
The current value for array access returned by each()
$defaults
$defaults
Holds the original child objects and values
$elements
$elements
Holds the active elements
$filter
$filter
Optional filter definition to modify objects as they are set or get.

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
$locked
$locked
Allows the map to be locked so that it's values are not accidentally changed.
Methods
__construct()
__construct($defaults = Array ( ) , $extend = Array ( ) , $filter_def = Array ( ) )

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.

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 = array(‘enabled’ => true); $map = new Hazaar\Map(array( ‘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)

If the input arguments are strings then the Map class will try and figure out what kind of string is is and either convert from JSON or unserialize the string.

Tags

Since

1.0.0

Parameters

$defaultsmixed

Default values will set the default state of the Map

$extendmixed

Extend the default values overwriting existing key values and creating new ones

$filter_defArray

Optional filter definition

__get()
__get($key) : mixed

Magic method to allow -> access to key values. Calls Map::get().

Tags

Since

1.0.0

Parameters

$key

No description

Returns

mixed

Value at key $key

__isset()
__isset($key) : boolean

Magic method to test if an element exists

Tags

Since

1.0.0

Parameters

$key

No description

Returns

boolean

True if the element exists, false otherwise.

__set()
__set($key, $value)

Magic method to allow -> access to when setting a new kay value

Tags

Since

1.0.0

Parameters

$key

No description

$value

No description

__tostring()
__tostring()

Magic method to convert the map to a string. See Map::toString();

__unset()
__unset($key)

Magic method to remove an element

Tags

Since

1.0.0

Parameters

$key

No description

addInputFilter()
addInputFilter($callback, $filter_field = null, $filter_type = null, $filter_recurse = false)

Set an input filter callback to modify objects as they are being set

Tags

Since

1.0.0

Parameters

$callbackmixed

The function to execute on set.

$filter_field

No description

$filter_typemixed

A class name or array of class names to run the callback on.

$filter_recurseboolean

All children will have the same filter applied

addOutputFilter()
addOutputFilter($callback, $filter_field = null, $filter_type = null, $filter_recurse = false)

Set an output filter callback to modify objects as they are being returned

Tags

Since

1.0.0

Parameters

$callbackmixed

The function to execute on get.

$filter_field

No description

$filter_typemixed

A class name or array of class names to run the callback on.

$filter_recurseboolean

All children will have the same filter applied

applyFilters()
applyFilters($filters_def, $recurse = true) : boolean

Apply a filter array to be used for input/output filters

Tags

Since

1.0.0

Parameters

$filters_def

No description

$recurse

No description

Returns

boolean

True if the filter was valid, false otherwise.

cancel()
cancel($recursive = true)

The cancel method will flush the default elements so that all elements are considered new or changed.

Tags

Since

1.0.0

Parameters

$recursive

No description

clear()
clear()

Clear all values from the array.

It is still possible to reset the array back to it’s default state after doing this.

Tags

Since

2.0.0

commit()
commit($recursive = true) : boolean

Commit any changes to be the new default values

Tags

Since

1.0.0

Parameters

$recursiveboolean

Recurse through any child Map objects and also commit them.

Returns

boolean

True on success. False otherwise.

count()
count($ignorenulls = false) : int

Countable interface method. This method is called when a call to count() is made on this object.

Tags

Since

1.0.0

Parameters

$ignorenulls

No description

Returns

int

The number of elements in this Map.

current()
current()

Return the current element in the Map

Tags

Since

1.0.0

del()
del($key)

Remove an element from the Map object

Tags

Since

1.0.0

Parameters

$key

No description

enhance()
enhance($values) : boolean

Enhance is the compliment of modify. It will only update values if they DON’T already exist.

Tags

Since

1.2

Parameters

$valuesmixed

Array or Map of values to add.

Returns

boolean
execFilter()
execFilter($key, $elem, $direction) : mixed

Execute a filter on the given element.

Tags

Since

1.0.0

Internal

Parameters

$keystring

The name of the key to pass to the callback

$elemmixed

The element that we are executing the callback on

$directionstring

The filter direction identified (‘in’ or ‘out’)

Returns

mixed

Returns the element once it has been passed through the callback

Static
exportAll()
exportAll($element, $export_as_json = false)

Export all objects/arrays/Maps as an array

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.

Tags

Since

2.0.0

Parameters

$element

No description

$export_as_jsonboolean

Instead of returning an array, return a JSON string of the array.

extend()
extend()

Extend the Map using elements from another Map or Array.

Tags

Since

1.0.0

fill()
fill($start_index, $num, $value)

Parameters

$start_index

No description

$num

No description

$value

No description

find()
find($criteria) : Map

Find elements based on search criteria

Tags

Since

1.0.0

Parameters

$criteria

No description

Returns

\Hazaar\Map

A Map of elements that satisfied the search criteria.

findOne()
findOne($criteria, $field = null) : mixed

Find a sub element based on search criteria

Tags

Since

1.0.0

Parameters

$criteria\Hazaar\Map

Search criteria in the format of key => value.

$field

No description

Returns

mixed

The first element that matches the criteria

flatten()
flatten($inner_glue = '=', $outer_glue = ' ', $ignore = Array ( ) )

Parameters

$inner_glue

No description

$outer_glue

No description

$ignore

No description

fromDotNotation()
fromDotNotation($array, $merge = false) : array
Convert to Map from dot notation

Converts/reduces a single dimensional array with keys in dot-notation and expands it into a multi-dimensional array.

Tags

Since

2.0.0

Parameters

$array

No description

$merge

No description

Returns

array
fromJSON()
fromJSON($json, $merge = false)
Populate or extend the object values from a JSON string

Parameters

$jsonmixed

No description

$mergemixed

No description

get()
get($key) : mixed

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. Filters are applied/executed only for element types specified in the ‘out’ filter definition.

Note that when using an output filter the value will NOT be returned by reference meaning in-place modifications will not work.

Tags

Since

1.0.0

Parameters

$key

No description

Returns

mixed

Value at key $key

getChanges()
getChanges() : Map

Return an array of element value changes that have been made to this Map

Tags

Since

1.0.0

Returns

\Hazaar\Map

An Map of changed elements

getDefault()
getDefault($key) : bool
Get the default value for a value stored in the Map object.

This is useful for getting the original value of a value that has changed. Such as an original index number or other identifier.

Parameters

$key

No description

Returns

\Hazaar\bool
getNew()
getNew() : Map

Return any new elements in the Map

Tags

Since

1.0.0

Returns

\Hazaar\Map

An map of only new elements in the Map

getRemoves()
getRemoves() : Map

Return a list of keys that have been removed

Tags

Since

1.0.0

Returns

\Hazaar\Map

A Map of key names that have been removed from this Map.

has()
has($key) : boolean

Test if an element exists in the Map object.

Tags

Since

1.0.0

Parameters

$key

No description

Returns

boolean

True if the element exists, false otherwise.

hasChanges()
hasChanges() : boolean

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.

Tags

Since

1.0.0

Returns

boolean

True if there are any changes/additions/removal of elements, false otherwise.

hasNew()
hasNew() : boolean

Test if there are any new elements in the Map

Tags

Since

1.0.0

Returns

boolean

True if there are new elements, false otherwise.

hasRemoves()
hasRemoves() : boolean

Test if any values have been removed

Tags

Since

1.0.0

Returns

boolean

True if one or more values have been removed. False otherwise.

implode()
implode($glue = ' ')

Parameters

$glue

No description

in()
in($value) : boolean

Searches a numeric keyed array for a value that is contained within it and returns true if it exists.

Tags

Since

2.0.0

Parameters

$valuemixed

The value to search for

Returns

boolean
isEmpty()
isEmpty() : boolean
Check whether the map object is empty or not.

Returns

boolean
isNull()
isNull($key)

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.

Tags

Since

1.0.0

Parameters

$key

No description

Static
is_array()
is_array($array) : boolean

Test if an object is a usable Array.

Tags

Since

1.0.0

Parameters

$array

No description

Returns

boolean

True if the value is an array or extends ArrayAccess

key()
key()

Return the current key from the Map

Tags

Since

1.0.0

keys()
keys()

Returns an array of key names currently in this Map object

lock()
lock()

Lock the map so that it’s values can not be accidentally changed.

modify()
modify($values)

Modify multiple elements in one go. Unlike extends this will only modify a value that already exists in the Map.

Tags

Since

1.0.0

Parameters

$values\Hazaar\Map

Map of values to update.

next()
next()

Move to the next element in the Map

Tags

Since

1.0.0

offsetExists()
offsetExists($key)

Tags

Internal

Parameters

$key

No description

offsetGet()
offsetGet($key)

Tags

Private

Parameters

$key

No description

offsetSet()
offsetSet($key, $value)

Tags

Private

Parameters

$key

No description

$value

No description

offsetUnset()
offsetUnset($key)

Tags

Private

Parameters

$key

No description

pop()
pop() : mixed

Pop an element off of the end of the Map

Tags

Since

1.0.0

Returns

mixed

The element in the last position of the Map

populate()
populate($defaults, $erase = true)

Populate sets up the array with initial values.

  • 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.

This method will overwrite ALL values currently in the Map.

Tags

Since

1.0.0

Parameters

$defaultsmixed

Map or Array of values to initialise the Map with.

$eraseboolean

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.

push()
push($value)

Push an element on to the end of the Map

Tags

Since

1.0.0

Parameters

$value

No description

read()
read($key, $default, $insert = false)

Read will return either the value stored with the specified key, or the default value. This is 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

$key

No description

$default

No description

$insert

No description

remove()
remove($criteria) : boolean

Remove an element from the Map based on search criteria

Tags

Since

1.0.0

Parameters

$criteriaArray

An array of ssearch criteria that must be met for the element to be removed.

Returns

boolean

True if something is removed, false otherwise.

reset()
reset($recursive = false)

Reset the Map back to its default values

Tags

Since

1.0.0

Parameters

$recursive

No description

rewind()
rewind()

Set the internal pointer the first element

Tags

Since

1.0.0

search()
search($value)

Parameters

$value

No description

set()
set($key, $value, $merge_arrays = false)

Set key value. Filters are applied/executed at this point for element types specified in the ‘in’ filter definition.

Tags

Since

1.0.0

Parameters

$key

No description

$value

No description

$merge_arrays

No description

shift()
shift() : mixed

Shift an element off of the front of the Map

Tags

Since

1.0.0

Returns

mixed

The element in the first position of the Map

sum()
sum($criteria = null, $fields = Array ( ) , $recursive = false) : float

Return a total of all numeric values in the Map.

Tags

Since

1.0.0

Parameters

$criteriaArray

Search criteria that must be met for the value to be included.

$fieldsMixed

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.

$recursiveboolean

Set true if you need to recurse into child elements and add them to the sum.

Returns

\Hazaar\float

Sum of all numeric values

toArray()
toArray($ignorenulls = false) : Array

Return the Map as a standard Array

Tags

Since

1.0.0

Parameters

$ignorenulls

No description

Returns

Array

The Map object as an array

toDotNotation()
toDotNotation() : array
Convert to dot notation

Converts/reduces a multidimensional array into a single dimensional array with keys in dot-notation.

Tags

Since

2.0.0

Returns

array
toJSON()
toJSON($ignorenulls = false, $args = null) : string

Return a valid JSON string representation of the Map

Tags

Since

1.0.0

Parameters

$ignorenulls

No description

$args

No description

Returns

string

The Map as a JSON string

toString()
toString() : string

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.

Tags

Since

1.0.0

Returns

string

A string

unlock()
unlock()

Unlock the map so that it’s values can be changed.

unshift()
unshift($value)

Push an element on to the front of the Map

Tags

Since

1.0.0

Parameters

$value

No description

update()
update($values) : boolean
Updates the Map with values in the supplied array if they exist

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

$values

No description

Returns

boolean

WIll return False if the supplied parameter is not an array.

valid()
valid()

Test that an element exists at the current internal pointer position

Tags

Since

1.0.0