ImagePlaceHolderReplacer::add_image_to_replace()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 4
1
<?php
2
3
/**
4
 *@author nicolaas [at] sunnysideup.co.nz + toro[at] sunnysideup.co.nz
5
 *
6
 *
7
 **/
8
9
class ImagePlaceHolderReplacer extends DataObjectDecorator
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...
10
{
11
12
    //Notes e.g. "this image is shown on the homepage under products" - optional
13
    //CopyFromPath  -e .g. themes/mytheme/images/myImage.gif - optional
14
    protected static $images_to_replace = array();
15
    public static function get_images_to_replace()
16
    {
17
        return self::$images_to_replace;
18
    }
19
    public static function remove_image_to_replace($className, $fieldName)
20
    {
21
        unset(self::$images_to_replace[$className.'_'.$fieldName]);
22
    }
23
    public static function add_image_to_replace($className, $fieldName, $notes, $copyFromPath)
24
    {
25
        $key = $className.'_'.$fieldName;
26
        self::$images_to_replace[$key] = array(
27
                "ClassName" => $className,
28
                "FieldName" => $fieldName,
29
                "Notes" => $notes,
30
                "CopyFromPath" => $copyFromPath,
31
                "DBFieldName" => $key
32
            );
33
    }
34
    protected static $folder_name = "SampleImages";
35
    public static function get_folder_name()
36
    {
37
        return self::$folder_name;
38
    }
39
    public static function set_folder_name($v)
40
    {
41
        self::$folder_name = $v;
42
    }
43
44
45
    public function extraStatics()
46
    {
47
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
48
        DOES NOT WORK BECAUSE extraStatics runs before the settings are set...
49
        $hasOneArray = array();
50
        $fullArray = self::get_images_to_replace();
51
        if($fullArray) {
52
            foreach($fullArray as $key => $array) {
53
                $hasOneArray[$key] = "Image";
54
            }
55
56
            return array(
57
                'has_one' => $hasOneArray,
58
                "db" => array("TESTME")
59
            );
60
        }
61
        return array();
62
        */
63
    }
64
65
    public function updateCMSFields(FieldSet &$fields)
66
    {
67
        /*
0 ignored issues
show
Unused Code Comprehensibility introduced by
61% 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...
68
        $fullArray = self::get_images_to_replace();
69
        if($fullArray) {
70
            $folder = Folder::findOrMake(self::get_folder_name());
71
            if(!$folder) {
72
                $fields->addFieldToTab('Root.Main', new LiteralField('folderError'.self::get_folder_name(), '<p>Can not create folder for place holder images(/assets/'.self::get_folder_name().'), please contact your administrator.</p>'));
73
            }
74
            foreach($fullArray as $key => $array) {
75
                $fields->addFieldToTab('Root.Main', new ImageField($key."ID", "Place holder for $key ... ".$array["Notes"], $value = null, $form = null, $rightTitle = null, $folder->Name));
76
            }
77
        }
78
        */
79
        return $fields;
80
    }
81
    public function requireDefaultRecords()
0 ignored issues
show
Coding Style introduced by
requireDefaultRecords uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
82
    {
83
        parent::requireDefaultRecords();
84
        $bt = defined('DB::USE_ANSI_SQL') ? '"' : '`';
85
86
        $update = array();
87
        $siteConfig = DataObject::get_one('SiteConfig');
88
        $folder = Folder::findOrMake(self::get_folder_name());
89
        if ($siteConfig && $folder) {
90
            $fullArray = self::get_images_to_replace();
91
            //copying ....
92
            if ($fullArray) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fullArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
93
                foreach ($fullArray as $key => $array) {
94
                    $className = $array["ClassName"];
95
                    $fieldName = $array["FieldName"]."ID";
96
                    if (class_exists($className)) {
97
                        $dataObject = singleton($className);
98
                        $dbFieldName = $array["DBFieldName"];
99
                        $fileName = basename($array["CopyFromPath"]);
100
                        $fromLocationLong = Director::baseFolder().'/'.$array["CopyFromPath"];
101
                        $toLocationShort = "assets/".self::get_folder_name()."/{$fileName}";
102
                        $toLocationLong = Director::baseFolder().'/'.$toLocationShort;
103
                        $image = DataObject::get_one('Image', "Filename='$toLocationShort' AND ParentID = ".$folder->ID);
104
                        if (!$image) {
105
                            if (!file_exists($toLocationLong)) {
106
                                copy($fromLocationLong, $toLocationLong);
107
                            }
108
                            $image = new Image();
109
                            $image->ParentID = $folder->ID;
110
                            $image->FileName = $toLocationShort;
111
                            $image->setName($fileName);
112
                            $image->write();
113
                        } elseif (!$image && file_exists($toLocationLong)) {
114
                            debug::show("need to update files");
115
                        }
116
                        if ($image && $image->ID) {
117
                            if (!$siteConfig->$dbFieldName) {
118
                                $siteConfig->$dbFieldName = $image->ID;
119
                                $update[]= "created placeholder image for $key";
120
                            }
121
                            $updateSQL = " UPDATE {$bt}".$className."{$bt}";
122
                            if (isset($_GET["removeplaceholderimages"])) {
123
                                $setSQL = " SET {$bt}".$fieldName."{$bt} = 0";
124
                                $whereSQL = " WHERE {$bt}".$fieldName."{$bt}  = ".$image->ID;
125
                                DB::alteration_message("removing ".$className.".".$fieldName." placeholder images", 'deleted');
126
                            } else {
127
                                DB::alteration_message("adding ".$className.".".$fieldName." placeholder images", 'created');
128
                                $setSQL = " SET {$bt}".$fieldName."{$bt} = ".$image->ID;
129
                                if (!isset($_GET["forceplaceholder"])) {
130
                                    $whereSQL = " WHERE {$bt}".$fieldName."{$bt} IS NULL OR {$bt}".$fieldName."{$bt} = 0";
131
                                } else {
132
                                    $whereSQL = '';
133
                                }
134
                            }
135
                            $sql = $updateSQL.$setSQL.$whereSQL;
136
                            DB::query($sql);
137
                            $versioningPresent = false;
138
                            $array = $dataObject->stat('extensions');
139
                            if (is_array($array) && count($array)) {
140
                                if (in_array("Versioned('Stage', 'Live')", $array)) {
141
                                    $versioningPresent = true;
142
                                }
143
                            }
144
                            if ($dataObject->stat('versioning')) {
145
                                $versioningPresent = true;
146
                            }
147
                            if ($versioningPresent) {
148
                                $sql = str_replace("{$bt}$className{$bt}", "{$bt}{$className}_Live{$bt}", $sql);
149
                                DB::query($sql);
150
                            }
151
                        } else {
152
                            debug::show("could not create image!".print_r($array));
153
                        }
154
                    } else {
155
                        debug::show("bad classname reference ".$className);
156
                    }
157
                }
158
            }
159
            if (count($update)) {
160
                $siteConfig->write();
161
                DB::alteration_message($siteConfig->ClassName." created/updated: ".implode(" --- ", $update), 'created');
162
            }
163
        } elseif (!$folder) {
164
            debug::show("COULD NOT CREATE FOLDER: ".self::get_folder_name());
165
        }
166
    }
167
}
168