HasStaticAttributes_CheckboxSetField   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 20
c 2
b 0
f 1
lcom 1
cbo 1
dl 0
loc 93
ccs 0
cts 45
cp 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getAttributeTypeID() 0 5 2
A getFieldName() 0 5 2
C saveInto() 0 47 12
A setValue() 0 10 4
1
<?php
2
/**
3
 * Extension for Product that allows static attributes in the same way
4
 * they're used for variations. I'm separating this out because it will
5
 * probably be useful in other projects.
6
 *
7
 * @author Mark Guinn <[email protected]>
8
 * @date 01.21.2014
9
 * @package Daywind
10
 * @subpackage extensions
11
 */
12
class HasStaticAttributes extends DataExtension
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
    private static $many_many = array(
0 ignored issues
show
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...
15
        'StaticAttributeTypes'  => 'ProductAttributeType',
16
        'StaticAttributeValues' => 'ProductAttributeValue',
17
    );
18
19
20
    /**
21
     * Adds variations specific fields to the CMS.
22
     */
23
    public function updateCMSFields(FieldList $fields)
24
    {
25
        $fields->addFieldsToTab('Root.Attributes', array(
26
            HeaderField::create('Applicable Attribute Types'),
27
            CheckboxSetField::create('StaticAttributeTypes', 'Static Attribute Types', ProductAttributeType::get()->map("ID", "Title")),
28
            LiteralField::create('staticattributehelp', '<p>Select any attributes that apply to this product and click Save.</p>'),
29
            HeaderField::create('Attributes'),
30
        ));
31
32
        foreach ($this->owner->StaticAttributeTypes() as $type) {
33
            $source = $this->getValuesClosure($type->ID);
34
35
            $newValFields = FieldList::create(array(
36
                TextField::create('Value', 'Label'),
37
                HiddenField::create('TypeID', '', $type->ID),
38
            ));
39
40
            $newValReq = RequiredFields::create('Value');
41
42
            $valuesField = HasStaticAttributes_CheckboxSetField::create('StaticAttributeValues-'.$type->ID, $type->Title, $source());
43
            $valuesField->setValue($this->owner->StaticAttributeValues()->filter('TypeID', $type->ID)->getIDList());
44
            $valuesField->useAddNew('ProductAttributeValue', $source, $newValFields, $newValReq);
0 ignored issues
show
Documentation Bug introduced by
The method useAddNew does not exist on object<HasStaticAttributes_CheckboxSetField>? 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...
45
46
            $fields->addFieldToTab('Root.Attributes', $valuesField);
47
        }
48
    }
49
50
51
    /**
52
     * @param $typeID
53
     * @return callable
54
     */
55
    protected function getValuesClosure($typeID)
56
    {
57
        return function () use ($typeID) {
58
            return ProductAttributeValue::get()->filter('TypeID', $typeID)->map('ID', 'Value')->toArray();
59
        };
60
    }
61
62
63
    /**
64
     * @return ArrayList
65
     */
66
    public function StaticAttributes()
67
    {
68
        $list = array();
69
70
        foreach ($this->owner->StaticAttributeTypes() as $type) {
71
            $type->ActiveValues = new ArrayList();
72
            $list[$type->ID] = $type;
73
        }
74
75
        foreach ($this->owner->StaticAttributeValues() as $val) {
76
            if (!isset($list[$val->TypeID])) {
77
                continue;
78
            }
79
            $list[$val->TypeID]->ActiveValues->push($val);
80
        }
81
82
        return new ArrayList($list);
83
    }
84
85
86
    /**
87
     * Add the default attribute types if any
88
     */
89 8
    public function onBeforeWrite()
90
    {
91 8
        if (empty($this->owner->ID)) {
92 8
            $defaultAttributes = Config::inst()->get($this->owner->ClassName, 'default_attributes');
93 8
            if (!empty($defaultAttributes)) {
94
                $types = $this->owner->StaticAttributeTypes();
95
                foreach ($defaultAttributes as $typeID) {
0 ignored issues
show
Bug introduced by
The expression $defaultAttributes of type array|integer|double|string|boolean 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...
96
                    $types->add($typeID);
97
                }
98
            }
99 8
        }
100 8
    }
101
}
102
103
104
/**
105
 * This is needed because the checkboxsetfield doesn't have an easy
106
 * way to segment by TypeID. This is exactly the same except that
107
 * you set the name to StaticAttributeValues-<TypeID>.
108
 *
109
 * @class HasStaticAttributes_CheckboxSetField
110
 */
111
class HasStaticAttributes_CheckboxSetField extends CheckboxSetField
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
112
{
113
    /**
114
     * @return int
115
     */
116
    public function getAttributeTypeID()
117
    {
118
        $parts = explode('-', $this->name);
119
        return count($parts) > 1 ? $parts[1] : 0;
120
    }
121
122
123
    /**
124
     * @return string
125
     */
126
    public function getFieldName()
127
    {
128
        $parts = explode('-', $this->name);
129
        return count($parts) > 0 ? $parts[0] : '';
130
    }
131
132
133
    /**
134
     * Save the current value of this CheckboxSetField into a DataObject.
135
     * If the field it is saving to is a has_many or many_many relationship,
136
     * it is saved by setByIDList(), otherwise it creates a comma separated
137
     * list for a standard DB text/varchar field.
138
     *
139
     * @param DataObjectInterface $record The record to save into
140
     */
141
    public function saveInto(DataObjectInterface $record)
142
    {
143
        $fieldname  = $this->getFieldName();
144
        if (empty($fieldname)) {
145
            return;
146
        }
147
        $typeID     = $this->getAttributeTypeID();
148
        if (empty($typeID)) {
149
            return;
150
        }
151
        $relation   = $record->$fieldname();
152
        if (!$relation) {
153
            return;
154
        }
155
        $relation   = $relation->filter('TypeID', $typeID);
156
157
        // make a list of id's that should be there
158
        $idList = array();
159
        if (!empty($this->value) && is_array($this->value)) {
160
            foreach ($this->value as $id => $bool) {
161
                if ($bool) {
162
                    $idList[$id] = $id;
163
                }
164
            }
165
        }
166
167
        // look at the existing elements and add/subtract
168
        $toDelete = array();
169
        foreach ($relation as $rec) {
170
            if (isset($idList[$rec->ID])) {
171
                // don't try to add it twice
172
                unset($idList[$rec->ID]);
173
            } else {
174
                $toDelete[] = $rec->ID;
175
            }
176
        }
177
178
        // add
179
        foreach ($idList as $id) {
180
            $relation->add($id);
181
        }
182
183
        // remove
184
        foreach ($toDelete as $id) {
185
            $relation->removeByID($id);
186
        }
187
    }
188
189
190
    /**
191
     * Load a value into this CheckboxSetField
192
     */
193
    public function setValue($value, $obj = null)
194
    {
195
        if (!empty($value) && !is_array($value) && !empty($this->value)) {
196
            $this->value[] = $value;
197
        } else {
198
            parent::setValue($value, $obj);
199
        }
200
201
        return $this;
202
    }
203
}
204
205
206
//class HasStaticAttributes_ProductAttributeType extends DataExtension
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
207
//{
208
//
209
//}
210
//
211
//class HasStaticAttributes_ProductAttributeValue extends DataExtension
212
//{
213
//	public function getAddNewFields() {
214
//		return new FieldList(array(
215
//
216
//		));
217
//	}
218
//}
219
220