Search code examples
phpparsingtokenizebitrix

Parsing PHP file in order to get an array of parameters


I have a PHP file with following content:

<?
require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php");

$APPLICATION->IncludeComponent(
    "hoo:account",
    "hoo",
    array(
        "COMPONENT_TEMPLATE" => "hoo",
        "ACCOUNT_URL" => "/account/",
        "LOG_IN_URL" => "/log-in/",
        "FIELDS_REQUIRED" => array(
            0 => "FIRST_NAME",
            1 => "LAST_NAME",
            2 => "BIRTHDAY",
        ),
        "FIELDS_VALIDATED" => array(
            0 => "BIRTHDAY",
            1 => "COMPANY_VAT_CODE",
        ),
        "AGE_MIN" => "18",
        "AGE_MAX" => "180",
        "COMPANY_VAT_CODE_VALIDATION_SERVICE_CACHE_TTL" => "86400",
        "COMPANY_VAT_CODE_VALIDATION_SERVICE_SERVICE_UNAVAILABLE_ERROR" => "Y",
        ...
    ), false);

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");
?>

Somehow I need to parse this file in order to get an associative array with parameters to use it somewhere else in my code. Please give me some ideas and code examples how to achieve that goal.

Thanks in advance!


Solution

  • Using Tokenizer I was able to write a small parser to achieve my goal:

    <?
    $tokens = token_get_all();
    
    $componentName = "hoo:account";
    
    $arParams = array();
    
    foreach ($tokens as $tokenKey => $token) {
        if (is_array($token)) {
            if (_getTokenName($token) == "T_STRING" &&
                _getToken($tokens, $tokenKey + 3) == $componentName
            ) {
                $isComponent = true;
            } elseif (_getTokenName($token) == "T_STRING" &&
                      _getToken($tokens, $tokenKey + 3) != $componentName
            ) {
                $isComponent = false;
            }
    
            if ($isComponent) {
                if (_getTokenName($token) == "T_DOUBLE_ARROW") {
                    if (_getTokenName($tokens[$tokenKey - 2]) == "T_CONSTANT_ENCAPSED_STRING") {
                        if (_getTokenName($tokens[$tokenKey + 2]) == "T_ARRAY") {
                            $key = _getToken($tokens, $tokenKey - 2);
                        } else {
                            $arParams[_getToken($tokens, $tokenKey - 2)] = _getToken($tokens, $tokenKey + 2);
                        }
                    } elseif (_getTokenName($tokens[$tokenKey - 2]) == "T_LNUMBER") {
                        $arParams[$key][] = _getToken($tokens, $tokenKey + 2);
                    }
                }
            }
        }
    }
    
    function _getTokenName(array $token): string {
        return token_name($token[0]);
    }
    
    function _getToken(array $tokens, int $key): int | string {
        return trim($tokens[$key][1], "\"");
    }
    ?>