1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-23 17:12:41 +00:00
Arsse/lib/Db/AbstractStatement.php

93 lines
3 KiB
PHP
Raw Normal View History

<?php
/** @license MIT
* Copyright 2017 J. King, Dustin Wilson et al.
* See LICENSE and AUTHORS files for details */
declare(strict_types=1);
2017-03-28 04:12:12 +00:00
namespace JKingWeb\Arsse\Db;
2017-08-29 14:50:31 +00:00
use JKingWeb\Arsse\Misc\Date;
abstract class AbstractStatement implements Statement {
protected $types = [];
protected $isNullable = [];
2017-08-29 14:50:31 +00:00
abstract public function runArray(array $values = []): Result;
public function run(...$values): Result {
return $this->runArray($values);
}
public function rebind(...$bindings): bool {
return $this->rebindArray($bindings);
}
public function rebindArray(array $bindings, bool $append = false): bool {
2017-08-29 14:50:31 +00:00
if (!$append) {
2017-07-21 02:40:09 +00:00
$this->types = [];
}
2017-08-29 14:50:31 +00:00
foreach ($bindings as $binding) {
if (is_array($binding)) {
// recursively flatten any arrays, which may be provided for SET or IN() clauses
$this->rebindArray($binding, true);
} else {
$binding = trim(strtolower($binding));
2017-08-29 14:50:31 +00:00
if (strpos($binding, "strict ")===0) {
// "strict" types' values may never be null; null values will later be cast to the type specified
$this->isNullable[] = false;
$binding = substr($binding, 7);
} else {
$this->isNullable[] = true;
}
2017-08-29 14:50:31 +00:00
if (!array_key_exists($binding, self::TYPES)) {
throw new Exception("paramTypeInvalid", $binding); // @codeCoverageIgnore
2017-07-21 02:40:09 +00:00
}
$this->types[] = self::TYPES[$binding];
}
}
return true;
}
protected function cast($v, string $t, bool $nullable) {
2017-08-29 14:50:31 +00:00
switch ($t) {
case "date":
2017-08-29 14:50:31 +00:00
if (is_null($v) && !$nullable) {
2017-07-21 02:40:09 +00:00
$v = 0;
}
return Date::transform($v, "date");
case "time":
2017-08-29 14:50:31 +00:00
if (is_null($v) && !$nullable) {
2017-07-21 02:40:09 +00:00
$v = 0;
}
return Date::transform($v, "time");
case "datetime":
2017-08-29 14:50:31 +00:00
if (is_null($v) && !$nullable) {
2017-07-21 02:40:09 +00:00
$v = 0;
}
return Date::transform($v, "sql");
case "null":
case "integer":
case "float":
case "binary":
case "string":
case "boolean":
2017-08-29 14:50:31 +00:00
if ($t=="binary") {
2017-07-21 02:40:09 +00:00
$t = "string";
}
2017-08-29 14:50:31 +00:00
if ($v instanceof \DateTimeInterface) {
if ($t=="string") {
return Date::transform($v, "sql");
} else {
$v = $v->getTimestamp();
2017-08-29 14:50:31 +00:00
settype($v, $t);
}
} else {
settype($v, $t);
}
return $v;
default:
throw new Exception("paramTypeUnknown", $type); // @codeCoverageIgnore
}
}
2017-08-29 14:50:31 +00:00
}