Skip to content

Commit

Permalink
add additional safety checks to insert/append card methods (#94)
Browse files Browse the repository at this point in the history
  • Loading branch information
mac-gallagher authored Jul 8, 2020
1 parent 94bbd30 commit 1168aac
Show file tree
Hide file tree
Showing 8 changed files with 167 additions and 25 deletions.
4 changes: 2 additions & 2 deletions Shuffle-iOS.podspec
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|

s.name = "Shuffle-iOS"
s.version = "0.3.0"
s.version = "0.3.1"
s.platform = :ios, "9.0"
s.summary = "A multi-directional card swiping library inspired by Tinder"

Expand All @@ -13,7 +13,7 @@ s.homepage = "https://github.com/mac-gallagher/Shuffle"
s.documentation_url = "https://github.com/mac-gallagher/Shuffle/tree/master/README.md"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Mac Gallagher" => "[email protected]" }
s.source = { :git => "https://github.com/mac-gallagher/Shuffle.git", :tag => "v0.3.0" }
s.source = { :git => "https://github.com/mac-gallagher/Shuffle.git", :tag => "v0.3.1" }

s.swift_version = "5.0"
s.source_files = "Sources/**/*.{h,swift}"
Expand Down
4 changes: 4 additions & 0 deletions Shuffle.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@
ADA444D922AC658E00AFAFFE /* SwipeCardStackDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA444D822AC658E00AFAFFE /* SwipeCardStackDataSource.swift */; };
ADA444DB22AC662C00AFAFFE /* CardStackAnimator.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA444DA22AC662C00AFAFFE /* CardStackAnimator.swift */; };
ADA444DF22AC682400AFAFFE /* CardStackLayoutProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADA444DE22AC682400AFAFFE /* CardStackLayoutProvider.swift */; };
ADAC94E224B558EC00F5D52E /* StringUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADAC94E124B558EC00F5D52E /* StringUtils.swift */; };
ADC3622D2466B23E00FB9F1C /* SwipeCardSpec_Base.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADC3622C2466B23E00FB9F1C /* SwipeCardSpec_Base.swift */; };
ADCEAE2022A1B80B002A5F82 /* CardAnimatorSpec.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADCEAE1F22A1B80B002A5F82 /* CardAnimatorSpec.swift */; };
ADCEAE2222A1B88D002A5F82 /* TestableCardAnimator.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADCEAE2122A1B88D002A5F82 /* TestableCardAnimator.swift */; };
Expand Down Expand Up @@ -185,6 +186,7 @@
ADA444D822AC658E00AFAFFE /* SwipeCardStackDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwipeCardStackDataSource.swift; sourceTree = "<group>"; };
ADA444DA22AC662C00AFAFFE /* CardStackAnimator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardStackAnimator.swift; sourceTree = "<group>"; };
ADA444DE22AC682400AFAFFE /* CardStackLayoutProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardStackLayoutProvider.swift; sourceTree = "<group>"; };
ADAC94E124B558EC00F5D52E /* StringUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringUtils.swift; sourceTree = "<group>"; };
ADB8EED122F174BB004F8633 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = "<group>"; };
ADC3622C2466B23E00FB9F1C /* SwipeCardSpec_Base.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwipeCardSpec_Base.swift; sourceTree = "<group>"; };
ADCEAE1F22A1B80B002A5F82 /* CardAnimatorSpec.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CardAnimatorSpec.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -425,6 +427,7 @@
ADDF5F832277FA2C00274C09 /* CGPoint+Extensions.swift */,
AD72AC752270F4130083E735 /* CGVector+Extensions.swift */,
AD2E1C8F245E176F00A520A3 /* PanGestureRecognizer.swift */,
ADAC94E124B558EC00F5D52E /* StringUtils.swift */,
AD439DF72285FB7E009DE2F7 /* TapGestureRecognizer.swift */,
AD4AACA2231C61FC008EC632 /* UIView+Extensions.swift */,
);
Expand Down Expand Up @@ -821,6 +824,7 @@
AD52EF8122E5088B0063AE5D /* CardTransformProvider.swift in Sources */,
AD514C5B22A08D5600BD8F3E /* CardLayoutProvider.swift in Sources */,
AD72AC9A2270FCCE0083E735 /* SwipeDirection.swift in Sources */,
ADAC94E224B558EC00F5D52E /* StringUtils.swift in Sources */,
ADA444D922AC658E00AFAFFE /* SwipeCardStackDataSource.swift in Sources */,
AD52EF8722E523020063AE5D /* CardStackTransformProvider.swift in Sources */,
ADEE86D722ACE5AA00AAE7A1 /* Array+Extensions.swift in Sources */,
Expand Down
37 changes: 37 additions & 0 deletions Sources/Shuffle/Internal/StringUtils.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
///
/// MIT License
///
/// Copyright (c) 2020 Mac Gallagher
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///

import Foundation

//swiftlint:disable line_length
enum StringUtils {

static func createInvalidUpdateErrorString(newCount: Int,
oldCount: Int,
insertedCount: Int = 0,
deletedCount: Int = 0) -> String {
return "Invalid update: invalid number of cards. The number of cards contained in the card stack after the update (\(newCount)) must be equal to the number of cards contained in the card stack before the update (\(oldCount)), plus or minus the number of cards inserted or deleted (\(insertedCount) inserted, \(deletedCount) deleted)"
}
}
//swiftlint:enable line_length
9 changes: 7 additions & 2 deletions Sources/Shuffle/SwipeCardStack/CardStackStateManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ typealias Swipe = (index: Int, direction: SwipeDirection)
protocol CardStackStateManagable {
var remainingIndices: [Int] { get }
var swipes: [Swipe] { get }
var totalIndexCount: Int { get }

func insert(_ index: Int, at position: Int)

Expand All @@ -51,6 +52,10 @@ class CardStackStateManager: CardStackStateManagable {
/// An array containing the swipe history of the card stack.
var swipes: [Swipe] = []

var totalIndexCount: Int {
return remainingIndices.count + swipes.count
}

func insert(_ index: Int, at position: Int) {
if position < 0 {
fatalError("Attempt to insert card at position \(position)")
Expand All @@ -65,9 +70,9 @@ class CardStackStateManager: CardStackStateManagable {
fatalError("Attempt to insert card at data source index \(index)")
}

if index > remainingIndices.count + swipes.count {
if index > totalIndexCount {
//swiftlint:disable:next line_length
fatalError("Attempt to insert card at index \(index), but there are only \(remainingIndices.count + swipes.count + 1) cards after the update")
fatalError("Attempt to insert card at index \(index), but there are only \(totalIndexCount + 1) cards after the update")
}

// Increment all stored indices in the range [0, index] by 1
Expand Down
26 changes: 26 additions & 0 deletions Sources/Shuffle/SwipeCardStack/SwipeCardStack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -312,16 +312,42 @@ open class SwipeCardStack: UIView, SwipeCardDelegate, UIGestureRecognizerDelegat
/// - position: The position of the new card in the card stack. This position should be determined on
/// the returned value of `numberOfRemainingCards`.
public func insertCard(atIndex index: Int, position: Int) {
guard let dataSource = dataSource else { return }

let oldNumberOfCards = stateManager.totalIndexCount
let newNumberOfCards = dataSource.numberOfCards(in: self)

stateManager.insert(index, at: position)

if newNumberOfCards != oldNumberOfCards + 1 {
let errorString = StringUtils.createInvalidUpdateErrorString(newCount: newNumberOfCards,
oldCount: oldNumberOfCards,
insertedCount: 1)
fatalError(errorString)
}

reloadVisibleCards()
}

/// Appends a collection of new cards with the specifed indices to the bottom of the card stack.
/// - Parameter indices: The indices of the cards in the data source.
public func appendCards(atIndices indices: [Int]) {
guard let dataSource = dataSource else { return }

let oldNumberOfCards = stateManager.totalIndexCount
let newNumberOfCards = dataSource.numberOfCards(in: self)

for index in indices {
stateManager.insert(index, at: numberOfRemainingCards())
}

if newNumberOfCards != oldNumberOfCards + indices.count {
let errorString = StringUtils.createInvalidUpdateErrorString(newCount: newNumberOfCards,
oldCount: oldNumberOfCards,
insertedCount: indices.count)
fatalError(errorString)
}

reloadVisibleCards()
}

Expand Down
3 changes: 0 additions & 3 deletions Tests/ShuffleTests/SwipeCard/Specs/SwipeCardSpec_Base.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ class SwipeCardSpec_Base: QuickSpec {
var mockCardTransformProvider: MockCardTransformProvider!
var mockSwipeCardDelegate: MockSwipeCardDelegate!
var mockNotificationCenter: TestableNotificationCenter!
var testPanGestureRecognizer: PanGestureRecognizer!
var subject: TestableSwipeCard!

beforeEach {
Expand All @@ -51,8 +50,6 @@ class SwipeCardSpec_Base: QuickSpec {
notificationCenter: mockNotificationCenter,
transformProvider: mockCardTransformProvider)
subject.delegate = mockSwipeCardDelegate

testPanGestureRecognizer = subject.panGestureRecognizer as? PanGestureRecognizer
}

describe("Initialization") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ import UIKit
class MockCardStackStateManager: CardStackStateManagable {

var remainingIndices: [Int] = []

var swipes: [Swipe] = []
var totalIndexCount: Int = 0

var insertCalled: Bool = false
var insertIndices: [Int] = []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -504,18 +504,53 @@ class SwipeCardStackSpec_MainMethods: QuickSpec {
let index: Int = 1
let position: Int = 2

beforeEach {
subject.insertCard(atIndex: index, position: position)
}
context("and there is no data source") {
beforeEach {
subject.insertCard(atIndex: index, position: position)
}

it("should call the stateManager's insert method with the correct parameters") {
expect(mockStateManager.insertCalled) == true
expect(mockStateManager.insertIndices) == [index]
expect(mockStateManager.insertPositions) == [position]
it("should not call the stateManager's insert method or reloadVisibleCards") {
expect(mockStateManager.insertCalled) == false
expect(subject.reloadVisibleCardsCalled) == false
}
}

it("should call reloadVisibleCards") {
expect(subject.reloadVisibleCardsCalled) == true
context("and there is a data source") {
let newNumberOfCards: Int = 10
var dataSource: MockSwipeCardStackDataSource!

beforeEach {
dataSource = MockSwipeCardStackDataSource()
dataSource.testNumberOfCards = newNumberOfCards
subject.dataSource = dataSource
}

context("and the new number of cards is not equal to the old number of cards plus one") {
beforeEach {
mockStateManager.totalIndexCount = newNumberOfCards - 2
}

it("should throw a fatal error") {
expect(subject.insertCard(atIndex: index, position: position)).to(throwAssertion())
}
}

context("and the new number of cards is not equal to the old number of cards plus one") {
beforeEach {
mockStateManager.totalIndexCount = newNumberOfCards - 1
subject.insertCard(atIndex: index, position: position)
}

it("should call the stateManager's insert method with the correct parameters") {
expect(mockStateManager.insertCalled) == true
expect(mockStateManager.insertIndices) == [index]
expect(mockStateManager.insertPositions) == [position]
}

it("should call reloadVisibleCards") {
expect(subject.reloadVisibleCardsCalled) == true
}
}
}
}

Expand All @@ -527,18 +562,56 @@ class SwipeCardStackSpec_MainMethods: QuickSpec {

beforeEach {
mockStateManager.remainingIndices = remainingIndices
subject.appendCards(atIndices: indices)
}

it("should call the stateManager's insert method with the correct parameters") {
expect(mockStateManager.insertCalled) == true
expect(mockStateManager.insertIndices) == indices
expect(mockStateManager.insertPositions) == Array(repeating: remainingIndices.count,
count: indices.count)
context("and there is no data source") {
beforeEach {
subject.appendCards(atIndices: indices)
}

it("should not call the stateManager's insert method or reloadVisibleCards") {
expect(mockStateManager.insertCalled) == false
expect(subject.reloadVisibleCardsCalled) == false
}
}

it("should call reloadVisibleCards") {
expect(subject.reloadVisibleCardsCalled) == true
context("and there is a data source") {
let newNumberOfCards: Int = 8
var dataSource: MockSwipeCardStackDataSource!

beforeEach {
dataSource = MockSwipeCardStackDataSource()
dataSource.testNumberOfCards = newNumberOfCards
subject.dataSource = dataSource
}

context("and the new number of cards is not equal to the old number of cards plus the number of new cards") {
beforeEach {
mockStateManager.totalIndexCount = newNumberOfCards - 2
}

it("should throw a fatal error") {
expect(subject.appendCards(atIndices: indices)).to(throwAssertion())
}
}

context("and the new number of cards is equal to the old number of cards plus the number of new cards") {
beforeEach {
mockStateManager.totalIndexCount = newNumberOfCards - indices.count
subject.appendCards(atIndices: indices)
}

it("should call the stateManager's insert method with the correct parameters") {
expect(mockStateManager.insertCalled) == true
expect(mockStateManager.insertIndices) == indices
expect(mockStateManager.insertPositions) == Array(repeating: remainingIndices.count,
count: indices.count)
}

it("should call reloadVisibleCards") {
expect(subject.reloadVisibleCardsCalled) == true
}
}
}
}

Expand Down

0 comments on commit 1168aac

Please sign in to comment.