1
0
mirror of https://github.com/nicoverbruggen/phpmon.git synced 2026-04-05 18:50:08 +02:00

🚧 WIP: Add ContainerAccess macro

This commit is contained in:
2025-10-05 17:03:06 +02:00
parent 2e06b1a59e
commit 6227a6f2cc
9 changed files with 377 additions and 13 deletions

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>NVContainer.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>4</integer>
</dict>
</dict>
</dict>
</plist>

View File

@@ -0,0 +1,38 @@
// swift-tools-version: 5.9
import PackageDescription
import CompilerPluginSupport
let package = Package(
name: "NVContainer",
platforms: [.macOS(.v13)],
products: [
.library(
name: "NVContainer",
targets: ["NVContainer"]
),
],
dependencies: [
.package(url: "https://github.com/apple/swift-syntax.git", from: "509.0.0"),
],
targets: [
.macro(
name: "NVContainerMacros",
dependencies: [
.product(name: "SwiftSyntaxMacros", package: "swift-syntax"),
.product(name: "SwiftCompilerPlugin", package: "swift-syntax")
]
),
.target(
name: "NVContainer",
dependencies: ["NVContainerMacros"]
),
.testTarget(
name: "NVContainerTests",
dependencies: [
"NVContainerMacros",
.product(name: "SwiftSyntaxMacrosTestSupport", package: "swift-syntax"),
]
),
]
)

View File

@@ -0,0 +1,65 @@
# NVContainer Macro
A Swift macro for automatic container dependency injection in PHP Monitor.
## Usage
```swift
import NVContainer
// Expose all Container services
@ContainerAccess
class MyClass {
func doSomething() {
shell.run("command")
favorites.add(site)
warningManager.evaluateWarnings()
}
}
// Or expose only specific services
@ContainerAccess(["shell", "favorites"])
class AnotherClass {
func doSomething() {
shell.run("command")
favorites.add(site)
}
}
```
## What it generates
The `@ContainerAccess` macro automatically adds:
- A private `container: Container` property
- An `init(container:)` with default parameter `App.shared.container`
- Computed properties for each Container service you want to access
## Maintenance
When you add new services to `Container`, you must update the service list in:
**`Sources/NVContainerMacros/ContainerAccessMacro.swift`** (lines 14-18):
```swift
let allContainerServices: [(name: String, type: String)] = [
("shell", "ShellProtocol"),
("favorites", "Favorites"),
("warningManager", "WarningManager"),
// Add your new service here:
// ("myNewService", "MyServiceType"),
]
```
## Testing
Run tests with:
```bash
cd packages/container-macro
swift test
```
## Integration
The package is added as a local Swift Package in Xcode:
- File → Add Package Dependencies → Add Local...
- Select `packages/container-macro`

View File

@@ -0,0 +1,37 @@
/// Automatically adds container dependency injection to a class.
///
/// This macro generates:
/// - A private `container` property
/// - An `init(container:)` with a default parameter of `App.shared.container`
/// - Computed properties for Container services
///
/// Usage:
/// ```swift
/// import NVContainer
///
/// // Expose specific services:
/// @ContainerAccess(["shell", "favorites"])
/// class MyClass {
/// func doSomething() {
/// shell.run("command")
/// favorites.add(site)
/// }
/// }
///
/// // Or expose ALL Container services by omitting the array:
/// @ContainerAccess
/// class AnotherClass {
/// func doSomething() {
/// shell.run("command")
/// favorites.add(site)
/// warningManager.evaluateWarnings()
/// }
/// }
/// ```
///
/// - Parameter services: Optional array of service names to expose. If omitted, all Container services are exposed.
@attached(member, names: named(container), named(init(container:)), arbitrary)
public macro ContainerAccess(_ services: [String] = []) = #externalMacro(
module: "NVContainerMacros",
type: "ContainerAccessMacro"
)

View File

@@ -0,0 +1,92 @@
import SwiftCompilerPlugin
import SwiftSyntax
import SwiftSyntaxBuilder
import SwiftSyntaxMacros
public struct ContainerAccessMacro: MemberMacro {
public static func expansion(
of node: AttributeSyntax,
providingMembersOf declaration: some DeclGroupSyntax,
in context: some MacroExpansionContext
) throws -> [DeclSyntax] {
// Map of ALL Container properties to their types
// This should be kept in sync with the Container class
let allContainerServices: [(name: String, type: String)] = [
("shell", "ShellProtocol"),
("favorites", "Favorites"),
("warningManager", "WarningManager")
]
// Extract the service names from the macro arguments (if provided)
var requestedServices: [String]? = nil
if let argumentList = node.arguments?.as(LabeledExprListSyntax.self),
let firstArgument = argumentList.first,
let arrayExpr = firstArgument.expression.as(ArrayExprSyntax.self) {
requestedServices = arrayExpr.elements.compactMap { element -> String? in
guard let stringLiteral = element.expression.as(StringLiteralExprSyntax.self),
let segment = stringLiteral.segments.first?.as(StringSegmentSyntax.self) else {
return nil
}
return segment.content.text
}
}
// Determine which services to expose
let servicesToExpose: [(name: String, type: String)]
if let requested = requestedServices, !requested.isEmpty {
// Only expose the requested services
servicesToExpose = allContainerServices.filter { requested.contains($0.name) }
} else {
// No arguments provided - expose ALL services
servicesToExpose = allContainerServices
}
// Check if the class already has an initializer
let hasExistingInit = declaration.memberBlock.members.contains { member in
if let initDecl = member.decl.as(InitializerDeclSyntax.self) {
return true
}
return false
}
var members: [DeclSyntax] = []
// Add the container property
members.append(
"""
private let container: Container
"""
)
// Only add the initializer if one doesn't already exist
if !hasExistingInit {
members.append(
"""
init(container: Container = App.shared.container) {
self.container = container
}
"""
)
}
// Add computed properties for each service
for service in servicesToExpose {
members.append(
"""
private var \(raw: service.name): \(raw: service.type) {
return container.\(raw: service.name)
}
"""
)
}
return members
}
}
@main
struct NVContainerMacrosPlugin: CompilerPlugin {
let providingMacros: [Macro.Type] = [
ContainerAccessMacro.self,
]
}

View File

@@ -0,0 +1,106 @@
import SwiftSyntaxMacros
import SwiftSyntaxMacrosTestSupport
import XCTest
#if canImport(NVContainerMacros)
import NVContainerMacros
final class ContainerAccessMacroTests: XCTestCase {
let testMacros: [String: Macro.Type] = [
"ContainerAccess": ContainerAccessMacro.self,
]
func testContainerAccessWithSpecificServices() throws {
assertMacroExpansion(
"""
@ContainerAccess(["shell"])
class InternalSwitcher {
func doSomething() {
print("Hello")
}
}
""",
expandedSource: """
class InternalSwitcher {
func doSomething() {
print("Hello")
}
private let container: Container
init(container: Container = App.shared.container) {
self.container = container
}
private var shell: ShellProtocol {
return container.shell
}
}
""",
macros: testMacros
)
}
func testContainerAccessWithMultipleServices() throws {
assertMacroExpansion(
"""
@ContainerAccess(["shell", "favorites"])
class MyClass {
}
""",
expandedSource: """
class MyClass {
private let container: Container
init(container: Container = App.shared.container) {
self.container = container
}
private var shell: ShellProtocol {
return container.shell
}
private var favorites: Favorites {
return container.favorites
}
}
""",
macros: testMacros
)
}
func testContainerAccessWithAllServices() throws {
assertMacroExpansion(
"""
@ContainerAccess
class MyClass {
}
""",
expandedSource: """
class MyClass {
private let container: Container
init(container: Container = App.shared.container) {
self.container = container
}
private var shell: ShellProtocol {
return container.shell
}
private var favorites: Favorites {
return container.favorites
}
private var warningManager: WarningManager {
return container.warningManager
}
}
""",
macros: testMacros
)
}
}
#endif