Drupal 8  8.0.2
NestedArray Class Reference

Static Public Member Functions

static & getValue (array &$array, array $parents, &$key_exists=NULL)
 
static setValue (array &$array, array $parents, $value, $force=FALSE)
 
static unsetValue (array &$array, array $parents, &$key_existed=NULL)
 
static keyExists (array $array, array $parents)
 
static mergeDeep ()
 
static mergeDeepArray (array $arrays, $preserve_integer_keys=FALSE)
 

Detailed Description

Provides helpers to perform operations on nested arrays and array keys of variable depth.

Member Function Documentation

static& getValue ( array &  $array,
array  $parents,
$key_exists = NULL 
)
static

Retrieves a value from a nested array with variable depth.

This helper function should be used when the depth of the array element being retrieved may vary (that is, the number of parent keys is variable). It is primarily used for form structures and renderable arrays.

Without this helper function the only way to get a nested array value with variable depth in one line would be using eval(), which should be avoided:

// Do not do this! Avoid eval().
// May also throw a PHP notice, if the variable array keys do not exist.
eval('$value = $array[\'' . implode("']['", $parents) . "'];");

Instead, use this helper function:

$value = NestedArray::getValue($form, $parents);

A return value of NULL is ambiguous, and can mean either that the requested key does not exist, or that the actual value is NULL. If it is required to know whether the nested array key actually exists, pass a third argument that is altered by reference:

$key_exists = NULL;
$value = NestedArray::getValue($form, $parents, $key_exists);
if ($key_exists) {
// Do something with $value.
}

However if the number of array parent keys is static, the value should always be retrieved directly rather than calling this function. For instance:

$value = $form['signature_settings']['signature'];
Parameters
array$arrayThe array from which to get the value.
array$parentsAn array of parent keys of the value, starting with the outermost key.
bool$key_exists(optional) If given, an already defined variable that is altered by reference.
Returns
mixed The requested nested value. Possibly NULL if the value is NULL or not all nested parent keys exist. $key_exists is altered by reference and is a Boolean that indicates whether all nested parent keys exist (TRUE) or not (FALSE). This allows to distinguish between the two possibilities when NULL is returned.
See Also
NestedArray::setValue()
NestedArray::unsetValue()

Referenced by WidgetBase\addMoreAjax(), WidgetBase\addMoreSubmit(), FormState\cleanValues(), WidgetBase\extractFormValues(), Config\get(), ConfigBase\get(), FormState\get(), Row\getDestinationProperty(), Config\getOriginal(), WizardPluginBase\getSelected(), Row\getSourceProperty(), FormState\getTemporaryValue(), FormState\getValue(), WidgetBase\getWidgetState(), FormValidator\handleErrorsWithLimitedValidation(), FormBuilder\handleInputElement(), FormState\has(), FormState\hasTemporaryValue(), FormState\hasValue(), FormState\isValueEmpty(), FileWidget\process(), MachineName\processMachineName(), LibraryDiscoveryParser\setOverrideValue(), EntityReferenceItem\settingsAjax(), FileWidget\submit(), Sql\submitOptionsForm(), MenuForm\submitOverviewForm(), FormBuilderTest\testChildAccessInheritance(), NestedArrayTest\testGetValue(), Extract\transform(), StaticMap\transform(), Datelist\validateDatelist(), Datetime\validateDatetime(), FileWidget\validateMultipleCount(), and ImageWidget\validateRequiredFields().

Here is the caller graph for this function:

static keyExists ( array  $array,
array  $parents 
)
static

Determines whether a nested array contains the requested keys.

This helper function should be used when the depth of the array element to be checked may vary (that is, the number of parent keys is variable). See NestedArray::setValue() for details. It is primarily used for form structures and renderable arrays.

If it is required to also get the value of the checked nested key, use NestedArray::getValue() instead.

If the number of array parent keys is static, this helper function is unnecessary and the following code can be used instead:

$value_exists = isset($form['signature_settings']['signature']);
$key_exists = array_key_exists('signature', $form['signature_settings']);
Parameters
array$arrayThe array with the value to check for.
array$parentsAn array of parent keys of the value, starting with the outermost key.
Returns
bool TRUE if all the parent keys exist, FALSE otherwise.
See Also
NestedArray::getValue()

Referenced by FormValidator\handleErrorsWithLimitedValidation(), FormBuilder\handleInputElement(), Row\hasDestinationProperty(), Row\hasSourceProperty(), and NestedArrayTest\testKeyExists().

Here is the caller graph for this function:

static mergeDeep ( )
static

Merges multiple arrays, recursively, and returns the merged array.

This function is similar to PHP's array_merge_recursive() function, but it handles non-array values differently. When merging values that are not both arrays, the latter value replaces the former rather than merging with it.

Example:

$link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
$link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
// This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
$incorrect = array_merge_recursive($link_options_1, $link_options_2);
// This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
$correct = NestedArray::mergeDeep($link_options_1, $link_options_2);
Parameters
array... Arrays to merge.
Returns
array The merged array.
See Also
NestedArray::mergeDeepArray()

Referenced by ConfigurableSearchPluginBase\__construct(), Plugin\__construct(), ConfigEntityDependency\__construct(), LibraryDiscoveryCollector\applyLibrariesExtend(), ModuleHandler\buildHookInfo(), View\duplicateDisplayAsType(), ClientFactory\fromOptions(), ViewsData\getData(), ConfigEntityBase\getDependencies(), EntityTestViewsData\getViewsData(), FilterPluginCollection\initializePlugin(), ModuleHandler\invokeAll(), LibraryDiscoveryParser\parseLibraryInfo(), SystemCompactLink\preRenderCompactLink(), MenuLinkManager\processDefinition(), DefaultPluginManager\processDefinition(), BlockBase\setConfiguration(), and NestedArrayTest\testMergeDeepArray().

Here is the caller graph for this function:

static mergeDeepArray ( array  $arrays,
  $preserve_integer_keys = FALSE 
)
static

Merges multiple arrays, recursively, and returns the merged array.

This function is equivalent to NestedArray::mergeDeep(), except the input arrays are passed as a single array parameter rather than a variable parameter list.

The following are equivalent:

The following are also equivalent:

Parameters
array$arraysAn arrays of arrays to merge.
bool$preserve_integer_keys(optional) If given, integer keys will be preserved and merged instead of appended. Defaults to FALSE.
Returns
array The merged array.
See Also
NestedArray::mergeDeep()

Referenced by EntityViewDisplay\collectRenderDisplays(), WebTestBase\drupalProcessAjaxResponse(), Internal\getConfig(), TypedConfigManager\getDefinition(), EditorSelector\getEditorAttachments(), CKEditorPluginManager\getEnabledPluginFiles(), AssetResolver\getJsAssets(), AssetResolver\getJsSettingsAssets(), Config\getOriginal(), ConfigFactory\loadOverrides(), ConfigBase\merge(), BubbleableMetadata\mergeAttachments(), Migration\mergeProcessOfProperty(), FieldNormalizer\normalize(), Config\setOverriddenData(), ConfigModuleOverridesEvent\setOverride(), NestedArrayTest\testMergeDeepArray(), NestedArrayTest\testMergeExplicitKeys(), NestedArrayTest\testMergeImplicitKeys(), NestedArrayTest\testMergeOutOfSequenceKeys(), and LocaleConfigManager\updateConfigTranslations().

Here is the caller graph for this function:

static setValue ( array &  $array,
array  $parents,
  $value,
  $force = FALSE 
)
static

Sets a value in a nested array with variable depth.

This helper function should be used when the depth of the array element you are changing may vary (that is, the number of parent keys is variable). It is primarily used for form structures and renderable arrays.

Example:

// Assume you have a 'signature' element somewhere in a form. It might be:
$form['signature_settings']['signature'] = array(
'#type' => 'text_format',
'#title' => t('Signature'),
);
// Or, it might be further nested:
$form['signature_settings']['user']['signature'] = array(
'#type' => 'text_format',
'#title' => t('Signature'),
);

To deal with the situation, the code needs to figure out the route to the element, given an array of parents that is either

array('signature_settings', 'signature')

in the first case or

array('signature_settings', 'user', 'signature')

in the second case.

Without this helper function the only way to set the signature element in one line would be using eval(), which should be avoided:

// Do not do this! Avoid eval().
eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');

Instead, use this helper function:

NestedArray::setValue($form, $parents, $element);

However if the number of array parent keys is static, the value should always be set directly rather than calling this function. For instance, for the first example we could just do:

$form['signature_settings']['signature'] = $element;
Parameters
array$arrayA reference to the array to modify.
array$parentsAn array of parent keys, starting with the outermost key.
mixed$valueThe value to set.
bool$force(optional) If TRUE, the value is forced into the structure even if it requires the deletion of an already existing non-array parent value. If FALSE, PHP throws an error if trying to add into a value that is not an array. Defaults to FALSE.
See Also
NestedArray::unsetValue()
NestedArray::getValue()

Referenced by CommentLinkBuilder\buildCommentedEntityLinks(), FormValidator\handleErrorsWithLimitedValidation(), FormBuilder\handleInputElement(), MachineName\processMachineName(), ConfigBase\set(), FormState\set(), Row\setDestinationProperty(), LibraryDiscoveryParser\setOverrideValue(), Row\setSourceProperty(), FormState\setTemporaryValue(), FormState\setValue(), WidgetBase\setWidgetState(), FileWidget\submit(), NestedArrayTest\testSetValue(), NestedArrayTest\testSetValueForce(), EntityConfigBase\updateEntityProperty(), and FileWidget\validateMultipleCount().

Here is the caller graph for this function:

static unsetValue ( array &  $array,
array  $parents,
$key_existed = NULL 
)
static

Unsets a value in a nested array with variable depth.

This helper function should be used when the depth of the array element you are changing may vary (that is, the number of parent keys is variable). It is primarily used for form structures and renderable arrays.

Example:

// Assume you have a 'signature' element somewhere in a form. It might be:
$form['signature_settings']['signature'] = array(
'#type' => 'text_format',
'#title' => t('Signature'),
);
// Or, it might be further nested:
$form['signature_settings']['user']['signature'] = array(
'#type' => 'text_format',
'#title' => t('Signature'),
);

To deal with the situation, the code needs to figure out the route to the element, given an array of parents that is either

array('signature_settings', 'signature')

in the first case or

array('signature_settings', 'user', 'signature')

in the second case.

Without this helper function the only way to unset the signature element in one line would be using eval(), which should be avoided:

// Do not do this! Avoid eval().
eval('unset($form[\'' . implode("']['", $parents) . '\']);');

Instead, use this helper function:

NestedArray::unset_nested_value($form, $parents, $element);

However if the number of array parent keys is static, the value should always be set directly rather than calling this function. For instance, for the first example we could just do:

unset($form['signature_settings']['signature']);
Parameters
array$arrayA reference to the array to modify.
array$parentsAn array of parent keys, starting with the outermost key and including the key to be unset.
bool$key_existed(optional) If given, an already defined variable that is altered by reference.
See Also
NestedArray::setValue()
NestedArray::getValue()

Referenced by ConfigBase\clear(), Row\removeDestinationProperty(), LibraryDiscoveryParser\setOverrideValue(), NestedArrayTest\testUnsetValue(), and FormState\unsetValue().

Here is the caller graph for this function:


The documentation for this class was generated from the following file: