Skip to content

Commit

Permalink
Merge pull request #16 from InitPHP/v2.1
Browse files Browse the repository at this point in the history
2.1
  • Loading branch information
muhammetsafak authored Mar 25, 2023
2 parents 4ae07cc + c37622c commit a257936
Show file tree
Hide file tree
Showing 7 changed files with 95 additions and 61 deletions.
13 changes: 0 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,19 +262,6 @@ namespace App\Model;
class Posts extends \InitPHP\Database\Model
{

/**
* Only if you don't have global connectivity.
*
* @var array|string[]
*/
protected array $connection = [
'dsn' => '', // Database connection address.
'username' => '', // Username with required privileges in the database.
'password' => '', // The password of the database user.
'charset' => 'utf8mb4', // The character set to use in the database.
'collation' => 'utf8mb4_general_ci', // Collection set to use in database
];

/**
* If not specified, \InitPHP\Database\Entity::class is used by default.
*
Expand Down
27 changes: 2 additions & 25 deletions src/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @author Muhammet ŞAFAK <[email protected]>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 2.0.7
* @version 2.1
* @link https://www.muhammetsafak.com.tr
*/

Expand Down Expand Up @@ -295,29 +295,6 @@ final public function escape_str($value)
return false;
}

/**
* @param string $key
* @param string|int|float|bool|null $value
* @return $this
*/
final public function setParameter(string $key, $value): self
{
Parameters::set($key, $value);
return $this;
}

/**
* @param array $parameters
* @return $this
*/
final public function setParameters(array $parameters = []): self
{
foreach ($parameters as $key => $value) {
Parameters::set($key, $value);
}
return $this;
}

/**
* @param string $sqlQuery
* @param array $parameters
Expand Down Expand Up @@ -358,7 +335,7 @@ final public function query(string $sqlQuery, array $parameters = []): Result
case self::ARRAY:
return $this->_last->asArray();
case self::ENTITY:
return $this->_last->asEntity();
return $this->_last->asEntity($this->_credentials['entity'] ?? Entity::class);
case self::OBJECT:
return $this->_last->asObject();
case self::LAZY:
Expand Down
24 changes: 12 additions & 12 deletions src/Entity.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
class Entity
{

private array $_Attributes = [];
protected array $__attributes = [];

private array $_OriginalAttributes = [];
protected array $__attributesOriginal = [];

public function __construct(?array $data = [])
{
Expand All @@ -35,10 +35,10 @@ public function __call($name, $arguments)
switch (\substr($name, 0, 3)) {
case 'get':
$attr = Helper::camelCaseToSnakeCase(\substr($name, 3, -9));
return $this->_Attributes[$attr] ?? null;
return $this->__attributes[$attr] ?? null;
case 'set':
$attr = Helper::camelCaseToSnakeCase(\substr($name, 3, -9));
return $this->_Attributes[$attr] = $arguments[0];
return $this->__attributes[$attr] = $arguments[0];
default:
throw new \RuntimeException('There is no "' . $name . '" method.');
}
Expand All @@ -51,7 +51,7 @@ public function __set($name, $value)
$this->{$methodName}($value);
return $value;
}
return $this->_Attributes[$name] = $value;
return $this->__attributes[$name] = $value;
}

public function __get($name)
Expand All @@ -60,29 +60,29 @@ public function __get($name)
if(\method_exists($this, $methodName)){
return $this->{$methodName}();
}
return $this->_Attributes[$name] ?? null;
return $this->__attributes[$name] ?? null;
}

public function __isset($name)
{
return isset($this->_Attributes[$name]);
return isset($this->__attributes[$name]);
}

public function __unset($name)
{
if(isset($this->_Attributes[$name])){
unset($this->_Attributes[$name]);
if(isset($this->__attributes[$name])){
unset($this->__attributes[$name]);
}
}

public function __debugInfo()
{
return $this->_Attributes;
return $this->__attributes;
}

public function toArray(): array
{
return $this->_Attributes;
return $this->__attributes;
}

public function getAttributes(): array
Expand All @@ -109,7 +109,7 @@ protected function fill(?array $data = null): self

protected function syncOriginal(): self
{
$this->_OriginalAttributes = $this->_Attributes;
$this->__attributesOriginal = $this->__attributes;
return $this;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Helpers/Helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @author Muhammet ŞAFAK <[email protected]>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 2.0.8
* @version 2.1
* @link https://www.muhammetsafak.com.tr
*/

Expand Down Expand Up @@ -59,7 +59,7 @@ public static function isSQLParameterOrFunction($value): bool
return ((\is_string($value)) && (
$value === '?'
|| (bool)\preg_match('/^:[\w]+$/', $value)
|| (bool)\preg_match('/^[a-zA-Z_\.]+$/', $value)
|| (bool)\preg_match('/^[a-zA-Z_]+[\.]+[a-zA-Z_]+$/', $value)
|| (bool)\preg_match('/^[a-zA-Z_]+\(\)$/', $value)
)) || ($value instanceof Raw) || \is_int($value);
}
Expand Down
4 changes: 3 additions & 1 deletion src/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@
* @author Muhammet ŞAFAK <[email protected]>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 2.0.8
* @version 2.1
* @link https://www.muhammetsafak.com.tr
*/
declare(strict_types=1);

namespace InitPHP\Database;

Expand Down Expand Up @@ -226,6 +227,7 @@ public function __construct()
$credentials['updatable'] = $this->updatable ?? true;
$credentials['deletable'] = $this->deletable ?? true;
$credentials['writable'] = $this->writable ?? true;
$credentials['return'] = $this->return ?? self::ENTITY;
parent::__construct($credentials);
}

Expand Down
55 changes: 47 additions & 8 deletions src/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@
* @author Muhammet ŞAFAK <[email protected]>
* @copyright Copyright © 2022 Muhammet ŞAFAK
* @license ./LICENSE MIT
* @version 2.0.8
* @version 2.1
* @link https://www.muhammetsafak.com.tr
*/
declare(strict_types=1);

namespace InitPHP\Database;

use InitPHP\Database\Helpers\{Helper, Parameters, Validation};
use InitPHP\Database\Exceptions\QueryBuilderException;
use InitPHP\Database\Exceptions\QueryGeneratorException;
use \InitPHP\Database\Exceptions\ValueException;
use \InitPHP\Database\Helpers\{Helper, Parameters};
use \InitPHP\Database\Exceptions\{QueryBuilderException, QueryGeneratorException, ValueException};

class QueryBuilder
{
Expand Down Expand Up @@ -65,6 +64,29 @@ public function exportQB(): array
return $this->_STRUCTURE;
}

/**
* @param string $key
* @param string|int|float|bool|null $value
* @return $this
*/
final public function setParameter(string $key, $value): self
{
Parameters::set($key, $value);
return $this;
}

/**
* @param array $parameters
* @return $this
*/
final public function setParameters(array $parameters = []): self
{
foreach ($parameters as $key => $value) {
Parameters::set($key, $value);
}
return $this;
}

/**
* @param string|Raw ...$columns
* @return $this
Expand Down Expand Up @@ -368,7 +390,7 @@ final public function join($table, $onStmt = null, string $type = 'INNER'): self
$this->_STRUCTURE['join'][$table] = 'NATURAL JOIN ' . $table;
break;
default:
$this->_STRUCTURE['join'][$table] = $type . ' JOIN ' . $table . ' ON ' . $onStmt;
$this->_STRUCTURE['join'][$table] = \trim(($type . ' JOIN ' . $table . ' ON ' . $onStmt));
}
return $this;
}
Expand Down Expand Up @@ -1124,6 +1146,23 @@ final public function raw(string $rawQuery): Raw
return new Raw($rawQuery);
}

final public function subQuery(\Closure $closure, ?string $alias = null, bool $isIntervalQuery = true): Raw
{
$queryBuilder = new self();
\call_user_func_array($closure, [$queryBuilder]);

if ($alias !== null && $isIntervalQuery !== TRUE) {
throw new QueryBuilderException('To define alias to a subquery, it must be an inner query.');
}

$rawQuery = ($isIntervalQuery === TRUE ? '(' : '')
. $queryBuilder->generateSelectQuery()
. ($isIntervalQuery === TRUE ? ')' : '')
. ($alias !== null ? ' AS ' . $alias : '');

return $this->raw($rawQuery);
}

final public function generateInsertQuery(): string
{
if (!empty($this->_STRUCTURE['table'])) {
Expand Down Expand Up @@ -1533,15 +1572,15 @@ private function whereOrHavingStatementPrepare($column, $value, string $mark = '
}
$values[] = Helper::isSQLParameterOrFunction($val) ? $val : Parameters::add($column, $val);
}
$value = \implode(', ', \array_unique($values));
$value = '(' . \implode(', ', \array_unique($values)) . ')';
} elseif (Helper::isSQLParameterOrFunction($value)) {
$value = (string)$value;
}else{
throw new ValueException('An incorrect value was defined.');
}
return $column
. ($searchMark === 'NOTIN' ? ' NOT ' : ' ')
. 'IN (' . $value . ')';
. 'IN ' . $value;
case 'FINDINSET':
case 'NOTFINDINSET':
if(\is_array($value)){
Expand Down
29 changes: 29 additions & 0 deletions tests/QueryBuilderUnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -420,4 +420,33 @@ public function testJoinClosureGive()
$this->db->reset();
}

public function testSubQuery()
{
Parameters::reset();
$this->db->select('u.name')
->from('users AS u')
->in('u.id', $this->db->subQuery(function (QueryBuilder $builder) {
$builder->select('id')
->from('roles')
->where('name', 'admin');
}));
$expected = 'SELECT u.name FROM users AS u WHERE u.id IN (SELECT id FROM roles WHERE name = :name)';
$this->assertEquals($expected, $this->db->generateSelectQuery());
$this->db->reset();


Parameters::reset();
$this->db->select('u.name, p.title')
->from('users AS u')
->join($this->db->subQuery(function (QueryBuilder $builder) {
$builder->select('id, title, user_id')
->from('posts')
->where('user_id', 5);
}, 'p'), 'p.user_id = u.id', '');

$expected = 'SELECT u.name, p.title FROM users AS u JOIN (SELECT id, title, user_id FROM posts WHERE user_id = 5) AS p ON p.user_id = u.id WHERE 1';
$this->assertEquals($expected, $this->db->generateSelectQuery());
$this->db->reset();
}

}

0 comments on commit a257936

Please sign in to comment.