Completed
Pull Request — master (#264)
by Robbie
13:29
created

LanguageDropdownField   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 113
Duplicated Lines 8.85 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 28
lcom 1
cbo 1
dl 10
loc 113
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
C __construct() 10 59 17
A Type() 0 4 1
A getAttributes() 0 7 1

How to fix   Duplicated Code   

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:

1
<?php
2
3
namespace SilverStripe\Translatable\Forms;
4
5
use SilverStripe\CMS\Model\SiteTree;
6
use SilverStripe\Core\Convert;
7
use SilverStripe\Forms\GroupedDropdownField;
8
use SilverStripe\i18n\i18n;
9
use SilverStripe\ORM\DataObject;
10
use SilverStripe\Translatable\Model\Translatable;
11
12
/**
13
 * An extension to dropdown field, pre-configured to list languages.
14
 * The languages already used in the site will be on top.
15
 *
16
 * @package translatable
17
 */
18
class LanguageDropdownField extends GroupedDropdownField
19
{
20
    private static $allowed_actions = array(
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...
21
        'getLocaleForObject'
22
    );
23
24
    /**
25
     * Create a new LanguageDropdownField
26
     * @param string $name
27
     * @param string $title
28
     * @param array $excludeLocales List of locales that won't be included
29
     * @param string $translatingClass Name of the class with translated instances
30
     *               where to look for used languages
31
     * @param string $list Indicates the source language list.
32
     *               Can be either Common-English or Locale-English (default)
33
     */
34
    public function __construct(
35
        $name,
36
        $title,
37
        $excludeLocales = array(),
38
        $translatingClass = SiteTree::class,
39
        $list = 'Common-English',
40
        $instance = null
41
    ) {
42
        $usedLocalesWithTitle = Translatable::get_existing_content_languages($translatingClass);
43
        $usedLocalesWithTitle = array_diff_key($usedLocalesWithTitle, $excludeLocales);
44
45
        if ('Common-English' == $list) {
46
            $allLocalesWithTitle = i18n::getData()->getLanguages();
47
        } else {
48
            $allLocalesWithTitle = i18n::getData()->getLocales();
49
        }
50
51
        if (isset($allLocales[Translatable::default_locale()])) {
0 ignored issues
show
Bug introduced by
The variable $allLocales does not exist. Did you mean $allLocalesWithTitle?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
52
            unset($allLocales[Translatable::default_locale()]);
53
        }
54
55
        // Limit to allowed locales if defined
56
        // Check for canTranslate() if an $instance is given
57
        $allowedLocales = Translatable::get_allowed_locales();
58
        foreach ($allLocalesWithTitle as $locale => $localeTitle) {
59
            if (($allowedLocales && !in_array($locale, $allowedLocales))
0 ignored issues
show
Bug Best Practice introduced by
The expression $allowedLocales of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
60
                || ($excludeLocales && in_array($locale, $excludeLocales))
0 ignored issues
show
Bug Best Practice introduced by
The expression $excludeLocales of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
61
                || ($usedLocalesWithTitle && array_key_exists($locale, $usedLocalesWithTitle))
0 ignored issues
show
Bug Best Practice introduced by
The expression $usedLocalesWithTitle of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
62
            ) {
63
                unset($allLocalesWithTitle[$locale]);
64
            }
65
        }
66
        // instance specific permissions
67 View Code Duplication
        foreach ($allLocalesWithTitle as $locale => $localeTitle) {
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...
68
            if ($instance && !$instance->canTranslate(null, $locale)) {
69
                unset($allLocalesWithTitle[$locale]);
70
            }
71
        }
72 View Code Duplication
        foreach ($usedLocalesWithTitle as $locale => $localeTitle) {
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...
73
            if ($instance && !$instance->canTranslate(null, $locale)) {
74
                unset($usedLocalesWithTitle[$locale]);
75
            }
76
        }
77
78
        // Sort by title (array value)
79
        asort($allLocalesWithTitle);
80
81
        if (count($usedLocalesWithTitle)) {
82
            asort($usedLocalesWithTitle);
83
            $source = array(
84
                _t('Form.LANGAVAIL', "Available languages") => $usedLocalesWithTitle,
85
                _t('Form.LANGAOTHER', "Other languages") => $allLocalesWithTitle
86
            );
87
        } else {
88
            $source = $allLocalesWithTitle;
89
        }
90
91
        parent::__construct($name, $title, $source);
92
    }
93
94
    public function Type()
95
    {
96
        return 'languagedropdown dropdown';
97
    }
98
99
    public function getAttributes()
100
    {
101
        return array_merge(
102
            parent::getAttributes(),
103
            array('data-locale-url' => $this->Link('getLocaleForObject'))
104
        );
105
    }
106
107
    /**
108
     * Get the locale for an object that has the Translatable extension.
109
     *
110
     * @return locale
111
     */
112
    public function getLocaleForObject()
113
    {
114
        $id = (int)$this->getRequest()->requestVar('id');
115
        $class = Convert::raw2sql($this->getRequest()->requestVar('class'));
116
        $locale = Translatable::get_current_locale();
117
        if ($id && $class && class_exists($class) && $class::has_extension(Translatable::class)) {
118
            // temporarily disable locale filter so that we won't filter out the object
119
            Translatable::disable_locale_filter();
120
            $object = DataObject::get_by_id($class, $id);
0 ignored issues
show
Bug introduced by
It seems like $class defined by \SilverStripe\Core\Conve...)->requestVar('class')) on line 115 can also be of type array; however, SilverStripe\ORM\DataObject::get_by_id() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
121
            Translatable::enable_locale_filter();
122
            if ($object) {
123
                $locale = $object->Locale;
124
            }
125
        }
126
        return $locale;
127
    }
128
}
129