Skip to content

Commit

Permalink
Make TopLevelEncoder implementation overridable (#182)
Browse files Browse the repository at this point in the history
`TopLevelEncoder` implementation was added by #175. However, its method cannot be overridden. If it can be, we can use custom root key, root attributes, or header even when we use Combine-style like this:

```swift
final class MyEncoder: XMLEncoder {
    override func encode<T>(_ value: T) throws -> Data where T : Encodable {
        try self.encode(value, withRootKey: "foo", rootAttributes: nil, header: XMLHeader(version: 1.0, encoding: "UTF-8"))
    }
}
```
  • Loading branch information
kkebo committed May 20, 2020
1 parent ac411bd commit 41e3d46
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
7 changes: 1 addition & 6 deletions Sources/XMLCoder/Decoder/XMLDecoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -382,10 +382,5 @@ import protocol OpenCombine.TopLevelEncoder

#if canImport(Combine) || canImport(OpenCombine)
extension XMLDecoder: TopLevelDecoder {}

extension XMLEncoder: TopLevelEncoder {
public func encode<T>(_ value: T) throws -> Data where T: Encodable {
try encode(value, withRootKey: nil, rootAttributes: nil, header: nil)
}
}
extension XMLEncoder: TopLevelEncoder {}
#endif
8 changes: 8 additions & 0 deletions Sources/XMLCoder/Encoder/XMLEncoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,14 @@ open class XMLEncoder {
return element.toXMLString(with: header, formatting: outputFormatting)
.data(using: .utf8, allowLossyConversion: true)!
}

// MARK: - TopLevelEncoder

#if canImport(Combine) || canImport(OpenCombine)
open func encode<T>(_ value: T) throws -> Data where T: Encodable {
return try encode(value, withRootKey: nil, rootAttributes: nil, header: nil)
}
#endif
}

private extension String {
Expand Down
22 changes: 22 additions & 0 deletions Tests/XMLCoderTests/CombineTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ private struct Foo: Codable {
var name: String
}

final class CustomEncoder: XMLEncoder {
override func encode<T>(_ value: T) throws -> Data where T: Encodable {
return try encode(value, withRootKey: "bar", rootAttributes: nil, header: nil)
}
}

@available(iOS 13.0, macOS 10.15.0, tvOS 13.0, watchOS 6.0, *)
final class CombineTests: XCTestCase {
func testDecode() {
Expand All @@ -51,5 +57,21 @@ final class CombineTests: XCTestCase {
)
XCTAssertEqual(foo?.name, "Foo")
}

func testCustomEncode() {
var foo: Data?
_ = Just(Foo(name: "Foo"))
.encode(encoder: CustomEncoder())
.sink(
receiveCompletion: { _ in },
receiveValue: {
foo = $0
}
)
XCTAssertEqual(
String(data: foo!, encoding: .utf8)!,
"<bar><name>Foo</name></bar>"
)
}
}
#endif

0 comments on commit 41e3d46

Please sign in to comment.