<?php

final class ExtensionStoreExtensionKeyTransaction
  extends ExtensionStoreExtensionTransactionType {

  const TRANSACTIONTYPE = 'est:extension:key';

  public function generateOldValue($object) {
    return $object->getExtensionKey();
  }

  public function applyInternalEffects($object, $value) {
    $object->setExtensionKey($value);
  }

  public function validateTransactions($object, array $xactions) {
    $errors = array();

    if ($this->isEmptyTextTransaction($object->getName(), $xactions)) {
      $errors[] = $this->newRequiredError(
        pht('Extensions must have a unique extension key.'));
    }

    if (!$this->isNewObject()) {
      foreach ($xactions as $xaction) {
        $errors[] = $this->newInvalidError(
          pht('Once a extension is created, its key can not be changed.'),
          $xaction);
      }
    }

    foreach ($xactions as $xaction) {
      $value = $xaction->getNewValue();
      try {
        PhabricatorPackagesPackage::assertValidPackageName($value); // TODO bring it here
      } catch (Throwable $ex) {
        $errors[] = $this->newInvalidError($ex->getMessage(), $xaction);
      }
    }

    return $errors;
  }

}
