TranslatableCMSMainExtension   A
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 241
Duplicated Lines 8.71 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 41
lcom 2
cbo 2
dl 21
loc 241
rs 9.1199
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
D init() 0 83 18
A updateEditForm() 0 7 3
A updatePageOptions() 0 4 1
A createtranslation() 0 36 3
A updateLink() 7 7 3
A updateLinkWithSearch() 7 7 3
A updateExtraTreeTools() 0 5 2
A updateLinkPageAdd() 7 7 3
A LangForm() 0 37 2
A selectlang() 0 4 1
A MultipleLanguages() 0 6 1
A IsTranslatableEnabled() 0 4 1

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like TranslatableCMSMainExtension often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TranslatableCMSMainExtension, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package translatable
4
 */
5
class TranslatableCMSMainExtension extends Extension
6
{
7
    private static $allowed_actions = array(
8
        'createtranslation',
9
    );
10
11
    public function init()
12
    {
13
        $req = $this->owner->getRequest();
14
        
15
        // Ignore being called on LeftAndMain base class,
16
        // which is the case when requests are first routed through AdminRootController
17
        // as an intermediary rather than the endpoint controller
18
        if (!$this->owner->stat('tree_class')) {
19
            return;
20
        }
21
22
        // Locale" attribute is either explicitly added by LeftAndMain Javascript logic,
23
        // or implied on a translated record (see {@link Translatable->updateCMSFields()}).
24
        // $Lang serves as a "context" which can be inspected by Translatable - hence it
25
        // has the same name as the database property on Translatable.
26
        $id = $req->param('ID');
27
        if ($req->requestVar("Locale")) {
28
            $this->owner->Locale = $req->requestVar("Locale");
29
        } elseif ($id && is_numeric($id)) {
30
            $record = DataObject::get_by_id($this->owner->stat('tree_class'), $id);
31
            if ($record && $record->Locale) {
32
                $this->owner->Locale = $record->Locale;
33
            }
34
        } else {
35
            $this->owner->Locale = Translatable::default_locale();
36
            if ($this->owner->class == 'CMSPagesController') {
37
                // the CMSPagesController always needs to have the locale set, 
38
                // otherwise page editing will cause an extra
39
                // ajax request which looks weird due to multiple "loading"-flashes
40
                $getVars = $req->getVars();
41
                if (isset($getVars['url'])) {
42
                    unset($getVars['url']);
43
                }
44
                return $this->owner->redirect(Controller::join_links(
45
                    $this->owner->Link(),
46
                    $req->param('Action'),
47
                    $req->param('ID'),
48
                    $req->param('OtherID'),
49
                    ($query = http_build_query($getVars)) ? "?$query" : null
50
                ));
51
            }
52
        }
53
        Translatable::set_current_locale($this->owner->Locale);
54
55
        // If a locale is set, it needs to match to the current record
56
        $requestLocale = $req->requestVar("Locale");
57
        $page = $this->owner->currentPage();
58
        if (
59
            $req->httpMethod() == 'GET' // leave form submissions alone
60
            && $requestLocale
61
            && $page
62
            && $page->hasExtension('Translatable')
63
            && $page->Locale != $requestLocale
64
            && $req->latestParam('Action') != 'EditorToolbar'
65
        ) {
66
            $transPage = $page->getTranslation($requestLocale);
67
            if ($transPage) {
68
                Translatable::set_current_locale($transPage->Locale);
69
                return $this->owner->redirect(Controller::join_links(
70
                    $this->owner->Link('show'),
71
                    $transPage->ID
72
                    // ?locale will automatically be added
73
                ));
74
            } elseif ($this->owner->class != 'CMSPagesController') {
75
                // If the record is not translated, redirect to pages overview
76
                return $this->owner->redirect(Controller::join_links(
77
                    singleton('CMSPagesController')->Link(),
78
                    '?Locale=' . $requestLocale
79
                ));
80
            }
81
        }
82
        
83
        // collect languages for TinyMCE spellchecker plugin.
84
        // see http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/spellchecker
85
        $langName = i18n::get_locale_name($this->owner->Locale);
86
        HtmlEditorConfig::get('cms')->setOption(
87
            'spellchecker_languages',
88
            "+{$langName}={$this->owner->Locale}"
89
        );
90
91
        Requirements::javascript('translatable/javascript/CMSMain.Translatable.js');
92
        Requirements::css('translatable/css/CMSMain.Translatable.css');
93
    }
94
    
95
    public function updateEditForm(&$form)
96
    {
97
        if ($form->getName() == 'RootForm' && SiteConfig::has_extension("Translatable")) {
98
            $siteConfig = SiteConfig::current_site_config();
99
            $form->Fields()->push(new HiddenField('Locale', '', $siteConfig->Locale));
100
        }
101
    }
102
    
103
    public function updatePageOptions(&$fields)
104
    {
105
        $fields->push(new HiddenField("Locale", 'Locale', Translatable::get_current_locale()));
106
    }
107
    
108
    /**
109
     * Create a new translation from an existing item, switch to this language and reload the tree.
110
     */
111
    public function createtranslation($data, $form)
112
    {
113
        $request = $this->owner->getRequest();
114
115
        // Protect against CSRF on destructive action
116
        if (!SecurityToken::inst()->checkRequest($request)) {
117
            return $this->owner->httpError(400);
118
        }
119
120
        $langCode = Convert::raw2sql($request->postVar('NewTransLang'));
121
        $record = $this->owner->getRecord($request->postVar('ID'));
122
        if (!$record) {
123
            return $this->owner->httpError(404);
124
        }
125
        
126
        $this->owner->Locale = $langCode;
127
        Translatable::set_current_locale($langCode);
128
        
129
        // Create a new record in the database - this is different
130
        // to the usual "create page" pattern of storing the record
131
        // in-memory until a "save" is performed by the user, mainly
132
        // to simplify things a bit.
133
        // @todo Allow in-memory creation of translations that don't 
134
        // persist in the database before the user requests it
135
        $translatedRecord = $record->createTranslation($langCode);
136
137
        $url = Controller::join_links(
138
            $this->owner->Link('show'),
139
            $translatedRecord->ID
140
        );
141
142
        // set the X-Pjax header to Content, so that the whole admin panel will be refreshed
143
        $this->owner->getResponse()->addHeader('X-Pjax', 'Content');
144
        
145
        return $this->owner->redirect($url);
146
    }
147
148 View Code Duplication
    public function updateLink(&$link)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
149
    {
150
        $locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
151
        if ($locale) {
152
            $link = Controller::join_links($link, '?Locale=' . $locale);
153
        }
154
    }
155
156 View Code Duplication
    public function updateLinkWithSearch(&$link)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
157
    {
158
        $locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
159
        if ($locale) {
160
            $link = Controller::join_links($link, '?Locale=' . $locale);
161
        }
162
    }
163
164
    public function updateExtraTreeTools(&$html)
165
    {
166
        $locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
0 ignored issues
show
Unused Code introduced by
$locale 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...
167
        $html = $this->LangForm()->forTemplate() . $html;
168
    }
169
170 View Code Duplication
    public function updateLinkPageAdd(&$link)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
171
    {
172
        $locale = $this->owner->Locale ? $this->owner->Locale : Translatable::get_current_locale();
173
        if ($locale) {
174
            $link = Controller::join_links($link, '?Locale=' . $locale);
175
        }
176
    }
177
    
178
    /**
179
     * Returns a form with all languages with languages already used appearing first.
180
     * 
181
     * @return Form
182
     */
183
    public function LangForm()
184
    {
185
        $member = Member::currentUser(); //check to see if the current user can switch langs or not
186
        if (Permission::checkMember($member, 'VIEW_LANGS')) {
187
            $field = new LanguageDropdownField(
188
                'Locale',
189
                _t('CMSMain.LANGUAGEDROPDOWNLABEL', 'Language'),
190
                array(),
191
                'SiteTree',
192
                'Locale-English',
193
                singleton('SiteTree')
194
            );
195
            $field->setValue(Translatable::get_current_locale());
196
        } else {
197
            // user doesn't have permission to switch langs 
198
            // so just show a string displaying current language
199
            $field = new LiteralField(
200
                'Locale',
201
                i18n::get_locale_name(Translatable::get_current_locale())
202
            );
203
        }
204
        
205
        $form = new Form(
206
            $this->owner,
207
            'LangForm',
208
            new FieldList(
209
                $field
210
            ),
211
            new FieldList(
212
                new FormAction('selectlang', _t('CMSMain_left.GO', 'Go'))
213
            )
214
        );
215
        $form->unsetValidator();
216
        $form->addExtraClass('nostyle');
217
        
218
        return $form;
219
    }
220
    
221
    public function selectlang($data, $form)
222
    {
223
        return $this->owner;
224
    }
225
    
226
    /**
227
     * Determine if there are more than one languages in our site tree.
228
     * 
229
     * @return boolean
230
     */
231
    public function MultipleLanguages()
232
    {
233
        $langs = Translatable::get_existing_content_languages('SiteTree');
234
235
        return (count($langs) > 1);
236
    }
237
    
238
    /**
239
     * @return boolean
240
     */
241
    public function IsTranslatableEnabled()
242
    {
243
        return SiteTree::has_extension('Translatable');
244
    }
245
}
246