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

NewsRoute::__invoke()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 49

Duplication

Lines 49
Ratio 100 %

Importance

Changes 0
Metric Value
dl 49
loc 49
rs 8.8016
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\NewsInterface;
25
26
/**
27
 * News Route Handler
28
 */
29 View Code Duplication
class NewsRoute 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 news entry matching the URI path.
42
     *
43
     * @var NewsInterface|RoutableInterface
44
     */
45
    private $news;
46
47
    /**
48
     * The news entry model.
49
     *
50
     * @var string
51
     */
52
    private $objType = 'charcoal/cms/news';
53
54
    /**
55
     * @param array $data Class depdendencies.
56
     */
57
    public function __construct(array $data)
58
    {
59
        parent::__construct($data);
60
        $this->path = ltrim($data['path'], '/');
61
    }
62
63
    /**
64
     * Determine if the URI path resolves to an object.
65
     *
66
     * @param  Container $container A DI (Pimple) container.
67
     * @return boolean
68
     */
69
    public function pathResolvable(Container $container)
70
    {
71
        $news = $this->loadNewsFromPath($container);
72
        return ($news instanceof NewsInterface) && $news->id();
73
    }
74
75
    /**
76
     * @param  Container         $container A DI (Pimple) container.
77
     * @param  RequestInterface  $request   A PSR-7 compatible Request instance.
78
     * @param  ResponseInterface $response  A PSR-7 compatible Response instance.
79
     * @return ResponseInterface
80
     */
81
    public function __invoke(
82
        Container $container,
83
        RequestInterface $request,
84
        ResponseInterface $response
85
    ) {
86
        $config = $this->config();
87
88
        $news = $this->loadNewsFromPath($container);
89
        if ($news === null) {
90
            return $response->withStatus(404);
91
        }
92
93
        $templateIdent      = (string)$news['templateIdent'];
94
        $templateController = (string)$news['templateIdent'];
95
96
        if (!$templateController) {
97
            $container['logger']->warning(sprintf(
98
                '[%s] Missing template controller on model [%s] for ID [%s]',
99
                get_class($this),
100
                get_class($news),
101
                $news['id']
102
            ));
103
            return $response->withStatus(500);
104
        }
105
106
        $templateFactory = $container['template/factory'];
107
108
        $template = $templateFactory->create($templateController);
109
        $template->init($request);
110
111
        // Set custom data from config.
112
        $template->setData($config['template_data']);
113
        $template->setNews($news);
114
115
        $templateContent = $container['view']->render($templateIdent, $template);
116
        if ($templateContent === $templateIdent || $templateContent === '') {
117
            $container['logger']->warning(sprintf(
118
                '[%s] Missing or bad template identifier on model [%s] for ID [%s]',
119
                get_class($this),
120
                get_class($news),
121
                $templateIdent
122
            ));
123
            return $response->withStatus(500);
124
        }
125
126
        $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...
127
128
        return $response;
129
    }
130
131
    /**
132
     * @todo   Add support for `@see setlocale()`; {@see GenericRoute::setLocale()}
133
     * @param  Container $container Pimple DI container.
134
     * @return NewsInterface|null
135
     */
136
    protected function loadNewsFromPath(Container $container)
137
    {
138
        if ($this->news === null) {
139
            $config  = $this->config();
140
            $objType = (isset($config['obj_type']) ? $config['obj_type'] : $this->objType);
141
142
            try {
143
                $model = $container['model/factory']->create($objType);
144
                $langs = $container['translator']->availableLocales();
145
                $lang  = $model->loadFromL10n('slug', $this->path, $langs);
146
147
                if ($lang) {
148
                    $container['translator']->setLocale($lang);
149
                }
150
151
                if ($model->id()) {
152
                    $this->news = $model;
153
                    return $model;
154
                }
155
            } catch (Exception $e) {
156
                $container['logger']->debug(sprintf(
157
                    '[%s] Unable to load model [%s] for path [%s]',
158
                    get_class($this),
159
                    get_class($model),
160
                    $this->path
161
                ));
162
            }
163
164
            $this->news = 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\News...ject\RoutableInterface> of property $news.

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...
165
        }
166
167
        return $this->news ?: null;
168
    }
169
}
170