Formatting

This commit is contained in:
Greyscale 2024-04-14 18:11:25 +02:00
parent 167a482163
commit bc7fd3bf4f
34 changed files with 267 additions and 299 deletions

View file

@ -1,42 +1,2 @@
<?php <?php
$finder = PhpCsFixer\Finder::create(); return require("vendor/benzine/core/.php-cs-fixer.php");
if (!defined('__PHPCS_ROOT__')) {
define('__PHPCS_ROOT__', __DIR__);
}
$directories = [
__PHPCS_ROOT__.'/bin',
__PHPCS_ROOT__.'/src',
__PHPCS_ROOT__.'/test/src',
__PHPCS_ROOT__.'/test/tests',
];
if (isset($additionalDirectories)) {
$directories = array_merge($directories, $additionalDirectories);
}
foreach ($directories as $directory) {
if (file_exists($directory) && is_dir($directory)) {
$finder->in($directory);
}
}
return PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setHideProgress(false)
->setRules([
'@PSR2' => true,
'strict_param' => true,
'array_syntax' => ['syntax' => 'short'],
'@PhpCsFixer' => true,
'@PHP73Migration' => true,
'no_php4_constructor' => true,
'no_unused_imports' => true,
'no_useless_else' => true,
'no_superfluous_phpdoc_tags' => false,
'void_return' => true,
'yoda_style' => false,
])
->setFinder($finder)
;

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Abstracts; namespace Benzine\ORM\Abstracts;
abstract class AbstractCollection abstract class AbstractCollection

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Abstracts; namespace Benzine\ORM\Abstracts;
use Benzine\ORM\Finder; use Benzine\ORM\Finder;
@ -9,7 +11,7 @@ use Camel\Format;
abstract class AbstractModel implements ModelInterface, \Serializable abstract class AbstractModel implements ModelInterface, \Serializable
{ {
protected array $_primary_keys = []; protected array $_primary_keys = [];
protected array $_autoincrement_keys = []; protected array $_autoincrement_keys = [];
protected array $_original; protected array $_original;
@ -26,9 +28,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
* Overrideable __setUp function that will allow you to hijack * Overrideable __setUp function that will allow you to hijack
* it and create any related objects that need to be recreated. * it and create any related objects that need to be recreated.
*/ */
public function __setUp(): void public function __setUp(): void {}
{
}
public function __wakeup(): void public function __wakeup(): void
{ {
@ -45,8 +45,8 @@ abstract class AbstractModel implements ModelInterface, \Serializable
$transformer = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps()); $transformer = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps());
foreach ($this->getListOfProperties() as $property) { foreach ($this->getListOfProperties() as $property) {
$getFunction = "get{$property}"; $getFunction = "get{$property}";
$currentValue = $this->{$getFunction}(); $currentValue = $this->{$getFunction}();
$array[$transformer->transform($property)] = $currentValue; $array[$transformer->transform($property)] = $currentValue;
} }
@ -146,7 +146,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
{ {
$primaryKeyValues = []; $primaryKeyValues = [];
foreach ($this->_primary_keys as $internalName => $dbName) { foreach ($this->_primary_keys as $internalName => $dbName) {
$getFunction = "get{$internalName}"; $getFunction = "get{$internalName}";
$primaryKeyValues[$internalName] = $this->{$getFunction}(); $primaryKeyValues[$internalName] = $this->{$getFunction}();
} }
@ -157,7 +157,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
{ {
$primaryKeyValues = []; $primaryKeyValues = [];
foreach ($this->_primary_keys as $internalName => $dbName) { foreach ($this->_primary_keys as $internalName => $dbName) {
$getFunction = "get{$internalName}"; $getFunction = "get{$internalName}";
$primaryKeyValues[$dbName] = $this->{$getFunction}(); $primaryKeyValues[$dbName] = $this->{$getFunction}();
} }
@ -173,7 +173,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
{ {
$autoIncrementKeyValues = []; $autoIncrementKeyValues = [];
foreach ($this->_autoincrement_keys as $autoincrement_key => $autoincrement_db_column) { foreach ($this->_autoincrement_keys as $autoincrement_key => $autoincrement_db_column) {
$getFunction = "get{$autoincrement_key}"; $getFunction = "get{$autoincrement_key}";
$autoIncrementKeyValues[$autoincrement_key] = $this->{$getFunction}(); $autoIncrementKeyValues[$autoincrement_key] = $this->{$getFunction}();
} }
@ -209,7 +209,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
*/ */
public function getListOfDirtyProperties(): array public function getListOfDirtyProperties(): array
{ {
$transformer = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps()); $transformer = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps());
$dirtyProperties = []; $dirtyProperties = [];
foreach ($this->getListOfProperties() as $property) { foreach ($this->getListOfProperties() as $property) {
$originalProperty = $transformer->transform($property); $originalProperty = $transformer->transform($property);
@ -217,7 +217,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
if (!isset($this->_original[$originalProperty]) || $this->{$property} != $this->_original[$originalProperty]) { if (!isset($this->_original[$originalProperty]) || $this->{$property} != $this->_original[$originalProperty]) {
$dirtyProperties[$property] = [ $dirtyProperties[$property] = [
'before' => $this->_original[$originalProperty] ?? null, 'before' => $this->_original[$originalProperty] ?? null,
'after' => $this->{$property}, 'after' => $this->{$property},
]; ];
} }
} }
@ -265,7 +265,7 @@ abstract class AbstractModel implements ModelInterface, \Serializable
if (method_exists($this, 'getName')) { if (method_exists($this, 'getName')) {
return $this->getName(); return $this->getName();
} }
$labelParts = []; $labelParts = [];
$primaryKeyFields = array_keys($this->getPrimaryKeys()); $primaryKeyFields = array_keys($this->getPrimaryKeys());
foreach ($primaryKeyFields as $primaryKeyField) { foreach ($primaryKeyFields as $primaryKeyField) {
$labelParts[] = $this->__get($primaryKeyField); $labelParts[] = $this->__get($primaryKeyField);

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Abstracts; namespace Benzine\ORM\Abstracts;
use Benzine\ORM\Interfaces\CollectionsInterface; use Benzine\ORM\Interfaces\CollectionsInterface;
@ -19,24 +21,22 @@ abstract class AbstractService
/** /**
* @param null|array|\Closure[] $wheres * @param null|array|\Closure[] $wheres
* @param null|Sql\Expression|string $order * @param null|Sql\Expression|string $order
*
* @return CollectionsInterface
*/ */
public function getAll( public function getAll(
int $limit = null, ?int $limit = null,
int $offset = null, ?int $offset = null,
array $wheres = null, ?array $wheres = null,
$order = null, $order = null,
string $orderDirection = null ?string $orderDirection = null
): CollectionsInterface { ): CollectionsInterface {
/** @var AbstractTableGateway $tableGateway */ /** @var AbstractTableGateway $tableGateway */
$tableGateway = $this->getNewTableGatewayInstance(); $tableGateway = $this->getNewTableGatewayInstance();
[$matches, $count] = $tableGateway->fetchAll( [$matches, $count] = $tableGateway->fetchAll(
$limit, $limit,
$offset, $offset,
$wheres, $wheres,
$order, $order,
null !== $orderDirection ? $orderDirection : Sql\Select::ORDER_ASCENDING null !== $orderDirection ? $orderDirection : Select::ORDER_ASCENDING
); );
$collection = $this->getNewCollectionInstance(); $collection = $this->getNewCollectionInstance();
@ -51,15 +51,13 @@ abstract class AbstractService
/** /**
* @param null|string $distinctColumn * @param null|string $distinctColumn
* @param null|array|\Closure[] $wheres * @param null|array|\Closure[] $wheres
*
* @return AbstractCollection
*/ */
public function getDistinct( public function getDistinct(
string $distinctColumn, string $distinctColumn,
array $wheres = null ?array $wheres = null
): AbstractCollection { ): AbstractCollection {
/** @var AbstractTableGateway $tableGateway */ /** @var AbstractTableGateway $tableGateway */
$tableGateway = $this->getNewTableGatewayInstance(); $tableGateway = $this->getNewTableGatewayInstance();
[$matches, $count] = $tableGateway->fetchDistinct( [$matches, $count] = $tableGateway->fetchDistinct(
$distinctColumn, $distinctColumn,
$wheres $wheres
@ -76,11 +74,9 @@ abstract class AbstractService
/** /**
* @param null|array|\Closure[] $wheres * @param null|array|\Closure[] $wheres
*
* @return int
*/ */
public function countAll( public function countAll(
array $wheres = null ?array $wheres = null
): int { ): int {
/** @var AbstractTableGateway $tableGateway */ /** @var AbstractTableGateway $tableGateway */
$tableGateway = $this->getNewTableGatewayInstance(); $tableGateway = $this->getNewTableGatewayInstance();
@ -91,7 +87,7 @@ abstract class AbstractService
/** /**
* @return Benzine\ORM\Abstracts\Model[] * @return Benzine\ORM\Abstracts\Model[]
*/ */
public function search(Sql\Where $where, int $limit = null, int $offset = null): \Generator public function search(Sql\Where $where, ?int $limit = null, ?int $offset = null): \Generator
{ {
$tableGateway = $this->getNewTableGatewayInstance(); $tableGateway = $this->getNewTableGatewayInstance();
@ -118,7 +114,7 @@ abstract class AbstractService
abstract public function getByField(string $field, $value, $orderBy = null, $orderDirection = Select::ORDER_ASCENDING): ?AbstractModel; abstract public function getByField(string $field, $value, $orderBy = null, $orderDirection = Select::ORDER_ASCENDING): ?AbstractModel;
abstract public function getManyByField(string $field, $value, int $limit = null, int $offset = null, $orderBy = null, $orderDirection = Select::ORDER_ASCENDING): AbstractCollection; abstract public function getManyByField(string $field, $value, ?int $limit = null, ?int $offset = null, $orderBy = null, $orderDirection = Select::ORDER_ASCENDING): AbstractCollection;
abstract public function countByField(string $field, $value): int; abstract public function countByField(string $field, $value): int;

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Abstracts; namespace Benzine\ORM\Abstracts;
use Benzine\Controllers\Filters\FilterCondition; use Benzine\Controllers\Filters\FilterCondition;
@ -17,6 +19,7 @@ use Laminas\Db\Sql\Predicate\PredicateInterface;
use Laminas\Db\Sql\Select; use Laminas\Db\Sql\Select;
use Laminas\Db\Sql\Where; use Laminas\Db\Sql\Where;
use Laminas\Db\TableGateway\TableGateway; use Laminas\Db\TableGateway\TableGateway;
use Laminas\Db\ResultSet\ResultSetInterface;
abstract class AbstractTableGateway extends TableGateway abstract class AbstractTableGateway extends TableGateway
{ {
@ -26,7 +29,7 @@ abstract class AbstractTableGateway extends TableGateway
public function __construct($table, AdapterInterface $adapter, $features = null, $resultSetPrototype = null, $sql = null) public function __construct($table, AdapterInterface $adapter, $features = null, $resultSetPrototype = null, $sql = null)
{ {
$this->adapter = $adapter; $this->adapter = $adapter;
$this->table = $table; $this->table = $table;
if (!$sql) { if (!$sql) {
$sql = new LaminatorSql($this->adapter, $this->table); $sql = new LaminatorSql($this->adapter, $this->table);
@ -91,9 +94,9 @@ abstract class AbstractTableGateway extends TableGateway
return $updatedModel; return $updatedModel;
} catch (InvalidQueryException $iqe) { } catch (InvalidQueryException $iqe) {
throw new InvalidQueryException( throw new InvalidQueryException(
'While trying to call '.get_class().'->save(): ... '. 'While trying to call ' . get_class() . '->save(): ... ' .
$iqe->getMessage()."\n\n". $iqe->getMessage() . "\n\n" .
substr(var_export($model, true), 0, 1024)."\n\n", substr(var_export($model, true), 0, 1024) . "\n\n",
$iqe->getCode(), $iqe->getCode(),
$iqe $iqe
); );
@ -188,6 +191,7 @@ abstract class AbstractTableGateway extends TableGateway
public function update($data, $where = null, $oldData = []) public function update($data, $where = null, $oldData = [])
{ {
$data = array_filter($data); $data = array_filter($data);
// !\Kint::dump($data, $oldData, $where);exit; // !\Kint::dump($data, $oldData, $where);exit;
return parent::update($data, $where); return parent::update($data, $where);
} }
@ -204,9 +208,9 @@ abstract class AbstractTableGateway extends TableGateway
* @return array [ResultSet,int] Returns an array of resultSet,total_found_rows * @return array [ResultSet,int] Returns an array of resultSet,total_found_rows
*/ */
public function fetchAll( public function fetchAll(
int $limit = null, ?int $limit = null,
int $offset = null, ?int $offset = null,
array $wheres = null, ?array $wheres = null,
$order = null, $order = null,
string $direction = Select::ORDER_ASCENDING string $direction = Select::ORDER_ASCENDING
) { ) {
@ -326,7 +330,7 @@ abstract class AbstractTableGateway extends TableGateway
*/ */
public function fetchDistinct( public function fetchDistinct(
string $distinctColumn, string $distinctColumn,
array $wheres = null ?array $wheres = null
) { ) {
/** @var Select $select */ /** @var Select $select */
$select = $this->getSql()->select(); $select = $this->getSql()->select();
@ -403,9 +407,9 @@ abstract class AbstractTableGateway extends TableGateway
} }
/** /**
* @throws BenzineException
*
* @return null|ModelInterface * @return null|ModelInterface
*
* @throws BenzineException
*/ */
public function fetchRandom() public function fetchRandom()
{ {
@ -489,7 +493,7 @@ abstract class AbstractTableGateway extends TableGateway
public function getCountUnique(string $field, $wheres = []): int public function getCountUnique(string $field, $wheres = []): int
{ {
$select = $this->getSql()->select(); $select = $this->getSql()->select();
$select->columns(['total' => new Expression('DISTINCT '.$field)]); $select->columns(['total' => new Expression('DISTINCT ' . $field)]);
if (count($wheres) > 0) { if (count($wheres) > 0) {
foreach ($wheres as $where) { foreach ($wheres as $where) {
$select->where($where); $select->where($where);
@ -536,7 +540,7 @@ abstract class AbstractTableGateway extends TableGateway
->current() ->current()
; ;
$highestPrimaryKey = !is_null($row) ? $row['max'] : 0; $highestPrimaryKey = !is_null($row) ? $row['max'] : 0;
$highestPrimaryKeys[$primaryKey] = $highestPrimaryKey; $highestPrimaryKeys[$primaryKey] = $highestPrimaryKey;
} }
@ -558,7 +562,7 @@ abstract class AbstractTableGateway extends TableGateway
->current() ->current()
; ;
$highestAutoIncrementKey = !is_null($row) ? $row['max'] : 0; $highestAutoIncrementKey = !is_null($row) ? $row['max'] : 0;
$highestAutoIncrementKeys[$autoIncrementKey] = $highestAutoIncrementKey; $highestAutoIncrementKeys[$autoIncrementKey] = $highestAutoIncrementKey;
} }
@ -566,8 +570,6 @@ abstract class AbstractTableGateway extends TableGateway
} }
/** /**
* @param $id
*
* @return null|AbstractModel * @return null|AbstractModel
*/ */
public function getById($id) public function getById($id)
@ -576,9 +578,7 @@ abstract class AbstractTableGateway extends TableGateway
} }
/** /**
* @param $field * @param $orderBy string Field to sort by
* @param $value
* @param $orderBy string Field to sort by
* @param $orderDirection string Direction to sort (Select::ORDER_ASCENDING || Select::ORDER_DESCENDING) * @param $orderDirection string Direction to sort (Select::ORDER_ASCENDING || Select::ORDER_DESCENDING)
* *
* @return null|array|\ArrayObject * @return null|array|\ArrayObject
@ -633,15 +633,11 @@ abstract class AbstractTableGateway extends TableGateway
} }
/** /**
* @param Where $where
* @param null|int $limit
* @param null|int $offset
* @param null|Expression|string $orderBy * @param null|Expression|string $orderBy
* @param string $orderDirection
* *
* @return \Laminas\Db\ResultSet\ResultSetInterface * @return ResultSetInterface
*/ */
public function getManyByWhere(Where $where, int $limit = null, int $offset = null, $orderBy = null, string $orderDirection = Select::ORDER_ASCENDING) public function getManyByWhere(Where $where, ?int $limit = null, ?int $offset = null, $orderBy = null, string $orderDirection = Select::ORDER_ASCENDING)
{ {
$select = $this->sql->select(); $select = $this->sql->select();
@ -667,15 +663,14 @@ abstract class AbstractTableGateway extends TableGateway
} }
/** /**
* @param null|int $limit int * @param null|int $limit int
* @param null|int $offset int * @param null|int $offset int
* @param null|string $orderBy string Field to sort by * @param null|string $orderBy string Field to sort by
* @param $orderDirection string Direction to sort (Select::ORDER_ASCENDING || Select::ORDER_DESCENDING) * @param $orderDirection string Direction to sort (Select::ORDER_ASCENDING || Select::ORDER_DESCENDING)
* @param mixed $value
* *
* @return AbstractCollection * @return AbstractCollection
*/ */
public function getManyByField(string $field, $value, int $limit = null, int $offset = null, string $orderBy = null, string $orderDirection = Select::ORDER_ASCENDING) public function getManyByField(string $field, $value, ?int $limit = null, ?int $offset = null, ?string $orderBy = null, string $orderDirection = Select::ORDER_ASCENDING)
{ {
if ($value instanceof \DateTime) { if ($value instanceof \DateTime) {
$value = $value->format('Y-m-d H:i:s'); $value = $value->format('Y-m-d H:i:s');
@ -695,7 +690,7 @@ abstract class AbstractTableGateway extends TableGateway
new Expression('COUNT(*) as count'), new Expression('COUNT(*) as count'),
]); ]);
$statement = $this->sql->prepareStatementForSqlObject($select); $statement = $this->sql->prepareStatementForSqlObject($select);
$result = $statement->execute(); $result = $statement->execute();
$data = $result->current(); $data = $result->current();
@ -744,7 +739,7 @@ abstract class AbstractTableGateway extends TableGateway
public function getBySelect(Select $select): array public function getBySelect(Select $select): array
{ {
$resultSet = $this->executeSelect($select); $resultSet = $this->executeSelect($select);
$return = []; $return = [];
foreach ($resultSet as $result) { foreach ($resultSet as $result) {
$return[] = $result; $return[] = $result;
} }
@ -758,7 +753,7 @@ abstract class AbstractTableGateway extends TableGateway
public function getBySelectRaw(Select $select): array public function getBySelectRaw(Select $select): array
{ {
$resultSet = $this->executeSelect($select); $resultSet = $this->executeSelect($select);
$return = []; $return = [];
while ($result = $resultSet->getDataSource()->current()) { while ($result = $resultSet->getDataSource()->current()) {
$return[] = $result; $return[] = $result;
$resultSet->getDataSource()->next(); $resultSet->getDataSource()->next();

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM; namespace Benzine\ORM;
use Benzine\ORM\Profiler\Profiler as BenzineProfiler; use Benzine\ORM\Profiler\Profiler as BenzineProfiler;
@ -10,7 +12,7 @@ use Laminas\Db\ResultSet;
class Adapter extends LaminasAdapter class Adapter extends LaminasAdapter
{ {
public function __construct($driver, Platform\PlatformInterface $platform = null, ResultSet\ResultSetInterface $queryResultPrototype = null, Profiler\ProfilerInterface $profiler = null) public function __construct($driver, ?Platform\PlatformInterface $platform = null, ?ResultSet\ResultSetInterface $queryResultPrototype = null, ?Profiler\ProfilerInterface $profiler = null)
{ {
parent::__construct($driver, $platform, $queryResultPrototype, $profiler); parent::__construct($driver, $platform, $queryResultPrototype, $profiler);
// if (!defined('ZEND_PROFILER_DISABLE') || ZEND_PROFILER_DISABLE == false) { // if (!defined('ZEND_PROFILER_DISABLE') || ZEND_PROFILER_DISABLE == false) {

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Components; namespace Benzine\ORM\Components;
use Benzine\ORM\Exception\DBTypeNotTranslatedException; use Benzine\ORM\Exception\DBTypeNotTranslatedException;
@ -23,8 +25,8 @@ class Column extends Entity
protected $permittedValues; protected $permittedValues;
protected $defaultValue; protected $defaultValue;
protected $defaultValueIsLiteral = false; protected $defaultValueIsLiteral = false;
protected $isAutoIncrement = false; protected $isAutoIncrement = false;
protected $isUnique = false; protected $isUnique = false;
/** @var RelatedModel[] */ /** @var RelatedModel[] */
protected $relatedObjects = []; protected $relatedObjects = [];
@ -97,8 +99,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $phpType
*
* @return Column * @return Column
*/ */
public function setPhpType($phpType) public function setPhpType($phpType)
@ -124,8 +124,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $field
*
* @return Column * @return Column
*/ */
public function setField($field) public function setField($field)
@ -154,8 +152,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $dbField
*
* @return Column * @return Column
*/ */
public function setDbField($dbField) public function setDbField($dbField)
@ -176,8 +172,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $maxDecimalPlaces
*
* @return Column * @return Column
*/ */
public function setMaxDecimalPlaces($maxDecimalPlaces) public function setMaxDecimalPlaces($maxDecimalPlaces)
@ -193,8 +187,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $defaultValue
*
* @return Column * @return Column
*/ */
public function setDefaultValue($defaultValue) public function setDefaultValue($defaultValue)
@ -233,8 +225,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $maxLength
*
* @return Column * @return Column
*/ */
public function setMaxLength($maxLength) public function setMaxLength($maxLength)
@ -250,8 +240,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $maxFieldLength
*
* @return Column * @return Column
*/ */
public function setMaxFieldLength($maxFieldLength) public function setMaxFieldLength($maxFieldLength)
@ -267,11 +255,9 @@ class Column extends Entity
} }
/** /**
* @param mixed $dbType * @return Column
* *
* @throws DBTypeNotTranslatedException * @throws DBTypeNotTranslatedException
*
* @return Column
*/ */
public function setDbType($dbType) public function setDbType($dbType)
{ {
@ -325,7 +311,7 @@ class Column extends Entity
case 'timestamp': // MySQL case 'timestamp': // MySQL
case 'datetime': // MySQL case 'datetime': // MySQL
$this->setPhpType('\\'.DateTime::class); $this->setPhpType('\\' . DateTime::class);
break; break;
@ -342,8 +328,6 @@ class Column extends Entity
} }
/** /**
* @param mixed $permittedValues
*
* @return Column * @return Column
*/ */
public function setPermittedValues($permittedValues) public function setPermittedValues($permittedValues)

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Components; namespace Benzine\ORM\Components;
use Benzine\ORM\Laminator; use Benzine\ORM\Laminator;
@ -23,16 +25,16 @@ class Entity
public function __construct() public function __construct()
{ {
$this->transSnake2Studly = new CaseTransformer(new Format\SnakeCase(), new Format\StudlyCaps()); $this->transSnake2Studly = new CaseTransformer(new Format\SnakeCase(), new Format\StudlyCaps());
$this->transStudly2Camel = new CaseTransformer(new Format\StudlyCaps(), new Format\CamelCase()); $this->transStudly2Camel = new CaseTransformer(new Format\StudlyCaps(), new Format\CamelCase());
$this->transStudly2Studly = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps()); $this->transStudly2Studly = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps());
$this->transCamel2Camel = new CaseTransformer(new Format\CamelCase(), new Format\CamelCase()); $this->transCamel2Camel = new CaseTransformer(new Format\CamelCase(), new Format\CamelCase());
$this->transCamel2Studly = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps()); $this->transCamel2Studly = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps());
$this->transSnake2Camel = new CaseTransformer(new Format\SnakeCase(), new Format\CamelCase()); $this->transSnake2Camel = new CaseTransformer(new Format\SnakeCase(), new Format\CamelCase());
$this->transSnake2Spinal = new CaseTransformer(new Format\SnakeCase(), new Format\SpinalCase()); $this->transSnake2Spinal = new CaseTransformer(new Format\SnakeCase(), new Format\SpinalCase());
$this->transCamel2Snake = new CaseTransformer(new Format\CamelCase(), new Format\SnakeCase()); $this->transCamel2Snake = new CaseTransformer(new Format\CamelCase(), new Format\SnakeCase());
$this->transCamel2ScreamingSnake = new CaseTransformer(new Format\CamelCase(), new Format\ScreamingSnakeCase()); $this->transCamel2ScreamingSnake = new CaseTransformer(new Format\CamelCase(), new Format\ScreamingSnakeCase());
$this->transStudly2Snake = new CaseTransformer(new Format\StudlyCaps(), new Format\SnakeCase()); $this->transStudly2Snake = new CaseTransformer(new Format\StudlyCaps(), new Format\SnakeCase());
$this->transField2Property = $this->transCamel2Camel; $this->transField2Property = $this->transCamel2Camel;
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Components; namespace Benzine\ORM\Components;
use Benzine\Exceptions\BenzineException; use Benzine\Exceptions\BenzineException;
@ -17,10 +19,10 @@ class Model extends Entity
protected string $table; protected string $table;
/** @var Column[] */ /** @var Column[] */
protected array $columns = []; protected array $columns = [];
protected array $constraints = []; protected array $constraints = [];
protected array $relatedObjects = []; protected array $relatedObjects = [];
protected array $primaryKeys = []; protected array $primaryKeys = [];
protected $autoIncrements; protected $autoIncrements;
/** /**
@ -41,9 +43,9 @@ class Model extends Entity
foreach ($zendConstraints as $zendConstraint) { foreach ($zendConstraints as $zendConstraint) {
if ('FOREIGN KEY' == $zendConstraint->getType()) { if ('FOREIGN KEY' == $zendConstraint->getType()) {
// \Kint::dump($this->getTable(), $this->getClassPrefix(), $zendConstraint->getTableName()); // \Kint::dump($this->getTable(), $this->getClassPrefix(), $zendConstraint->getTableName());
$keyMapIdLocal = $zendConstraint->getSchemaName().'::'.$zendConstraint->getTableName(); $keyMapIdLocal = $zendConstraint->getSchemaName() . '::' . $zendConstraint->getTableName();
$keyMapIdRemote = $zendConstraint->getReferencedTableSchema().'::'.$zendConstraint->getReferencedTableName(); $keyMapIdRemote = $zendConstraint->getReferencedTableSchema() . '::' . $zendConstraint->getReferencedTableName();
$localRelatedModel = $models[$keyMap[$keyMapIdLocal]]; $localRelatedModel = $models[$keyMap[$keyMapIdLocal]];
$remoteRelatedModel = $models[$keyMap[$keyMapIdRemote]]; $remoteRelatedModel = $models[$keyMap[$keyMapIdRemote]];
// \Kint::dump(array_keys($models), $zendConstraint, $relatedModel);exit; // \Kint::dump(array_keys($models), $zendConstraint, $relatedModel);exit;
@ -122,7 +124,7 @@ class Model extends Entity
{ {
if ($this->getClassPrefix()) { if ($this->getClassPrefix()) {
return return
$this->getClassPrefix(). $this->getClassPrefix() .
$this->transStudly2Studly->transform($this->getTableSanitised()); $this->transStudly2Studly->transform($this->getTableSanitised());
} }
@ -217,7 +219,7 @@ class Model extends Entity
return $this->columns[$name]; return $this->columns[$name];
} }
throw new BenzineException("Cannot find a Column called {$name} in ".implode(', ', array_keys($this->getColumns()))); throw new BenzineException("Cannot find a Column called {$name} in " . implode(', ', array_keys($this->getColumns())));
} }
public function hasColumn(string $columName): bool public function hasColumn(string $columName): bool
@ -258,8 +260,8 @@ class Model extends Entity
foreach ($columns as $column) { foreach ($columns as $column) {
/** @var ColumnObject $column */ /** @var ColumnObject $column */
$typeFragments = explode(' ', $column->getDataType()); $typeFragments = explode(' ', $column->getDataType());
$dbColumnName = $column->getName(); $dbColumnName = $column->getName();
$codeColumnName = $this->sanitiseColumnName($column->getName()); $codeColumnName = $this->sanitiseColumnName($column->getName());
$oColumn = Column::Factory($this->getLaminator()) $oColumn = Column::Factory($this->getLaminator())
@ -281,7 +283,7 @@ class Model extends Entity
case 'Postgresql': case 'Postgresql':
if ('USER-DEFINED' == $column->getDataType()) { if ('USER-DEFINED' == $column->getDataType()) {
$enumName = explode('::', $column->getColumnDefault(), 2)[1]; $enumName = explode('::', $column->getColumnDefault(), 2)[1];
$permittedValues = []; $permittedValues = [];
foreach ($this->getDatabase()->getAdaptor()->query("SELECT unnest(enum_range(NULL::{$enumName})) AS option")->execute() as $aiColumn) { foreach ($this->getDatabase()->getAdaptor()->query("SELECT unnest(enum_range(NULL::{$enumName})) AS option")->execute() as $aiColumn) {
$permittedValues[] = $aiColumn['option']; $permittedValues[] = $aiColumn['option'];
@ -343,26 +345,26 @@ class Model extends Entity
{ {
return [ return [
'namespace' => $this->getNamespace(), 'namespace' => $this->getNamespace(),
'database' => $this->getDatabase()->getName(), 'database' => $this->getDatabase()->getName(),
'table' => $this->getTable(), 'table' => $this->getTable(),
'app_name' => $this->getLaminator()->getBenzineConfig()->getAppName(), 'app_name' => $this->getLaminator()->getBenzineConfig()->getAppName(),
'app_core' => $this->getLaminator()->getBenzineConfig()->getCore(), 'app_core' => $this->getLaminator()->getBenzineConfig()->getCore(),
// 'app_container' => $this->getLaminator()->getBenzineConfig()->getAppContainer(), // 'app_container' => $this->getLaminator()->getBenzineConfig()->getAppContainer(),
'class_name' => $this->getClassName(), 'class_name' => $this->getClassName(),
'endpoint_name' => $this->getEndpointName(), 'endpoint_name' => $this->getEndpointName(),
'variable_name' => $this->transStudly2Camel->transform($this->getClassName()), 'variable_name' => $this->transStudly2Camel->transform($this->getClassName()),
'name' => $this->getClassName(), 'name' => $this->getClassName(),
'object_name_plural' => Inflect::pluralize($this->getClassName()), 'object_name_plural' => Inflect::pluralize($this->getClassName()),
'object_name_singular' => $this->getClassName(), 'object_name_singular' => $this->getClassName(),
'controller_route' => $this->transCamel2Snake->transform(Inflect::pluralize($this->getClassName())), 'controller_route' => $this->transCamel2Snake->transform(Inflect::pluralize($this->getClassName())),
'namespace_model' => "{$this->getNamespace()}\\Models\\{$this->getClassName()}Model", 'namespace_model' => "{$this->getNamespace()}\\Models\\{$this->getClassName()}Model",
'columns' => $this->columns, 'columns' => $this->columns,
'related_objects' => $this->getRelatedObjects(), 'related_objects' => $this->getRelatedObjects(),
'related_objects_shared' => $this->getRelatedObjectsSharedAssets(), 'related_objects_shared' => $this->getRelatedObjectsSharedAssets(),
'remote_objects' => $this->getRemoteObjects(), 'remote_objects' => $this->getRemoteObjects(),
'primary_keys' => $this->getPrimaryKeys(), 'primary_keys' => $this->getPrimaryKeys(),
'primary_parameters' => $this->getPrimaryParameters(), 'primary_parameters' => $this->getPrimaryParameters(),
'autoincrement_keys' => $this->getAutoIncrements(), 'autoincrement_keys' => $this->getAutoIncrements(),
// @todo: work out why there are two. // @todo: work out why there are two.
'autoincrement_parameters' => $this->getAutoIncrements(), 'autoincrement_parameters' => $this->getAutoIncrements(),
]; ];
@ -407,6 +409,7 @@ class Model extends Entity
foreach ($this->getRelatedObjects() as $relatedObject) { foreach ($this->getRelatedObjects() as $relatedObject) {
$sharedAssets[$relatedObject->getRemoteClass()] = $relatedObject; $sharedAssets[$relatedObject->getRemoteClass()] = $relatedObject;
} }
// if(count($this->getRelatedObjects())) { // if(count($this->getRelatedObjects())) {
// \Kint::dump($this->getRelatedObjects(), $sharedAssets); // \Kint::dump($this->getRelatedObjects(), $sharedAssets);
// exit; // exit;
@ -514,7 +517,7 @@ class Model extends Entity
} }
} }
if (Laminator::BenzineConfig()->has("benzine/databases/{$database}/column_options/_/transform")) { if (Laminator::BenzineConfig()->has("benzine/databases/{$database}/column_options/_/transform")) {
$transform = Laminator::BenzineConfig()->get("benzine/databases/{$database}/column_options/_/transform"); $transform = Laminator::BenzineConfig()->get("benzine/databases/{$database}/column_options/_/transform");
$columnName = $this->getLaminator()->{$transform}->transform($columnName); $columnName = $this->getLaminator()->{$transform}->transform($columnName);
} }
if (Laminator::BenzineConfig()->has("benzine/databases/{$database}/column_options/_/replace")) { if (Laminator::BenzineConfig()->has("benzine/databases/{$database}/column_options/_/replace")) {

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Components; namespace Benzine\ORM\Components;
use Benzine\ORM\Connection\Database; use Benzine\ORM\Connection\Database;
@ -65,7 +67,7 @@ class RelatedModel extends Entity
public function getRemoteVariable(): string public function getRemoteVariable(): string
{ {
return $this->transStudly2Camel->transform( return $this->transStudly2Camel->transform(
$this->getRemoteClassPrefix(). $this->getRemoteClassPrefix() .
$this->transCamel2Studly->transform($this->getRemoteTableSanitised()) $this->transCamel2Studly->transform($this->getRemoteTableSanitised())
); );
} }
@ -102,7 +104,7 @@ class RelatedModel extends Entity
public function getLocalVariable(): string public function getLocalVariable(): string
{ {
return $this->transStudly2Camel->transform( return $this->transStudly2Camel->transform(
$this->getLocalClassPrefix(). $this->getLocalClassPrefix() .
$this->transCamel2Studly->transform($this->getLocalTableSanitised()) $this->transCamel2Studly->transform($this->getLocalTableSanitised())
); );
} }
@ -126,7 +128,7 @@ class RelatedModel extends Entity
public function getLocalBoundColumnAsConstant(): string public function getLocalBoundColumnAsConstant(): string
{ {
return 'FIELD_'.str_replace('_', '', $this->transCamel2ScreamingSnake->transform($this->getLocalBoundColumn())); return 'FIELD_' . str_replace('_', '', $this->transCamel2ScreamingSnake->transform($this->getLocalBoundColumn()));
} }
public function getLocalTable(): string public function getLocalTable(): string
@ -145,7 +147,7 @@ class RelatedModel extends Entity
{ {
return $this->transCamel2Studly->transform( return $this->transCamel2Studly->transform(
$this->getLocalClass() $this->getLocalClass()
.'TableGateway' . 'TableGateway'
); );
} }
@ -153,7 +155,7 @@ class RelatedModel extends Entity
{ {
return $this->transCamel2Studly->transform( return $this->transCamel2Studly->transform(
$this->getRemoteClass() $this->getRemoteClass()
.'TableGateway' . 'TableGateway'
); );
} }
@ -161,7 +163,7 @@ class RelatedModel extends Entity
{ {
return $this->transCamel2Studly->transform( return $this->transCamel2Studly->transform(
$this->getLocalClass() $this->getLocalClass()
.'Model' . 'Model'
); );
} }
@ -169,7 +171,7 @@ class RelatedModel extends Entity
{ {
return $this->transCamel2Studly->transform( return $this->transCamel2Studly->transform(
$this->getRemoteClass() $this->getRemoteClass()
.'Model' . 'Model'
); );
} }
@ -177,10 +179,9 @@ class RelatedModel extends Entity
{ {
if ($this->hasClassConflict()) { if ($this->hasClassConflict()) {
return return
self::singulariseCamelCaseSentence($this->getLocalClass()). self::singulariseCamelCaseSentence($this->getLocalClass()) .
'By'. 'By' .
$this->transCamel2Studly->transform($this->getLocalBoundColumn()) $this->transCamel2Studly->transform($this->getLocalBoundColumn());
;
} }
return $this->transCamel2Studly->transform( return $this->transCamel2Studly->transform(
@ -192,8 +193,8 @@ class RelatedModel extends Entity
{ {
if ($this->hasClassConflict()) { if ($this->hasClassConflict()) {
return return
self::singulariseCamelCaseSentence($this->getRemoteClass()). self::singulariseCamelCaseSentence($this->getRemoteClass()) .
'By'. 'By' .
$this->transCamel2Studly->transform($this->getLocalBoundColumn()); $this->transCamel2Studly->transform($this->getLocalBoundColumn());
} }
@ -210,7 +211,7 @@ class RelatedModel extends Entity
public function getLocalClass(): string public function getLocalClass(): string
{ {
return $this->getLocalClassPrefix(). return $this->getLocalClassPrefix() .
$this->transCamel2Studly->transform($this->getLocalTableSanitised()); $this->transCamel2Studly->transform($this->getLocalTableSanitised());
} }
@ -233,28 +234,28 @@ class RelatedModel extends Entity
public function getRemoteClass(): string public function getRemoteClass(): string
{ {
return $this->getRemoteClassPrefix(). return $this->getRemoteClassPrefix() .
$this->transCamel2Studly->transform($this->getRemoteTableSanitised()); $this->transCamel2Studly->transform($this->getRemoteTableSanitised());
} }
public function getLocalBoundColumnGetter(): string public function getLocalBoundColumnGetter(): string
{ {
return 'get'.$this->transCamel2Studly->transform($this->getLocalBoundColumn()); return 'get' . $this->transCamel2Studly->transform($this->getLocalBoundColumn());
} }
public function getRemoteBoundColumnGetter(): string public function getRemoteBoundColumnGetter(): string
{ {
return 'get'.$this->transCamel2Studly->transform($this->getRemoteBoundColumn()); return 'get' . $this->transCamel2Studly->transform($this->getRemoteBoundColumn());
} }
public function getLocalBoundColumnSetter(): string public function getLocalBoundColumnSetter(): string
{ {
return 'set'.$this->transCamel2Studly->transform($this->getLocalBoundColumn()); return 'set' . $this->transCamel2Studly->transform($this->getLocalBoundColumn());
} }
public function getRemoteBoundColumnSetter(): string public function getRemoteBoundColumnSetter(): string
{ {
return 'set'.$this->transCamel2Studly->transform($this->getRemoteBoundColumn()); return 'set' . $this->transCamel2Studly->transform($this->getRemoteBoundColumn());
} }
public function getRemoteBoundColumn(): string public function getRemoteBoundColumn(): string
@ -269,7 +270,7 @@ class RelatedModel extends Entity
public function getRemoteBoundColumnAsConstant(): string public function getRemoteBoundColumnAsConstant(): string
{ {
return 'FIELD_'.str_replace('_', '', $this->transCamel2ScreamingSnake->transform($this->getRemoteBoundColumn())); return 'FIELD_' . str_replace('_', '', $this->transCamel2ScreamingSnake->transform($this->getRemoteBoundColumn()));
} }
public function setRemoteBoundColumn(string $remoteBoundColumn): RelatedModel public function setRemoteBoundColumn(string $remoteBoundColumn): RelatedModel
@ -345,7 +346,7 @@ class RelatedModel extends Entity
*/ */
private function singulariseCamelCaseSentence(string $camel): string private function singulariseCamelCaseSentence(string $camel): string
{ {
$snake = explode('_', $this->transCamel2Snake->transform($camel)); $snake = explode('_', $this->transCamel2Snake->transform($camel));
$snake[count($snake) - 1] = Inflect::singularize($snake[count($snake) - 1]); $snake[count($snake) - 1] = Inflect::singularize($snake[count($snake) - 1]);
return $this->transSnake2Camel->transform(implode('_', $snake)); return $this->transSnake2Camel->transform(implode('_', $snake));

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Connection; namespace Benzine\ORM\Connection;
use Benzine\ORM\Tests\App; use Benzine\ORM\Tests\App;
@ -16,7 +18,7 @@ class Database
private string $username; private string $username;
private string $password; private string $password;
private string $database; private string $database;
private string $charset = 'utf8mb4'; private string $charset = 'utf8mb4';
private array $ignoredTables = []; private array $ignoredTables = [];
/** @var callable[] */ /** @var callable[] */
@ -26,8 +28,8 @@ class Database
public function __construct( public function __construct(
private Logger $logger, private Logger $logger,
string $name = null, ?string $name = null,
array $config = null ?array $config = null
) { ) {
if ($name) { if ($name) {
$this->setName($name); $this->setName($name);
@ -163,19 +165,11 @@ class Database
return new Metadata($this->getAdapter()); return new Metadata($this->getAdapter());
} }
/**
* @return array
*/
public function getIgnoredTables(): array public function getIgnoredTables(): array
{ {
return $this->ignoredTables; return $this->ignoredTables;
} }
/**
* @param array $ignoredTables
*
* @return Database
*/
public function setIgnoredTables(array $ignoredTables): Database public function setIgnoredTables(array $ignoredTables): Database
{ {
$this->ignoredTables = $ignoredTables; $this->ignoredTables = $ignoredTables;
@ -186,14 +180,14 @@ class Database
public function getArray(): array public function getArray(): array
{ {
return [ return [
'driver' => 'pdo', 'driver' => 'pdo',
'pdodriver' => $this->getType(), 'pdodriver' => $this->getType(),
'type' => $this->getType(), 'type' => $this->getType(),
'charset' => $this->getCharset(), 'charset' => $this->getCharset(),
'host' => $this->getHostname(), 'host' => $this->getHostname(),
'username' => $this->getUsername(), 'username' => $this->getUsername(),
'password' => $this->getPassword(), 'password' => $this->getPassword(),
'database' => $this->getDatabase(), 'database' => $this->getDatabase(),
]; ];
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Connection; namespace Benzine\ORM\Connection;
use Benzine\Exceptions\BenzineException; use Benzine\Exceptions\BenzineException;
@ -20,7 +22,7 @@ class Databases
Logger $logger Logger $logger
) { ) {
$this->configurationService = $configurationService; $this->configurationService = $configurationService;
$this->logger = $logger; $this->logger = $logger;
foreach ($this->configurationService->get('databases') as $name => $config) { foreach ($this->configurationService->get('databases') as $name => $config) {
if (!isset(self::$databases[$name])) { if (!isset(self::$databases[$name])) {

View file

@ -1,7 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Entities; namespace Benzine\ORM\Entities;
abstract class AbstractEntity abstract class AbstractEntity {}
{
}

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Entities; namespace Benzine\ORM\Entities;
class Column extends AbstractEntity class Column extends AbstractEntity

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Entities; namespace Benzine\ORM\Entities;
class Table extends AbstractEntity class Table extends AbstractEntity
@ -13,8 +15,6 @@ class Table extends AbstractEntity
} }
/** /**
* @param mixed $tableName
*
* @return Table * @return Table
*/ */
public function setTableName($tableName) public function setTableName($tableName)

View file

@ -1,9 +1,9 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Exception; namespace Benzine\ORM\Exception;
use Benzine\Exceptions\BenzineException; use Benzine\Exceptions\BenzineException;
class BenzineOrmException extends BenzineException class BenzineOrmException extends BenzineException {}
{
}

View file

@ -1,7 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Exception; namespace Benzine\ORM\Exception;
class CollectionException extends BenzineOrmException class CollectionException extends BenzineOrmException {}
{
}

View file

@ -1,7 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Exception; namespace Benzine\ORM\Exception;
class DBTypeNotTranslatedException extends BenzineOrmException class DBTypeNotTranslatedException extends BenzineOrmException {}
{
}

View file

@ -1,7 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Exception; namespace Benzine\ORM\Exception;
class SchemaToAdaptorException extends BenzineOrmException class SchemaToAdaptorException extends BenzineOrmException {}
{
}

View file

@ -1,10 +1,13 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM; namespace Benzine\ORM;
use Benzine\ORM\Exception\BenzineOrmException; use Benzine\ORM\Exception\BenzineOrmException;
use Laminas\Db\Sql\Where;
class Finder extends \Laminas\Db\Sql\Where class Finder extends Where
{ {
public function __construct( public function __construct(
?array $predicates = null, ?array $predicates = null,
@ -65,11 +68,6 @@ class Finder extends \Laminas\Db\Sql\Where
return $this; return $this;
} }
/**
* @param string $orderDirection
*
* @return Finder
*/
public function orderDirection(string $orderDirection): Finder public function orderDirection(string $orderDirection): Finder
{ {
if (!in_array($orderDirection, ['desc', 'asc'], true)) { if (!in_array($orderDirection, ['desc', 'asc'], true)) {

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Interfaces; namespace Benzine\ORM\Interfaces;
use Laminas\Db\ResultSet\ResultSet; use Laminas\Db\ResultSet\ResultSet;

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Interfaces; namespace Benzine\ORM\Interfaces;
interface ModelInterface interface ModelInterface

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Interfaces; namespace Benzine\ORM\Interfaces;
interface QueryStatisticInterface interface QueryStatisticInterface

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Interfaces; namespace Benzine\ORM\Interfaces;
use Laminas\Db\Sql\Expression; use Laminas\Db\Sql\Expression;
@ -12,11 +14,11 @@ interface ServiceInterface
* @return ModelInterface[] * @return ModelInterface[]
*/ */
public function getAll( public function getAll(
int $limit = null, ?int $limit = null,
int $offset = null, ?int $offset = null,
array $wheres = null, ?array $wheres = null,
$order = null, $order = null,
string $orderDirection = null ?string $orderDirection = null
); );
public function getByField(string $field, $value); public function getByField(string $field, $value);

View file

@ -1,7 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Interfaces; namespace Benzine\ORM\Interfaces;
interface TableGatewayInterface extends \Laminas\Db\TableGateway\TableGatewayInterface interface TableGatewayInterface extends \Laminas\Db\TableGateway\TableGatewayInterface {}
{
}

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM; namespace Benzine\ORM;
use Benzine\App; use Benzine\App;
@ -23,6 +25,10 @@ use Twig\Error\LoaderError;
use Twig\Error\RuntimeError; use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError; use Twig\Error\SyntaxError;
use Twig\Loader\FilesystemLoader as TwigFileSystemLoader; use Twig\Loader\FilesystemLoader as TwigFileSystemLoader;
use Twig\Environment;
use Twig\Extension\DebugExtension;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;
class Laminator class Laminator
{ {
@ -35,11 +41,11 @@ class Laminator
public CaseTransformer $transCamel2Snake; public CaseTransformer $transCamel2Snake;
private string $workPath; private string $workPath;
private static ConfigurationService $benzineConfig; private static ConfigurationService $benzineConfig;
private array $config = [ private array $config = [
'templates' => [], 'templates' => [],
'formatting' => [], 'formatting' => [],
'sql' => [], 'sql' => [],
'clean' => [], 'clean' => [],
]; ];
private static bool $useClassPrefixes = false; private static bool $useClassPrefixes = false;
private TwigFileSystemLoader $loader; private TwigFileSystemLoader $loader;
@ -49,20 +55,20 @@ class Laminator
private bool $waitForKeypressEnabled = true; private bool $waitForKeypressEnabled = true;
private array $defaultEnvironment = []; private array $defaultEnvironment = [];
private array $defaultHeaders = []; private array $defaultHeaders = [];
private int $expectedFileOwner; private int $expectedFileOwner;
private int $expectedFileGroup; private int $expectedFileGroup;
private int $expectedPermissions; private int $expectedPermissions;
public function __construct(string $workPath, ConfigurationService $benzineConfig, Databases $databases) public function __construct(string $workPath, ConfigurationService $benzineConfig, Databases $databases)
{ {
$this->workPath = $workPath; $this->workPath = $workPath;
self::$benzineConfig = $benzineConfig; self::$benzineConfig = $benzineConfig;
$this->databases = $databases; $this->databases = $databases;
$script = realpath($_SERVER['SCRIPT_FILENAME']); $script = realpath($_SERVER['SCRIPT_FILENAME']);
$this->expectedFileOwner = fileowner($script); $this->expectedFileOwner = fileowner($script);
$this->expectedFileGroup = filegroup($script); $this->expectedFileGroup = filegroup($script);
$this->expectedPermissions = fileperms($script); $this->expectedPermissions = fileperms($script);
set_exception_handler([$this, 'exceptionHandler']); set_exception_handler([$this, 'exceptionHandler']);
@ -70,7 +76,7 @@ class Laminator
$this->defaultEnvironment = [ $this->defaultEnvironment = [
'SCRIPT_NAME' => '/index.php', 'SCRIPT_NAME' => '/index.php',
'RAND' => rand(0, 100000000), 'RAND' => random_int(0, 100000000),
]; ];
$this->defaultHeaders = []; $this->defaultHeaders = [];
} }
@ -88,9 +94,9 @@ class Laminator
$this->setWorkPath(self::$benzineConfig->get(ConfigurationService::KEY_APP_ROOT)); $this->setWorkPath(self::$benzineConfig->get(ConfigurationService::KEY_APP_ROOT));
} }
$this->loader = new \Twig\Loader\FilesystemLoader(__DIR__.'/Generator/Templates'); $this->loader = new FilesystemLoader(__DIR__ . '/Generator/Templates');
$this->twig = new \Twig\Environment($this->loader, ['debug' => true]); $this->twig = new Environment($this->loader, ['debug' => true]);
$this->twig->addExtension(new \Twig\Extension\DebugExtension()); $this->twig->addExtension(new DebugExtension());
$this->twig->addExtension(new TransformExtension()); $this->twig->addExtension(new TransformExtension());
$this->twig->addExtension(new InflectionExtension()); $this->twig->addExtension(new InflectionExtension());
@ -98,16 +104,16 @@ class Laminator
new ArrayUniqueTwigExtension() new ArrayUniqueTwigExtension()
); );
$fct = new \Twig\TwigFunction('var_export', 'var_export'); $fct = new TwigFunction('var_export', 'var_export');
$this->twig->addFunction($fct); $this->twig->addFunction($fct);
$this->transSnake2Studly = new CaseTransformer(new Format\SnakeCase(), new Format\StudlyCaps()); $this->transSnake2Studly = new CaseTransformer(new Format\SnakeCase(), new Format\StudlyCaps());
$this->transStudly2Camel = new CaseTransformer(new Format\StudlyCaps(), new Format\CamelCase()); $this->transStudly2Camel = new CaseTransformer(new Format\StudlyCaps(), new Format\CamelCase());
$this->transStudly2Studly = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps()); $this->transStudly2Studly = new CaseTransformer(new Format\StudlyCaps(), new Format\StudlyCaps());
$this->transCamel2Studly = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps()); $this->transCamel2Studly = new CaseTransformer(new Format\CamelCase(), new Format\StudlyCaps());
$this->transSnake2Camel = new CaseTransformer(new Format\SnakeCase(), new Format\CamelCase()); $this->transSnake2Camel = new CaseTransformer(new Format\SnakeCase(), new Format\CamelCase());
$this->transSnake2Spinal = new CaseTransformer(new Format\SnakeCase(), new Format\SpinalCase()); $this->transSnake2Spinal = new CaseTransformer(new Format\SnakeCase(), new Format\SpinalCase());
$this->transCamel2Snake = new CaseTransformer(new Format\CamelCase(), new Format\SnakeCase()); $this->transCamel2Snake = new CaseTransformer(new Format\CamelCase(), new Format\SnakeCase());
return $this; return $this;
} }
@ -138,12 +144,12 @@ class Laminator
{ {
// UHOH exception handler // UHOH exception handler
/** @var \Exception $exception */ /** @var \Exception $exception */
echo "\n".ConsoleHelper::COLOR_RED; echo "\n" . ConsoleHelper::COLOR_RED;
echo " ____ ____ ____ ____ \n"; echo " ____ ____ ____ ____ \n";
echo "||U |||H |||O |||H ||\n"; echo "||U |||H |||O |||H ||\n";
echo "||__|||__|||__|||__||\n"; echo "||__|||__|||__|||__||\n";
echo "|/__\\|/__\\|/__\\|/__\\|\n"; echo "|/__\\|/__\\|/__\\|/__\\|\n";
echo ConsoleHelper::COLOR_RESET."\n\n"; echo ConsoleHelper::COLOR_RESET . "\n\n";
echo $exception->getMessage(); echo $exception->getMessage();
echo "\n\n"; echo "\n\n";
echo "In {$exception->getFile()}:{$exception->getLine()}"; echo "In {$exception->getFile()}:{$exception->getLine()}";
@ -171,11 +177,9 @@ class Laminator
} }
/** /**
* @param $schemaName * @return int|string
* *
* @throws SchemaToAdaptorException * @throws SchemaToAdaptorException
*
* @return int|string
*/ */
public function schemaName2databaseName($schemaName) public function schemaName2databaseName($schemaName)
{ {
@ -228,8 +232,8 @@ class Laminator
{ {
switch ($database->getAdapter()->getDriver()->getDatabasePlatformName()) { switch ($database->getAdapter()->getDriver()->getDatabasePlatformName()) {
case 'Mysql': case 'Mysql':
$sql = "SHOW columns FROM `{$table}` WHERE extra LIKE '%auto_increment%'"; $sql = "SHOW columns FROM `{$table}` WHERE extra LIKE '%auto_increment%'";
$query = $database->getAdapter()->query($sql); $query = $database->getAdapter()->query($sql);
$columns = []; $columns = [];
foreach ($query->execute() as $aiColumn) { foreach ($query->execute() as $aiColumn) {
@ -239,8 +243,8 @@ class Laminator
return $columns; return $columns;
case 'Postgresql': case 'Postgresql':
$sql = "SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$table}' AND column_default LIKE 'nextval(%'"; $sql = "SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$table}' AND column_default LIKE 'nextval(%'";
$query = $database->getAdapter()->query($sql); $query = $database->getAdapter()->query($sql);
$columns = []; $columns = [];
foreach ($query->execute() as $aiColumn) { foreach ($query->execute() as $aiColumn) {
@ -255,11 +259,11 @@ class Laminator
} }
/** /**
* @return $this
*
* @throws LoaderError * @throws LoaderError
* @throws RuntimeError * @throws RuntimeError
* @throws SyntaxError * @throws SyntaxError
*
* @return $this
*/ */
public function makeLaminator() public function makeLaminator()
{ {
@ -280,7 +284,7 @@ class Laminator
{ {
/** @var Model[] $models */ /** @var Model[] $models */
$models = []; $models = [];
$keys = []; $keys = [];
foreach ($this->databases->getAll() as $dbName => $database) { foreach ($this->databases->getAll() as $dbName => $database) {
/** @var Database $database */ /** @var Database $database */
echo "Database: {$dbName}\n"; echo "Database: {$dbName}\n";
@ -288,13 +292,13 @@ class Laminator
/** @var TableObject $tables */ /** @var TableObject $tables */
$tables = $database->getMetadata()->getTables(); $tables = $database->getMetadata()->getTables();
echo 'Collecting '.count($tables)." entities data.\n"; echo 'Collecting ' . count($tables) . " entities data.\n";
foreach ($tables as $table) { foreach ($tables as $table) {
if (in_array($table->getName(), $database->getIgnoredTables(), true)) { if (in_array($table->getName(), $database->getIgnoredTables(), true)) {
continue; continue;
} }
$oModel = Components\Model::Factory($this) $oModel = Model::Factory($this)
->setClassPrefix(self::$benzineConfig->get("databases/{$dbName}/class_prefix", null)) ->setClassPrefix(self::$benzineConfig->get("databases/{$dbName}/class_prefix", null))
->setNamespace(self::$benzineConfig->getNamespace()) ->setNamespace(self::$benzineConfig->getNamespace())
->setDatabase($database) ->setDatabase($database)
@ -304,8 +308,8 @@ class Laminator
if (self::$benzineConfig->has("databases/{$dbName}/class_prefix")) { if (self::$benzineConfig->has("databases/{$dbName}/class_prefix")) {
$oModel->setClassPrefix(self::$benzineConfig->get("databases/{$dbName}/class_prefix")); $oModel->setClassPrefix(self::$benzineConfig->get("databases/{$dbName}/class_prefix"));
} }
$models[$oModel->getClassName()] = $oModel; $models[$oModel->getClassName()] = $oModel;
$keys[$database->getAdapter()->getCurrentSchema().'::'.$table->getName()] = $oModel->getClassName(); $keys[$database->getAdapter()->getCurrentSchema() . '::' . $table->getName()] = $oModel->getClassName();
} }
} }
ksort($models); ksort($models);
@ -317,7 +321,7 @@ class Laminator
if (in_array($table->getName(), $database->getIgnoredTables(), true)) { if (in_array($table->getName(), $database->getIgnoredTables(), true)) {
continue; continue;
} }
$key = $keys[$database->getAdapter()->getCurrentSchema().'::'.$table->getName()]; $key = $keys[$database->getAdapter()->getCurrentSchema() . '::' . $table->getName()];
$models[$key] $models[$key]
->computeColumns($table->getColumns()) ->computeColumns($table->getColumns())
->computeConstraints($models, $keys, $table->getConstraints()) ->computeConstraints($models, $keys, $table->getConstraints())
@ -391,15 +395,15 @@ class Laminator
/** /**
* @param Model[] $models * @param Model[] $models
* *
* @return Laminator
*
* @throws LoaderError When the template cannot be found * @throws LoaderError When the template cannot be found
* @throws SyntaxError When an error occurred during compilation * @throws SyntaxError When an error occurred during compilation
* @throws RuntimeError When an error occurred during rendering * @throws RuntimeError When an error occurred during rendering
*
* @return Laminator
*/ */
private function makeCoreFiles(array $models) private function makeCoreFiles(array $models)
{ {
echo 'Generating Core files for '.count($models)." models... \n"; echo 'Generating Core files for ' . count($models) . " models... \n";
$allModelData = []; $allModelData = [];
foreach ($models as $model) { foreach ($models as $model) {
$allModelData[$model->getClassName()] = $model->getRenderDataset(); $allModelData[$model->getClassName()] = $model->getRenderDataset();
@ -447,10 +451,10 @@ class Laminator
private function renderToFile(bool $overwrite, string $path, string $template, array $data) private function renderToFile(bool $overwrite, string $path, string $template, array $data)
{ {
$output = $this->twig->render($template, $data); $output = $this->twig->render($template, $data);
$path = $this->getWorkPath().'/'.$path; $path = $this->getWorkPath() . '/' . $path;
if (!(new Filesystem())->exists(dirname($path))) { if (!(new Filesystem())->exists(dirname($path))) {
(new Filesystem())->mkdir(dirname($path), 0777); (new Filesystem())->mkdir(dirname($path), 0o777);
} }
if (!(new Filesystem())->exists($path) || $overwrite) { if (!(new Filesystem())->exists($path) || $overwrite) {
// printf(" [Done]" . PHP_EOL); // printf(" [Done]" . PHP_EOL);

View file

@ -1,10 +1,13 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM; namespace Benzine\ORM;
use Laminas\Db\Adapter\AdapterInterface; use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Db\Sql\Sql;
class LaminatorSql extends \Laminas\Db\Sql\Sql class LaminatorSql extends Sql
{ {
public function __construct(AdapterInterface $adapter, $table = null, $sqlPlatform = null) public function __construct(AdapterInterface $adapter, $table = null, $sqlPlatform = null)
{ {

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Migrations; namespace Benzine\ORM\Migrations;
abstract class AbstractMigration extends \Phinx\Migration\AbstractMigration abstract class AbstractMigration extends \Phinx\Migration\AbstractMigration
@ -10,7 +12,7 @@ abstract class AbstractMigration extends \Phinx\Migration\AbstractMigration
]; ];
protected array $enumYesNoOptions = [ protected array $enumYesNoOptions = [
'values' => ['Yes', 'No'], 'values' => ['Yes', 'No'],
'default' => 'No', 'default' => 'No',
]; ];
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Migrations; namespace Benzine\ORM\Migrations;
use Benzine\ORM\Tests\App; use Benzine\ORM\Tests\App;
@ -14,6 +16,6 @@ abstract class AbstractSeed extends \Phinx\Seed\AbstractSeed
public function __construct() public function __construct()
{ {
$this->faker = App::Instance()->get(Generator::class); $this->faker = App::Instance()->get(Generator::class);
$this->log = App::Instance()->get(Logger::class); $this->log = App::Instance()->get(Logger::class);
} }
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Profiler; namespace Benzine\ORM\Profiler;
use Benzine\ORM\Interfaces\QueryStatisticInterface; use Benzine\ORM\Interfaces\QueryStatisticInterface;
@ -12,19 +14,17 @@ class Profiler implements ProfilerInterface
{ {
private ?float $timer; private ?float $timer;
private ?string $sql; private ?string $sql;
private array $queries = []; private array $queries = [];
private array $queryTimes = []; private array $queryTimes = [];
public function __construct(private Logger $logger) public function __construct(private Logger $logger) {}
{
}
public function getQueryStats(QueryStatisticInterface $queryStatisticClass = null): array public function getQueryStats(?QueryStatisticInterface $queryStatisticClass = null): array
{ {
return [ return [
'TotalQueries' => count($this->queryTimes), 'TotalQueries' => count($this->queryTimes),
'TotalTime' => array_sum($this->queryTimes), 'TotalTime' => array_sum($this->queryTimes),
'Diagnostic' => $this->getQueries($queryStatisticClass), 'Diagnostic' => $this->getQueries($queryStatisticClass),
]; ];
} }
@ -47,25 +47,25 @@ class Profiler implements ProfilerInterface
public function profilerFinish(): void public function profilerFinish(): void
{ {
$uuid = UUID::v4(); $uuid = UUID::v4();
$executionTime = microtime(true) - $this->timer; $executionTime = microtime(true) - $this->timer;
// $this->logger->addDebug("Query \"{$this->sql}\" took {$executionTime} sec"); // $this->logger->addDebug("Query \"{$this->sql}\" took {$executionTime} sec");
$this->queryTimes[$uuid] = $executionTime; $this->queryTimes[$uuid] = $executionTime;
$this->queries[$uuid] = [$this->sql, debug_backtrace()]; $this->queries[$uuid] = [$this->sql, debug_backtrace()];
$this->sql = null; $this->sql = null;
$this->timer = null; $this->timer = null;
} }
/** /**
* @return QueryStatisticInterface[] * @return QueryStatisticInterface[]
*/ */
public function getQueries(QueryStatisticInterface $queryStatisticClass = null): array public function getQueries(?QueryStatisticInterface $queryStatisticClass = null): array
{ {
$stats = []; $stats = [];
foreach ($this->queries as $uuid => [$query, $backTrace]) { foreach ($this->queries as $uuid => [$query, $backTrace]) {
if ($queryStatisticClass) { if ($queryStatisticClass) {
if (is_object($queryStatisticClass)) { if (is_object($queryStatisticClass)) {
$queryStatisticClass = get_class($queryStatisticClass); $queryStatisticClass = $queryStatisticClass::class;
} }
$stat = new $queryStatisticClass(); $stat = new $queryStatisticClass();
} else { } else {

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\Profiler; namespace Benzine\ORM\Profiler;
use Benzine\ORM\Interfaces\QueryStatisticInterface; use Benzine\ORM\Interfaces\QueryStatisticInterface;
@ -13,7 +15,7 @@ class QueryStatistic implements QueryStatisticInterface
public function __toArray(): array public function __toArray(): array
{ {
return [ return [
'Time' => number_format($this->getTime() * 1000, 3).'ms', 'Time' => number_format($this->getTime() * 1000, 3) . 'ms',
'Query' => $this->getSql(), 'Query' => $this->getSql(),
]; ];
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\TabularData; namespace Benzine\ORM\TabularData;
use Benzine\ORM\Abstracts\AbstractService; use Benzine\ORM\Abstracts\AbstractService;
@ -10,16 +12,16 @@ class Table
protected AbstractService $service; protected AbstractService $service;
protected array $data; protected array $data;
protected string $name; protected string $name;
protected int $page = 0; protected int $page = 0;
protected int $perPage = 25; protected int $perPage = 25;
protected array $colums = []; protected array $colums = [];
protected array $rows = []; protected array $rows = [];
public function __construct(AbstractService $service) public function __construct(AbstractService $service)
{ {
$this->service = $service; $this->service = $service;
$this->setName(get_class($service)); $this->setName($service::class);
$this->reload(); $this->reload();
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM\TabularData; namespace Benzine\ORM\TabularData;
use Benzine\ORM\Abstracts\AbstractModel; use Benzine\ORM\Abstracts\AbstractModel;
@ -22,7 +24,7 @@ class TableRow
$service = $options['service']; $service = $options['service'];
/** @var AbstractModel $relatedEntity */ /** @var AbstractModel $relatedEntity */
$relatedEntity = $service->getByField($field, $this->data[$field]); $relatedEntity = $service->getByField($field, $this->data[$field]);
$this->related[$field] = $relatedEntity; $this->related[$field] = $relatedEntity;
} }
} }

View file

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types=1);
namespace Benzine\ORM; namespace Benzine\ORM;
use Benzine\App; use Benzine\App;