-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathBlogQuery.swift
More file actions
83 lines (66 loc) · 2.63 KB
/
BlogQuery.swift
File metadata and controls
83 lines (66 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import CoreData
import Foundation
/// A helper to query `Blog` from given `NSManagedObjectContext`.
///
/// Note: the implementation here isn't meant to be a standard way to perform query. But it might be valuable
/// to explore a standard way to perform query. https://github.com/wordpress-mobile/WordPress-iOS/pull/19394 made
/// an attempt, but still has lots of unknowns.
public struct BlogQuery {
private var predicates: [NSPredicate]
public init() {
predicates = []
}
public func blogID(_ id: Int) -> Self {
blogID(Int64(id))
}
public func blogID(_ id: NSNumber) -> Self {
blogID(id.int64Value)
}
public func blogID(_ id: Int64) -> Self {
and(NSPredicate(format: "blogID = %ld", id))
}
public func dotComAccountUsername(_ username: String) -> Self {
and(NSPredicate(format: "account.username = %@", username))
}
public func selfHostedBlogUsername(_ username: String) -> Self {
and(NSPredicate(format: "username = %@", username))
}
public func hostname(containing hostname: String) -> Self {
and(NSPredicate(format: "url CONTAINS %@", hostname))
}
public func hostname(matching hostname: String) -> Self {
and(NSPredicate(format: "url = %@", hostname))
}
public func hostedByWPCom(_ flag: Bool) -> Self {
and(NSPredicate(format: flag ? "account != NULL" : "account == NULL"))
}
public func xmlrpc(matching xmlrpc: String) -> Self {
and(NSPredicate(format: "xmlrpc = %@", xmlrpc))
}
public func apiKey(is string: String) -> Self {
and(NSPredicate(format: "apiKey = %@", string))
}
public func count(in context: NSManagedObjectContext) -> Int {
(try? context.count(for: buildFetchRequest())) ?? 0
}
public func blog(in context: NSManagedObjectContext) throws -> Blog? {
let request = buildFetchRequest()
request.fetchLimit = 1
return (try context.fetch(request).first)
}
public func blogs(in context: NSManagedObjectContext) throws -> [Blog] {
try context.fetch(buildFetchRequest())
}
private func buildFetchRequest() -> NSFetchRequest<Blog> {
let request = NSFetchRequest<Blog>(entityName: Blog.entityName())
request.includesSubentities = false
request.sortDescriptors = [NSSortDescriptor(key: "settings.name", ascending: true)]
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
return request
}
private func and(_ predicate: NSPredicate) -> Self {
var query = self
query.predicates.append(predicate)
return query
}
}