Passed
Push — master ( e5e306...f7c14f )
by Swen
02:36
created

LocalizedUniqueSlugField.pre_save()   C

Complexity

Conditions 10

Size

Total Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 10.0064

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
c 3
b 0
f 0
dl 0
loc 54
ccs 24
cts 25
cp 0.96
crap 10.0064
rs 5.1428

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:

Complexity

Complex classes like LocalizedUniqueSlugField.pre_save() 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.

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.

1 1
from datetime import datetime
2
3 1
from django.utils.text import slugify
0 ignored issues
show
Configuration introduced by
The import django.utils.text 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...
4 1
from django.core.exceptions import ImproperlyConfigured
0 ignored issues
show
Configuration introduced by
The import django.core.exceptions 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
6 1
from .autoslug_field import LocalizedAutoSlugField
7 1
from ..util import get_language_codes
8 1
from ..mixins import AtomicSlugRetryMixin
9 1
from ..value import LocalizedValue
10
11
12 1
class LocalizedUniqueSlugField(LocalizedAutoSlugField):
13
    """Automatically provides slugs for a localized
14
    field upon saving."
15
16
    An improved version of :see:LocalizedAutoSlugField,
17
    which adds:
18
19
        - Concurrency safety
20
        - Improved performance
21
22
    When in doubt, use this over :see:LocalizedAutoSlugField.
23
    Inherit from :see:AtomicSlugRetryMixin in your model to
24
    make this field work properly.
25
    """
26
27 1
    def __init__(self, *args, **kwargs):
28
        """Initializes a new instance of :see:LocalizedUniqueSlugField."""
29
30 1
        kwargs['uniqueness'] = kwargs.pop('uniqueness', get_language_codes())
31
32 1
        super(LocalizedUniqueSlugField, self).__init__(
33
            *args,
34
            **kwargs
35
        )
36
37 1
        self.populate_from = kwargs.pop('populate_from')
38 1
        self.include_time = kwargs.pop('include_time', False)
39
40 1
    def deconstruct(self):
41
        """Deconstructs the field into something the database
42
        can store."""
43
44 1
        name, path, args, kwargs = super(
45
            LocalizedUniqueSlugField, self).deconstruct()
46
47 1
        kwargs['populate_from'] = self.populate_from
48 1
        kwargs['include_time'] = self.include_time
49 1
        return name, path, args, kwargs
50
51 1
    def pre_save(self, instance, add: bool):
52
        """Ran just before the model is saved, allows us to built
53
        the slug.
54
55
        Arguments:
56
            instance:
57
                The model that is being saved.
58
59
            add:
60
                Indicates whether this is a new entry
61
                to the database or an update.
62
63
        Returns:
64
            The localized slug that was generated.
65
        """
66
67 1
        if not isinstance(instance, AtomicSlugRetryMixin):
68
            raise ImproperlyConfigured((
69
                'Model \'%s\' does not inherit from AtomicSlugRetryMixin. '
70
                'Without this, the LocalizedUniqueSlugField will not work.'
71
            ) % type(instance).__name__)
72
73 1
        slugs = LocalizedValue()
74
75 1
        for lang_code, value in self._get_populate_values(instance):
76 1
            if not value:
77 1
                continue
78
79 1
            slug = slugify(value, allow_unicode=True)
80
81
            # verify whether it's needed to re-generate a slug,
82
            # if not, re-use the same slug
83 1
            if instance.pk is not None:
84 1
                current_slug = getattr(instance, self.name).get(lang_code)
0 ignored issues
show
Bug introduced by
The Instance of LocalizedUniqueSlugField does not seem to have a member named name.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
85 1
                if current_slug is not None:
86 1
                    stripped_slug = current_slug[0:current_slug.rfind('-')]
87 1
                    if slug == stripped_slug:
88 1
                        slugs.set(lang_code, current_slug)
89 1
                        continue
90
91 1
            if self.include_time:
92 1
                slug += '-%d' % datetime.now().microsecond
93
94 1
            retries = getattr(instance, 'retries', 0)
95 1
            if retries > 0:
96
                # do not add another - if we already added time
97 1
                if not self.include_time:
98 1
                    slug += '-'
99 1
                slug += '%d' % retries
100
101 1
            slugs.set(lang_code, slug)
102
103 1
        setattr(instance, self.name, slugs)
0 ignored issues
show
Bug introduced by
The Instance of LocalizedUniqueSlugField does not seem to have a member named name.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
104
        return slugs
105