Download the PHP package dazet/data-map without Composer
On this page you can find all versions of the php package dazet/data-map. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package data-map
Data Mapper
Library for mapping and transforming data structures.
Defining mapper
Mapper
configuration is a description of output structure defined as association:
Key
defines property name in output structure and Getter
is a function that extracts value from input.
Examples
Getter function
Getter
generally can be described as interface:
There are 2 forms of defining map:
Getter
can be string which is shorthand fornew GetRaw('key')
.Getter
can also be a closure or any other callable. It will receiveDataMap\Input\Input
as first argument and original input as second argument.Getter
interface is not required, it's just a hint.
Predefined Getters
new GetRaw($key, $default)
Get value by property path without additional transformation.
new GetString($key, $default)
Gets value and casts to string (if possible) or returns $default
.
new GetInteger($key, $default)
Gets value and casts to integer (if possible) or $default
.
new GetFloat($key, $default)
Gets value and casts to float (if possible) or $default
.
new GetBoolean($key, $default)
Gets value and casts to boolean (true
, false
, 0
, 1
, '0'
, '1'
) or $default
.
new GetDate($key, $default)
Gets value and transform to \DateTimeImmutable
(if possible) or $default
.
new GetJoinedStrings($glue, $key1, $key2, ...)
Gets string value for given keys an join it using $glue
.
new GetMappedCollection($key, $callback)
Gets collection under given $key
and maps it with $callback
or return []
if entry cannot be mapped.
new GetMappedFlatCollection($key, $callback)
Similar to GetMappedCollection
but result is flattened.
new GetTranslated($key, $map, $default)
Gets value and translates it using provided associative array ($map
) or $default
when translation for value is not available.
GetFiltered::from('key')->...
Gets value and transforms it through filters pipeline.
Using function as filter:
Regular filters will not be called when value becomes null
, with exceptions of ifNull
, ifEmpty
and withNullable
.
Custom null
handling filter:
GetFiltered
has set of built-in filters similar to FilteredInput
.
with(callable $filter)
: add to pipeline custom filter functionswithNullable(callable $filter)
: add to pipeline custom filter functions that will be called even when value has become nullstring()
: try cast to stringint()
: try cast to intfloat()
: try cast to floatbool()
: try cast to boolarray()
: try cast to arrayexplode(string $delimiter)
implode(string $glue)
upper()
lower()
trim()
format(string $template)
: format value withsprintf
templatereplace(string $search, string $replace)
stripTags()
numberFormat(int $decimals = 0, string $decimalPoint = '.', string $thousandsSeparator = ',')
round(int $precision = 0)
floor()
ceil()
date()
: try cast toDateTimeImmutable
dateFormat(string $format)
count()
ifNull($default)
ifEmpty($default)
Input abstraction
Input
interface defines common abstraction for accessing data from different data structures,
so mapping and getters must not depend of underlying data type.
It also allows to create input decorators for additional input processing, like data filtering, transformation, traversing etc.
ArrayInput
Wraps associative arrays and ArrayAccess objects.
ObjectInput
Wraps generic object and fetches data using object public interface: public properties or getters (a public method without parameters that returns some value).
Access method for key example name
is resolved in the following order:
- check for public property
name
- check for getter
name()
- check for getter
getName()
- check for getter
isName()
RecursiveInput
RecursiveInput
allows to traverse trees od data using dot notation ($input->get('root.branch.leaf')
).
It decorates Input
(current leaf) and requires Wrapper
to wrap with proper Input
next visited leafs (which can be arrays or objects).
FilteredInput
FilteredInput
is another Input
decorator that allows to transform data after it is extracted from inner structure.
Default input parser supports given filters:
string
: cast value to string if possible or return null |int
,integer
: cast to integer or return nullfloat
: cast to float or return nullbool
,boolean
: resolve value as boolean or return nullarray
: cast value to array if possible (from array or iterable) or return nullexplode [delimiter=","]
: explode string using delimiter (,
by default)implode [delimiter=","]
: implode array of strings using delimiter (,
by default)upper
: upper case stringlower
: lower case stringtrim
,ltrim
,rtrim
: trim stringformat
: format value as string usingsprintf
replace [search] [replace=""]
: replace substring in string likestr_replace
functionstrip_tags
: same asstrip_tags
functionnumber_format [decimals=2] [decimal_point="."] [thousands_separator=","]
: same asnumber_format
functionround [precision=0]
: same asround
functionfloor
: floor value, returnsfloat|null
ceil
: floor value, returnsfloat|null
datetime
: try to transform value toDateTimeImmutable
or return nulldate_format [format="Y-m-d H:i:s"]
: try to transform value to datetime and format as string or return null when value cannot be transformeddate_modify [modifier]
: try to transform value toDateTimeImmutable
and then transform it using modifier$datetime->modify($modifier)
timestamp
: try to transform value to datetime and then to timestamp or return nulljson_encode
: encode value to json or return nulljson_decode
: decode array from json string or return null when failedcount
: return count for array orCountable
or null when not countableif_null [then]
: return default value when mapped value is nullif_empty [then]
: return default value when mapped value is empty
Examples
- default explode by comma:
string | explode
- explode by custom string:
string | explode "-"
- default implode by comma:
array | implode
- implode by custom string:
array | implode "-"
- format string like
sprintf
:string | format "string: %s"
- format money from float:
float | format "price: $%01.2f"
- transforms12.3499
to'price: $12.35'
- cast to string with default value:
maybe_string | string | if_null "default"
- cast to date and modify:
date_string | date_modify "+1 day"
- calculate md5 of mapped value:
key | string | md5
- wrap string after 20 characters:
key | string | wordwrap 20
- using native function with custom argument position of mapped value
key | string | preg_replace "/\s+/" " " $$
Function as transformation
Default configuration of InputFilterParser
allows use any PHP function as transformation.
By default mapped value is passed as first argument to that function optionally followed by other arguments defined in filter config.
It is also possible to define different argument position of mapped value using $$
as a placeholder.
Output formatting
Mapping output type depends on Formatter
used by Mapper
.
Built-in formatters:
ArrayFormatter
Returns associative array which is raw result of Mapper transformation.
ObjectConstructor
Tries to create new instance of object using regular constructor. Keys are matched with constructor parameters by variable name.
There is no value type and correctness checking, so you will get TypeError when mapped types does not match.
It also fallback to null
value when object constructor has parameter that is not in the mapping.
ObjectHydrator
Tries to hydrate instance of object using his public interface, that is:
- by setting public properties values
- by using setters (
setSomething
orwithSomething
assuming immutability)
Customizing and extending
Mapper
consists of 3 components:
GetterMap
that describes mapping asstring => Getter
association,Wrapper
that wraps input mixed structure with properInput
implementation,Formatter
that formats raw mapping result (associative array) to array, object, XML, JSON and so on.
Implement Input
and Wrapper
to extract data from specific sources
It is possible to define data extracting for some object type explicitly.
Use only MixedWrapper
for better performance
By default Mapper supports nested structure fetching and value filters, which is nice but has some expense in performance (see BENCHMARK.md). But it is possible to create Mapper only with MixedWrapper when these feature are not needed.
Custom filters for FilteredInput
Filter functions list can be extended or overwritten with own implementation.
Custom Formatter
Custom formatter can be used to achieve better object construction performance than generic object formatters. It is also possible to create formatters creating different result types like XML, JSON etc.
All versions of data-map with dependencies
ext-json Version *
ext-ctype Version *