85 lines
2.4 KiB
PHP
85 lines
2.4 KiB
PHP
|
<?php
|
||
|
|
||
|
namespace RssLib\Classes;
|
||
|
|
||
|
use InvalidArgumentException;
|
||
|
use SimpleXMLElement;
|
||
|
|
||
|
class Utilities
|
||
|
{
|
||
|
/**
|
||
|
* Attempts to parse a string into a timestamp
|
||
|
*
|
||
|
* @param string $input
|
||
|
* @return int
|
||
|
*/
|
||
|
public static function parseTimestamp(string $input): int
|
||
|
{
|
||
|
$timestamp = strtotime($input);
|
||
|
|
||
|
if($timestamp === false)
|
||
|
{
|
||
|
throw new InvalidArgumentException(sprintf('Invalid timestamp %s', $input));
|
||
|
}
|
||
|
|
||
|
return $timestamp;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Converts a SimpleXMLElement to an array representation
|
||
|
*
|
||
|
* @param SimpleXMLElement $element
|
||
|
* @return array
|
||
|
* @noinspection UnknownInspectionInspection
|
||
|
*/
|
||
|
public static function xmlToArray(SimpleXMLElement $element): array
|
||
|
{
|
||
|
$array = [];
|
||
|
if ($element->attributes())
|
||
|
{
|
||
|
foreach ($element->attributes() as $name => $value)
|
||
|
{
|
||
|
$array[$element->getName() . '_' . $name] = (string)$value;
|
||
|
}
|
||
|
if (trim((string)$element) !== '')
|
||
|
{
|
||
|
$array[$element->getName()] = trim((string)$element);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Handle child elements
|
||
|
$items = [];
|
||
|
foreach ($element->children() as $child)
|
||
|
{
|
||
|
$value = ($child->count() > 0 || $child->attributes()) ? self::xmlToArray($child) : (string)$child;
|
||
|
|
||
|
if ($child->getName() === 'item')
|
||
|
{
|
||
|
$items[] = $value;
|
||
|
}
|
||
|
else if (isset($array[$child->getName()]))
|
||
|
{
|
||
|
if (!is_array($array[$child->getName()]))
|
||
|
{
|
||
|
$array[$child->getName()] = [$array[$child->getName()]];
|
||
|
}
|
||
|
|
||
|
/** @noinspection UnsupportedStringOffsetOperationsInspection */
|
||
|
$array[$child->getName()][] = $value;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
$array[$child->getName()] = $value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
if (!empty($items))
|
||
|
{
|
||
|
$array['item'] = $items;
|
||
|
}
|
||
|
|
||
|
return $array;
|
||
|
}
|
||
|
|
||
|
|
||
|
}
|