EditTemplate::title()   F
last analyzed

Complexity

Conditions 22
Paths 1011

Size

Total Lines 76
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 22
eloc 45
nc 1011
nop 0
dl 0
loc 76
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Charcoal\Admin\Template\Object;
4
5
use Exception;
6
7
// From Pimple
8
use Pimple\Container;
9
10
// From 'charcoal-admin'
11
use Charcoal\Admin\AdminTemplate;
12
use Charcoal\Admin\Ui\DashboardContainerInterface;
13
use Charcoal\Admin\Ui\DashboardContainerTrait;
14
use Charcoal\Admin\Ui\ObjectContainerInterface;
15
use Charcoal\Admin\Ui\ObjectContainerTrait;
16
17
/**
18
 * Object Edit Template
19
 */
20
class EditTemplate extends AdminTemplate implements
21
    DashboardContainerInterface,
22
    ObjectContainerInterface
23
{
24
    use DashboardContainerTrait;
25
    use ObjectContainerTrait;
26
27
    /**
28
     * Retrieve the list of parameters to extract from the HTTP request.
29
     *
30
     * @return string[]
31
     */
32
    protected function validDataFromRequest()
33
    {
34
        return array_merge([
35
            'obj_type', 'obj_id'
36
        ], parent::validDataFromRequest());
37
    }
38
39
    /**
40
     * Retrieve the title of the page.
41
     *
42
     * @return \Charcoal\Translator\Translation
43
     */
44
    public function title()
45
    {
46
        if ($this->title === null) {
47
            $title = null;
48
49
            $translator = $this->translator();
50
51
            try {
52
                $config = $this->dashboardConfig();
53
            } catch (Exception $e) {
54
                $this->logger->error($e->getMessage());
55
                $config = [];
56
            }
57
58
            if (isset($config['title'])) {
59
                $title = $translator->translation($config['title']);
60
            } else {
61
                $obj      = $this->obj();
62
                $objId    = $this->objId();
63
                $objType  = $this->objType();
0 ignored issues
show
Unused Code introduced by
The assignment to $objType is dead and can be removed.
Loading history...
64
                $metadata = $obj->metadata();
65
66
                if (!$title && isset($metadata['admin']['forms'])) {
0 ignored issues
show
introduced by
$title is of type null, thus it always evaluated to false.
Loading history...
67
                    $adminMetadata = $metadata['admin'];
68
69
                    $formIdent = filter_input(INPUT_GET, 'form_ident', FILTER_SANITIZE_STRING);
70
                    if (!$formIdent) {
71
                        $formIdent = (isset($adminMetadata['default_form']) ? $adminMetadata['default_form'] : '');
72
                    }
73
74
                    if (isset($adminMetadata['forms'][$formIdent]['label'])) {
75
                        $title = $translator->translation($adminMetadata['forms'][$formIdent]['label']);
76
                    }
77
                }
78
79
                if ($objId) {
80
                    if (!$title && isset($metadata['labels']['edit_item'])) {
81
                        $title = $translator->translation($metadata['labels']['edit_item']);
82
                    }
83
84
                    if (!$title && isset($metadata['labels']['edit_model'])) {
85
                        $title = $translator->translation($metadata['labels']['edit_model']);
86
                    }
87
                } else {
88
                    if (!$title && isset($metadata['labels']['new_item'])) {
89
                        $title = $translator->translation($metadata['labels']['new_item']);
90
                    }
91
92
                    if (!$title && isset($metadata['labels']['new_model'])) {
93
                        $title = $translator->translation($metadata['labels']['new_model']);
94
                    }
95
                }
96
97
                if (!$title) {
98
                    $objType = (isset($metadata['labels']['singular_name'])
99
                                ? $translator->translation($metadata['labels']['singular_name'])
100
                                : null);
101
102
                    if ($objId) {
103
                        $title = $translator->translation('Edit: {{ objType }} #{{ id }}');
104
                    } else {
105
                        $title = $translator->translation('Create: {{ objType }}');
106
                    }
107
108
                    if ($objType) {
109
                        $title = strtr($title, [
0 ignored issues
show
Bug introduced by
It seems like $title can also be of type null; however, parameter $str of strtr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

109
                        $title = strtr(/** @scrutinizer ignore-type */ $title, [
Loading history...
110
                            '{{ objType }}' => $objType
111
                        ]);
112
                    }
113
                }
114
            }
115
116
            $this->title = $this->renderTitle($title);
117
        }
118
119
        return $this->title;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->title also could return the type string which is incompatible with the documented return type Charcoal\Translator\Translation.
Loading history...
120
    }
121
122
    /**
123
     * Retrieve the page's sub-title.
124
     *
125
     * @return Translation|string|null
0 ignored issues
show
Bug introduced by
The type Charcoal\Admin\Template\Object\Translation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
126
     */
127
    public function subtitle()
128
    {
129
        if ($this->subtitle === null) {
130
            try {
131
                $config = $this->dashboardConfig();
132
            } catch (Exception $e) {
133
                $this->logger->error($e->getMessage());
134
                $config = [];
135
            }
136
137
            if (isset($config['subtitle'])) {
138
                $title = $this->translator()->translation($config['subtitle']);
139
            } else {
140
                $title = '';
141
            }
142
143
            $this->subtitle = $this->renderTitle($title);
144
        }
145
146
        return $this->subtitle;
147
    }
148
149
    /**
150
     * @param Container $container DI container.
151
     * @return void
152
     */
153
    protected function setDependencies(Container $container)
154
    {
155
        parent::setDependencies($container);
156
157
        // Required ObjectContainerInterface dependencies
158
        $this->setModelFactory($container['model/factory']);
159
160
        // Required dependencies.
161
        $this->dashboardBuilder = $container['dashboard/builder'];
162
    }
163
164
    /**
165
     * @throws Exception If the object's dashboard config can not be loaded.
166
     * @return array
167
     */
168
    protected function createDashboardConfig()
169
    {
170
        $adminMetadata  = $this->objAdminMetadata();
171
        $dashboardIdent = $this->dashboardIdent();
172
173
        if (empty($dashboardIdent)) {
174
            $dashboardIdent = filter_input(INPUT_GET, 'dashboard_ident', FILTER_SANITIZE_STRING);
175
        }
176
177
        if (empty($dashboardIdent)) {
178
            if (!$this->objId()) {
179
                if (!isset($adminMetadata['default_create_dashboard'])) {
180
                    throw new Exception(sprintf(
181
                        'No default create dashboard defined in admin metadata for %s',
182
                        get_class($this->obj())
183
                    ));
184
                }
185
186
                $dashboardIdent = $adminMetadata['default_create_dashboard'];
187
            } else {
188
                if (!isset($adminMetadata['default_edit_dashboard'])) {
189
                    throw new Exception(sprintf(
190
                        'No default edit dashboard defined in admin metadata for %s',
191
                        get_class($this->obj())
192
                    ));
193
                }
194
195
                $dashboardIdent = $adminMetadata['default_edit_dashboard'];
196
            }
197
        }
198
199
        if (!isset($adminMetadata['dashboards']) || !isset($adminMetadata['dashboards'][$dashboardIdent])) {
200
            throw new Exception(
201
                'Dashboard config is not defined.'
202
            );
203
        }
204
205
        $dashboardConfig = $adminMetadata['dashboards'][$dashboardIdent];
206
207
        return $dashboardConfig;
208
    }
209
210
    /**
211
     * Retrieve the page's sub-title.
212
     *
213
     * @param  mixed $title The title to render.
214
     * @return string|null
215
     */
216
    protected function renderTitle($title)
217
    {
218
        $obj = $this->obj();
219
        if ($obj->view()) {
0 ignored issues
show
Bug introduced by
The method view() does not exist on Charcoal\Model\ModelInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Charcoal\Queue\QueueItemInterface or Charcoal\Object\ContentInterface or Charcoal\Object\UserDataInterface or Charcoal\User\UserInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

219
        if ($obj->/** @scrutinizer ignore-call */ view()) {
Loading history...
220
            return $obj->render((string)$title, $obj);
0 ignored issues
show
Bug introduced by
The method render() does not exist on Charcoal\Model\ModelInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Charcoal\Queue\QueueItemInterface or Charcoal\Object\ContentInterface or Charcoal\Object\UserDataInterface or Charcoal\User\UserInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

220
            return $obj->/** @scrutinizer ignore-call */ render((string)$title, $obj);
Loading history...
221
        } else {
222
            return (string)$title;
223
        }
224
    }
225
226
    /**
227
     * @throws Exception If the object's admin metadata is not set.
228
     * @return \ArrayAccess
229
     */
230
    private function objAdminMetadata()
231
    {
232
        $obj = $this->obj();
233
234
        $objMetadata = $obj->metadata();
235
236
        $adminMetadata = isset($objMetadata['admin']) ? $objMetadata['admin'] : null;
237
        if ($adminMetadata === null) {
238
            throw new Exception(sprintf(
239
                'The object %s does not have an admin metadata.',
240
                get_class($obj)
241
            ));
242
        }
243
244
        return $adminMetadata;
245
    }
246
}
247