Passed
Push — trunk ( 4b7b72...febbe2 )
by Christian
18:02 queued 03:43
created

src/Administration/Resources/app/administration/src/app/init/context.init.ts   C

Complexity

Total Complexity 54
Complexity/F 54

Size

Lines of Code 156
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 116
dl 0
loc 156
rs 6.4799
c 0
b 0
f 0
wmc 54
mnd 53
bc 53
fnc 1
bpm 53
cpm 54
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
F context.init.ts ➔ initializeContext 0 146 54

How to fix   Complexity   

Complexity

Complex classes like src/Administration/Resources/app/administration/src/app/init/context.init.ts 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
/**
2
 * @package admin
3
 */
4
5
/* Is covered by E2E tests */
6
import { publish } from '@shopware-ag/admin-extension-sdk/es/channel';
7
8
// eslint-disable-next-line sw-deprecation-rules/private-feature-declarations
9
export default function initializeContext(): void {
10
    // Handle incoming context requests from the ExtensionAPI
11
    Shopware.ExtensionAPI.handle('contextCurrency', () => {
12
        return {
13
            systemCurrencyId: Shopware.Context.app.systemCurrencyId ?? '',
14
            systemCurrencyISOCode: Shopware.Context.app.systemCurrencyISOCode ?? '',
15
        };
16
    });
17
18
    Shopware.ExtensionAPI.handle('contextEnvironment', () => {
19
        return Shopware.Context.app.environment ?? 'production';
20
    });
21
22
    Shopware.ExtensionAPI.handle('contextLanguage', () => {
23
        return {
24
            languageId: Shopware.Context.api.languageId ?? '',
25
            systemLanguageId: Shopware.Context.api.systemLanguageId ?? '',
26
        };
27
    });
28
29
    Shopware.ExtensionAPI.handle('contextLocale', () => {
30
        return {
31
            fallbackLocale: Shopware.Context.app.fallbackLocale ?? '',
32
            locale: Shopware.State.get('session').currentLocale ?? '',
33
        };
34
    });
35
36
    Shopware.ExtensionAPI.handle('contextShopwareVersion', () => {
37
        return Shopware.Context.app.config.version ?? '';
38
    });
39
40
    Shopware.ExtensionAPI.handle('contextModuleInformation', (_, additionalInformation) => {
41
        const extension = Object.values(Shopware.State.get('extensions'))
42
            .find(ext => ext.baseUrl.startsWith(additionalInformation._event_.origin));
43
44
        if (!extension) {
45
            return {
46
                modules: [],
47
            };
48
        }
49
50
        // eslint-disable-next-line max-len,@typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
51
        const modules = Shopware.State.getters['extensionSdkModules/getRegisteredModuleInformation'](extension.baseUrl) as Array< {
52
            displaySearchBar: boolean,
53
            heading: string,
54
            id: string,
55
            locationId: string
56
        }>;
57
58
        return {
59
            modules,
60
        };
61
    });
62
63
    Shopware.ExtensionAPI.handle('contextUserInformation', (_, { _event_ }) => {
64
        const appOrigin = _event_.origin;
65
        const extension = Object.entries(Shopware.State.get('extensions')).find((ext) => {
66
            return ext[1].baseUrl.startsWith(appOrigin);
67
        });
68
69
        if (!extension) {
70
            return Promise.reject(new Error(`Could not find a extension with the given event origin "${_event_.origin}"`));
71
        }
72
73
        if (!extension[1]?.permissions?.read?.includes('user')) {
74
            return Promise.reject(new Error(`Extension "${extension[0]}" does not have the permission to read users`));
75
        }
76
77
        const currentUser = Shopware.State.get('session').currentUser;
78
79
        return Promise.resolve({
80
            aclRoles: currentUser.aclRoles as unknown as Array<{
81
                name: string,
82
                type: string,
83
                id: string,
84
                privileges: Array<string>,
85
            }>,
86
            active: !!currentUser.active,
87
            admin: !!currentUser.admin,
88
            avatarId: currentUser.avatarId ?? '',
89
            email: currentUser.email ?? '',
90
            firstName: currentUser.firstName ?? '',
91
            id: currentUser.id ?? '',
92
            lastName: currentUser.lastName ?? '',
93
            localeId: currentUser.localeId ?? '',
94
            title: currentUser.title ?? '',
95
            // @ts-expect-error - type is not defined in entity directly
96
            type: (currentUser.type as unknown as string) ?? '',
97
            username: currentUser.username ?? '',
98
        });
99
    });
100
101
    Shopware.ExtensionAPI.handle('contextAppInformation', (_, { _event_ }) => {
102
        const appOrigin = _event_.origin;
103
        const extension = Object.entries(Shopware.State.get('extensions')).find((ext) => {
104
            return ext[1].baseUrl.startsWith(appOrigin);
105
        });
106
107
        if (!extension || !extension[0] || !extension[1]) {
108
            const type: 'app'|'plugin' = 'app';
109
110
            return {
111
                name: 'unknown',
112
                type: type,
113
                version: '0.0.0',
114
            };
115
        }
116
117
        return {
118
            name: extension[0],
119
            type: extension[1].type,
120
            version: extension[1].version ?? '',
121
        };
122
    });
123
124
    Shopware.State.watch((state) => {
125
        return {
126
            languageId: state.context.api.languageId,
127
            systemLanguageId: state.context.api.systemLanguageId,
128
        };
129
    }, ({ languageId, systemLanguageId }, { languageId: oldLanguageId, systemLanguageId: oldSystemLanguageId }) => {
130
        if (languageId === oldLanguageId && systemLanguageId === oldSystemLanguageId) {
131
            return;
132
        }
133
134
        void publish('contextLanguage', {
135
            languageId: languageId ?? '',
136
            systemLanguageId: systemLanguageId ?? '',
137
        });
138
    });
139
140
    Shopware.State.watch((state) => {
141
        return {
142
            fallbackLocale: state.context.app.fallbackLocale,
143
            locale: state.session.currentLocale,
144
        };
145
    }, ({ fallbackLocale, locale }, { fallbackLocale: oldFallbackLocale, locale: oldLocale }) => {
146
        if (fallbackLocale === oldFallbackLocale && locale === oldLocale) {
147
            return;
148
        }
149
150
        void publish('contextLocale', {
151
            locale: locale ?? '',
152
            fallbackLocale: fallbackLocale ?? '',
153
        });
154
    });
155
}
156