From 05c35c0e08c0ab80110e051580aac74e6cd4f4c4 Mon Sep 17 00:00:00 2001 From: Tony Messias Date: Tue, 22 Jun 2021 23:46:57 -0300 Subject: [PATCH] Records passed to the RecordIdentifier must only implement the getKey method --- src/Views/RecordIdentifier.php | 24 ++++--------------- src/Views/TurboStreamable.php | 8 ------- src/Views/UnidentifiableRecordException.php | 15 ++++++++++++ tests/Stubs/Models/TestTurboStreamable.php | 6 ++--- tests/TestTurboStreamable.php | 13 ---------- .../Views/RecordIdentifierStreamableTest.php | 9 ++++--- 6 files changed, 25 insertions(+), 50 deletions(-) delete mode 100644 src/Views/TurboStreamable.php create mode 100644 src/Views/UnidentifiableRecordException.php delete mode 100644 tests/TestTurboStreamable.php diff --git a/src/Views/RecordIdentifier.php b/src/Views/RecordIdentifier.php index 38f1c95..4764933 100644 --- a/src/Views/RecordIdentifier.php +++ b/src/Views/RecordIdentifier.php @@ -10,14 +10,14 @@ class RecordIdentifier const NEW_PREFIX = "create"; const DELIMITER = "_"; - /** @var Model|TurboStreamable */ + /** @var Model */ private $record; public function __construct(object $record) { throw_if( - ! $this->isStreamable($record), - sprintf('[%s] must be an instance of Eloquent or TurboStreamable.', get_class($record)) + ! method_exists($record, 'getKey'), + UnidentifiableRecordException::missingGetKeyMethod($record), ); $this->record = $record; @@ -25,7 +25,7 @@ public function __construct(object $record) public function domId(?string $prefix = null): string { - if ($recordId = $this->streamableKey()) { + if ($recordId = $this->record->getKey()) { return sprintf('%s%s%s', $this->domClass($prefix), self::DELIMITER, $recordId); } @@ -39,20 +39,4 @@ public function domClass(?string $prefix = null): string return trim("{$prefix}{$delimiter}{$singular}", $delimiter); } - - protected function streamableKey(): ?string - { - if ($this->record instanceof Model) { - return $this->record->getKey(); - } - - if ($this->record instanceof TurboStreamable) { - return $this->record->getDomId(); - } - } - - protected function isStreamable($record): bool - { - return $record instanceof Model || $record instanceof TurboStreamable; - } } diff --git a/src/Views/TurboStreamable.php b/src/Views/TurboStreamable.php deleted file mode 100644 index d1cf3b3..0000000 --- a/src/Views/TurboStreamable.php +++ /dev/null @@ -1,8 +0,0 @@ -assertEquals("custom_prefix_{$this->singular}_turbo-dom-id", (new RecordIdentifier($this->streamable))->domId("custom_prefix")); } - + /** @test */ public function exception_is_thrown_when_given_non_streamable_instance() { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('[stdClass] must be an instance of Eloquent or TurboStreamable.'); + $this->expectException(UnidentifiableRecordException::class); new RecordIdentifier(new stdClass); }