View source
<?php
namespace Drupal\radioactivity;
use Drupal\Core\Site\Settings;
use Drupal\Component\Serialization\Json;
class Incident {
private $field_name;
private $entity_type;
private $entity_id;
private $energy;
private $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;
}
public function isValid() {
return strcmp($this->hash, $this
->calculateHash()) === 0;
}
private function calculateHash() {
return sha1(implode('##', [
$this->field_name,
$this->entity_type,
$this->entity_id,
$this->energy,
Settings::getHashSalt(),
]));
}
public function toJson() {
return Json::encode([
'fn' => $this->field_name,
'et' => $this->entity_type,
'id' => $this->entity_id,
'e' => $this->energy,
'h' => $this
->calculateHash(),
]);
}
public static function createFromPostData($data) {
return new Incident($data['fn'], $data['et'], $data['id'], $data['e'], $data['h']);
}
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;
}
}