2013-08-11 15:30:41 +04:00
|
|
|
<?php
|
2022-07-01 16:10:30 +03:00
|
|
|
|
2022-06-22 19:27:20 +03:00
|
|
|
class FormatFactory
|
|
|
|
{
|
2024-01-25 18:06:24 +03:00
|
|
|
private array $formatNames = [];
|
2022-06-22 19:27:20 +03:00
|
|
|
|
2024-01-25 18:06:24 +03:00
|
|
|
public function __construct()
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
2024-01-25 18:06:24 +03:00
|
|
|
$iterator = new \FilesystemIterator(__DIR__ . '/../formats');
|
|
|
|
foreach ($iterator as $file) {
|
|
|
|
if (preg_match('/^([^.]+)Format\.php$/U', $file->getFilename(), $m)) {
|
2022-07-01 16:10:30 +03:00
|
|
|
$this->formatNames[] = $m[1];
|
|
|
|
}
|
|
|
|
}
|
2024-01-25 18:06:24 +03:00
|
|
|
sort($this->formatNames);
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
2022-06-22 19:27:20 +03:00
|
|
|
|
2023-09-25 22:18:48 +03:00
|
|
|
public function create(string $name): FormatAbstract
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
|
|
|
if (! preg_match('/^[a-zA-Z0-9-]*$/', $name)) {
|
|
|
|
throw new \InvalidArgumentException('Format name invalid!');
|
|
|
|
}
|
2024-01-25 18:06:24 +03:00
|
|
|
$sanitizedName = $this->sanitizeName($name);
|
|
|
|
if (!$sanitizedName) {
|
2022-10-16 18:55:43 +03:00
|
|
|
throw new \InvalidArgumentException(sprintf('Unknown format given `%s`', $name));
|
2022-07-01 16:10:30 +03:00
|
|
|
}
|
2022-10-16 18:55:43 +03:00
|
|
|
$className = '\\' . $sanitizedName . 'Format';
|
2022-07-01 16:10:30 +03:00
|
|
|
return new $className();
|
|
|
|
}
|
2013-08-11 15:30:41 +04:00
|
|
|
|
2022-07-01 16:10:30 +03:00
|
|
|
public function getFormatNames(): array
|
|
|
|
{
|
|
|
|
return $this->formatNames;
|
|
|
|
}
|
2018-11-15 22:08:33 +03:00
|
|
|
|
2024-01-25 18:06:24 +03:00
|
|
|
protected function sanitizeName(string $name): ?string
|
2022-07-01 16:10:30 +03:00
|
|
|
{
|
|
|
|
$name = ucfirst(strtolower($name));
|
|
|
|
// Trim trailing '.php' if exists
|
|
|
|
if (preg_match('/(.+)(?:\.php)/', $name, $matches)) {
|
|
|
|
$name = $matches[1];
|
|
|
|
}
|
|
|
|
// 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;
|
|
|
|
}
|
2016-08-23 15:29:53 +03:00
|
|
|
}
|