Sane argument names in the various classes

This commit is contained in:
MarkBaker 2020-11-05 19:15:01 +01:00
parent b12cebe1f5
commit cf6abbc10e
18 changed files with 346 additions and 347 deletions

View File

@ -137,24 +137,24 @@ abstract class Coordinate
/** /**
* Build range from coordinate strings. * Build range from coordinate strings.
* *
* @param array $range Array containg one or more arrays containing one or two coordinate strings * @param array $rangea Array containg one or more arrays containing one or two coordinate strings
* *
* @return string String representation of $pRange * @return string String representation of $pRange
*/ */
public static function buildRange(array $range) public static function buildRange(array $rangea)
{ {
// Verify range // Verify range
if (empty($range) || !is_array($range[0])) { if (empty($rangea) || !is_array($rangea[0])) {
throw new Exception('Range does not contain any information'); throw new Exception('Range does not contain any information');
} }
// Build range // Build range
$counter = count($range); $counter = count($rangea);
for ($i = 0; $i < $counter; ++$i) { for ($i = 0; $i < $counter; ++$i) {
$range[$i] = implode(':', $range[$i]); $rangea[$i] = implode(':', $rangea[$i]);
} }
return implode(',', $range); return implode(',', $rangea);
} }
/** /**

View File

@ -92,7 +92,7 @@ class Properties
/** /**
* Custom Properties. * Custom Properties.
* *
* @var string * @var array
*/ */
private $customProperties = []; private $customProperties = [];
@ -144,13 +144,13 @@ class Properties
/** /**
* Set Last Modified By. * Set Last Modified By.
* *
* @param string $pValue * @param string $modifiedBy
* *
* @return $this * @return $this
*/ */
public function setLastModifiedBy($pValue) public function setLastModifiedBy($modifiedBy)
{ {
$this->lastModifiedBy = $pValue; $this->lastModifiedBy = $modifiedBy;
return $this; return $this;
} }
@ -165,26 +165,31 @@ class Properties
return $this->created; return $this->created;
} }
private function asTimeStamp($timestamp)
{
if ($timestamp === null) {
return time();
} elseif (is_string($timestamp)) {
if (is_numeric($timestamp)) {
return (int) $timestamp;
}
return strtotime($timestamp);
}
return $timestamp;
}
/** /**
* Set Created. * Set Created.
* *
* @param int|string $time * @param int|string $timestamp
* *
* @return $this * @return $this
*/ */
public function setCreated($time) public function setCreated($timestamp)
{ {
if ($time === null) { $this->created = $this->asTimeStamp($timestamp);
$time = time();
} elseif (is_string($time)) {
if (is_numeric($time)) {
$time = (int) $time;
} else {
$time = strtotime($time);
}
}
$this->created = $time;
return $this; return $this;
} }
@ -202,23 +207,13 @@ class Properties
/** /**
* Set Modified. * Set Modified.
* *
* @param int|string $time * @param int|string $timestamp
* *
* @return $this * @return $this
*/ */
public function setModified($time) public function setModified($timestamp)
{ {
if ($time === null) { $this->modified = $this->asTimeStamp($timestamp);
$time = time();
} elseif (is_string($time)) {
if (is_numeric($time)) {
$time = (int) $time;
} else {
$time = strtotime($time);
}
}
$this->modified = $time;
return $this; return $this;
} }
@ -394,7 +389,7 @@ class Properties
/** /**
* Get a List of Custom Property Names. * Get a List of Custom Property Names.
* *
* @return array of string * @return array
*/ */
public function getCustomProperties() public function getCustomProperties()
{ {
@ -425,6 +420,8 @@ class Properties
if (isset($this->customProperties[$propertyName])) { if (isset($this->customProperties[$propertyName])) {
return $this->customProperties[$propertyName]['value']; return $this->customProperties[$propertyName]['value'];
} }
return null;
} }
/** /**
@ -432,13 +429,15 @@ class Properties
* *
* @param string $propertyName * @param string $propertyName
* *
* @return string * @return mixed
*/ */
public function getCustomPropertyType($propertyName) public function getCustomPropertyType($propertyName)
{ {
if (isset($this->customProperties[$propertyName])) { if (isset($this->customProperties[$propertyName])) {
return $this->customProperties[$propertyName]['type']; return $this->customProperties[$propertyName]['type'];
} }
return null;
} }
/** /**

View File

@ -73,13 +73,13 @@ class Security
/** /**
* Set LockRevision. * Set LockRevision.
* *
* @param bool $pValue * @param bool $locked
* *
* @return $this * @return $this
*/ */
public function setLockRevision($pValue) public function setLockRevision($locked)
{ {
$this->lockRevision = $pValue; $this->lockRevision = $locked;
return $this; return $this;
} }
@ -97,13 +97,13 @@ class Security
/** /**
* Set LockStructure. * Set LockStructure.
* *
* @param bool $pValue * @param bool $locked
* *
* @return $this * @return $this
*/ */
public function setLockStructure($pValue) public function setLockStructure($locked)
{ {
$this->lockStructure = $pValue; $this->lockStructure = $locked;
return $this; return $this;
} }
@ -121,13 +121,13 @@ class Security
/** /**
* Set LockWindows. * Set LockWindows.
* *
* @param bool $pValue * @param bool $locked
* *
* @return $this * @return $this
*/ */
public function setLockWindows($pValue) public function setLockWindows($locked)
{ {
$this->lockWindows = $pValue; $this->lockWindows = $locked;
return $this; return $this;
} }
@ -145,17 +145,17 @@ class Security
/** /**
* Set RevisionsPassword. * Set RevisionsPassword.
* *
* @param string $pValue * @param string $password
* @param bool $pAlreadyHashed If the password has already been hashed, set this to true * @param bool $alreadyHashed If the password has already been hashed, set this to true
* *
* @return $this * @return $this
*/ */
public function setRevisionsPassword($pValue, $pAlreadyHashed = false) public function setRevisionsPassword($password, $alreadyHashed = false)
{ {
if (!$pAlreadyHashed) { if (!$alreadyHashed) {
$pValue = PasswordHasher::hashPassword($pValue); $password = PasswordHasher::hashPassword($password);
} }
$this->revisionsPassword = $pValue; $this->revisionsPassword = $password;
return $this; return $this;
} }
@ -173,17 +173,17 @@ class Security
/** /**
* Set WorkbookPassword. * Set WorkbookPassword.
* *
* @param string $pValue * @param string $password
* @param bool $pAlreadyHashed If the password has already been hashed, set this to true * @param bool $alreadyHashed If the password has already been hashed, set this to true
* *
* @return $this * @return $this
*/ */
public function setWorkbookPassword($pValue, $pAlreadyHashed = false) public function setWorkbookPassword($password, $alreadyHashed = false)
{ {
if (!$pAlreadyHashed) { if (!$alreadyHashed) {
$pValue = PasswordHasher::hashPassword($pValue); $password = PasswordHasher::hashPassword($password);
} }
$this->workbookPassword = $pValue; $this->workbookPassword = $password;
return $this; return $this;
} }

View File

@ -684,9 +684,9 @@ class Html
$this->stringData = ''; $this->stringData = '';
} }
protected function rgbToColour($rgb) protected function rgbToColour($rgbValue)
{ {
preg_match_all('/\d+/', $rgb, $values); preg_match_all('/\d+/', $rgbValue, $values);
foreach ($values[0] as &$value) { foreach ($values[0] as &$value) {
$value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT);
} }
@ -694,9 +694,9 @@ class Html
return implode('', $values[0]); return implode('', $values[0]);
} }
public static function colourNameLookup(string $rgb): string public static function colourNameLookup(string $colorName): string
{ {
return self::$colourMap[$rgb] ?? ''; return self::$colourMap[$colorName] ?? '';
} }
protected function startFontTag($tag): void protected function startFontTag($tag): void

View File

@ -42,13 +42,13 @@ class RichText implements IComparable
/** /**
* Add text. * Add text.
* *
* @param ITextElement $pText Rich text element * @param ITextElement $text Rich text element
* *
* @return $this * @return $this
*/ */
public function addText(ITextElement $pText) public function addText(ITextElement $text)
{ {
$this->richTextElements[] = $pText; $this->richTextElements[] = $text;
return $this; return $this;
} }
@ -56,13 +56,13 @@ class RichText implements IComparable
/** /**
* Create text. * Create text.
* *
* @param string $pText Text * @param string $text Text
* *
* @return TextElement * @return TextElement
*/ */
public function createText($pText) public function createText($text)
{ {
$objText = new TextElement($pText); $objText = new TextElement($text);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;
@ -71,13 +71,13 @@ class RichText implements IComparable
/** /**
* Create text run. * Create text run.
* *
* @param string $pText Text * @param string $text Text
* *
* @return Run * @return Run
*/ */
public function createTextRun($pText) public function createTextRun($text)
{ {
$objText = new Run($pText); $objText = new Run($text);
$this->addText($objText); $this->addText($objText);
return $objText; return $objText;

View File

@ -16,11 +16,11 @@ class Run extends TextElement implements ITextElement
/** /**
* Create a new Run instance. * Create a new Run instance.
* *
* @param string $pText Text * @param string $text Text
*/ */
public function __construct($pText = '') public function __construct($text = '')
{ {
parent::__construct($pText); parent::__construct($text);
// Initialise variables // Initialise variables
$this->font = new Font(); $this->font = new Font();
} }
@ -38,13 +38,13 @@ class Run extends TextElement implements ITextElement
/** /**
* Set font. * Set font.
* *
* @param Font $pFont Font * @param Font $font Font
* *
* @return $this * @return $this
*/ */
public function setFont(?Font $pFont = null) public function setFont(?Font $font = null)
{ {
$this->font = $pFont; $this->font = $font;
return $this; return $this;
} }

View File

@ -14,12 +14,12 @@ class TextElement implements ITextElement
/** /**
* Create a new TextElement instance. * Create a new TextElement instance.
* *
* @param string $pText Text * @param string $text Text
*/ */
public function __construct($pText = '') public function __construct($text = '')
{ {
// Initialise variables // Initialise variables
$this->text = $pText; $this->text = $text;
} }
/** /**

View File

@ -65,17 +65,17 @@ class Date
/** /**
* Set the Excel calendar (Windows 1900 or Mac 1904). * Set the Excel calendar (Windows 1900 or Mac 1904).
* *
* @param int $baseDate Excel base date (1900 or 1904) * @param int $baseYear Excel base date (1900 or 1904)
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setExcelCalendar($baseDate) public static function setExcelCalendar($baseYear)
{ {
if ( if (
($baseDate == self::CALENDAR_WINDOWS_1900) || ($baseYear == self::CALENDAR_WINDOWS_1900) ||
($baseDate == self::CALENDAR_MAC_1904) ($baseYear == self::CALENDAR_MAC_1904)
) { ) {
self::$excelCalendar = $baseDate; self::$excelCalendar = $baseYear;
return true; return true;
} }
@ -252,17 +252,17 @@ class Date
/** /**
* Convert a Unix timestamp to an MS Excel serialized date/time value. * Convert a Unix timestamp to an MS Excel serialized date/time value.
* *
* @param int $dateValue Unix Timestamp * @param int $unixTimestamp Unix Timestamp
* *
* @return float MS Excel serialized date/time value * @return float MS Excel serialized date/time value
*/ */
public static function timestampToExcel($dateValue) public static function timestampToExcel($unixTimestamp)
{ {
if (!is_numeric($dateValue)) { if (!is_numeric($unixTimestamp)) {
return false; return false;
} }
return self::dateTimeToExcel(new \DateTime('@' . $dateValue)); return self::dateTimeToExcel(new \DateTime('@' . $unixTimestamp));
} }
/** /**
@ -332,9 +332,9 @@ class Date
* *
* @return bool * @return bool
*/ */
public static function isDateTimeFormat(NumberFormat $pFormat) public static function isDateTimeFormat(NumberFormat $excelFormatCode)
{ {
return self::isDateTimeFormatCode($pFormat->getFormatCode()); return self::isDateTimeFormatCode($excelFormatCode->getFormatCode());
} }
private static $possibleDateFormatCharacters = 'eymdHs'; private static $possibleDateFormatCharacters = 'eymdHs';
@ -342,23 +342,23 @@ class Date
/** /**
* Is a given number format code a date/time? * Is a given number format code a date/time?
* *
* @param string $pFormatCode * @param string $excelFormatCode
* *
* @return bool * @return bool
*/ */
public static function isDateTimeFormatCode($pFormatCode) public static function isDateTimeFormatCode($excelFormatCode)
{ {
if (strtolower($pFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) { if (strtolower($excelFormatCode) === strtolower(NumberFormat::FORMAT_GENERAL)) {
// "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check)
return false; return false;
} }
if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) { if (preg_match('/[0#]E[+-]0/i', $excelFormatCode)) {
// Scientific format // Scientific format
return false; return false;
} }
// Switch on formatcode // Switch on formatcode
switch ($pFormatCode) { switch ($excelFormatCode) {
// Explicitly defined date formats // Explicitly defined date formats
case NumberFormat::FORMAT_DATE_YYYYMMDD: case NumberFormat::FORMAT_DATE_YYYYMMDD:
case NumberFormat::FORMAT_DATE_YYYYMMDD2: case NumberFormat::FORMAT_DATE_YYYYMMDD2:
@ -386,21 +386,21 @@ class Date
} }
// Typically number, currency or accounting (or occasionally fraction) formats // Typically number, currency or accounting (or occasionally fraction) formats
if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) { if ((substr($excelFormatCode, 0, 1) == '_') || (substr($excelFormatCode, 0, 2) == '0 ')) {
return false; return false;
} }
// Some "special formats" provided in German Excel versions were detected as date time value, // Some "special formats" provided in German Excel versions were detected as date time value,
// so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany). // so filter them out here - "\C\H\-00000" (Switzerland) and "\D-00000" (Germany).
if (\strpos($pFormatCode, '-00000') !== false) { if (\strpos($excelFormatCode, '-00000') !== false) {
return false; return false;
} }
// Try checking for any of the date formatting characters that don't appear within square braces // Try checking for any of the date formatting characters that don't appear within square braces
if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $pFormatCode)) { if (preg_match('/(^|\])[^\[]*[' . self::$possibleDateFormatCharacters . ']/i', $excelFormatCode)) {
// We might also have a format mask containing quoted strings... // We might also have a format mask containing quoted strings...
// we don't want to test for any of our characters within the quoted blocks // we don't want to test for any of our characters within the quoted blocks
if (strpos($pFormatCode, '"') !== false) { if (strpos($excelFormatCode, '"') !== false) {
$segMatcher = false; $segMatcher = false;
foreach (explode('"', $pFormatCode) as $subVal) { foreach (explode('"', $excelFormatCode) as $subVal) {
// Only test in alternate array entries (the non-quoted blocks) // Only test in alternate array entries (the non-quoted blocks)
if ( if (
($segMatcher = !$segMatcher) && ($segMatcher = !$segMatcher) &&
@ -456,21 +456,21 @@ class Date
/** /**
* Converts a month name (either a long or a short name) to a month number. * Converts a month name (either a long or a short name) to a month number.
* *
* @param string $month Month name or abbreviation * @param string $monthName Month name or abbreviation
* *
* @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name * @return int|string Month number (1 - 12), or the original string argument if it isn't a valid month name
*/ */
public static function monthStringToNumber($month) public static function monthStringToNumber($monthName)
{ {
$monthIndex = 1; $monthIndex = 1;
foreach (self::$monthNames as $shortMonthName => $longMonthName) { foreach (self::$monthNames as $shortMonthName => $longMonthName) {
if (($month === $longMonthName) || ($month === $shortMonthName)) { if (($monthName === $longMonthName) || ($monthName === $shortMonthName)) {
return $monthIndex; return $monthIndex;
} }
++$monthIndex; ++$monthIndex;
} }
return $month; return $monthName;
} }
/** /**

View File

@ -7,26 +7,26 @@ class Drawing
/** /**
* Convert pixels to EMU. * Convert pixels to EMU.
* *
* @param int $pValue Value in pixels * @param int $pxValue Value in pixels
* *
* @return int Value in EMU * @return int Value in EMU
*/ */
public static function pixelsToEMU($pValue) public static function pixelsToEMU($pxValue)
{ {
return round($pValue * 9525); return round($pxValue * 9525);
} }
/** /**
* Convert EMU to pixels. * Convert EMU to pixels.
* *
* @param int $pValue Value in EMU * @param int $emValue Value in EMU
* *
* @return int Value in pixels * @return int Value in pixels
*/ */
public static function EMUToPixels($pValue) public static function EMUToPixels($emValue)
{ {
if ($pValue != 0) { if ($emValue != 0) {
return round($pValue / 9525); return round($emValue / 9525);
} }
return 0; return 0;
@ -37,24 +37,24 @@ class Drawing
* By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875 * By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875
* This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional.
* *
* @param int $pValue Value in pixels * @param int $pxValue Value in pixels
* @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook * @param \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Default font of the workbook
* *
* @return int Value in cell dimension * @return int Value in cell dimension
*/ */
public static function pixelsToCellDimension($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) public static function pixelsToCellDimension($pxValue, \PhpOffice\PhpSpreadsheet\Style\Font $defaultFont)
{ {
// Font name and size // Font name and size
$name = $pDefaultFont->getName(); $name = $defaultFont->getName();
$size = $pDefaultFont->getSize(); $size = $defaultFont->getSize();
if (isset(Font::$defaultColumnWidths[$name][$size])) { if (isset(Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined // Exact width can be determined
$colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['width'] / Font::$defaultColumnWidths[$name][$size]['px']; $colWidth = $pxValue * Font::$defaultColumnWidths[$name][$size]['width'] / Font::$defaultColumnWidths[$name][$size]['px'];
} else { } else {
// We don't have data for this particular font and size, use approximation by // We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11 // extrapolating from Calibri 11
$colWidth = $pValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; $colWidth = $pxValue * 11 * Font::$defaultColumnWidths['Calibri'][11]['width'] / Font::$defaultColumnWidths['Calibri'][11]['px'] / $size;
} }
return $colWidth; return $colWidth;
@ -63,12 +63,12 @@ class Drawing
/** /**
* Convert column width from (intrinsic) Excel units to pixels. * Convert column width from (intrinsic) Excel units to pixels.
* *
* @param float $pValue Value in cell dimension * @param float $excelSize Value in cell dimension
* @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook * @param \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont Default font of the workbook
* *
* @return int Value in pixels * @return int Value in pixels
*/ */
public static function cellDimensionToPixels($pValue, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont) public static function cellDimensionToPixels($excelSize, \PhpOffice\PhpSpreadsheet\Style\Font $pDefaultFont)
{ {
// Font name and size // Font name and size
$name = $pDefaultFont->getName(); $name = $pDefaultFont->getName();
@ -76,11 +76,11 @@ class Drawing
if (isset(Font::$defaultColumnWidths[$name][$size])) { if (isset(Font::$defaultColumnWidths[$name][$size])) {
// Exact width can be determined // Exact width can be determined
$colWidth = $pValue * Font::$defaultColumnWidths[$name][$size]['px'] / Font::$defaultColumnWidths[$name][$size]['width']; $colWidth = $excelSize * Font::$defaultColumnWidths[$name][$size]['px'] / Font::$defaultColumnWidths[$name][$size]['width'];
} else { } else {
// We don't have data for this particular font and size, use approximation by // We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11 // extrapolating from Calibri 11
$colWidth = $pValue * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; $colWidth = $excelSize * $size * Font::$defaultColumnWidths['Calibri'][11]['px'] / Font::$defaultColumnWidths['Calibri'][11]['width'] / 11;
} }
// Round pixels to closest integer // Round pixels to closest integer
@ -92,26 +92,26 @@ class Drawing
/** /**
* Convert pixels to points. * Convert pixels to points.
* *
* @param int $pValue Value in pixels * @param int $pxValue Value in pixels
* *
* @return float Value in points * @return float Value in points
*/ */
public static function pixelsToPoints($pValue) public static function pixelsToPoints($pxValue)
{ {
return $pValue * 0.67777777; return $pxValue * 0.67777777;
} }
/** /**
* Convert points to pixels. * Convert points to pixels.
* *
* @param int $pValue Value in points * @param int $ptValue Value in points
* *
* @return int Value in pixels * @return int Value in pixels
*/ */
public static function pointsToPixels($pValue) public static function pointsToPixels($ptValue)
{ {
if ($pValue != 0) { if ($ptValue != 0) {
return (int) ceil($pValue * 1.333333333); return (int) ceil($ptValue * 1.333333333);
} }
return 0; return 0;
@ -120,26 +120,26 @@ class Drawing
/** /**
* Convert degrees to angle. * Convert degrees to angle.
* *
* @param int $pValue Degrees * @param int $degrees Degrees
* *
* @return int Angle * @return int Angle
*/ */
public static function degreesToAngle($pValue) public static function degreesToAngle($degrees)
{ {
return (int) round($pValue * 60000); return (int) round($degrees * 60000);
} }
/** /**
* Convert angle to degrees. * Convert angle to degrees.
* *
* @param int $pValue Angle * @param int $angle Angle
* *
* @return int Degrees * @return int Degrees
*/ */
public static function angleToDegrees($pValue) public static function angleToDegrees($angle)
{ {
if ($pValue != 0) { if ($angle != 0) {
return round($pValue / 60000); return round($angle / 60000);
} }
return 0; return 0;
@ -150,14 +150,14 @@ class Drawing
* *
* @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 * @see http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214
* *
* @param string $p_sFile Path to Windows DIB (BMP) image * @param string $bmpFilename Path to Windows DIB (BMP) image
* *
* @return resource * @return resource
*/ */
public static function imagecreatefrombmp($p_sFile) public static function imagecreatefrombmp($bmpFilename)
{ {
// Load the image into a string // Load the image into a string
$file = fopen($p_sFile, 'rb'); $file = fopen($bmpFilename, 'rb');
$read = fread($file, 10); $read = fread($file, 10);
while (!feof($file) && ($read != '')) { while (!feof($file) && ($read != '')) {
$read .= fread($file, 1024); $read .= fread($file, 1024);

View File

@ -37,19 +37,19 @@ class File
/** /**
* Verify if a file exists. * Verify if a file exists.
* *
* @param string $pFilename Filename * @param string $filename Filename
* *
* @return bool * @return bool
*/ */
public static function fileExists($pFilename) public static function fileExists($filename)
{ {
// Sick construction, but it seems that // Sick construction, but it seems that
// file_exists returns strange values when // file_exists returns strange values when
// doing the original file_exists on ZIP archives... // doing the original file_exists on ZIP archives...
if (strtolower(substr($pFilename, 0, 3)) == 'zip') { if (strtolower(substr($filename, 0, 3)) == 'zip') {
// Open ZIP file and verify if the file exists // Open ZIP file and verify if the file exists
$zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); $zipFile = substr($filename, 6, strpos($filename, '#') - 6);
$archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); $archiveFile = substr($filename, strpos($filename, '#') + 1);
$zip = new ZipArchive(); $zip = new ZipArchive();
if ($zip->open($zipFile) === true) { if ($zip->open($zipFile) === true) {
@ -62,29 +62,29 @@ class File
return false; return false;
} }
return file_exists($pFilename); return file_exists($filename);
} }
/** /**
* Returns canonicalized absolute pathname, also for ZIP archives. * Returns canonicalized absolute pathname, also for ZIP archives.
* *
* @param string $pFilename * @param string $filename
* *
* @return string * @return string
*/ */
public static function realpath($pFilename) public static function realpath($filename)
{ {
// Returnvalue // Returnvalue
$returnValue = ''; $returnValue = '';
// Try using realpath() // Try using realpath()
if (file_exists($pFilename)) { if (file_exists($filename)) {
$returnValue = realpath($pFilename); $returnValue = realpath($filename);
} }
// Found something? // Found something?
if ($returnValue == '' || ($returnValue === null)) { if ($returnValue == '' || ($returnValue === null)) {
$pathArray = explode('/', $pFilename); $pathArray = explode('/', $filename);
while (in_array('..', $pathArray) && $pathArray[0] != '..') { while (in_array('..', $pathArray) && $pathArray[0] != '..') {
$iMax = count($pathArray); $iMax = count($pathArray);
for ($i = 0; $i < $iMax; ++$i) { for ($i = 0; $i < $iMax; ++$i) {

View File

@ -4,6 +4,7 @@ namespace PhpOffice\PhpSpreadsheet\Shared;
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException;
use PhpOffice\PhpSpreadsheet\RichText\RichText; use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Font as FontStyle;
class Font class Font
{ {
@ -163,16 +164,16 @@ class Font
/** /**
* Set autoSize method. * Set autoSize method.
* *
* @param string $pValue see self::AUTOSIZE_METHOD_* * @param string $method see self::AUTOSIZE_METHOD_*
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setAutoSizeMethod($pValue) public static function setAutoSizeMethod($method)
{ {
if (!in_array($pValue, self::$autoSizeMethods)) { if (!in_array($method, self::$autoSizeMethods)) {
return false; return false;
} }
self::$autoSizeMethod = $pValue; self::$autoSizeMethod = $method;
return true; return true;
} }
@ -196,11 +197,11 @@ class Font
* <li>~/.fonts/</li> * <li>~/.fonts/</li>
* </ul>. * </ul>.
* *
* @param string $pValue * @param string $folderPath
*/ */
public static function setTrueTypeFontPath($pValue): void public static function setTrueTypeFontPath($folderPath): void
{ {
self::$trueTypeFontPath = $pValue; self::$trueTypeFontPath = $folderPath;
} }
/** /**
@ -216,14 +217,14 @@ class Font
/** /**
* Calculate an (approximate) OpenXML column width, based on font size and text contained. * Calculate an (approximate) OpenXML column width, based on font size and text contained.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font Font object * @param FontStyle $font Font object
* @param RichText|string $cellText Text to calculate width * @param RichText|string $cellText Text to calculate width
* @param int $rotation Rotation angle * @param int $rotation Rotation angle
* @param null|\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont Font object * @param null|FontStyle $defaultFont Font object
* *
* @return int Column width * @return int Column width
*/ */
public static function calculateColumnWidth(\PhpOffice\PhpSpreadsheet\Style\Font $font, $cellText = '', $rotation = 0, ?\PhpOffice\PhpSpreadsheet\Style\Font $defaultFont = null) public static function calculateColumnWidth(FontStyle $font, $cellText = '', $rotation = 0, ?FontStyle $defaultFont = null)
{ {
// If it is rich text, use plain text // If it is rich text, use plain text
if ($cellText instanceof RichText) { if ($cellText instanceof RichText) {
@ -273,12 +274,12 @@ class Font
* Get GD text width in pixels for a string of text in a certain font at a certain rotation angle. * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle.
* *
* @param string $text * @param string $text
* @param \PhpOffice\PhpSpreadsheet\Style\Font * @param FontStyle
* @param int $rotation * @param int $rotation
* *
* @return int * @return int
*/ */
public static function getTextWidthPixelsExact($text, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0) public static function getTextWidthPixelsExact($text, FontStyle $font, $rotation = 0)
{ {
if (!function_exists('imagettfbbox')) { if (!function_exists('imagettfbbox')) {
throw new PhpSpreadsheetException('GD library needs to be enabled'); throw new PhpSpreadsheetException('GD library needs to be enabled');
@ -307,7 +308,7 @@ class Font
* *
* @return int Text width in pixels (no padding added) * @return int Text width in pixels (no padding added)
*/ */
public static function getTextWidthPixelsApprox($columnText, \PhpOffice\PhpSpreadsheet\Style\Font $font, $rotation = 0) public static function getTextWidthPixelsApprox($columnText, FontStyle $font, $rotation = 0)
{ {
$fontName = $font->getName(); $fontName = $font->getName();
$fontSize = $font->getSize(); $fontSize = $font->getSize();
@ -395,11 +396,11 @@ class Font
/** /**
* Returns the font path given the font. * Returns the font path given the font.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font * @param FontStyle $font
* *
* @return string Path to TrueType font file * @return string Path to TrueType font file
*/ */
public static function getTrueTypeFontFileFromFont($font) public static function getTrueTypeFontFileFromFont(FontStyle $font)
{ {
if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) { if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) {
throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified'); throw new PhpSpreadsheetException('Valid directory to TrueType Font files not specified');
@ -525,13 +526,13 @@ class Font
/** /**
* Returns the associated charset for the font name. * Returns the associated charset for the font name.
* *
* @param string $name Font name * @param string $fontName Font name
* *
* @return int Character set code * @return int Character set code
*/ */
public static function getCharsetFromFontName($name) public static function getCharsetFromFontName($fontName)
{ {
switch ($name) { switch ($fontName) {
// Add more cases. Check FONT records in real Excel files. // Add more cases. Check FONT records in real Excel files.
case 'EucrosiaUPC': case 'EucrosiaUPC':
return self::CHARSET_ANSI_THAI; return self::CHARSET_ANSI_THAI;
@ -550,28 +551,28 @@ class Font
* Get the effective column width for columns without a column dimension or column with width -1 * Get the effective column width for columns without a column dimension or column with width -1
* For example, for Calibri 11 this is 9.140625 (64 px). * For example, for Calibri 11 this is 9.140625 (64 px).
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font * @param FontStyle $font The workbooks default font
* @param bool $pPixels true = return column width in pixels, false = return in OOXML units * @param bool $returnAsPixels true = return column width in pixels, false = return in OOXML units
* *
* @return mixed Column width * @return mixed Column width
*/ */
public static function getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font, $pPixels = false) public static function getDefaultColumnWidthByFont(FontStyle $font, $returnAsPixels = false)
{ {
if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) { if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) {
// Exact width can be determined // Exact width can be determined
$columnWidth = $pPixels ? $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px']
: self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width'];
} else { } else {
// We don't have data for this particular font and size, use approximation by // We don't have data for this particular font and size, use approximation by
// extrapolating from Calibri 11 // extrapolating from Calibri 11
$columnWidth = $pPixels ? $columnWidth = $returnAsPixels ?
self::$defaultColumnWidths['Calibri'][11]['px'] self::$defaultColumnWidths['Calibri'][11]['px']
: self::$defaultColumnWidths['Calibri'][11]['width']; : self::$defaultColumnWidths['Calibri'][11]['width'];
$columnWidth = $columnWidth * $font->getSize() / 11; $columnWidth = $columnWidth * $font->getSize() / 11;
// Round pixels to closest integer // Round pixels to closest integer
if ($pPixels) { if ($returnAsPixels) {
$columnWidth = (int) round($columnWidth); $columnWidth = (int) round($columnWidth);
} }
} }
@ -583,11 +584,11 @@ class Font
* Get the effective row height for rows without a row dimension or rows with height -1 * Get the effective row height for rows without a row dimension or rows with height -1
* For example, for Calibri 11 this is 15 points. * For example, for Calibri 11 this is 15 points.
* *
* @param \PhpOffice\PhpSpreadsheet\Style\Font $font The workbooks default font * @param FontStyle $font The workbooks default font
* *
* @return float Row height in points * @return float Row height in points
*/ */
public static function getDefaultRowHeightByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font) public static function getDefaultRowHeightByFont(FontStyle $font)
{ {
switch ($font->getName()) { switch ($font->getName()) {
case 'Arial': case 'Arial':

View File

@ -109,15 +109,15 @@ class OLE
* *
* @acces public * @acces public
* *
* @param string $file * @param string $filename
* *
* @return bool true on success, PEAR_Error on failure * @return bool true on success, PEAR_Error on failure
*/ */
public function read($file) public function read($filename)
{ {
$fh = fopen($file, 'rb'); $fh = fopen($filename, 'rb');
if (!$fh) { if (!$fh) {
throw new ReaderException("Can't open file $file"); throw new ReaderException("Can't open file $filename");
} }
$this->_file_handle = $fh; $this->_file_handle = $fh;
@ -243,13 +243,13 @@ class OLE
/** /**
* Reads a signed char. * Reads a signed char.
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt1($fh) private static function readInt1($fileHandle)
{ {
[, $tmp] = unpack('c', fread($fh, 1)); [, $tmp] = unpack('c', fread($fileHandle, 1));
return $tmp; return $tmp;
} }
@ -257,13 +257,13 @@ class OLE
/** /**
* Reads an unsigned short (2 octets). * Reads an unsigned short (2 octets).
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt2($fh) private static function readInt2($fileHandle)
{ {
[, $tmp] = unpack('v', fread($fh, 2)); [, $tmp] = unpack('v', fread($fileHandle, 2));
return $tmp; return $tmp;
} }
@ -271,13 +271,13 @@ class OLE
/** /**
* Reads an unsigned long (4 octets). * Reads an unsigned long (4 octets).
* *
* @param resource $fh file handle * @param resource $fileHandle file handle
* *
* @return int * @return int
*/ */
private static function readInt4($fh) private static function readInt4($fileHandle)
{ {
[, $tmp] = unpack('V', fread($fh, 4)); [, $tmp] = unpack('V', fread($fileHandle, 4));
return $tmp; return $tmp;
} }

View File

@ -93,24 +93,24 @@ class OLERead
/** /**
* Read the file. * Read the file.
* *
* @param $pFilename string Filename * @param $filename string Filename
*/ */
public function read($pFilename): void public function read($filename): void
{ {
File::assertFile($pFilename); File::assertFile($filename);
// Get the file identifier // Get the file identifier
// Don't bother reading the whole file until we know it's a valid OLE file // Don't bother reading the whole file until we know it's a valid OLE file
$this->data = file_get_contents($pFilename, false, null, 0, 8); $this->data = file_get_contents($filename, false, null, 0, 8);
// Check OLE identifier // Check OLE identifier
$identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1); $identifierOle = pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1);
if ($this->data != $identifierOle) { if ($this->data != $identifierOle) {
throw new ReaderException('The filename ' . $pFilename . ' is not recognised as an OLE file'); throw new ReaderException('The filename ' . $filename . ' is not recognised as an OLE file');
} }
// Get the file data // Get the file data
$this->data = file_get_contents($pFilename); $this->data = file_get_contents($filename);
// Total number of sectors used for the SAT // Total number of sectors used for the SAT
$this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS);
@ -237,13 +237,12 @@ class OLERead
/** /**
* Read a standard stream (by joining sectors using information from SAT). * Read a standard stream (by joining sectors using information from SAT).
* *
* @param int $bl Sector ID where the stream starts * @param int $block Sector ID where the stream starts
* *
* @return string Data for standard stream * @return string Data for standard stream
*/ */
private function readData($bl) private function readData($block)
{ {
$block = $bl;
$data = ''; $data = '';
while ($block != -2) { while ($block != -2) {

View File

@ -44,26 +44,26 @@ class PasswordHasher
* Daniel Rentz of OpenOffice and the PEAR package * Daniel Rentz of OpenOffice and the PEAR package
* Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>. * Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>.
* *
* @param string $pPassword Password to hash * @param string $password Password to hash
*/ */
private static function defaultHashPassword(string $pPassword): string private static function defaultHashPassword(string $password): string
{ {
$password = 0x0000; $passwordValue = 0x0000;
$charPos = 1; // char position $charPos = 1; // char position
// split the plain text password in its component characters // split the plain text password in its component characters
$chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY); $chars = preg_split('//', $password, -1, PREG_SPLIT_NO_EMPTY);
foreach ($chars as $char) { foreach ($chars as $char) {
$value = ord($char) << $charPos++; // shifted ASCII value $value = ord($char) << $charPos++; // shifted ASCII value
$rotated_bits = $value >> 15; // rotated bits beyond bit 15 $rotated_bits = $value >> 15; // rotated bits beyond bit 15
$value &= 0x7fff; // first 15 bits $value &= 0x7fff; // first 15 bits
$password ^= ($value | $rotated_bits); $passwordValue ^= ($value | $rotated_bits);
} }
$password ^= strlen($pPassword); $passwordValue ^= strlen($password);
$password ^= 0xCE4B; $passwordValue ^= 0xCE4B;
return strtoupper(dechex($password)); return strtoupper(dechex($passwordValue));
} }
/** /**

View File

@ -294,15 +294,15 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element. * element or in the shared string <t> element.
* *
* @param string $value Value to unescape * @param string $textValue Value to unescape
* *
* @return string * @return string
*/ */
public static function controlCharacterOOXML2PHP($value) public static function controlCharacterOOXML2PHP($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value); return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $textValue);
} }
/** /**
@ -316,64 +316,64 @@ class StringHelper
* So you could end up with something like _x0008_ in a string (either in a cell value (<v>) * So you could end up with something like _x0008_ in a string (either in a cell value (<v>)
* element or in the shared string <t> element. * element or in the shared string <t> element.
* *
* @param string $value Value to escape * @param string $textValue Value to escape
* *
* @return string * @return string
*/ */
public static function controlCharacterPHP2OOXML($value) public static function controlCharacterPHP2OOXML($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value); return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $textValue);
} }
/** /**
* Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters. * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters.
* *
* @param string $value * @param string $textValue
* *
* @return string * @return string
*/ */
public static function sanitizeUTF8($value) public static function sanitizeUTF8($textValue)
{ {
if (self::getIsIconvEnabled()) { if (self::getIsIconvEnabled()) {
$value = @iconv('UTF-8', 'UTF-8', $value); $textValue = @iconv('UTF-8', 'UTF-8', $textValue);
return $value; return $textValue;
} }
$value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); $textValue = mb_convert_encoding($textValue, 'UTF-8', 'UTF-8');
return $value; return $textValue;
} }
/** /**
* Check if a string contains UTF8 data. * Check if a string contains UTF8 data.
* *
* @param string $value * @param string $textValue
* *
* @return bool * @return bool
*/ */
public static function isUTF8($value) public static function isUTF8($textValue)
{ {
return $value === '' || preg_match('/^./su', $value) === 1; return $textValue === '' || preg_match('/^./su', $textValue) === 1;
} }
/** /**
* Formats a numeric value as a string for output in various output writers forcing * Formats a numeric value as a string for output in various output writers forcing
* point as decimal separator in case locale is other than English. * point as decimal separator in case locale is other than English.
* *
* @param mixed $value * @param mixed $numericValue
* *
* @return string * @return string
*/ */
public static function formatNumber($value) public static function formatNumber($numericValue)
{ {
if (is_float($value)) { if (is_float($numericValue)) {
return str_replace(',', '.', $value); return str_replace(',', '.', $numericValue);
} }
return (string) $value; return (string) $numericValue;
} }
/** /**
@ -383,25 +383,25 @@ class StringHelper
* although this will give wrong results for non-ASCII strings * although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
* *
* @param string $value UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* @param mixed[] $arrcRuns Details of rich text runs in $value * @param mixed[] $arrcRuns Details of rich text runs in $value
* *
* @return string * @return string
*/ */
public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = []) public static function UTF8toBIFF8UnicodeShort($textValue, $arrcRuns = [])
{ {
// character count // character count
$ln = self::countCharacters($value, 'UTF-8'); $ln = self::countCharacters($textValue, 'UTF-8');
// option flags // option flags
if (empty($arrcRuns)) { if (empty($arrcRuns)) {
$data = pack('CC', $ln, 0x0001); $data = pack('CC', $ln, 0x0001);
// characters // characters
$data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
} else { } else {
$data = pack('vC', $ln, 0x09); $data = pack('vC', $ln, 0x09);
$data .= pack('v', count($arrcRuns)); $data .= pack('v', count($arrcRuns));
// characters // characters
$data .= self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $data .= self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
foreach ($arrcRuns as $cRun) { foreach ($arrcRuns as $cRun) {
$data .= pack('v', $cRun['strlen']); $data .= pack('v', $cRun['strlen']);
$data .= pack('v', $cRun['fontidx']); $data .= pack('v', $cRun['fontidx']);
@ -418,17 +418,17 @@ class StringHelper
* although this will give wrong results for non-ASCII strings * although this will give wrong results for non-ASCII strings
* see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3. * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3.
* *
* @param string $value UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function UTF8toBIFF8UnicodeLong($value) public static function UTF8toBIFF8UnicodeLong($textValue)
{ {
// character count // character count
$ln = self::countCharacters($value, 'UTF-8'); $ln = self::countCharacters($textValue, 'UTF-8');
// characters // characters
$chars = self::convertEncoding($value, 'UTF-16LE', 'UTF-8'); $chars = self::convertEncoding($textValue, 'UTF-16LE', 'UTF-8');
return pack('vC', $ln, 0x0001) . $chars; return pack('vC', $ln, 0x0001) . $chars;
} }
@ -436,91 +436,91 @@ class StringHelper
/** /**
* Convert string from one encoding to another. * Convert string from one encoding to another.
* *
* @param string $value * @param string $textValue
* @param string $to Encoding to convert to, e.g. 'UTF-8' * @param string $to Encoding to convert to, e.g. 'UTF-8'
* @param string $from Encoding to convert from, e.g. 'UTF-16LE' * @param string $from Encoding to convert from, e.g. 'UTF-16LE'
* *
* @return string * @return string
*/ */
public static function convertEncoding($value, $to, $from) public static function convertEncoding($textValue, $to, $from)
{ {
if (self::getIsIconvEnabled()) { if (self::getIsIconvEnabled()) {
$result = iconv($from, $to . self::$iconvOptions, $value); $result = iconv($from, $to . self::$iconvOptions, $textValue);
if (false !== $result) { if (false !== $result) {
return $result; return $result;
} }
} }
return mb_convert_encoding($value, $to, $from); return mb_convert_encoding($textValue, $to, $from);
} }
/** /**
* Get character count. * Get character count.
* *
* @param string $value * @param string $textValue
* @param string $enc Encoding * @param string $encoding Encoding
* *
* @return int Character count * @return int Character count
*/ */
public static function countCharacters($value, $enc = 'UTF-8') public static function countCharacters($textValue, $encoding = 'UTF-8')
{ {
return mb_strlen($value, $enc); return mb_strlen($textValue, $encoding);
} }
/** /**
* Get a substring of a UTF-8 encoded string. * Get a substring of a UTF-8 encoded string.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* @param int $pStart Start offset * @param int $offset Start offset
* @param int $pLength Maximum number of characters in substring * @param int $length Maximum number of characters in substring
* *
* @return string * @return string
*/ */
public static function substring($pValue, $pStart, $pLength = 0) public static function substring($textValue, $offset, $length = 0)
{ {
return mb_substr($pValue, $pStart, $pLength, 'UTF-8'); return mb_substr($textValue, $offset, $length, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to upper case. * Convert a UTF-8 encoded string to upper case.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToUpper($pValue) public static function strToUpper($textValue)
{ {
return mb_convert_case($pValue, MB_CASE_UPPER, 'UTF-8'); return mb_convert_case($textValue, MB_CASE_UPPER, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to lower case. * Convert a UTF-8 encoded string to lower case.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToLower($pValue) public static function strToLower($textValue)
{ {
return mb_convert_case($pValue, MB_CASE_LOWER, 'UTF-8'); return mb_convert_case($textValue, MB_CASE_LOWER, 'UTF-8');
} }
/** /**
* Convert a UTF-8 encoded string to title/proper case * Convert a UTF-8 encoded string to title/proper case
* (uppercase every first character in each word, lower case all other characters). * (uppercase every first character in each word, lower case all other characters).
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strToTitle($pValue) public static function strToTitle($textValue)
{ {
return mb_convert_case($pValue, MB_CASE_TITLE, 'UTF-8'); return mb_convert_case($textValue, MB_CASE_TITLE, 'UTF-8');
} }
public static function mbIsUpper($char) public static function mbIsUpper($character)
{ {
return mb_strtolower($char, 'UTF-8') != $char; return mb_strtolower($character, 'UTF-8') != $character;
} }
public static function mbStrSplit($string) public static function mbStrSplit($string)
@ -534,13 +534,13 @@ class StringHelper
* Reverse the case of a string, so that all uppercase characters become lowercase * Reverse the case of a string, so that all uppercase characters become lowercase
* and all lowercase characters become uppercase. * and all lowercase characters become uppercase.
* *
* @param string $pValue UTF-8 encoded string * @param string $textValue UTF-8 encoded string
* *
* @return string * @return string
*/ */
public static function strCaseReverse($pValue) public static function strCaseReverse($textValue)
{ {
$characters = self::mbStrSplit($pValue); $characters = self::mbStrSplit($textValue);
foreach ($characters as &$character) { foreach ($characters as &$character) {
if (self::mbIsUpper($character)) { if (self::mbIsUpper($character)) {
$character = mb_strtolower($character, 'UTF-8'); $character = mb_strtolower($character, 'UTF-8');
@ -601,11 +601,11 @@ class StringHelper
* Set the decimal separator. Only used by NumberFormat::toFormattedString() * Set the decimal separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for decimal separator * @param string $separator Character for decimal separator
*/ */
public static function setDecimalSeparator($pValue): void public static function setDecimalSeparator($separator): void
{ {
self::$decimalSeparator = $pValue; self::$decimalSeparator = $separator;
} }
/** /**
@ -634,11 +634,11 @@ class StringHelper
* Set the thousands separator. Only used by NumberFormat::toFormattedString() * Set the thousands separator. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for thousands separator * @param string $separator Character for thousands separator
*/ */
public static function setThousandsSeparator($pValue): void public static function setThousandsSeparator($separator): void
{ {
self::$thousandsSeparator = $pValue; self::$thousandsSeparator = $separator;
} }
/** /**
@ -672,51 +672,51 @@ class StringHelper
* Set the currency code. Only used by NumberFormat::toFormattedString() * Set the currency code. Only used by NumberFormat::toFormattedString()
* to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf. * to format output by \PhpOffice\PhpSpreadsheet\Writer\Html and \PhpOffice\PhpSpreadsheet\Writer\Pdf.
* *
* @param string $pValue Character for currency code * @param string $currencyCode Character for currency code
*/ */
public static function setCurrencyCode($pValue): void public static function setCurrencyCode($currencyCode): void
{ {
self::$currencyCode = $pValue; self::$currencyCode = $currencyCode;
} }
/** /**
* Convert SYLK encoded string to UTF-8. * Convert SYLK encoded string to UTF-8.
* *
* @param string $pValue * @param string $textValue
* *
* @return string UTF-8 encoded string * @return string UTF-8 encoded string
*/ */
public static function SYLKtoUTF8($pValue) public static function SYLKtoUTF8($textValue)
{ {
self::buildCharacterSets(); self::buildCharacterSets();
// If there is no escape character in the string there is nothing to do // If there is no escape character in the string there is nothing to do
if (strpos($pValue, '') === false) { if (strpos($textValue, '') === false) {
return $pValue; return $textValue;
} }
foreach (self::$SYLKCharacters as $k => $v) { foreach (self::$SYLKCharacters as $k => $v) {
$pValue = str_replace($k, $v, $pValue); $textValue = str_replace($k, $v, $textValue);
} }
return $pValue; return $textValue;
} }
/** /**
* Retrieve any leading numeric part of a string, or return the full string if no leading numeric * Retrieve any leading numeric part of a string, or return the full string if no leading numeric
* (handles basic integer or float, but not exponent or non decimal). * (handles basic integer or float, but not exponent or non decimal).
* *
* @param string $value * @param string $textValue
* *
* @return mixed string or only the leading numeric part of the string * @return mixed string or only the leading numeric part of the string
*/ */
public static function testStringAsNumeric($value) public static function testStringAsNumeric($textValue)
{ {
if (is_numeric($value)) { if (is_numeric($textValue)) {
return $value; return $textValue;
} }
$v = (float) $value; $v = (float) $textValue;
return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value; return (is_numeric(substr($textValue, 0, strlen($v)))) ? $v : $textValue;
} }
} }

View File

@ -17,26 +17,26 @@ class TimeZone
/** /**
* Validate a Timezone name. * Validate a Timezone name.
* *
* @param string $timezone Time zone (e.g. 'Europe/London') * @param string $timezoneName Time zone (e.g. 'Europe/London')
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
private static function validateTimeZone($timezone) private static function validateTimeZone($timezoneName)
{ {
return in_array($timezone, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC)); return in_array($timezoneName, DateTimeZone::listIdentifiers(DateTimeZone::ALL_WITH_BC));
} }
/** /**
* Set the Default Timezone used for date/time conversions. * Set the Default Timezone used for date/time conversions.
* *
* @param string $timezone Time zone (e.g. 'Europe/London') * @param string $timezoneName Time zone (e.g. 'Europe/London')
* *
* @return bool Success or failure * @return bool Success or failure
*/ */
public static function setTimeZone($timezone) public static function setTimeZone($timezoneName)
{ {
if (self::validateTimezone($timezone)) { if (self::validateTimezone($timezoneName)) {
self::$timezone = $timezone; self::$timezone = $timezoneName;
return true; return true;
} }
@ -58,22 +58,22 @@ class TimeZone
* Return the Timezone offset used for date/time conversions to/from UST * Return the Timezone offset used for date/time conversions to/from UST
* This requires both the timezone and the calculated date/time to allow for local DST. * This requires both the timezone and the calculated date/time to allow for local DST.
* *
* @param string $timezone The timezone for finding the adjustment to UST * @param string $timezoneName The timezone for finding the adjustment to UST
* @param int $timestamp PHP date/time value * @param int $timestamp PHP date/time value
* *
* @return int Number of seconds for timezone adjustment * @return int Number of seconds for timezone adjustment
*/ */
public static function getTimeZoneAdjustment($timezone, $timestamp) public static function getTimeZoneAdjustment($timezoneName, $timestamp)
{ {
if ($timezone !== null) { if ($timezoneName !== null) {
if (!self::validateTimezone($timezone)) { if (!self::validateTimezone($timezoneName)) {
throw new PhpSpreadsheetException('Invalid timezone ' . $timezone); throw new PhpSpreadsheetException('Invalid timezone ' . $timezoneName);
} }
} else { } else {
$timezone = self::$timezone; $timezoneName = self::$timezone;
} }
$objTimezone = new DateTimeZone($timezone); $objTimezone = new DateTimeZone($timezoneName);
$transitions = $objTimezone->getTransitions($timestamp, $timestamp); $transitions = $objTimezone->getTransitions($timestamp, $timestamp);
return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; return (count($transitions) > 0) ? $transitions[0]['offset'] : 0;

View File

@ -20,20 +20,20 @@ class XMLWriter extends \XMLWriter
/** /**
* Create a new XMLWriter instance. * Create a new XMLWriter instance.
* *
* @param int $pTemporaryStorage Temporary storage location * @param int $temporaryStorage Temporary storage location
* @param string $pTemporaryStorageFolder Temporary storage folder * @param string $temporaryStorageFolder Temporary storage folder
*/ */
public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = null) public function __construct($temporaryStorage = self::STORAGE_MEMORY, $temporaryStorageFolder = null)
{ {
// Open temporary storage // Open temporary storage
if ($pTemporaryStorage == self::STORAGE_MEMORY) { if ($temporaryStorage == self::STORAGE_MEMORY) {
$this->openMemory(); $this->openMemory();
} else { } else {
// Create temporary filename // Create temporary filename
if ($pTemporaryStorageFolder === null) { if ($temporaryStorageFolder === null) {
$pTemporaryStorageFolder = File::sysGetTempDir(); $temporaryStorageFolder = File::sysGetTempDir();
} }
$this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); $this->tempFileName = @tempnam($temporaryStorageFolder, 'xml');
// Open storage // Open storage
if ($this->openUri($this->tempFileName) === false) { if ($this->openUri($this->tempFileName) === false) {
@ -77,16 +77,16 @@ class XMLWriter extends \XMLWriter
/** /**
* Wrapper method for writeRaw. * Wrapper method for writeRaw.
* *
* @param string|string[] $text * @param string|string[] $rawTextData
* *
* @return bool * @return bool
*/ */
public function writeRawData($text) public function writeRawData($rawTextData)
{ {
if (is_array($text)) { if (is_array($rawTextData)) {
$text = implode("\n", $text); $rawTextData = implode("\n", $rawTextData);
} }
return $this->writeRaw(htmlspecialchars($text)); return $this->writeRaw(htmlspecialchars($rawTextData));
} }
} }

View File

@ -12,17 +12,17 @@ class Xls
* x is the width in intrinsic Excel units (measuring width in number of normal characters) * x is the width in intrinsic Excel units (measuring width in number of normal characters)
* This holds for Arial 10. * This holds for Arial 10.
* *
* @param Worksheet $sheet The sheet * @param Worksheet $worksheet The sheet
* @param string $col The column * @param string $col The column
* *
* @return int The width in pixels * @return int The width in pixels
*/ */
public static function sizeCol($sheet, $col = 'A') public static function sizeCol(Worksheet $worksheet, $col = 'A')
{ {
// default font of the workbook // default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont(); $font = $worksheet->getParent()->getDefaultStyle()->getFont();
$columnDimensions = $sheet->getColumnDimensions(); $columnDimensions = $worksheet->getColumnDimensions();
// first find the true column width in pixels (uncollapsed and unhidden) // first find the true column width in pixels (uncollapsed and unhidden)
if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) { if (isset($columnDimensions[$col]) && $columnDimensions[$col]->getWidth() != -1) {
@ -30,9 +30,9 @@ class Xls
$columnDimension = $columnDimensions[$col]; $columnDimension = $columnDimensions[$col];
$width = $columnDimension->getWidth(); $width = $columnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font); $pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} elseif ($sheet->getDefaultColumnDimension()->getWidth() != -1) { } elseif ($worksheet->getDefaultColumnDimension()->getWidth() != -1) {
// then we have default column dimension with explicit width // then we have default column dimension with explicit width
$defaultColumnDimension = $sheet->getDefaultColumnDimension(); $defaultColumnDimension = $worksheet->getDefaultColumnDimension();
$width = $defaultColumnDimension->getWidth(); $width = $defaultColumnDimension->getWidth();
$pixelWidth = Drawing::cellDimensionToPixels($width, $font); $pixelWidth = Drawing::cellDimensionToPixels($width, $font);
} else { } else {
@ -55,17 +55,17 @@ class Xls
* the relationship is: y = 4/3x. If the height hasn't been set by the user we * the relationship is: y = 4/3x. If the height hasn't been set by the user we
* use the default value. If the row is hidden we use a value of zero. * use the default value. If the row is hidden we use a value of zero.
* *
* @param Worksheet $sheet The sheet * @param Worksheet $worksheet The sheet
* @param int $row The row index (1-based) * @param int $row The row index (1-based)
* *
* @return int The width in pixels * @return int The width in pixels
*/ */
public static function sizeRow($sheet, $row = 1) public static function sizeRow(Worksheet $worksheet, $row = 1)
{ {
// default font of the workbook // default font of the workbook
$font = $sheet->getParent()->getDefaultStyle()->getFont(); $font = $worksheet->getParent()->getDefaultStyle()->getFont();
$rowDimensions = $sheet->getRowDimensions(); $rowDimensions = $worksheet->getRowDimensions();
// first find the true row height in pixels (uncollapsed and unhidden) // first find the true row height in pixels (uncollapsed and unhidden)
if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) { if (isset($rowDimensions[$row]) && $rowDimensions[$row]->getRowHeight() != -1) {
@ -73,9 +73,9 @@ class Xls
$rowDimension = $rowDimensions[$row]; $rowDimension = $rowDimensions[$row];
$rowHeight = $rowDimension->getRowHeight(); $rowHeight = $rowDimension->getRowHeight();
$pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10
} elseif ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { } elseif ($worksheet->getDefaultRowDimension()->getRowHeight() != -1) {
// then we have a default row dimension with explicit height // then we have a default row dimension with explicit height
$defaultRowDimension = $sheet->getDefaultRowDimension(); $defaultRowDimension = $worksheet->getDefaultRowDimension();
$rowHeight = $defaultRowDimension->getRowHeight(); $rowHeight = $defaultRowDimension->getRowHeight();
$pixelRowHeight = Drawing::pointsToPixels($rowHeight); $pixelRowHeight = Drawing::pointsToPixels($rowHeight);
} else { } else {
@ -105,7 +105,7 @@ class Xls
* *
* @return int Horizontal measured in pixels * @return int Horizontal measured in pixels
*/ */
public static function getDistanceX(Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) public static function getDistanceX(Worksheet $worksheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0)
{ {
$distanceX = 0; $distanceX = 0;
@ -113,14 +113,14 @@ class Xls
$startColumnIndex = Coordinate::columnIndexFromString($startColumn); $startColumnIndex = Coordinate::columnIndexFromString($startColumn);
$endColumnIndex = Coordinate::columnIndexFromString($endColumn); $endColumnIndex = Coordinate::columnIndexFromString($endColumn);
for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) {
$distanceX += self::sizeCol($sheet, Coordinate::stringFromColumnIndex($i)); $distanceX += self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($i));
} }
// correct for offsetX in startcell // correct for offsetX in startcell
$distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); $distanceX -= (int) floor(self::sizeCol($worksheet, $startColumn) * $startOffsetX / 1024);
// correct for offsetX in endcell // correct for offsetX in endcell
$distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024)); $distanceX -= (int) floor(self::sizeCol($worksheet, $endColumn) * (1 - $endOffsetX / 1024));
return $distanceX; return $distanceX;
} }
@ -136,20 +136,20 @@ class Xls
* *
* @return int Vertical distance measured in pixels * @return int Vertical distance measured in pixels
*/ */
public static function getDistanceY(Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) public static function getDistanceY(Worksheet $worksheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0)
{ {
$distanceY = 0; $distanceY = 0;
// add the widths of the spanning rows // add the widths of the spanning rows
for ($row = $startRow; $row <= $endRow; ++$row) { for ($row = $startRow; $row <= $endRow; ++$row) {
$distanceY += self::sizeRow($sheet, $row); $distanceY += self::sizeRow($worksheet, $row);
} }
// correct for offsetX in startcell // correct for offsetX in startcell
$distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256); $distanceY -= (int) floor(self::sizeRow($worksheet, $startRow) * $startOffsetY / 256);
// correct for offsetX in endcell // correct for offsetX in endcell
$distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); $distanceY -= (int) floor(self::sizeRow($worksheet, $endRow) * (1 - $endOffsetY / 256));
return $distanceY; return $distanceY;
} }
@ -198,7 +198,7 @@ class Xls
* W is the width of the cell * W is the width of the cell
* H is the height of the cell * H is the height of the cell
* *
* @param Worksheet $sheet * @param Worksheet $worksheet
* @param string $coordinates E.g. 'A1' * @param string $coordinates E.g. 'A1'
* @param int $offsetX Horizontal offset in pixels * @param int $offsetX Horizontal offset in pixels
* @param int $offsetY Vertical offset in pixels * @param int $offsetY Vertical offset in pixels
@ -207,7 +207,7 @@ class Xls
* *
* @return array * @return array
*/ */
public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) public static function oneAnchor2twoAnchor(Worksheet $worksheet, $coordinates, $offsetX, $offsetY, $width, $height)
{ {
[$column, $row] = Coordinate::coordinateFromString($coordinates); [$column, $row] = Coordinate::coordinateFromString($coordinates);
$col_start = Coordinate::columnIndexFromString($column); $col_start = Coordinate::columnIndexFromString($column);
@ -221,10 +221,10 @@ class Xls
$row_end = $row_start; // Row containing bottom right corner of object $row_end = $row_start; // Row containing bottom right corner of object
// Zero the specified offset if greater than the cell dimensions // Zero the specified offset if greater than the cell dimensions
if ($x1 >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start))) { if ($x1 >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start))) {
$x1 = 0; $x1 = 0;
} }
if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { if ($y1 >= self::sizeRow($worksheet, $row_start + 1)) {
$y1 = 0; $y1 = 0;
} }
@ -232,37 +232,37 @@ class Xls
$height = $height + $y1 - 1; $height = $height + $y1 - 1;
// Subtract the underlying cell widths to find the end cell of the image // Subtract the underlying cell widths to find the end cell of the image
while ($width >= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end))) { while ($width >= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end))) {
$width -= self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)); $width -= self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end));
++$col_end; ++$col_end;
} }
// Subtract the underlying cell heights to find the end cell of the image // Subtract the underlying cell heights to find the end cell of the image
while ($height >= self::sizeRow($sheet, $row_end + 1)) { while ($height >= self::sizeRow($worksheet, $row_end + 1)) {
$height -= self::sizeRow($sheet, $row_end + 1); $height -= self::sizeRow($worksheet, $row_end + 1);
++$row_end; ++$row_end;
} }
// Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
// with zero height or width. // with zero height or width.
if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) == 0) { if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) == 0) {
return; return;
} }
if (self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) == 0) { if (self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) == 0) {
return; return;
} }
if (self::sizeRow($sheet, $row_start + 1) == 0) { if (self::sizeRow($worksheet, $row_start + 1) == 0) {
return; return;
} }
if (self::sizeRow($sheet, $row_end + 1) == 0) { if (self::sizeRow($worksheet, $row_end + 1) == 0) {
return; return;
} }
// Convert the pixel values to the percentage value expected by Excel // Convert the pixel values to the percentage value expected by Excel
$x1 = $x1 / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_start)) * 1024; $x1 = $x1 / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_start)) * 1024;
$y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; $y1 = $y1 / self::sizeRow($worksheet, $row_start + 1) * 256;
$x2 = ($width + 1) / self::sizeCol($sheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object $x2 = ($width + 1) / self::sizeCol($worksheet, Coordinate::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object
$y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object $y2 = ($height + 1) / self::sizeRow($worksheet, $row_end + 1) * 256; // Distance to bottom of object
$startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1); $startCoordinates = Coordinate::stringFromColumnIndex($col_start) . ($row_start + 1);
$endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1); $endCoordinates = Coordinate::stringFromColumnIndex($col_end) . ($row_end + 1);