Skip to content

fix(Fetch.php): warning when preparing condition for log message#385

Open
gitrequests wants to merge 1 commit intomodx-pro:3x-newfrom
gitrequests:3x-new
Open

fix(Fetch.php): warning when preparing condition for log message#385
gitrequests wants to merge 1 commit intomodx-pro:3x-newfrom
gitrequests:3x-new

Conversation

@gitrequests
Copy link

@gitrequests gitrequests commented Aug 15, 2025

Что оно делает?

Исправляет warning при подготовке сообщения для логирования

[2025-08-15 10:53:13] (ERROR @ /var/www/public/core/components/pdotools/src/Fetch.php : 229) PHP warning: Array to string conversion

Описание проблемы

Исходя из документации по xPDOQuery::where Этот запрос может быть комплексным и включать в себя многомерный массив. Из за этого функция implode принимает значения, которые не может обработать.

В качестве примера вот такой запрос WHERE отлично парсится и отрабатывает в MODX, но выдает WARNING в коде, который предназначен для подготовки WHERE запроса к логировалию (Смотрите пример предупреждения выше):

[
    [
        [
            "TVtags.value:LIKE" => "%hit%"
        ],
        [
            "OR:TVtags.value:LIKE" => "%promo%"
        ],
        [
            "OR:TVtags.value:LIKE" => "%sale%"
        ],
    ],
    [
        "TVprice.value:>=" => 104,
        "AND:TVprice.value:<=" => 140
    ],
    "modResource.parent:IN" => [5],
    "modResource.template:IN" => [3],
    "modResource.published" => 1,
    "modResource.deleted" => 0
]

Обратите внимание на различие TVprice и TVtags. Из за того, что TVtags могут иметь несколько значений, мы не можем иметь одну вложенность массива (иначе ключ "OR:TVtags.value:LIKE" будет повторяться, и значения будут переписаны, а не добавлены):

// Этот участок кода не работает из за повторяющегося ключа массива
 [
    [
        "TVtags.value:LIKE" => "%hit%",
        "OR:TVtags.value:LIKE" => "%promo%", //<-- Ключь массива установлен
        "OR:TVtags.value:LIKE" => "%sale%" //<-- Значение перепишет предыдущий ключь
    ]
]

Поэтому мы можем передать многомерный массив в xPDOQuery.

Парсер xPDOQuery обрабатывает такие массивы рекурсивно, с любым уровнем вложенности.


Предлагаю заменить логирование WHERE (и заодно и HAVING чуть ниже) на json_encode - это выведет в сообщения логов более четкую информацию о том, что именно попало в WHERE и так же снизит количество warning (и error в будущих версиях PHP).

}
}
$this->addTime('Added where condition: <b>' . implode(', ', $condition) . '</b>', microtime(true) - $time);
$this->addTime('Added where condition: <b>' . json_encode($where) . '</b>', microtime(true) - $time);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$this->addTime('Added where condition: <b>' . json_encode($where) . '</b>', microtime(true) - $time);
$whereLog = json_encode($where);
$this->addTime('Added where condition: ' . ($whereLog !== false ? $whereLog : print_r($where, true)) . ' ', microtime(true) - $time);

json_encode() may return false if the UTF-8 format is invalid or if there are circular references. In this case, an empty line will be logged.

}
}
$this->addTime('Added having condition: <b>' . implode(', ', $condition) . '</b>', microtime(true) - $time);
$this->addTime('Added having condition: <b>' . json_encode($having) . '</b>', microtime(true) - $time);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$this->addTime('Added having condition: <b>' . json_encode($having) . '</b>', microtime(true) - $time);
$havingLog = json_encode($having);
$this->addTime('Added having condition: ' . ($havingLog !== false ? $havingLog : print_r($having, true)) . ' ', microtime(true) - $time);

json_encode() may return false if the UTF-8 format is invalid or if there are circular references. In this case, an empty line will be logged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants