CategoryExtension::PrimaryImage()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 0
dl 0
loc 18
rs 10
1
<?php
2
3
namespace SilverCommerce\CatalogueFrontend\Extensions;
4
5
use SilverStripe\Assets\Image;
6
use SilverStripe\Forms\FieldList;
7
use SilverStripe\ORM\DataExtension;
8
use SilverStripe\AssetAdmin\Forms\UploadField;
9
use SilverCommerce\CatalogueAdmin\Helpers\Helper;
10
11
/**
12
 * Simple extension to category to add image support. This is mostly
13
 * for use in templates.
14
 * 
15
 * @package    CatalogueFrontend
16
 * @subpackage Extensions
17
 */
18
class CategoryExtension extends DataExtension
19
{
20
    private static $has_one = [
0 ignored issues
show
introduced by
The private property $has_one is not used, and could be removed.
Loading history...
21
        "Image" => Image::class
22
    ];
23
24
    private static $owns = [
0 ignored issues
show
introduced by
The private property $owns is not used, and could be removed.
Loading history...
25
        "Image"
26
    ];
27
28
    /**
29
     * Gets the main image to use for this category, this
30
     * can either be the selected image, an image from the
31
     * first product or the default "no-product" image.
32
     * 
33
     * @return Image
34
     */
35
    public function PrimaryImage()
36
    {
37
        // If we have associated an image, return it
38
        $image = $this->owner->Image();
39
40
        if ($image->exists()) {
41
            return $image;
42
        }
43
44
        // Next try and get a child product image
45
        $product = $this->owner->AllProducts()->first();
46
47
        if (!empty($product)) {
48
            return $product->PrimaryImage();
49
        }
50
51
        // Finally generate our no product image
52
        return Helper::generate_no_image();
53
    }
54
55
    /**
56
     * Add the image upload field to the admin fields.
57
     */
58
    public function updateCMSFields(FieldList $fields)
59
    {
60
        $fields->addFieldToTab(
61
            "Root.Main",
62
            UploadField::create("Image")
63
                ->setFolderName("categories")
64
        );
65
    }
66
}