DefaultContentHandler.php in Fixed Block Content 8
File
src/DefaultContentHandler.php
View source
<?php
namespace Drupal\fixed_block_content;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\Serializer;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\hal\LinkManager\LinkManager;
use Drupal\Core\Entity\EntityTypeInterface;
use Psr\Log\LoggerInterface;
use Drupal\block_content\Entity\BlockContent;
class DefaultContentHandler implements DefaultContentHandlerInterface {
protected $serializer;
protected $cache;
protected $linkManager;
protected $logger;
public function __construct(Serializer $serializer, CacheBackendInterface $cache, LinkManager $link_manager, LoggerInterface $logger) {
$this->serializer = $serializer;
$this->cache = $cache;
$this->linkManager = $link_manager;
$this->logger = $logger;
}
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($container
->get('serializer'), $container
->get('cache.default'), $container
->get('hal.link_manager'), $container
->get('logger.factory')
->get('fixed_block_content'));
}
public function exportDefaultContent(FixedBlockContentInterface $fixed_block) {
if (empty($fixed_block
->get('default_content'))) {
return NULL;
}
$new_block_content = NULL;
try {
$this->linkManager
->setLinkDomain('http://fixed_block_content.drupal.org');
$this->cache
->invalidate('hal:links:types');
$new_block_content = $this->serializer
->deserialize($fixed_block
->get('default_content'), BlockContent::class, 'hal_json', [
'fixed_block_content' => $fixed_block,
]);
} catch (\Exception $e) {
try {
$message = $e
->getMessage();
$new_block_content = $this->serializer
->deserialize($fixed_block
->get('default_content'), BlockContent::class, 'json', [
'fixed_block_content' => $fixed_block,
]);
} catch (\Exception $e) {
$this->logger
->error('Unable to export default content for fixed block %id, deserialization fails with message "%message"', [
'%id' => $fixed_block
->id(),
'%message' => $message,
]);
}
}
if ($new_block_content) {
$new_block_content
->set('reusable', !$fixed_block
->isProtected());
}
$this->linkManager
->setLinkDomain('');
$this->cache
->invalidate('hal:links:types');
return $new_block_content;
}
public function importDefaultContent(FixedBlockContentInterface $fixed_block) {
$this->linkManager
->setLinkDomain('http://fixed_block_content.drupal.org');
$fixed_block
->set('default_content', $this->serializer
->serialize($fixed_block
->getBlockContent(), 'hal_json', [
'fixed_block_content' => $fixed_block,
]));
$this->linkManager
->setLinkDomain('');
}
}