ChimpifyRequestHandler   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 128
Duplicated Lines 5.47 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 14.29%

Importance

Changes 0
Metric Value
wmc 14
lcom 1
cbo 6
dl 7
loc 128
ccs 8
cts 56
cp 0.1429
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A ItemEditForm() 0 18 4
A handleMailChimpResponse() 7 14 4
A createCampaign() 0 13 1
A populateCampaignContent() 0 13 1
B doGenerateCampaign() 0 32 4

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
use \DrewM\MailChimp\MailChimp;
4
5
class ChimpifyAdmin extends ModelAdmin
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...
6
{
7
    private static $managed_models = [
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 $managed_models 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...
8
        'ChimpifyCampaign',
9
    ];
10
11
    private static $url_segment = 'mailchimp-campaigns';
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 $url_segment 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
13
    private static $menu_title = 'MailChimp Campaigns';
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 $menu_title 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...
14
15
    public function getEditForm($id = null, $fields = null)
16
    {
17
        $form = parent::getEditForm($id, $fields);
18
19
        $gridFieldName = $this->sanitiseClassName($this->modelClass);
20
        $gridFieldConfig = $form->Fields()->fieldByName($gridFieldName)->getConfig();
21
22
        $gridFieldConfig->removeComponentsByType('GridFieldPrintButton');
23
        $gridFieldConfig->removeComponentsByType('GridFieldExportButton');
24
        $gridFieldConfig
25
            ->getComponentByType('GridFieldAddNewButton')
26
            ->setButtonName(
27
                _t('Chimpify.ButtonLabelAddMailChimpCampaign', 'Add MailChimp Campaign')
28
            );
29
        $gridFieldConfig
30
            ->getComponentByType('GridFieldDetailForm')
31
            ->setItemRequestClass('ChimpifyRequestHandler');
32
33
        return $form;
34
    }
35
}
36
37
class ChimpifyRequestHandler extends GridFieldDetailForm_ItemRequest
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
38
{
39
    private static $allowed_actions = [
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 $allowed_actions 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...
40
        'edit',
41
        'view',
42
        'ItemEditForm'
43
    ];
44
45
    public function ItemEditForm()
46
    {
47
        $form = parent::ItemEditForm();
48
49
        if (!$this->record->ID) {
50
            return $form;
51
        }
52
53
        $formActions = $form->Actions();
54
55
        if ($actions = $this->record->getCMSActions()) {
56
            foreach ($actions as $action) {
57
                $formActions->push($action);
58
            }
59
        }
60
61
        return $form;
62
    }
63
64
    /**
65
     * Handles responses from the MailChimp API.
66
     *
67
     * @param MailChimp $mailChimp
68
     * @return Array
69
     */
70 1
    public function handleMailChimpResponse($mailChimp)
71
    {
72 1
        $response = $mailChimp->getLastResponse();
73
74 1 View Code Duplication
        if (!$mailChimp->success()) {
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...
75 1
            $message = $response && array_key_exists($response['errors'])
0 ignored issues
show
Bug Best Practice introduced by
The expression $response 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...
76 1
                ? $response['errors'][0]['message']
77 1
                : 'Error connecting to MailChimp API';
78
79 1
            user_error($message, E_USER_ERROR);
80
        }
81
82 1
        return Convert::json2array($response['body']);
83
    }
84
85
    /**
86
     * Creates a MailChimp campaign via the API.
87
     *
88
     * @param MailChimp $mailChimp
89
     * @return Array
90
     */
91
    public function createCampaign($mailChimp)
92
    {
93
        $mailChimp->post('campaigns', [
94
          'type' => 'regular',
95
          'settings' => [
96
            'subject_line' => $this->record->Title,
97
            'from_name' => $this->record->FromName,
98
            'reply_to' => $this->record->ReplyTo,
99
          ],
100
        ]);
101
102
        return $this->handleMailChimpResponse($mailChimp);
103
    }
104
105
    /**
106
     * Populates a MailChimp Campaign with Blog content via the API.
107
     *
108
     * @param MailChimp $mailChimp
109
     * @param Int $campaignID
110
     * @return Array
111
     */
112
    public function populateCampaignContent($mailChimp, $campaignID)
113
    {
114
        $mailChimp->put("campaigns/{$campaignID}/content", [
115
            'template' => [
116
                'id' => $this->record->TemplateID,
117
                'sections' => [
118
                    'chimpify' => $this->record->getCampaignContent(),
119
                ],
120
            ],
121
        ]);
122
123
        return $this->handleMailChimpResponse($mailChimp);
124
    }
125
126
    /**
127
     * Creates and populates a MailChimp Campaign with blog content via the API.
128
     *
129
     * @param Array $data
130
     * @param Form $form
131
     */
132
    public function doGenerateCampaign($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $data 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...
133
    {
134
        if (!$api_key = $this->record->config()->get('api_key')) {
135
            user_error(
136
                'Add a MailChimp API key to config (ChimpifyCampaign::api_key)',
137
                E_USER_ERROR
138
            );
139
        }
140
141
        $controller = $this->getToplevelController();
142
143
        if (!$this->record || !$this->record->canEdit()) {
144
            return $controller->httpError(403);
145
        }
146
147
        $form->validate();
148
149
        $mailChimp = new MailChimp($api_key);
150
151
        $response = $this->createCampaign($mailChimp);
152
        $response = $this->populateCampaignContent($mailChimp, $response['id']);
0 ignored issues
show
Unused Code introduced by
$response 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...
153
154
        $form->sessionMessage(
155
            _t(
156
                'Chimpify.MessageGenerateCampaignSuccess',
157
                'Successfully created MailChimp Campaign'
158
            ),
159
            'good'
160
        );
161
162
        return $controller->redirectBack();
163
    }
164
}
165