EmailAFriendForm   B
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 170
Duplicated Lines 3.53 %

Coupling/Cohesion

Components 1
Dependencies 18

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 18
dl 6
loc 170
rs 7.3333
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 30 3
F sendemailafriend() 6 100 21

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
class EmailAFriendForm extends Form
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...
4
{
5
6
    /**
7
     * @var String
8
     */
9
    private static $friend_email_address_label = "Friend#039;s Email Address";
0 ignored issues
show
Unused Code introduced by
The property $friend_email_address_label 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...
10
11
    /**
12
     * @var String
13
     */
14
    private static $message_label = "Message";
0 ignored issues
show
Unused Code introduced by
The property $message_label 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
16
    /**
17
     * @var String
18
     */
19
    private static $your_email_address_label = "Your email address";
0 ignored issues
show
Unused Code introduced by
The property $your_email_address_label 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...
20
21
    /**
22
     * @var String
23
     */
24
    private static $send_label = 'Send';
0 ignored issues
show
Unused Code introduced by
The property $send_label 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...
25
26
    /**
27
     * yes or no
28
     * @var String
29
     */
30
    private static $mail_to_site_owner_only = 'no';
0 ignored issues
show
Unused Code introduced by
The property $mail_to_site_owner_only 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...
31
32
    /**
33
     * @param Controller $controller
34
     * @param String $name
35
     */
36
    public function __construct($controller, $name)
37
    {
38
        Requirements::themedCSS("EmailReferral", "emailreferral");
39
        Requirements::javascript(THIRDPARTY_DIR."/jquery/jquery.js");
40
        Requirements::javascript("emailreferral/javascript/EmailReferralForm.js");
41
42
        $fields[] = new HiddenField('PageID', 'PageID', $controller->dataRecord->ID);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fields was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fields = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
43
44
        $fields[] = new EmailField('YourMailAddress', $this->Config()->get("your_email_address_label"));
45
        $fields[] = new TextareaField(
46
            'Message',
47
            $this->Config()->get("message_label"),
48
            $this->Config()->get("EmailAFriendExtension", "default_message")
49
        );
50
        if ($this->Config()->get("mail_to_site_owner_only") != 'yes') {
51
            $fields[] = new LiteralField('AdditionalMessage', '<div id="additionalMessageStuff"><p>'.Director::absoluteURL($controller->Link()).'</p><p>Sent by: <span id="emailReplacer">[your email address]</span></p></div>');
52
            $fields[] = new EmailField('To', $this->Config()->get("friend_email_address_label"));
53
        }
54
55
        $fields = new FieldList($fields);
56
57
        $actions = new FieldList(new FormAction('sendemailafriend', $this->Config()->get("send_label")));
58
        if ($this->Config()->get("mail_to_site_owner_only") != 'yes') {
59
            $requiredFields = new RequiredFields(array('YourMailAddress', 'To', 'Message'));
60
        } else {
61
            $requiredFields = new RequiredFields(array('YourMailAddress', 'Message'));
62
        }
63
64
        parent::__construct($controller, $name, $fields, $actions, $requiredFields);
65
    }
66
67
    /**
68
     *
69
     * @param Array
70
     * @param EmailAFriendForm
71
     */
72
    public function sendemailafriend($RAW_data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
73
    {
74
        $adminEmail = Config::inst()->get("Email", "admin_email");
75
        $data = Convert::raw2sql($RAW_data);
76
        if ($page = Page::get()->byID(intval($data['PageID']))) {
77
            $pageLink = $page->AbsoluteLink();
78
        }
79
        $toList = array();
80
        if ($this->Config()->get("mail_to_site_owner_only") != 'yes') {
81
            $tos = explode(',', $data['To']);
82
            foreach ($tos as $to) {
83
                $toList = array_merge($toList, explode(';', $to));
84
            }
85
        } else {
86
            $toList[] = $adminEmail;
87
        }
88
        if ($data['YourMailAddress']) {
89
            $toList[] = $data['YourMailAddress'];
90
        }
91
        $ip = EmailAFriendExtension::get_ip_user();
92
        $count = 0;
93
        if ($this->Config()->get("EmailAFriendExtension", "max_message_phour_pip")) {
94
            $anHourAgo = date('Y-m-d H:i:s', mktime(date('G') - 1, date('i'), date('s'), date('n'), date('j'), date('Y')));
95
            $count = FriendEmail::get()->filter(
96
                array(
97
                    "IPAddress" => $ip,
98
                    "Created:GreaterThan" => $anHourAgo
99
                )
100
            )->count();
101
        }
102
        if ($this->Config()->get("mail_to_site_owner_only") != 'yes') {
103
            $mailFrom = $data['YourMailAddress'];
104
        } else {
105
            if ($this->Config()->get("EmailAFriendExtension", "sender_name")) {
106
                $mailFrom = $this->Config()->get("EmailAFriendExtension", "sender_name");
107
                if ($this->Config()->get("EmailAFriendRole", "sender_email_address")) {
108
                    $mailFrom .= ' <' . $this->Config()->get("EmailAFriendExtension", "sender_email_address") . '>';
109
                }
110
            } elseif ($this->Config()->get("EmailAFriendExtension", "sender_email_address")) {
111
                $mailFrom = $this->Config()->get("EmailAFriendExtension", "sender_email_address");
112
            } else {
113
                $mailFrom = $adminEmail;
114
            }
115
        }
116
        foreach ($toList as $index => $to) {
117
            $messagesPerHour = $this->Config()->get("EmailAFriendExtension", "max_message_phour_pip");
118
            if ($messagesPerHour && $count > $messagesPerHour) {
119
                $stopIndex = $index;
120
                break;
121
            } else {
122
                $friendEmail = new FriendEmail();
123
                $friendEmail->To = $to;
0 ignored issues
show
Documentation introduced by
The property To does not exist on object<FriendEmail>. 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...
124
                $friendEmail->Message = $data['Message'];
0 ignored issues
show
Documentation introduced by
The property Message does not exist on object<FriendEmail>. 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...
125
                $friendEmail->From = $data['YourMailAddress'];
0 ignored issues
show
Documentation introduced by
The property From does not exist on object<FriendEmail>. 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...
126
                $friendEmail->IPAddress = $ip;
0 ignored issues
show
Documentation introduced by
The property IPAddress does not exist on object<FriendEmail>. 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...
127
                $friendEmail->PageID = $data['PageID'];
0 ignored issues
show
Documentation introduced by
The property PageID does not exist on object<FriendEmail>. 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...
128
                $friendEmail->write();
129
                $subject = $this->Config()->get("EmailAFriendExtension", "mail_subject");
130
                $subject .= ' | sent by '.$data['YourMailAddress'];
131
                $email = new Email(
132
                    $mailFrom,
133
                    $to,
134
                    $subject,
135
                    Convert::raw2xml($data['Message']) . '<br/><br/>Page Link : ' . $pageLink. '<br /><br />Sent by: '.$data['YourMailAddress']
0 ignored issues
show
Bug introduced by
The variable $pageLink 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...
136
                );
137
                $outcome = $email->send();
138
                if ($outcome) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $outcome of type string[] 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...
139
                    $count++;
140
                } else {
141
                    unset($toList[$index]);
142
                }
143
            }
144
        }
145
146
        if (count($toList) > 0) {
147
            $content = '';
148
            $endIndex = isset($stopIndex) ? $stopIndex : count($toList);
149
            if (! isset($stopIndex) || $stopIndex > 0) {
150
                $content .= '<p class="message good">This page has been successfully e-mailed to the following addresses :</p><ul>';
151 View Code Duplication
                for ($i = 0; $i < $endIndex; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
152
                    $content .= '<li>' . $toList[$i] . '</li>';
153
                }
154
                $content .= '</ul>';
155
            }
156
            if ($endIndex < count($toList)) {
157
                $content .= '<p class="message required">This page could not be e-mailed to the following addresses :</p><ul>';
158 View Code Duplication
                for ($i = $endIndex; $i < count($toList); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
159
                    $content .= '<li>' . $toList[$i] . '</li>';
160
                }
161
                $content .= '</ul>';
162
            }
163
        } else {
164
            $content = '<p class="message required bad">This page has not been e-mailed to anyone.</p>';
165
        }
166
167
        $content .= '<br/><p><a href="' . $this->controller->Link() . '">Send more?</a>.</p>';
168
169
        $templateData = array("EmailAFriendForm" => null, "EmailAFriendThankYouContent" => $content);
170
        return $this->customise($templateData)->renderWith('EmailAFriendHolder');
171
    }
172
}
173