ShortURL::getCMSFields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 25
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 41
ccs 20
cts 20
cp 1
crap 1
rs 9.52
1
<?php
2
3
namespace Dynamic\ShortURL\Model;
4
5
use GuzzleHttp\Client;
6
use SilverStripe\Core\Config\Config;
7
use SilverStripe\Forms\FieldList;
8
use SilverStripe\Forms\ReadonlyField;
9
use SilverStripe\ORM\DataObject;
10
use SilverStripe\ORM\ValidationResult;
11
12
class ShortURL extends DataObject
13
{
14
    /**
15
     * @var string
16
     */
17
    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...
18
19
    /**
20
     * @var string
21
     */
22
    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...
23
24
    /**
25
     * @var array
26
     */
27
    private static $db = [
0 ignored issues
show
introduced by
The private property $db is not used, and could be removed.
Loading history...
28
        'Title' => 'Varchar(255)',
29
        'URL' => 'Varchar(255)',
30
        'CampaignSource' => 'Varchar(255)',
31
        'CampaignMedium' => 'Varchar(255)',
32
        'CampaignName' => 'Varchar(255)',
33
        'CampaignTerm' => 'Varchar(255)',
34
        'CampaignContent' => 'Varchar(255)',
35
        'ShortURL' => 'Varchar(255)',
36
    ];
37
38
    /**
39
     * @var array
40
     */
41
    private static $summary_fields = [
0 ignored issues
show
introduced by
The private property $summary_fields is not used, and could be removed.
Loading history...
42
        'Title',
43
        'URL',
44
        'ShortURL',
45
    ];
46
47
    /**
48
     * @var array
49
     */
50
    private static $searchable_fields = [
0 ignored issues
show
introduced by
The private property $searchable_fields is not used, and could be removed.
Loading history...
51
        'Title',
52
        'URL',
53
        'CampaignSource',
54
        'CampaignMedium',
55
        'CampaignName',
56
        'CampaignTerm',
57
        'CampaignContent',
58
        'ShortURL',
59
    ];
60
61
    /**
62
     * @var string
63
     */
64
    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...
65
66
    /**
67
     * @return FieldList
68
     */
69
    public function getCMSFields()
70
    {
71
        $fields = parent::getCMSFields();
72
73
        $fields->dataFieldByName('URL')
74 1
            ->setDescription('URL to shorten and tag');
75
76 1
        $fields->dataFieldByName('CampaignSource')
77
            ->setDescription(
78 1
                'Use to identify a search engine, newsletter name, or other source. Example: google'
79 1
            );
80
81 1
        $fields->dataFieldByName('CampaignMedium')
82 1
            ->setDescription(
83 1
                'Use utm_medium to identify a medium such as email or cost-per- click. Example: cpc'
84
            );
85
86 1
        $fields->dataFieldByName('CampaignName')
87 1
            ->setDescription(
88 1
                'Used for keyword analysis. Use utm_campaign to identify a specific product promotion or
89
                strategic campaign. Example: utm_campaign=spring_sale'
90
            );
91 1
92 1
        $fields->dataFieldByName('CampaignTerm')
93 1
            ->setDescription(
94
                'Used for paid search. Use utm_term to note the keywords for this ad. Example: running+shoes'
95
            );
96
97 1
        $fields->dataFieldByName('CampaignContent')
98 1
            ->setDescription(
99 1
                'Used for A/B testing and content-targeted ads. Use utm_content to differentiate ads or links
100
                that point to the same URL. Examples: logolink or textlink'
101
            );
102 1
103 1
        $fields->addFieldToTab('Root.Main', ReadonlyField::create('LongURL', 'Long URL', $this->getLongURL()));
104 1
105
        $short = $fields->dataFieldByName('ShortURL');
106
        $short = $short->performReadonlyTransformation();
107
        $fields->addFieldToTab('Root.Main', $short);
108 1
109
        return $fields;
110 1
    }
111 1
112 1
    /**
113
     * @return ValidationResult
114 1
     */
115
    public function validate()
116
    {
117
        $result = parent::validate();
118
119
        if (!$this->Title) {
120 1
            $result->addError('A Title is required before you can save');
121
        }
122 1
123
        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...
124 1
            $result->addError('A URL is required before you can save');
125 1
        }
126
127
        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...
128 1
            $result->addError('A Campaign Source is required before you can save');
129
        }
130
131
        return $result;
132 1
    }
133
134
    /**
135
     * @return mixed
136 1
     */
137
    public function getToken()
138
    {
139
        return Config::inst()->get(ShortURL::class, 'bitly_token');
140
    }
141
142 1
    /**
143
     * @return mixed
144 1
     */
145
    public function getDomain()
146
    {
147
        return Config::inst()->get(ShortURL::class, 'bitly_domain');
148
    }
149
150 2
    /**
151
     * @return string
152
     */
153 2
    public function getLongURL()
154 2
    {
155 2
        $vars = [
156 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...
157 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...
158
            '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...
159 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...
160 2
            '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...
161
        ];
162
        $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...
163
        return $LongURL;
164
    }
165
166 1
    /**
167
     * @return bool
168 1
     */
169
    public function getLinkChanged()
170
    {
171
        $isChanged = false;
172
173
        if (
174
            $this->isChanged('URL', self::CHANGE_VALUE) ||
175
            $this->isChanged('CampaignMedium', self::CHANGE_VALUE) ||
176
            $this->isChanged('CampaignName', self::CHANGE_VALUE) ||
177
            $this->isChanged('CampaignTerm', self::CHANGE_VALUE) ||
178
            $this->isChanged('CampaignContent', self::CHANGE_VALUE)
179 1
        ) {
180
            $isChanged = true;
181
        }
182
183
        $this->extend('updateIsLinkChanged', $isChanged);
184
        return $isChanged;
185
    }
186
187
    /**
188
     *
189
     */
190
    public function onBeforeWrite()
191
    {
192
        // do not call api if link is not changed
193
        if (!$this->getLinkChanged()) {
194
            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...
195
        }
196
197
        if ($token = $this->getToken()) {
0 ignored issues
show
Unused Code introduced by
The assignment to $token is dead and can be removed.
Loading history...
198
            $client = new Client([
199
                'base_uri' => 'https://api-ssl.bitly.com/v4/',
200
                'timeout' => $this->config()->get('timeout'),
201
                'http_errors' => false,
202
                'verify' => true,
203
                'headers' => [
204
                    'Authorization' => 'Bearer ' . $this->getToken(),
205
                    'Content-Type' => 'application/json',
206
                ],
207
            ]);
208
209
            $data = [
210
                'long_url' => $this->getLongURL(),
211
            ];
212
213
            if ($domain = $this->getDomain()) {
214
                $data['domain'] = $domain;
215
            }
216
217
            $response = $client->post('shorten', [
218
                'json' => $data,
219
            ]);
220
221
            $responseData = json_decode($response->getBody(), true);
222
            if ($response->getStatusCode() != 200 && $response->getStatusCode() != 201) {
223
                throw new \Exception($responseData['message'] . ' : ' . $responseData['description']);
224
            }
225
226
            $this->ShortURL = $responseData['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...
227
        }
228
229
        parent::onBeforeWrite();
230
    }
231
}
232