You are here

class Barcode in Barcodes 8

Same name in this branch
  1. 8 src/Template/Barcode.php \Drupal\barcodes\Template\Barcode
  2. 8 src/Plugin/Block/Barcode.php \Drupal\barcodes\Plugin\Block\Barcode
  3. 8 src/Plugin/Field/FieldFormatter/Barcode.php \Drupal\barcodes\Plugin\Field\FieldFormatter\Barcode
Same name and namespace in other branches
  1. 2.0.x 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 21

Namespace

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

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

  /**
   * 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.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, LoggerInterface $logger) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->logger = $logger;
  }

  /**
   * {@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'));
  }

  /**
   * {@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 (\Drupal::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 = [];
    $token_service = \Drupal::token();
    $generator = new BarcodeGenerator();
    $suffix = str_replace('+', 'plus', strtolower($this->configuration['type']));
    $tokens = [];
    $parameters = \Drupal::routeMatch()
      ->getParameters();
    foreach ($parameters as $parameter) {
      if ($parameter instanceof EntityInterface) {
        $tokens[$parameter
          ->getEntityTypeId()] = $parameter;
      }
    }
    $value = $token_service
      ->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::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
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. 2
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.
ContextAwarePluginBase::$context protected property The data objects representing the context of this plugin.
ContextAwarePluginBase::$contexts Deprecated private property Data objects representing the contexts passed in the plugin configuration.
ContextAwarePluginBase::createContextFromConfiguration protected function Overrides ContextAwarePluginBase::createContextFromConfiguration
ContextAwarePluginBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyInterface::getCacheContexts 9
ContextAwarePluginBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyInterface::getCacheMaxAge 7
ContextAwarePluginBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyInterface::getCacheTags 4
ContextAwarePluginBase::getContext public function This code is identical to the Component in order to pick up a different Context class. Overrides ContextAwarePluginBase::getContext
ContextAwarePluginBase::getContextDefinition public function Overrides ContextAwarePluginBase::getContextDefinition
ContextAwarePluginBase::getContextDefinitions public function Overrides ContextAwarePluginBase::getContextDefinitions
ContextAwarePluginBase::getContextMapping public function Gets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::getContextMapping
ContextAwarePluginBase::getContexts public function Gets the defined contexts. Overrides ContextAwarePluginInterface::getContexts
ContextAwarePluginBase::getContextValue public function Gets the value for a defined context. Overrides ContextAwarePluginInterface::getContextValue
ContextAwarePluginBase::getContextValues public function Gets the values for all defined contexts. Overrides ContextAwarePluginInterface::getContextValues
ContextAwarePluginBase::setContext public function Set a context on this plugin. Overrides ContextAwarePluginBase::setContext
ContextAwarePluginBase::setContextMapping public function Sets a mapping of the expected assignment names to their context names. Overrides ContextAwarePluginInterface::setContextMapping
ContextAwarePluginBase::setContextValue public function Sets the value for a defined context. Overrides ContextAwarePluginBase::setContextValue
ContextAwarePluginBase::validateContexts public function Validates the set values for the defined contexts. Overrides ContextAwarePluginInterface::validateContexts
ContextAwarePluginBase::__get public function Implements magic __get() method.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
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::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
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
PluginWithFormsTrait::hasFormClass public function
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.
TypedDataTrait::$typedDataManager protected property The typed data manager used for creating the data types.
TypedDataTrait::getTypedDataManager public function Gets the typed data manager. 2
TypedDataTrait::setTypedDataManager public function Sets the typed data manager. 2