From 5c5d552952410ab685372b41f0d44325a2e1b6c8 Mon Sep 17 00:00:00 2001 From: Yanick Witschi Date: Mon, 14 Oct 2024 12:43:31 +0200 Subject: [PATCH] Add ability to replace existing tokens easily --- src/Token/TokenCollection.php | 13 +++++++++++++ tests/Token/TokenCollectionTest.php | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Token/TokenCollection.php b/src/Token/TokenCollection.php index 0bc5fd6..b432436 100644 --- a/src/Token/TokenCollection.php +++ b/src/Token/TokenCollection.php @@ -29,6 +29,19 @@ public static function fromSerializedArray(array $data): self return new self($tokens); } + public function replaceToken(Token $token): self + { + $existing = $this->getByName($token->getName()); + + if (null !== $existing) { + $this->remove($existing); + } + + $this->addToken($token); + + return $this; + } + /** * Provides a fluent interface alternative to add() with a type hint. */ diff --git a/tests/Token/TokenCollectionTest.php b/tests/Token/TokenCollectionTest.php index 9e16176..fdba5e2 100644 --- a/tests/Token/TokenCollectionTest.php +++ b/tests/Token/TokenCollectionTest.php @@ -61,6 +61,23 @@ public function testCollectionHandling(): void $this->assertNull($tokenCollection->getByName('form_i_do_not_exist')); } + public function testReplace(): void + { + $tokenCollection = new TokenCollection(); + $tokenCollection->addToken(Token::fromValue('test', 'foobar')); + $tokenCollection->addToken(Token::fromValue('test', 'foobar new')); + + $this->assertSame(2, $tokenCollection->count()); + $this->assertSame('foobar', $tokenCollection->getByName('test')->getValue(), 'foobar'); + + $tokenCollection = new TokenCollection(); + $tokenCollection->replaceToken(Token::fromValue('test', 'foobar')); + $tokenCollection->replaceToken(Token::fromValue('test', 'foobar new')); + + $this->assertSame(1, $tokenCollection->count()); + $this->assertSame('foobar new', $tokenCollection->getByName('test')->getValue(), 'foobar'); + } + public function testMerge(): void { $tokenCollectionA = new TokenCollection();