1
0
mirror of https://github.com/nicoverbruggen/phpmon.git synced 2025-08-07 03:50:08 +02:00

♻️ Refactor ActivePhpInstallation

This commit is contained in:
2022-09-09 22:18:52 +02:00
parent 6ddddc744a
commit f02e45486e
15 changed files with 52 additions and 64 deletions

View File

@ -41,7 +41,7 @@ class Actions {
]
PhpEnv.shared.availablePhpVersions.forEach { version in
let formula = version == PhpEnv.brewPhpVersion
let formula = version == PhpEnv.brewPhpAlias
? "php"
: "php@\(version)"
servicesCommands.append("\(Paths.brew) services stop \(formula)")
@ -144,7 +144,7 @@ class Actions {
extensions and/or run `composer global update`.
*/
public static func fixMyValet(completed: @escaping () -> Void) {
InternalSwitcher().performSwitch(to: PhpEnv.brewPhpVersion, completion: {
InternalSwitcher().performSwitch(to: PhpEnv.brewPhpAlias, completion: {
brew("services restart dnsmasq", sudo: true)
brew("services restart php", sudo: true)
brew("services restart nginx", sudo: true)

View File

@ -17,11 +17,12 @@ import Foundation
Using `version.short` is advisable if you want to interact with Homebrew.
*/
class ActivePhpInstallation {
var version: Version!
var version: PhpVersionNumber!
var limits: Limits!
var iniFiles: [PhpConfigurationFile] = []
var hasErrorState: Bool = false
var extensions: [PhpExtension] {
return iniFiles.flatMap { initFile in
return initFile.extensions
@ -31,20 +32,20 @@ class ActivePhpInstallation {
// MARK: - Computed
var formula: String {
return (version.short == PhpEnv.brewPhpVersion) ? "php" : "php@\(version.short)"
return (version.short == PhpEnv.brewPhpAlias) ? "php" : "php@\(version.short)"
}
// MARK: - Initializer
init() {
// Show information about the current version
getVersion()
determineVersion()
// Initialize the list of ini files that are loaded
iniFiles = []
// If an error occurred, exit early
if version.error {
if self.hasErrorState {
limits = Limits()
return
}
@ -81,26 +82,11 @@ class ActivePhpInstallation {
When the app tries to retrieve the version, the installation is considered broken if the output is nothing,
_or_ if the output contains the word "Warning" or "Error". In normal situations this should not be the case.
*/
private func getVersion() {
self.version = Version()
private func determineVersion() {
let output = Command.execute(path: Paths.phpConfig, arguments: ["--version"], trimNewlines: true)
let version = Command.execute(path: Paths.phpConfig, arguments: ["--version"], trimNewlines: true)
if version == "" || version.contains("Warning") || version.contains("Error") {
self.version.short = "💩 BROKEN"
self.version.long = ""
self.version.error = true
return
}
// That's the long version
self.version.long = version
// Next up, let's strip away the minor version number
let segments = self.version.long.components(separatedBy: ".")
// Get the first two elements
self.version.short = segments[0...1].joined(separator: ".")
self.hasErrorState = (output == "" || output.contains("Warning") || output.contains("Error"))
self.version = PhpVersionNumber.make(from: output)
}
/**
@ -152,18 +138,6 @@ class ActivePhpInstallation {
// MARK: - Structs
/**
Struct containing information about the version number of the current PHP installation.
Also includes information about whether the install is considered "broken" or not.
If an error was found in the terminal output, `error` is set to `true` and the installation
can be considered broken. (The app will display this as well.)
*/
struct Version {
var short = "???"
var long = "???"
var error = false
}
/**
Struct containing information about the limits of the current PHP installation.
Includes: memory limit, max upload size and max post size.

View File

@ -54,7 +54,7 @@ class PhpEnv {
As such, we take that information from Homebrew.
*/
static var brewPhpVersion: String {
static var brewPhpAlias: String {
return Self.shared.homebrewPackage.version
}

View File

@ -106,7 +106,11 @@ public struct PhpVersionNumber: Equatable, Hashable {
return patch ?? (strictFallback ? 0 : constraint?.patch ?? 999)
}
public var homebrewVersion: String {
public var long: String {
return "\(major).\(minor).\(patch ?? 0)"
}
public var short: String {
return "\(major).\(minor)"
}

View File

@ -57,7 +57,7 @@ class InternalSwitcher: PhpSwitcher {
let isolated = Valet.shared.sites.filter { site in
site.isolatedPhpVersion != nil
}.map { site in
return site.isolatedPhpVersion!.versionNumber.homebrewVersion
return site.isolatedPhpVersion!.versionNumber.short
}
var versions: Set<String> = [primary]
@ -95,14 +95,14 @@ class InternalSwitcher: PhpSwitcher {
}
func stopPhpVersion(_ version: String) {
let formula = (version == PhpEnv.brewPhpVersion) ? "php" : "php@\(version)"
let formula = (version == PhpEnv.brewPhpAlias) ? "php" : "php@\(version)"
brew("unlink \(formula)")
brew("services stop \(formula)", sudo: true)
Log.info("Unlinked and stopped services for \(formula)")
}
func startPhpVersion(_ version: String, primary: Bool) {
let formula = (version == PhpEnv.brewPhpVersion) ? "php" : "php@\(version)"
let formula = (version == PhpEnv.brewPhpAlias) ? "php" : "php@\(version)"
if primary {
Log.info("\(formula) is the primary formula, linking and starting services...")

View File

@ -65,14 +65,19 @@ class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDele
override init() {
logger.verbosity = .info
#if DEBUG
// logger.verbosity = .performance
logger.verbosity = .performance
#endif
if CommandLine.arguments.contains("--v") {
logger.verbosity = .performance
Log.info("Extra verbose mode has been activated.")
}
Log.separator(as: .info)
Log.info("PHP MONITOR by Nico Verbruggen")
#if SPONSOR
Log.info("PHP MONITOR SE by Nico Verbruggen")
#else
Log.info("PHP MONITOR by Nico Verbruggen")
#endif
Log.info("Version \(App.version)")
Log.separator(as: .info)
self.sharedShell = Shell.user

View File

@ -59,7 +59,7 @@ class DomainListPhpCell: NSTableCellView, DomainListCellProtocol {
}
return PhpEnv.shared.validVersions(for: site.composerPhp).filter({ version in
version.homebrewVersion != PhpEnv.phpInstall.version.short
version.short != PhpEnv.phpInstall.version.short
})
}

View File

@ -89,13 +89,13 @@ class HomebrewDiagnostics {
from: tapAlias.data(using: .utf8)!
).first!
if tapPhp.version != PhpEnv.brewPhpVersion {
if tapPhp.version != PhpEnv.brewPhpAlias {
Log.warn("The `php` formula alias seems to be the different between the tap and core. "
+ "This could be a problem!")
Log.info("Determining whether both of these versions are installed...")
let bothInstalled = PhpEnv.shared.availablePhpVersions.contains(tapPhp.version)
&& PhpEnv.shared.availablePhpVersions.contains(PhpEnv.brewPhpVersion)
&& PhpEnv.shared.availablePhpVersions.contains(PhpEnv.brewPhpAlias)
if bothInstalled {
Log.warn("Both conflicting aliases seem to be installed, warning the user!")

View File

@ -38,7 +38,7 @@ extension ValetSite {
self.composerPhpCompatibleWithLinked = self.composerPhp.split(separator: "|")
.map { string in
let origin = self.isolatedPhpVersion?.versionNumber.homebrewVersion ?? PhpEnv.phpInstall.version.long
let origin = self.isolatedPhpVersion?.versionNumber.short ?? PhpEnv.phpInstall.version.long
return !PhpVersionNumberCollection.make(from: [origin])
.matching(constraint: string.trimmingCharacters(in: .whitespacesAndNewlines))
.isEmpty

View File

@ -55,7 +55,7 @@ class ValetSite: DomainListable {
/// Which version of PHP is actually used to serve this site.
var servingPhpVersion: String {
return self.isolatedPhpVersion?.versionNumber.homebrewVersion
return self.isolatedPhpVersion?.versionNumber.short
?? PhpEnv.phpInstall.version.short
}
@ -144,7 +144,7 @@ class ValetSite: DomainListable {
// For example, for Laravel 8 projects the value is "^7.3|^8.0"
self.composerPhpCompatibleWithLinked = self.composerPhp.split(separator: "|")
.map { string in
let origin = self.isolatedPhpVersion?.versionNumber.homebrewVersion ?? PhpEnv.phpInstall.version.long
let origin = self.isolatedPhpVersion?.versionNumber.short ?? PhpEnv.phpInstall.version.long
return !PhpVersionNumberCollection.make(from: [origin])
.matching(constraint: string.trimmingCharacters(in: .whitespacesAndNewlines))
.isEmpty

View File

@ -208,7 +208,7 @@ extension MainMenu {
}
@objc func openActiveConfigFolder() {
if PhpEnv.phpInstall.version.error {
if PhpEnv.phpInstall.hasErrorState {
Actions.openGenericPhpConfigFolder()
return
}

View File

@ -14,7 +14,7 @@ extension MainMenu {
@MainActor @objc func fixMyValet() {
let previousVersion = PhpEnv.phpInstall.version.short
if !PhpEnv.shared.availablePhpVersions.contains(PhpEnv.brewPhpVersion) {
if !PhpEnv.shared.availablePhpVersions.contains(PhpEnv.brewPhpAlias) {
presentAlertForMissingFormula()
return
}
@ -22,7 +22,7 @@ extension MainMenu {
if !BetterAlert()
.withInformation(
title: "alert.fix_my_valet.title".localized,
subtitle: "alert.fix_my_valet.info".localized(PhpEnv.brewPhpVersion)
subtitle: "alert.fix_my_valet.info".localized(PhpEnv.brewPhpAlias)
)
.withPrimary(text: "alert.fix_my_valet.ok".localized)
.withSecondary(text: "alert.fix_my_valet.cancel".localized)
@ -33,7 +33,7 @@ extension MainMenu {
Actions.fixMyValet {
DispatchQueue.main.async {
if previousVersion == PhpEnv.brewPhpVersion {
if previousVersion == PhpEnv.brewPhpAlias {
self.presentAlertForSameVersion()
} else {
self.presentAlertForDifferentVersion(version: previousVersion)
@ -74,7 +74,7 @@ extension MainMenu {
alert.close(with: .alertSecondButtonReturn)
MainMenu.shared.switchToPhpVersion(version)
})
.withSecondary(text: "alert.fix_my_valet_done.stay".localized(PhpEnv.brewPhpVersion))
.withSecondary(text: "alert.fix_my_valet_done.stay".localized(PhpEnv.brewPhpAlias))
.withTertiary(text: "", action: { _ in
NSWorkspace.shared.open(Constants.Urls.FrequentlyAskedQuestions)
})

View File

@ -90,7 +90,12 @@ extension MainMenu {
// Update the stats
Stats.incrementSuccessfulLaunchCount()
Stats.evaluateSponsorMessageShouldBeDisplayed()
#if SPONSOR
Log.info("Sponsor encouragement messages are omitted in SE builds.")
#else
Stats.evaluateSponsorMessageShouldBeDisplayed()
#endif
// Present first launch screen if needed
if Stats.successfulLaunchCount == 0 && !isRunningSwiftUIPreview {

View File

@ -13,13 +13,13 @@ import Cocoa
extension StatusMenu {
func addPhpVersionMenuItems() {
if PhpEnv.phpInstall.version.error {
if PhpEnv.phpInstall.hasErrorState {
let brokenMenuItems = ["mi_php_broken_1", "mi_php_broken_2", "mi_php_broken_3", "mi_php_broken_4"]
return addItems(brokenMenuItems.map { NSMenuItem(title: $0.localized) })
}
addItem(HeaderView.asMenuItem(
text: "\("mi_php_version".localized) \(PhpEnv.phpInstall.version.long)")
text: "\("mi_php_version".localized) \(PhpEnv.phpInstall.version.toString())")
)
}
@ -58,7 +58,7 @@ extension StatusMenu {
let versionString = long ? longVersion.toString() : shortVersion
let action = #selector(MainMenu.switchToPhpVersion(sender:))
let brew = (shortVersion == PhpEnv.brewPhpVersion) ? "php" : "php@\(shortVersion)"
let brew = (shortVersion == PhpEnv.brewPhpAlias) ? "php" : "php@\(shortVersion)"
let menuItem = PhpMenuItem(
title: "\("mi_php_switch".localized) \(versionString) (\(brew))",
action: (shortVersion == PhpEnv.phpInstall.version.short)
@ -254,7 +254,7 @@ extension StatusMenu {
NSMenuItem(title: "mi_view_onboarding".localized, action: #selector(MainMenu.showWelcomeTour)),
NSMenuItem(title: "mi_fa_php_doctor".localized, action: #selector(MainMenu.openWarnings)),
NSMenuItem.separator(),
NSMenuItem(title: "mi_fix_my_valet".localized(PhpEnv.brewPhpVersion),
NSMenuItem(title: "mi_fix_my_valet".localized(PhpEnv.brewPhpAlias),
action: #selector(MainMenu.fixMyValet),
toolTip: "mi_fix_my_valet_tooltip".localized),
NSMenuItem(title: "mi_fix_brew_permissions".localized(), action: #selector(MainMenu.fixHomebrewPermissions),

View File

@ -34,8 +34,8 @@ struct VersionPopoverView: View {
)
HStack {
ForEach(validPhpVersions, id: \.self) { version in
Button("site_link.switch_to_php".localized(version.homebrewVersion), action: {
MainMenu.shared.switchToPhpVersion(version.homebrewVersion)
Button("site_link.switch_to_php".localized(version.short), action: {
MainMenu.shared.switchToPhpVersion(version.short)
parent?.close()
})
}
@ -88,7 +88,7 @@ struct VersionPopoverView: View {
if site.isolatedPhpVersion != nil {
information += "alert.composer_php_isolated.desc".localized(
site.isolatedPhpVersion!.versionNumber.homebrewVersion,
site.isolatedPhpVersion!.versionNumber.short,
PhpEnv.phpInstall.version.short
)
information += "\n\n"