CampaignMonitorCampaignStyle::onBeforeWrite()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
1
<?php
2
3
/**
4
 *@author nicolaas [at] sunnysideup.co.nz
5
 *
6
 *
7
 **/
8
9
class CampaignMonitorCampaignStyle extends DataObject
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
    private static $db = array(
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...
12
        "Title" => "Varchar(100)",
13
        "TemplateName" => "Varchar(200)",
14
        "CSSFiles" => "Text"
15
    );
16
17
    private static $indexes = array(
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 $indexes 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...
18
        "Title" => true
19
    );
20
21
    private static $has_many = array(
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 $has_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...
22
        "CampaignMonitorCampaigns" => "CampaignMonitorCampaign"
23
    );
24
25
    private static $searchable_fields = array(
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 $searchable_fields 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...
26
        "Title" => "PartialMatchFilter"
27
    );
28
29
    private static $summary_fields = array(
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 $summary_fields 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...
30
        "Title" => "Title"
31
    );
32
33
    private static $singular_name = "Campaign Template";
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 $singular_name 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...
34
35
    private static $plural_name = "Campaign Templates";
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 $plural_name 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...
36
37
    private static $default_template = "CampaignMonitorCampaign";
0 ignored issues
show
Unused Code introduced by
The property $default_template 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...
38
39
    public function getCMSFields()
40
    {
41
        $fields = parent::getCMSFields();
42
        $fields->addFieldToTab("Root.Debug", TextField::create("TemplateName"));
43
        $fields->addFieldToTab("Root.Debug", ReadonlyField::create("FileLocation"));
44
        $fields->addFieldToTab("Root.Debug", ReadonlyField::create("CSSFiles"));
45
        $fields->addFieldToTab("Root.Debug", ReadonlyField::create("CampaignMonitorCampaigns", "Used in ", implode(",", $this->CampaignMonitorCampaigns()->map()->toArray())));
0 ignored issues
show
Documentation Bug introduced by
The method CampaignMonitorCampaigns does not exist on object<CampaignMonitorCampaignStyle>? 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...
46
        $fields->removeFieldFromTab("Root", "CampaignMonitorCampaigns");
47
        return $fields;
48
    }
49
50
    public function canCreate($member = null)
51
    {
52
        return false;
53
    }
54
55
    /**
56
     * @return array
57
     */
58 View Code Duplication
    public function getFoldersToSearch()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
59
    {
60
        $array = array(
61
            Director::baseFolder() ."/".SSViewer::get_theme_folder()."_campaignmonitor/templates/Email/",
62
            Director::baseFolder()."/campaignmonitor/templates/Email/"
63
        );
64
        foreach ($array as $key => $folder) {
65
            if (!file_exists($folder)) {
66
                unset($array[$key]);
67
            }
68
        }
69
        return $array;
70
    }
71
72
    /**
73
     * @return array
74
     */
75 View Code Duplication
    public function getCSSFoldersToSearch()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
76
    {
77
        $array = array(
78
            Director::baseFolder() ."/".SSViewer::get_theme_folder()."_campaignmonitor/css/",
79
            Director::baseFolder()."/campaignmonitor/css/"
80
81
        );
82
        foreach ($array as $key => $folder) {
83
            if (!file_exists($folder)) {
84
                unset($array[$key]);
85
            }
86
        }
87
        return $array;
88
    }
89
90
    /**
91
     *
92
     * @return string | null
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
93
     */
94
    public function getFileLocation()
95
    {
96
        if (!$this->TemplateName) {
0 ignored issues
show
Documentation introduced by
The property TemplateName does not exist on object<CampaignMonitorCampaignStyle>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
97
            $this->TemplateName = "CampaignMonitorCampaign";
0 ignored issues
show
Documentation introduced by
The property TemplateName does not exist on object<CampaignMonitorCampaignStyle>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
98
        }
99
        foreach ($this->getFoldersToSearch() as $folder) {
100
            $fileLocation = $folder.$this->TemplateName.".ss";
0 ignored issues
show
Documentation introduced by
The property TemplateName does not exist on object<CampaignMonitorCampaignStyle>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
101
            if (file_exists($fileLocation)) {
102
                return $fileLocation;
103
            } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
104
                //just try the next one ...
105
            }
106
        }
107
        user_error("can not find template, last one tried: $fileLocation");
0 ignored issues
show
Bug introduced by
The variable $fileLocation does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
108
    }
109
110
    public function getCSSFiles()
111
    {
112
        return implode(", ", $this->getCSSFilesAsArray());
113
    }
114
115
    public function getCSSFilesAsArray()
116
    {
117
        $dom = new DOMDocument();
118
        $cssFiles = array();
119
        $fileLocation = $this->getFileLocation();
120
        if ($fileLocation) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $fileLocation of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
121
            @$dom->loadHTMLFile($fileLocation);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
122
            $linkTags = $dom->getElementsByTagName('link');
123
            foreach ($linkTags as $linkTag) {
124
                if (strtolower($linkTag->getAttribute("rel")) == "stylesheet") {
125
                    $file = Director::baseFolder()."/".$linkTag->getAttribute("href");
126
                    if (file_exists($file)) {
127
                        $cssFiles[$file] = $file;
128
                    } else {
129
                        user_error("can find css file $file");
130
                    }
131
                }
132
                // if $link_tag rel == stylesheet
133
                 //   get href value and load CSS
134
            }
135
        } else {
136
            user_error("Can not find template file");
137
        }
138
        if (count($cssFiles) == 0) {
139
            foreach ($this->getCSSFoldersToSearch() as $folder) {
140
                $file = $folder."CampaignMonitorCampaign.css";
141
                if (file_exists($file)) {
142
                    $cssFiles[$file] = $file;
143
                    break;
144
                }
145
            }
146
        }
147
        return $cssFiles;
148
    }
149
150
    public function requireDefaultRecords()
151
    {
152
        parent::requireDefaultRecords();
153
        $templates = array();
154
        foreach ($this->getFoldersToSearch() as $folder) {
155
            $finder = new SS_FileFinder();
156
            $finder->setOption('name_regex', '/^.*\.ss$/');
157
            $found = $finder->find($folder);
158
            foreach ($found as $key => $value) {
159
                $template = pathinfo($value);
160
                $templates[$template['filename']] = $template['filename'];
161
            }
162
        }
163
        foreach ($templates as $template) {
164
            $filter = array("TemplateName" => $template);
165
            $obj = CampaignMonitorCampaignStyle::get()->filter($filter)->first();
166
            if (!$obj) {
167
                $obj = CampaignMonitorCampaignStyle::create($filter+array("Title" => $template));
168
                $obj->write();
169
            }
170
        }
171
        $excludes = $obj = CampaignMonitorCampaignStyle::get()->exclude(array("TemplateName" => $templates));
0 ignored issues
show
Unused Code introduced by
$obj is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
172
        foreach ($excludes as $exclude) {
173
            $exclude->delete();
174
        }
175
    }
176
177
    public function onBeforeWrite()
178
    {
179
        parent::onBeforeWrite();
180
        if ($this->TemplateName == "CampaignMonitorCampaign") {
0 ignored issues
show
Documentation introduced by
The property TemplateName does not exist on object<CampaignMonitorCampaignStyle>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
181
            $this->Title = "Default Template";
0 ignored issues
show
Documentation introduced by
The property Title does not exist on object<CampaignMonitorCampaignStyle>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
182
        }
183
    }
184
}
185