Completed
Push — main ( d77b46...305f9c )
by Bjarn
17s queued 11s
created

UseController.switchPhpVersionTo   B

Complexity

Conditions 5

Size

Total Lines 39
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 32
dl 0
loc 39
rs 8.6453
c 0
b 0
f 0
1
import {client} from '../utils/os'
2
import {getLinkedPhpVersion, getPhpFpmByName, supportedPhpVersions} from '../utils/phpFpm'
3
4
class UseController {
5
6
    /**
7
     * Switch the service to the given version.
8
     */
9
    execute = async (service: string, version: string): Promise<boolean> => {
10
        switch (service) {
11
        case 'php':
12
            console.log(`Switching to PHP ${version}`)
13
            await this.switchPhpVersionTo(version)
14
            return true
15
        default:
16
            console.log('Invalid service.')
17
            return false
18
        }
19
    }
20
21
    /**
22
     * Switch the active PHP version to the provided phpVersion string.
23
     * @param phpVersion
24
     */
25
    switchPhpVersionTo = async (phpVersion: string): Promise<void> => {
26
        const currentPhpVersion = await getLinkedPhpVersion()
27
28
        if (!supportedPhpVersions.includes(phpVersion)) {
29
            throw Error(`Invalid PHP version. Please pick one of the following version: ${supportedPhpVersions.join(', ')}`)
30
        }
31
32
        if (currentPhpVersion.versionName === phpVersion) {
33
            console.log(`PHP ${phpVersion} is already active.`)
34
            return
35
        }
36
37
        const newPhpVersion = getPhpFpmByName(`php@${phpVersion}`)
38
39
        if (newPhpVersion.isEndOfLife) {
40
            console.warn('This PHP version is End Of Life. Be aware it might contain security flaws.')
41
            console.warn('Please check http://php.net/supported-versions.php for more information.')
42
        }
43
44
        // Make sure the PHP version is installed.
45
        const isVersionInstalled = await client().packageManager.packageIsInstalled(newPhpVersion.service)
46
47
        if (!isVersionInstalled) {
48
            console.log(`Installing PHP ${newPhpVersion.versionName}`)
49
            await client().packageManager.install(newPhpVersion.service, false)
50
            console.log(`Configuring PHP ${newPhpVersion.versionName}`)
51
            await newPhpVersion.configure()
52
        }
53
54
        await currentPhpVersion.unLinkPhpVersion()
55
56
        // TODO: Relink some libs like libjpeg etc.
57
58
        await newPhpVersion.linkPhpVersion()
59
60
        await currentPhpVersion.stop()
61
        await newPhpVersion.start()
62
63
        console.log(`Successfully switched to PHP ${newPhpVersion.versionName}`)
64
    }
65
66
}
67
68
export default UseController