Completed
Pull Request — master (#24)
by Jason
13:57
created

updateCollectionItems()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 0
cts 15
cp 0
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 4
nop 2
crap 30
1
<?php
2
3
namespace Dynamic\ProductCatalog\ORM;
4
5
use Dynamic\ProductCatalog\Page\CatalogCategory;
6
use SilverStripe\Forms\DropdownField;
7
use SilverStripe\ORM\ArrayList;
8 2
use SilverStripe\ORM\DataExtension;
9
10 2
class ProductDocCollectionDataExtension extends DataExtension
11 2
{
12 2
    /**
13 2
     * @param $object
14
     */
15
    public function updateCollectionObject(&$object)
16
    {
17
        if ($class = $this->owner->data()->ManagedClass) {
18 1
            $object = (string) $class;
19
        }
20 1
    }
21 1
22 1
    /**
23 1
     * @param $form
24
     */
25 1
    public function updateCollectionForm(&$form)
26
    {
27 1
        $fields = $form->Fields();
28 1
29 1
        $fields->insertAfter(
30 1
            DropdownField::create('CategoryID', 'Category', CatalogCategory::get()->map())
31 1
                ->setEmptyString('All categories'),
32 1
            'Title'
33
        );
34
35
        $fields->insertAfter(
36
            DropdownField::create('Products__ID', 'Product', CatalogProduct::get()->map())
37
                ->setEmptyString('All products'),
38
            'CategoryID'
39
        );
40
41
        $fields->removeByName([
42
            'Name',
43
            'Title',
44
        ]);
45
    }
46
47
    /**
48
     * @param $collection
49
     * @param $searchCriteria
50
     */
51
    public function updateCollectionItems(&$collection, &$searchCriteria)
52
    {
53
        $class = $this->owner->data()->ManagedClass;
54
55
        if (isset($searchCriteria['CategoryID']) && $searchCriteria['CategoryID'] != '') {
56
            $category = CatalogCategory::get()->byID($searchCriteria['CategoryID']);
57
            $products = $category->Products();
58
            $docs = new ArrayList();
59
60
            foreach($products as $product) {
61
                $records = $class::get()->filter(['Products.ID' => $product->ID]);
62
                foreach ($records as $record) {
63
                    $docs->push($record);
64
                }
65
            }
66
67
            $collection = $docs;
68
        }
69
    }
70
}