InstagramAdminRequestHandler   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 3
dl 0
loc 26
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A ItemEditForm() 0 14 3
1
<?php
2
3
use League\OAuth2\Client\Provider\Exception\InstagramIdentityProviderException;
4
5
class InstagramAdmin 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
    /**
8
     * @var string
9
     */
10
    private static $url_segment = 'instagram';
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...
11
12
    /**
13
     * @var string
14
     */
15
    private static $menu_title = 'Instagram';
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...
16
17
    /**
18
     * @var array
19
     */
20
    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...
21
        'InstagramAccount',
22
    ];
23
24
    /**
25
     * @var array
26
     */
27
    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...
28
        'ImportForm',
29
        'SearchForm',
30
        'OAuth',
31
    ];
32
33
    /**
34
     * @var string
35
     */
36
    private static $menu_icon = 'silverstripe-instagram/images/instagram-logo.png';
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_icon 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...
37
38
    /**
39
     * @param int $id
40
     * @param FieldList $fields
41
     * @return Form
42
     */
43
    public function getEditForm($id = null, $fields = null)
44
    {
45
        $form = parent::getEditForm($id, $fields);
46
47
        $gridFieldName = $this->sanitiseClassName($this->modelClass);
48
        $gridFieldConfig = $form->Fields()->fieldByName($gridFieldName)->getConfig();
49
50
        $gridFieldConfig->removeComponentsByType('GridFieldPrintButton');
51
        $gridFieldConfig->removeComponentsByType('GridFieldExportButton');
52
        $gridFieldConfig
53
            ->getComponentByType('GridFieldAddNewButton')
54
            ->setButtonName(_t('Instagram.ButtonLabelAddAccount', 'Add account'));
55
        $gridFieldConfig
56
            ->getComponentByType('GridFieldDetailForm')
57
            ->setItemRequestClass('InstagramAdminRequestHandler');
58
59
        return $form;
60
    }
61
62
    /**
63
     * Gets a InstagramAccount ID from the Session.
64
     *
65
     * @param string $state
66
     * @return int|null
67
     */
68
    private function getInstagramAccountIDFromSession($state = null)
69
    {
70
        if (!$state) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $state of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
71
            return null;
72
        }
73
74
        $instagramAccounts = Session::get('InstagramAccounts');
75
76
        foreach ($instagramAccounts as $key => $value) {
77
            if ($value == $state) {
78
                return $key;
79
            }
80
        }
81
    }
82
83
    /**
84
     * Handles failed AOuth attempts.
85
     *
86
     * @param Form $form
87
     * @return Controller
88
     */
89
    private function handleOAuthError($form, $message = null)
90
    {
91
        $message = $message ? $message : _t(
92
            'Instagram.MessageOAuthErrorResponse',
93
            'Unable to authorise account. Please try again.'
94
        );
95
96
        $form->sessionMessage($message, 'bad');
97
98
        return Controller::curr()->redirect($this->Link());
99
    }
100
101
    /**
102
     * OAuth callback handler.
103
     *
104
     * @param SS_HTTPRequest $request
105
     */
106
    public function OAuth($request)
107
    {
108
        $code = $request->getVar('code');
109
        $state = $request->getVar('state');
110
111
        if (!$code || !$state) {
112
            return Controller::curr()->redirect($this->Link());
113
        }
114
115
        $client = InstagramAccount::getNewInstagramClient();
116
        $form = $this->getEditForm();
117
118
        try {
119
            $token = $client->getAccessToken($code);
120
121
            $instagramAccountID = $this->getInstagramAccountIDFromSession($state);
122
123
            // Find the matching InstagramAccount.
124
            if (!$instagramAccountID ||
125
                !$instagramAccount = InstagramAccount::get()->byId($instagramAccountID)
126
            ) {
127
                return $this->handleOAuthError($form);
128
            }
129
130
            try {
131
                $instagramAccount->updateAccessToken(Convert::raw2json($token), $state);
132
                $instagramAccount->write();
133
134
                $form->sessionMessage(
135
                    _t(
136
                        'Instagram.MessageOAuthSuccess',
137
                        'Successfully authorised your account.'
138
                    ),
139
                    'good'
140
                );
141
142
                return Controller::curr()->redirect($this->Link());
143
            } catch (Exception $e) {
144
                return $this->handleOAuthError($form, _t(
145
                    'Instagram.MessageOAuthErrorUserConflict',
146
                    'Unable to authorise account. Make sure you are logged out of Instagram and ' .
147
                    'your username is spelled correctly.'
148
                ));
149
            }
150
        } catch (InstagramIdentityProviderException $e) {
151
            return $this->handleOAuthError($form);
152
        }
153
    }
154
}
155
156
class InstagramAdminRequestHandler 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...
157
{
158
    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...
159
        'edit',
160
        'view',
161
        'ItemEditForm'
162
    ];
163
164
    /**
165
     * @return Form
166
     */
167
    public function ItemEditForm()
168
    {
169
        $form = parent::ItemEditForm();
170
171
        $formActions = $form->Actions();
172
173
        if ($actions = $this->record->getCMSActions()) {
174
            foreach ($actions as $action) {
175
                $formActions->push($action);
176
            }
177
        }
178
179
        return $form;
180
    }
181
}
182