2013-08-11 15:30:41 +04:00
|
|
|
<?php
|
2022-07-01 16:10:30 +03:00
|
|
|
|
2018-11-15 22:01:56 +03:00
|
|
|
/**
|
|
|
|
* This file is part of RSS-Bridge, a PHP project capable of generating RSS and
|
|
|
|
* Atom feeds for websites that don't have one.
|
|
|
|
*
|
|
|
|
* For the full license information, please view the UNLICENSE file distributed
|
|
|
|
* with this source code.
|
|
|
|
*
|
|
|
|
* @package Core
|
|
|
|
* @license http://unlicense.org/ UNLICENSE
|
|
|
|
* @link https://github.com/rss-bridge/rss-bridge
|
|
|
|
*/
|
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
class FormatFactory
|
|
|
|
{
|
|
|
|
private $folder;
|
|
|
|
private $formatNames;
|
|
|
|
|
|
|
|
public function __construct(string $folder = PATH_LIB_FORMATS)
|
|
|
|
{
|
|
|
|
$this->folder = $folder;
|
|
|
|
|
|
|
|
// create format names
|
|
|
|
foreach (scandir($this->folder) as $file) {
|
|
|
|
if (preg_match('/^([^.]+)Format\.php$/U', $file, $m)) {
|
|
|
|
$this->formatNames[] = $m[1];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-11-15 22:01:56 +03:00
|
|
|
/**
|
2022-06-22 19:27:20 +03:00
|
|
|
* @throws \InvalidArgumentException
|
|
|
|
* @param string $name The name of the format e.g. "Atom", "Mrss" or "Json"
|
2018-11-15 22:01:56 +03:00
|
|
|
*/
|
2022-06-22 19:27:20 +03:00
|
|
|
public function create(string $name): FormatInterface
|
|
|
|
{
|
|
|
|
if (! preg_match('/^[a-zA-Z0-9-]*$/', $name)) {
|
2018-11-15 22:01:56 +03:00
|
|
|
throw new \InvalidArgumentException('Format name invalid!');
|
2016-09-10 21:41:11 +03:00
|
|
|
}
|
2021-02-09 16:13:03 +03:00
|
|
|
$name = $this->sanitizeFormatName($name);
|
2022-06-22 19:27:20 +03:00
|
|
|
if ($name === null) {
|
2021-02-09 16:13:03 +03:00
|
|
|
throw new \InvalidArgumentException('Unknown format given!');
|
|
|
|
}
|
2022-06-22 19:27:20 +03:00
|
|
|
$className = '\\' . $name . 'Format';
|
|
|
|
return new $className();
|
2016-09-10 21:41:11 +03:00
|
|
|
}
|
2013-08-11 15:30:41 +04:00
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
public function getFormatNames(): array
|
|
|
|
{
|
|
|
|
return $this->formatNames;
|
2018-11-15 22:08:33 +03:00
|
|
|
}
|
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
protected function sanitizeFormatName(string $name)
|
|
|
|
{
|
2021-02-09 16:13:03 +03:00
|
|
|
$name = ucfirst(strtolower($name));
|
2019-06-18 19:32:56 +03:00
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
// Trim trailing '.php' if exists
|
|
|
|
if (preg_match('/(.+)(?:\.php)/', $name, $matches)) {
|
|
|
|
$name = $matches[1];
|
2019-06-18 19:32:56 +03:00
|
|
|
}
|
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
// Trim trailing 'Format' if exists
|
|
|
|
if (preg_match('/(.+)(?:Format)/i', $name, $matches)) {
|
|
|
|
$name = $matches[1];
|
|
|
|
}
|
|
|
|
if (in_array($name, $this->formatNames)) {
|
|
|
|
return $name;
|
|
|
|
}
|
|
|
|
return null;
|
2019-06-18 19:32:56 +03:00
|
|
|
}
|
2016-08-23 15:29:53 +03:00
|
|
|
}
|