Skip to content
2 changes: 1 addition & 1 deletion phpstan.dist.neon
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
parameters:
treatPhpDocTypesAsCertain: false
level: 7
level: 8
paths:
- src
- test
Expand Down
9 changes: 9 additions & 0 deletions src/ArrayHelpers/UniqueMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use ArrayAccess;
use ArrayIterator;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use OutOfBoundsException;
use Traversable;
Expand Down Expand Up @@ -41,6 +42,10 @@ public function offsetExists(mixed $offset): bool

public function offsetGet(mixed $offset): mixed
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Map keys must be strings');
}

if (!array_key_exists($offset, $this->items)) {
throw new OutOfBoundsException('No item with key '.$offset);
}
Expand All @@ -50,6 +55,10 @@ public function offsetGet(mixed $offset): mixed

public function offsetSet(mixed $offset, mixed $value): void
{
if (!is_string($offset)) {
throw new InvalidArgumentException('Map keys must be strings');
}

if (array_key_exists($offset, $this->items)) {
throw new DuplicateMapItemException('Map already contains an item with key '.$offset);
}
Expand Down
12 changes: 12 additions & 0 deletions src/CSV/CSVWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,15 @@ public function write(array $row): void
throw MismatchedSchemaException::forSchema($this->expect_schema, $row_schema);
}

if (!$this->isResourceOpen()) {
throw new LogicException('Cannot write to a closed file');
}
fputcsv($this->resource, $row, eol: $this->options['eol']);
}

/**
* @phpstan-assert-if-true resource $this->resource
*/
protected function isResourceOpen(): bool
{
return $this->resource && (get_resource_type($this->resource) === 'stream');
Expand All @@ -113,6 +119,9 @@ public function close(): void
private function writeHeaders(array $keys): void
{
if ($this->options['quote_headers']) {
if (!$this->isResourceOpen()) {
throw new LogicException('Cannot write to a closed file');
}
fputcsv($this->resource, $keys, eol: $this->options['eol']);
} else {
array_walk(
Expand All @@ -122,6 +131,9 @@ private function writeHeaders(array $keys): void
"Column header `$str` cannot contain comma if headers are not quoted"
)
);
if (!$this->isResourceOpen()) {
throw new LogicException('Cannot write to a closed file');
}
fwrite($this->resource, implode(',', $keys).$this->options['eol']);
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Cookie/ArrayCookieWrapperStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ public function __construct(array $cookies = [])
$this->cookies = $cookies;
}

public function set(string $name, ?string $value = null, array $options = []): void
public function set(string $name, string $value = '', array $options = []): void
{
parent::set($name, $value, $options);
$this->set_cookie_calls[$name][] = ['value' => $value, 'opts' => $options];
}

/** @param array<string, mixed> $options */
protected function set_cookie(string $name, ?string $value, array $options): void
protected function set_cookie(string $name, string $value, array $options): void
{
// No-op
}
Expand Down
4 changes: 2 additions & 2 deletions src/Cookie/CookieWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public function __construct(protected bool $has_ssl_available = true)
/**
* @param array<string, mixed> $options
*/
public function set(string $name, ?string $value = null, array $options = []): void
public function set(string $name, string $value = '', array $options = []): void
{
if ($this->headers_sent($file, $line)) {
throw new HeadersSentException($name, $file, $line);
Expand Down Expand Up @@ -97,7 +97,7 @@ public function delete(string $name): void
}

/** @param array<string, mixed> $options */
protected function set_cookie(string $name, ?string $value, array $options): void
protected function set_cookie(string $name, string $value, array $options): void
{
setcookie($name, $value, $options);
}
Expand Down
9 changes: 6 additions & 3 deletions src/Cookie/HeadersSentException.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
*/
class HeadersSentException extends LogicException
{
public function __construct(string $cookie_name, string $output_file, ?int $output_line)
public function __construct(string $cookie_name, ?string $output_file, ?int $output_line)
{
parent::__construct(
"Cannot assign cookie $cookie_name - headers have been sent by output at $output_file:$output_line"
parent::__construct(sprintf(
"Cannot assign cookie $cookie_name - headers have been sent by output at %s:%s",
$output_file ?? '{unknown file}',
$output_line ?? '{unknown line}'
)
);
}
}
8 changes: 5 additions & 3 deletions src/DateTime/DateString.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<?php

declare(strict_types=1);

/**
* @author Andrew Coulton <andrew@ingenerator.com>
*
Expand All @@ -15,7 +17,7 @@
*/
class DateString
{
public static function format(?DateTimeImmutable $date, string $format, string $empty_value = ''): string
public static function format(?DateTimeImmutable $date, string $format, ?string $empty_value = ''): ?string
{
if (!$date instanceof DateTimeImmutable) {
return $empty_value;
Expand All @@ -35,15 +37,15 @@ public static function isoMS(?DateTimeImmutable $date, ?string $empty_value = ''
/**
* Formats as Y-m-d H:i:s.
*/
public static function ymd(?DateTimeImmutable $date, string $empty_value = ''): string
public static function ymd(?DateTimeImmutable $date, ?string $empty_value = ''): ?string
{
return static::format($date, 'Y-m-d', $empty_value);
}

/**
* Formats as Y-m-d H:i:s.
*/
public static function ymdhis(?DateTimeImmutable $date, string $empty_value = ''): string
public static function ymdhis(?DateTimeImmutable $date, ?string $empty_value = ''): ?string
{
return static::format($date, 'Y-m-d H:i:s', $empty_value);
}
Expand Down
18 changes: 15 additions & 3 deletions src/Encryption/CryptoBox/CryptoBoxKeypair.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ private function __construct(
) {
// Creating the public key now is the easiest way to validate that the incoming keypair string is actually valid
try {
$this->public_key = new CryptoBoxPublicKey(sodium_crypto_box_publickey($this->keypair), $this->keypair_id);
$this->public_key = new CryptoBoxPublicKey(sodium_crypto_box_publickey($this->requireKeypair()), $this->keypair_id);
} catch (SodiumException $e) {
throw new InvalidArgumentException('Invalid keypair: '.$e->getMessage(), $e->getCode(), $e);
}
Expand Down Expand Up @@ -120,7 +120,7 @@ public function decrypt(CryptoBoxString $encrypted): string
}

try {
$result = sodium_crypto_box_seal_open($encrypted->ciphertext, $this->keypair);
$result = sodium_crypto_box_seal_open($encrypted->ciphertext, $this->requireKeypair());
if ($result === false) {
throw new DecryptionFailedException('Failed to decrypt - invalid key or ciphertext?');
}
Expand All @@ -140,6 +140,18 @@ public function decrypt(CryptoBoxString $encrypted): string
public function exportToString(): string
{
// Use constant-time base64 decoding to avoid timing attacks
return $this->keypair_id.'.'.sodium_bin2base64($this->keypair, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING);
return $this->keypair_id.'.'.sodium_bin2base64($this->requireKeypair(), SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING);
}

private function requireKeypair(): string
{
if ($this->keypair === null) {
// This shouldn't be possible if created through our constructors which all take a `string` not a `?string`.
// However the property itself has to be nullable to allow us to null it on __destruct, meaning phpstan
// (and we) cannot *guarantee* that it will never be null when we attempt to use it.
throw new InvalidArgumentException('Unexpected state: keypair is null');
}

return $this->keypair;
}
}
1 change: 1 addition & 0 deletions src/Logging/DeviceIdentifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public static function initAndEnsureCookieSet(bool $ssl_available, bool $is_cli
} else {
static::$instance = new DeviceIdentifier(new CookieWrapper($ssl_available));
}
assert(static::$instance instanceof DeviceIdentifier, 'Should have been assigned by above or by ::forceGlobalTestValue');
static::$instance->init();
}

Expand Down
4 changes: 4 additions & 0 deletions src/Sitemap/SitemapParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use DOMDocument;
use InvalidArgumentException;
use LibXMLError;
use SimpleXMLElement;

use function array_map;
use function implode;
Expand All @@ -29,6 +30,9 @@ public static function parse(string $sitemap): array
$doc = self::validateSitemapXML($sitemap);

$xml = simplexml_import_dom($doc);
if (!$xml instanceof SimpleXMLElement) {
throw new InvalidArgumentException('Failed to parse sitemap XML');
}
$urls = [];
foreach ($xml->url as $x_url) {
$url = (string) $x_url->loc;
Expand Down
5 changes: 5 additions & 0 deletions src/StringEncoding/StringSanitiser.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Ingenerator\PHPUtils\StringEncoding;

use RuntimeException;

class StringSanitiser
{
/**
Expand All @@ -23,6 +25,9 @@ public static function ensurePrintableUtf8(string $input, ?int $max_length = nul
'�',
mb_convert_encoding($input, 'UTF-8', 'UTF-8')
);
if ($cleaned === null) {
throw new RuntimeException('Failed to replace invalid UTF8 in string');
}

if ($max_length !== null) {
return mb_substr($cleaned, 0, $max_length);
Expand Down
2 changes: 1 addition & 1 deletion test/unit/Cookie/CookieWrapperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ class TestableCookieWrapper extends CookieWrapper
/** @param array<string, mixed> $options */
protected function set_cookie(
string $name,
?string $value,
string $value,
array $options,
): void {
$this->setcookie_calls[] = [
Expand Down
2 changes: 1 addition & 1 deletion test/unit/Logging/StackdriverApplicationLoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ public function testItAppendsLogsToExistingContentIfFileSpecified(): void

$entries = $this->assertLoggedJSONLines();
$this->assertSame(['previous' => 'content'], array_shift($entries));
$this->assertSame('Another message appended', array_shift($entries)['message']);
$this->assertSame('Another message appended', array_shift($entries)['message'] ?? null);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion test/unit/Mutex/BasicPDOStub.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@
class BasicPDOStub extends PDO
{
/** @var list<array{sql: string, result: array<mixed>}> */
protected $query_stack = [];
protected array $query_stack = [];

/** @param list<array{sql: string, result: array<mixed>}> $stack */
public static function withQueryStack(array $stack): self
{
$i = new self();
foreach ($stack as $q) {
Assert::assertIsString($q['sql'] ?? null, 'Each query stack entry must have `sql` string');
Assert::assertIsArray($q['result'] ?? null, 'Each query stack entry must have result array');
}
$i->query_stack = $stack;

return $i;
Expand All @@ -36,6 +40,7 @@ public function query(
): PDOStatement|false {
Assert::assertNotEmpty($this->query_stack, 'No expectation defined for query '.$statement);
$next_query = array_shift($this->query_stack);
assert($next_query !== null, 'Should not get empty from array_shift on non-empty array');
Assert::assertSame($next_query['sql'], $statement);

return new BasicPDOStatementStub($next_query['result']);
Expand Down
Loading