Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@
"autoload": {
"psr-4": {
"BlitzPHP\\Database\\": "src/"
}
},
"files": [
"src/Config/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
Expand Down
20 changes: 11 additions & 9 deletions src/Builder/BaseBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,14 @@ class BaseBuilder implements BuilderInterface
/**
* Les callbacks qui doivent être invoqués avant l'exécution de la requête.
*
* @var list<Closure($this): void>
* @var list<callable($this): void>
*/
protected array $beforeQueryCallbacks = [];

/**
* Les callbacks qui doivent être invoqués après la récupération des données de la base de données.
*
* @var list<Closure(mixed): mixed>
* @var list<callable(mixed): mixed>
*/
protected array $afterQueryCallbacks = [];

Expand Down Expand Up @@ -758,7 +758,9 @@ public function execute(): ResultInterface
$this->applyBeforeQueryCallbacks();

try {
return $this->query($this->toSql(), $this->getBindings());
$result = $this->query($this->toSql(), $this->getBindings());

return $this->applyAfterQueryCallbacks($result);
} finally {
$this->reset();
}
Expand Down Expand Up @@ -1031,7 +1033,7 @@ public function decrementEach(array $columns, array $extra = [])
/**
* Enregistre une closure à invoquer avant l'exécution de la requête.
*
* @param Closure($this): void $callback
* @param callable($this): void $callback
*/
public function beforeQuery(callable $callback): static
{
Expand All @@ -1046,7 +1048,7 @@ public function beforeQuery(callable $callback): static
public function applyBeforeQueryCallbacks(): void
{
foreach ($this->beforeQueryCallbacks as $callback) {
$callback($this);
call_user_func($callback, $this);
}

$this->beforeQueryCallbacks = [];
Expand All @@ -1055,9 +1057,9 @@ public function applyBeforeQueryCallbacks(): void
/**
* Enregistre une closure à invoquer après l'exécution de la requête.
*
* @param Closure(mixed): mixed $callback
* @param callable(mixed): mixed $callback
*/
public function afterQuery(Closure $callback): static
public function afterQuery(callable $callback): static
{
$this->afterQueryCallbacks[] = $callback;

Expand All @@ -1069,8 +1071,8 @@ public function afterQuery(Closure $callback): static
*/
public function applyAfterQueryCallbacks(mixed $result): mixed
{
foreach ($this->afterQueryCallbacks as $afterQueryCallback) {
$result = $afterQueryCallback($result) ?: $result;
foreach ($this->afterQueryCallbacks as $callback) {
$result = call_user_func($callback, $result) ?: $result;
}

return $result;
Expand Down
28 changes: 15 additions & 13 deletions src/Builder/Concerns/DataMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

use BlitzPHP\Contracts\Database\BuilderInterface;
use BlitzPHP\Database\Query\Expression;
use BlitzPHP\Database\Result\BaseResult;
use BlitzPHP\Database\Query\Result;
use Closure;

/**
Expand Down Expand Up @@ -146,33 +146,35 @@ public function insertUsing(array $columns, Closure|BuilderInterface $query)

$result = $this->execute();

return $result instanceof BaseResult ? $result->affectedRows() : 0;
return $result instanceof Result ? $result->affectedRows() : 0;
}

/**
* Insère et récupère l'ID généré
*
* @return int|static|string|null
*/
public function insertGetId(array $values, ?string $sequence = null): int|string|null
public function insertGetId(array $values, ?string $sequence = null)
{
$this->insert($values);
if (is_bool($inserted = $this->insert($values))) {
return $inserted === true ? $this->db->lastId($this->getTable()) : null;
}

return $this->db->lastId($this->getTable());
return $inserted;
}

/**
* Insère et récupère l'enregistrement inséré
*
* @return object|static|string|null
*/
public function insertAndGet(array $values): ?object
public function insertAndGet(array $values)
{
$this->insert($values);

$id = $this->db->lastId($this->getTable());

if ($id === null) {
return null;
if (is_int($id = $this->insertGetId($values))) {
return $this->clone()->where($this->getKeyName(), $id)->first();
}

return $this->clone()->where($this->getKeyName(), $id)->first();
return $id;
}

/**
Expand Down
71 changes: 71 additions & 0 deletions src/Config/helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

use BlitzPHP\Contracts\Database\ConnectionInterface;
use BlitzPHP\Database\Config\Services;
use BlitzPHP\Database\Connection\BaseConnection;
use BlitzPHP\Loader\Load;

/**
* This file is part of Blitz PHP framework - Schild.
*
* (c) 2023 Dimitri Sitchet Tomkeu <devcode.dst@gmail.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/



if (! function_exists('model')) {
/**
* Simple maniere d'obtenir un modele.
*
* @template TModel
*
* @param class-string<TModel>|list<class-string<TModel>> $name
*
* @return ($name is string ? TModel : list<TModel>)
*/
function model(array|string $name, ?ConnectionInterface &$conn = null)
{
return Load::model($name, $conn);
}
}


if (! function_exists('db')) {
/**
* Grabs a database connection and returns it to the user.
*
* This is a convenience wrapper for \BlitzPHP\Database\Config\Services::database()
* and supports the same parameters. Namely:
*
* When passing in $db, you may pass any of the following to connect:
* - group name
* - existing connection instance
* - array of database configuration values
*
* If $shared === false then a new connection instance will be provided,
* otherwise it will all calls will return the same instance.
*
* @param array{
* dsn?: string,
* driver?: 'mysql'|'postgre'|'sqlite',
* port?: int,
* hostname?: string,
* username?: string,
* password?: string,
* database?: string,
* prefix?: string,
* debug?: bool,
* charset?: string,
* collation?: string,
* }|ConnectionInterface|string|null $db
*
* @return BaseConnection
*/
function db($db = null, bool $shared = true): ConnectionInterface
{
return Services::dbManager()->connect($db, $shared);
}
}
5 changes: 5 additions & 0 deletions src/DatabaseManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ public function __construct(protected ?LoggerInterface $logger = null, protected
{
}

public function __destruct()
{
$this->closeAll();
}

/**
* {@inheritDoc}
*/
Expand Down
45 changes: 45 additions & 0 deletions src/Listeners/DatabaseListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@

namespace BlitzPHP\Database\Listeners;

use BlitzPHP\Contracts\Database\ConnectionInterface;
use BlitzPHP\Contracts\Database\ConnectionResolverInterface;
use BlitzPHP\Contracts\Event\EventInterface;
use BlitzPHP\Contracts\Event\EventListenerInterface;
use BlitzPHP\Contracts\Event\EventManagerInterface;
use BlitzPHP\Database\Collectors\DatabaseCollector;
use BlitzPHP\Exceptions\LoadException;
use BlitzPHP\Loader\FileLocator;
use BlitzPHP\Loader\Load;

class DatabaseListener implements EventListenerInterface
{
Expand All @@ -27,6 +31,7 @@ public function listen(EventManagerInterface $event): void

$event->on('app:init', function () {
$this->addInfoToAboutCommand();
$this->extendsFramework();
});
}

Expand Down Expand Up @@ -64,4 +69,44 @@ private function addInfoToAboutCommand()
},
]));
}

private function extendsFramework()
{
FileLocator::macro('model', function(string $model, ?ConnectionInterface $connection = null) {
if (! class_exists($model) && ! str_ends_with($model, 'Model')) {
$model .= 'Model';
}

if (! class_exists($model)) {
$model = str_replace(APP_NAMESPACE . '\\Models\\', '', $model);
$model = APP_NAMESPACE . '\\Models\\' . $model;
}

if (! class_exists($model)) {
throw LoadException::modelNotFound($model);
}

return service('container')->make($model, ['db' => $connection]);
});

Load::macro('model', function(array|string $model, ?ConnectionInterface $connection = null) {
if ($model === '' || $model === '0' || $model === []) {
throw new LoadException('Veuillez specifier le modele à charger');
}

$models = is_array($model) ? $model : [$model];
$results = [];

foreach ($models as $model) {
if (null === $result = self::getLoaded('models', $model)) {
$result = FileLocator::model($model, $connection);
self::loaded('models', $model, $result);
}

$results[] = $result;
}

return count($results) === 1 ? $results[0] : $results;
});
}
}
Loading