[Improvement] Naming of libraries and package (#22)

This PR contains the work done to fix the naming of the libraries and the package, along with tweaks to the folder structure.

Reviewed-on: #22
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit was merged in pull request #22.
This commit is contained in:
2023-08-13 21:53:47 +00:00
committed by Javier Cicchelli
parent 060d8a84a9
commit e6e82b3b40
54 changed files with 65 additions and 53 deletions
@@ -0,0 +1,122 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// This class overrides the `URLProtocol` protocol used by the `URLSession` to handle the loading of protocol-specific URL data so it is possible to mock URL response for testing purposes.
public class MockURLProtocol: URLProtocol {
// MARK: Properties
/// The dictionary in which the mock requests with its respective mock responses will be injected.
public static var mockData: [MockURLRequest: MockURLResponse] = [:]
// MARK: Functions
public override class func canInit(with task: URLSessionTask) -> Bool {
true
}
public override class func canInit(with request: URLRequest) -> Bool {
true
}
public override class func canonicalRequest(for request: URLRequest) -> URLRequest {
request
}
public override func startLoading() {
guard
let httpMethod = request.httpMethod,
let method = HTTPRequestMethod(rawValue: httpMethod),
let url = request.url,
let response = Self.mockData[.init(
method: method,
url: url
)]
else {
client?.urlProtocolDidFinishLoading(self)
return
}
if let data = response.data {
client?.urlProtocol(self, didLoad: data)
}
if let httpResponse = HTTPURLResponse(
url: url,
statusCode: response.status.rawValue,
httpVersion: nil,
headerFields: response.headers
) {
client?.urlProtocol(
self,
didReceive: httpResponse,
cacheStoragePolicy: .allowedInMemoryOnly
)
}
client?.urlProtocolDidFinishLoading(self)
}
public override func stopLoading() {}
}
// MARK: - Structs
/// This model includes the data to be injected into an specific URL at the time of mocking its request.
public struct MockURLRequest: Hashable {
// MARK: Properties
public let method: HTTPRequestMethod
public let url: URL
// MARK: Initialisers
public init(
method: HTTPRequestMethod,
url: URL
) {
self.method = method
self.url = url
}
}
/// This model includes the data to be injected into an specific URL at the time of mocking its response.
public struct MockURLResponse {
// MARK: Properties
public let status: HTTPResponseCode
public let headers: [String: String]
public let data: Data?
// MARK: Initialisers
public init(
status: HTTPResponseCode,
headers: [String : String] = [:],
data: Data? = nil
) {
self.status = status
self.headers = headers
self.data = data
}
}
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// Enumeration that represents the available HTTP request methods to use in this library.
public enum HTTPRequestMethod: String {
/// Establishes a tunnel to the service identified by the target resource.
case connect = "CONNECT"
/// Deletes the specified resource.
case delete = "DELETE"
/// Asks for a response identical to a GET request, but without the response body.
case head = "HEAD"
/// Requests a representation of the specified resource, which should only retrieve data.
case get = "GET"
/// Describes the communication options for the target resource.
case options = "OPTIONS"
/// Applies partial modifications to a resource.
case patch = "PATCH"
/// Submits an entity to the specified resource, often causing a change of state or side effect on the server.
case post = "POST"
/// Replaces all current representations of the target resource with the request payload.
case put = "PUT"
/// Performs a message loop-back test along the path to the target resource.
case trace = "TRACE"
}
@@ -0,0 +1,213 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public enum HTTPResponseCode: Int {
// MARK: Information
/// This interim response indicates that the client should continue the request or ignore the response if the request is already finished.
case `continue` = 100
/// This code is sent in response to an Upgrade request header from the client and indicates the protocol the server is switching to.
case switchingProtocols = 101
/// *[WebDAV]* This code indicates that the server has received and is processing the request, but no response is available yet.
case processing = 102
/// This status code is primarily intended to be used with the Link header, letting the user agent start preloading resources while the server prepares a response.
case earlyHints = 103
// MARK: Success
/// The request succeeded.
case ok = 200
/// The request, succeeded, and a new resource was created as a result as this is usually used in **POST** and **PUT** requests.
case created = 201
/// The request has been received but not yet acted upon, as no later asynchronous message will be sent indicating the outcome of the request. This is intended for cases where another server handles the request, or for batch processing.
case accepted = 202
/// The returned metadata is not exactly the same as is available from the origin server, but is collected from a local or 3rd party copy. This is intended to be used for mirrors or backups of another resource.
case nonAuthoritativeInformation = 203
/// No content to send for this request, but the headers may be useful, as the user agent may update its cached header for this resource for new ones.
case noContent = 204
/// Tells the user agent to reset the document which sent this request.
case resetContent = 205
/// Used when the **Range** header is sent from the client to request only part of a resource.
case partialContent = 206
/// *[WebDAV]* Conveys information about multiple resources, for situation where multiple status codes might be appropriate.
case multiStatus = 207
/// *[WebDAV]* Avoids repeatedly enumerating the internal numbers of multiple bindings to the same collection, as it is used inside a `dav:prostat` response element.
case alreadyReported = 208
/// *[HTTP delta encoding]* Indicates the server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.
case imUsed = 226
// MARK: Redirection
/// The request has more than one possible response. The user agent or user should choose one of them. (There is no standardized way of choosing one of the responses, but HTML links to the possibilities are recommended so the user can pick.)
case multipleChoices = 300
/// The URL of the requested resource has been changed permanently. The new URL is given in the response.
case movedPermanetly = 301
/// This response code means that the URI of requested resource has been changed temporarily. Further changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests.
case found = 302
/// The server sent this response to direct the client to get the requested resource at another URI with a GET request.
case seeOther = 303
/// This is used for caching purposes. It tells the client that the response has not been modified, so the client can continue to use the same cached version of the response.
case notModified = 304
/// Defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy.
case useProxy = 305
/// This response code is no longer used; it is just reserved. It was used in a previous version of the HTTP/1.1 specification.
case unused = 306
/// The server sends this response to direct the client to get the requested resource at another URI with the same method that was used in the prior request. This has the same semantics as the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
case temporaryRedirect = 307
/// This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request.
case permanentRedirect = 308
// MARK: Client error
/// The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
case badRequest = 400
/// Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response.
case unauthorized = 401
/// This response code is reserved for future use. The initial aim for creating this code was using it for digital payment systems, however this status code is used very rarely and no standard convention exists.
case paymentRequired = 402
/// The client does not have access rights to the content; that is, it is unauthorized, so the server is refusing to give the requested resource. Unlike 401 Unauthorized, the client's identity is known to the server.
case forbidden = 403
/// The server cannot find the requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 Forbidden to hide the existence of a resource from an unauthorized client. This response code is probably the most well known due to its frequent occurrence on the web.
case notFound = 404
/// The request method is known by the server but is not supported by the target resource. For example, an API may not allow calling DELETE to remove a resource.
case methodNotAllowed = 405
/// This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.
case notAcceptable = 406
/// This is similar to 401 Unauthorized but authentication is needed to be done by a proxy.
case proxyAuthenticationRequired = 407
/// This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message.
case requestTimeout = 408
/// This response is sent when a request conflicts with the current state of the server.
case conflict = 409
/// This response is sent when the requested content has been permanently deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code.
case gone = 410
/// Server rejected the request because the Content-Length header field is not defined and the server requires it.
case lengthRequired = 411
/// The client has indicated preconditions in its headers which the server does not meet.
case preconditionFailed = 412
/// Request entity is larger than limits defined by server. The server might close the connection or return an Retry-After header field.
case payloadTooLarge = 413
/// The URI requested by the client is longer than the server is willing to interpret.
case uriTooLong = 414
/// The media format of the requested data is not supported by the server, so the server is rejecting the request.
case unsupportedMediaType = 415
/// The range specified by the Range header field in the request cannot be fulfilled. It's possible that the range is outside the size of the target URI's data.
case rangeNotSatisfiable = 416
/// This response code means the expectation indicated by the Expect request header field cannot be met by the server.
case expectationFailed = 417
/// The server refuses the attempt to brew coffee with a teapot.
case imATeapot = 418
/// The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
case misdirectedRequest = 421
/// *[WebDAV]* The request was well-formed but was unable to be followed due to semantic errors.
case unprocessableContent = 422
/// *[WebDAV]* The resource that is being accessed is locked.
case locked = 423
/// *[WebDAV]* The request failed due to failure of a previous request.
case failedDependency = 424
/// Indicates that the server is unwilling to risk processing a request that might be replayed.
case tooEarly = 425
/// The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server sends an Upgrade header in a 426 response to indicate the required protocol(s).
case upgradeRequired = 426
/// The origin server requires the request to be conditional. This response is intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
case preconditionRequired = 428
/// The user has sent too many requests in a given amount of time ("rate limiting").
case tooManyRequests = 429
/// The server is unwilling to process the request because its header fields are too large. The request may be resubmitted after reducing the size of the request header fields.
case requestHeaderFieldsTooLarge = 431
/// The user agent requested a resource that cannot legally be provided, such as a web page censored by a government.
case unavailableForLegalReasons = 451
// MARK: Server error
/// The server has encountered a situation it does not know how to handle.
case internalServerError = 500
/// The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.
case notImplemented = 501
/// This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.
case badGateway = 502
/// The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This response should be used for temporary conditions and the Retry-After HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.
case serviceUnavailable = 503
/// This error response is given when the server is acting as a gateway and cannot get a response in time.
case gatewayTimeout = 504
/// The HTTP version used in the request is not supported by the server.
case httpVersionNotSupported = 505
/// The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
case variantAlsoNegotiates = 506
/// *[WebDAV]* The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request.
case insufficientStorage = 507
/// *[WebDAV]* The server detected an infinite loop while processing the request.
case loopDetected = 508
/// Further extensions to the request are required for the server to fulfill it.
case notExtended = 510
/// Indicates that the client needs to authenticate to gain network access.
case networkAuthenticationRequired = 511
}
@@ -0,0 +1,17 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// Errors generated out of the `MakeURLRequestUseCase` use case.
public enum MakeURLRequestError: Error {
/// An expected URL was not created.
case urlNotCreated
}
@@ -0,0 +1,30 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// This protocol defines a client that will be making the remote calls.
public protocol Client {
// MARK: Functions
/// Makes a request to a remote location based on a given endpoint and expects to return a response casted as a given model type.
/// - Parameters:
/// - endpoint: The endpoint for which to make a remote call.
/// - model: The model to cast an expected response from the remote location.
/// - Returns: A casted model instance created out of a response retrieved from a call to a remote endpoint.
func request<Model: Decodable>(
endpoint: some Endpoint,
as model: Model.Type
) async throws -> Model
}
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// This protocol defines an endpoint to be used in a remote call.
public protocol Endpoint {
// MARK: Type aliases
typealias Parameters = [String : String?]
typealias Headers = [String : String]
// MARK: Properties
/// The scheme subcomponent for the endpoint.
var scheme: String { get }
/// The host subcomponent for the endpoint.
var host: String { get }
/// The port subcomponent for the component.
var port: Int? { get }
/// The path subcomponent for the endpoint.
var path: String { get }
/// The query parameter subcomponents for the endpoint.
var parameters: Parameters { get }
/// The HTTP request method for the endpoint.
var method: HTTPRequestMethod { get }
/// The HTTP header fields as a dictionary for the endpoint.
var headers: Headers { get }
/// The message body as data for a request.
var body: Data? { get }
}
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
/// This use case generate a url request out of a given endpoint.
public struct MakeURLRequestUseCase {
// MARK: Initialisers
public init() {}
// MARK: Functions
/// Generate a `URLRequest` instance out of a given endpoint that conforms to the `Endpoint` protocol.
/// - Parameter endpoint: An endpoint which is used to generate a `URLRequest` instance from.
/// - Returns: A `URLRequest` instance filled with data provided by the given endpoint.
public func callAsFunction(endpoint: some Endpoint) throws -> URLRequest {
var urlComponents = URLComponents()
urlComponents.scheme = endpoint.scheme
urlComponents.host = endpoint.host
urlComponents.path = endpoint.path
if let port = endpoint.port {
urlComponents.port = port
}
if !endpoint.parameters.isEmpty {
urlComponents.queryItems = endpoint.parameters
.map(URLQueryItem.init)
.sorted(by: { $0.name < $1.name })
}
guard let url = urlComponents.url else {
throw MakeURLRequestError.urlNotCreated
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = endpoint.method.rawValue
urlRequest.httpBody = endpoint.body
urlRequest.allHTTPHeaderFields = endpoint.headers
return urlRequest
}
}
@@ -0,0 +1,80 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// This protocol organize the flow logic between view controllers in the app.
public protocol Coordinator: AnyObject {
// MARK: Properties
/// The child coordinators that are being currently presented.
var children: [Coordinator] { get set }
/// The router that handles how the view controllers in the coordinators will be shown or dismissed.
var router: Router { get }
// MARK: Functions
/// Present the coordinator animatedly or not, depending on the given `animated` parameter, and also pass a closure that should be called on dismissal.
/// - Parameters:
/// - animated: A boolean that represents whether the coordinator should be dismissed animatedly or not.
/// - onDismiss: A closure to be called or executed when the presented coordinator is dismissed.
func present(animated: Bool, onDismiss: Router.OnDismissedClosure?)
}
// MARK: - Coordinator+Implementations
public extension Coordinator {
/// Present a child coordinator animatedly or not, depending on the given `animated` parameter, and also pass a closure that should be called on dismissal.
/// - Parameters:
/// - child: A child coordinator to be presented.
/// - animated: A boolean that represents whether the coordinator should be dismissed animatedly or not.
/// - onDismiss: A closure to be called or executed when the presented coordinator is dismissed.
func present(
child: Coordinator,
animated: Bool,
onDismiss: Router.OnDismissedClosure? = nil
) {
store(child)
child.present(animated: animated) { [weak self, weak child] in
guard let self, let child else {
return
}
self.free(child)
onDismiss?()
}
}
/// Dismiss the coordinator animatedly or not, depending on the given `animated` parameter.
/// - Parameter animated: A boolean that represents whether the coordinator should be dismissed animatedly or not.
func dismiss(animated: Bool) {
router.dismiss(animated: animated)
}
}
// MARK: - Helpers
private extension Coordinator {
// MARK: Functions
func store(_ coordinator: Coordinator) {
children.append(coordinator)
}
func free(_ coordinator: Coordinator) {
children = children.filter { $0 !== coordinator }
}
}
@@ -0,0 +1,65 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if canImport(UIKit) && !os(watchOS)
import UIKit
#endif
/// This protocol defines how view controllers will be shown and dismissed.
public protocol Router: AnyObject {
// MARK: Type aliases
typealias OnDismissedClosure = () -> Void
// MARK: Functions
#if canImport(UIKit) && !os(watchOS)
/// Present a view controller animatedly or not, depending on the given `animated` parameter, and also pass a closure that should be called on dismissal.
/// - Parameters:
/// - viewController: A `UIViewController` view controller instance to present.
/// - animated: A boolean that represents whether the view controller should be dismissed animatedly or not.
/// - onDismiss: A closure to be called or executed when the presented view controller is dismissed.
func present(
_ viewController: UIViewController,
animated: Bool,
onDismiss: OnDismissedClosure?
)
#endif
/// Dismiss a view controller animatedly or not, depending on the given `animated` parameter.
/// - Parameter animated: A boolean that represents whether the view controller should be dismissed animatedly or not.
func dismiss(animated: Bool)
}
#if canImport(UIKit) && !os(watchOS)
// MARK: - Router+Implementations
public extension Router {
// MARK: Functions
/// Present a view controller animatedly or not, depending on the given `animated` parameter.
/// - Parameters:
/// - viewController: A `UIViewController` view controller instance to present.
/// - animated: A boolean that represents whether the view controller should be dismissed animatedly or not.
func present(_ viewController: UIViewController, animated: Bool) {
present(
viewController,
animated: animated,
onDismiss: nil
)
}
}
#endif
@@ -0,0 +1,74 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if os(iOS)
import UIKit
/// This is a base class for the `NavigationRouter` concrete router implementations.
public class BaseNavigationRouter: NSObject {
// MARK: Properties
/// A navigation controller to use within this concrete router.
var navigationController: UINavigationController
/// Dictionary that persist `onDismiss` closure for its respective view controllers until one of the later is dismissed.
var onDismissForViewController: [UIViewController: Router.OnDismissedClosure] = [:]
// MARK: Initialisers
/// Initialise this router.
/// - Parameter navigationController: A `UINavigationController` navigation controller instance to use in this router.
init(navigationController: UINavigationController) {
self.navigationController = navigationController
super.init()
self.navigationController.delegate = self
}
// MARK: Functions
/// Executes the `onDismiss` closure for a given view controller.
/// - Parameter viewController: A `UIViewController` view controller instance for which the on dismiss closure will be executed.
func performOnDismissed(for viewController: UIViewController) {
guard let onDismiss = onDismissForViewController[viewController] else {
return
}
onDismiss()
onDismissForViewController[viewController] = nil
}
}
// MARK: - UINavigationControllerDelegate
extension BaseNavigationRouter: UINavigationControllerDelegate {
// MARK: Functions
public func navigationController(
_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool
) {
guard let dismissedViewController = navigationController.transitionCoordinator?.viewController(forKey: .from) else {
return
}
performOnDismissed(for: dismissedViewController)
}
}
#endif
@@ -0,0 +1,92 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if os(iOS)
import UIKit
/// This class is responsible for showing view controllers modally, as it is a concrete implementation of the `Router` protocol.
public class ModalNavigationRouter: BaseNavigationRouter {
// MARK: Properties
/// The parent view controller from where this router is being called from.
public unowned let parentViewController: UIViewController
// MARK: Initialisers
/// Initialise this router.
/// - Parameter parentViewController: A `UIViewController` view controller instance from where this router is originated.
public init(parentViewController: UIViewController) {
self.parentViewController = parentViewController
super.init(navigationController: .init())
}
}
extension ModalNavigationRouter: Router {
public func present(
_ viewController: UIViewController,
animated: Bool,
onDismiss: OnDismissedClosure?
) {
onDismissForViewController[viewController] = onDismiss
if navigationController.viewControllers.isEmpty {
presentModally(viewController, animated: animated)
} else {
navigationController.pushViewController(viewController, animated: animated)
}
}
public func dismiss(animated: Bool) {
guard let firstViewController = navigationController.viewControllers.first else {
return
}
performOnDismissed(for: firstViewController)
parentViewController.dismiss(animated: animated)
}
}
// MARK: - Helpers
private extension ModalNavigationRouter {
// MARK: Functions
func presentModally(_ viewController: UIViewController, animated: Bool) {
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(
title: "Cancel",
style: .plain,
target: self,
action: #selector(onCancelPressed)
)
navigationController.setViewControllers([viewController], animated: false)
parentViewController.present(navigationController, animated: animated)
}
@objc func onCancelPressed() {
guard let firstViewController = navigationController.viewControllers.first else {
return
}
performOnDismissed(for: firstViewController)
dismiss(animated: true)
}
}
#endif
@@ -0,0 +1,70 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if os(iOS)
import UIKit
/// This class is responsible for pushing view controllers into a navigation controller, as it is a concrete implementation of the `Router` protocol.
public class PushNavigationRouter: BaseNavigationRouter {
// MARK: Properties
/// A root view controller coming in from the navigation controller, if any.
private let rootViewController: UIViewController?
// MARK: Initialisers
/// Initialise this router.
/// - Parameters:
/// - navigationController: A `UINavigationController` navigation controller instance to use in this router.
/// - rootViewController: A `UIViewController` view controller instance to define as a root view controller of the navigation controller.
/// - Note This initialiser added the `rootViewController` parameter although it is not really needed to differentiate itself from the `.init(navigationController:)` implemented for the `BaseNavigationRouter` base class.
public init(
navigationController: UINavigationController,
rootViewController: UIViewController? = nil
) {
self.rootViewController = navigationController.viewControllers.first ?? rootViewController
super.init(navigationController: navigationController)
}
}
// MARK: - Router
extension PushNavigationRouter: Router {
// MARK: Functions
public func present(
_ viewController: UIViewController,
animated: Bool,
onDismiss: OnDismissedClosure?
) {
onDismissForViewController[viewController] = onDismiss
navigationController.pushViewController(viewController, animated: animated)
}
public func dismiss(animated: Bool) {
guard let rootViewController else {
navigationController.popViewController(animated: animated)
return
}
performOnDismissed(for: rootViewController)
navigationController.popToViewController(rootViewController, animated: animated)
}
}
#endif
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if os(iOS)
import UIKit
/// This class is responsible for populating the window of an application.
public class WindowRouter: Router {
// MARK: Properties
/// The window to set manually with a `UIViewController` view controller instance.
private let window: UIWindow?
// MARK: Initialisers
/// Initialise this router.
/// - Parameter window: A `UIWindow` window instance to be set manually.
public init(window: UIWindow?) {
self.window = window
}
// MARK: Functions
public func present(
_ viewController: UIViewController,
animated: Bool,
onDismiss: OnDismissedClosure?
) {
window?.rootViewController = viewController
window?.makeKeyAndVisible()
}
public func dismiss(animated: Bool) {
// Nothing to do here...
}
}
#endif
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// This property wrapper provides a direct connection to the `DependencyService` service.
@propertyWrapper
public struct Dependency<D> {
// MARK: Properties
private let keyPath: WritableKeyPath<DependencyService, D>
/// This property allows direct read/write access to a defined dependency attached to a selected key path.
public var wrappedValue: D {
get { DependencyService[keyPath] }
set { DependencyService[keyPath] = newValue }
}
// MARK: Initialisers
/// Initialise the property wrapper by setting a key path to a defined dependency.
/// - Parameter keyPath: A key path to a defined dependency in the `DependencyService` service.
public init(_ keyPath: WritableKeyPath<DependencyService, D>) {
self.keyPath = keyPath
}
}
@@ -0,0 +1,26 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// This protocol defines a key to use in the dependency service.
public protocol DependencyKey {
// MARK: Associated types
/// The associated type representing the type of the dependency key's value.
associatedtype Value
// MARK: Properties
/// The default value for the dependency key.
static var currentValue: Value { get set }
}
@@ -0,0 +1,32 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// This service provide write/read access to the injected dependencies.
public struct DependencyService {
// MARK: Properties
private static var current = DependencyService()
// MARK: Subscripts
public static subscript<DK: DependencyKey>(key: DK.Type) -> DK.Value {
get { key.currentValue }
set { key.currentValue = newValue }
}
public static subscript<D>(_ keyPath: WritableKeyPath<DependencyService, D>) -> D {
get { current[keyPath: keyPath] }
set { current[keyPath: keyPath] = newValue }
}
}
@@ -0,0 +1,15 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public enum BundleError: Error {
case bundleNotFound
}
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public extension Bool {
// MARK: Initialisers
/// Initialise a boolean primitive out of a given string.
/// - Parameter string: A string to initialise the boolean with.
init(_ string: String) {
let strings: [String] = [
.Constants.oneNumber,
.Constants.oneWord,
.Constants.true,
.Constants.yes
]
self = strings.contains(string.lowercased())
}
}
// MARK: - String+Constants
private extension String {
enum Constants {
static let yes = "yes"
static let `true` = "true"
static let oneWord = "one"
static let oneNumber = "1"
}
}
@@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
public extension Bundle {
// MARK: Functions
/// Retrieve a localisation bundle for a given language code or identifier, if exist inside a certain bundle.
/// - Parameter languageCode: A string that represent a language code or identifier.
/// - Returns: A `Bundle` instance that contains localised resources based on a given language code or identifier.
/// - Throws: A `BundleError` error in case the localisation bundle for a given language code or identifier is not found inside a certain bundle.
func localisation(for languageCode: String) throws -> Bundle {
guard
let path = path(forResource: languageCode, ofType: .ResourceType.localisationBundle),
let bundle = Bundle(path: path)
else {
throw BundleError.bundleNotFound
}
return bundle
}
}
// MARK: - String+Constants
private extension String {
enum ResourceType {
static let localisationBundle = "lproj"
}
}
@@ -0,0 +1,20 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public extension Collection {
// MARK: Properties
/// A Boolean value indicating whether a collection is not empty.
var isNotEmpty: Bool { !isEmpty }
}
@@ -0,0 +1,23 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public extension Optional {
// MARK: Properties
/// A Boolean value indicating whether an optional has not been set.
var isNil: Bool { self == nil }
/// A Boolean value indicating whether an optional has been set.
var isNotNil: Bool { !isNil }
}
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
public extension String {
// MARK: Constants
/// A string that represents an empty string.
static let empty = ""
// MARK: Properties
/// A Boolean value indicating whether a string is not empty.
var isNotEmpty: Bool { !isEmpty }
}
@@ -0,0 +1,45 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
public extension String {
// MARK: Functions
/// Localise a string based on a given language code or identifier in an specific bundle.
/// - Parameters:
/// - languageCode: A string that represent a language code or identifier.
/// - bundle: A bundle in which to retrieve a localisation bundle.
/// - value: A default value to return if key is nil or if a localized string for key can't be found in the table.
/// - table: The receiver's string table to search. In case of nil or an empty string, the method attempts to use the table in `Localizable.strings`.
/// - Returns: A localized version of the string in case it is found. Otherwise, it returns the original string or a default string, if provided.
func localise(
for languageCode: String,
in bundle: Bundle,
value: String? = nil,
table: String? = nil
) -> String {
do {
return try bundle
.localisation(for: languageCode)
.localizedString(
forKey: self,
value: value,
table: table
)
} catch {
return value ?? self
}
}
}
@@ -0,0 +1,10 @@
import Foundation
public extension TimeZone {
// MARK: Zones
/// A time zone indicating it is Greenwich Mean Time or UTC+0
static let gmt = TimeZone(secondsFromGMT: 0)
}
@@ -0,0 +1,91 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
/// This struct (that could also be used as a property wrapper as well) provides a generic type that acts as a thin wrapper around an array of `Elements` instances to allow a lossy decoding and or encoding process.
///
/// This implementation is heavily influenced by this [article](https://www.swiftbysundell.com/articles/ignoring-invalid-json-elements-codable/).
@propertyWrapper
public struct LossyCodableList<Element> {
// MARK: Properties
private var elements: [Element]
/// Provides read/write access to the array of `Element` instances.
public var wrappedValue: [Element] {
get { elements }
set { elements = newValue }
}
// MARK: Initialisers
/// Initialises this struct.
public init() {
self.elements = []
}
}
// MARK: - Decodable
extension LossyCodableList: Decodable where Element: Decodable {
// MARK: Initialisers
/// Initialises the struct with a lossy decoder.
/// - Parameter decoder: The decoder to use for the lossy decoder process.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let wrappers = try container.decode([ElementWrapper].self)
self.elements = wrappers.compactMap(\.element)
}
}
// MARK: - Encodable
extension LossyCodableList: Encodable where Element: Encodable {
// MARK: Functions
/// Encodes an array of `Element` instances loosely.
/// - Parameter encoder: The encoder to use for the lossy encoding process.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
elements.forEach { element in
try? container.encode(element)
}
}
}
// MARK: - Structs
private extension LossyCodableList where Element: Decodable {
struct ElementWrapper: Decodable {
// MARK: Properties
var element: Element?
// MARK: Initialisers
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self.element = try? container.decode(Element.self)
}
}
}
+171
View File
@@ -0,0 +1,171 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if canImport(Combine) && canImport(CoreData)
import Combine
import CoreData
/// This class fetches objects from a given managed object context and it notifies of changes in the object fetched if any.
public class Fetcher<Model: NSManagedObject>: NSObject, NSFetchedResultsControllerDelegate {
// MARK: Properties
/// The publisher that emits the changes detected to the Location entities in a given object context.
public let didChangePublisher = PassthroughSubject<[Change], Never>()
private let fetchedResultsController: NSFetchedResultsController<Model>
/// The number of sections in the data.
public var numberOfSections: Int {
fetchedResultsController.sections?.count ?? 0
}
private var changesToNotify: [Change] = []
// MARK: Initialisers
/// Initialises the fetcher give the given parameters.
/// - Parameters:
/// - fetchRequest: The fetch request to use to get the objects.
/// - managedObjectContext: The managed object context against the fetch request is executed.
/// - sectionNameKeyPath: A key path on result objects that returns the section name.
/// - cacheName: The name of the cache file the receiver should use.
public init(
fetchRequest: NSFetchRequest<Model>,
managedObjectContext: NSManagedObjectContext,
sectionNameKeyPath: String? = nil,
cacheName: String? = nil
) {
self.fetchedResultsController = .init(
fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: sectionNameKeyPath,
cacheName: cacheName
)
super.init()
self.fetchedResultsController.delegate = self
}
// MARK: Functions
/// Perform the fetching.
public func fetch() throws {
try fetchedResultsController.performFetch()
}
/// Retrieve the number of objects in a given section number.
/// - Parameter section: The section number to inquiry about.
/// - Returns: A number of objects in the given section number.
public func numberOfObjects(in section: Int) throws -> Int {
guard let sections = fetchedResultsController.sections else {
throw FetcherError.fetchNotExecuted
}
guard sections.endIndex > section else {
throw FetcherError.sectionNotFound
}
return sections[section].numberOfObjects
}
/// Retrieve an object out of a given index path.
/// - Parameter indexPath: The index path to use to retrieve an object.
/// - Returns: A `NSManagedObject` entity positioned in the given index path.
public func object(at indexPath: IndexPath) throws -> Model {
guard fetchedResultsController.sections != nil else {
throw FetcherError.fetchNotExecuted
}
return fetchedResultsController.object(at: indexPath)
}
// MARK: NSFetchedResultsControllerDelegate
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
changesToNotify.removeAll()
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
didChangePublisher.send(changesToNotify)
}
public func controller(
_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange sectionInfo: NSFetchedResultsSectionInfo,
atSectionIndex sectionIndex: Int,
for type: NSFetchedResultsChangeType
) {
if type == .insert {
changesToNotify.append(.section(.inserted(sectionIndex)))
} else if type == .delete {
changesToNotify.append(.section(.deleted(sectionIndex)))
}
}
public func controller(
_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?
) {
switch type {
case .insert:
guard let newIndexPath else { return }
changesToNotify.append(.object(.inserted(at: newIndexPath)))
case .delete:
guard let indexPath else { return }
changesToNotify.append(.object(.deleted(from: indexPath)))
case .move:
guard let indexPath, let newIndexPath else { return }
changesToNotify.append(.object(.moved(from: indexPath, to: newIndexPath)))
case .update:
guard let indexPath else { return }
changesToNotify.append(.object(.updated(at: indexPath)))
default:
break
}
}
}
// MARK: - Errors
public enum FetcherError: Error {
case fetchNotExecuted
case sectionNotFound
}
// MARK: - Enumerations
public enum Change: Hashable {
public enum SectionUpdate: Hashable {
case inserted(Int)
case deleted(Int)
}
public enum ObjectUpdate: Hashable {
case inserted(at: IndexPath)
case deleted(from: IndexPath)
case updated(at: IndexPath)
case moved(from: IndexPath, to: IndexPath)
}
case section(SectionUpdate)
case object(ObjectUpdate)
}
#endif
@@ -0,0 +1,22 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
import Foundation
public extension URL {
// MARK: Properties
/// URL to a virtual device in which any data written vanishes or disappear.
static let bitBucket = URL(fileURLWithPath: "/dev/null")
}
@@ -0,0 +1,42 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftLibs open source project
//
// Copyright (c) 2023 Röck+Cöde VoF. and the SwiftLibs project authors
// Licensed under the EUPL 1.2 or later.
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftLibs project authors
//
//===----------------------------------------------------------------------===//
#if canImport(CoreData)
import CoreData
public protocol Service {
// MARK: Properties
/// The main managed object context.
var viewContext: NSManagedObjectContext { get }
// MARK: Functions
/// Create a private queue context.
/// - Returns: A concurrent `NSManagedObjectContext` context instance ready to use.
func makeTaskContext() -> NSManagedObjectContext
/// Create a child context of the view context.
/// - Returns: A generated child `NSManagedObjectContext` context instance ready to use.
func makeChildContext() -> NSManagedObjectContext
/// Save a given context.
/// - Parameter context: A `NSManagedObjectContext` context instance to save.
func save(context: NSManagedObjectContext) throws
/// Save a given child context as well as its respective parent context.
/// - Parameter context: A child `NSManagedObjectContext` context instance to save.
func save(childContext context: NSManagedObjectContext) throws
}
#endif