Минимальная цена из MIGX в сниппете MODX

Листинг орёт «от 4 990», а цены сидят внутри MIGX: три тарифа, две опции, менеджер вчера добавил четвёртую. Отдельное TV «мин. цена» он заполнит один раз и забудет навсегда. Пусть считает машина.

Берём детей раздела, джойним значение нужного TV, JSON разбираем, из строк тащим price, отдаём минимум. Id TV параметром, не магической девяткой в коде, которую через год никто не вспомнит. Пустой MIGX — пустая строка, не min() по пустому массиву с фаталом посреди категории.

<?php
$pdo = $modx->getService('pdoFetch');
if (!$pdo) {
    return '';
}

$tvId = (int) $modx->getOption('tvId', $scriptProperties, 0);
$parent = (int) $modx->getOption('parent', $scriptProperties, 0);
$exclude = array_filter(array_map('intval', explode(',', $modx->getOption('exclude', $scriptProperties, ''))));
if ($tvId <= 0 || $parent <= 0) {
    return '';
}

$where = array(
    'modResource.parent' => $parent,
    'modResource.published' => 1,
    'modResource.deleted' => 0,
);
if ($exclude) {
    $where['modResource.id:NOT IN'] = $exclude;
}

$rows = $pdo->getCollection('modResource', $where, array(
    'innerJoin' => array(
        'TV' => array(
            'class' => 'modTemplateVarResource',
            'on' => 'TV.contentid = modResource.id AND TV.tmplvarid = ' . $tvId,
        ),
    ),
    'select' => array(
        'modResource' => 'modResource.id',
        'TV' => 'TV.value',
    ),
));

$prices = array();
foreach ($rows as $row) {
    $data = json_decode($row['value'], true);
    if (!is_array($data)) {
        continue;
    }
    foreach ($data as $item) {
        if (!is_array($item) || !isset($item['price'])) {
            continue;
        }
        $price = (float) str_replace(array(' ', ','), array('', '.'), $item['price']);
        if ($price > 0) {
            $prices[] = $price;
        }
    }
}

if (!$prices) {
    return '';
}

$min = min($prices);
if ($miniShop2 = $modx->getService('miniShop2')) {
    return $miniShop2->formatPrice($min);
}
return $min;

Вызов: сниппет, &tvId, &parent, по желанию &exclude через запятую. Поле в MIGX должно называться price, не «Цена» с большой буквы и пробелом. Если назвали по-русски — в цикле ключ свой, я телепат выходной.

Комментарии


Комментарии (0)



Разрешённые теги: <b><i><br>Добавить новый комментарий: