Completed
Push — master ( 80bbdc...57b200 )
by Donata
02:28
created

ContentImageBlock::getCMSFields()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 1
eloc 17
nc 1
nop 0
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
        $fields->findOrMakeTab('Root.Template', $this->fieldLabel('Template'));
111
        $fields->findOrMakeTab('Root.Images', $this->fieldLabel('Images'));
112
113
        $fields->addFieldsToTab('Root.Template', [
114
            \OptionsetField::create('Template', $this->fieldLabel('ChooseTemplate'), $this->getTemplateOptions(), $this->Template)->addExtraClass('content-image-block-cms'),
115
        ]);
116
117
        $fields->addFieldsToTab('Root.Images', [
118
            \SortableUploadField::create('Images', $this->fieldLabel('Images'))
119
                                ->setAllowedFileCategories('image')
120
                                ->setFolderName($this->getUploadDirectory()),
121
        ]);
122
123
        $fields->addFieldToTab(
124
            'Root.Main',
125
            $fields->dataFieldByName('ExtraClass'),
126
            'Content'
127
        );
128
129
        $this->extend('updateCMSFields', $fields);
130
131
        return $fields;
132
    }
133
134
    /**
135
     * @param bool $includeRelations
136
     *
137
     * @return array
138
     */
139
    public function fieldLabels($includeRelations = true) {
140
        return array_merge(parent::fieldLabels($includeRelations), [
141
            'Template'                        => _t("ContentImageBlock.TEMPLATE", "Template"),
142
            'Images'                          => _t("ContentImageBlock.IMAGES", "Images"),
143
            'ChooseTemplate'                  => _t("ContentImageBlock.CHOOSE_TEMPLATE", "Choose a template"),
144
            "BottomImageTopContent"           => _t("ContentImageBlock.BOTTOM_IMAGE_TOP_CONTENT", "Bottom image top content"),
145
            "TopImageBottomContent"           => _t("ContentImageBlock.TOP_IMAGE_BOTTOM_CONTENT", "Top image bottom content"),
146
            "LeftImageRightContentWrap"       => _t("ContentImageBlock.LEFT_IMAGE_RIGHT_CONTENT_WRAP", "Left image right content wrap"),
147
            "LeftBiggerImageRightContentWrap" => _t("ContentImageBlock.LEFT_BIGGER_IMAGE_RIGHT_CONTENT_WRAP", "Left bigger image right content wrap"),
148
            "RightImageLeftContentWrap"       => _t("ContentImageBlock.RIGHT_IMAGE_LEFT_CONTENT_WRAP", "Right image left content wrap"),
149
            "RightBiggerImageLeftContentWrap" => _t("ContentImageBlock.RIGHT_BIGGER_IMAGE_LEFT_CONTENT_WRAP", "Right bigger image left content wrap"),
150
            "LeftImageRightContent"           => _t("ContentImageBlock.LEFT_IMAGE_RIGHT_CONTENT", "Left image right content"),
151
            "LeftBiggerImageRightContent"     => _t("ContentImageBlock.LEFT_BIGGER_IMAGE_RIGHT_CONTENT", "Left bigger image right content"),
152
            "RightImageLeftContent"           => _t("ContentImageBlock.RIGHT_IMAGE_LEFT_CONTENT", "Right image left content"),
153
            "RightBiggerImageLeftContent"     => _t("ContentImageBlock.RIGHT_BIGGER_IMAGE_LEFT_CONTENT", "Right bigger image left content"),
154
            "BottomImageListTopContent"       => _t("ContentImageBlock.BOTTOM_IMAGE_LIST_TOP_CONTENT", "Bottom image list top content"),
155
            "TopImageListBottomContent"       => _t("ContentImageBlock.TOP_IMAGE_LIST_BOTTOM_CONTENT", "Top image list bottom content"),
156
            "FullWidthImageLeftContent"       => _t("ContentImageBlock.FULL_WIDTH_IMAGE_LEFT_CONTENT", "Full width image left content"),
157
        ]);
158
    }
159
160
    /**
161
     * @return array
162
     */
163
    protected function getTemplateOptions() {
164
        $options = [];
165
166
        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...
167
            if (\Director::fileExists($fileName)) {
168
                $thumbnail = "<img src=\"{$fileName}\" title=\"{$this->fieldLabel($type)}\" class=\"content-image-block-cms__thumbnail--picture\" />";
169
                $content = "<div class=\"content-image-block-cms__thumbnail\">{$thumbnail}</div>";
170
                $content .= "<p class=\"content-image-block-cms__thumbnail--right-title\">{$this->fieldLabel($type)}</p>";
171
172
                $options[$type] = \DBField::create_field("HTMLText", $content);
173
            }
174
        }
175
176
        $this->extend('updateTemplateOptions', $options);
177
178
        return $options;
179
    }
180
181
    /**
182
     * @return \HTMLText
183
     */
184
    public function forTemplate() {
185
        if (BaseBlock::config()->default_styles) {
186
            \Requirements::css(sprintf('%s/assets/styles/app.css', CONTENT_BLOCKS_DIR));
187
        }
188
189
        return $this->renderWith($this->ClassName, [
190
            'Layout' => $this->renderWith("{$this->ClassName}_{$this->Template}"),
191
        ]);
192
    }
193
194
    /**
195
     * @return bool|\Image
196
     */
197
    public function getFirstImage() {
198
        $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...
199
200
        return $image instanceof Image ? $image : false;
201
    }
202
203
}