Skip to content

Commit

Permalink
Merge pull request adobe#34 from adobe/dev
Browse files Browse the repository at this point in the history
merge dev cleanup to main
  • Loading branch information
sbenedicadb authored Jan 7, 2021
2 parents b2e0247 + 26f1c5d commit 4b08e1e
Show file tree
Hide file tree
Showing 35 changed files with 320 additions and 191 deletions.
4 changes: 2 additions & 2 deletions AEPRulesEngine.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ Pod::Spec.new do |s|
s.requires_arc = true

s.ios.deployment_target = '10.0'
s.pod_target_xcconfig = { 'BUILD_LIBRARY_FOR_DISTRIBUTION' => 'YES' }

s.swift_version = '5.0'
s.source_files = 'Sources/AEPRulesEngine/**/*.swift'

s.source_files = 'Sources/AEPRulesEngine/**/*.swift'

end
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.

Copyright 2020 Adobe
Copyright 2021 Adobe

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
45 changes: 35 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
[![codecov](https://codecov.io/gh/yangyansong-adbe/aepsdk-rulesengine-ios/branch/dev/graph/badge.svg?token=T8LRU71KTB)](undefined)

# AEPRulesEngine

<!--
on [![Cocoapods](https://img.shields.io/cocoapods/v/AEPRulesEngine.svg?color=orange&label=AEPCore&logo=apple&logoColor=white)](https://cocoapods.org/pods/AEPRulesEngine)
-->
[![SPM](https://img.shields.io/badge/SPM-Supported-orange.svg?logo=apple&logoColor=white)](https://swift.org/package-manager/)
[![CI](https://github.com/adobe/aepsdk-rulesengine-ios/workflows/CI/badge.svg)](https://github.com/adobe/aepsdk-rulesengine-ios/actions)
[![Code Coverage](https://img.shields.io/codecov/c/github/adobe/aepsdk-rulesengine-ios/main.svg?logo=codecov)](https://codecov.io/gh/adobe/aepsdk-rulesengine-ios/branch/main)
[![GitHub](https://img.shields.io/github/license/adobe/aepsdk-rulesengine-ios)](https://github.com/adobe/aepsdk-rulesengine-ios/blob/main/LICENSE)

## BETA

AEPRulesEngine is currently in beta. Use of this code is by invitation only and not otherwise supported by Adobe. Please contact your Adobe Customer Success Manager to learn more.
Expand All @@ -10,17 +16,37 @@ AEPRulesEngine is currently in beta. Use of this code is by invitation only and

A simple, generic, extensible Rules Engine in Swift.

## Requirements
- Xcode 11.0 (or newer)
- Swift 5.1 (or newer)

## Installation

### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html)
```ruby
# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
pod 'AEPRulesEngine', :git => 'https://github.com/adobe/aepsdk-rulesengine-ios.git', :branch => 'main'
end
```

Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type:

```bash
$ pod install
```

### Swift Package Manager

To add the AEPRulesEngine Package to your application, from the Xcode menu select:
To add the AEPRulesEngine package to your application, from the Xcode menu select:

`File > Swift Packages > Add Package Dependency...`

Enter the URL for the AEPRulesEngine package repository: `https://github.com/adobe/aepsdk-rulesengine-ios.git`.

When prompted, make sure you change the branch to `main`.
When prompted, make sure you change the branch to `main`.

There are three options for selecting your dependencies as identified by the *suffix* of the library name:

Expand All @@ -38,18 +64,17 @@ dependencies: [

## Usage

### Initialize the Rules Engine

### Initialize Rules Engine

To create a `RuleEngine` instance, first define an `Evaluator` and then use it as the parameter for `RuleEngine`.
To create a `RulesEngine` instance, define an `Evaluator` and pass it to the `RulesEngine`'s initializer:
```
let evaluator = ConditionEvaluator(options: .caseInsensitive)
let rulesEngine = RulesEngine(evaluator: evaluator)
```

### Define Rules

Any thing that conforms to the `Rule` protocol can be used as rule.
Anything that conforms to the `Rule` protocol can be used as rule:
``` Swift
public class MobileRule: Rule {
init(condition: Evaluable) { self.condition = condition }
Expand All @@ -59,7 +84,7 @@ let condition = ComparisonExpression(lhs: "abc", operationName: "equals", rhs: "
let rule = MobileRule(condition: condition)
rulesEngine.addRules(rules: [rule])
```
However, a rule like this doesn't make much sense, without the ability to dynamically fetch a value it will always be true or false.
A rule without the flexibility to dynamically fetch a value will always evaluate to true or false. To fetch the value for a rule at runtime, use a Mustache Token:

``` Swift
let mustache = Operand<String>(mustache: "{{company}}")
Expand All @@ -70,7 +95,7 @@ rulesEngine.addRules(rules: [rule])

### Evaluate data

Use the method `evaluate` to run rule engine on the input data that is `Traversable`.
Use the `evaluate` method to process `Traversable` data through the `RulesEngine`:

```
let matchedRules = rulesEngine.evaluate(data: ["company":"adobe"])
Expand Down
26 changes: 16 additions & 10 deletions Sources/AEPRulesEngine/ConditionEvaluator.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -13,11 +13,15 @@
public class ConditionEvaluator: Evaluating {
fileprivate let LOG_TAG = "ConditionEvaluator"
var operators: [String: Any] = [:]

// MARK: - Evaluating

public func evaluate<A>(operation: String, lhs: A) -> Result<Bool, RulesFailure> {
let op = operators[getHash(operation: operation, typeA: A.self)] as? ((A) -> Bool)

guard let op_ = op else {
let message = "Operator not defined for \(getHash(operation: operation, typeA: A.self))"
RulesEngineLog.trace(label: LOG_TAG, message)
let message = "No operator defined for \(getHash(operation: operation, typeA: A.self))"
Log.trace(label: LOG_TAG, message)
return Result.failure(RulesFailure.missingOperator(message: message))
}
return op_(lhs) ? Result.success(true) : Result.failure(.conditionNotMatched(message: "(\(String(describing: A.self))(\(lhs)) \(operation))"))
Expand All @@ -27,24 +31,24 @@ public class ConditionEvaluator: Evaluating {
let op = operators[getHash(operation: operation, typeA: A.self, typeB: B.self)] as? ((A, B) -> Bool)

guard let op_ = op else {
let message = "Operator not defined for \(getHash(operation: operation, typeA: A.self, typeB: B.self))"
RulesEngineLog.trace(label: LOG_TAG, message)
let message = "No operator defined for \(getHash(operation: operation, typeA: A.self, typeB: B.self))"
Log.trace(label: LOG_TAG, message)
return Result.failure(RulesFailure.missingOperator(message: message))
}
return op_(lhs, rhs) ? Result.success(true) : Result.failure(.conditionNotMatched(message: "\(String(describing: A.self))(\(lhs)) \(operation) \(String(describing: B.self))(\(rhs))"))
}
}

extension ConditionEvaluator {
public func addUnaryOperator<A>(operation: String, closure: @escaping (A) -> Bool) {
public extension ConditionEvaluator {
func addUnaryOperator<A>(operation: String, closure: @escaping (A) -> Bool) {
operators[getHash(operation: operation, typeA: A.self)] = closure
}

public func addComparisonOperator<A, B>(operation: String, closure: @escaping (A, B) -> Bool) {
func addComparisonOperator<A, B>(operation: String, closure: @escaping (A, B) -> Bool) {
operators[getHash(operation: operation, typeA: A.self, typeB: B.self)] = closure
}

public func addComparisonOperator<A>(operation: String, type _: A.Type, closure: @escaping (A, A) -> Bool) {
func addComparisonOperator<A>(operation: String, type _: A.Type, closure: @escaping (A, A) -> Bool) {
operators[getHash(operation: operation, typeA: A.self, typeB: A.self)] = closure
}

Expand Down Expand Up @@ -117,9 +121,11 @@ public extension ConditionEvaluator {
}

private func addCaseInSensitiveOperators() {
addComparisonOperator(operation: "startsWith", type: String.self, closure: { $0.lowercased().starts(with: $1.lowercased()) })
addComparisonOperator(operation: "equals", type: String.self, closure: { $0.lowercased() == $1.lowercased() })
addComparisonOperator(operation: "notEquals", type: String.self, closure: { $0.lowercased() != $1.lowercased() })
addComparisonOperator(operation: "startsWith", type: String.self, closure: { $0.lowercased().starts(with: $1.lowercased()) })
addComparisonOperator(operation: "endsWith", type: String.self, closure: { $0.lowercased().hasSuffix($1.lowercased()) })
addComparisonOperator(operation: "contains", type: String.self, closure: { $0.lowercased().contains($1.lowercased()) })
addComparisonOperator(operation: "notContains", type: String.self, closure: { !$0.lowercased().contains($1.lowercased()) })
}
}
20 changes: 20 additions & 0 deletions Sources/AEPRulesEngine/Context.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

/// A type that contains all pieces necessary for boolean evaluation
public struct Context {
public let data: Traversable
public let evaluator: Evaluating
public let transformer: Transforming
}
2 changes: 1 addition & 1 deletion Sources/AEPRulesEngine/Evaluating.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
10 changes: 6 additions & 4 deletions Sources/AEPRulesEngine/Expression/ComparisonExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -24,8 +24,10 @@ public struct ComparisonExpression<A, B>: Evaluable {
self.operationName = operationName
}

// MARK: - Evaluable

public func evaluate(in context: Context) -> Result<Bool, RulesFailure> {
RulesEngineLog.trace(label: LOG_TAG, "Evaluating \(lhs) - \(operationName) - \(rhs)")
Log.trace(label: LOG_TAG, "Evaluating \(lhs) - \(operationName) - \(rhs)")
let resolvedLhs = lhs(context)
let resolvedRhs = rhs(context)
var result: Result<Bool, RulesFailure>
Expand All @@ -38,8 +40,8 @@ public struct ComparisonExpression<A, B>: Evaluable {
case .success:
return result
case let .failure(error):
RulesEngineLog.debug(label: LOG_TAG, "Failed to evaluate \(String(describing: resolvedLhs)) - \(operationName) - \(String(describing: resolvedRhs))")
return Result.failure(.innerFailure(message: "Comparison (\(lhs) \(operationName) \(rhs)) returns false", error: error))
Log.debug(label: LOG_TAG, "Failed to evaluate \(String(describing: resolvedLhs)) - \(operationName) - \(String(describing: resolvedRhs))")
return Result.failure(.innerFailure(message: "Comparison (\(lhs) \(operationName) \(rhs)) returned false", error: error))
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down
4 changes: 2 additions & 2 deletions Sources/AEPRulesEngine/Expression/LogicalExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down Expand Up @@ -43,7 +43,7 @@ public struct LogicalExpression: Evaluable {
}
return Result.failure(.innerFailures(message: "`Or` returns false", errors: operandsResolve.filter { !$0.value }.map { $0.error ?? RulesFailure.unknown }))
default:
return .failure(.missingOperator(message: "Unkonwn conjunction operator"))
return .failure(.missingOperator(message: "Unknown conjunction operator '\(operationName)'"))
}
}
}
10 changes: 5 additions & 5 deletions Sources/AEPRulesEngine/Expression/Operand.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand Down Expand Up @@ -34,8 +34,8 @@ public enum Operand<T> {
}
}

extension Operand {
public init(mustache: String) {
public extension Operand {
init(mustache: String) {
let tokens = try? TemplateParser.parse(mustache).get()
if let tokens = tokens, tokens.count > 0, case let .mustache(token) = tokens[0].type {
self = .token(token)
Expand All @@ -51,9 +51,9 @@ extension Operand: CustomStringConvertible {
case .none:
return "<None>"
case let .some(value):
return "<Value:\(value)>"
return "<Value: \(value)>"
case let .token(mustache):
return "<Token:\(mustache)>"
return "<Token: \(mustache)>"
}
}
}
4 changes: 2 additions & 2 deletions Sources/AEPRulesEngine/Expression/UnaryExpression.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -23,7 +23,7 @@ public struct UnaryExpression<A>: Evaluable {
}

public func evaluate(in context: Context) -> Result<Bool, RulesFailure> {
RulesEngineLog.trace(label: LOG_TAG, "Evaluating \(operationName) - \(lhs)")
Log.trace(label: LOG_TAG, "Evaluating \(operationName) - \(lhs)")
let resolvedLhs = lhs(context)
if let resolvedLhs_ = resolvedLhs {
return context.evaluator.evaluate(operation: operationName, lhs: resolvedLhs_)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -12,8 +12,11 @@

import Foundation

public class RulesEngineLog {
public static var logging: RulesEngineLogging?
/// The `Log` class will be dormant unless its static `logging` variable is initialized.
/// To enable logging from the RulesEngine, implement a class that conforms to the
/// `Logging` protocol and use an instance of it to set the `Log.logging` variable.
public enum Log {
public static var logging: Logging?
/// Used to print more verbose information.
/// - Parameters:
/// - label: the name of the label to localize message
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -11,27 +11,19 @@
*/

import Foundation
public protocol RulesEngineLogging {
/// Logs a message
/// - Parameters:
/// - level: One of the message level identifiers, e.g., DEBUG
/// - label: Name of a label to localize message
/// - message: The string message
func log(level: RulesEngineLogLevel, label: String, message: String)
}

public enum RulesEngineLogLevel: Int, Comparable {
public enum LogLevel: Int, Comparable {
case error = 0
case warning = 1
case debug = 2
case trace = 3

/// Compares two `RulesEngineLogLevel`s for order
/// Compares two `LogLevel`s for order
/// - Parameters:
/// - lhs: the first `RulesEngineLogLevel` to be compared
/// - rhs: the second `RulesEngineLogLevel` to be compared
/// - Returns: true, only if the second `LogLevel` is more critical
public static func < (lhs: RulesEngineLogLevel, rhs: RulesEngineLogLevel) -> Bool {
/// - lhs: the first `LogLevel` to be compared
/// - rhs: the second `LogLevel` to be compared
/// - Returns: true if the second `LogLevel` is more critical
public static func < (lhs: LogLevel, rhs: LogLevel) -> Bool {
lhs.rawValue < rhs.rawValue
}

Expand Down
22 changes: 22 additions & 0 deletions Sources/AEPRulesEngine/Log/Logging.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

public protocol Logging {
/// Logs a message
/// - Parameters:
/// - level: A `LogLevel` identifying the severity of the log. e.g. - `.debug`
/// - label: Label for the log
/// - message: The `String` message
func log(level: LogLevel, label: String, message: String)
}
Loading

0 comments on commit 4b08e1e

Please sign in to comment.