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
$finder = PhpCsFixer\Finder::create();
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)
;
return require("vendor/benzine/core/.php-cs-fixer.php");

View file

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

View file

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

View file

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

View file

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

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace Benzine\ORM;
use Benzine\ORM\Profiler\Profiler as BenzineProfiler;
@ -10,7 +12,7 @@ use Laminas\Db\ResultSet;
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);
// if (!defined('ZEND_PROFILER_DISABLE') || ZEND_PROFILER_DISABLE == false) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,10 +1,13 @@
<?php
declare(strict_types=1);
namespace Benzine\ORM;
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)
{

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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