Completed
Pull Request — master (#10)
by Tomáš
04:50 queued 01:55
created

FormatterManager::buildBaseFormatContext()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 27
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 27
ccs 0
cts 23
cp 0
rs 8.439
c 0
b 0
f 0
cc 6
eloc 16
nc 9
nop 1
crap 42
1
<?php
2
3
/*
4
 * This file is a part of Sculpin.
5
 *
6
 * (c) Dragonfly Development Inc.
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Symplify\PHP7_Sculpin\Formatter;
13
14
use Dflydev\DotAccessConfiguration\Configuration;
15
use Symplify\PHP7_Sculpin\DataProvider\DataProviderManager;
16
use Symplify\PHP7_Sculpin\Source\SourceInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18
19
final class FormatterManager
20
{
21
    /**
22
     * @var EventDispatcherInterface
23
     */
24
    private $eventDispatcher;
25
26
    /**
27
     * @var Configuration
28
     */
29
    private $siteConfiguration;
30
31
    /**
32
     * @var DataProviderManager
33
     */
34
    private $dataProviderManager;
35
36
    /**
37
     * @var array
38
     */
39
    private $formatters = [];
40
41
    /**
42
     * @var string
43
     */
44
    private $defaultFormatter;
45
46
    public function __construct(
47
        EventDispatcherInterface $eventDispatcher,
48
        Configuration $siteConfiguration,
49
        DataProviderManager $dataProviderManager = null
50
    ) {
51
        $this->eventDispatcher = $eventDispatcher;
52
        $this->siteConfiguration = $siteConfiguration;
53
        $this->dataProviderManager = $dataProviderManager;
54
    }
55
56
    /**
57
     * @param mixed $context
58
     */
59
    private function buildBaseFormatContext($context) : Configuration
60
    {
61
        $baseContext = new Configuration([
62
            'site' => $this->siteConfiguration->export(),
63
            'page' => $context,
64
            'formatter' => $this->defaultFormatter,
65
            'converters' => [],
66
        ]);
67
68
        if (isset($context['url'])) {
69
            if ('/' === $context['url']) {
70
                $relativeUrl = '.';
71
            } else {
72
                $relativeUrl = rtrim(str_repeat('../', substr_count($context['url'], '/')), '/');
73
            }
74
75
            $baseContext->set('relative_root_url', $relativeUrl);
76
        }
77
78
        foreach ($this->dataProviderManager->dataProviders() as $name) {
79
            if (isset($context['use']) and in_array($name, $context['use'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
80
                $baseContext->set('data.'.$name, $this->dataProviderManager->dataProvider($name)->provideData());
81
            }
82
        }
83
84
        return $baseContext;
85
    }
86
87
    public function buildFormatContext(string $templateId, string $template, array $context) : FormatContext
88
    {
89
        $baseContext = $this->buildBaseFormatContext($context);
90
91
        foreach (['layout', 'formatter', 'converters'] as $key) {
92
            if (isset($context[$key])) {
93
                $baseContext->set($key, $context[$key]);
94
            }
95
        }
96
97
        return new FormatContext($templateId, $template, $baseContext->export());
98
    }
99
100
    public function registerFormatter(string $name, FormatterInterface $formatter)
101
    {
102
        $this->formatters[$name] = $formatter;
103
104
        if (null === $this->defaultFormatter) {
105
            $this->defaultFormatter = $name;
106
        }
107
    }
108
109
    public function formatter(string $name) : FormatterInterface
110
    {
111
        return $this->formatters[$name];
112
    }
113
114 View Code Duplication
    public function formatPage(string $templateId, string $template, array $context) : string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
115
    {
116
        $formatContext = $this->buildFormatContext($templateId, $template, $context);
117
118
        if (!$formatContext->formatter()) {
119
            return $template;
120
        }
121
122
        return $this->formatter($formatContext->formatter())->formatPage($formatContext);
123
    }
124
125
    public function formatSourcePage(SourceInterface $source) : string
126
    {
127
        return $this->formatPage(
128
            $source->sourceId(),
129
            $source->content(),
130
            $source->data()->export()
131
        );
132
    }
133
134 View Code Duplication
    public function formatBlocks(string $templateId, string $template = null, array $context) : array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
    {
136
        $formatContext = $this->buildFormatContext($templateId, $template, $context);
137
138
        if (!$formatContext->formatter()) {
139
            return ['content' => $template];
140
        }
141
142
        return $this->formatter($formatContext->formatter())->formatBlocks($formatContext);
143
    }
144
145
    public function formatSourceBlocks(SourceInterface $source) : array
146
    {
147
        return $this->formatBlocks(
148
            $source->sourceId(),
149
            $source->content(),
150
            $source->data()->export()
151
        );
152
    }
153
154
    public function defaultFormatter() : string
155
    {
156
        return $this->defaultFormatter;
157
    }
158
159
    /**
160
     * NOTE: This is a hack because Symfony DiC cannot handle passing Data Provider
161
     * Manager via constructor injection as some data providers might also rely
162
     * on formatter. Hurray for circular dependencies. :(.
163
     */
164
    public function setDataProviderManager(DataProviderManager $dataProviderManager)
165
    {
166
        $this->dataProviderManager = $dataProviderManager;
167
    }
168
}
169