Passed
Pull Request — master (#13)
by Matthew
14:09
created

ShortURL::getLinkChanged()   A

Complexity

Conditions 6
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 19.1203

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 16
ccs 2
cts 7
cp 0.2857
crap 19.1203
rs 9.2222
1
<?php
2
3
namespace Dynamic\ShortURL\Model;
4
5
use PHPLicengine\Api\Api;
6
use PHPLicengine\Service\Bitlink;
7
use SilverStripe\Core\Config\Config;
8
use SilverStripe\Forms\FieldList;
9
use SilverStripe\Forms\ReadonlyField;
10
use SilverStripe\ORM\DataObject;
11
use SilverStripe\ORM\ValidationResult;
12
13
class ShortURL extends DataObject
14
{
15
    /**
16
     * @var string
17
     */
18
    private static $singular_name = 'Short URL';
0 ignored issues
show
introduced by
The private property $singular_name is not used, and could be removed.
Loading history...
19
20
    /**
21
     * @var string
22
     */
23
    private static $plural_name = 'Short URLs';
0 ignored issues
show
introduced by
The private property $plural_name is not used, and could be removed.
Loading history...
24
25
    /**
26
     * @var
27
     */
28
    private $bitly_token;
0 ignored issues
show
introduced by
The private property $bitly_token is not used, and could be removed.
Loading history...
29
30
    /**
31
     * @var array
32
     */
33
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
34
        'Title' => 'Varchar(255)',
35
        'URL' => 'Varchar(255)',
36
        'CampaignSource' => 'Varchar(255)',
37
        'CampaignMedium' => 'Varchar(255)',
38
        'CampaignName' => 'Varchar(255)',
39
        'CampaignTerm' => 'Varchar(255)',
40
        'CampaignContent' => 'Varchar(255)',
41
        'ShortURL' => 'Varchar(255)',
42
    ];
43
44
    /**
45
     * @var array
46
     */
47
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
48
        'Title',
49
        'URL',
50
        'ShortURL',
51
    ];
52
53
    /**
54
     * @var array
55
     */
56
    private static $searchable_fields = [
0 ignored issues
show
introduced by
The private property $searchable_fields is not used, and could be removed.
Loading history...
57
        'Title',
58
        'URL',
59
        'CampaignSource',
60
        'CampaignMedium',
61
        'CampaignName',
62
        'CampaignTerm',
63
        'CampaignContent',
64
        'ShortURL',
65
    ];
66
67
    /**
68
     * @var string
69
     */
70
    private static $table_name = 'ShortURL';
0 ignored issues
show
introduced by
The private property $table_name is not used, and could be removed.
Loading history...
71
72
    /**
73
     * @return FieldList
74 1
     */
75
    public function getCMSFields()
76 1
    {
77
        $fields = parent::getCMSFields();
78 1
79 1
        $fields->dataFieldByName('URL')
80
            ->setDescription('URL to shorten and tag');
81 1
82 1
        $fields->dataFieldByName('CampaignSource')
83 1
            ->setDescription(
84
                'Use to identify a search engine, newsletter name, or other source. Example: google'
85
            );
86 1
87 1
        $fields->dataFieldByName('CampaignMedium')
88 1
            ->setDescription(
89
                'Use utm_medium to identify a medium such as email or cost-per- click. Example: cpc'
90
            );
91 1
92 1
        $fields->dataFieldByName('CampaignName')
93 1
            ->setDescription(
94
                'Used for keyword analysis. Use utm_campaign to identify a specific product promotion or
95
                strategic campaign. Example: utm_campaign=spring_sale'
96
            );
97 1
98 1
        $fields->dataFieldByName('CampaignTerm')
99 1
            ->setDescription(
100
                'Used for paid search. Use utm_term to note the keywords for this ad. Example: running+shoes'
101
            );
102 1
103 1
        $fields->dataFieldByName('CampaignContent')
104 1
            ->setDescription(
105
                'Used for A/B testing and content-targeted ads. Use utm_content to differentiate ads or links
106
                that point to the same URL. Examples: logolink or textlink'
107
            );
108 1
109
        $fields->addFieldToTab('Root.Main', ReadonlyField::create('LongURL', 'Long URL', $this->getLongURL()));
110 1
111 1
        $short = $fields->dataFieldByName('ShortURL');
112 1
        $short = $short->performReadonlyTransformation();
113
        $fields->addFieldToTab('Root.Main', $short);
114 1
115
        return $fields;
116
    }
117
118
    /**
119
     * @return ValidationResult
120 1
     */
121
    public function validate()
122 1
    {
123
        $result = parent::validate();
124 1
125 1
        if (!$this->Title) {
126
            $result->addError('A Title is required before you can save');
127
        }
128 1
129
        if (!$this->URL) {
0 ignored issues
show
Bug Best Practice introduced by
The property URL does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
130
            $result->addError('A URL is required before you can save');
131
        }
132 1
133
        if (!$this->CampaignSource) {
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignSource does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
134
            $result->addError('A Campaign Source is required before you can save');
135
        }
136 1
137
        return $result;
138
    }
139
140
    /**
141
     * @return mixed
142 1
     */
143
    public function getToken()
144 1
    {
145
        return Config::inst()->get(ShortURL::class, 'bitly_token');
146
    }
147
148
    /**
149
     * @return string
150 2
     */
151
    public function getLongURL()
152
    {
153 2
        $vars = [
154 2
            'utm_source' => $this->CampaignSource,
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignSource does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
155 2
            'utm_medium' => $this->CampaignMedium,
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignMedium does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
156 2
            'utm_campaign' => $this->CampaignName,
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignName does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
157 2
            'utm_term' => $this->CampaignTerm,
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignTerm does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
158
            'utm_content' => $this->CampaignContent,
0 ignored issues
show
Bug Best Practice introduced by
The property CampaignContent does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
159 2
        ];
160 2
        $LongURL = $this->URL . '?' . http_build_query($vars);
0 ignored issues
show
Bug Best Practice introduced by
The property URL does not exist on Dynamic\ShortURL\Model\ShortURL. Since you implemented __get, consider adding a @property annotation.
Loading history...
161
        return $LongURL;
162
    }
163
164
    /**
165
     * @return bool
166 1
     */
167
    public function getLinkChanged()
168 1
    {
169
        $isChanged = false;
170
171
        if (
172
            $this->isChanged('URL', self::CHANGE_VALUE) ||
173
            $this->isChanged('CampaignMedium', self::CHANGE_VALUE) ||
174
            $this->isChanged('CampaignName', self::CHANGE_VALUE) ||
175
            $this->isChanged('CampaignTerm', self::CHANGE_VALUE) ||
176
            $this->isChanged('CampaignContent', self::CHANGE_VALUE)
177
        ) {
178
            $isChanged = true;
179 1
        }
180
181
        $this->extend('updateIsLinkChanged', $isChanged);
182
        return $isChanged;
183
    }
184
185
    /**
186
     *
187
     */
188
    public function onBeforeWrite()
189
    {
190
        // do not call api if link is not changed
191
        if (!$this->getLinkChanged()) {
192
            return parent::onBeforeWrite();
0 ignored issues
show
Bug introduced by
Are you sure the usage of parent::onBeforeWrite() targeting SilverStripe\ORM\DataObject::onBeforeWrite() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
193
        }
194
195
        if ($token = $this->getToken()) {
196
            $api = new Api($token);
197
            $bitlink = new Bitlink($api);
198
199
            $result = $bitlink->createBitlink([
200
                'long_url' => $this->getLongURL()
201
            ]);
202
203
            // if cURL error occurs.
204
            if ($api->isCurlError()) {
205
                throw new \Exception($api->getCurlErrno().': '.$api->getCurlError());
206
207
            } else {
208
                // if Bitly response contains error message.
209
                if ($result->isError()) {
210
                    throw new \Exception($result->getDescription());
211
212
                } else {
213
214
                    // if Bitly response is 200 or 201
215
                    if ($result->isSuccess()) {
216
                        $this->ShortURL = $result->getResponseArray()['link'];
0 ignored issues
show
Bug Best Practice introduced by
The property ShortURL does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
217
218
                    } else {
219
                        throw new \Exception($result->getResponse());
220
                    }
221
                }
222
            }
223
        }
224
225
        parent::onBeforeWrite();
226
    }
227
}
228