Skip to content

Commit

Permalink
Let Phpstan Run on Samples (#3808)
Browse files Browse the repository at this point in the history
* Let Phpstan Run on Samples

Phpstan currently analyzes all source and test members. We already run phpcs and php-cs-fixer on samples as well. I would expect that samples are often used as templates for code in userland; it behooves us to be at least as careful with those members as for the others which are already being analyzed.  Aside from 1300+ messages `Variable $helper might not be defined.`, which will be suppressed in phpstan.neon.dist, there are really only a few changes needed for sample members, so that part of the code base was already in good shape, and is now even better. No annotations were needed.

* Scrutinizer 2 out of 3

1 false positive, now suppressed; fix other 2.

* Remove Dead Code

* Very Minor Changes

* Add infra
  • Loading branch information
oleibman authored Dec 6, 2023
1 parent 5bcbc7d commit 29c0162
Show file tree
Hide file tree
Showing 48 changed files with 367 additions and 134 deletions.
1 change: 1 addition & 0 deletions .phpcs.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<file>samples</file>
<file>src</file>
<file>tests</file>
<file>infra</file>

<exclude-pattern>samples/Header.php</exclude-pattern>
<exclude-pattern>*/tests/Core/*/*Test\.(inc|css|js)$</exclude-pattern>
Expand Down
2 changes: 1 addition & 1 deletion infra/DocumentGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private static function tableRow(array $lengths, ?array $values = null): string
return rtrim($result, ' ');
}

private static function getPhpSpreadsheetFunctionText($functionCall): string
private static function getPhpSpreadsheetFunctionText(mixed $functionCall): string
{
if (is_string($functionCall)) {
return $functionCall;
Expand Down
35 changes: 22 additions & 13 deletions infra/LocaleGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,32 +38,32 @@ class LocaleGenerator
*/
protected $translationBaseFolder;

protected $phpSpreadsheetFunctions;
protected array $phpSpreadsheetFunctions;

/**
* @var Spreadsheet
*/
protected $translationSpreadsheet;

protected $verbose;
protected bool $verbose;

/**
* @var Worksheet
*/
protected $localeTranslations;

protected $localeLanguageMap = [];
protected array $localeLanguageMap = [];

protected $errorCodeMap = [];
protected array $errorCodeMap = [];

/**
* @var Worksheet
*/
private $functionNameTranslations;

protected $functionNameLanguageMap = [];
protected array $functionNameLanguageMap = [];

protected $functionNameMap = [];
protected array $functionNameMap = [];

public function __construct(
string $translationBaseFolder,
Expand Down Expand Up @@ -98,7 +98,7 @@ public function generateLocales(): void
}
}

protected function buildConfigFileForLocale($column, $locale): void
protected function buildConfigFileForLocale(string $column, string $locale): void
{
$language = $this->localeTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue();
$localeLanguage = $this->localeTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW)->getValue();
Expand All @@ -124,7 +124,8 @@ protected function buildConfigFileForLocale($column, $locale): void
fclose($configFile);
}

protected function writeConfigArgumentSeparator($configFile, $column): void
/** @param resource $configFile resource to write to */
protected function writeConfigArgumentSeparator($configFile, string $column): void
{
$translationCell = $this->localeTranslations->getCell($column . self::ARGUMENT_SEPARATOR_ROW);
$localeValue = $translationCell->getValue();
Expand All @@ -136,7 +137,8 @@ protected function writeConfigArgumentSeparator($configFile, $column): void
}
}

protected function writeConfigCurrencySymbol($configFile, $column): void
/** @param resource $configFile resource to write to */
protected function writeConfigCurrencySymbol($configFile, string $column): void
{
$translationCell = $this->localeTranslations->getCell($column . self::CURRENCY_SYMBOL_ROW);
$localeValue = $translationCell->getValue();
Expand All @@ -151,7 +153,7 @@ protected function writeConfigCurrencySymbol($configFile, $column): void
}
}

protected function buildFunctionsFileForLocale($column, $locale): void
protected function buildFunctionsFileForLocale(string $column, string $locale): void
{
$language = $this->functionNameTranslations->getCell($column . self::ENGLISH_LANGUAGE_NAME_ROW)->getValue();
$localeLanguage = $this->functionNameTranslations->getCell($column . self::LOCALE_LANGUAGE_NAME_ROW)
Expand All @@ -176,6 +178,7 @@ protected function buildFunctionsFileForLocale($column, $locale): void
fclose($functionFile);
}

/** @return resource used by other methods in this class */
protected function openConfigFile(string $locale, string $language, string $localeLanguage)
{
$this->log("Building locale {$locale} ($language) configuration");
Expand All @@ -185,11 +188,15 @@ protected function openConfigFile(string $locale, string $language, string $loca
$this->log("Writing locale configuration to {$configFileName}");

$configFile = fopen($configFileName, 'wb');
if ($configFile === false) {
throw new Exception('Unable to open $configFileName for write');
}
$this->writeFileHeader($configFile, $localeLanguage, $language, 'locale settings');

return $configFile;
}

/** @return resource used by other methods in this class */
protected function openFunctionNameFile(string $locale, string $language, string $localeLanguage)
{
$this->log("Building locale {$locale} ($language) function names");
Expand All @@ -199,6 +206,9 @@ protected function openFunctionNameFile(string $locale, string $language, string
$this->log("Writing local function names to {$functionFileName}");

$functionFile = fopen($functionFileName, 'wb');
if ($functionFile === false) {
throw new Exception('Unable to open $functionFileName for write');
}
$this->writeFileHeader($functionFile, $localeLanguage, $language, 'function name translations');

return $functionFile;
Expand All @@ -218,6 +228,7 @@ protected function getLocaleFolder(string $locale): string
return $localeFolder;
}

/** @param resource $localeFile file being written to */
protected function writeFileHeader($localeFile, string $localeLanguage, string $language, string $title): void
{
fwrite($localeFile, str_repeat('#', 60) . self::EOL);
Expand All @@ -229,6 +240,7 @@ protected function writeFileHeader($localeFile, string $localeLanguage, string $
fwrite($localeFile, str_repeat('#', 60) . self::EOL . self::EOL);
}

/** @param resource $localeFile file being written to */
protected function writeFileSectionHeader($localeFile, string $header): void
{
fwrite($localeFile, self::EOL . '##' . self::EOL);
Expand All @@ -245,9 +257,6 @@ protected function openTranslationWorkbook(): void
protected function getTranslationSheet(string $sheetName): Worksheet
{
$worksheet = $this->translationSpreadsheet->setActiveSheetIndexByName($sheetName);
if ($worksheet === null) {
throw new Exception("{$sheetName} Worksheet not found");
}

return $worksheet;
}
Expand Down
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ parameters:
paths:
- src/
- tests/
- samples/
- infra/
excludePaths:
- src/PhpSpreadsheet/Chart/Renderer/JpGraph.php
- src/PhpSpreadsheet/Chart/Renderer/JpGraphRendererBase.php
Expand All @@ -21,3 +23,4 @@ parameters:
ignoreErrors:
# Accept a bit anything for assert methods
- '~^Parameter \#2 .* of static method PHPUnit\\Framework\\Assert\:\:assert\w+\(\) expects .*, .* given\.$~'
- '~^Variable \$helper might not be defined\.$~'
2 changes: 1 addition & 1 deletion samples/Autofilter/10_Autofilter_selection_2.php
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@
$autoFilter->getColumn('D')
->setFilterType(Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER)
->createRule()
->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, null, Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE)
->setRule(Rule::AUTOFILTER_COLUMN_RULE_EQUAL, '', Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE)
->setRuleType(Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER);

$helper->log('Add filter on the Date (Column D) to display year to date');
Expand Down
8 changes: 4 additions & 4 deletions samples/Basic/02_Types.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,9 @@
$richText->createText('你好 ');

$payable = $richText->createTextRun('你 好 吗?');
$payable->getFont()->setBold(true);
$payable->getFont()->setItalic(true);
$payable->getFont()->setColor(new Color(Color::COLOR_DARKGREEN));
$payable->getFontOrThrow()->setBold(true);
$payable->getFontOrThrow()->setItalic(true);
$payable->getFontOrThrow()->setColor(new Color(Color::COLOR_DARKGREEN));

$richText->createText(', unless specified otherwise on the invoice.');

Expand All @@ -123,7 +123,7 @@
$richText2->createText("black text\n");

$red = $richText2->createTextRun('red text');
$red->getFont()->setColor(new Color(Color::COLOR_RED));
$red->getFontOrThrow()->setColor(new Color(Color::COLOR_RED));

$spreadsheet->getActiveSheet()
->getCell('C14')
Expand Down
3 changes: 3 additions & 0 deletions samples/Basic/19_Namedrange.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@

// Rename named ranges
$helper->log('Rename named ranges');
if ($spreadsheet->getNamedRange('PersonName') === null) {
throw new Exception('named range not found');
}
$spreadsheet->getNamedRange('PersonName')->setName('PersonFN');

// Rename worksheet
Expand Down
7 changes: 5 additions & 2 deletions samples/Basic/25_In_memory_image.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,15 @@

// Generate an image
$helper->log('Generate an image');
$gdImage = @imagecreatetruecolor(120, 20);
$gdImage = imagecreatetruecolor(120, 20);
if (!$gdImage) {
exit('Cannot Initialize new GD image stream');
throw new Exception('Cannot Initialize new GD image stream');
}

$textColor = imagecolorallocate($gdImage, 255, 255, 255);
if ($textColor === false) {
throw new Exception('imagecolorallocate failed');
}
imagestring($gdImage, 1, 5, 5, 'Created with PhpSpreadsheet', $textColor);

// Add a drawing to the worksheet
Expand Down
7 changes: 4 additions & 3 deletions samples/Basic/39_Dropdown.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
->setDescription('Test document for PhpSpreadsheet, generated using PHP classes.')
->setKeywords('Office PhpSpreadsheet php')
->setCategory('Test result file');
function transpose($value)

function transpose(string $value): array
{
return [$value];
}
Expand All @@ -30,12 +31,12 @@ function transpose($value)
$column = 'F';

// Set data for dropdowns
$continents = glob(__DIR__ . '/data/continents/*');
$continents = glob(__DIR__ . '/data/continents/*') ?: [];
foreach ($continents as $key => $filename) {
$continent = pathinfo($filename, PATHINFO_FILENAME);
$helper->log("Loading $continent");
$continent = str_replace(' ', '_', $continent);
$countries = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$countries = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
$countryCount = count($countries);

// Transpose $countries from a row to a column array
Expand Down
1 change: 1 addition & 0 deletions samples/Calculations/Engineering/Convert-Online.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
$quantity = $_POST['quantity'];
$fromUnit = $_POST['fromUnit'];
$toUnit = $_POST['toUnit'];
/** @var float|string */
$result = ConvertUOM::CONVERT($quantity, $fromUnit, $toUnit);

echo "{$quantity} {$units[$_POST['category']][$fromUnit]} is {$result} {$units[$_POST['category']][$toUnit]}", PHP_EOL;
Expand Down
10 changes: 5 additions & 5 deletions samples/Chart/32_Chart_read_write.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
$inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i];
}
} else {
$inputFileNames = glob($inputFileNames);
$inputFileNames = glob($inputFileNames) ?: [];
}
foreach ($inputFileNames as $inputFileName) {
$inputFileNameShort = basename($inputFileName);
Expand All @@ -40,23 +40,23 @@
} else {
natsort($chartNames);
foreach ($chartNames as $i => $chartName) {
$chart = $worksheet->getChartByName($chartName);
$chart = $worksheet->getChartByNameOrThrow($chartName);
if ($chart->getTitle() !== null) {
$caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"';
} else {
$caption = 'Untitled';
}
$helper->log(' ' . $chartName . ' - ' . $caption);
$indentation = str_repeat(' ', strlen($chartName) + 3);
$groupCount = $chart->getPlotArea()->getPlotGroupCount();
$groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount();
if ($groupCount == 1) {
$chartType = $chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType();
$chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType();
$helper->log($indentation . ' ' . $chartType);
$helper->renderChart($chart, __FILE__);
} else {
$chartTypes = [];
for ($i = 0; $i < $groupCount; ++$i) {
$chartTypes[] = $chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
$chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType();
}
$chartTypes = array_unique($chartTypes);
if (count($chartTypes) == 1) {
Expand Down
12 changes: 6 additions & 6 deletions samples/Chart/32_Chart_read_write_HTML.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
$inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i];
}
} else {
$inputFileNames = glob($inputFileNames);
$inputFileNames = glob($inputFileNames) ?: [];
}
foreach ($inputFileNames as $inputFileName) {
$inputFileNameShort = basename($inputFileName);
Expand Down Expand Up @@ -46,22 +46,22 @@
} else {
natsort($chartNames);
foreach ($chartNames as $i => $chartName) {
$chart = $worksheet->getChartByName($chartName);
$chart = $worksheet->getChartByNameOrThrow($chartName);
if ($chart->getTitle() !== null) {
$caption = '"' . implode(' ', $chart->getTitle()->getCaption()) . '"';
$caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"';
} else {
$caption = 'Untitled';
}
$helper->log(' ' . $chartName . ' - ' . $caption);
$helper->log(str_repeat(' ', strlen($chartName) + 3));
$groupCount = $chart->getPlotArea()->getPlotGroupCount();
$groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount();
if ($groupCount == 1) {
$chartType = $chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType();
$chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType();
$helper->log(' ' . $chartType);
} else {
$chartTypes = [];
for ($i = 0; $i < $groupCount; ++$i) {
$chartTypes[] = $chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
$chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType();
}
$chartTypes = array_unique($chartTypes);
if (count($chartTypes) == 1) {
Expand Down
12 changes: 6 additions & 6 deletions samples/Chart/32_Chart_read_write_PDF.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
$inputFileNames[] = __DIR__ . '/../templates/' . $argv[$i];
}
} else {
$inputFileNames = glob($inputFileNames);
$inputFileNames = glob($inputFileNames) ?: [];
}
foreach ($inputFileNames as $inputFileName) {
$inputFileNameShort = basename($inputFileName);
Expand Down Expand Up @@ -48,22 +48,22 @@
} else {
natsort($chartNames);
foreach ($chartNames as $i => $chartName) {
$chart = $worksheet->getChartByName($chartName);
$chart = $worksheet->getChartByNameOrThrow($chartName);
if ($chart->getTitle() !== null) {
$caption = '"' . implode(' ', $chart->getTitle()->getCaption()) . '"';
$caption = '"' . $chart->getTitle()->getCaptionText($spreadsheet) . '"';
} else {
$caption = 'Untitled';
}
$helper->log(' ' . $chartName . ' - ' . $caption);
$helper->log(str_repeat(' ', strlen($chartName) + 3));
$groupCount = $chart->getPlotArea()->getPlotGroupCount();
$groupCount = $chart->getPlotAreaOrThrow()->getPlotGroupCount();
if ($groupCount == 1) {
$chartType = $chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType();
$chartType = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex(0)->getPlotType();
$helper->log(' ' . $chartType);
} else {
$chartTypes = [];
for ($i = 0; $i < $groupCount; ++$i) {
$chartTypes[] = $chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType();
$chartTypes[] = $chart->getPlotAreaOrThrow()->getPlotGroupByIndex($i)->getPlotType();
}
$chartTypes = array_unique($chartTypes);
if (count($chartTypes) == 1) {
Expand Down
Loading

0 comments on commit 29c0162

Please sign in to comment.