Passed
Push — master ( f7c14f...06873a )
by Swen
02:26
created

LocalizedFileValue   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 17
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 17
ccs 9
cts 10
cp 0.9
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __str__() 0 3 1
A localized() 0 3 1
A __getattr__() 0 8 2
1 1
import collections
2
3
4 1
from django.conf import settings
0 ignored issues
show
Configuration introduced by
The import django.conf could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
5 1
from django.utils import translation
0 ignored issues
show
Configuration introduced by
The import django.utils could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
6
7
8 1
class LocalizedValue(dict):
9
    """Represents the value of a :see:LocalizedField."""
10 1
    default_value = None
11
12 1
    def __init__(self, keys: dict=None):
13
        """Initializes a new instance of :see:LocalizedValue.
14
15
        Arguments:
16
            keys:
17
                The keys to initialize this value with. Every
18
                key contains the value of this field in a
19
                different language.
20
        """
21
22 1
        super().__init__({})
23 1
        self._interpret_value(keys)
24
25 1
    def get(self, language: str=None, default: str=None) -> str:
26
        """Gets the underlying value in the specified or
27
        primary language.
28
29
        Arguments:
30
            language:
31
                The language to get the value in.
32
33
        Returns:
34
            The value in the current language, or
35
            the primary language in case no language
36
            was specified.
37
        """
38
39 1
        language = language or settings.LANGUAGE_CODE
40 1
        return super().get(language, default)
41
42 1
    def set(self, language: str, value: str):
43
        """Sets the value in the specified language.
44
45
        Arguments:
46
            language:
47
                The language to set the value in.
48
49
            value:
50
                The value to set.
51
        """
52
53 1
        self[language] = value
54 1
        self.__dict__.update(self)
55 1
        return self
56
57 1
    def deconstruct(self) -> dict:
58
        """Deconstructs this value into a primitive type.
59
60
        Returns:
61
            A dictionary with all the localized values
62
            contained in this instance.
63
        """
64
65 1
        path = 'localized_fields.localized_value.%s' % self.__class__.__name__
66 1
        return path, [self.__dict__], {}
67
68 1
    def _interpret_value(self, value):
69
        """Interprets a value passed in the constructor as
70
        a :see:LocalizedValue.
71
72
        If string:
73
            Assumes it's the default language.
74
75
        If dict:
76
            Each key is a language and the value a string
77
            in that language.
78
79
        If list:
80
            Recurse into to apply rules above.
81
82
        Arguments:
83
            value:
84
                The value to interpret.
85
        """
86
87 1
        for lang_code, _ in settings.LANGUAGES:
88 1
            self.set(lang_code, self.default_value)
89
90 1
        if isinstance(value, str):
91 1
            self.set(settings.LANGUAGE_CODE, value)
92
93 1
        elif isinstance(value, dict):
94 1
            for lang_code, _ in settings.LANGUAGES:
95 1
                lang_value = value.get(lang_code, self.default_value)
96 1
                self.set(lang_code, lang_value)
97
98 1
        elif isinstance(value, collections.Iterable):
99 1
            for val in value:
100 1
                self._interpret_value(val)
101
102 1
    def __str__(self) -> str:
103
        """Gets the value in the current language, or falls
104
        back to the primary language if there's no value
105
        in the current language."""
106
107 1
        value = self.get(translation.get_language())
108
109 1
        if not value:
110 1
            value = self.get(settings.LANGUAGE_CODE)
111
112 1
        return value or ''
113
114 1
    def __eq__(self, other):
115
        """Compares :paramref:self to :paramref:other for
116
        equality.
117
118
        Returns:
119
            True when :paramref:self is equal to :paramref:other.
120
            And False when they are not.
121
        """
122
123 1
        if not isinstance(other, type(self)):
124 1
            if isinstance(other, str):
125 1
                return self.__str__() == other
126 1
            return False
127
128 1
        for lang_code, _ in settings.LANGUAGES:
129 1
            if self.get(lang_code) != other.get(lang_code):
130 1
                return False
131
132 1
        return True
133
134 1
    def __ne__(self, other):
135
        """Compares :paramref:self to :paramerf:other for
136
        in-equality.
137
138
        Returns:
139
            True when :paramref:self is not equal to :paramref:other.
140
            And False when they are.
141
        """
142
143 1
        return not self.__eq__(other)
144
145 1
    def __setattr__(self, language: str, value: str):
146
        """Sets the value for a language with the specified name.
147
148
        Arguments:
149
            language:
150
                The language to set the value in.
151
152
            value:
153
                The value to set.
154
        """
155
156 1
        self.set(language, value)
157
158
    def __repr__(self):  # pragma: no cover
159
        """Gets a textual representation of this object."""
160
161
        return '%s<%s> 0x%s' % (self.__class__.__name__,
162
                                self.__dict__, id(self))
163
164
165 1
class LocalizedStringValue(LocalizedValue):
166 1
    default_value = ''
167
168
169 1
class LocalizedFileValue(LocalizedValue):
170 1
    def __getattr__(self, name: str):
171
        """Proxies access to attributes to attributes of LocalizedFile"""
172
173 1
        value = self.get(translation.get_language())
174 1
        if hasattr(value, name):
175 1
            return getattr(value, name)
176 1
        raise AttributeError("'{}' object has no attribute '{}'".
177
                             format(self.__class__.__name__, name))
178
179 1
    def __str__(self) -> str:
180
        """Returns string representation of value"""
181 1
        return str(super().__str__())
182
183 1
    def localized(self):
184
        """Returns value for current language"""
185
        return self.get(translation.get_language())
186