Files
kupshop/class/smarty_plugins/function.insert_external_feed.php
2025-08-02 16:30:27 +02:00

96 lines
2.9 KiB
PHP

<?php
function smarty_function_insert_external_feed($params, &$smarty)
{
if (empty($params['url']) || empty($params['count'])) {
throw new InvalidArgumentException('Missing required parameter \'url\' or \'count\'');
}
$default = [
'template' => 'block.external_feed.rss.tpl',
'cache' => 1,
'type' => 'rss',
'ttl' => 7200,
'cache_key' => function ($params) {
return ['insert_external_feed', $params['template'], $params['type'], $params['url'], $params['count']];
},
];
$params = array_merge($default, $params);
$params['get_data_function'] = function (&$params) {
$feed = simplexml_load_file($params['url'], null, LIBXML_NOCDATA);
if ($feed === false) {
$params['ttl'] = 5;
}
$params['items'] = [];
switch ($params['type']) {
case 'rss':
foreach ($feed->channel->item as $item) {
$params['items'][] = xml2array($item);
}
break;
case 'atom':
foreach ($feed->entry as $item) {
$params['items'][] = xml2array($item);
}
break;
case 'heureka_review':
foreach ($feed->review as $item) {
$params['items'][] = xml2array($item);
}
break;
default:
throw new InvalidArgumentException('Type \''.$params['type'].'\' is not supported');
}
$params['items'] = array_slice($params['items'], 0, $params['count']);
};
if (!empty($params['template'])) {
$smarty->loadPlugin('Smarty_function_include_cached');
smarty_function_include_cached_optional($params, $smarty);
}
if (!empty($params['assign'])) {
if (empty($params['template'])) {
$params['get_data_function']($params);
}
$smarty->assign($params['assign'], $params);
}
return null;
}
function xml2array($xmlObject, $out = [])
{
foreach ((array) $xmlObject as $index => $node) {
$out[$index] = (is_object($node) || is_array($node)) ? xml2array($node) : (string) $node;
}
if (is_object($xmlObject)) {
foreach ($xmlObject->attributes() as $name => $attribute) {
$out["@{$name}"] = (string) $attribute;
}
foreach ($xmlObject->getDocNamespaces() as $namespace) {
foreach ($xmlObject->children($namespace) as $index => $node) {
$out[$index] = (is_object($node) || is_array($node)) ? xml2array($node) : (string) $node;
}
foreach ($xmlObject->attributes($namespace) as $name => $attribute) {
$out["@{$name}"] = (string) $attribute;
}
}
}
foreach ($out as $key => $item) {
if (is_array($item) && count($item) === 1 && key($item) == 0) {
$out[$key] = reset($item);
}
}
return $out;
}