getSharedStimulusResourceSpecification()->isSatisfiedBy($mediaResource)) { return (string)$contents; } $xmlDocument = new XmlDocument(); $xmlDocument->loadFromString((string)$contents); foreach ($this->getComponents($xmlDocument) as $component) { $mediaAsset = $this->getMediaAsset($component); if ($mediaAsset) { $this->replaceComponentPath($component, $mediaAsset); } } return $xmlDocument->saveToString(); } private function replaceComponentPath(BodyElement $component, MediaAsset $mediaAsset): void { $mediaSource = $mediaAsset->getMediaSource(); $fileInfo = $mediaSource->getFileInfo($mediaAsset->getMediaIdentifier()); $stream = $this->getFileManagement()->getFileStream($fileInfo['link']); $contents = $stream->getContents(); $base64Content = $this->getEncodedSource($fileInfo['mime'], $contents); $this->setComponentSource($component, $base64Content); } public function withMediaResolver(TaoMediaResolver $mediaResolver): self { $this->mediaResolver = $mediaResolver; return $this; } private function getMediaResolver(): TaoMediaResolver { if (!$this->mediaResolver) { return $this->mediaResolver = new TaoMediaResolver(); } return $this->mediaResolver; } /** * @return BodyElement[] */ private function getComponents(XmlDocument $xmlDocument): array { $components = []; foreach (self::PROCESS_XML_ELEMENTS as $element) { $components = array_merge( $components, $xmlDocument->getDocumentComponent() ->getComponentsByClassName($element) ->getArrayCopy() ); } return $components; } private function getComponentSource(BodyElement $element): string { if ($element instanceof Img) { return $element->getSrc(); } if ($element instanceof QtiObject) { return $element->getData(); } throw new LogicException(sprintf('Body element [%s] not supported', get_class($element))); } private function setComponentSource(BodyElement $element, string $source): void { if ($element instanceof Img) { $element->setSrc($source); } if ($element instanceof QtiObject) { $element->setData($source); } } /** * @throws Exception */ private function getMediaAsset(BodyElement $component): ?MediaAsset { try { $source = $this->getComponentSource($component); $mediaAsset = $this->getMediaResolver() ->resolve($source); $mediaSource = $mediaAsset->getMediaSource(); return $mediaSource instanceof MediaSource ? $mediaAsset : null; } catch (TaoMediaException $exception) { return null; } } private function getEncodedSource(string $mimeType, string $content): string { return 'data:' . $mimeType . ';base64,' . base64_encode($content); } private function getFileManagement(): FileManagement { return $this->getServiceLocator()->get(FileManagement::SERVICE_ID); } private function getSharedStimulusResourceSpecification(): SharedStimulusResourceSpecification { return $this->getServiceLocator()->get(SharedStimulusResourceSpecification::class); } }