Array Manager Class in Magento 2

Magento 2 Commerce provides a powerful set of tools for PHP developers to work and simplify their lives when building Magento 2 extensions. Magento 2 Framework includes various components and sub-components allowing you to write less code in your extensions.

Today we are going to talk about a utility class, that helps when working with giant arrays of data and configurations.

It is not a secret, that Magento 2 uses XML files for storing critical parts of system's configurations. Behind the scenes, when an XML file is opened by Magento 2, the file is converted and presented as an array. It is much simple working with array than with an DomDocumentobject in PHP.

Let's take a checkout configuration in Magento 2. Every time a value should be added into the checkout configuration a developer should write a very long chain of array keys to get access to a desired tree level.

Here is an example of the nested $jsLayoutarray from the LayoutProcessor::process()method located in the Magento\Checkoutmodule:

$fields = $jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']

In most of the cases the above example code snippet is used in 3rd party Magento 2 extensions related to checkout customizations. As we may notice, the usability and readability of nested arrays requires an improvement.

The solution is to use an Array Manager utility class.

Array Manager

The Array Manager provides an easy read and write access to arrays. That's probably the only description that should be provided to explain the purpose of the Array Manager.

The Magento\Framework\Stdlib\ArrayManagerclass provides a simple but powerful utility methods when working with arrays.

Let's take the above source code example and re-write it with an ArrayManagerclass.

$arrayManager = new ArrayManager();

$path = $arrayManager->findPath('shipping-address-fieldset', $jsLayout, 'components');
$fields = $arrayManager->get($path, $jsLayout);

You may find the use of the ArrayManagerclass straightforward and simple to read approach. This is a definitely something you can use when working with the nested arrays. Especially when it comes to building customizations for checkout in Magento 2 Commerce. Particularly, when there is a requirement to modify layout configuration before it is rendered.