Documentation

Converter

\Bitrix\Main\Engine\Response\Converter - class coverts strings or arrays, containing strings.

Frequently, style guidelines for format and data going to the frontend must be complied with when writing backend API. For example, converting all key from snake_case to camelCase. Other conversions are all likely as well. To avoid "manual" adjustments, you may use the class Response\Converter, capable to convert as follows:

  • camelCase -> snake_case Response\Converter::TO_SNAKE
  • snake_case -> camelCase Response\Converter::TO_CAMEL
  • Response\Converter::TO_SNAKE_DIGIT
  • some string -> SOME STRING Response\Converter::TO_UPPER
  • SOME STRING -> some string Response\Converter::TO_LOWER
  • SOME STRING -> sOME STRING Response\Converter::LC_FIRST
  • some string -> Some string Response\Converter::UC_FIRST
  • Apply conversion to keys of associative array Response\Converter::KEYS
  • Apply conversion to array values Response\Converter::VALUES
  • Perform conversion recursively for array and inserted arrays Response\Converter::RECURSIVE

Methods

Method Description Available from version
__construct(
   $format
)
Constructor method. Parameters:
  • $format {int} Listing the required formatting. Bit masks are used. Available options can be found in constants of class \Bitrix\Main\Engine\Response\Converter.
toJson(
)
Creates object immediately setting the format for converting into camelCase array \Bitrix\Main\Engine\Response\Converter::OUTPUT_JSON_FORMAT.
process($data)
Parameter: $data {string|array} Data to be converted.
getFormat()
int. getting current format, listing the conversions.
setFormat($format)
Parameter: $format {int} Listing of required conversions. Bit masks are used. Available options can be found in constants of class \Bitrix\Main\Engine\Response\Converter.

Example

use \Bitrix\Main\Engine\Response\Converter;

$converter = new Converter(Converter::LC_FIRST | Converter::TO_CAMEL);
echo $converter->process('la_la_land'); //laLaLand

$converter = new Converter(Converter::OUTPUT_JSON_FORMAT);
$converter->process([
    'CATEGORIES' => [
        [
            'ID' => 1,
            'NAME' => 'Foods',
        ],
        [
            'ID' => 12,
            'NAME' => 'Auto',
        ]
    ]
]);
/**
[
  'categories' => [
    [
      'id' => 1,
      'name' => 'foods',
    ],
    [
      'id' => 12,
      'name' => 'auto',
    ],
  ],
]
**/

$converter = new Converter(Converter::TO_SNAKE_DIGIT | Converter::VALUES | Converter::KEYS | Converter::RECURSIVE);
$converter->process([
    'property109',
    'props' => [
        'element1' => [
            'property210'
        ],
    ]
]);
/**
[
'property_109',
'props' => [
    'element_1' => [
        'property_210'
    ],
];
**/

© «Bitrix24», 2001-2024
Up