I need to get absolute path of image in service. For example
/var/www/shop/public/media/a6/a0/27/1681870318/b86e01f8caac46fec00a3db724c00c79.jpg
.
I have entity of MediaRepository, but it only provides getUrl();
function.
You're supposed to use the filesystem abstraction so you don't have to deal with full paths and stay within the constraints of the abstraction.
You inject shopware.filesystem.public
and UrlGeneratorInterface
to build a relative path and use the relative path for filesystem operations using the abstraction.
<service id="MyPlugin\Core\Content\Media\File\PathFinder">
<!-- ... -->
<argument type="service" id="shopware.filesystem.public"/>
<argument type="service" id="Shopware\Core\Content\Media\Pathname\UrlGeneratorInterface"/>
</service>
$media = $this->mediaRepository->search(new Criteria([$mediaId]), $context)->get($mediaId);
$path = $this->urlGenerator->getRelativeMediaUrl($media);
// read, copy, delete, save the file using the filesystem abstraction
$this->publicFilesystem->read($path);
If you absolutely must, you can read the file as a stream and retrieve the absolute path from the resource
object.
$stream = $this->publicFilesystem->readStream($path);
$metaData = stream_get_meta_data($stream);
$absolutePath = $metaData['uri'];