Completed
Push — master ( 0277cb...57b1d6 )
by David
39s
created

ChimpifyCampaign::getCMSFields()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 77
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 77
ccs 0
cts 59
cp 0
rs 8.9342
cc 3
eloc 51
nc 4
nop 0
crap 12

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
use \DrewM\MailChimp\MailChimp;
4
5
class ChimpifyCampaign 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...
6
{
7
    private static $api_key;
0 ignored issues
show
Unused Code introduced by
The property $api_key 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
9
    private static $db = [
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...
10
        'Title' => 'Varchar',
11
        'FromName' => 'Varchar',
12
        'ReplyTo' => 'Varchar',
13
        'TemplateID' => 'Int',
14
        'Intro' => 'Text',
15
        'ItemLimit' => 'Int',
16
    ];
17
18
    private static $many_many = [
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 $many_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...
19
        'ContentSources' => 'Blog',
20
    ];
21
22
    private static $defaults = [
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 $defaults 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...
23
        'ItemLimit' => 3,
24
    ];
25
26
    private static $singular_name = 'MailChimp Campaign';
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...
27
28
    private static $plural_name = '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 $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...
29
30
    public function getCMSFields()
31
    {
32
        if (!$api_key = $this->config()->get('api_key')) {
33
            user_error(
34
                'Add a MailChimp API key to config (ChimpifyCampaign::api_key)',
35
                E_USER_ERROR
36
            );
37
        }
38
39
        $fields = parent::getCMSFields();
40
41
        $fields->removeByName('ItemLimit');
42
        $fields->removeByName('ContentSources');
43
44
        $mailChimp = new MailChimp($api_key);
45
46
        $fields->addFieldsToTab(
47
            'Root.Main',
48
            [
49
                TextField::create(
50
                    'Title',
51
                    _t('Chimpify.FieldLabelSubjectLine', 'Subject line')
52
                ),
53
                TextField::create(
54
                    'FromName',
55
                    _t('Chimpify.FieldLabelFromName', 'From name')
56
                ),
57
                EmailField::create(
58
                    'ReplyTo',
59
                    _t('Chimpify.FieldLabelReplyTo', 'Reply to email address')
60
                ),
61
                DropdownField::create(
62
                    'TemplateID',
63
                    _t('Chimpify.FieldLabelMailChimpTemplate', 'MailChimp template'),
64
                    $this->getMailChimpTemplates($mailChimp)->map('id', 'name'))
65
                    ->setEmptyString(
66
                        _t('Chimpify.FieldPlaceholderMailChimpTemplate', 'Select...')
67
                    ),
68
                TextareaField::create(
69
                    'Intro',
70
                    _t('Chimpify.FieldLabelIntro', 'Introduction'))
71
                    ->setDescription(_t(
72
                        'Chimpify.FieldDescriptionIntro',
73
                        'Dispayled above the list of Blog posts.'
74
                    )),
75
            ]
76
        );
77
78
        if ($this->ID) {
79
            $sourcesConfig = GridFieldConfig_RelationEditor::create();
80
            $sourcesConfig->removeComponentsByType('GridFieldEditButton');
81
            $sourcesConfig->removeComponentsByType('GridFieldAddNewButton');
82
83
            $fields->addFieldsToTab(
84
                'Root.Main',
85
                [
86
                    GridField::create(
87
                        'ContentSources',
88
                        _t('Chimpify.FieldLabelContentSources', 'Content sources'),
89
                        $this->ContentSources(),
0 ignored issues
show
Documentation Bug introduced by
The method ContentSources does not exist on object<ChimpifyCampaign>? 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...
90
                        $sourcesConfig
91
                    ),
92
                    NumericField::create(
93
                        'ItemLimit',
94
                        _t('Chimpify.FieldLabelItemLimit', 'Number of posts'))
95
                        ->setDescription(_t(
96
                            'Chimpify.FieldDescriptionItemLimit',
97
                            'The number of posts to display from each content source.'
98
                        )),
99
                ]
100
            );
101
        }
102
103
        $this->extend('updateCMSFields', $fields);
104
105
        return $fields;
106
    }
107
108
    public function getCMSActions()
109
    {
110
        $actions = parent::getCMSActions();
111
112
        $actions->push(
113
            FormAction::create(
114
                'doGenerateCampaign',
115
                _t('Chimpify.ButtonLabelGenerateCampaign', 'Create in MailChimp')
116
            )
117
        );
118
119
        $this->extend('updateCMSActions', $actions);
120
121
        return $actions;
122
    }
123
124
    public function getCMSValidator()
125
    {
126
        return new RequiredFields(
127
            'Title', 'FromName', 'ReplyTo', 'TemplateID', 'Intro', 'ItemLimit'
128
        );
129
    }
130
131
    /**
132
     * Fetches a list of email templates from MailChimp.
133
     *
134
     * @param MailChimp $mailChimp
135
     * @return ArrayList
136
     */
137 1
    public function getMailChimpTemplates($mailChimp)
138
    {
139 1
        $templates = ArrayList::create();
140 1
        $response = $mailChimp->get('templates');
141
142 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...
143 1
            $message = $response && array_key_exists($response['errors'])
144 1
                ? $response['errors'][0]['message']
145 1
                : 'Error connecting to MailChimp API';
146
147 1
            user_error($message, E_USER_ERROR);
148
        }
149
150 1
        foreach ($response['templates'] as $template) {
151 1
            if ($template['type'] == 'user') {
152 1
                $templates->push(ArrayData::create($template));
153 1
            }
154 1
        }
155
156 1
        $this->extend('updateMailChimpTemplates', $templates);
157
158 1
        return $templates;
159
    }
160
161
    /**
162
     * Generates HTML from ContentSources.
163
     *
164
     * @return String
165
     */
166
    public function getCampaignContent()
167
    {
168
        return $this->renderWith('ChimpifyCampaignContent')->Value;
169
    }
170
}
171