Translator::translate()   F
last analyzed

Complexity

Conditions 14
Paths 352

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
nc 352
nop 2
dl 0
loc 52
rs 3.5333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11
 * @link          https://cakephp.org CakePHP(tm) Project
12
 */
13
namespace Cake\I18n;
14
15
use Aura\Intl\Translator as BaseTranslator;
16
17
/**
18
 * Provides missing message behavior for CakePHP internal message formats.
19
 *
20
 * @internal
21
 */
22
class Translator extends BaseTranslator
23
{
24
    const PLURAL_PREFIX = 'p:';
25
26
    /**
27
     * Translates the message formatting any placeholders
28
     *
29
     *
30
     * @param string $key The message key.
31
     * @param array $tokensValues Token values to interpolate into the
32
     *   message.
33
     * @return string The translated message with tokens replaced.
34
     */
35
    public function translate($key, array $tokensValues = [])
36
    {
37
        if (isset($tokensValues['_count'])) {
38
            $message = $this->getMessage(static::PLURAL_PREFIX . $key);
39
            if (!$message) {
40
                $message = $this->getMessage($key);
41
            }
42
        } else {
43
            $message = $this->getMessage($key);
44
            if (!$message) {
45
                $message = $this->getMessage(static::PLURAL_PREFIX . $key);
46
            }
47
        }
48
49
        if (!$message) {
50
            // Fallback to the message key
51
            $message = $key;
52
        }
53
54
        // Check for missing/invalid context
55
        if (isset($message['_context'])) {
56
            $message = $this->resolveContext($key, $message, $tokensValues);
57
            unset($tokensValues['_context']);
58
        }
59
60
        if (!$tokensValues) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $tokensValues 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
            // Fallback for plurals that were using the singular key
62
            if (is_array($message)) {
63
                return array_values($message + [''])[0];
64
            }
65
66
            return $message;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $message; (object|integer|double|string|null|boolean) is incompatible with the return type documented by Cake\I18n\Translator::translate of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
67
        }
68
69
        // Singular message, but plural call
70
        if (is_string($message) && isset($tokensValues['_singular'])) {
71
            $message = [$tokensValues['_singular'], $message];
72
        }
73
74
        // Resolve plural form.
75
        if (is_array($message)) {
76
            $count = isset($tokensValues['_count']) ? $tokensValues['_count'] : 0;
77
            $form = PluralRules::calculate($this->locale, $count);
78
            $message = isset($message[$form]) ? $message[$form] : (string)end($message);
79
        }
80
81
        if (strlen($message) === 0) {
82
            $message = $key;
83
        }
84
85
        return $this->formatter->format($this->locale, $message, $tokensValues);
86
    }
87
88
    /**
89
     * Resolve a message's context structure.
90
     *
91
     * @param string $key The message key being handled.
92
     * @param string|array $message The message content.
93
     * @param array $vars The variables containing the `_context` key.
94
     * @return string
95
     */
96
    protected function resolveContext($key, $message, array $vars)
97
    {
98
        $context = isset($vars['_context']) ? $vars['_context'] : null;
99
100
        // No or missing context, fallback to the key/first message
101
        if ($context === null) {
102
            if (isset($message['_context'][''])) {
103
                return $message['_context'][''] === '' ? $key : $message['_context'][''];
104
            }
105
106
            return current($message['_context']);
107
        }
108
        if (!isset($message['_context'][$context])) {
109
            return $key;
110
        }
111
        if ($message['_context'][$context] === '') {
112
            return $key;
113
        }
114
115
        return $message['_context'][$context];
116
    }
117
}
118