cforge-2.0.x-dev/modules/cforge_gallery/src/Plugin/Block/RandomPhoto.php
modules/cforge_gallery/src/Plugin/Block/RandomPhoto.php
<?php
namespace Drupal\cforge_gallery\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Shows a random photo.
*
* @Block(
* id = "cforge_random_photo",
* label = "Random photo",
* admin_label = @Translation("Cforge random photo"),
* category = @Translation("Hamlets")
* )
*/
class RandomPhoto extends BlockBase implements ContainerFactoryPluginInterface {
private $entityTypeManager;
/**
* Constructor.
*/
public function __construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* Injection.
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static (
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$nids = $this->entityTypeManager
->getStorage('node')
->getQuery()->accessCheck(TRUE)->condition('type', 'image')
->execute();
$nids = array_values($nids);
if ($nids) {
$nid = $nids[rand(0, count($nids) - 1)];
return cforge_gallery_format_photo($nid);
}
}
/**
* Prevent anon from seeing photos.
*
* @param AccountInterface $account
* The current user.
*
* @return AccessResult
* The Access result.
*/
public function blockAccess(AccountInterface $account) {
return $account->isAuthenticated() ?
AccessResult::allowed() :
AccessResult::forbidden();
}
}
