Compare commits

...

4 commits

115 changed files with 817 additions and 827 deletions

View file

@ -20,13 +20,13 @@ The way each implementation stores data is NOT guaranteed to be compatible, plea
Requires the `redis` extension.
Valkey is the name of the Linux Foundation's fork of Redis.
### `Index\Data\MariaDB`
### `Index\Data\MariaDb`
Requires the `mysqli` extension.
`mysqlnd` is recommended as the underlying driver, but `libmysql` should work without a hitch.
This driver also works for MySQL as the dependencies would suggest, but you should consider using MariaDB instead of possible.
### `Index\Data\SQLite`
### `Index\Data\Sqlite`
Requires the `sqlite3` extension.
@ -36,7 +36,7 @@ Requires the `sqlite3` extension.
Index versioning will mostly follow the [Semantic Versioning specification v2.0.0](https://semver.org/spec/v2.0.0.html), counting dropped support for a minor PHP version (e.g. 7.1 -> 7.2 or 7.4 -> 8.0) as a reason to increment the major version.
Previous major versions may be supported for a time with backports depending on what projects of mine still target older versions of PHP.
The version is stored in the root of the repository in a file called `VERSION` and can be read out within Index using `Index\Environment::getIndexVersion()`.
The version is stored in the root of the repository in a file called `VERSION` and can be read out within Index using `Index\Index::version()`.
## Contribution

View file

@ -1 +1 @@
0.2408.611934
0.2410.20209

View file

@ -13,8 +13,8 @@
"phpstan/phpstan": "^1.11"
},
"suggest": {
"ext-mysqli": "Support for the Index\\Data\\MariaDB namespace (both mysqlnd and libmysql are supported).",
"ext-sqlite3": "Support for the Index\\Data\\SQLite namespace."
"ext-mysqli": "Support for the Index\\Data\\MariaDb namespace (both mysqlnd and libmysql are supported).",
"ext-sqlite3": "Support for the Index\\Data\\Sqlite namespace."
},
"authors": [
{

View file

@ -1,13 +1,13 @@
<?php
// Bencode.php
// Created: 2022-01-13
// Updated: 2024-08-18
// Updated: 2024-10-02
namespace Index\Bencode;
use InvalidArgumentException;
use RuntimeException;
use Index\IO\{GenericStream,Stream,TempFileStream};
use Index\Io\{GenericStream,Stream,TempFileStream};
/**
* Provides a Bencode serialiser.
@ -59,8 +59,8 @@ final class Bencode {
return $output . 'e';
case 'object':
if($value instanceof IBencodeSerialisable)
return self::encode($value->bencodeSerialise(), $depth - 1);
if($value instanceof BencodeSerializable)
return self::encode($value->bencodeSerialize(), $depth - 1);
$value = get_object_vars($value);
$output = 'd';

View file

@ -1,18 +1,18 @@
<?php
// IBencodeSerialisable.php
// BencodeSerializable.php
// Created: 2022-01-13
// Updated: 2024-07-31
// Updated: 2024-10-02
namespace Index\Bencode;
/**
* Provides an interface for serialising objects for bencoding in a controlled manner.
*/
interface IBencodeSerialisable {
interface BencodeSerializable {
/**
* Gets the data that should represent this object in a Bencode structure.
*
* @return mixed Representative data.
*/
function bencodeSerialise(): mixed;
function bencodeSerialize(): mixed;
}

View file

@ -1,7 +1,7 @@
<?php
// BencodeSerialisableTrait.php
// BencodeSerializableTrait.php
// Created: 2024-09-29
// Updated: 2024-09-30
// Updated: 2024-10-02
namespace Index\Bencode;
@ -13,13 +13,13 @@ use RuntimeException;
/**
* Implements support for the BencodeProperty attribute.
*/
trait BencodeSerialisableTrait {
trait BencodeSerializableTrait {
/**
* Constructs Bencode object based on BencodeProperty attributes.
*
* @return array<string, mixed>
*/
public function bencodeSerialise(): mixed {
public function bencodeSerialize(): mixed {
$objectInfo = new ReflectionObject($this);
$props = [];

View file

@ -1,17 +1,17 @@
<?php
// ArrayCacheBackend.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache\ArrayCache;
use InvalidArgumentException;
use Index\Cache\{ICacheBackend,ICacheProvider,ICacheProviderInfo};
use Index\Cache\{CacheBackend,CacheProvider,CacheProviderInfo};
/**
* Information about the dummy cache backend.
*/
class ArrayCacheBackend implements ICacheBackend {
class ArrayCacheBackend implements CacheBackend {
public function isAvailable(): bool {
return true;
}
@ -22,7 +22,7 @@ class ArrayCacheBackend implements ICacheBackend {
* @param ArrayCacheProviderInfo $providerInfo Dummy provider info.
* @return ArrayCacheProvider Dummy provider instance.
*/
public function createProvider(ICacheProviderInfo $providerInfo): ICacheProvider {
public function createProvider(CacheProviderInfo $providerInfo): CacheProvider {
if(!($providerInfo instanceof ArrayCacheProviderInfo))
throw new InvalidArgumentException('$providerInfo must by of type ArrayCacheProviderInfo');
@ -37,7 +37,7 @@ class ArrayCacheBackend implements ICacheBackend {
* @param string|array<string, string|int> $dsn DSN with provider information.
* @return ArrayCacheProviderInfo Dummy provider info instance.
*/
public function parseDsn(string|array $dsn): ICacheProviderInfo {
public function parseDsn(string|array $dsn): CacheProviderInfo {
return new ArrayCacheProviderInfo;
}
}

View file

@ -1,17 +1,17 @@
<?php
// ArrayCacheProvider.php
// Created: 2024-04-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Cache\ArrayCache;
use InvalidArgumentException;
use Index\Cache\ICacheProvider;
use Index\Cache\CacheProvider;
/**
* Represents a dummy cache provider.
*/
class ArrayCacheProvider implements ICacheProvider {
class ArrayCacheProvider implements CacheProvider {
/** @var array<string, array{ttl: int, value: string}> */
private array $items = [];

View file

@ -1,13 +1,13 @@
<?php
// ArrayCacheProviderInfo.php
// Created: 2024-04-10
// Updated: 2024-04-10
// Updated: 2024-10-02
namespace Index\Cache\ArrayCache;
use Index\Cache\ICacheProviderInfo;
use Index\Cache\CacheProviderInfo;
/**
* Represents dummy provider info.
*/
class ArrayCacheProviderInfo implements ICacheProviderInfo {}
class ArrayCacheProviderInfo implements CacheProviderInfo {}

View file

@ -1,14 +1,14 @@
<?php
// ICacheBackend.php
// CacheBackend.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache;
/**
* Information about a cache provider. Should not have any external dependencies.
*/
interface ICacheBackend {
interface CacheBackend {
/**
* Checks whether the driver is available and a provider can be made.
*
@ -19,18 +19,18 @@ interface ICacheBackend {
/**
* Creates the cache provider described in the argument.
*
* @param ICacheProviderInfo $providerInfo Object that describes the desired provider.
* @throws \InvalidArgumentException An invalid implementation of ICacheProviderInfo was provided.
* @param CacheProviderInfo $providerInfo Object that describes the desired provider.
* @throws \InvalidArgumentException An invalid implementation of CacheProviderInfo was provided.
* @throws \RuntimeException If you ignored the output of isAvailable and tried to create an instance anyway.
* @return ICacheProvider The provider described in the provider info.
* @return CacheProvider The provider described in the provider info.
*/
function createProvider(ICacheProviderInfo $providerInfo): ICacheProvider;
function createProvider(CacheProviderInfo $providerInfo): CacheProvider;
/**
* Constructs a cache info instance from a dsn.
*
* @param string|array<string, string|int> $dsn DSN with provider information.
* @return ICacheProviderInfo Provider info based on the dsn.
* @return CacheProviderInfo Provider info based on the dsn.
*/
function parseDsn(string|array $dsn): ICacheProviderInfo;
function parseDsn(string|array $dsn): CacheProviderInfo;
}

View file

@ -1,16 +1,16 @@
<?php
// ICacheProvider.php
// CacheProvider.php
// Created: 2024-04-10
// Updated: 2024-04-10
// Updated: 2024-10-02
namespace Index\Cache;
use Index\ICloseable;
use Index\Closeable;
/**
* Represents a cache provider.
*/
interface ICacheProvider extends ICloseable {
interface CacheProvider extends Closeable {
/**
* Retrieve an item from the cache.
*

View file

@ -1,7 +1,7 @@
<?php
// ICacheProviderInfo.php
// CacheProviderInfo.php
// Created: 2024-04-10
// Updated: 2024-04-10
// Updated: 2024-10-02
namespace Index\Cache;
@ -10,4 +10,4 @@ namespace Index\Cache;
*
* Any cache backend should have its own implementation of this, there are no baseline requirements.
*/
interface ICacheProviderInfo {}
interface CacheProviderInfo {}

View file

@ -1,7 +1,7 @@
<?php
// CacheTools.php
// Created: 2024-04-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Cache;
@ -16,7 +16,7 @@ use RuntimeException;
* CacheTools only handles the scheme part of the URL,
* the rest of the URL is described in the documentation of the parseDsn implementation of the respective backend.
*
* The scheme can be a PHP classpath to an implementation of ICacheBackend, or any of these aliases:
* The scheme can be a PHP classpath to an implementation of CacheBackend, or any of these aliases:
* - `array`, `null`: maps to `ArrayCache\ArrayCacheBackend` or `Index-Cache-ArrayCache-ArrayCacheBackend`, uses a simple array backed cache that doesn't get saved.
* - `memcached`, `memcache`: maps to `Memcached\MemcachedBackend` or `Index-Cache-Memcached-MemcachedBackend`, provides a backend based on the memcached or memcache extension.
* - `valkey`, `keydb`, `redis`: maps to `Valkey\ValkeyBackend` or `Index-Cache-Valkey-ValkeyBackend`, provides a backend based on the phpredis extension.
@ -43,7 +43,7 @@ final class CacheTools {
}
/** @param array<string, int|string> $uri */
private static function resolveBackend(array $uri): ICacheBackend {
private static function resolveBackend(array $uri): CacheBackend {
static $backends = null;
if(!is_array($backends))
$backends = [];
@ -51,7 +51,7 @@ final class CacheTools {
$scheme = $uri['scheme'];
$backend = $backends[$scheme] ?? null;
if(!($backend instanceof ICacheBackend)) {
if(!($backend instanceof CacheBackend)) {
$backend = null;
if(array_key_exists($scheme, self::CACHE_PROTOS))
@ -59,7 +59,7 @@ final class CacheTools {
else
$name = str_replace('-', '\\', (string)$scheme);
if(class_exists($name) && is_subclass_of($name, ICacheBackend::class)) {
if(class_exists($name) && is_subclass_of($name, CacheBackend::class)) {
$backend = new $name;
$name = get_class($backend);
}
@ -83,9 +83,9 @@ final class CacheTools {
* @param string $dsn URL to create cache provider from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no cache provider can be made using the URL.
* @return ICacheBackend Cache backend instance.
* @return CacheBackend Cache backend instance.
*/
public static function backend(string $dsn): ICacheBackend {
public static function backend(string $dsn): CacheBackend {
return self::resolveBackend(self::parseDsnUri($dsn));
}
@ -97,9 +97,9 @@ final class CacheTools {
* @param string $dsn URL to create cache provider from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no cache provider can be made using the URL.
* @return ICacheProviderInfo Cache provider info.
* @return CacheProviderInfo Cache provider info.
*/
public static function parse(string $dsn): ICacheProviderInfo {
public static function parse(string $dsn): CacheProviderInfo {
$uri = self::parseDsnUri($dsn);
return self::resolveBackend($uri)->parseDsn($uri);
}
@ -112,9 +112,9 @@ final class CacheTools {
* @param string $dsn URL to create cache provider from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no cache provider can be made using the URL.
* @return ICacheProvider A cache provider.
* @return CacheProvider A cache provider.
*/
public static function create(string $dsn): ICacheProvider {
public static function create(string $dsn): CacheProvider {
$uri = self::parseDsnUri($dsn);
$backend = self::resolveBackend($uri);
return $backend->createProvider($backend->parseDsn($uri));

View file

@ -1,19 +1,19 @@
<?php
// MemcachedBackend.php
// Created: 2024-04-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Cache\Memcached;
use InvalidArgumentException;
use RuntimeException;
use Index\Cache\{ICacheBackend,ICacheProvider,ICacheProviderInfo};
use Index\Cache\{CacheBackend,CacheProvider,CacheProviderInfo};
use Index\Net\{EndPoint,UnixEndPoint};
/**
* Information about the memcached backend.
*/
class MemcachedBackend implements ICacheBackend {
class MemcachedBackend implements CacheBackend {
public function isAvailable(): bool {
return extension_loaded('memcached')
|| extension_loaded('memcache');
@ -28,7 +28,7 @@ class MemcachedBackend implements ICacheBackend {
* @param MemcachedProviderInfo $providerInfo Memcached provider info.
* @return MemcachedProvider Memcached provider instance.
*/
public function createProvider(ICacheProviderInfo $providerInfo): ICacheProvider {
public function createProvider(CacheProviderInfo $providerInfo): CacheProvider {
if(!($providerInfo instanceof MemcachedProviderInfo))
throw new InvalidArgumentException('$providerInfo must by of type MemcachedProviderInfo');
@ -74,7 +74,7 @@ class MemcachedBackend implements ICacheBackend {
* @param string|array<string, string|int> $dsn DSN with provider information.
* @return MemcachedProviderInfo Memcached provider info instance.
*/
public function parseDsn(string|array $dsn): ICacheProviderInfo {
public function parseDsn(string|array $dsn): CacheProviderInfo {
if(is_string($dsn)) {
$dsn = parse_url($dsn);
if($dsn === false)

View file

@ -1,16 +1,16 @@
<?php
// MemcachedProvider.php
// Created: 2024-04-10
// Updated: 2024-04-10
// Updated: 2024-10-02
namespace Index\Cache\Memcached;
use Index\Cache\ICacheProvider;
use Index\Cache\CacheProvider;
/**
* Base Memcached provider implementation.
*/
abstract class MemcachedProvider implements ICacheProvider {
abstract class MemcachedProvider implements CacheProvider {
public const MAX_TTL = 30 * 24 * 60 * 60;
public abstract function get(string $key): mixed;

View file

@ -1,18 +1,18 @@
<?php
// MemcachedProviderInfo.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache\Memcached;
use InvalidArgumentException;
use Index\Cache\ICacheProviderInfo;
use Index\Cache\CacheProviderInfo;
use Index\Net\EndPoint;
/**
* Represents Memcached provider info.
*/
class MemcachedProviderInfo implements ICacheProviderInfo {
class MemcachedProviderInfo implements CacheProviderInfo {
/**
* @param array<int, array{EndPoint, int}> $endPoints Memcached end points.
* @param string $prefixKey Prefix to apply to keys.

View file

@ -1,13 +1,13 @@
<?php
// MemcachedProviderLegacy.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache\Memcached;
use InvalidArgumentException;
use Memcache;
use Index\Net\{DnsEndPoint,IPEndPoint,UnixEndPoint};
use Index\Net\{DnsEndPoint,IpEndPoint,UnixEndPoint};
/**
* Legacy Memcached provider implementation.
@ -31,7 +31,7 @@ class MemcachedProviderLegacy extends MemcachedProvider {
} elseif($endPointInfo[0] instanceof DnsEndPoint) {
$host = $endPointInfo[0]->getHost();
$port = $endPointInfo[0]->getPort();
} elseif($endPointInfo[0] instanceof IPEndPoint) {
} elseif($endPointInfo[0] instanceof IpEndPoint) {
$host = $endPointInfo[0]->getAddress()->getCleanAddress();
$port = $endPointInfo[0]->getPort();
} else throw new InvalidArgumentException('One of the servers specified in $providerInfo is not a supported endpoint.');

View file

@ -1,14 +1,14 @@
<?php
// MemcachedProviderModern.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache\Memcached;
use InvalidArgumentException;
use Memcached;
use RuntimeException;
use Index\Net\{DnsEndPoint,IPEndPoint,UnixEndPoint};
use Index\Net\{DnsEndPoint,IpEndPoint,UnixEndPoint};
/**
* Base Memcached provider implementation.
@ -30,7 +30,7 @@ class MemcachedProviderModern extends MemcachedProvider {
} elseif($endPointInfo[0] instanceof DnsEndPoint) {
$host = $endPointInfo[0]->getHost();
$port = $endPointInfo[0]->getPort();
} elseif($endPointInfo[0] instanceof IPEndPoint) {
} elseif($endPointInfo[0] instanceof IpEndPoint) {
$host = $endPointInfo[0]->getAddress()->getCleanAddress();
$port = $endPointInfo[0]->getPort();
} else throw new InvalidArgumentException('One of the servers specified in $providerInfo is not a supported endpoint.');

View file

@ -1,13 +1,13 @@
<?php
// ValkeyBackend.php
// Created: 2024-04-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Cache\Valkey;
use InvalidArgumentException;
use RuntimeException;
use Index\Cache\{ICacheBackend,ICacheProvider,ICacheProviderInfo};
use Index\Cache\{CacheBackend,CacheProvider,CacheProviderInfo};
use Index\Net\{EndPoint,UnixEndPoint};
/**
@ -15,7 +15,7 @@ use Index\Net\{EndPoint,UnixEndPoint};
*
* Also compatible with Redis and KeyDB.
*/
class ValkeyBackend implements ICacheBackend {
class ValkeyBackend implements CacheBackend {
public function isAvailable(): bool {
return extension_loaded('redis');
}
@ -26,7 +26,7 @@ class ValkeyBackend implements ICacheBackend {
* @param ValkeyProviderInfo $providerInfo Valkey provider info.
* @return ValkeyProvider Valkey provider instance.
*/
public function createProvider(ICacheProviderInfo $providerInfo): ICacheProvider {
public function createProvider(CacheProviderInfo $providerInfo): CacheProvider {
if(!($providerInfo instanceof ValkeyProviderInfo))
throw new InvalidArgumentException('$providerInfo must by of type ValkeyProviderInfo');
@ -55,7 +55,7 @@ class ValkeyBackend implements ICacheBackend {
* @param string|array<string, int|string> $dsn DSN with provider information.
* @return ValkeyProviderInfo Valkey provider info instance.
*/
public function parseDsn(string|array $dsn): ICacheProviderInfo {
public function parseDsn(string|array $dsn): CacheProviderInfo {
if(is_string($dsn)) {
$dsn = parse_url($dsn);
if($dsn === false)

View file

@ -1,19 +1,19 @@
<?php
// ValkeyProvider.php
// Created: 2024-04-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Cache\Valkey;
use InvalidArgumentException;
use Redis;
use Index\Cache\ICacheProvider;
use Index\Net\{DnsEndPoint,IPEndPoint,UnixEndPoint};
use Index\Cache\CacheProvider;
use Index\Net\{DnsEndPoint,UnixEndPoint};
/**
* Valkey provider implementation.
*/
class ValkeyProvider implements ICacheProvider {
class ValkeyProvider implements CacheProvider {
private Redis $redis;
private bool $persist;

View file

@ -1,19 +1,19 @@
<?php
// ValkeyProviderInfo.php
// Created: 2024-04-10
// Updated: 2024-04-10
// Updated: 2024-10-02
namespace Index\Cache\Valkey;
use InvalidArgumentException;
use RuntimeException;
use Index\Cache\ICacheProviderInfo;
use Index\Net\{DnsEndPoint,EndPoint,IPEndPoint,UnixEndPoint};
use Index\Cache\CacheProviderInfo;
use Index\Net\{DnsEndPoint,EndPoint,IpEndPoint,UnixEndPoint};
/**
* Represents Valkey provider info.
*/
class ValkeyProviderInfo implements ICacheProviderInfo {
class ValkeyProviderInfo implements CacheProviderInfo {
public function __construct(
private EndPoint $endPoint,
private string $prefix,
@ -43,7 +43,7 @@ class ValkeyProviderInfo implements ICacheProviderInfo {
return $this->endPoint->getPath();
if($this->endPoint instanceof DnsEndPoint)
return $this->endPoint->getHost();
if($this->endPoint instanceof IPEndPoint)
if($this->endPoint instanceof IpEndPoint)
return $this->endPoint->getAddress()->getCleanAddress();
throw new RuntimeException('EndPoint type is not supported.');
@ -55,7 +55,7 @@ class ValkeyProviderInfo implements ICacheProviderInfo {
* @return int
*/
public function getServerPort(): int {
if($this->endPoint instanceof DnsEndPoint || $this->endPoint instanceof IPEndPoint)
if($this->endPoint instanceof DnsEndPoint || $this->endPoint instanceof IpEndPoint)
return $this->endPoint->getPort();
return 0;

View file

@ -1,14 +1,14 @@
<?php
// ICloseable.php
// Closeable.php
// Created: 2021-04-30
// Updated: 2021-05-12
// Updated: 2024-10-02
namespace Index;
/**
* Provides an interface for releasing unmanaged resources.
*
* If ICloseable is implemented __destruct() should also be added to the class and should call close in it:
* If Closeable is implemented __destruct() should also be added to the class and should call close in it:
*
* <code>
* public function close(): void {
@ -22,7 +22,7 @@ namespace Index;
*
* However if close() is only implemented because a parent interface requires it, the __destruct() implementation may be omitted.
*/
interface ICloseable {
interface Closeable {
/**
* Free, release or reset unmanaged resources.
*/

View file

@ -1,7 +1,7 @@
<?php
// Colour.php
// Created: 2023-01-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Colour;
@ -122,7 +122,7 @@ abstract class Colour implements Stringable {
if($colour1->shouldInherit() || $colour2->shouldInherit())
return self::none();
return new ColourRGB(
return new ColourRgb(
(int)round(XNumber::weighted($colour2->getRed(), $colour1->getRed(), $weight)),
(int)round(XNumber::weighted($colour2->getGreen(), $colour1->getGreen(), $weight)),
(int)round(XNumber::weighted($colour2->getBlue(), $colour1->getBlue(), $weight)),
@ -136,7 +136,7 @@ abstract class Colour implements Stringable {
* Creates a Colour object from raw Misuzu format.
*
* If bit 31 is set the global instance of ColourNull will always be returned,
* otherwise an instance of ColourRGB will be created using the fromRawRGB method (top 8 bits ignored).
* otherwise an instance of ColourRgb will be created using the fromRawRgb method (top 8 bits ignored).
*
* @param int $raw Raw RGB colour in Misuzu format.
* @return Colour Colour instance representing the Misuzu colour.
@ -144,7 +144,7 @@ abstract class Colour implements Stringable {
public static function fromMisuzu(int $raw): Colour {
if($raw & self::MSZ_INHERIT)
return self::$none;
return ColourRGB::fromRawRGB($raw);
return ColourRgb::fromRawRgb($raw);
}
/**
@ -194,9 +194,9 @@ abstract class Colour implements Stringable {
}
if($length === 6)
return ColourRGB::fromRawRGB((int)hexdec($value));
return ColourRgb::fromRawRgb((int)hexdec($value));
if($length === 8)
return ColourRGB::fromRawRGBA((int)hexdec($value));
return ColourRgb::fromRawRgba((int)hexdec($value));
}
return self::$none;
@ -231,7 +231,7 @@ abstract class Colour implements Stringable {
];
}
return new ColourRGB(...$value);
return new ColourRgb(...$value);
}
if(str_starts_with($value, 'hsl(') || str_starts_with($value, 'hsla(')) {
@ -297,7 +297,7 @@ abstract class Colour implements Stringable {
$alpha = (float)trim($alpha ?? '1');
}
return new ColourHSL($hue, $saturation, $lightness, $alpha);
return new ColourHsl($hue, $saturation, $lightness, $alpha);
}
return self::$none;

View file

@ -1,14 +1,14 @@
<?php
// ColourHSL.php
// ColourHsl.php
// Created: 2023-01-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Colour;
/**
* Represents a colour using Hue, Saturation and Lightness.
*/
class ColourHSL extends Colour {
class ColourHsl extends Colour {
private int $red;
private int $green;
private int $blue;
@ -121,13 +121,13 @@ class ColourHSL extends Colour {
}
/**
* Converts any other colour to a ColourHSL.
* Converts any other colour to a ColourHsl.
*
* @param Colour $colour Original colour.
* @return ColourHSL Converted colour.
* @return ColourHsl Converted colour.
*/
public static function convert(Colour $colour): ColourHSL {
if($colour instanceof ColourHSL)
public static function convert(Colour $colour): ColourHsl {
if($colour instanceof ColourHsl)
return $colour;
$r = $colour->getRed() / 255.0;
@ -155,7 +155,7 @@ class ColourHSL extends Colour {
}
}
return new ColourHSL(
return new ColourHsl(
round($h, 3),
round($s, 3),
round($l, 3),

View file

@ -1,14 +1,14 @@
<?php
// ColourRGB.php
// ColourRgb.php
// Created: 2023-01-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Colour;
/**
* Represents an RGB colour.
*/
class ColourRGB extends Colour {
class ColourRgb extends Colour {
/**
* @param int $red Red property.
* @param int $green Green property.
@ -56,13 +56,13 @@ class ColourRGB extends Colour {
}
/**
* Create a ColourRGB instance from a raw RGB value.
* Create a ColourRgb instance from a raw RGB value.
*
* @param int $raw A raw RGB colour in 0xRRGGBB format.
* @return ColourRGB An instance of ColourRGB.
* @return ColourRgb An instance of ColourRgb.
*/
public static function fromRawRGB(int $raw): ColourRGB {
return new ColourRGB(
public static function fromRawRgb(int $raw): ColourRgb {
return new ColourRgb(
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
($raw & 0xFF),
@ -71,13 +71,13 @@ class ColourRGB extends Colour {
}
/**
* Create a ColourRGB instance from a raw ARGB value.
* Create a ColourRgb instance from a raw ARGB value.
*
* @param int $raw A raw ARGB colour in 0xAARRGGBB format.
* @return ColourRGB An instance of ColourRGB.
* @return ColourRgb An instance of ColourRgb.
*/
public static function fromRawARGB(int $raw): ColourRGB {
return new ColourRGB(
public static function fromRawArgb(int $raw): ColourRgb {
return new ColourRgb(
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
($raw & 0xFF),
@ -86,13 +86,13 @@ class ColourRGB extends Colour {
}
/**
* Create a ColourRGB instance from a raw RGBA value.
* Create a ColourRgb instance from a raw RGBA value.
*
* @param int $raw A raw RGBA colour in 0xRRGGBBAA format.
* @return ColourRGB An instance of ColourRGB.
* @return ColourRgb An instance of ColourRgb.
*/
public static function fromRawRGBA(int $raw): ColourRGB {
return new ColourRGB(
public static function fromRawRgba(int $raw): ColourRgb {
return new ColourRgb(
(($raw >> 24) & 0xFF),
(($raw >> 16) & 0xFF),
(($raw >> 8) & 0xFF),
@ -101,15 +101,15 @@ class ColourRGB extends Colour {
}
/**
* Converts any other colour to a ColourRGB.
* Converts any other colour to a ColourRgb.
*
* @param Colour $colour Original colour.
* @return ColourRGB Converted colour.
* @return ColourRgb Converted colour.
*/
public static function convert(Colour $colour): ColourRGB {
if($colour instanceof ColourRGB)
public static function convert(Colour $colour): ColourRgb {
if($colour instanceof ColourRgb)
return $colour;
return new ColourRGB(
return new ColourRgb(
$colour->getRed(),
$colour->getGreen(),
$colour->getBlue(),

View file

@ -1,14 +1,14 @@
<?php
// IComparable.php
// Comparable.php
// Created: 2021-04-30
// Updated: 2021-05-12
// Updated: 2024-10-02
namespace Index;
/**
* Provides an interface for comparison between objects. Allows for order/sorting instances.
*/
interface IComparable {
interface Comparable {
/**
* Compares the current instance with another and returns an integer that indicates whether
* the current object comes before or after or the same position and the other object.

View file

@ -1,7 +1,7 @@
<?php
// CSRFP.php
// CsrfToken.php
// Created: 2021-06-11
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index;
@ -10,7 +10,7 @@ use Index\UriBase64;
/**
* Contains a mechanism for validating requests.
*/
class CSRFP {
class CsrfToken {
private const TOLERANCE = 30 * 60;
private const EPOCH = 1575158400;
private const HASH_ALGO = 'sha3-256';
@ -25,7 +25,7 @@ class CSRFP {
* @param string $secretKey Secret key for HMAC hashes.
* @param string $identity Unique identity component for these tokens.
* @param int $tolerance Default amount of time a token should remain valid for.
* @return CSRFP New CSRFP instance.
* @return CsrfToken New CsrfToken instance.
*/
public function __construct(
private string $secretKey,

View file

@ -1,14 +1,14 @@
<?php
// IDbBackend.php
// DbBackend.php
// Created: 2021-04-30
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data;
/**
* Information about a database layer. Should not have any external dependencies.
*/
interface IDbBackend {
interface DbBackend {
/**
* Checks whether the driver is available and a connection can be made.
*
@ -19,17 +19,17 @@ interface IDbBackend {
/**
* Creates a connection with the database described in the argument.
*
* @param IDbConnectionInfo $connectionInfo Object that describes the desired connection.
* @throws \InvalidArgumentException An invalid implementation of IDbConnectionInfo was provided.
* @return IDbConnection A connection described in the connection info.
* @param DbConnectionInfo $connectionInfo Object that describes the desired connection.
* @throws \InvalidArgumentException An invalid implementation of DbConnectionInfo was provided.
* @return DbConnection A connection described in the connection info.
*/
function createConnection(IDbConnectionInfo $connectionInfo): IDbConnection;
function createConnection(DbConnectionInfo $connectionInfo): DbConnection;
/**
* Constructs a connection info instance from a dsn.
*
* @param string|array<string, int|string> $dsn DSN with connection information.
* @return IDbConnectionInfo Connection info based on the dsn.
* @return DbConnectionInfo Connection info based on the dsn.
*/
function parseDsn(string|array $dsn): IDbConnectionInfo;
function parseDsn(string|array $dsn): DbConnectionInfo;
}

View file

@ -1,16 +1,16 @@
<?php
// IDbConnection.php
// DbConnection.php
// Created: 2021-04-30
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data;
use Index\ICloseable;
use Index\Closeable;
/**
* Represents a connection to a database service.
*/
interface IDbConnection extends ICloseable {
interface DbConnection extends Closeable {
/**
* Returns the ID of the last inserted row.
*
@ -31,17 +31,17 @@ interface IDbConnection extends ICloseable {
* The statement should use question mark (?) parameters.
*
* @param string $query SQL query to prepare.
* @return IDbStatement An instance of an implementation of IDbStatement.
* @return DbStatement An instance of an implementation of DbStatement.
*/
function prepare(string $query): IDbStatement;
function prepare(string $query): DbStatement;
/**
* Executes a statement and returns a database result instance.
*
* @param string $query SQL query to execute.
* @return IDbResult An instance of an implementation of IDbResult
* @return DbResult An instance of an implementation of DbResult
*/
function query(string $query): IDbResult;
function query(string $query): DbResult;
/**
* Executes a statement and returns how many rows are affected.

View file

@ -1,7 +1,7 @@
<?php
// IDbConnectionInfo.php
// DbConnectionInfo.php
// Created: 2021-04-30
// Updated: 2022-02-16
// Updated: 2024-10-02
namespace Index\Data;
@ -10,4 +10,4 @@ namespace Index\Data;
*
* Any database backend should have its own implementation of this, there are no baseline requirements.
*/
interface IDbConnectionInfo {}
interface DbConnectionInfo {}

View file

@ -1,17 +1,17 @@
<?php
// IDbResult.php
// DbResult.php
// Created: 2021-05-02
// Updated: 2024-02-06
// Updated: 2024-10-02
namespace Index\Data;
use Index\ICloseable;
use Index\IO\Stream;
use Index\Closeable;
use Index\Io\Stream;
/**
* Represents a database result set.
*/
interface IDbResult extends ICloseable {
interface DbResult extends Closeable {
/**
* Fetches the next result set.
*
@ -110,7 +110,7 @@ interface IDbResult extends ICloseable {
/**
* Creates an iterator for this result.
*
* @param callable(IDbResult): object $construct Result info constructor.
* @param callable(DbResult): object $construct Result info constructor.
* @return DbResultIterator Result iterator.
*/
function getIterator(callable $construct): DbResultIterator;

View file

@ -1,7 +1,7 @@
<?php
// DbResultIterator.php
// Created: 2024-02-06
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Data;
@ -9,7 +9,7 @@ use InvalidArgumentException;
use Iterator;
/**
* Implements an iterator and constructor wrapper for IDbResult.
* Implements an iterator and constructor wrapper for DbResult.
*
* @implements Iterator<int, object>
*/
@ -18,13 +18,13 @@ class DbResultIterator implements Iterator {
private object $current;
/**
* Call this through an IDbResult instance instead!
* Call this through an DbResult instance instead!
*
* @param IDbResult $result Result to operate on.
* @param callable(IDbResult): object $construct Constructor callback.
* @param DbResult $result Result to operate on.
* @param callable(DbResult): object $construct Constructor callback.
*/
public function __construct(
private IDbResult $result,
private DbResult $result,
private $construct
) {
if(!is_callable($construct))

View file

@ -1,12 +1,12 @@
<?php
// DbResultTrait.php
// Created: 2023-11-09
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data;
/**
* Implements common IDbResult methods.
* Implements common DbResult methods.
*/
trait DbResultTrait {
public function getString(int|string $index): string {

View file

@ -1,18 +1,18 @@
<?php
// IDbStatement.php
// DbStatement.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data;
use InvalidArgumentException;
use RuntimeException;
use Index\ICloseable;
use Index\Closeable;
/**
* Represents a prepared database statement.
*/
interface IDbStatement extends ICloseable {
interface DbStatement extends Closeable {
/**
* Returns how many parameters there are.
*
@ -45,9 +45,9 @@ interface IDbStatement extends ICloseable {
/**
* Gets the result after execution.
*
* @return IDbResult Instance of an implementation of IDbResult.
* @return DbResult Instance of an implementation of DbResult.
*/
function getResult(): IDbResult;
function getResult(): DbResult;
/**
* Returns the ID of the last inserted row.

View file

@ -1,7 +1,7 @@
<?php
// DbStatementCache.php
// Created: 2023-07-21
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data;
@ -9,14 +9,14 @@ namespace Index\Data;
* Container to avoid having many prepared instances of the same query.
*/
class DbStatementCache {
/** @var array<string, IDbStatement> */
/** @var array<string, DbStatement> */
private array $stmts = [];
/**
* @param IDbConnection $dbConn Connection to use with this cache.
* @param DbConnection $dbConn Connection to use with this cache.
*/
public function __construct(
private IDbConnection $dbConn
private DbConnection $dbConn
) {}
private static function hash(string $query): string {
@ -24,12 +24,12 @@ class DbStatementCache {
}
/**
* Gets a cached or creates a new IDbStatement instance.
* Gets a cached or creates a new DbStatement instance.
*
* @param string $query SQL query.
* @return IDbStatement Statement representing the query.
* @return DbStatement Statement representing the query.
*/
public function get(string $query): IDbStatement {
public function get(string $query): DbStatement {
$hash = self::hash($query);
if(array_key_exists($hash, $this->stmts)) {

View file

@ -1,7 +1,7 @@
<?php
// DbTools.php
// Created: 2021-05-02
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Data;
@ -17,20 +17,20 @@ use RuntimeException;
* DbTools only handles the scheme part of the URL,
* the rest of the URL is described in the documentation of the parseDsn implementation of the respective backend.
*
* The scheme can be a PHP classpath to an implementation of IDbBackend, or any of these aliases:
* The scheme can be a PHP classpath to an implementation of DbBackend, or any of these aliases:
* - `null`: maps to `NullDb\NullDbBackend` or `Index-Data-NullDb-NullDbBackend`, provides a fallback blackhole database backend.
* - `mariadb`, `mysql`: maps to `MariaDB\MariaDBBackend` or `Index-Data-MariaDB-MariaDBBackend`, provides a backend based on the mysqli extension.
* - `sqlite`, `sqlite3`: maps to `SQLite\SQLiteBackend` or `Index-Data-SQLite-SQLiteBackend`, provides a backend based on the sqlite3 extension.
* - `mariadb`, `mysql`: maps to `MariaDb\MariaDbBackend` or `Index-Data-MariaDb-MariaDbBackend`, provides a backend based on the mysqli extension.
* - `sqlite`, `sqlite3`: maps to `Sqlite\SqliteBackend` or `Index-Data-Sqlite-SqliteBackend`, provides a backend based on the sqlite3 extension.
*
* Short names are currently hardcoded and cannot be expanded.
*/
final class DbTools {
private const DB_PROTOS = [
'null' => NullDb\NullDbBackend::class,
'mariadb' => MariaDB\MariaDBBackend::class,
'mysql' => MariaDB\MariaDBBackend::class,
'sqlite' => SQLite\SQLiteBackend::class,
'sqlite3' => SQLite\SQLiteBackend::class,
'mariadb' => MariaDb\MariaDbBackend::class,
'mysql' => MariaDb\MariaDbBackend::class,
'sqlite' => Sqlite\SqliteBackend::class,
'sqlite3' => Sqlite\SqliteBackend::class,
];
/** @return array<string, string|int> */
@ -42,7 +42,7 @@ final class DbTools {
}
/** @param array<string, string|int> $uri */
private static function resolveBackend(array $uri): IDbBackend {
private static function resolveBackend(array $uri): DbBackend {
static $backends = null;
if(!is_array($backends))
$backends = [];
@ -50,7 +50,7 @@ final class DbTools {
$scheme = $uri['scheme'];
$backend = $backends[$scheme] ?? null;
if(!($backend instanceof IDbBackend)) {
if(!($backend instanceof DbBackend)) {
$backend = null;
if(array_key_exists($scheme, self::DB_PROTOS))
@ -58,7 +58,7 @@ final class DbTools {
else
$name = str_replace('-', '\\', (string)$scheme);
if(class_exists($name) && is_subclass_of($name, IDbBackend::class)) {
if(class_exists($name) && is_subclass_of($name, DbBackend::class)) {
$backend = new $name;
$name = get_class($backend);
}
@ -82,9 +82,9 @@ final class DbTools {
* @param string $dsn URL to create database connection from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no database connection can be made using the URL.
* @return IDbBackend Database backend instance.
* @return DbBackend Database backend instance.
*/
public static function backend(string $dsn): IDbBackend {
public static function backend(string $dsn): DbBackend {
return self::resolveBackend(self::parseDsnUri($dsn));
}
@ -96,9 +96,9 @@ final class DbTools {
* @param string $dsn URL to create database connection from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no database connection can be made using the URL.
* @return IDbConnectionInfo Database connection info.
* @return DbConnectionInfo Database connection info.
*/
public static function parse(string $dsn): IDbConnectionInfo {
public static function parse(string $dsn): DbConnectionInfo {
$uri = self::parseDsnUri($dsn);
return self::resolveBackend($uri)->parseDsn($uri);
}
@ -111,9 +111,9 @@ final class DbTools {
* @param string $dsn URL to create database connection from.
* @throws InvalidArgumentException if $dsn is not a valid URL.
* @throws RuntimeException if no database connection can be made using the URL.
* @return IDbConnection An active database connection.
* @return DbConnection An active database connection.
*/
public static function create(string $dsn): IDbConnection {
public static function create(string $dsn): DbConnection {
$uri = self::parseDsnUri($dsn);
$backend = self::resolveBackend($uri);
return $backend->createConnection($backend->parseDsn($uri));
@ -127,10 +127,10 @@ final class DbTools {
* If the callable returns true, commit will be called.
* If the callable returns false, rollback will be called.
*
* @param IDbTransactions $connection A database connection with transaction support.
* @param DbTransactions $connection A database connection with transaction support.
* @param callable $callable A callable that handles the transaction, may return a bool.
*/
public static function transaction(IDbTransactions $connection, callable $callable): void {
public static function transaction(DbTransactions $connection, callable $callable): void {
$connection->beginTransaction();
$result = $callable($connection) ?? null;
if(is_bool($result)) {

View file

@ -1,14 +1,14 @@
<?php
// IDbTransactions.php
// DbTransactions.php
// Created: 2021-05-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data;
/**
* Indicates supports for transactions in a database connection.
*/
interface IDbTransactions extends IDbConnection {
interface DbTransactions extends DbConnection {
/**
* Sets whether changes should be applied immediately or whether commit should always be called first.
*

View file

@ -1,18 +1,18 @@
<?php
// MariaDBBackend.php
// MariaDbBackend.php
// Created: 2021-04-30
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use InvalidArgumentException;
use Index\Data\{IDbBackend,IDbConnection,IDbConnectionInfo};
use Index\Data\{DbBackend,DbConnection,DbConnectionInfo};
use Index\Net\{EndPoint,UnixEndPoint};
/**
* Information about the MariaDB/MySQL database layer.
*/
class MariaDBBackend implements IDbBackend {
class MariaDbBackend implements DbBackend {
public function isAvailable(): bool {
return extension_loaded('mysqli');
}
@ -41,14 +41,14 @@ class MariaDBBackend implements IDbBackend {
/**
* Creates a connection with a MariaDB or MySQL server.
*
* @param MariaDBConnectionInfo $connectionInfo Object that describes the desired connection.
* @return MariaDBConnection A connection with a MariaDB or MySQL server.
* @param MariaDbConnectionInfo $connectionInfo Object that describes the desired connection.
* @return MariaDbConnection A connection with a MariaDB or MySQL server.
*/
public function createConnection(IDbConnectionInfo $connectionInfo): IDbConnection {
if(!($connectionInfo instanceof MariaDBConnectionInfo))
throw new InvalidArgumentException('$connectionInfo must by of type MariaDBConnectionInfo');
public function createConnection(DbConnectionInfo $connectionInfo): DbConnection {
if(!($connectionInfo instanceof MariaDbConnectionInfo))
throw new InvalidArgumentException('$connectionInfo must by of type MariaDbConnectionInfo');
return new MariaDBConnection($connectionInfo);
return new MariaDbConnection($connectionInfo);
}
/**
@ -78,9 +78,9 @@ class MariaDBBackend implements IDbBackend {
* - `enc_verify=<anything>`: Enabled verification of server certificate. Replaced with `enc_no_verify` as it now defaults to on.
*
* @param string|array<string, int|string> $dsn DSN with connection information.
* @return MariaDBConnectionInfo MariaDB connection info.
* @return MariaDbConnectionInfo MariaDB connection info.
*/
public function parseDsn(string|array $dsn): IDbConnectionInfo {
public function parseDsn(string|array $dsn): DbConnectionInfo {
if(is_string($dsn)) {
$dsn = parse_url($dsn);
if($dsn === false)
@ -141,7 +141,7 @@ class MariaDBBackend implements IDbBackend {
if($endPoint === null)
throw new InvalidArgumentException('No end point could be determined from the provided DSN.');
return new MariaDBConnectionInfo(
return new MariaDbConnectionInfo(
$endPoint, $user, $pass, $dbName,
$charSet, $initCommand, $keyPath, $certPath,
$certAuthPath, $trustedCertsPath, $cipherAlgos,

View file

@ -1,21 +1,21 @@
<?php
// MariaDBCharacterSetInfo.php
// MariaDbCharacterSetInfo.php
// Created: 2021-05-02
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
/**
* Contains information about the character set.
*
* @see https://www.php.net/manual/en/mysqli.get-charset
*/
class MariaDBCharacterSetInfo {
class MariaDbCharacterSetInfo {
/**
* Creates a new character set info instance.
*
* @param object $charSet Anonymous object containing the information.
* @return MariaDBCharacterSetInfo Character set information class.
* @return MariaDbCharacterSetInfo Character set information class.
*/
public function __construct(
private object $charSet

View file

@ -1,21 +1,21 @@
<?php
// MariaDBConnection.php
// MariaDbConnection.php
// Created: 2021-04-30
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli;
use mysqli_sql_exception;
use stdClass;
use InvalidArgumentException;
use RuntimeException;
use Index\Data\{IDbConnection,IDbTransactions};
use Index\Data\{DbConnection,DbTransactions};
/**
* Represents a connection with a MariaDB or MySQL database server.
*/
class MariaDBConnection implements IDbConnection, IDbTransactions {
class MariaDbConnection implements DbConnection, DbTransactions {
/**
* Refresh grant tables.
*
@ -75,12 +75,12 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
private mysqli $connection;
/**
* Creates a new instance of MariaDBConnection.
* Creates a new instance of MariaDbConnection.
*
* @param MariaDBConnectionInfo $connectionInfo Information about the connection.
* @return MariaDBConnection A new instance of MariaDBConnection.
* @param MariaDbConnectionInfo $connectionInfo Information about the connection.
* @return MariaDbConnection A new instance of MariaDbConnection.
*/
public function __construct(MariaDBConnectionInfo $connectionInfo) {
public function __construct(MariaDbConnectionInfo $connectionInfo) {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// I'm not sure if calling "new mysqli" without arguments is equivalent to this
@ -173,10 +173,10 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
/**
* Returns info about the currently character set and collation.
*
* @return MariaDBCharacterSetInfo Information about the character set.
* @return MariaDbCharacterSetInfo Information about the character set.
*/
public function getCharacterSetInfo(): MariaDBCharacterSetInfo {
return new MariaDBCharacterSetInfo($this->connection->get_charset());
public function getCharacterSetInfo(): MariaDbCharacterSetInfo {
return new MariaDbCharacterSetInfo($this->connection->get_charset());
}
/**
@ -209,7 +209,7 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
* @return string Version of the server.
*/
public function getServerVersion(): string {
return MariaDBBackend::intToVersion($this->connection->server_version);
return MariaDbBackend::intToVersion($this->connection->server_version);
}
/**
@ -242,13 +242,13 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
/**
* Gets a list of errors from the last command.
*
* @return MariaDBWarning[] List of last errors.
* @return MariaDbWarning[] List of last errors.
*/
public function getLastErrors(): array {
// imagine if stdlib stuff had type annotations, couldn't be me
/** @var array<int, array{errno: int, sqlstate: string, error: string}> */
$errorList = $this->connection->error_list;
return MariaDBWarning::fromLastErrors($errorList);
return MariaDbWarning::fromLastErrors($errorList);
}
/**
@ -265,10 +265,10 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
*
* The result of SHOW WARNINGS;
*
* @return MariaDBWarning[] List of warnings.
* @return MariaDbWarning[] List of warnings.
*/
public function getWarnings(): array {
return MariaDBWarning::fromGetWarnings($this->connection->get_warnings());
return MariaDbWarning::fromGetWarnings($this->connection->get_warnings());
}
/**
@ -351,9 +351,9 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
}
/**
* @return MariaDBStatement A database statement.
* @return MariaDbStatement A database statement.
*/
public function prepare(string $query): MariaDBStatement {
public function prepare(string $query): MariaDbStatement {
try {
$statement = $this->connection->prepare($query);
} catch(mysqli_sql_exception $ex) {
@ -361,13 +361,13 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
}
if($statement === false)
throw new RuntimeException($this->getLastErrorString(), $this->getLastErrorCode());
return new MariaDBStatement($statement);
return new MariaDbStatement($statement);
}
/**
* @return MariaDBResult A database result.
* @return MariaDbResult A database result.
*/
public function query(string $query): MariaDBResult {
public function query(string $query): MariaDbResult {
try {
$result = $this->connection->query($query, MYSQLI_STORE_RESULT);
} catch(mysqli_sql_exception $ex) {
@ -382,7 +382,7 @@ class MariaDBConnection implements IDbConnection, IDbTransactions {
throw new RuntimeException('Query succeeded but you should have use the execute method for that query.');
// Yes, this always uses Native, for some reason the stupid limitation in libmysql only applies to preparing
return new MariaDBResultNative($result);
return new MariaDbResultNative($result);
}
public function execute(string $query): int|string {

View file

@ -1,20 +1,20 @@
<?php
// MariaDBConnectionInfo.php
// MariaDbConnectionInfo.php
// Created: 2021-04-30
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use InvalidArgumentException;
use Index\Data\IDbConnectionInfo;
use Index\Net\{EndPoint,DnsEndPoint,IPAddress,IPEndPoint,UnixEndPoint};
use Index\Data\DbConnectionInfo;
use Index\Net\{EndPoint,DnsEndPoint,IpEndPoint,UnixEndPoint};
/**
* Describes a MariaDB or MySQL connection.
*/
class MariaDBConnectionInfo implements IDbConnectionInfo {
class MariaDbConnectionInfo implements DbConnectionInfo {
/**
* Creates an instance of MariaDBConnectionInfo.
* Creates an instance of MariaDbConnectionInfo.
*
* @param EndPoint $endPoint End point at which the server can be found.
* @param string $userName User name to use for the connection.
@ -29,7 +29,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
* @param string|null $cipherAlgos List of SSL encryption cipher that are allowed.
* @param bool $verifyCert true if the client should verify the server's SSL certificate, false if not.
* @param bool $useCompression true if compression should be used, false if not.
* @return MariaDBConnectionInfo A connection info instance representing the given information.
* @return MariaDbConnectionInfo A connection info instance representing the given information.
*/
public function __construct(
private EndPoint $endPoint,
@ -46,10 +46,10 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
private bool $verifyCert,
private bool $useCompression
) {
if(!($endPoint instanceof IPEndPoint)
if(!($endPoint instanceof IpEndPoint)
&& !($endPoint instanceof DnsEndPoint)
&& !($endPoint instanceof UnixEndPoint))
throw new InvalidArgumentException('$endPoint must be of type IPEndPoint, DnsEndPoint or UnixEndPoint.');
throw new InvalidArgumentException('$endPoint must be of type IpEndPoint, DnsEndPoint or UnixEndPoint.');
if(empty($charSet))
$charSet = null;
@ -95,7 +95,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
public function getHost(): string {
if($this->endPoint instanceof DnsEndPoint)
return $this->endPoint->getHost();
if($this->endPoint instanceof IPEndPoint)
if($this->endPoint instanceof IpEndPoint)
return $this->endPoint->getAddress()->getCleanAddress();
return '';
}
@ -108,7 +108,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
* @return int Target port number.
*/
public function getPort(): int {
if(($this->endPoint instanceof DnsEndPoint) || ($this->endPoint instanceof IPEndPoint)) {
if(($this->endPoint instanceof DnsEndPoint) || ($this->endPoint instanceof IpEndPoint)) {
$port = $this->endPoint->getPort();
return $port < 1 ? 3306 : $port;
}
@ -283,7 +283,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
* @param string|null $cipherAlgos List of SSL encryption cipher that are allowed.
* @param bool $verifyCert true if the client should verify the server's SSL certificate, false if not.
* @param bool $useCompression true if compression should be used, false if not.
* @return MariaDBConnectionInfo A connection info instance representing the given information.
* @return MariaDbConnectionInfo A connection info instance representing the given information.
*/
public static function createHost(
string $host,
@ -300,8 +300,8 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
string|null $cipherAlgos = null,
bool $verifyCert = false,
bool $useCompression = false
): MariaDBConnectionInfo {
return new MariaDBConnectionInfo(
): MariaDbConnectionInfo {
return new MariaDbConnectionInfo(
new DnsEndPoint($host, $port),
$userName,
$password,
@ -334,7 +334,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
* @param string|null $cipherAlgos List of SSL encryption cipher that are allowed.
* @param bool $verifyCert true if the client should verify the server's SSL certificate, false if not.
* @param bool $useCompression true if compression should be used, false if not.
* @return MariaDBConnectionInfo A connection info instance representing the given information.
* @return MariaDbConnectionInfo A connection info instance representing the given information.
*/
public static function createUnix(
string $path,
@ -350,8 +350,8 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
string|null $cipherAlgos = null,
bool $verifyCert = false,
bool $useCompression = false
): MariaDBConnectionInfo {
return new MariaDBConnectionInfo(
): MariaDbConnectionInfo {
return new MariaDbConnectionInfo(
UnixEndPoint::parse($path),
$userName,
$password,
@ -386,7 +386,7 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
* @param string|null $cipherAlgos List of SSL encryption cipher that are allowed.
* @param bool $verifyCert true if the client should verify the server's SSL certificate, false if not.
* @param bool $useCompression true if compression should be used, false if not.
* @return MariaDBConnectionInfo A connection info instance representing the given information.
* @return MariaDbConnectionInfo A connection info instance representing the given information.
*/
public static function create(
string $endPoint,
@ -402,8 +402,8 @@ class MariaDBConnectionInfo implements IDbConnectionInfo {
string|null $cipherAlgos = null,
bool $verifyCert = false,
bool $useCompression = false
): MariaDBConnectionInfo {
return new MariaDBConnectionInfo(
): MariaDbConnectionInfo {
return new MariaDbConnectionInfo(
EndPoint::parse($endPoint),
$userName,
$password,

View file

@ -1,23 +1,23 @@
<?php
// MariaDBParameter.php
// MariaDbParameter.php
// Created: 2021-05-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use Index\Data\{DbTools,DbType};
/**
* Represents a bound parameter.
*/
class MariaDBParameter {
class MariaDbParameter {
/**
* Create a new MariaDBParameter.
* Create a new MariaDbParameter.
*
* @param int $ordinal Parameter number.
* @param int $type DbType number.
* @param mixed $value Value to bind.
* @return MariaDBParameter A new parameter instance.
* @return MariaDbParameter A new parameter instance.
*/
public function __construct(
private int $ordinal,

View file

@ -1,30 +1,30 @@
<?php
// MariaDBResult.php
// MariaDbResult.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli_result;
use mysqli_stmt;
use InvalidArgumentException;
use Index\Data\{DbResultTrait,IDbResult};
use Index\IO\{Stream,TempFileStream};
use Index\Data\{DbResult,DbResultTrait};
use Index\Io\{Stream,TempFileStream};
/**
* Represents a MariaDB/MySQL database result.
*/
abstract class MariaDBResult implements IDbResult {
abstract class MariaDbResult implements DbResult {
use DbResultTrait;
/** @var array<int|string, mixed> */
protected array $currentRow = [];
/**
* Creates a new MariaDBResult instance.
* Creates a new MariaDbResult instance.
*
* @param mysqli_stmt|mysqli_result $result A result to work with.
* @return MariaDBResult A result instance.
* @return MariaDbResult A result instance.
*/
public function __construct(
protected mysqli_stmt|mysqli_result $result

View file

@ -1,19 +1,19 @@
<?php
// MariaDBResultLib.php
// MariaDbResultLib.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli_stmt;
use RuntimeException;
/**
* Implementation of MariaDBResult for libmysql.
* Implementation of MariaDbResult for libmysql.
*
* @internal
*/
class MariaDBResultLib extends MariaDBResult {
class MariaDbResultLib extends MariaDbResult {
/** @var mixed[] */
private array $fields = [];

View file

@ -1,20 +1,20 @@
<?php
// MariaDBResultNative.php
// MariaDbResultNative.php
// Created: 2021-05-02
// Updated: 2024-08-18
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli_result;
use mysqli_stmt;
use RuntimeException;
/**
* Implementation of MariaDBResult for mysqlnd.
* Implementation of MariaDbResult for mysqlnd.
*
* @internal
*/
class MariaDBResultNative extends MariaDBResult {
class MariaDbResultNative extends MariaDbResult {
public function __construct(mysqli_stmt|mysqli_result $result) {
if($result instanceof mysqli_stmt) {
$_result = $result->get_result();

View file

@ -1,28 +1,28 @@
<?php
// MariaDBStatement.php
// MariaDbStatement.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli_stmt;
use InvalidArgumentException;
use RuntimeException;
use Index\Data\{DbType,IDbStatement};
use Index\IO\Stream;
use Index\Data\{DbType,DbStatement};
use Index\Io\Stream;
/**
* Represents a MariaDB/MySQL prepared statement.
*/
class MariaDBStatement implements IDbStatement {
/** @var array<int, MariaDBParameter> */
class MariaDbStatement implements DbStatement {
/** @var array<int, MariaDbParameter> */
private array $params = [];
/**
* Creates a MariaDBStatement.
* Creates a MariaDbStatement.
*
* @param mysqli_stmt $statement Underlying statement object.
* @return MariaDBStatement A new statement instance.
* @return MariaDbStatement A new statement instance.
*/
public function __construct(
private mysqli_stmt $statement
@ -30,11 +30,11 @@ class MariaDBStatement implements IDbStatement {
private static bool $constructed = false;
/** @var class-string<MariaDBResult> */
/** @var class-string<MariaDbResult> */
private static string $resultImplementation;
/**
* Determines which MariaDBResult implementation should be used.
* Determines which MariaDbResult implementation should be used.
*
* @internal
*/
@ -43,8 +43,8 @@ class MariaDBStatement implements IDbStatement {
throw new RuntimeException('Static constructor was already called.');
self::$constructed = true;
self::$resultImplementation = function_exists('mysqli_stmt_get_result')
? MariaDBResultNative::class
: MariaDBResultLib::class;
? MariaDbResultNative::class
: MariaDbResultLib::class;
}
public function getParameterCount(): int {
@ -55,7 +55,7 @@ class MariaDBStatement implements IDbStatement {
if($ordinal < 1 || $ordinal > $this->getParameterCount())
throw new InvalidArgumentException('$ordinal is not a valid parameter number.');
$this->params[$ordinal - 1] = new MariaDBParameter($ordinal, $type, $value);
$this->params[$ordinal - 1] = new MariaDbParameter($ordinal, $type, $value);
}
public function nextParameter(mixed $value, int $type = DbType::AUTO): void {
@ -63,7 +63,7 @@ class MariaDBStatement implements IDbStatement {
if($nextIndex >= $this->getParameterCount())
throw new RuntimeException('Attempted to specify too many parameters.');
$this->params[$nextIndex] = new MariaDBParameter($nextIndex + 1, $type, $value);
$this->params[$nextIndex] = new MariaDbParameter($nextIndex + 1, $type, $value);
}
/**
@ -96,10 +96,10 @@ class MariaDBStatement implements IDbStatement {
/**
* Gets a list of errors from the last command.
*
* @return MariaDBWarning[] List of last errors.
* @return MariaDbWarning[] List of last errors.
*/
public function getLastErrors(): array {
return MariaDBWarning::fromLastErrors($this->statement->error_list);
return MariaDbWarning::fromLastErrors($this->statement->error_list);
}
/**
@ -107,13 +107,13 @@ class MariaDBStatement implements IDbStatement {
*
* The result of SHOW WARNINGS;
*
* @return MariaDBWarning[] List of warnings.
* @return MariaDbWarning[] List of warnings.
*/
public function getWarnings(): array {
return MariaDBWarning::fromGetWarnings($this->statement->get_warnings());
return MariaDbWarning::fromGetWarnings($this->statement->get_warnings());
}
public function getResult(): MariaDBResult {
public function getResult(): MariaDbResult {
return new self::$resultImplementation($this->statement);
}
@ -173,4 +173,4 @@ class MariaDBStatement implements IDbStatement {
}
}
MariaDBStatement::construct();
MariaDbStatement::construct();

View file

@ -1,9 +1,9 @@
<?php
// MariaDBWarning.php
// MariaDbWarning.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\MariaDB;
namespace Index\Data\MariaDb;
use mysqli_warning;
use Stringable;
@ -12,14 +12,14 @@ use Index\XArray;
/**
* Represents a MariaDB/MySQL warning.
*/
class MariaDBWarning implements Stringable {
class MariaDbWarning implements Stringable {
/**
* Creates a new MariaDBWarning object.
* Creates a new MariaDbWarning object.
*
* @param string $message Warning message string.
* @param string $sqlState SQL State of the warning.
* @param int $code Error code of the warning.
* @return MariaDBWarning A new warning instance.
* @return MariaDbWarning A new warning instance.
*/
public function __construct(
private string $message,
@ -62,24 +62,24 @@ class MariaDBWarning implements Stringable {
* Creates an array of warning objects from the output of $last_errors.
*
* @param array<int, array{errno: int, sqlstate: string, error: string}> $errors Array of warning arrays.
* @return MariaDBWarning[] Array of warnings objects.
* @return MariaDbWarning[] Array of warnings objects.
*/
public static function fromLastErrors(array $errors): array {
return XArray::select($errors, fn($error) => new MariaDBWarning($error['error'], $error['sqlstate'], $error['errno']));
return XArray::select($errors, fn($error) => new MariaDbWarning($error['error'], $error['sqlstate'], $error['errno']));
}
/**
* Creates an array of warning objects from a mysqli_warning instance.
*
* @param mysqli_warning|false $warnings Warning object.
* @return MariaDBWarning[] Array of warning objects.
* @return MariaDbWarning[] Array of warning objects.
*/
public static function fromGetWarnings(mysqli_warning|false $warnings): array {
$array = [];
if($warnings !== false)
do {
$array[] = new MariaDBWarning(
$array[] = new MariaDbWarning(
$warnings->message,
$warnings->sqlstate,
$warnings->errno

View file

@ -0,0 +1,20 @@
<?php
// DbMigration.php
// Created: 2023-01-07
// Updated: 2024-10-02
namespace Index\Data\Migration;
use Index\Data\DbConnection;
/**
* Interface for migration classes to inherit.
*/
interface DbMigration {
/**
* Runs the migration implemented by this class. This process is irreversible!
*
* @param DbConnection $conn Database connection to execute this migration on.
*/
public function migrate(DbConnection $conn): void;
}

View file

@ -1,16 +1,16 @@
<?php
// IDbMigrationInfo.php
// DbMigrationInfo.php
// Created: 2023-01-07
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\Migration;
use Index\Data\IDbConnection;
use Index\Data\DbConnection;
/**
* Information on a migration repository item.
*/
interface IDbMigrationInfo {
interface DbMigrationInfo {
/**
* Returns the name of the migration.
*
@ -28,7 +28,7 @@ interface IDbMigrationInfo {
/**
* Creates an instance of the underlying migration and runs it. This process is irreversible!
*
* @param IDbConnection $conn Database connection to execute this migration on.
* @param DbConnection $conn Database connection to execute this migration on.
*/
public function migrate(IDbConnection $conn): void;
public function migrate(DbConnection $conn): void;
}

View file

@ -1,7 +1,7 @@
<?php
// DbMigrationManager.php
// Created: 2023-01-07
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Data\Migration;
@ -11,8 +11,8 @@ use DateTimeInterface;
use InvalidArgumentException;
use RuntimeException;
use Index\XDateTime;
use Index\Data\{IDbConnection,IDbStatement,DbType};
use Index\Data\SQLite\SQLiteConnection;
use Index\Data\{DbConnection,DbStatement,DbType};
use Index\Data\Sqlite\SqliteConnection;
/**
* Provides a common interface for database migrations.
@ -34,26 +34,26 @@ class DbMigrationManager {
private const TEMPLATE = <<<EOF
<?php
use Index\Data\IDbConnection;
use Index\Data\Migration\IDbMigration;
use Index\Data\DbConnection;
use Index\Data\Migration\DbMigration;
final class %s implements IDbMigration {
public function migrate(IDbConnection \$conn): void {
final class %s implements DbMigration {
public function migrate(DbConnection \$conn): void {
\$conn->execute('CREATE TABLE ...');
}
}
EOF;
private ?IDbStatement $checkStmt = null;
private ?IDbStatement $insertStmt = null;
private ?DbStatement $checkStmt = null;
private ?DbStatement $insertStmt = null;
/**
* @param IDbConnection $conn Connection to apply to migrations to.
* @param DbConnection $conn Connection to apply to migrations to.
* @param string $tableName Name of the migration tracking table.
*/
public function __construct(
private IDbConnection $conn,
private DbConnection $conn,
private string $tableName = self::DEFAULT_TABLE,
) {}
@ -62,7 +62,8 @@ EOF;
*/
public function createTrackingTable(): void {
// HACK: this is not ok but it works for now, there should probably be a generic type bag alias thing
$nameType = $this->conn instanceof SQLiteConnection ? 'TEXT' : 'VARCHAR(255)';
// TODO: ACTUALLY get rid of this
$nameType = $this->conn instanceof SqliteConnection ? 'TEXT' : 'VARCHAR(255)';
$this->conn->execute(sprintf(self::CREATE_TRACK_TABLE, $this->tableName, $nameType));
$this->conn->execute(sprintf(self::CREATE_TRACK_INDEX, $this->tableName));
@ -120,7 +121,7 @@ EOF;
if($this->insertStmt === null)
throw new RuntimeException('Database migration manager has not been initialised.');
$dateTime = XDateTime::toISO8601String($dateTime);
$dateTime = XDateTime::toIso8601String($dateTime);
$this->insertStmt->reset();
$this->insertStmt->addParameter(1, $name, DbType::STRING);
@ -208,10 +209,10 @@ EOF;
/**
* Runs all migrations present in a migration repository. This process is irreversible!
*
* @param IDbMigrationRepo $migrations Migrations repository to fetch migrations from.
* @param DbMigrationRepo $migrations Migrations repository to fetch migrations from.
* @return string[] Names of migrations that have been completed.
*/
public function processMigrations(IDbMigrationRepo $migrations): array {
public function processMigrations(DbMigrationRepo $migrations): array {
$migrations = $migrations->getMigrations();
$completed = [];

View file

@ -1,18 +1,18 @@
<?php
// IDbMigrationRepo.php
// DbMigrationRepo.php
// Created: 2023-01-07
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\Migration;
/**
* Represents a repository of migrations.
*/
interface IDbMigrationRepo {
interface DbMigrationRepo {
/**
* Returns info on migrations contained in this repository.
*
* @return IDbMigrationInfo[] Collection of migration infos.
* @return DbMigrationInfo[] Collection of migration infos.
*/
public function getMigrations(): array;
}

View file

@ -1,13 +1,13 @@
<?php
// FsDbMigrationInfo.php
// Created: 2023-01-07
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\Migration;
use Index\Data\IDbConnection;
use Index\Data\DbConnection;
class FsDbMigrationInfo implements IDbMigrationInfo {
class FsDbMigrationInfo implements DbMigrationInfo {
private string $name;
private string $className;
@ -39,11 +39,11 @@ class FsDbMigrationInfo implements IDbMigrationInfo {
return $this->className;
}
public function migrate(IDbConnection $conn): void {
public function migrate(DbConnection $conn): void {
require_once $this->path;
$migration = new $this->className;
if($migration instanceof IDbMigration)
if($migration instanceof DbMigration)
$migration->migrate($conn);
}
}

View file

@ -1,13 +1,13 @@
<?php
// FsDbMigrationRepo.php
// Created: 2023-01-07
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\Migration;
use RuntimeException;
class FsDbMigrationRepo implements IDbMigrationRepo {
class FsDbMigrationRepo implements DbMigrationRepo {
/**
* @param string $path Filesystem path to the directory containing the migration files.
*/

View file

@ -1,20 +0,0 @@
<?php
// IDbMigration.php
// Created: 2023-01-07
// Updated: 2024-08-01
namespace Index\Data\Migration;
use Index\Data\IDbConnection;
/**
* Interface for migration classes to inherit.
*/
interface IDbMigration {
/**
* Runs the migration implemented by this class. This process is irreversible!
*
* @param IDbConnection $conn Database connection to execute this migration on.
*/
public function migrate(IDbConnection $conn): void;
}

View file

@ -1,16 +1,16 @@
<?php
// NullDbBackend.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\NullDb;
use Index\Data\{IDbBackend,IDbConnection,IDbConnectionInfo};
use Index\Data\{DbBackend,DbConnection,DbConnectionInfo};
/**
* Information about the dummy database layer.
*/
class NullDbBackend implements IDbBackend {
class NullDbBackend implements DbBackend {
public function isAvailable(): bool {
return true;
}
@ -21,7 +21,7 @@ class NullDbBackend implements IDbBackend {
* @param NullDbConnectionInfo $connectionInfo Dummy connection info.
* @return NullDbConnection Dummy connection instance.
*/
public function createConnection(IDbConnectionInfo $connectionInfo): IDbConnection {
public function createConnection(DbConnectionInfo $connectionInfo): DbConnection {
return new NullDbConnection;
}
@ -33,7 +33,7 @@ class NullDbBackend implements IDbBackend {
* @param string|array<string, int|string> $dsn DSN with connection information.
* @return NullDbConnectionInfo Dummy connection info instance.
*/
public function parseDsn(string|array $dsn): IDbConnectionInfo {
public function parseDsn(string|array $dsn): DbConnectionInfo {
return new NullDbConnectionInfo;
}
}

View file

@ -1,16 +1,16 @@
<?php
// NullDbConnection.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\NullDb;
use Index\Data\{IDbConnection,IDbStatement,IDbResult};
use Index\Data\{DbConnection,DbStatement,DbResult};
/**
* Represents a dummy database connection.
*/
class NullDbConnection implements IDbConnection {
class NullDbConnection implements DbConnection {
public function getLastInsertId(): int|string {
return 0;
}
@ -19,11 +19,11 @@ class NullDbConnection implements IDbConnection {
return 0;
}
public function prepare(string $query): IDbStatement {
public function prepare(string $query): DbStatement {
return new NullDbStatement;
}
public function query(string $query): IDbResult {
public function query(string $query): DbResult {
return new NullDbResult;
}

View file

@ -1,13 +1,13 @@
<?php
// NullDbConnectionInfo.php
// Created: 2021-05-02
// Updated: 2022-02-16
// Updated: 2024-10-02
namespace Index\Data\NullDb;
use Index\Data\IDbConnectionInfo;
use Index\Data\DbConnectionInfo;
/**
* Represents dummy connection info.
*/
class NullDbConnectionInfo implements IDbConnectionInfo {}
class NullDbConnectionInfo implements DbConnectionInfo {}

View file

@ -1,17 +1,17 @@
<?php
// NullDbResult.php
// Created: 2021-05-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\NullDb;
use Index\Data\{IDbResult,DbResultIterator};
use Index\IO\Stream;
use Index\Data\{DbResult,DbResultIterator};
use Index\Io\Stream;
/**
* Represents a dummy database result.
*/
class NullDbResult implements IDbResult {
class NullDbResult implements DbResult {
public function next(): bool {
return false;
}

View file

@ -1,16 +1,16 @@
<?php
// NullDbStatement.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\NullDb;
use Index\Data\{DbType,IDbResult,IDbStatement};
use Index\Data\{DbType,DbResult,DbStatement};
/**
* Represents a dummy database statement.
*/
class NullDbStatement implements IDbStatement {
class NullDbStatement implements DbStatement {
public function getParameterCount(): int {
return 0;
}
@ -19,7 +19,7 @@ class NullDbStatement implements IDbStatement {
public function nextParameter(mixed $value, int $type = DbType::AUTO): void {}
public function getResult(): IDbResult {
public function getResult(): DbResult {
return new NullDbResult;
}

View file

@ -1,18 +1,18 @@
<?php
// SQLiteBackend.php
// SqliteBackend.php
// Created: 2021-05-02
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Data\SQLite;
namespace Index\Data\Sqlite;
use SQLite3;
use InvalidArgumentException;
use Index\Data\{IDbBackend,IDbConnection,IDbConnectionInfo};
use Index\Data\{DbBackend,DbConnection,DbConnectionInfo};
/**
* Information about the SQLite 3 database layer.
*/
class SQLiteBackend implements IDbBackend {
class SqliteBackend implements DbBackend {
public function isAvailable(): bool {
return extension_loaded('sqlite3');
}
@ -31,14 +31,14 @@ class SQLiteBackend implements IDbBackend {
/**
* Creates a new SQLite client.
*
* @param SQLiteConnectionInfo $connectionInfo Object that describes the desired connection.
* @return SQLiteConnection A client for an SQLite database.
* @param SqliteConnectionInfo $connectionInfo Object that describes the desired connection.
* @return SqliteConnection A client for an SQLite database.
*/
public function createConnection(IDbConnectionInfo $connectionInfo): IDbConnection {
if(!($connectionInfo instanceof SQLiteConnectionInfo))
throw new InvalidArgumentException('$connectionInfo must by of type SQLiteConnectionInfo');
public function createConnection(DbConnectionInfo $connectionInfo): DbConnection {
if(!($connectionInfo instanceof SqliteConnectionInfo))
throw new InvalidArgumentException('$connectionInfo must by of type SqliteConnectionInfo');
return new SQLiteConnection($connectionInfo);
return new SqliteConnection($connectionInfo);
}
/**
@ -54,9 +54,9 @@ class SQLiteBackend implements IDbBackend {
* - `openOnly` to prevent a new file from being created if the specified path does not exist.
*
* @param string|array<string, int|string> $dsn DSN with connection information.
* @return SQLiteConnectionInfo SQLite connection info.
* @return SqliteConnectionInfo SQLite connection info.
*/
public function parseDsn(string|array $dsn): IDbConnectionInfo {
public function parseDsn(string|array $dsn): DbConnectionInfo {
if(is_string($dsn)) {
$dsn = parse_url($dsn);
if($dsn === false)
@ -78,6 +78,6 @@ class SQLiteBackend implements IDbBackend {
$readOnly = isset($query['readOnly']);
$create = !isset($query['openOnly']);
return new SQLiteConnectionInfo($path, $encKey, $readOnly, $create);
return new SqliteConnectionInfo($path, $encKey, $readOnly, $create);
}
}

View file

@ -1,19 +1,19 @@
<?php
// SQLiteConnection.php
// SqliteConnection.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\SQLite;
namespace Index\Data\Sqlite;
use RuntimeException;
use SQLite3;
use Index\Data\{IDbConnection,IDbTransactions,IDbStatement,IDbResult};
use Index\IO\{GenericStream,Stream};
use Index\Data\{DbConnection,DbTransactions,DbStatement,DbResult};
use Index\Io\{GenericStream,Stream};
/**
* Represents a client for an SQLite database.
*/
class SQLiteConnection implements IDbConnection, IDbTransactions {
class SqliteConnection implements DbConnection, DbTransactions {
/**
* CREATE INDEX authorizer.
*
@ -358,10 +358,10 @@ class SQLiteConnection implements IDbConnection, IDbTransactions {
/**
* Creates a new SQLite client.
*
* @param SQLiteConnectionInfo $connectionInfo Information about the client.
* @return SQLiteConnection A new SQLite client.
* @param SqliteConnectionInfo $connectionInfo Information about the client.
* @return SqliteConnection A new SQLite client.
*/
public function __construct(SQLiteConnectionInfo $connectionInfo) {
public function __construct(SqliteConnectionInfo $connectionInfo) {
$flags = 0;
if($connectionInfo->shouldReadOnly())
$flags |= SQLITE3_OPEN_READONLY;
@ -460,7 +460,7 @@ class SQLiteConnection implements IDbConnection, IDbTransactions {
/**
* Opens a BLOB field as a Stream.
*
* To be used instead of getStream on SQLiteResult.
* To be used instead of getStream on SqliteResult.
*
* @param string $table Name of the source table.
* @param string $column Name of the source column.
@ -480,18 +480,18 @@ class SQLiteConnection implements IDbConnection, IDbTransactions {
return $this->connection->lastInsertRowID();
}
public function prepare(string $query): IDbStatement {
public function prepare(string $query): DbStatement {
$statement = $this->connection->prepare($query);
if($statement === false)
throw new RuntimeException((string)$this->getLastErrorString(), $this->getLastErrorCode());
return new SQLiteStatement($this, $statement);
return new SqliteStatement($this, $statement);
}
public function query(string $query): IDbResult {
public function query(string $query): DbResult {
$result = $this->connection->query($query);
if($result === false)
throw new RuntimeException($this->getLastErrorString(), $this->getLastErrorCode());
return new SQLiteResult($result);
return new SqliteResult($result);
}
public function execute(string $query): int|string {

View file

@ -1,24 +1,24 @@
<?php
// SQLiteConnectionInfo.php
// SqliteConnectionInfo.php
// Created: 2021-05-02
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Data\SQLite;
namespace Index\Data\Sqlite;
use Index\Data\IDbConnectionInfo;
use Index\Data\DbConnectionInfo;
/**
* Represents information about a SQLite Client.
*/
class SQLiteConnectionInfo implements IDbConnectionInfo {
class SqliteConnectionInfo implements DbConnectionInfo {
/**
* Creates a new SQLiteConnectionInfo instance.
* Creates a new SqliteConnectionInfo instance.
*
* @param string $fileName Path to the SQLite database.
* @param string $encryptionKey Key to encrypt the database with.
* @param bool $readOnly Set to true if the database should be opened read-only.
* @param bool $create Set to true to create the database if it does not exist.
* @return SQLiteConnectionInfo Information to create an SQLite database client.
* @return SqliteConnectionInfo Information to create an SQLite database client.
*/
public function __construct(
private string $fileName,
@ -68,15 +68,15 @@ class SQLiteConnectionInfo implements IDbConnectionInfo {
* @param string $encryptionKey Key to encrypt the database with.
* @param bool $readOnly Set to true if the database should be opened read-only.
* @param bool $create Set to true to create the database if it does not exist.
* @return SQLiteConnectionInfo Information to create an SQLite database client.
* @return SqliteConnectionInfo Information to create an SQLite database client.
*/
public static function createPath(
string $path,
string $encryptionKey = '',
bool $readOnly = false,
bool $create = true
): SQLiteConnectionInfo {
return new SQLiteConnectionInfo(
): SqliteConnectionInfo {
return new SqliteConnectionInfo(
$path,
$encryptionKey,
$readOnly,
@ -88,19 +88,19 @@ class SQLiteConnectionInfo implements IDbConnectionInfo {
* Creates a connection info instance for an in-memory database.
*
* @param string $encryptionKey Key to encrypt the database with.
* @return SQLiteConnectionInfo Information to create an SQLite database client.
* @return SqliteConnectionInfo Information to create an SQLite database client.
*/
public static function createMemory(string $encryptionKey = ''): SQLiteConnectionInfo {
return new SQLiteConnectionInfo(':memory:', $encryptionKey, false, true);
public static function createMemory(string $encryptionKey = ''): SqliteConnectionInfo {
return new SqliteConnectionInfo(':memory:', $encryptionKey, false, true);
}
/**
* Creates a connection info instance for a database stored in a temporary file.
*
* @param string $encryptionKey Key to encrypt the database with.
* @return SQLiteConnectionInfo Information to create an SQLite database client.
* @return SqliteConnectionInfo Information to create an SQLite database client.
*/
public static function createTemp(string $encryptionKey = ''): SQLiteConnectionInfo {
return new SQLiteConnectionInfo('', $encryptionKey, false, true);
public static function createTemp(string $encryptionKey = ''): SqliteConnectionInfo {
return new SqliteConnectionInfo('', $encryptionKey, false, true);
}
}

View file

@ -1,29 +1,29 @@
<?php
// SQLiteResult.php
// SqliteResult.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Data\SQLite;
namespace Index\Data\Sqlite;
use SQLite3Result;
use InvalidArgumentException;
use Index\Data\{DbResultTrait,IDbResult};
use Index\IO\{Stream,TempFileStream};
use Index\Data\{DbResult,DbResultTrait};
use Index\Io\{Stream,TempFileStream};
/**
* Represents an SQLite result set.
*/
class SQLiteResult implements IDbResult {
class SqliteResult implements DbResult {
use DbResultTrait;
/** @var array<int|string, mixed> */
private array $currentRow = [];
/**
* Creates a new instance of SQLiteResult.
* Creates a new instance of SqliteResult.
*
* @param SQLite3Result $result Raw underlying result class.
* @return SQLiteResult A new SQLiteResult instance.
* @return SqliteResult A new SqliteResult instance.
*/
public function __construct(
private SQLite3Result $result
@ -56,7 +56,7 @@ class SQLiteResult implements IDbResult {
/**
* Gets the value from the target index as a Stream.
* If you're aware that you're using SQLite it may make more sense to use SQLiteConnection::getBlobStream instead.
* If you're aware that you're using SQLite it may make more sense to use SqliteConnection::getBlobStream instead.
*/
public function getStream(int|string $index): ?Stream {
if($this->isNull($index))

View file

@ -1,33 +1,33 @@
<?php
// SQLiteStatement.php
// SqliteStatement.php
// Created: 2021-05-02
// Updated: 2024-09-13
// Updated: 2024-10-02
namespace Index\Data\SQLite;
namespace Index\Data\Sqlite;
use SQLite3Result;
use SQLite3Stmt;
use InvalidArgumentException;
use RuntimeException;
use Index\Data\{DbTools,DbType,IDbStatement,IDbResult};
use Index\IO\Stream;
use Index\Data\{DbTools,DbType,DbStatement,DbResult};
use Index\Io\Stream;
/**
* Represents a prepared SQLite SQL statement.
*/
class SQLiteStatement implements IDbStatement {
class SqliteStatement implements DbStatement {
private ?SQLite3Result $result = null;
private int $lastOrdinal = 1;
/**
* Creates a new SQLiteStatement instance.
* Creates a new SqliteStatement instance.
*
* @param SQLiteConnection $connection A reference to the connection which creates this statement.
* @param SqliteConnection $connection A reference to the connection which creates this statement.
* @param SQLite3Stmt $statement The raw statement instance.
* @return SQLiteStatement A new statement instance.
* @return SqliteStatement A new statement instance.
*/
public function __construct(
private SQLiteConnection $connection,
private SqliteConnection $connection,
private SQLite3Stmt $statement
) {}
@ -73,10 +73,10 @@ class SQLiteStatement implements IDbStatement {
$this->bindParameter($this->lastOrdinal, $value, $type);
}
public function getResult(): IDbResult {
public function getResult(): DbResult {
if($this->result === null)
throw new RuntimeException('No result is available.');
return new SQLiteResult($this->result);
return new SqliteResult($this->result);
}
public function getLastInsertId(): int|string {

View file

@ -1,14 +1,14 @@
<?php
// IEquatable.php
// Equatable.php
// Created: 2021-04-26
// Updated: 2021-05-12
// Updated: 2024-10-02
namespace Index;
/**
* Provides an interface for determining the value-equality of two objects.
*/
interface IEquatable {
interface Equatable {
/**
* Checks whether the current object is equal to another.
*

View file

@ -1,17 +1,17 @@
<?php
// BencodedContent.php
// Created: 2022-02-10
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Content;
use Index\Bencode\{Bencode,IBencodeSerialisable};
use Index\IO\{Stream,FileStream};
use Index\Bencode\{Bencode,BencodeSerializable};
use Index\Io\{Stream,FileStream};
/**
* Represents Bencoded body content for a HTTP message.
*/
class BencodedContent implements IHttpContent, IBencodeSerialisable {
class BencodedContent implements BencodeSerializable, HttpContent {
/**
* @param mixed $content Content to be bencoded.
*/
@ -28,7 +28,7 @@ class BencodedContent implements IHttpContent, IBencodeSerialisable {
return $this->content;
}
public function bencodeSerialise(): mixed {
public function bencodeSerialize(): mixed {
return $this->content;
}

View file

@ -1,7 +1,7 @@
<?php
// FormContent.php
// Created: 2022-02-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Http\Content;
@ -11,7 +11,7 @@ use Index\Http\HttpUploadedFile;
/**
* Represents form body content for a HTTP message.
*/
class FormContent implements IHttpContent {
class FormContent implements HttpContent {
/**
* @param array<string, mixed> $postFields Form fields.
* @param array<string, HttpUploadedFile|array<string, mixed>> $uploadedFiles Uploaded files.
@ -100,7 +100,7 @@ class FormContent implements IHttpContent {
public static function fromRaw(array $post, array $files): FormContent {
return new FormContent(
$post,
HttpUploadedFile::createFromFILES($files)
HttpUploadedFile::createFromPhpFiles($files)
);
}

View file

@ -1,7 +1,7 @@
<?php
// IHttpContent.php
// HttpContent.php
// Created: 2022-02-08
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Content;
@ -10,4 +10,4 @@ use Stringable;
/**
* Represents the body content for a HTTP message.
*/
interface IHttpContent extends Stringable {}
interface HttpContent extends Stringable {}

View file

@ -1,17 +1,17 @@
<?php
// JsonContent.php
// Created: 2022-02-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Http\Content;
use JsonSerializable;
use Index\IO\{Stream,FileStream};
use Index\Io\{Stream,FileStream};
/**
* Represents JSON body content for a HTTP message.
*/
class JsonContent implements IHttpContent, JsonSerializable {
class JsonContent implements HttpContent, JsonSerializable {
/**
* @param mixed $content Content to be JSON encoded.
*/

View file

@ -1,16 +1,16 @@
<?php
// StreamContent.php
// Created: 2022-02-10
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Content;
use Index\IO\{Stream,FileStream};
use Index\Io\{Stream,FileStream};
/**
* Represents Stream body content for a HTTP message.
*/
class StreamContent implements IHttpContent {
class StreamContent implements HttpContent {
/**
* @param Stream $stream Stream that represents this message body.
*/

View file

@ -1,7 +1,7 @@
<?php
// StringContent.php
// Created: 2022-02-10
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Http\Content;
@ -10,7 +10,7 @@ use Stringable;
/**
* Represents string body content for a HTTP message.
*/
class StringContent implements IHttpContent {
class StringContent implements HttpContent {
/**
* @param string $string String that represents this message body.
*/

View file

@ -1,20 +1,20 @@
<?php
// BencodeContentHandler.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\ContentHandling;
use Index\Bencode\IBencodeSerialisable;
use Index\Bencode\BencodeSerializable;
use Index\Http\HttpResponseBuilder;
use Index\Http\Content\BencodedContent;
/**
* Represents a Bencode content handler for building HTTP response messages.
*/
class BencodeContentHandler implements IContentHandler {
class BencodeContentHandler implements ContentHandler {
public function match(mixed $content): bool {
return $content instanceof IBencodeSerialisable;
return $content instanceof BencodeSerializable;
}
public function handle(HttpResponseBuilder $response, mixed $content): void {

View file

@ -1,7 +1,7 @@
<?php
// IContentHandler.php
// ContentHandler.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\ContentHandling;
@ -10,7 +10,7 @@ use Index\Http\HttpResponseBuilder;
/**
* Represents a content handler for building HTTP response messages.
*/
interface IContentHandler {
interface ContentHandler {
/**
* Determines whether this handler is suitable for the body content.
*

View file

@ -1,7 +1,7 @@
<?php
// JsonContentHandler.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\ContentHandling;
@ -13,7 +13,7 @@ use Index\Http\Content\JsonContent;
/**
* Represents a JSON content handler for building HTTP response messages.
*/
class JsonContentHandler implements IContentHandler {
class JsonContentHandler implements ContentHandler {
public function match(mixed $content): bool {
return is_array($content) || $content instanceof JsonSerializable || $content instanceof stdClass;
}

View file

@ -1,18 +1,18 @@
<?php
// StreamContentHandler.php
// Created: 2024-03-28
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Http\ContentHandling;
use Index\Http\HttpResponseBuilder;
use Index\Http\Content\StreamContent;
use Index\IO\Stream;
use Index\Io\Stream;
/**
* Represents a Stream content handler for building HTTP response messages.
*/
class StreamContentHandler implements IContentHandler {
class StreamContentHandler implements ContentHandler {
public function match(mixed $content): bool {
return $content instanceof Stream;
}

View file

@ -1,7 +1,7 @@
<?php
// IErrorHandler.php
// ErrorHandler.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\ErrorHandling;
@ -10,7 +10,7 @@ use Index\Http\{HttpResponseBuilder,HttpRequest};
/**
* Represents an error message handler for building HTTP response messages.
*/
interface IErrorHandler {
interface ErrorHandler {
/**
* Applies an error message template to the provided HTTP response builder.
*

View file

@ -1,7 +1,7 @@
<?php
// HtmlErrorHandler.php
// Created: 2024-03-28
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Http\ErrorHandling;
@ -10,7 +10,7 @@ use Index\Http\{HttpResponseBuilder,HttpRequest};
/**
* Represents a basic HTML error message handler for building HTTP response messages.
*/
class HtmlErrorHandler implements IErrorHandler {
class HtmlErrorHandler implements ErrorHandler {
private const TEMPLATE = <<<HTML
<!doctype html>
<html>
@ -27,7 +27,7 @@ class HtmlErrorHandler implements IErrorHandler {
HTML;
public function handle(HttpResponseBuilder $response, HttpRequest $request, int $code, string $message): void {
$response->setTypeHTML();
$response->setTypeHtml();
$charSet = mb_preferred_mime_name(mb_internal_encoding());
if($charSet === false)

View file

@ -1,7 +1,7 @@
<?php
// PlainErrorHandler.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\ErrorHandling;
@ -10,7 +10,7 @@ use Index\Http\{HttpResponseBuilder,HttpRequest};
/**
* Represents a plain text error message handler for building HTTP response messages.
*/
class PlainErrorHandler implements IErrorHandler {
class PlainErrorHandler implements ErrorHandler {
public function handle(HttpResponseBuilder $response, HttpRequest $request, int $code, string $message): void {
$response->setTypePlain();
$response->setContent(sprintf('HTTP %03d %s', $code, $message));

View file

@ -1,13 +1,13 @@
<?php
// HttpMessage.php
// Created: 2022-02-08
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http;
use RuntimeException;
use Index\IO\Stream;
use Index\Http\Content\{IHttpContent,BencodedContent,FormContent,JsonContent,StreamContent,StringContent};
use Index\Io\Stream;
use Index\Http\Content\{BencodedContent,FormContent,HttpContent,JsonContent,StreamContent,StringContent};
/**
* Represents a base HTTP message.
@ -16,12 +16,12 @@ abstract class HttpMessage {
/**
* @param string $version HTTP message version.
* @param HttpHeaders $headers HTTP message headers.
* @param ?IHttpContent $content Body contents.
* @param ?HttpContent $content Body contents.
*/
public function __construct(
private string $version,
private HttpHeaders $headers,
private ?IHttpContent $content
private ?HttpContent $content
) {}
/**
@ -105,9 +105,9 @@ abstract class HttpMessage {
/**
* Retrieves message body contents, if present.
*
* @return ?IHttpContent Body contents, null if none present.
* @return ?HttpContent Body contents, null if none present.
*/
public function getContent(): ?IHttpContent {
public function getContent(): ?HttpContent {
return $this->content;
}

View file

@ -1,12 +1,12 @@
<?php
// HttpMessageBuilder.php
// Created: 2022-02-08
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\Http;
use Index\IO\Stream;
use Index\Http\Content\{IHttpContent,StreamContent,StringContent};
use Index\Io\Stream;
use Index\Http\Content\{HttpContent,StreamContent,StringContent};
/**
* Represents a base HTTP message builder.
@ -14,7 +14,7 @@ use Index\Http\Content\{IHttpContent,StreamContent,StringContent};
class HttpMessageBuilder {
private ?string $version = null;
private HttpHeadersBuilder $headers;
private ?IHttpContent $content = null;
private ?HttpContent $content = null;
public function __construct() {
$this->headers = new HttpHeadersBuilder;
@ -100,9 +100,9 @@ class HttpMessageBuilder {
/**
* Retrieves HTTP message body content.
*
* @return ?IHttpContent Body content.
* @return ?HttpContent Body content.
*/
protected function getContent(): ?IHttpContent {
protected function getContent(): ?HttpContent {
return $this->content;
}
@ -119,9 +119,9 @@ class HttpMessageBuilder {
/**
* Sets HTTP message body contents.
*
* @param IHttpContent|Stream|string|null $content Body contents
* @param HttpContent|Stream|string|null $content Body contents
*/
public function setContent(IHttpContent|Stream|string|null $content): void {
public function setContent(HttpContent|Stream|string|null $content): void {
if($content instanceof Stream)
$content = new StreamContent($content);
elseif(is_string($content))

View file

@ -1,14 +1,14 @@
<?php
// HttpRequest.php
// Created: 2022-02-08
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Http;
use InvalidArgumentException;
use RuntimeException;
use Index\MediaType;
use Index\Http\Content\{IHttpContent,JsonContent,StreamContent,FormContent};
use Index\Http\Content\{HttpContent,JsonContent,StreamContent,FormContent};
/**
* Represents a HTTP request message.
@ -21,7 +21,7 @@ class HttpRequest extends HttpMessage {
* @param array<string, mixed> $params HTTP request query parameters.
* @param array<string, string> $cookies HTTP request cookies.
* @param HttpHeaders $headers HTTP message headers.
* @param ?IHttpContent $content Body contents.
* @param ?HttpContent $content Body contents.
*/
public function __construct(
string $version,
@ -30,7 +30,7 @@ class HttpRequest extends HttpMessage {
private array $params,
private array $cookies,
HttpHeaders $headers,
?IHttpContent $content
?HttpContent $content
) {
parent::__construct($version, $headers, $content);
}

View file

@ -1,11 +1,11 @@
<?php
// HttpResponse.php
// Created: 2022-02-08
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http;
use Index\Http\Content\IHttpContent;
use Index\Http\Content\HttpContent;
/**
* Represents a HTTP response message.
@ -16,14 +16,14 @@ class HttpResponse extends HttpMessage {
* @param int $statusCode HTTP response status code.
* @param string $statusText HTTP response status text.
* @param HttpHeaders $headers HTTP message headers.
* @param ?IHttpContent $content Body contents.
* @param ?HttpContent $content Body contents.
*/
public function __construct(
string $version,
private int $statusCode,
private string $statusText,
HttpHeaders $headers,
?IHttpContent $content
?HttpContent $content
) {
parent::__construct($version, $headers, $content);
}

View file

@ -1,7 +1,7 @@
<?php
// HttpResponseBuilder.php
// Created: 2022-02-08
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Http;
@ -248,7 +248,7 @@ class HttpResponseBuilder extends HttpMessageBuilder {
*
* @param string $charset Character set.
*/
public function setTypeHTML(string $charset = 'utf-8'): void {
public function setTypeHtml(string $charset = 'utf-8'): void {
$this->setContentType('text/html; charset=' . $charset);
}
@ -266,7 +266,7 @@ class HttpResponseBuilder extends HttpMessageBuilder {
*
* @param string $charset Character set.
*/
public function setTypeXML(string $charset = 'utf-8'): void {
public function setTypeXml(string $charset = 'utf-8'): void {
$this->setContentType('application/xml; charset=' . $charset);
}
@ -275,7 +275,7 @@ class HttpResponseBuilder extends HttpMessageBuilder {
*
* @param string $charset Character set.
*/
public function setTypeCSS(string $charset = 'utf-8'): void {
public function setTypeCss(string $charset = 'utf-8'): void {
$this->setContentType('text/css; charset=' . $charset);
}
@ -284,7 +284,7 @@ class HttpResponseBuilder extends HttpMessageBuilder {
*
* @param string $charset Character set.
*/
public function setTypeJS(string $charset = 'utf-8'): void {
public function setTypeJs(string $charset = 'utf-8'): void {
$this->setContentType('application/javascript; charset=' . $charset);
}

View file

@ -1,19 +1,19 @@
<?php
// HttpUploadedFile.php
// Created: 2022-02-10
// Updated: 2024-08-04
// Updated: 2024-10-02
namespace Index\Http;
use InvalidArgumentException;
use RuntimeException;
use Index\{MediaType,ICloseable};
use Index\IO\{Stream,FileStream};
use Index\{MediaType,Closeable};
use Index\Io\{Stream,FileStream};
/**
* Represents an uploaded file in a multipart/form-data request.
*/
class HttpUploadedFile implements ICloseable {
class HttpUploadedFile implements Closeable {
private bool $hasMoved = false;
private ?Stream $stream = null;
@ -166,7 +166,7 @@ class HttpUploadedFile implements ICloseable {
* @param array<string, int|string> $file File info array.
* @return HttpUploadedFile Uploaded file info.
*/
public static function createFromFILE(array $file): self {
public static function createFromPhpFilesEntry(array $file): self {
return new HttpUploadedFile(
(int)($file['error'] ?? UPLOAD_ERR_NO_FILE),
(int)($file['size'] ?? -1),
@ -182,18 +182,18 @@ class HttpUploadedFile implements ICloseable {
* @param array<string, mixed> $files Value of a $_FILES superglobal.
* @return array<string, HttpUploadedFile|array<string, mixed>> Uploaded files.
*/
public static function createFromFILES(array $files): array {
public static function createFromPhpFiles(array $files): array {
if(empty($files))
return [];
return self::createObjectInstances(self::normalizeFILES($files));
return self::createObjectInstances(self::normalizePhpFiles($files));
}
/**
* @param array<string, mixed> $files
* @return array<string, mixed>
*/
private static function traverseFILES(array $files, string $keyName): array {
private static function traversePhpFiles(array $files, string $keyName): array {
$arr = [];
foreach($files as $key => $val) {
@ -201,7 +201,7 @@ class HttpUploadedFile implements ICloseable {
if(is_array($val)) {
/** @var array<string, mixed> $val */
$arr[$key] = self::traverseFILES($val, $keyName);
$arr[$key] = self::traversePhpFiles($val, $keyName);
} else {
$arr[$key][$keyName] = $val;
}
@ -214,7 +214,7 @@ class HttpUploadedFile implements ICloseable {
* @param array<string, mixed> $files
* @return array<string, mixed>
*/
private static function normalizeFILES(array $files): array {
private static function normalizePhpFiles(array $files): array {
$out = [];
foreach($files as $key => $arr) {
@ -240,7 +240,7 @@ class HttpUploadedFile implements ICloseable {
$mergeWith = $out[$key] ?? [];
/** @var array<string, mixed> $source */
$out[$key] = array_merge_recursive($mergeWith, self::traverseFILES($source, (string)$keyName));
$out[$key] = array_merge_recursive($mergeWith, self::traversePhpFiles($source, (string)$keyName));
}
continue;
}
@ -264,7 +264,7 @@ class HttpUploadedFile implements ICloseable {
if(isset($val['error']))
/** @var array<string, int|string> $val */
$coll[$key] = self::createFromFILE($val);
$coll[$key] = self::createFromPhpFilesEntry($val);
else
/** @var array<string, mixed> $val */
$coll[$key] = self::createObjectInstances($val);

View file

@ -1,7 +1,7 @@
<?php
// HandlerAttribute.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Routing;
@ -29,12 +29,12 @@ abstract class HandlerAttribute {
}
/**
* Reads attributes from methods in a IRouteHandler instance and registers them to a given IRouter instance.
* Reads attributes from methods in a RouteHandler instance and registers them to a given Router instance.
*
* @param IRouter $router Router instance.
* @param IRouteHandler $handler Handler instance.
* @param Router $router Router instance.
* @param RouteHandler $handler Handler instance.
*/
public static function register(IRouter $router, IRouteHandler $handler): void {
public static function register(Router $router, RouteHandler $handler): void {
$objectInfo = new ReflectionObject($handler);
$methodInfos = $objectInfo->getMethods();

View file

@ -1,7 +1,7 @@
<?php
// HttpRouter.php
// Created: 2024-03-28
// Updated: 2024-08-18
// Updated: 2024-10-02
namespace Index\Http\Routing;
@ -9,10 +9,10 @@ use stdClass;
use InvalidArgumentException;
use Index\Http\{HttpResponse,HttpResponseBuilder,HttpRequest};
use Index\Http\Content\StringContent;
use Index\Http\ContentHandling\{BencodeContentHandler,IContentHandler,JsonContentHandler,StreamContentHandler};
use Index\Http\ErrorHandling\{HtmlErrorHandler,IErrorHandler,PlainErrorHandler};
use Index\Http\ContentHandling\{BencodeContentHandler,ContentHandler,JsonContentHandler,StreamContentHandler};
use Index\Http\ErrorHandling\{HtmlErrorHandler,ErrorHandler,PlainErrorHandler};
class HttpRouter implements IRouter {
class HttpRouter implements Router {
use RouterTrait;
/** @var array{handler: callable, match?: string, prefix?: string}[] */
@ -24,19 +24,19 @@ class HttpRouter implements IRouter {
/** @var array<string, array<string, callable>> */
private array $dynamicRoutes = [];
/** @var IContentHandler[] */
/** @var ContentHandler[] */
private array $contentHandlers = [];
private IErrorHandler $errorHandler;
private ErrorHandler $errorHandler;
/**
* @param string $charSet Default character set to specify when none is present.
* @param IErrorHandler|string $errorHandler Error handling to use for error responses with an empty body. 'html' for the default HTML implementation, 'plain' for the plaintext implementation.
* @param ErrorHandler|string $errorHandler Error handling to use for error responses with an empty body. 'html' for the default HTML implementation, 'plain' for the plaintext implementation.
* @param bool $registerDefaultContentHandlers true to register default content handlers for JSON, Bencode, etc.
*/
public function __construct(
private string $charSet = '',
IErrorHandler|string $errorHandler = 'html',
ErrorHandler|string $errorHandler = 'html',
bool $registerDefaultContentHandlers = true,
) {
$this->setErrorHandler($errorHandler);
@ -65,19 +65,19 @@ class HttpRouter implements IRouter {
/**
* Retrieves the error handler instance.
*
* @return IErrorHandler The error handler.
* @return ErrorHandler The error handler.
*/
public function getErrorHandler(): IErrorHandler {
public function getErrorHandler(): ErrorHandler {
return $this->errorHandler;
}
/**
* Changes the active error handler.
*
* @param IErrorHandler|string $handler Error handling to use for error responses with an empty body. 'html' for the default HTML implementation, 'plain' for the plaintext implementation.
* @param ErrorHandler|string $handler Error handling to use for error responses with an empty body. 'html' for the default HTML implementation, 'plain' for the plaintext implementation.
*/
public function setErrorHandler(IErrorHandler|string $handler): void {
if($handler instanceof IErrorHandler)
public function setErrorHandler(ErrorHandler|string $handler): void {
if($handler instanceof ErrorHandler)
$this->errorHandler = $handler;
elseif($handler === 'html')
$this->setHTMLErrorHandler();
@ -102,9 +102,9 @@ class HttpRouter implements IRouter {
/**
* Register a message body content handler.
*
* @param IContentHandler $contentHandler Content handler to register.
* @param ContentHandler $contentHandler Content handler to register.
*/
public function registerContentHandler(IContentHandler $contentHandler): void {
public function registerContentHandler(ContentHandler $contentHandler): void {
if(!in_array($contentHandler, $this->contentHandlers))
$this->contentHandlers[] = $contentHandler;
}
@ -122,9 +122,9 @@ class HttpRouter implements IRouter {
* Retrieve a scoped router to a given path prefix.
*
* @param string $prefix Prefix to apply to paths within the returned router.
* @return IRouter Scopes router proxy.
* @return Router Scopes router proxy.
*/
public function scopeTo(string $prefix): IRouter {
public function scopeTo(string $prefix): Router {
return new ScopedRouter($this, $prefix);
}
@ -295,7 +295,7 @@ class HttpRouter implements IRouter {
if(!$response->hasContentType()) {
if(strtolower(substr($result, 0, 14)) === '<!doctype html')
$response->setTypeHTML($this->getCharSet());
$response->setTypeHtml($this->getCharSet());
else {
$charset = mb_detect_encoding($result);
if($charset !== false)
@ -303,7 +303,7 @@ class HttpRouter implements IRouter {
$charset = $charset === false ? 'utf-8' : strtolower($charset);
if(strtolower(substr($result, 0, 5)) === '<?xml')
$response->setTypeXML($charset);
$response->setTypeXml($charset);
else
$response->setTypePlain($charset);
}

View file

@ -1,18 +0,0 @@
<?php
// IRouteHandler.php
// Created: 2024-03-28
// Updated: 2024-03-28
namespace Index\Http\Routing;
/**
* Provides the interface for IRouter::register().
*/
interface IRouteHandler {
/**
* Registers routes on a given IRouter instance.
*
* @param IRouter $router Target router.
*/
public function registerRoutes(IRouter $router): void;
}

View file

@ -1,14 +1,18 @@
<?php
// RouteHandler.php
// Created: 2024-03-28
// Updated: 2024-03-28
// Updated: 2024-10-02
namespace Index\Http\Routing;
/**
* Provides an abstract class version of IRouteHandler that already includes the trait as well,
* letting you only have to use one use statement rather than two!
* Provides the interface for Router::register().
*/
abstract class RouteHandler implements IRouteHandler {
use RouteHandlerTrait;
interface RouteHandler {
/**
* Registers routes on a given Router instance.
*
* @param Router $router Target router.
*/
public function registerRoutes(Router $router): void;
}

View file

@ -1,16 +1,16 @@
<?php
// RouteHandlerTrait.php
// Created: 2024-03-28
// Updated: 2024-03-28
// Updated: 2024-10-02
namespace Index\Http\Routing;
/**
* Provides an implementation of IRouteHandler::registerRoutes that uses the attributes.
* Provides an implementation of RouteHandler::registerRoutes that uses the attributes.
* For more advanced use, everything can be use'd separately and HandlerAttribute::register called manually.
*/
trait RouteHandlerTrait {
public function registerRoutes(IRouter $router): void {
public function registerRoutes(Router $router): void {
HandlerAttribute::register($router, $this);
}
}

View file

@ -1,7 +1,7 @@
<?php
// IRouter.php
// Router.php
// Created: 2024-03-28
// Updated: 2024-03-28
// Updated: 2024-10-02
namespace Index\Http\Routing;
@ -9,14 +9,14 @@ use InvalidArgumentException;
use RuntimeException;
use Index\Http\HttpRequest;
interface IRouter {
interface Router {
/**
* Creates a scoped version of this router.
*
* @param string $prefix Prefix path to prepend to all registered routes.
* @return IRouter Scoped router.
* @return Router Scoped router.
*/
public function scopeTo(string $prefix): IRouter;
public function scopeTo(string $prefix): Router;
/**
* Apply middleware functions to a path.
@ -94,9 +94,9 @@ interface IRouter {
public function options(string $path, callable $handler): void;
/**
* Registers routes in an IRouteHandler implementation.
* Registers routes in an RouteHandler implementation.
*
* @param IRouteHandler $handler Routes handler.
* @param RouteHandler $handler Routes handler.
*/
public function register(IRouteHandler $handler): void;
public function register(RouteHandler $handler): void;
}

View file

@ -1,7 +1,7 @@
<?php
// RouterTrait.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Routing;
@ -33,7 +33,7 @@ trait RouterTrait {
$this->add('OPTIONS', $path, $handler);
}
public function register(IRouteHandler $handler): void {
public function register(RouteHandler $handler): void {
$handler->registerRoutes($this);
}
}

View file

@ -1,22 +1,22 @@
<?php
// ScopedRouter.php
// Created: 2024-03-28
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\Http\Routing;
/**
* Provides a scoped router interface, automatically adds a prefix to any routes added.
*/
class ScopedRouter implements IRouter {
class ScopedRouter implements Router {
use RouterTrait;
/**
* @param IRouter $router Underlying router.
* @param Router $router Underlying router.
* @param string $prefix Base path to use as a prefix.
*/
public function __construct(
private IRouter $router,
private Router $router,
private string $prefix
) {
if($router instanceof ScopedRouter)
@ -25,11 +25,11 @@ class ScopedRouter implements IRouter {
// TODO: cleanup prefix
}
private function getParentRouter(): IRouter {
private function getParentRouter(): Router {
return $this->router;
}
public function scopeTo(string $prefix): IRouter {
public function scopeTo(string $prefix): Router {
return $this->router->scopeTo($this->prefix . $prefix);
}

View file

@ -1,9 +1,9 @@
<?php
// FileStream.php
// Created: 2021-04-30
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use ErrorException;
use RuntimeException;

View file

@ -1,9 +1,9 @@
<?php
// GenericStream.php
// Created: 2021-04-30
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use InvalidArgumentException;
use RuntimeException;

View file

@ -1,9 +1,9 @@
<?php
// MemoryStream.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use RuntimeException;

View file

@ -1,13 +1,13 @@
<?php
// NetworkStream.php
// Created: 2021-04-30
// Updated: 2024-08-01
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use ErrorException;
use RuntimeException;
use Index\Net\{IPAddress,EndPoint};
use Index\Net\{IpAddress,EndPoint};
/**
* Represents a network socket stream.
@ -105,35 +105,35 @@ class NetworkStream extends GenericStream {
}
/**
* Opens a network socket stream to an endpoint represented by an Index IPAddress instance and port.
* Opens a network socket stream to an endpoint represented by an Index IpAddress instance and port.
*
* @param IPAddress $address Address to connect to.
* @param IpAddress $address Address to connect to.
* @param int $port Port to connect at.
* @param float|null $timeout Amount of seconds until timeout, null for php.ini default.
*/
public static function openAddress(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
public static function openAddress(IpAddress $address, int $port, float|null $timeout = null): NetworkStream {
return new NetworkStream($address->getAddress(), $port, $timeout);
}
/**
* Opens an SSL network socket stream to an endpoint represented by an Index IPAddress instance and port.
* Opens an SSL network socket stream to an endpoint represented by an Index IpAddress instance and port.
*
* @param IPAddress $address Address to connect to.
* @param IpAddress $address Address to connect to.
* @param int $port Port to connect at.
* @param float|null $timeout Amount of seconds until timeout, null for php.ini default.
*/
public static function openAddressSSL(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
public static function openAddressSSL(IpAddress $address, int $port, float|null $timeout = null): NetworkStream {
return new NetworkStream('ssl://' . $address->getAddress(), $port, $timeout);
}
/**
* Opens a TLS network socket stream to an endpoint represented by an Index IPAddress instance and port.
* Opens a TLS network socket stream to an endpoint represented by an Index IpAddress instance and port.
*
* @param IPAddress $address Address to connect to.
* @param IpAddress $address Address to connect to.
* @param int $port Port to connect at.
* @param float|null $timeout Amount of seconds until timeout, null for php.ini default.
*/
public static function openAddressTLS(IPAddress $address, int $port, float|null $timeout = null): NetworkStream {
public static function openAddressTLS(IpAddress $address, int $port, float|null $timeout = null): NetworkStream {
return new NetworkStream('tls://' . $address->getAddress(), $port, $timeout);
}

View file

@ -1,9 +1,9 @@
<?php
// ProcessStream.php
// Created: 2023-01-25
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use InvalidArgumentException;
use RuntimeException;

View file

@ -1,18 +1,18 @@
<?php
// Stream.php
// Created: 2021-04-30
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use RuntimeException;
use Stringable;
use Index\ICloseable;
use Index\Closeable;
/**
* Represents a generic data stream.
*/
abstract class Stream implements Stringable, ICloseable {
abstract class Stream implements Stringable, Closeable {
/**
* Place the cursor relative to the start of the file.
*

View file

@ -1,9 +1,9 @@
<?php
// TempFileStream.php
// Created: 2021-05-02
// Updated: 2024-08-03
// Updated: 2024-10-02
namespace Index\IO;
namespace Index\Io;
use RuntimeException;

View file

@ -1,7 +1,7 @@
<?php
// MediaType.php
// Created: 2022-02-10
// Updated: 2024-08-18
// Updated: 2024-10-02
namespace Index;
@ -12,7 +12,7 @@ use Stringable;
/**
* Implements a structure for representing and comparing media/mime types.
*/
class MediaType implements Stringable, IComparable, IEquatable {
class MediaType implements Stringable, Comparable, Equatable {
/**
* @param string $category Media type category.
* @param string $kind Media type kind.

Some files were not shown because too many files have changed in this diff Show more