Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BaseFactory.php « core - github.com/matomo-org/matomo.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 789f77680ef14e2dc8b02b2bd75e0af6deb89e62 (plain)
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
61
62
63
64
65
<?php
/**
 * Matomo - free/libre analytics platform
 *
 * @link https://matomo.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik;

use Exception;

/**
 * Base class for all factory types.
 *
 * Factory types are base classes that contain a **factory** method. This method is used to instantiate
 * concrete instances by a specified string ID. Fatal errors do not occur if a class does not exist.
 * Instead an exception is thrown.
 *
 * Derived classes should override the **getClassNameFromClassId** and **getInvalidClassIdExceptionMessage**
 * static methods.
 */
abstract class BaseFactory
{
    /**
     * Creates a new instance of a class using a string ID.
     *
     * @param string $classId The ID of the class.
     * @return \Piwik\DataTable\Renderer
     * @throws Exception if $classId is invalid.
     */
    public static function factory($classId)
    {
        $className = static::getClassNameFromClassId($classId);

        if (!class_exists($className)) {
            self::sendPlainHeader();
            throw new Exception(static::getInvalidClassIdExceptionMessage($classId));
        }

        return new $className;
    }

    private static function sendPlainHeader()
    {
        Common::sendHeader('Content-Type: text/plain; charset=utf-8');
    }

    /**
     * Should return a class name based on the class's associated string ID.
     */
    protected static function getClassNameFromClassId($id)
    {
        return $id;
    }

    /**
     * Should return a message to use in an Exception when an invalid class ID is supplied to
     * {@link factory()}.
     */
    protected static function getInvalidClassIdExceptionMessage($id)
    {
        return "Invalid class ID '$id' for " . get_called_class() . "::factory().";
    }
}