Improve error message when invalid sheet name set

Instead of listing all the requirements, only list the requirements that actually failed to be met.
This commit is contained in:
Adrien Loison 2016-11-29 14:19:22 -08:00
parent e255895cff
commit dae47cd9b7

View File

@ -75,14 +75,7 @@ class Sheet
*/ */
public function setName($name) public function setName($name)
{ {
if (!$this->isNameValid($name)) { $this->throwIfNameIsInvalid($name);
$errorMessage = "The sheet's name is invalid. It did not meet at least one of these requirements:\n";
$errorMessage .= " - It should not be blank\n";
$errorMessage .= " - It should not exceed 31 characters\n";
$errorMessage .= " - It should not contain these characters: \\ / ? * : [ or ]\n";
$errorMessage .= " - It should be unique";
throw new InvalidSheetNameException($errorMessage);
}
$this->name = $name; $this->name = $name;
self::$SHEETS_NAME_USED[$this->index] = $name; self::$SHEETS_NAME_USED[$this->index] = $name;
@ -91,27 +84,49 @@ class Sheet
} }
/** /**
* Returns whether the given sheet's name is valid. * Throws an exception if the given sheet's name is not valid.
* @see Sheet::setName for validity rules. * @see Sheet::setName for validity rules.
* *
* @param string $name * @param string $name
* @return bool TRUE if the name is valid, FALSE otherwise. * @return void
* @throws \Box\Spout\Writer\Exception\InvalidSheetNameException If the sheet's name is invalid.
*/ */
protected function isNameValid($name) protected function throwIfNameIsInvalid($name)
{ {
if (!is_string($name)) { if (!is_string($name)) {
return false; $actualType = gettype($name);
$errorMessage = "The sheet's name is invalid. It must be a string ($actualType given).";
throw new InvalidSheetNameException($errorMessage);
} }
$failedRequirements = [];
$nameLength = $this->stringHelper->getStringLength($name); $nameLength = $this->stringHelper->getStringLength($name);
return ( if (!$this->isNameUnique($name)) {
$nameLength > 0 && $failedRequirements[] = 'It should be unique';
$nameLength <= self::MAX_LENGTH_SHEET_NAME && } else {
!$this->doesContainInvalidCharacters($name) && if ($nameLength === 0) {
$this->isNameUnique($name) && $failedRequirements[] = 'It should not be blank';
!$this->doesStartOrEndWithSingleQuote($name) } else {
); if ($nameLength > self::MAX_LENGTH_SHEET_NAME) {
$failedRequirements[] = 'It should not exceed 31 characters';
}
if ($this->doesContainInvalidCharacters($name)) {
$failedRequirements[] = 'It should not contain these characters: \\ / ? * : [ or ]';
}
if ($this->doesStartOrEndWithSingleQuote($name)) {
$failedRequirements[] = 'It should not start or end with a single quote';
}
}
}
if (count($failedRequirements) !== 0) {
$errorMessage = "The sheet's name (\"$name\") is invalid. It did not respect these rules:\n - ";
$errorMessage .= implode("\n - ", $failedRequirements);
throw new InvalidSheetNameException($errorMessage);
}
} }
/** /**