I18nHelper   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 111
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 4
dl 0
loc 111
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
B i18nInput() 0 29 5
B i18nScript() 0 23 5
1
<?php
2
namespace App\View\Helper;
3
4
use Cake\Core\Configure;
5
use Cake\I18n\I18n;
6
use Cake\ORM\Entity;
7
use Cake\Utility\Inflector;
8
use Cake\View\Helper;
9
use Cake\View\View;
10
11
class I18nHelper extends Helper
12
{
13
14
    /**
15
     * Helpers used.
16
     *
17
     * @var array
18
     */
19
    public $helpers = ['Form'];
20
21
    /**
22
     * Default config.
23
     *
24
     * @var array
25
     */
26
    protected $_defaultConfig = [
27
        'locales' => null
28
    ];
29
30
    /**
31
     * The locales used in the application.
32
     *
33
     * @var array
34
     */
35
    protected $_locales = [];
36
37
    /**
38
     * Construct method.
39
     *
40
     * @param \Cake\View\View $view The view that was fired.
41
     * @param array $config The config passed to the class.
42
     */
43
    public function __construct(View $view, $config = [])
44
    {
45
        parent::__construct($view, $config);
46
47
        $this->_locales = (is_array($this->config('locales'))) ? $this->config('locales') : Configure::read('I18n.locales');
0 ignored issues
show
Documentation Bug introduced by
It seems like is_array($this->config('...e::read('I18n.locales') of type * is incompatible with the declared type array of property $_locales.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
Deprecated Code introduced by
The method Cake\Core\InstanceConfigTrait::config() has been deprecated with message: 3.4.0 use setConfig()/getConfig() instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
48
    }
49
50
    /**
51
     * Generate inputs in all locales.
52
     *
53
     * @param \Cake\ORM\Entity $entity The entity that was fired.
54
     * @param string $field The field to process.
55
     * @param array $options The options to pass to the input.
56
     * @param string $divClass The class to set to the div before the input.
57
     * @param string $id The id of the input.
58
     *
59
     * @return string
60
     */
61
    public function i18nInput(Entity $entity, $field, $options = [], $divClass = 'col-sm-5', $id = 'CkEditorBox')
62
    {
63
        $html = '';
64
        $options['CkEditor'] = (isset($options['CkEditor'])) ? $options['CkEditor'] : false;
65
66
        $i = 0;
67
68
        foreach ($this->_locales as $locale => $lang) {
69
            if ($locale == I18n::defaultLocale()) {
70
                continue;
71
            }
72
73
            $i ++;
74
            $options['label'] = Inflector::humanize($lang);
75
            $options['value'] = $entity->translation($locale)->{$field};
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Cake\ORM\Entity as the method translation() does only exist in the following sub-classes of Cake\ORM\Entity: App\Model\Entity\BlogArticle, App\Model\Entity\BlogCategory, App\Model\Entity\Group. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
76
77
            if ($options['CkEditor'] === true) {
78
                $options['id'] = $id . '-' . $i;
79
                unset($options['CkEditor']);
80
            }
81
82
            $html .= '<div class="form-group">';
83
            $html .= '<div class="col-sm-offset-2 ' . $divClass . '">';
84
            $html .= $this->Form->input('translations.' . $locale . '.' . $field, $options);
0 ignored issues
show
Documentation introduced by
The property Form does not exist on object<App\View\Helper\I18nHelper>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
85
            $html .= '</div></div>';
86
        }
87
88
        return $html;
89
    }
90
91
    /**
92
     * Generate the script tag to initialize CkEditor for textarea.
93
     *
94
     * @param array $options The options passed to the function.
95
     *
96
     * @return string
97
     */
98
    public function i18nScript($options = [])
99
    {
100
        $html = '';
101
        $file = (isset($options['file'])) ? $options['file'] : 'article';
102
        $name = (isset($options['name'])) ? $options['name'] : 'CkEditorBox';
103
        $i = 0;
104
105
        foreach ($this->_locales as $locale => $lang) {
106
            if ($locale == I18n::defaultLocale()) {
107
                continue;
108
            }
109
110
            $i ++;
111
            $html .= '
112
            <script type="text/javascript">
113
            CKEDITOR.replace(\'' . $name . '-' . $i . '\', {
114
                customConfig: \'config/' . $file . '.js\'
115
            });
116
            </script>';
117
        }
118
119
        return $html;
120
    }
121
}
122