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.

Summary
MethodsPropertiesConstants
No constants
Properties
$current
$current
The current value for array access returned by Map::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)

<span style="color: #0000ff;">'enabled'</span> <span style="color: #339933;">=&gt;</span> boolean <span style="color: #009900; font-weight: bold;">true</span>
<span style="color: #0000ff;">'label'</span> <span style="color: #339933;">=&gt;</span> string <span style="color: #0000ff;">'Test Map'</span> <span style="color: #009900;">&#40;</span>length<span style="color: #339933;">=</span><span style="color: #cc66cc;">8</span><span style="color: #009900;">&#41;</span></pre>

p(notice notice-info). 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.

__get()
__get($key) : mixed

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

__isset()
__isset($key) : boolean

Magic method to test if an element exists

__set()
__set($key, $value)

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

__sleep()
__sleep()
__tostring()
__tostring()

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

__unset()
__unset($key)

Magic method to remove an element

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

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

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

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

cancel()
cancel($recursive = true)

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

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.

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

Commit any changes to be the new default values

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

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

current()
current()

Return the current element in the Map

del()
del($key)

Remove an element from the Map object

each()
each()
enhance()
enhance($values) : boolean

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

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

Execute a filter on the given element.

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.

extend()
extend()

Extend the Map using elements from another Map or Array.

fill()
fill($start_index, $num, $value)
find()
find($criteria) : Map

Find elements based on search criteria

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

Find a sub element based on search criteria

flatten()
flatten($inner_glue = '=', $outer_glue = ' ', $ignore = Array ( ) )
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.

fromJSON()
fromJSON($json, $merge = false)
Populate or extend the object values from a JSON string
get()
get($key, $create = false) : 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.

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

getArray()
getArray($key, $ignorenulls = false)
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.
getChanges()
getChanges() : Map

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

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.

getNew()
getNew() : Map

Return any new elements in the Map

getRemoves()
getRemoves() : Map

Return a list of keys that have been removed

has()
has($key) : boolean

Test if an element exists in the Map object.

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.

hasNew()
hasNew() : boolean

Test if there are any new elements in the Map

hasRemoves()
hasRemoves() : boolean

Test if any values have been removed

implode()
implode($glue = ' ')
in()
in($value) : boolean

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

isEmpty()
isEmpty() : boolean
Check whether the map object is empty or not.
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.

Static
is_array()
is_array($array) : boolean

Test if an object is a usable Array.

key()
key()

Return the current key from the Map

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.

next()
next()

Move to the next element in the Map

offsetExists()
offsetExists($key)
offsetGet()
offsetGet($key)
offsetSet()
offsetSet($key, $value)
offsetUnset()
offsetUnset($key)
pop()
pop($key = null) : mixed
Pop an element off of the Map

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.

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.
push()
push($value)

Push an element on to the end of the Map

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.

remove()
remove($criteria) : boolean

Remove an element from the Map based on search criteria

reset()
reset($recursive = false)

Reset the Map back to its default values

rewind()
rewind()

Set the internal pointer the first element

search()
search($value)
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.

shift()
shift() : mixed

Shift an element off of the front of the Map

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

Return a total of all numeric values in the Map.

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

Return the Map as a standard Array

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

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

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

Return a valid JSON string representation of the Map

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.

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

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.

valid()
valid()

Test that an element exists at the current internal pointer position