ContentImageBlock   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 187
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 8
dl 0
loc 187
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A singular_name() 0 3 1
A plural_name() 0 3 1
A getTemplateTypes() 0 13 4
A getTemplateType() 0 3 1
A getCMSFields() 0 21 1
A fieldLabels() 0 20 1
A getTemplateOptions() 0 17 3
A forTemplate() 0 9 2
A getFirstImage() 0 5 2
1
<?php
2
3
/**
4
 * @author    Donatas Navidonskis <[email protected]>
5
 * @since     2017
6
 * @class     ContentImageBlock
7
 *
8
 * @property string Template
9
 *
10
 * @method \DataList Images
11
 */
12
class ContentImageBlock extends BaseBlock {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
13
14
    /**
15
     * @var array
16
     * @config
17
     */
18
    private static $db = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
19
        'Template' => 'Enum(array(
20
            "BottomImageTopContent",
21
            "TopImageBottomContent",
22
            
23
            "LeftImageRightContentWrap",
24
            "LeftBiggerImageRightContentWrap",
25
            "RightImageLeftContentWrap",
26
            "RightBiggerImageLeftContentWrap",
27
28
            "LeftImageRightContent",
29
            "LeftBiggerImageRightContent",
30
            "RightImageLeftContent",
31
            "RightBiggerImageLeftContent",
32
33
            "BottomImageListTopContent",
34
            "TopImageListBottomContent",
35
36
            "FullWidthImageLeftContent"
37
        ), "LeftBiggerImageRightContent")',
38
    ];
39
40
    /**
41
     * @var array
42
     * @config
43
     */
44
    private static $many_many = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
45
        'Images' => 'Image',
46
    ];
47
48
    /**
49
     * @var array
50
     * @config
51
     */
52
    private static $many_many_extraFields = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $many_many_extraFields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
        'Images' => ['SortOrder' => 'Int'],
54
    ];
55
56
    /**
57
     * If the singular name is set in a private static $singular_name, it cannot be changed using the translation files
58
     * for some reason. Fix it by defining a method that handles the translation.
59
     * @return string
60
     */
61
    public function singular_name() {
62
        return _t('ContentImageBlock.SINGULARNAME', 'Content Image Block');
63
    }
64
65
    /**
66
     * If the plural name is set in a private static $plural_name, it cannot be changed using the translation files
67
     * for some reason. Fix it by defining a method that handles the translation.
68
     * @return string
69
     */
70
    public function plural_name() {
71
        return _t('ContentImageBlock.PLURALNAME', 'Content Image Blocks');
72
    }
73
74
    /**
75
     * Get template types as lowercase and dashed string.
76
     *
77
     * @param string $currentType
78
     *
79
     * @return array|string
80
     */
81
    public function getTemplateTypes($currentType = null) {
82
        $templates = (array) $this->dbObject('Template')->enumValues();
83
        $types = [];
84
        $fileSource = sprintf('%s/assets/images/content-image-block', CONTENT_BLOCKS_DIR);
85
86
        foreach ($templates as $type) {
87
            $types[$type] = sprintf('%s/%s.png', $fileSource, str_replace(' ', '-', strtolower(\FormField::name_to_label($type))));
88
        }
89
90
        $this->extend('updateTemplateTypes', $types);
91
92
        return $currentType !== null && array_key_exists($currentType, $types) ? $types[$currentType] : $types;
93
    }
94
95
    /**
96
     * Get current template type as lowercase and dashed string.
97
     *
98
     * @return string
99
     */
100
    public function getTemplateType() {
101
        return $this->getTemplateTypes($this->Template);
102
    }
103
104
    /**
105
     * @return \FieldList
106
     */
107
    public function getCMSFields() {
108
        $fields = parent::getCMSFields();
109
        $fields->removeByName(['Template', 'Images']);
110
111
        $fields->findOrMakeTab('Root.Template', $this->fieldLabel('Template'));
112
        $fields->findOrMakeTab('Root.Images', $this->fieldLabel('Images'));
113
114
        $fields->addFieldsToTab('Root.Template', [
115
            \OptionsetField::create('Template', $this->fieldLabel('ChooseTemplate'), $this->getTemplateOptions(), $this->Template)->addExtraClass('content-image-block-cms'),
116
        ]);
117
118
        $fields->addFieldsToTab('Root.Images', [
119
            \SortableUploadField::create('Images', $this->fieldLabel('Images'))
120
                                ->setAllowedFileCategories('image')
121
                                ->setFolderName($this->getUploadDirectory()),
122
        ]);
123
124
        $this->extend('updateCMSFields', $fields);
125
126
        return $fields;
127
    }
128
129
    /**
130
     * @param bool $includeRelations
131
     *
132
     * @return array
133
     */
134
    public function fieldLabels($includeRelations = true) {
135
        return array_merge(parent::fieldLabels($includeRelations), [
136
            'Template'                        => _t("ContentImageBlock.TEMPLATE", "Template"),
137
            'Images'                          => _t("ContentImageBlock.IMAGES", "Images"),
138
            'ChooseTemplate'                  => _t("ContentImageBlock.CHOOSE_TEMPLATE", "Choose a template"),
139
            "BottomImageTopContent"           => _t("ContentImageBlock.BOTTOM_IMAGE_TOP_CONTENT", "Bottom image top content"),
140
            "TopImageBottomContent"           => _t("ContentImageBlock.TOP_IMAGE_BOTTOM_CONTENT", "Top image bottom content"),
141
            "LeftImageRightContentWrap"       => _t("ContentImageBlock.LEFT_IMAGE_RIGHT_CONTENT_WRAP", "Left image right content wrap"),
142
            "LeftBiggerImageRightContentWrap" => _t("ContentImageBlock.LEFT_BIGGER_IMAGE_RIGHT_CONTENT_WRAP", "Left bigger image right content wrap"),
143
            "RightImageLeftContentWrap"       => _t("ContentImageBlock.RIGHT_IMAGE_LEFT_CONTENT_WRAP", "Right image left content wrap"),
144
            "RightBiggerImageLeftContentWrap" => _t("ContentImageBlock.RIGHT_BIGGER_IMAGE_LEFT_CONTENT_WRAP", "Right bigger image left content wrap"),
145
            "LeftImageRightContent"           => _t("ContentImageBlock.LEFT_IMAGE_RIGHT_CONTENT", "Left image right content"),
146
            "LeftBiggerImageRightContent"     => _t("ContentImageBlock.LEFT_BIGGER_IMAGE_RIGHT_CONTENT", "Left bigger image right content"),
147
            "RightImageLeftContent"           => _t("ContentImageBlock.RIGHT_IMAGE_LEFT_CONTENT", "Right image left content"),
148
            "RightBiggerImageLeftContent"     => _t("ContentImageBlock.RIGHT_BIGGER_IMAGE_LEFT_CONTENT", "Right bigger image left content"),
149
            "BottomImageListTopContent"       => _t("ContentImageBlock.BOTTOM_IMAGE_LIST_TOP_CONTENT", "Bottom image list top content"),
150
            "TopImageListBottomContent"       => _t("ContentImageBlock.TOP_IMAGE_LIST_BOTTOM_CONTENT", "Top image list bottom content"),
151
            "FullWidthImageLeftContent"       => _t("ContentImageBlock.FULL_WIDTH_IMAGE_LEFT_CONTENT", "Full width image left content"),
152
        ]);
153
    }
154
155
    /**
156
     * @return array
157
     */
158
    protected function getTemplateOptions() {
159
        $options = [];
160
161
        foreach ($this->getTemplateTypes() as $type => $fileName) {
0 ignored issues
show
Bug introduced by
The expression $this->getTemplateTypes() of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
162
            if (\Director::fileExists($fileName)) {
163
                $thumbnail = "<img src=\"{$fileName}\" title=\"{$this->fieldLabel($type)}\" class=\"content-image-block-cms__thumbnail--picture\" />";
164
                $content = "<div class=\"content-image-block-cms__thumbnail\">{$thumbnail}</div>";
165
                $content .= "<p class=\"content-image-block-cms__thumbnail--right-title\">{$this->fieldLabel($type)}</p>";
166
167
                $options[$type] = \DBField::create_field("HTMLText", $content);
168
            }
169
        }
170
171
        $this->extend('updateTemplateOptions', $options);
172
173
        return $options;
174
    }
175
176
    /**
177
     * @return \HTMLText
178
     */
179
    public function forTemplate() {
180
        if (BaseBlock::config()->default_styles) {
181
            \Requirements::css(sprintf('%s/assets/styles/app.css', CONTENT_BLOCKS_DIR));
182
        }
183
184
        return $this->renderWith($this->ClassName, [
185
            'Layout' => $this->renderWith("{$this->ClassName}_{$this->Template}"),
186
        ]);
187
    }
188
189
    /**
190
     * @return bool|\Image
191
     */
192
    public function getFirstImage() {
193
        $image = $this->Images()->sort('SortOrder', 'ASC')->first();
0 ignored issues
show
Documentation Bug introduced by
The method Images does not exist on object<ContentImageBlock>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
194
195
        return $image instanceof Image ? $image : false;
196
    }
197
198
}