Breakpoint.php 10.7 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\breakpoint\Entity\Breakpoint.
6 7
 */

8
namespace Drupal\breakpoint\Entity;
9 10

use Drupal\Core\Config\Entity\ConfigEntityBase;
11
use Drupal\breakpoint\BreakpointInterface;
12 13 14 15 16
use Drupal\breakpoint\InvalidBreakpointException;
use Drupal\breakpoint\InvalidBreakpointNameException;
use Drupal\breakpoint\InvalidBreakpointSourceException;
use Drupal\breakpoint\InvalidBreakpointSourceTypeException;
use Drupal\breakpoint\InvalidBreakpointMediaQueryException;
17
use Drupal\Core\Entity\EntityStorageInterface;
18 19 20

/**
 * Defines the Breakpoint entity.
21
 *
22
 * @ConfigEntityType(
23 24 25 26
 *   id = "breakpoint",
 *   label = @Translation("Breakpoint"),
 *   entity_keys = {
 *     "id" = "id",
27
 *     "label" = "label"
28 29
 *   }
 * )
30
 */
31
class Breakpoint extends ConfigEntityBase implements BreakpointInterface {
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107

  /**
   * Denotes that a breakpoint or breakpoint group is defined by a theme.
   */
  const SOURCE_TYPE_THEME = 'theme';

  /**
   * Denotes that a breakpoint or breakpoint group is defined by a module.
   */
  const SOURCE_TYPE_MODULE = 'module';

  /**
   * Denotes that a breakpoint or breakpoint group is defined by the user.
   */
  const SOURCE_TYPE_USER_DEFINED = 'custom';

  /**
   * The breakpoint ID (config name).
   *
   * @var string
   */
  public $id;

  /**
   * The breakpoint name (machine name) as specified by theme or module.
   *
   * @var string
   */
  public $name;

  /**
   * The breakpoint label.
   *
   * @var string
   */
  public $label;

  /**
   * The breakpoint media query.
   *
   * @var string
   */
  public $mediaQuery = '';

  /**
   * The breakpoint source.
   *
   * @var string
   */
  public $source = 'user';

  /**
   * The breakpoint source type.
   *
   * @var string
   *   Allowed values:
   *     Breakpoint::SOURCE_TYPE_THEME
   *     Breakpoint::SOURCE_TYPE_MODULE
   *     Breakpoint::SOURCE_TYPE_USER_DEFINED
   */
  public $sourceType = Breakpoint::SOURCE_TYPE_USER_DEFINED;

  /**
   * The breakpoint weight.
   *
   * @var weight
   */
  public $weight = 0;

  /**
   * The breakpoint multipliers.
   *
   * @var multipliers
   */
  public $multipliers = array();

108 109 110 111 112 113 114 115 116 117 118 119 120 121
  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\breakpoint\InvalidBreakpointNameException
   *   Exception thrown if $values['name'] is empty.
   */
  public function __construct(array $values, $entity_type = 'breakpoint') {
    // Check required properties.
    if (empty($values['name'])) {
      throw new InvalidBreakpointNameException('Attempt to create an unnamed breakpoint.');
    }
    parent::__construct($values, $entity_type);
  }

122 123 124 125 126 127 128 129 130 131 132 133
  /**
   * {@inheritdoc}
   */
  public function id() {
    // If no ID is specified, build one from the properties that uniquely define
    // this breakpoint.
    if (!isset($this->id)) {
      $this->id = $this->sourceType . '.' . $this->source . '.' . $this->name;
    }
    return $this->id;
  }

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  /**
   * Overrides Drupal\config\ConfigEntityBase::save().
   */
  public function save() {
    // Check if everything is valid.
    if (!$this->isValid()) {
      throw new InvalidBreakpointException('Invalid data detected.');
    }

    // Set the label if none is set.
    if (empty($this->label)) {
      $this->label = $this->name;
    }

    // Remove unused multipliers.
    $this->multipliers = array_filter($this->multipliers);

    // Always add '1x' multiplier, use array_key_exists since the value might
    // be NULL.
    if (!array_key_exists('1x', $this->multipliers)) {
      $this->multipliers = array('1x' => '1x') + $this->multipliers;
    }
    return parent::save();
  }

  /**
160
   * {@inheritdoc}
161 162 163 164 165 166 167 168 169 170 171 172 173
   */
  public function isValid() {
    // Check for illegal values in breakpoint source type.
    if (!in_array($this->sourceType, array(
        Breakpoint::SOURCE_TYPE_USER_DEFINED,
        Breakpoint::SOURCE_TYPE_MODULE,
        Breakpoint::SOURCE_TYPE_THEME)
      )) {
      throw new InvalidBreakpointSourceTypeException(format_string('Invalid source type @source_type', array(
        '@source_type' => $this->sourceType,
      )));
    }
    // Check for illegal characters in breakpoint source.
174 175
    if (preg_match('/[^0-9a-z_]+/', $this->source)) {
      throw new InvalidBreakpointSourceException(format_string("Invalid value '@source' for breakpoint source property. Breakpoint source property can only contain lowercase alphanumeric characters and underscores.", array('@source' => $this->source)));
176 177 178 179 180 181 182 183 184
    }
    // Check for illegal characters in breakpoint names.
    if (preg_match('/[^0-9a-z_\-]/', $this->name)) {
      throw new InvalidBreakpointNameException(format_string("Invalid value '@name' for breakpoint name property. Breakpoint name property can only contain lowercase alphanumeric characters, underscores (_), and hyphens (-).", array('@name' => $this->name)));
    }
    return $this::isValidMediaQuery($this->mediaQuery);
  }

  /**
185
   * {@inheritdoc}
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
   */
  public static function isValidMediaQuery($media_query) {
    // Array describing all known media features and the expected value type or
    // an array containing the allowed values.
    $media_features = array(
      'width' => 'length', 'min-width' => 'length', 'max-width' => 'length',
      'height' => 'length', 'min-height' => 'length', 'max-height' => 'length',
      'device-width' => 'length', 'min-device-width' => 'length', 'max-device-width' => 'length',
      'device-height' => 'length', 'min-device-height' => 'length', 'max-device-height' => 'length',
      'orientation' => array('portrait', 'landscape'),
      'aspect-ratio' => 'ratio', 'min-aspect-ratio' => 'ratio', 'max-aspect-ratio' => 'ratio',
      'device-aspect-ratio' => 'ratio', 'min-device-aspect-ratio' => 'ratio', 'max-device-aspect-ratio' => 'ratio',
      'color' => 'integer', 'min-color' => 'integer', 'max-color' => 'integer',
      'color-index' => 'integer', 'min-color-index' => 'integer', 'max-color-index' => 'integer',
      'monochrome' => 'integer', 'min-monochrome' => 'integer', 'max-monochrome' => 'integer',
      'resolution' => 'resolution', 'min-resolution' => 'resolution', 'max-resolution' => 'resolution',
      'scan' => array('progressive', 'interlace'),
      'grid' => 'integer',
    );
    if ($media_query) {
      // Strip new lines and trim.
      $media_query = str_replace(array("\r", "\n"), ' ', trim($media_query));

      // Remove comments /* ... */.
      $media_query = preg_replace('/\/\*[\s\S]*?\*\//', '', $media_query);

      // Check media list.
      $parts = explode(',', $media_query);
      foreach ($parts as $part) {
        // Split on ' and '
        $query_parts = explode(' and ', trim($part));
        $media_type_found = FALSE;
        foreach ($query_parts as $query_part) {
          $matches = array();
          // Try to match: '(media_feature: value)' and variants.
          if (preg_match('/^\(([\w\-]+)(:\s?([\w\-\.]+))?\)/', trim($query_part), $matches)) {
            // Single expression like '(color)'.
            if (isset($matches[1]) && !isset($matches[2])) {
              if (!array_key_exists($matches[1], $media_features)) {
                throw new InvalidBreakpointMediaQueryException('Invalid media feature detected.');
              }
            }
            // Full expression like '(min-width: 20em)'.
            elseif (isset($matches[3]) && !isset($matches[4])) {
              $value = trim($matches[3]);
              if (!array_key_exists($matches[1], $media_features)) {
232 233
                // We need to allow vendor prefixed media features and make sure
                // we are future proof, so only check allowed characters.
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
                if (!preg_match('/^[a-zA-Z0-9\:\-\\ ]+$/i', trim($matches[1]))) {
                  throw new InvalidBreakpointMediaQueryException('Invalid media query detected.');
                }
              }
              elseif (is_array($media_features[$matches[1]])) {
                // Check if value is allowed.
                if (!array_key_exists($value, $media_features[$matches[1]])) {
                  throw new InvalidBreakpointMediaQueryException('Value is not allowed.');
                }
              }
              elseif (isset ($media_features[$matches[1]])) {
                switch ($media_features[$matches[1]]) {
                  case 'length':
                    $length_matches = array();
                    // Check for a valid number and an allowed unit.
                    if (preg_match('/^(\-)?(\d+(?:\.\d+)?)?((?:|em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|dpi|dpcm))$/i', trim($value), $length_matches)) {
                      // Only -0 is allowed.
                      if ($length_matches[1] === '-' && $length_matches[2] !== '0') {
                        throw new InvalidBreakpointMediaQueryException('Invalid length detected.');
                      }
                      // If there's a unit, a number is needed as well.
                      if ($length_matches[2] === '' && $length_matches[3] !== '') {
                        throw new InvalidBreakpointMediaQueryException('Unit found, value is missing.');
                      }
                    }
                    else {
                      throw new InvalidBreakpointMediaQueryException('Invalid unit detected.');
                    }
                    break;
                }
              }
            }
          }

          // Check for screen, only screen, not screen and variants.
          elseif (preg_match('/^((?:only|not)?\s?)([\w\-]+)$/i', trim($query_part), $matches)) {
            if ($media_type_found) {
              throw new InvalidBreakpointMediaQueryException('Only one media type is allowed.');
            }
            $media_type_found = TRUE;
          }
          // Check for (scan), (only scan), (not scan) and variants.
          elseif (preg_match('/^((?:only|not)\s?)\(([\w\-]+)\)$/i', trim($query_part), $matches)) {
            throw new InvalidBreakpointMediaQueryException('Invalid media query detected.');
          }
          else {
            // We need to allow vendor prefixed media fetures and make sure we
            // are future proof, so only check allowed characters.
            if (!preg_match('/^[a-zA-Z0-9\-\\ ]+$/i', trim($query_part), $matches)) {
              throw new InvalidBreakpointMediaQueryException('Invalid media query detected.');
            }
          }
        }
      }
      return TRUE;
    }
    throw new InvalidBreakpointMediaQueryException('Media query is empty.');
  }
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
    $this->dependencies = array();
    if ($this->sourceType == static::SOURCE_TYPE_MODULE) {
      $this->addDependency('module', $this->source);
    }
    elseif ($this->sourceType == static::SOURCE_TYPE_THEME) {
      $this->addDependency('theme', $this->source);
    }
    return $this->dependencies;
  }

308
}