diff --git a/src/Storage/FlysystemStorage.php b/src/Storage/FlysystemStorage.php index 6316a3b9..cf402a01 100644 --- a/src/Storage/FlysystemStorage.php +++ b/src/Storage/FlysystemStorage.php @@ -104,4 +104,24 @@ protected function getFilesystem(PropertyMapping $mapping): FilesystemOperator return $this->registry->get($mapping->getUploadDestination()); } + + public function resolveUri(object|array $obj, ?string $fieldName = null, ?string $className = null): ?string + { + $path = $this->resolvePath($obj, $fieldName, $className, true); + + if (empty($path)) { + return null; + } + + $mapping = null === $fieldName ? + $this->factory->fromFirstField($obj, $className) : + $this->factory->fromField($obj, $fieldName, $className); + $fs = $this->getFilesystem($mapping); + + try { + return $fs->publicUrl($path); + } catch (FilesystemException) { + return $mapping->getUriPrefix().'/'.$path; + } + } } diff --git a/tests/Storage/Flysystem/AbstractFlysystemStorageTest.php b/tests/Storage/Flysystem/AbstractFlysystemStorageTest.php index 8aeff0ab..4d15a73a 100644 --- a/tests/Storage/Flysystem/AbstractFlysystemStorageTest.php +++ b/tests/Storage/Flysystem/AbstractFlysystemStorageTest.php @@ -158,4 +158,27 @@ public static function pathProvider(): array ['foo', '/absolute/foo/file.txt', false], ]; } + + public function testResolveUri(): void + { + $this->mapping + ->expects(self::once()) + ->method('getUriPrefix') + ->willReturn('/uploads'); + + $this->mapping + ->expects(self::once()) + ->method('getFileName') + ->willReturn('file.txt'); + + $this->factory + ->expects(self::once()) + ->method('fromField') + ->with($this->object, 'file_field') + ->willReturn($this->mapping); + + $path = $this->getStorage()->resolveUri($this->object, 'file_field'); + + self::assertEquals('/uploads/file.txt', $path); + } }