Passed
Push — 2.x ( ab37e3...da17b1 )
by Jordi
05:29
created

senaite.core.registry.set()   A

Complexity

Conditions 5

Size

Total Lines 21
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 21
rs 9.0333
c 0
b 0
f 0
cc 5
nop 2
1
# -*- coding: utf-8 -*-
2
3
from plone.registry.interfaces import IRegistry
4
from senaite.core.registry.schema import ISenaiteRegistry
5
from zope.component import getUtility
6
from zope.schema._bootstrapinterfaces import WrongType
7
from zope.dottedname.resolve import resolve
8
9
10
def get_registry():
11
    """Returns the registry utility
12
13
    :returns: Registry object
14
    """
15
    return getUtility(IRegistry)
16
17
18
def get_registry_interfaces():
19
    """
20
    """
21
    registry = get_registry()
22
23
    interface_names = set(
24
        record.interfaceName for record in list(registry.records.values())
25
    )
26
27
    for name in interface_names:
28
        if not name:
29
            continue
30
31
        interface = None
32
        try:
33
            interface = resolve(name)
34
        except ImportError:
35
            # In case of leftover registry entries of uninstalled Products
36
            continue
37
38
        if interface.isOrExtends(ISenaiteRegistry):
39
            yield interface
40
41
42
def get_registry_record(name, default=None):
43
    """Get SENAITE registry record
44
    """
45
    registry = get_registry()
46
    for interface in get_registry_interfaces():
47
        proxy = registry.forInterface(interface)
48
        try:
49
            return getattr(proxy, name)
50
        except AttributeError:
51
            pass
52
    return default
53
54
55
def set_registry_record(name, value):
56
    """Set SENAITE registry record
57
    """
58
    registry = get_registry()
59
    for interface in get_registry_interfaces():
60
        proxy = registry.forInterface(interface)
61
        try:
62
            getattr(proxy, name)
63
        except AttributeError:
64
            pass
65
        else:
66
            try:
67
                return setattr(proxy, name, value)
68
            except WrongType:
69
                field_type = None
70
                for field in interface.namesAndDescriptions():
71
                    if field[0] == name:
72
                        field_type = field[1]
73
                        break
74
                raise TypeError(
75
                    u"The value parameter for the field {name} needs to be "
76
                    u"{of_class} instead of {of_type}".format(
77
                        name=name,
78
                        of_class=str(field_type.__class__),
79
                        of_type=type(value),
80
                    ))
81
82
    raise NameError("No registry record found for name '{}'".format(name))
83