Completed
Pull Request — master (#3)
by Nikola
32:48 queued 50s
created

WidgetManager::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
1
<?php
2
/**
3
 * This file is part of the Disqus Helper package.
4
 *
5
 * Copyright (c) Nikola Posa <[email protected]>
6
 *
7
 * For full copyright and license information, please refer to the LICENSE file,
8
 * located at the package root folder.
9
 */
10
11
namespace DisqusHelper\Widget;
12
13
use DisqusHelper\Exception\InvalidWidgetConfigurationException;
14
use DisqusHelper\Exception\InvalidWidgetException;
15
use DisqusHelper\Exception\WidgetNotFoundException;
16
17
class WidgetManager implements WidgetLocatorInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $widgets;
23
24
    private function __construct()
25
    {
26
    }
27
28
    public static function create(array $widgets) : WidgetManager
29
    {
30
        $widgetManager = new self();
31
32
        foreach ($widgets as $widgetId => $widget) {
33
            $widgetManager->registerWidget($widgetId, $widget);
34
        }
35
36
        return $widgetManager;
37
    }
38
39
    public static function createWithDefaultWidgets() : WidgetManager
40
    {
41
        return self::create([
42
            'thread' => ThreadWidget::class,
43
            'commentscount' => CommentsCountWidget::class,
44
        ]);
45
    }
46
47
    public function registerWidget(string $widgetId, $widget)
48
    {
49
        if (!($widget instanceof WidgetInterface || is_string($widget) || is_callable($widget))) {
50
            throw InvalidWidgetConfigurationException::forConfiguration($widgetId, $widget);
51
        }
52
53
        $widgetId = strtolower($widgetId);
54
55
        $this->widgets[$widgetId] = $widget;
56
    }
57
58
    public function has(string $widgetId) : bool
59
    {
60
        $widgetId = strtolower($widgetId);
61
62
        return isset($this->widgets[$widgetId]);
63
    }
64
65
    public function get(string $widgetId) : WidgetInterface
66
    {
67
        $widgetId = strtolower($widgetId);
68
69
        if (!isset($this->widgets[$widgetId])) {
70
            throw WidgetNotFoundException::forWidgetId($widgetId);
71
        }
72
73
        $widget = $this->createWidget($widgetId);
74
75
        if (!$widget instanceof WidgetInterface) {
76
            throw InvalidWidgetException::forWidget($widget);
77
        }
78
79
        return $widget;
80
    }
81
82
    protected function createWidget($widgetId)
83
    {
84
        $widget = $this->widgets[$widgetId];
85
86
        if (is_string($widget)) {
87
            return new $widget();
88
        }
89
90
        if (is_callable($widget)) {
91
            return $widget();
92
        }
93
94
        return $widget;
95
    }
96
}