You are here

class Barcode in Barcodes 2.0.x

Same name in this branch
  1. 2.0.x src/Template/Barcode.php \Drupal\barcodes\Template\Barcode
  2. 2.0.x src/Plugin/Block/Barcode.php \Drupal\barcodes\Plugin\Block\Barcode
  3. 2.0.x src/Plugin/Field/FieldFormatter/Barcode.php \Drupal\barcodes\Plugin\Field\FieldFormatter\Barcode
Same name and namespace in other branches
  1. 8 src/Plugin/Block/Barcode.php \Drupal\barcodes\Plugin\Block\Barcode

Provides a 'Barcode' block.

Plugin annotation


@Block(
 id = "barcode",
 admin_label = @Translation("Barcode"),
)

Hierarchy

Expanded class hierarchy of Barcode

File

src/Plugin/Block/Barcode.php, line 24

Namespace

Drupal\barcodes\Plugin\Block
View source
class Barcode extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * A logger instance.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * The token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * The currently active route match object.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * Construct.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module handler service.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The currently active route match object.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerInterface $logger, ModuleHandlerInterface $module_handler, Token $token, RouteMatchInterface $route_match) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->logger = $logger;
    $this->moduleHandler = $module_handler;
    $this->token = $token;
    $this->routeMatch = $route_match;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('logger.channel.barcodes'), $container
      ->get('module_handler'), $container
      ->get('token'), $container
      ->get('current_route_match'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'type' => 'QRCODE',
      'format' => 'SVG',
      'value' => '',
      'color' => '#000000',
      'height' => 100,
      'width' => 100,
      'padding_top' => 0,
      'padding_right' => 0,
      'padding_bottom' => 0,
      'padding_left' => 0,
      'show_value' => FALSE,
    ] + parent::defaultConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $generator = new BarcodeGenerator();
    $form['value'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Value'),
      '#description' => $this
        ->t('The Barcode value.'),
      '#default_value' => $this->configuration['value'],
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $form['value'] += [
        '#element_validate' => [
          'token_element_validate',
        ],
        '#token_types' => [
          'node',
        ],
      ];
      $form['token_help'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          'node',
        ],
      ];
    }
    $form['type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Barcode Type'),
      '#description' => $this
        ->t('The Barcode type.'),
      '#options' => array_combine($generator
        ->getTypes(), $generator
        ->getTypes()),
      '#default_value' => $this->configuration['type'],
    ];
    $form['format'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Display Format'),
      '#description' => $this
        ->t('The display format, e.g. png, svg, jpg.'),
      '#options' => [
        'PNG' => 'PNG Image',
        'SVG' => 'SVG Image',
        'HTMLDIV' => 'HTML DIV',
        'UNICODE' => 'Unicode String',
        'BINARY' => 'Binary String',
      ],
      '#default_value' => $this->configuration['format'],
    ];
    $form['color'] = [
      '#type' => 'color',
      '#title' => $this
        ->t('Color'),
      '#default_value' => $this->configuration['color'],
      '#description' => $this
        ->t('The color code.'),
    ];
    $form['height'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Height'),
      '#size' => 10,
      '#default_value' => $this->configuration['height'],
      '#description' => $this
        ->t('The height in pixels.'),
    ];
    $form['width'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Width'),
      '#size' => 10,
      '#default_value' => $this->configuration['width'],
      '#description' => $this
        ->t('The width in pixels'),
    ];
    $form['padding_top'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Padding-Top'),
      '#size' => 4,
      '#maxlength' => 4,
      '#default_value' => $this->configuration['padding_top'],
      '#description' => $this
        ->t('The top padding in pixels'),
    ];
    $form['padding_right'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Padding-Right'),
      '#size' => 4,
      '#maxlength' => 4,
      '#default_value' => $this->configuration['padding_right'],
      '#description' => $this
        ->t('The right padding in pixels'),
    ];
    $form['padding_bottom'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Padding-Bottom'),
      '#size' => 4,
      '#maxlength' => 4,
      '#default_value' => $this->configuration['padding_bottom'],
      '#description' => $this
        ->t('The bottom padding in pixels'),
    ];
    $form['padding_left'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Padding-Left'),
      '#size' => 4,
      '#maxlength' => 4,
      '#default_value' => $this->configuration['padding_left'],
      '#description' => $this
        ->t('The left padding in pixels'),
    ];
    $form['show_value'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Show value'),
      '#default_value' => $this->configuration['show_value'],
      '#description' => $this
        ->t('Show the actual value in addition to the barcode'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $this
      ->setConfiguration($values);
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];
    $generator = new BarcodeGenerator();
    $suffix = str_replace('+', 'plus', strtolower($this->configuration['type']));
    $tokens = [];
    $parameters = $this->routeMatch
      ->getParameters();
    foreach ($parameters as $parameter) {
      if ($parameter instanceof EntityInterface) {
        $tokens[$parameter
          ->getEntityTypeId()] = $parameter;
      }
    }
    $value = $this->token
      ->replace($this->configuration['value'], $tokens);
    $build['barcode'] = [
      '#theme' => 'barcode__' . $suffix,
      '#attached' => [
        'library' => [
          'barcodes/' . $suffix,
        ],
      ],
      '#type' => $this->configuration['type'],
      '#value' => $value,
      '#width' => $this->configuration['width'],
      '#height' => $this->configuration['height'],
      '#color' => $this->configuration['color'],
      '#padding_top' => $this->configuration['padding_top'],
      '#padding_right' => $this->configuration['padding_right'],
      '#padding_bottom' => $this->configuration['padding_bottom'],
      '#padding_left' => $this->configuration['padding_left'],
      '#show_value' => $this->configuration['show_value'],
    ];
    try {
      $barcode = $generator
        ->getBarcodeObj($this->configuration['type'], $value, $this->configuration['width'], $this->configuration['height'], $this->configuration['color'], [
        $this->configuration['padding_top'],
        $this->configuration['padding_right'],
        $this->configuration['padding_bottom'],
        $this->configuration['padding_left'],
      ]);
      $build['barcode']['#format'] = $this->configuration['format'];
      $build['barcode']['#svg'] = $barcode
        ->getSvgCode();
      $build['barcode']['#png'] = "<img alt=\"Embedded Image\" src=\"data:image/png;base64," . base64_encode($barcode
        ->getPngData()) . "\" />";
      $build['barcode']['#htmldiv'] = $barcode
        ->getHtmlDiv();
      $build['barcode']['#unicode'] = "<pre style=\"font-family:monospace;line-height:0.61em;font-size:6px;\">" . $barcode
        ->getGrid(json_decode('"\\u00A0"'), json_decode('"\\u2584"')) . "</pre>";
      $build['barcode']['#binary'] = "<pre style=\"font-family:monospace;\">" . $barcode
        ->getGrid() . "</pre>";
      $build['barcode']['#barcode'] = $build['barcode']['#' . strtolower($this->configuration['format'])];
      $build['barcode']['#extended_value'] = $barcode
        ->getExtendedCode();
    } catch (\Exception $e) {
      $this->logger
        ->error('Error: @error, given: @value', [
        '@error' => $e
          ->getMessage(),
        '@value' => $this->configuration['value'],
      ]);
    }
    return $build;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Barcode::$logger protected property A logger instance.
Barcode::$moduleHandler protected property The module handler service.
Barcode::$routeMatch protected property The currently active route match object.
Barcode::$token protected property The token service.
Barcode::blockForm public function Overrides BlockPluginTrait::blockForm
Barcode::blockSubmit public function Overrides BlockPluginTrait::blockSubmit
Barcode::build public function Builds and returns the renderable array for this block plugin. Overrides BlockPluginInterface::build
Barcode::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
Barcode::defaultConfiguration public function Overrides BlockPluginTrait::defaultConfiguration
Barcode::__construct public function Construct. Overrides BlockPluginTrait::__construct
BlockBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 2
BlockPluginInterface::BLOCK_LABEL_VISIBLE constant Indicates the block label (title) should be displayed to end users.
BlockPluginTrait::$transliteration protected property The transliteration service.
BlockPluginTrait::access public function
BlockPluginTrait::baseConfigurationDefaults protected function Returns generic default configuration for block plugins.
BlockPluginTrait::blockAccess protected function Indicates whether the block should be shown. 16
BlockPluginTrait::blockValidate public function 3
BlockPluginTrait::buildConfigurationForm public function Creates a generic configuration form for all block types. Individual block plugins can add elements to this form by overriding BlockBase::blockForm(). Most block plugins should not override this method unless they need to alter the generic form elements. Aliased as: traitBuildConfigurationForm
BlockPluginTrait::calculateDependencies public function
BlockPluginTrait::getConfiguration public function 1
BlockPluginTrait::getMachineNameSuggestion public function 1
BlockPluginTrait::getPreviewFallbackString public function 3
BlockPluginTrait::label public function
BlockPluginTrait::setConfiguration public function
BlockPluginTrait::setConfigurationValue public function
BlockPluginTrait::setTransliteration public function Sets the transliteration service.
BlockPluginTrait::submitConfigurationForm public function Most block plugins should not override this method. To add submission handling for a specific block type, override BlockBase::blockSubmit().
BlockPluginTrait::transliteration protected function Wraps the transliteration service.
BlockPluginTrait::validateConfigurationForm public function Most block plugins should not override this method. To add validation for a specific block type, override BlockBase::blockValidate(). 1
ContextAwarePluginAssignmentTrait::addContextAssignmentElement protected function Builds a form element for assigning a context to a given slot.
ContextAwarePluginAssignmentTrait::contextHandler protected function Wraps the context handler.
ContextAwarePluginTrait::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginTrait::$initializedContextConfig protected property Tracks whether the context has been initialized from configuration.
ContextAwarePluginTrait::getCacheContexts public function 9
ContextAwarePluginTrait::getCacheMaxAge public function 7
ContextAwarePluginTrait::getCacheTags public function 4
ContextAwarePluginTrait::getContext public function
ContextAwarePluginTrait::getContextDefinition public function
ContextAwarePluginTrait::getContextDefinitions public function
ContextAwarePluginTrait::getContextMapping public function
ContextAwarePluginTrait::getContexts public function
ContextAwarePluginTrait::getContextValue public function
ContextAwarePluginTrait::getContextValues public function
ContextAwarePluginTrait::getPluginDefinition abstract protected function 1
ContextAwarePluginTrait::setContext public function 1
ContextAwarePluginTrait::setContextMapping public function
ContextAwarePluginTrait::setContextValue public function
ContextAwarePluginTrait::validateContexts public function
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginWithFormsTrait::getFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::getFormClass().
PluginWithFormsTrait::hasFormClass public function Implements \Drupal\Core\Plugin\PluginWithFormsInterface::hasFormClass().
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.