Standard Data Types

SPL data types wrappers and utilities to dealing with array, strings, traversable, ...

Introduction

Standard Data Types Libraries is wrapper around existence PHP data types which adding more convenient methods and useful helpers to them. these libraries are used as part of core functionalities of Poirot Framework. The component are distributed under the "Poirot/Std" namespace and has a git repository, and, for the php components, a light autoloader and composer support. All Poirot components following the PSR-4 convention for namespace related to directory structure and so, can be loaded using any modern framework autoloader. 100% Test Coverage and fully testable by PHPUnit Test.

In Case You need any support or question use the links below:

Slack: getpoirot.slack.com https://join.slack.com/t/getpoirot/shared_invite/zt-dvfhkoes-h45XoKlyxamfhaHm6G4uSA

Arrays

Additionally to the rich set of PHP array functions, there is a collection of convenience helper methods array helper provides extra methods allowing you to deal with arrays more efficiently.

Method name convention: Any method from StdArray which prefixed with get like getKeys, getLast, ... has no effect on the current object and will return new instance of object include the expected result.

Instantiate and Construct

StdArray can be instantiated around existing array or from an initial empty array:

$arrOne   = new StdArray();
$arrTwo   = new StdArray([1, 2, 3, 4]);
$arrThree = new StdArray(new \ArrayIterator([1, 2, 3, 4]));

// Through factory static method:
$arr = StdArray::of([1, 2, 3, 4]);

StdArray can built around different data sources such as Traversable, Object, json string, reference memory address to array variable.

All accepted different data types can be constructed through construct method and none-strict mode by passing second argument to constructor.

Converting To Array

Traversable:

stdClass object:

class object:

json string:

memory address reference:

It's Iterable

StdArray is iterable object and items are accessible through \Iteratorinterface.

It's Array Accessible

The object items are accessible just like a regular array, the only difference is when key is undefined instead of trigger E_NOTICE error of Array key does not exist, it will just return null as a value.

It's Countable

Array keys accessible by reference

lookup - Search array elements by query path

The lookup method search array to matching against given query path expression and will return \Generator traversable of matching elements or exact value of an element based on the given query path expressiontype. Any expression which does not return nodes will return null. These path expressions look very much like the path expressions you use with traditional computer file systems:

Fetch one by nested hierarchy lookup:

Selects from the root by hierarchy descendant.

First slash given to expression can be removed, so this query will do the same:

Fetch all by nested hierarchy lookup:

By adding * beside the element in query, simply expected path to match with more than one element or make the result to \Generator iterable object.

Regex lookup:

Regex matching expression can be defined between ~ characters:

Match lookup in specified depth only:

The depth are counting from 1 for the next level of hierarchy elements inside root. check this out:

Recursive lookup - Match lookup expression within any depth:

The result of // expression is always an \Generator traversable.

Considerations about lookup resulting in same keys:

As the result of query lookup is a Generator some times we have duplicated key in the result so using some functions like iterator_to_array will not give us the expected result. check this sample: as you see here we have two similar key in the iterator each came from the nested element on main array. when use query take this into consideration.

Reindex lookup result:

By re-index expression token the result will get re-indexed on numeric values started from zero, it could be a solution the the same key on the traversable result which also mentioned. here are the examples: to re-index : should be comes after /

Samples on Combination of variant query expressions:

lookup - Access by reference

The lookup method can access elements by their memory reference address.

filter - Filter Array Items

This method will affect current elements inside array object, check out the following code. We'll use the filter helper to capitalise each string element with strtoupper and remove all none string and empty elements.

Array keys can change as well with filter method:

Further reading

As filter method use IteratorWrapper internally to provide the functionalities for filter elements to know better about all available features see IteratorWrapper documentation for more.

append - Append to end of array

The append method add a given value to the end of array, if given array key as a second argument exists will replaced by new value and will moved to the end of array elements.

prepend - Prepend to beginning of array

The prepend method add and element to the beginning of array and re-index array keys. if given array key as a second argument exists will replaced by new value and will moved to the beginning of array elements.

insert - Insert an element to array

The insert method will append an element to the array if not any specific key given as second argument or set value of the element if key exists. When key is not given the value will appended to array:

When we specify key the default behaviour is to replace value with new one:

By comparison callable as third arguments it's possible to define the insert behaviour when given key is exists in array:

merge - merges the given array recursively

The merge method gives flexibility on how to merges the given array into the current array by introducing merge strategies. By default when element has an integer key it will be appended to array.

The way that merge behaves can be changed with providing merge strategy as a second argument: Merge Strategy is a callable or integer value of compare result which instruct the merge how to behave when same element with key exists, the returned number is -1, 0, 1 which actually has equality constant defined in the class in order as MergeDoReplace, MergeDoMerging, MergeDoPush. The code below changes the merge behaviour in this way when there is an existing integer key try to merge their value together and for the rest default strategy is called.

If the array not consist of other different mix of structures which is not important how it's gonna merge, the codes above can be simplified to this:

Other examples to see how merge works in default:

Another merge strategy example:

If any field has a same value it's not gonna merge otherwise the values getting merged for the rest. In this sample 'value' field has same value in both array and will not get merged.

except - Remove array element(s) by key(s)

The except method will remove all given key(s) element from array if key exists.

keep - Keep only given key(s) in array

The keep method only keeps the given keys in array if they exists and rest of array will be cleared from unwanted keys.

keepIntersection - Keep values that are present in all the arguments.

Computes the intersection of arrays, compares data by a callback function.

getFirst - Get first array element

The getFirst method return first array element of array which the result is another StdArray object with the single element from beginning of current array. if current array is empty the result will be an empty array.

getFirstAndRemove - Pop an element off the beginning of array

The getFirstAndRemove shift element off from beginning of array by removing the element from array and return new StdArray object containing the element.

This method will reset the array pointer of the input array to the beginning.

getLast - Get last array element

The getLast method return last array element of array which the result is another StdArray object with the single element from end of current array. if current array is empty the result will be an empty array.

getLastAndRemove - Pop an element off the end of array

The getLastAndRemove pop element off from end of array by removing the element from array and return new StdArray object containing the element.

This method will reset the array pointer of the input array to the beginning.

getKeys - List Array keys

The getKeys method returns an instance of StdArray with values contains all the keys from current array.

getValues - List Array values

The getValues method returns an instance of StdArray contains all the values from current array indexed from zero.

getColumn - representing a single column from array

The getColumn method retrieves all of the values for a given key(column), it possible to specify how the resulting values from column to be keyed by defining another key as second argument.

getFlatten - Get flatten face of multi-dimensional array

The getFlatten method flattens a multi-dimensional array into a single level array that uses given notation to indicate depth and return new StdArray object containing the element.

reindex - ReIndex array keys

The reindex method will index array values from zero based on the current position of the item, if the key is an integer then take none-integer keys sort keys and concat them to the end of array as final result.

clean - Clean elements with empty values

The clean method Clean all elements with falsy values from the current array.

isEqual - Check whether origin array is equal to given value

The isEqual method check equality of current array with the given value can be any type which can constructed by StdArray

isEmpty - Check if array is empty

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

isAssoc - Check if array is Associative array

Enums

An enumeration type, "enum" for short, is a data type to categorise named values. Enums can be used instead of hard coded strings to represent, for example, the status of a blog post in a structured and typed way. For example, a Post object supposed to have three different values for status of the post, it could be one of three strings: draft, published or archived.

With StdEnum the enumeration type can be defined as follow:

And Named values can be accessed by calling as static methods:

Declaration

To define new enumeration type it's needed to just extend the StdEnum and define needed named values as public constant inside the class.

The StdEnum will automatically recognize the possible values from defined constants and will proxy all static method calls to related constant name to build new instance with value equal to const.

To get IDE support on autocompletion on the class the Docblock notation can be defined but it's not necessary but highly recommended.

Constructing object

Instantiating object is possible by new syntax and by calling statically the value name like ::NamedConst.

When the named value is not valid to class the \UnexpectedValueException will thrown.

Get Value of enum object

The StdEnum is invokable and by calling the object like functions will return the value which is holding.

An example on How it's used in classes which are needed these values can be found here.

Equality check

The isEqualTo method will tests whether enum instances are equal (returns true if enum values are equal, false otherwise).

Check on classes which extends from base enum class

The equality check on different object can be true only for the classes which extended from base enum class with same value. otherwise result check for different objects with the same value is always false.

List all possible enums

Return an array of enum name to the Enum object initialized with the internal value of related constant.

Strings

The StdString is easy to use and easy to bundle library include convenience methods to handle strings with different character set encoding support. This library will also auto-detect server environment and will use the available installed php-extensions and pick them as a fallback to do the task.

The StdString is immutable object which means any modification method to the current object will apply changes on the new instance of the object and the current one will stay same without any changes.

It's a wrapper around existence several extensions or libraries like mbstring, iconv, intl, ... in addition any custom user implementation can be registered as a fallback to the library through the available interfaces.

If Symfony Polyfills for mbstring is available (required in composer) or classes are loaded or autoloadable by PHP it might be selected as a fallback by StdString if needed.(https://github.com/symfony/polyfill)

Register custom wrapper

Any custom implementation string wrapper can be registered to StdString by implementing iStringWrapper interface and then simply can be registered.

Registered wrapper will take the higher priority when StdString taking a wrapper from registry basically depends on the implemented methods it would take the job.

Usage sample

Instantiate and Construct

When string object constructed the object should know about the encoding charset of string, the default charset is UTF-8, depend on the string representing content any other encoding can be chosen.

The Encodings class contains all available charsets which can be used to get more consistency when using different charset on code base.

Values given as initial value to the class will casting to string type if it's not string. On Any object which can't cast to string \UnexpectedValueException will thrown.

It's serializable

The serialized string is a 3 byte sequence in the beginning of the string which indicate the encoding charset of the string and the rest is the origin string byte sequences means the whole original string. For instance the serialized string 中文空白 with encoding UTF-16 represented like this: \x00\x25 中文空白 the string part is also should be considered as byte sequences but here just to make it more understandable the string is used.

Serialized string is safe to store in DB and other storages and can be searchable and can be converted and used byStdString object with same encoding again.

It's array like accessible

Characters within strings may be only accessed by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[0].

Instead of default PHP behaviour of accessing elements which is consider the string as series of 8bit data for each element, here each element represent a character in string. in multibyte encodings one character may consist more than 8bit.

It's countable

Get string encoding

To know which charset encoding object is instantiated with there are two readonly property which hold the same value.

lower

Convert all alphabetic characters within string to lowercase.

lowerFirstChar

Makes string's first char lowercase, if that character is alphabetic.

upper

Convert all alphabetic characters within string to uppercase.

upperFirstChar

Makes string's first char uppercase, if that character is alphabetic.

camelCase

Note that whitespaces will be removed from the string. only _ character will be considered as a separator char and will be used in creating camelCase result of string other like numbers will be considered as part of words.

The delimiter can given to the method and that will be remain if string at the beginning or end has it.

pascalCase

The delimiter can given to the method and that will be remain if string at the beginning or end has it.

snakeCase

The delimiter can given to the method and that will be remain if string at the beginning or end has it.

subString - Return part of a string

Returns the portion of string specified by the start and length parameters. to see about all possible values to the parameters check here.

stripPrefix - remove string from beginning

Remove given string if only it's found at the beginning of the original string.

Second argument to the method will strip any whitespace from beginning of array before strip given string when it has true value. which is default value.

stripPostfix - remove string from end

Remove given string if only it's found at the end of the original string.

Second argument to the method will strip any whitespace from end of array before strip given string when it has true value. which is default value.

hasStartedWith - Get prefixed string

Get the given string as a result if the origin string is started with that otherwise return empty string. Method will accept variadic argument of string values and will return the one which match first with the origin string prefix.

isStartedWith - Check prefix of string

Method will accept variadic argument of string values and will check if the string has one of the given values in the beginning.

hasContains - Has string contains a substring

Determine existence of a substring in origin string, if it has the substring will be returned as the result otherwise empty string will be returned.

isContains - Check string contains a substring

Check if string contains given substring and return boolean value true if has substring otherwise return false.

concatSafeImplode - Safe join strings

Join string elements from array with a delimiter glue, joining will be safe to not include extra glue character if concat string has already contain the delimiter glue.

normalizeExtraNewLines - Remove extra line breaks

Remove extra new lines and line breaks from string.

normalizeWhitespaces - Strip and remove whitespaces

Last updated

Was this helpful?