aboutsummaryrefslogtreecommitdiff
path: root/lib/FormatFactory.php
blob: 042dcf3120ddcf0826806301d35648cbe0d3c5a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?php

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];
            }
        }
    }

    /**
     * @throws \InvalidArgumentException
     * @param string $name The name of the format e.g. "Atom", "Mrss" or "Json"
     */
    public function create(string $name): FormatAbstract
    {
        if (! preg_match('/^[a-zA-Z0-9-]*$/', $name)) {
            throw new \InvalidArgumentException('Format name invalid!');
        }
        $sanitizedName = $this->sanitizeFormatName($name);
        if ($sanitizedName === null) {
            throw new \InvalidArgumentException(sprintf('Unknown format given `%s`', $name));
        }
        $className = '\\' . $sanitizedName . 'Format';
        return new $className();
    }

    public function getFormatNames(): array
    {
        return $this->formatNames;
    }

    protected function sanitizeFormatName(string $name)
    {
        $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;
    }
}