Test Setup Failed
Push — master ( da4039...f0d7ef )
by Chauncey
14:28
created

SectionRoute::__invoke()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 50

Duplication

Lines 50
Ratio 100 %

Importance

Changes 0
Metric Value
dl 50
loc 50
rs 8.7797
c 0
b 0
f 0
cc 5
nc 4
nop 3
1
<?php
2
3
namespace Charcoal\Cms\Route;
4
5
use Exception;
6
7
// From Pimple
8
use Pimple\Container;
9
10
// From PSR-7
11
use Psr\Http\Message\RequestInterface;
12
use Psr\Http\Message\ResponseInterface;
13
14
// From 'charcoal-translator'
15
use Charcoal\Translator\TranslatorAwareTrait;
16
17
// From 'charcoal-app'
18
use Charcoal\App\Route\TemplateRoute;
19
20
// From 'charcoal-object'
21
use Charcoal\Object\RoutableInterface;
22
23
// From 'charcoal-cms'
24
use Charcoal\Cms\SectionInterface;
25
26
/**
27
 * Section Route Handler
28
 */
29 View Code Duplication
class SectionRoute extends TemplateRoute
0 ignored issues
show
Duplication introduced by
This class 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...
30
{
31
    use TranslatorAwareTrait;
32
33
    /**
34
     * URI path.
35
     *
36
     * @var string
37
     */
38
    private $path;
39
40
    /**
41
     * The section object matching the URI path.
42
     *
43
     * @var SectionInterface|RoutableInterface
44
     */
45
    private $section;
46
47
    /**
48
     * The section model.
49
     *
50
     * @var string
51
     */
52
    private $objType = 'charcoal/cms/section';
53
54
    /**
55
     * @param array $data Class depdendencies.
56
     */
57
    public function __construct(array $data)
58
    {
59
        parent::__construct($data);
60
61
        $this->path = ltrim($data['path'], '/');
62
    }
63
64
    /**
65
     * Determine if the URI path resolves to an object.
66
     *
67
     * @param  Container $container A DI (Pimple) container.
68
     * @return boolean
69
     */
70
    public function pathResolvable(Container $container)
71
    {
72
        $section = $this->loadSectionFromPath($container);
73
        return ($section instanceof SectionInterface) && $section->id();
74
    }
75
76
    /**
77
     * @param  Container         $container A DI (Pimple) container.
78
     * @param  RequestInterface  $request   A PSR-7 compatible Request instance.
79
     * @param  ResponseInterface $response  A PSR-7 compatible Response instance.
80
     * @return ResponseInterface
81
     */
82
    public function __invoke(
83
        Container $container,
84
        RequestInterface $request,
85
        ResponseInterface $response
86
    ) {
87
        $config = $this->config();
88
89
        $section = $this->loadSectionFromPath($container);
90
        if ($section === null) {
91
            return $response->withStatus(404);
92
        }
93
94
        $templateIdent      = (string)$section['templateIdent'];
95
        $templateController = (string)$section['templateIdent'];
96
97
        if (!$templateController) {
98
            $container['logger']->warning(sprintf(
99
                '[%s] Missing template controller on model [%s] for ID [%s]',
100
                get_class($this),
101
                get_class($section),
102
                $section['id']
103
            ));
104
            return $response->withStatus(500);
105
        }
106
107
        $templateFactory = $container['template/factory'];
108
        $templateFactory->setDefaultClass($config['default_controller']);
109
110
        $template = $templateFactory->create($templateController);
111
        $template->init($request);
112
113
        // Set custom data from config.
114
        $template->setData($config['template_data']);
115
        $template->setSection($section);
116
117
        $templateContent = $container['view']->render($templateIdent, $template);
118
        if ($templateContent === $templateIdent || $templateContent === '') {
119
            $container['logger']->warning(sprintf(
120
                '[%s] Missing or bad template identifier on model [%s] for ID [%s]',
121
                get_class($this),
122
                get_class($section),
123
                $templateIdent
124
            ));
125
            return $response->withStatus(500);
126
        }
127
128
        $response->write($templateContent);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Psr\Http\Message\ResponseInterface as the method write() does only exist in the following implementations of said interface: Slim\Http\Response.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
129
130
        return $response;
131
    }
132
133
    /**
134
     * @todo   Add support for `@see setlocale()`; {@see GenericRoute::setLocale()}
135
     * @param  Container $container Pimple DI container.
136
     * @return SectionInterface|null
137
     */
138
    protected function loadSectionFromPath(Container $container)
139
    {
140
        if ($this->section === null) {
141
            $config  = $this->config();
142
            $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
143
144
            try {
145
                $model = $container['model/factory']->create($objType);
146
                $langs = $container['translator']->availableLocales();
147
                $lang  = $model->loadFromL10n('slug', $this->path, $langs);
148
149
                if ($lang) {
150
                    $container['translator']->setLocale($lang);
151
                }
152
153
                if ($model->id()) {
154
                    $this->section = $model;
155
                    return $model;
156
                }
157
            } catch (Exception $e) {
158
                $container['logger']->debug(sprintf(
159
                    '[%s] Unable to load model [%s] for path [%s]',
160
                    get_class($this),
161
                    get_class($model),
162
                    $this->path
163
                ));
164
            }
165
166
            $this->section = false;
0 ignored issues
show
Documentation Bug introduced by
It seems like false of type false is incompatible with the declared type object<Charcoal\Cms\Sect...ject\RoutableInterface> of property $section.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
167
        }
168
169
        return $this->section ?: null;
170
    }
171
}
172