You are here

Incident.php in Radioactivity 8.2

Same filename and directory in other branches
  1. 8.3 src/Incident.php
  2. 4.0.x src/Incident.php

File

src/Incident.php
View source
<?php

namespace Drupal\radioactivity;

use Drupal\Core\Site\Settings;
use Drupal\Component\Serialization\Json;

/**
 * Incident class
 */
class Incident {
  private $field_name;
  private $entity_type;
  private $entity_id;
  private $energy;
  private $hash;

  /**
   * Constructor
   * @param type $field_name
   * @param type $entity_type
   * @param type $entity_id
   * @param type $energy
   * @param type|null $hash
   */
  public function __construct($field_name, $entity_type, $entity_id, $energy, $hash = null) {
    $this->field_name = $field_name;
    $this->entity_type = $entity_type;
    $this->entity_id = $entity_id;
    $this->energy = $energy;
    $this->hash = $hash;
  }

  /**
   * Test validity of the Incident
   * @return boolean
   */
  public function isValid() {
    return strcmp($this->hash, $this
      ->calculateHash()) === 0;
  }

  /**
   * Calculate hash for this incident
   * @return string
   */
  private function calculateHash() {
    return sha1(implode('##', [
      $this->field_name,
      $this->entity_type,
      $this->entity_id,
      $this->energy,
      Settings::getHashSalt(),
    ]));
  }

  /**
   * Convert to JSON format
   * @return string
   */
  public function toJson() {
    return Json::encode([
      'fn' => $this->field_name,
      'et' => $this->entity_type,
      'id' => $this->entity_id,
      'e' => $this->energy,
      'h' => $this
        ->calculateHash(),
    ]);
  }

  /**
   * Create an Incident from data received in an http request
   * @param type $data
   * @return Incident
   */
  public static function createFromPostData($data) {
    return new Incident($data['fn'], $data['et'], $data['id'], $data['e'], $data['h']);
  }

  /**
   * Create an Incident from field items, a certain item within it and a formatter.
   * @param type $items
   * @param type $item
   * @param type $formatter
   * @return Incident
   */
  public static function createFromFieldItemsAndFormatter($items, $item, $formatter) {
    return new Incident($items
      ->getName(), $item
      ->getEntity()
      ->getEntityTypeId(), $item
      ->getEntity()
      ->id(), $formatter
      ->getSetting('energy'));
  }
  public function getFieldName() {
    return $this->field_name;
  }
  public function getEntityTypeId() {
    return $this->entity_type;
  }
  public function getEntityId() {
    return $this->entity_id;
  }
  public function getEnergy() {
    return $this->energy;
  }

}

Classes

Namesort descending Description
Incident Incident class