repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/UseLayout.php | src/Controller/Helper/UseLayout.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Helper;
use Bluz\Application\Application;
use Bluz\Controller\Controller;
use Bluz\Proxy\Layout;
/**
* Switch layout
*
* @param string $layout
*/
return
function (string $layout) {
/**
* @var Controller $this
*/
Application::getInstance()->useLayout(true);
Layout::setTemplate($layout);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Helper/CheckPrivilege.php | src/Controller/Helper/CheckPrivilege.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Helper;
use Bluz\Common\Exception\ComponentException;
use Bluz\Controller\ControllerException;
use Bluz\Http\Exception\ForbiddenException;
use Bluz\Controller\Controller;
use Bluz\Proxy\Acl;
use ReflectionException;
/**
* Denied helper can be declared inside Bootstrap
*
* @return void
* @throws ForbiddenException
* @throws ComponentException
* @throws ControllerException
* @throws ReflectionException
*/
return
function () {
/**
* @var Controller $this
*/
$privilege = $this->getMeta()->getPrivilege();
if ($privilege && !Acl::isAllowed($this->getModule(), $privilege)) {
throw new ForbiddenException();
}
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Mapper/Link.php | src/Controller/Mapper/Link.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Mapper;
/**
* Link
*
* @package Bluz\Controller\Mapper
* @author Anton Shevchuk
*/
class Link
{
/**
* @var string
*/
protected $module;
/**
* @var string
*/
protected $controller;
/**
* @var string
*/
protected $acl;
/**
* @var array
*/
protected $fields = [];
/**
* Constructor of Link
*
* @param string $module
* @param string $controller
*/
public function __construct(string $module, string $controller)
{
$this->setModule($module);
$this->setController($controller);
}
/**
* Set ACL privilege
*
* @param string $acl
*
* @return Link
*/
public function acl(string $acl): Link
{
$this->setAcl($acl);
return $this;
}
/**
* Set filters for data
*
* @param array $fields
*
* @return Link
*/
public function fields(array $fields): Link
{
$this->setFields($fields);
return $this;
}
/**
* @return string
*/
public function getModule(): ?string
{
return $this->module;
}
/**
* @param string $module
*/
protected function setModule(string $module): void
{
$this->module = $module;
}
/**
* @return string
*/
public function getController(): ?string
{
return $this->controller;
}
/**
* @param string $controller
*/
protected function setController(string $controller): void
{
$this->controller = $controller;
}
/**
* @return string|null
*/
public function getAcl(): ?string
{
return $this->acl;
}
/**
* @param string $acl
*/
protected function setAcl(string $acl): void
{
$this->acl = $acl;
}
/**
* @return array
*/
public function getFields(): array
{
return $this->fields;
}
/**
* Setup data filters
*
* @param array $fields
*/
protected function setFields(array $fields): void
{
$this->fields = $fields;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Mapper/Crud.php | src/Controller/Mapper/Crud.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Mapper;
/**
* Crud
*
* @package Bluz\Rest
* @author Anton Shevchuk
*/
class Crud extends AbstractMapper
{
protected function prepareParams(): array
{
return [
'crud' => $this->crud,
'primary' => $this->primary,
'data' => $this->data
];
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Mapper/Rest.php | src/Controller/Mapper/Rest.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Mapper;
use Bluz\Http\RequestMethod;
/**
* Rest
*
* @package Bluz\Rest
* @author Anton Shevchuk
*/
class Rest extends AbstractMapper
{
protected function prepareRequest(): void
{
parent::prepareRequest();
$params = $this->params;
if (count($params)) {
$primaryKeys = $this->crud->getPrimaryKey();
$primaryValues = explode('-', array_shift($params), count($primaryKeys));
$this->primary = array_combine($primaryKeys, $primaryValues);
}
if (count($params)) {
$this->relation = array_shift($params);
}
if (count($params)) {
$this->relationId = array_shift($params);
}
// OPTIONS
if (RequestMethod::OPTIONS === $this->method) {
$this->data = array_keys($this->map);
}
}
protected function prepareParams(): array
{
return [
'crud' => $this->crud,
'primary' => $this->primary,
'data' => $this->data,
'relation' => $this->relation,
'relationId' => $this->relationId
];
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Controller/Mapper/AbstractMapper.php | src/Controller/Mapper/AbstractMapper.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Controller\Mapper;
use Bluz\Application\Application;
use Bluz\Common\Exception\CommonException;
use Bluz\Common\Exception\ComponentException;
use Bluz\Controller\Controller;
use Bluz\Controller\ControllerException;
use Bluz\Crud\AbstractCrud;
use Bluz\Http\Exception\ForbiddenException;
use Bluz\Http\Exception\NotAcceptableException;
use Bluz\Http\Exception\NotAllowedException;
use Bluz\Http\Exception\NotImplementedException;
use Bluz\Http\RequestMethod;
use Bluz\Proxy\Acl;
use Bluz\Proxy\Request;
use Bluz\Proxy\Router;
use ReflectionException;
/**
* Mapper for controller
*
* @package Bluz\Rest
* @author Anton Shevchuk
*/
abstract class AbstractMapper
{
/**
* @var string HTTP Method
*/
protected $method = RequestMethod::GET;
/**
* @var string
*/
protected $module;
/**
* @var string
*/
protected $controller;
/**
* @var array identifier
*/
protected $primary;
/**
* @var string relation list
*/
protected $relation;
/**
* @var string relation Id
*/
protected $relationId;
/**
* @var array params of query
*/
protected $params = [];
/**
* @var array query data
*/
protected $data = [];
/**
* @var AbstractCrud instance of CRUD
*/
protected $crud;
/**
* [
* METHOD => Link {
* 'module' => 'module',
* 'controller' => 'controller',
* 'acl' => 'privilege',
* 'fields' => ['id', ... ]
* },
* ]
*
* @var Link[]
*/
protected $map = [];
/**
* Prepare params
*
* @return array
*/
abstract protected function prepareParams(): array;
/**
* @param AbstractCrud $crud
*/
public function __construct(AbstractCrud $crud)
{
$this->crud = $crud;
}
/**
* Add mapping data
*
* @param string $method
* @param string $module
* @param string $controller
*
* @return Link
*/
public function addMap(string $method, string $module, string $controller): Link
{
return $this->map[strtoupper($method)] = new Link($module, $controller);
}
/**
* Add param to data, for example - setup foreign keys on fly
*
* @param string $name
* @param string $value
*
* @return void
*/
public function addParam(string $name, string $value): void
{
$this->data[$name] = $value;
}
/**
* Add mapping for HEAD method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function head(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::HEAD, $module, $controller);
}
/**
* Add mapping for GET method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function get(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::GET, $module, $controller);
}
/**
* Add mapping for POST method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function post(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::POST, $module, $controller);
}
/**
* Add mapping for PATCH method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function patch(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::PATCH, $module, $controller);
}
/**
* Add mapping for PUT method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function put(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::PUT, $module, $controller);
}
/**
* Add mapping for DELETE method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function delete(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::DELETE, $module, $controller);
}
/**
* Add mapping for OPTIONS method
*
* @param string $module
* @param string $controller
*
* @return Link
*/
public function options(string $module, string $controller): Link
{
return $this->addMap(RequestMethod::OPTIONS, $module, $controller);
}
/**
* Run
*
* @return Controller
* @throws ComponentException
* @throws CommonException
* @throws ControllerException
* @throws ForbiddenException
* @throws NotAllowedException
* @throws NotAcceptableException
* @throws NotImplementedException
* @throws ReflectionException
*/
public function run(): Controller
{
$this->prepareRequest();
return $this->dispatch();
}
/**
* Prepare request for processing
*/
protected function prepareRequest(): void
{
// HTTP method
$method = Request::getMethod();
$this->method = strtoupper($method);
// get path
// %module% / %controller% / %id% / %relation% / %id%
$path = Router::getCleanUri();
$this->params = explode('/', rtrim($path, '/'));
// module
$this->module = array_shift($this->params);
// controller
$this->controller = array_shift($this->params);
$data = Request::getParams();
unset($data['_method'], $data['_module'], $data['_controller']);
$this->data = array_merge($data, $this->data);
$primary = $this->crud->getPrimaryKey();
$this->primary = array_intersect_key($this->data, array_flip($primary));
}
/**
* Dispatch REST or CRUD controller
*
* @return mixed
* @throws CommonException
* @throws ComponentException
* @throws ControllerException
* @throws ForbiddenException
* @throws NotImplementedException
* @throws ReflectionException
*/
protected function dispatch()
{
// check implementation
if (!isset($this->map[$this->method])) {
throw new NotImplementedException();
}
$link = $this->map[$this->method];
// check permissions
if (!Acl::isAllowed($this->module, $link->getAcl())) {
throw new ForbiddenException();
}
$this->crud->setFields($link->getFields());
// dispatch controller
$result = Application::getInstance()->dispatch(
$link->getModule(),
$link->getController(),
$this->prepareParams()
);
return $result;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Db.php | src/Db/Db.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db;
use Bluz\Common\Exception\ConfigurationException;
use Bluz\Common\Options;
use Bluz\Db\Exception\DbException;
use Bluz\Db\Query;
use Bluz\Proxy\Logger;
use PDO;
use PDOException;
use PDOStatement;
/**
* PDO wrapper
*
* @package Bluz\Db
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Db
*/
class Db
{
use Options;
/**
* PDO connection settings
*
* @var array
* @link http://php.net/manual/en/pdo.construct.php
*/
protected $connect = [
'type' => 'mysql',
'host' => 'localhost',
'name' => '',
'user' => 'root',
'pass' => '',
'options' => []
];
/**
* PDO connection flags
*
* @var array
* @link http://php.net/manual/en/pdo.setattribute.php
*/
protected $attributes = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
];
/**
* @var PDO PDO instance
*/
protected $handler;
/**
* Setup connection
*
* Just save connection settings
* <code>
* $db->setConnect([
* 'type' => 'mysql',
* 'host' => 'localhost',
* 'name' => 'db name',
* 'user' => 'root',
* 'pass' => ''
* ]);
* </code>
*
* @param array $connect options
*
* @throws ConfigurationException
* @return void
*/
public function setConnect(array $connect): void
{
$this->connect = array_merge($this->connect, $connect);
$this->checkConnect();
}
/**
* Check connection options
*
* @return void
* @throws ConfigurationException
*/
private function checkConnect(): void
{
if (
empty($this->connect['type']) ||
empty($this->connect['host']) ||
empty($this->connect['name']) ||
empty($this->connect['user'])
) {
throw new ConfigurationException(
'Database adapter is not configured.
Please check `db` configuration section: required type, host, db name and user'
);
}
}
/**
* Setup attributes for PDO connect
*
* @param array $attributes
*
* @return void
*/
public function setAttributes(array $attributes): void
{
$this->attributes = $attributes;
}
/**
* Connect to Db
*
* @return bool
* @throws DbException
*/
public function connect(): bool
{
try {
$this->checkConnect();
$this->log('Connect to ' . $this->connect['host']);
$this->handler = new PDO(
$this->connect['type'] . ':host=' . $this->connect['host'] . ';dbname=' . $this->connect['name'],
$this->connect['user'],
$this->connect['pass'],
$this->connect['options']
);
foreach ($this->attributes as $attribute => $value) {
$this->handler->setAttribute($attribute, $value);
}
$this->ok();
} catch (\Exception $e) {
throw new DbException("Attempt connection to database is failed: {$e->getMessage()}");
}
return true;
}
/**
* Disconnect PDO and clean default adapter
*
* @return void
*/
public function disconnect(): void
{
if ($this->handler) {
$this->handler = null;
}
}
/**
* Return PDO handler
*
* @return PDO
* @throws DbException
*/
public function handler(): PDO
{
if (null === $this->handler) {
$this->connect();
}
return $this->handler;
}
/**
* Prepare SQL query and return PDO Statement
*
* @param string $sql SQL query with placeholders
* @param array $params params for query placeholders
*
* @todo Switch to PDO::activeQueryString() when it will be possible
* @link https://wiki.php.net/rfc/debugging_pdo_prepared_statement_emulation
*
* @return PDOStatement
* @throws DbException
*/
protected function prepare(string $sql, array $params = []): PDOStatement
{
$stmt = $this->handler()->prepare($sql);
$stmt->execute($params);
$this->log($sql, $params);
return $stmt;
}
/**
* Quotes a string for use in a query
*
* Example of usage
* <code>
* $db->quote($_GET['id'])
* </code>
*
* @param string $value
* @param int $type
*
* @return string
* @throws DbException
*/
public function quote(string $value, int $type = PDO::PARAM_STR): string
{
return $this->handler()->quote($value, $type);
}
/**
* Quote a string so it can be safely used as a table or column name
*
* @param string $identifier
*
* @return string
*/
public function quoteIdentifier(string $identifier): string
{
// switch statement for DB type
switch ($this->connect['type']) {
case 'mysql':
return '`' . str_replace('`', '``', $identifier) . '`';
case 'postgresql':
case 'sqlite':
default:
return '"' . str_replace('"', '\\' . '"', $identifier) . '"';
}
}
/**
* Execute SQL query
*
* Example of usage
* <code>
* $db->query("SET NAMES 'utf8'");
* </code>
*
* @param string $sql SQL query with placeholders
* "UPDATE users SET name = :name WHERE id = :id"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John', ':id' => '123')
* @param array $types Types of params (optional)
* array (':name' => \PDO::PARAM_STR, ':id' => \PDO::PARAM_INT)
*
* @return integer the number of rows
* @throws DbException
*/
public function query(string $sql, array $params = [], array $types = []): int
{
$stmt = $this->handler()->prepare($sql);
foreach ($params as $key => &$param) {
$stmt->bindParam(
(is_int($key) ? $key + 1 : ':' . $key),
$param,
$types[$key] ?? PDO::PARAM_STR
);
}
$this->log($sql, $params);
$stmt->execute($params);
$this->ok();
return $stmt->rowCount();
}
/**
* Create new query select builder
*
* @param string[] $select The selection expressions
*
* @return Query\Select
*/
public function select(...$select): Query\Select
{
$query = new Query\Select();
$query->select(...$select);
return $query;
}
/**
* Create new query insert builder
*
* @param string $table
*
* @return Query\Insert
*/
public function insert(string $table): Query\Insert
{
$query = new Query\Insert();
$query->insert($table);
return $query;
}
/**
* Create new query update builder
*
* @param string $table
*
* @return Query\Update
*/
public function update(string $table): Query\Update
{
$query = new Query\Update();
$query->update($table);
return $query;
}
/**
* Create new query update builder
*
* @param string $table
*
* @return Query\Delete
*/
public function delete(string $table): Query\Delete
{
$query = new Query\Delete();
$query->delete($table);
return $query;
}
/**
* Return first field from first element from the result set
*
* Example of usage
* <code>
* $db->fetchOne("SELECT COUNT(*) FROM users");
* </code>
*
* @param string $sql SQL query with placeholders
* "SELECT * FROM users WHERE name = :name AND pass = :pass"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John', ':pass' => '123456')
*
* @return string|false
* @throws DbException
*/
public function fetchOne(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetch(PDO::FETCH_COLUMN);
$this->ok();
return $result;
}
/**
* Returns an array containing first row from the result set
*
* Example of usage
* <code>
* $db->fetchRow("SELECT name, email FROM users WHERE id = ". $db->quote($id));
* $db->fetchRow("SELECT name, email FROM users WHERE id = ?", [$id]);
* $db->fetchRow("SELECT name, email FROM users WHERE id = :id", [':id'=>$id]);
* </code>
*
* @param string $sql SQL query with placeholders
* "SELECT * FROM users WHERE name = :name AND pass = :pass"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John', ':pass' => '123456')
*
* @return array|false array ('name' => 'John', 'email' => 'john@smith.com')
* @throws DbException
*/
public function fetchRow(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$this->ok();
return $result;
}
/**
* Returns an array containing all of the result set rows
*
* Example of usage
* <code>
* $db->fetchAll("SELECT * FROM users WHERE ip = ?", ['192.168.1.1']);
* </code>
*
* @param string $sql SQL query with placeholders
* "SELECT * FROM users WHERE ip = :ip"
* @param array $params params for query placeholders (optional)
* array (':ip' => '127.0.0.1')
*
* @return array[]|false
* @throws DbException
*/
public function fetchAll(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$this->ok();
return $result;
}
/**
* Returns an array containing one column from the result set rows
*
* @param string $sql SQL query with placeholders
* "SELECT id FROM users WHERE ip = :ip"
* @param array $params params for query placeholders (optional)
* array (':ip' => '127.0.0.1')
*
* @return array|false
* @throws DbException
*/
public function fetchColumn(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN);
$this->ok();
return $result;
}
/**
* Returns an array containing all of the result set rows
*
* Group by first column
*
* <code>
* $db->fetchGroup("SELECT ip, COUNT(id) FROM users GROUP BY ip", []);
* </code>
*
* @param string $sql SQL query with placeholders
* "SELECT ip, id FROM users"
* @param array $params params for query placeholders (optional)
* @param mixed $object
*
* @return array|false
* @throws DbException
*/
public function fetchGroup(string $sql, array $params = [], $object = null)
{
$stmt = $this->prepare($sql, $params);
if ($object) {
$result = $stmt->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_GROUP, $object);
} else {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
}
$this->ok();
return $result;
}
/**
* Returns an array containing all of the result set rows
*
* Group by first column
*
* @param string $sql SQL query with placeholders
* "SELECT ip, id FROM users"
* @param array $params params for query placeholders (optional)
*
* @return array|false
* @throws DbException
*/
public function fetchColumnGroup(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);
$this->ok();
return $result;
}
/**
* Returns an array containing all of the result set rows
*
* Group by first unique column
*
* @param string $sql SQL query with placeholders
* "SELECT email, name, sex FROM users"
* @param array $params params for query placeholders (optional)
*
* @return array|false
* @throws DbException
*/
public function fetchUniqueGroup(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_ASSOC | PDO::FETCH_GROUP);
$this->ok();
return $result;
}
/**
* Returns a key-value array
*
* @param string $sql SQL query with placeholders
* "SELECT id, username FROM users WHERE ip = :ip"
* @param array $params params for query placeholders (optional)
* array (':ip' => '127.0.0.1')
*
* @return array|false
* @throws DbException
*/
public function fetchPairs(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$this->ok();
return $result;
}
/**
* Returns an object containing first row from the result set
*
* Example of usage
* <code>
* // Fetch object to stdClass
* $stdClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id]);
* // Fetch object to new Some object
* $someClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id], 'Some');
* // Fetch object to exists instance of Some object
* $someClass = $db->fetchObject('SELECT * FROM some_table WHERE id = ?', [$id], $someClass);
* </code>
*
* @param string $sql SQL query with placeholders
* "SELECT * FROM users WHERE name = :name AND pass = :pass"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John', ':pass' => '123456')
* @param mixed $object
*
* @return mixed
* @throws DbException
*/
public function fetchObject(string $sql, array $params = [], $object = 'stdClass')
{
$stmt = $this->prepare($sql, $params);
if (is_string($object)) {
// some class name
$result = $stmt->fetchObject($object);
} else {
// some instance
$stmt->setFetchMode(PDO::FETCH_INTO, $object);
$result = $stmt->fetch(PDO::FETCH_INTO);
}
$stmt->closeCursor();
$this->ok();
return $result;
}
/**
* Returns an array of objects containing the result set
*
* @param string $sql SQL query with placeholders
* "SELECT * FROM users WHERE name = :name AND pass = :pass"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John', ':pass' => '123456')
* @param mixed $object Class name or instance
*
* @return array|false
* @throws DbException
*/
public function fetchObjects(string $sql, array $params = [], $object = null)
{
$stmt = $this->prepare($sql, $params);
if (is_string($object)) {
// fetch to some class by name
$result = $stmt->fetchAll(PDO::FETCH_CLASS, $object);
} else {
// fetch to StdClass
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
}
$stmt->closeCursor();
$this->ok();
return $result;
}
/**
* Returns an array of linked objects containing the result set
*
* @param string $sql SQL query with placeholders
* "SELECT '__users', u.*, '__users_profile', up.*
* FROM users u
* LEFT JOIN users_profile up ON up.userId = u.id
* WHERE u.name = :name"
* @param array $params params for query placeholders (optional)
* array (':name' => 'John')
*
* @return array|false
* @throws DbException
*/
public function fetchRelations(string $sql, array $params = [])
{
$stmt = $this->prepare($sql, $params);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// prepare results
$result = Relations::fetch($result);
$stmt->closeCursor();
$this->ok();
return $result;
}
/**
* Transaction wrapper
*
* Example of usage
* <code>
* $db->transaction(function() use ($db) {
* $db->query("INSERT INTO `table` ...");
* $db->query("UPDATE `table` ...");
* $db->query("DELETE FROM `table` ...");
* })
* </code>
*
* @param callable $process callable structure - closure function or class with __invoke() method
*
* @return mixed|bool
* @throws DbException
*/
public function transaction(callable $process)
{
try {
$this->handler()->beginTransaction();
$result = $process();
$this->handler()->commit();
return $result ?? true;
} catch (PDOException $e) {
$this->handler()->rollBack();
Logger::error($e->getMessage());
return false;
}
}
/**
* Setup timer
*
* @return void
*/
protected function ok(): void
{
Logger::info('<<<');
}
/**
* Log queries by Application
*
* @param string $query SQL query for logs
* @param array $context
*
* @return void
*/
protected function log(string $query, array $context = []): void
{
$query = str_replace('%', '%%', $query);
$queries = preg_replace('/\?/', '"%s"', $query, count($context));
// replace mask by data
$log = vsprintf($queries, $context);
Logger::info($log);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Table.php | src/Db/Table.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db;
use Bluz\Common\Instance;
use Bluz\Db\Exception\DbException;
use Bluz\Db\Exception\InvalidPrimaryKeyException;
use Bluz\Db\Traits\TableRelations;
use Bluz\Proxy\Cache;
use Bluz\Proxy\Db as DbProxy;
use InvalidArgumentException;
/**
* Table
*
* Example of Users\Table
* <code>
* namespace Application\Users;
* class Table extends \Bluz\Db\Table
* {
* protected $table = 'users';
* protected $primary = ['id'];
* }
*
* $userRows = \Application\Users\Table::find(1,2,3,4,5);
* foreach ($userRows as $userRow) {
* $userRow -> description = 'In first 5';
* $userRow -> save();
* }
* </code>
*
* @package Bluz\Db
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Db-Table
*/
abstract class Table implements TableInterface
{
use Instance;
use TableRelations;
/**
* @var string the table name
*/
protected $name;
/**
* @var string the model name
*/
protected $model;
/**
* @var array table meta
*/
protected $meta = [];
/**
* @var string default SQL query for select
*/
protected $select = '';
/**
* @var array the primary key column or columns (only as array).
*/
protected $primary;
/**
* @var string the sequence name, required for PostgreSQL
*/
protected $sequence;
/**
* @var string row class name
*/
protected $rowClass;
/**
* Create and initialize Table instance
*/
private function __construct()
{
$tableClass = static::class;
$namespace = class_namespace($tableClass);
// autodetect model name
if (!$this->model) {
$this->model = substr($namespace, strrpos($namespace, '\\') + 1);
}
// autodetect table name - camelCase to uppercase
if (!$this->name) {
$table = preg_replace('/(?<=\\w)(?=[A-Z])/', '_$1', $this->model);
$this->name = strtolower($table);
}
// autodetect row class
if (!$this->rowClass) {
$this->rowClass = $namespace . '\\Row';
}
// setup default select query
if (empty($this->select)) {
$this->select = 'SELECT ' . DbProxy::quoteIdentifier($this->name) . '.* ' .
'FROM ' . DbProxy::quoteIdentifier($this->name);
}
Relations::addClassMap($this->model, $tableClass);
$this->init();
}
/**
* Initialization hook.
* Subclasses may override this method
*
* @return void
*/
public function init(): void
{
}
/**
* Get primary key(s)
*
* @return array
* @throws InvalidPrimaryKeyException if primary key was not set or has wrong format
*/
public function getPrimaryKey(): array
{
if (!is_array($this->primary)) {
throw new InvalidPrimaryKeyException('The primary key must be set as an array');
}
return $this->primary;
}
/**
* Get table name
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Get model name
*
* @return string
*/
public function getModel(): string
{
return $this->model;
}
/**
* Return information about table columns
*
* @return array
*/
public static function getMeta(): array
{
$self = static::getInstance();
if (empty($self->meta)) {
$cacheKey = "db.table.{$self->name}";
$meta = Cache::get($cacheKey);
if (!$meta) {
$schema = DbProxy::getOption('connect', 'name');
$meta = DbProxy::fetchUniqueGroup(
'
SELECT
COLUMN_NAME AS `name`,
DATA_TYPE AS `type`,
COLUMN_DEFAULT AS `default`,
COLUMN_KEY AS `key`
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = ?
AND TABLE_NAME = ?',
[$schema, $self->getName()]
);
Cache::set($cacheKey, $meta, Cache::TTL_NO_EXPIRY, ['system', 'db']);
}
$self->meta = $meta;
}
return $self->meta;
}
/**
* Return names of table columns
*
* @return array
*/
public static function getColumns(): array
{
$self = static::getInstance();
return array_keys($self::getMeta());
}
/**
* Filter columns for insert/update queries by table columns definition
*
* @param array $data
*
* @return array
*/
public static function filterColumns(array $data): array
{
return array_intersect_key($data, array_flip(static::getColumns()));
}
/**
* Fetching rows by SQL query
*
* @param string $sql SQL query with placeholders
* @param array $params Params for query placeholders
*
* @return RowInterface[] of rows results in FETCH_CLASS mode
*/
protected static function fetch(string $sql, array $params = []): array
{
$self = static::getInstance();
return DbProxy::fetchObjects($sql, $params, $self->rowClass);
}
/**
* {@inheritdoc}
*
* @throws DbException
* @throws InvalidPrimaryKeyException if wrong count of values passed
* @throws InvalidArgumentException
*/
public static function find(...$keys): array
{
$keyNames = array_values(static::getInstance()->getPrimaryKey());
$whereList = [];
foreach ($keys as $keyValues) {
$keyValues = (array)$keyValues;
if (count($keyValues) !== count($keyNames)) {
throw new InvalidPrimaryKeyException(
"Invalid columns for the primary key.\n" .
"Please check " . static::class . " initialization or usage.\n" .
"Settings described at https://github.com/bluzphp/framework/wiki/Db-Table"
);
}
if (array_keys($keyValues)[0] === 0) {
// for numerical array
$whereList[] = array_combine($keyNames, $keyValues);
} else {
// for assoc array
$whereList[] = $keyValues;
}
}
return static::findWhere(...$whereList);
}
/**
* {@inheritdoc}
*
* @throws InvalidArgumentException
* @throws Exception\DbException
*/
public static function findWhere(...$where): array
{
$self = static::getInstance();
$whereParams = [];
if (count($where) === 2 && is_string($where[0])) {
$whereClause = $where[0];
$whereParams = (array)$where[1];
} elseif (count($where)) {
$whereOrTerms = [];
foreach ($where as $keyValueSets) {
$whereAndTerms = [];
foreach ($keyValueSets as $keyName => $keyValue) {
if (is_array($keyValue)) {
$keyValue = array_map(
['DbProxy', 'quote'],
$keyValue
);
$keyValue = implode(',', $keyValue);
$whereAndTerms[] = $self->name . '.' . $keyName . ' IN (' . $keyValue . ')';
} elseif (null === $keyValue) {
$whereAndTerms[] = $self->name . '.' . $keyName . ' IS NULL';
} elseif (
is_string($keyValue)
&& ('%' === substr($keyValue, 0, 1) || '%' === substr($keyValue, -1, 1))
) {
$whereAndTerms[] = $self->name . '.' . $keyName . ' LIKE ?';
$whereParams[] = $keyValue;
} else {
$whereAndTerms[] = $self->name . '.' . $keyName . ' = ?';
$whereParams[] = $keyValue;
}
if (!is_scalar($keyValue) && !is_null($keyValue)) {
throw new InvalidArgumentException(
"Wrong arguments of method 'findWhere'.\n" .
'Please use syntax described at https://github.com/bluzphp/framework/wiki/Db-Table'
);
}
}
$whereOrTerms[] = '(' . implode(' AND ', $whereAndTerms) . ')';
}
$whereClause = '(' . implode(' OR ', $whereOrTerms) . ')';
} else {
throw new DbException(
"Method `Table::findWhere()` can't return all records from table"
);
}
return self::fetch($self->select . ' WHERE ' . $whereClause, $whereParams);
}
/**
* {@inheritdoc}
*
* @throws DbException
* @throws InvalidArgumentException
* @throws InvalidPrimaryKeyException
*/
public static function findRow($primaryKey): ?RowInterface
{
$result = static::find($primaryKey);
return current($result) ?: null;
}
/**
* {@inheritdoc}
*
* @throws DbException
* @throws InvalidArgumentException
*/
public static function findRowWhere(array $whereList): ?RowInterface
{
$result = static::findWhere($whereList);
return current($result) ?: null;
}
/**
* Prepare array for WHERE or SET statements
*
* @param array $where
*
* @return array
*/
private static function prepareStatement(array $where): array
{
$keys = array_keys($where);
foreach ($keys as &$key) {
$key = DbProxy::quoteIdentifier($key) . ' = ?';
}
return $keys;
}
/**
* Prepare Db\Query\Select for current table:
* - predefine "select" section as "*" from current table
* - predefine "from" section as current table name and first letter as alias
* - predefine fetch type
*
* <code>
* // use default select "*"
* $select = Users\Table::select();
* $arrUsers = $select->where('u.id = ?', $id)
* ->execute();
*
* // setup custom select "u.id, u.login"
* $select = Users\Table::select();
* $arrUsers = $select->select('u.id, u.login')
* ->where('u.id = ?', $id)
* ->execute();
* </code>
*
* @return Query\Select
*/
public static function select(): Query\Select
{
$self = static::getInstance();
$select = new Query\Select();
$select->select(DbProxy::quoteIdentifier($self->name) . '.*')
->from($self->name, $self->name)
->setFetchType($self->rowClass);
return $select;
}
/**
* {@inheritdoc}
*/
public static function create(array $data = []): RowInterface
{
$rowClass = static::getInstance()->rowClass;
/** @var Row $row */
$row = new $rowClass($data);
$row->setTable(static::getInstance());
return $row;
}
/**
* {@inheritdoc}
*
* @throws Exception\DbException
*/
public static function insert(array $data)
{
$self = static::getInstance();
$data = static::filterColumns($data);
if (!count($data)) {
throw new DbException(
"Invalid field names of table `{$self->name}`. Please check use of `insert()` method"
);
}
$table = DbProxy::quoteIdentifier($self->name);
$sql = "INSERT INTO $table SET " . implode(',', self::prepareStatement($data));
$result = DbProxy::query($sql, array_values($data));
if (!$result) {
return null;
}
/**
* If a sequence name was not specified for the name parameter, PDO::lastInsertId()
* returns a string representing the row ID of the last row that was inserted into the database.
*
* If a sequence name was specified for the name parameter, PDO::lastInsertId()
* returns a string representing the last value retrieved from the specified sequence object.
*
* If the PDO driver does not support this capability, PDO::lastInsertId() triggers an IM001 SQLSTATE.
*/
return DbProxy::handler()->lastInsertId($self->sequence);
}
/**
* {@inheritdoc}
*
* @throws Exception\DbException
*/
public static function update(array $data, array $where): int
{
$self = static::getInstance();
$data = static::filterColumns($data);
if (!count($data)) {
throw new DbException(
"Invalid field names of table `{$self->name}`. Please check use of `update()` method"
);
}
$where = static::filterColumns($where);
if (!count($where)) {
throw new DbException(
"Method `Table::update()` can't update all records in the table `{$self->name}`,\n" .
"please use `Db::query()` instead (of cause if you know what are you doing)"
);
}
$table = DbProxy::quoteIdentifier($self->name);
$sql = "UPDATE $table SET " . implode(',', self::prepareStatement($data))
. " WHERE " . implode(' AND ', self::prepareStatement($where));
return DbProxy::query($sql, array_merge(array_values($data), array_values($where)));
}
/**
* {@inheritdoc}
*
* @throws DbException
*/
public static function delete(array $where): int
{
$self = static::getInstance();
if (!count($where)) {
throw new DbException(
"Method `Table::delete()` can't delete all records in the table `{$self->name}`,\n" .
"please use `Db::query()` instead (of cause if you know what are you doing)"
);
}
$where = static::filterColumns($where);
if (!count($where)) {
throw new DbException(
"Invalid field names of table `{$self->name}`. Please check use of `delete()` method"
);
}
$table = DbProxy::quoteIdentifier($self->name);
$sql = "DELETE FROM $table WHERE " . implode(' AND ', self::prepareStatement($where));
return DbProxy::query($sql, array_values($where));
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/TableInterface.php | src/Db/TableInterface.php | <?php
/**
* @namespace
*/
namespace Bluz\Db;
use Bluz\Db\Exception\InvalidPrimaryKeyException;
/**
* TableInterface
*
* @package Bluz\Db
* @author Anton Shevchuk
*/
interface TableInterface
{
/**
* Get Table instance
*
* @return TableInterface
*/
public static function getInstance();
/**
* Get primary key(s)
*
* @return array
* @throws InvalidPrimaryKeyException if primary key was not set or has wrong format
*/
public function getPrimaryKey(): array;
/**
* Get table name
*
* @return string
*/
public function getName(): string;
/**
* Get model name
*
* @return string
*/
public function getModel(): string;
/**
* Create Row instance
*
* @param array $data
*
* @return RowInterface
*/
public static function create(array $data = []): RowInterface;
/**
* Fetches rows by primary key. The argument specifies one or more primary
* key value(s). To find multiple rows by primary key, the argument must
* be an array.
*
* This method accepts a variable number of arguments. If the table has a
* multi-column primary key, the number of arguments must be the same as
* the number of columns in the primary key. To find multiple rows in a
* table with a multi-column primary key, each argument must be an array
* with the same number of elements.
*
* The find() method always returns a array
*
* Row by primary key, return array
* Table::find(123);
*
* Row by compound primary key, return array
* Table::find([123, 'abc']);
*
* Multiple rows by primary key
* Table::find(123, 234, 345);
*
* Multiple rows by compound primary key
* Table::find([123, 'abc'], [234, 'def'], [345, 'ghi'])
*
* @param mixed ...$keys The value(s) of the primary keys.
*
* @return RowInterface[]
*/
public static function find(...$keys): array;
/**
* Find rows by WHERE
* // WHERE alias = 'foo'
* Table::findWhere(['alias' => 'foo']);
* // WHERE alias IS NULL
* Table::findWhere(['alias' => null]);
* // WHERE alias IN ('foo', 'bar')
* Table::findWhere(['alias' => ['foo', 'bar']]);
* // WHERE alias LIKE 'foo%'
* Table::findWhere(['alias' => 'foo%']);
* // WHERE alias = 'foo' OR 'alias' = 'bar'
* Table::findWhere(['alias'=>'foo'], ['alias'=>'bar']);
* // WHERE (alias = 'foo' AND userId = 2) OR ('alias' = 'bar' AND userId = 4)
* Table::findWhere(['alias'=>'foo', 'userId'=> 2], ['alias'=>'foo', 'userId'=>4]);
*
* @param mixed ...$where
*
* @return RowInterface[]
*/
public static function findWhere(...$where): array;
/**
* Find row by primary key
*
* @param mixed $primaryKey
*
* @return RowInterface
*/
public static function findRow($primaryKey): ?RowInterface;
/**
* Find row by where condition
*
* @param array $whereList
*
* @return RowInterface
*/
public static function findRowWhere(array $whereList): ?RowInterface;
/**
* Prepare Db\Query\Select for current table:
* - predefine "select" section as "*" from current table
* - predefine "from" section as current table name and first letter as alias
* - predefine fetch type
*
* <code>
* // use default select "*"
* $select = Users\Table::select();
* $arrUsers = $select->where('u.id = ?', $id)
* ->execute();
*
* // setup custom select "u.id, u.login"
* $select = Users\Table::select();
* $arrUsers = $select->select('u.id, u.login')
* ->where('u.id = ?', $id)
* ->execute();
* </code>
*
* @return Query\Select
*/
public static function select(): Query\Select;
/**
* Insert new record to table and return last insert Id
*
* <code>
* Table::insert(['login' => 'Man', 'email' => 'man@example.com'])
* </code>
*
* @param array $data Column-value pairs
*
* @return string|null Primary key or null
*/
public static function insert(array $data);
/**
* Updates existing rows
*
* <code>
* Table::update(['login' => 'Man', 'email' => 'man@domain.com'], ['id' => 42])
* </code>
*
* @param array $data Column-value pairs.
* @param array $where An array of SQL WHERE clause(s)
*
* @return integer The number of rows updated
*/
public static function update(array $data, array $where): int;
/**
* Deletes existing rows
*
* <code>
* Table::delete(['login' => 'Man'])
* </code>
*
* @param array $where An array of SQL WHERE clause(s)
*
* @return integer The number of rows deleted
*/
public static function delete(array $where): int;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Row.php | src/Db/Row.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db;
use Bluz\Common\Container;
use Bluz\Db\Exception\DbException;
use Bluz\Db\Exception\InvalidPrimaryKeyException;
use Bluz\Db\Exception\TableNotFoundException;
/**
* Db Table Row
*
* Example of Users\Row
* <code>
* namespace Application\Users;
* class Row extends \Bluz\Db\Row
* {
* public function beforeInsert(): void
* {
* $this->created = gmdate('Y-m-d H:i:s');
* }
*
* public function beforeUpdate(): void
* {
* $this->updated = gmdate('Y-m-d H:i:s');
* }
* }
*
* $userRow = new \Application\Users\Row();
* $userRow -> login = 'username';
* $userRow -> save();
* </code>
*
* @package Bluz\Db
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Db-Row
*/
abstract class Row implements RowInterface, \JsonSerializable, \ArrayAccess
{
use Container\Container;
use Container\ArrayAccess;
use Container\JsonSerialize;
use Container\MagicAccess;
use Traits\TableProperty;
use Traits\RowRelations;
/**
* This is set to a copy of $data when the data is fetched from
* a database, specified as a new tuple in the constructor, or
* when dirty data is posted to the database with save().
*
* @var array
*/
protected $clean = [];
/**
* Create Row instance
*
* @param array $data
*/
public function __construct(array $data = [])
{
// original cleaner data
$this->clean = $this->toArray();
// not clean data, but not modified
if (count($data)) {
$this->setFromArray($data);
}
$this->afterRead();
}
/**
* List of required for serialization properties
*
* @return string[]
*/
public function __sleep()
{
return ['container', 'clean'];
}
/**
* Cast to string as class name
*
* @return string
*/
public function __toString()
{
return static::class;
}
/**
* Magic method for var_dump()
*
* @return array
* @see var_dump()
*/
public function __debugInfo()
{
return [
'DATA::CLEAN' => $this->clean,
'DATA::RAW' => $this->container,
'RELATIONS' => $this->relations ?? []
];
}
/**
* Validate input data
*
* @param array $data
*
* @return bool
*/
public function validate($data): bool
{
return true;
}
/**
* Assert input data
*
* @param array $data
*
* @return void
*/
public function assert($data): void
{
return;
}
/**
* Saves the properties to the database.
*
* This performs an intelligent insert/update, and reloads the
* properties with fresh data from the table on success.
*
* @return mixed The primary key value(s), as an associative array if the
* key is compound, or a scalar if the key is single-column
* @throws DbException
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
*/
public function save()
{
$this->beforeSave();
/**
* If the primary key is empty, this is an INSERT of a new row.
* Otherwise check primary key updated or not, if it changed - INSERT
* otherwise UPDATE
*/
if (!count(array_filter($this->getPrimaryKey()))) {
$result = $this->doInsert();
} elseif (count(array_diff_assoc($this->getPrimaryKey(), $this->clean))) {
$result = $this->doInsert();
} else {
$result = $this->doUpdate();
}
$this->afterSave();
return $result;
}
/**
* Insert row to Db
*
* @return mixed The primary key value(s), as an associative array if the
* key is compound, or a scalar if the key is single-column
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
*/
protected function doInsert()
{
/**
* Run pre-INSERT logic
*/
$this->beforeInsert();
$data = $this->toArray();
/**
* Execute validator logic
* Can throw ValidatorException
*/
$this->assert($data);
$table = $this->getTable();
/**
* Execute the INSERT (this may throw an exception)
*/
$primaryKey = $table::insert($data);
/**
* Normalize the result to an array indexed by primary key column(s)
*/
$tempPrimaryKey = $table->getPrimaryKey();
$newPrimaryKey = [current($tempPrimaryKey) => $primaryKey];
/**
* Save the new primary key value in object. The primary key may have
* been generated by a sequence or auto-increment mechanism, and this
* merge should be done before the afterInsert() method is run, so the
* new values are available for logging, etc.
*/
$this->setFromArray($newPrimaryKey);
/**
* Run post-INSERT logic
*/
$this->afterInsert();
/**
* Update the "clean" to reflect that the data has been inserted.
*/
$this->clean = $this->toArray();
return $newPrimaryKey;
}
/**
* Update row
*
* @return integer The number of rows updated
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
* @throws DbException
*/
protected function doUpdate(): int
{
/**
* Run pre-UPDATE logic
*/
$this->beforeUpdate();
$data = $this->toArray();
/**
* Execute validator logic
* Can throw ValidatorException
*/
$this->assert($data);
$primaryKey = $this->getPrimaryKey();
/**
* Compare the data to the modified fields array to discover
* which columns have been changed.
*/
$diffData = array_diff_assoc($data, $this->clean);
/* @var Table $table */
$table = $this->getTable();
$diffData = $table::filterColumns($diffData);
/**
* Execute the UPDATE (this may throw an exception)
* Do this only if data values were changed.
* Use the $diffData variable, so the UPDATE statement
* includes SET terms only for data values that changed.
*/
$result = 0;
if (count($diffData) > 0) {
$result = $table::update($diffData, $primaryKey);
}
/**
* Run post-UPDATE logic. Do this before the _refresh()
* so the _afterUpdate() function can tell the difference
* between changed data and clean (pre-changed) data.
*/
$this->afterUpdate();
/**
* Refresh the data just in case triggers in the RDBMS changed
* any columns. Also this resets the "clean".
*/
$this->clean = $this->toArray();
return $result;
}
/**
* Delete existing row
*
* @return bool Removed or not
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
*/
public function delete(): bool
{
/**
* Execute pre-DELETE logic
*/
$this->beforeDelete();
$primaryKey = $this->getPrimaryKey();
/**
* Execute the DELETE (this may throw an exception)
*/
$table = $this->getTable();
$result = $table::delete($primaryKey);
/**
* Execute post-DELETE logic
*/
$this->afterDelete();
/**
* Reset all fields to null to indicate that the row is not there
*/
$this->resetArray();
return $result > 0;
}
/**
* Retrieves an associative array of primary keys, if it exists
*
* @return array
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
*/
protected function getPrimaryKey(): array
{
$primary = array_flip($this->getTable()->getPrimaryKey());
return array_intersect_key($this->toArray(), $primary);
}
/**
* Refreshes properties from the database
*
* @return void
*/
public function refresh(): void
{
$this->setFromArray($this->clean);
$this->afterRead();
}
/**
* After read data from Db
*
* @return void
*/
protected function afterRead(): void
{
}
/**
* Allows pre-insert and pre-update logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function beforeSave(): void
{
}
/**
* Allows post-insert and post-update logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function afterSave(): void
{
}
/**
* Allows pre-insert logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function beforeInsert(): void
{
}
/**
* Allows post-insert logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function afterInsert(): void
{
}
/**
* Allows pre-update logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function beforeUpdate(): void
{
}
/**
* Allows post-update logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function afterUpdate(): void
{
}
/**
* Allows pre-delete logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function beforeDelete(): void
{
}
/**
* Allows post-delete logic to be applied to row.
* Subclasses may override this method
*
* @return void
*/
protected function afterDelete(): void
{
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/RowInterface.php | src/Db/RowInterface.php | <?php
/**
* @namespace
*/
namespace Bluz\Db;
/**
* RowInterface
*
* @package Bluz\Db
* @author Anton Shevchuk
*/
interface RowInterface
{
/**
* Create Row instance
*
* @param array $data
*/
public function __construct(array $data = []);
/**
* Returns the column/value data as an array
*
* @return array
*/
public function toArray(): array;
/**
* Sets all data in the row from an array
*
* @param array $data
*
* @return void
*/
public function setFromArray(array $data): void;
/**
* Saves the properties to the database.
*
* This performs an intelligent insert/update, and reloads the
* properties with fresh data from the table on success.
*
* @return mixed The primary key value(s), as an associative array if the
* key is compound, or a scalar if the key is single-column
*/
public function save();
/**
* Delete existing row
*
* @return bool Removed or not
*/
public function delete(): bool;
/**
* Refreshes properties from the database
*
* @return void
*/
public function refresh(): void;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Relations.php | src/Db/Relations.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db;
use Bluz\Db\Exception\RelationNotFoundException;
/**
* Relations map of Db tables
*
* @package Bluz\Db
* @author Anton Shevchuk
*/
class Relations
{
/**
* Relation stack, i.e.
* <code>
* [
* 'Model1:Model2' => ['Model1'=>'foreignKey', 'Model2'=>'primaryKey'],
* 'Pages:Users' => ['Pages'=>'userId', 'Users'=>'id'],
* 'PagesTags:Pages' => ['PagesTags'=>'pageId', 'Pages'=>'id'],
* 'PagesTags:Tags' => ['PagesTags'=>'tagId', 'Tags'=>'id'],
* 'Pages:Tags' => ['PagesTags'],
* ]
* </code>
*
* @var array
*/
protected static $relations;
/**
* Class map, i.e.
* <code>
* [
* 'Pages' => '\Application\Pages\Table',
* 'Users' => '\Application\Users\Table',
* ]
* </code>
*
* @var array
*/
protected static $modelClassMap;
/**
* Setup relation between two models
*
* @param string $modelOne
* @param string $keyOne
* @param string $modelTwo
* @param string $keyTwo
*
* @return void
*/
public static function setRelation(string $modelOne, string $keyOne, string $modelTwo, string $keyTwo): void
{
$relations = [$modelOne => $keyOne, $modelTwo => $keyTwo];
self::setRelations($modelOne, $modelTwo, $relations);
}
/**
* Setup multi relations
*
* @param string $modelOne
* @param string $modelTwo
* @param array $relations
*
* @return void
*/
public static function setRelations(string $modelOne, string $modelTwo, array $relations): void
{
$name = [$modelOne, $modelTwo];
sort($name);
$name = implode(':', $name);
// create record in static variable
self::$relations[$name] = $relations;
}
/**
* Get relations
*
* @param string $modelOne
* @param string $modelTwo
*
* @return array|false
*/
public static function getRelations(string $modelOne, string $modelTwo)
{
$name = [$modelOne, $modelTwo];
sort($name);
$name = implode(':', $name);
return self::$relations[$name] ?? false;
}
/**
* findRelation
*
* @param Row $row
* @param string $relation
*
* @return array
* @throws Exception\TableNotFoundException
* @throws Exception\RelationNotFoundException
*/
public static function findRelation(Row $row, string $relation): array
{
$model = $row->getTable()->getModel();
/** @var \Bluz\Db\Table $relationTable */
$relationTable = self::getModelClass($relation);
$relationTable::getInstance();
if (!$relations = self::getRelations($model, $relation)) {
throw new RelationNotFoundException(
"Relations between model `$model` and `$relation` is not defined"
);
}
// check many-to-many relations
if (count($relations) === 1) {
$relations = self::getRelations($model, current($relations));
}
$field = $relations[$model];
$key = $row->{$field};
return self::findRelations($model, $relation, [$key]);
}
/**
* Find Relations between two tables
*
* @param string $modelOne Table
* @param string $modelTwo Target table
* @param array $keys Keys from first table
*
* @return array
* @throws Exception\RelationNotFoundException
*/
public static function findRelations(string $modelOne, string $modelTwo, array $keys): array
{
$keys = (array)$keys;
if (!$relations = self::getRelations($modelOne, $modelTwo)) {
throw new RelationNotFoundException("Relations between model `$modelOne` and `$modelTwo` is not defined");
}
/* @var Table $tableOneClass name */
$tableOneClass = self::getModelClass($modelOne);
/* @var string $tableOneName */
$tableOneName = $tableOneClass::getInstance()->getName();
/* @var Table $tableTwoClass name */
$tableTwoClass = self::getModelClass($modelTwo);
/* @var string $tableTwoName */
$tableTwoName = $tableTwoClass::getInstance()->getName();
/* @var Query\Select $tableTwoSelect */
$tableTwoSelect = $tableTwoClass::getInstance()::select();
// check many to many relation
if (is_int(\array_keys($relations)[0])) {
// many to many relation over third table
$modelThree = $relations[0];
// relations between target table and third table
$relations = self::getRelations($modelTwo, $modelThree);
/* @var Table $tableThreeClass name */
$tableThreeClass = self::getModelClass($modelThree);
/* @var string $tableTwoName */
$tableThreeName = $tableThreeClass::getInstance()->getName();
// join it to query
$tableTwoSelect->join(
$tableTwoName,
$tableThreeName,
$tableThreeName,
$tableTwoName . '.' . $relations[$modelTwo] . '=' . $tableThreeName . '.' . $relations[$modelThree]
);
// relations between source table and third table
$relations = self::getRelations($modelOne, $modelThree);
// join it to query
$tableTwoSelect->join(
$tableThreeName,
$tableOneName,
$tableOneName,
$tableThreeName . '.' . $relations[$modelThree] . '=' . $tableOneName . '.' . $relations[$modelOne]
);
// set source keys
$tableTwoSelect->where($tableOneName . '.' . $relations[$modelOne] . ' IN (?)', $keys);
} else {
// set source keys
$tableTwoSelect->where($relations[$modelTwo] . ' IN (?)', $keys);
}
return $tableTwoSelect->execute();
}
/**
* Add information about model's classes
*
* @param string $model
* @param string $className
*
* @return void
*/
public static function addClassMap(string $model, string $className): void
{
self::$modelClassMap[$model] = $className;
}
/**
* Get information about Model classes
*
* @param string $model
*
* @return string
* @throws Exception\RelationNotFoundException
*/
public static function getModelClass(string $model): string
{
if (!isset(self::$modelClassMap[$model])) {
// try to detect
$className = '\\Application\\' . $model . '\\Table';
if (!class_exists($className)) {
throw new RelationNotFoundException("Related class for model `$model` not found");
}
self::$modelClassMap[$model] = $className;
}
return self::$modelClassMap[$model];
}
/**
* Get information about Table classes
*
* @param string $modelName
* @param array $data
*
* @return RowInterface
* @throws Exception\RelationNotFoundException
*/
public static function createRow(string $modelName, array $data): RowInterface
{
$tableClass = self::getModelClass($modelName);
/* @var Table $tableClass name */
return $tableClass::getInstance()::create($data);
}
/**
* Fetch by Divider
*
* @param array $input
*
* @return array
* @throws Exception\RelationNotFoundException
*/
public static function fetch(array $input): array
{
$output = [];
$map = [];
foreach ($input as $i => $row) {
$model = '';
foreach ($row as $key => $value) {
if (strpos($key, '__') === 0) {
$model = substr($key, 2);
continue;
}
$map[$i][$model][$key] = $value;
}
foreach ($map[$i] as $model => &$data) {
$data = self::createRow($model, $data);
}
$output[] = $map;
}
return $output;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Traits/TableProperty.php | src/Db/Traits/TableProperty.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Traits;
use Bluz\Db\Exception\TableNotFoundException;
use Bluz\Db\TableInterface;
/**
* TableProperty
*
* @package Bluz\Db\Traits
* @author Anton Shevchuk
*/
trait TableProperty
{
/**
* @var TableInterface instance
*/
protected $table;
/**
* Setup Table instance
*
* @param TableInterface $table
*
* @return void
*/
public function setTable(TableInterface $table): void
{
$this->table = $table;
}
/**
* Return table instance for manipulation
*
* @return TableInterface
* @throws TableNotFoundException
*/
public function getTable(): TableInterface
{
if (!$this->table) {
$this->initTable();
}
return $this->table;
}
/**
* Init table instance for manipulation
*
* @return void
* @throws TableNotFoundException
*/
protected function initTable(): void
{
$tableClass = class_namespace(static::class) . '\\Table';
// check class initialization
if (!class_exists($tableClass) || !is_subclass_of($tableClass, TableInterface::class)) {
throw new TableNotFoundException('`Table` class is not exists or not initialized');
}
/**
* @var TableInterface $tableClass
*/
$this->setTable($tableClass::getInstance());
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Traits/TableRelations.php | src/Db/Traits/TableRelations.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Traits;
use Bluz\Db\Relations;
/**
* TableRelations
*
* @package Bluz\Db\Traits
* @author Anton Shevchuk
*/
trait TableRelations
{
/**
* Setup relation "one to one" or "one to many"
*
* @param string $key
* @param string $model
* @param string $foreign
*
* @return void
*/
public function linkTo($key, $model, $foreign): void
{
Relations::setRelation($this->model, $key, $model, $foreign);
}
/**
* Setup relation "many to many"
* [table1-key] [table1_key-table2-table3_key] [table3-key]
*
* @param string $model
* @param string $link
*
* @return void
*/
public function linkToMany($model, $link): void
{
Relations::setRelations($this->model, $model, [$link]);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Traits/RowRelations.php | src/Db/Traits/RowRelations.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Traits;
use Bluz\Db\Relations;
use Bluz\Db\Row;
use Bluz\Db\Exception\RelationNotFoundException;
use Bluz\Db\Exception\TableNotFoundException;
use Bluz\Db\RowInterface;
/**
* RowRelations
*
* @package Bluz\Db\Traits
* @author Anton Shevchuk
*/
trait RowRelations
{
/**
* @var array relations rows
*/
protected $relations = [];
/**
* Set relation
*
* @param Row $row
*
* @return void
* @throws TableNotFoundException
*/
public function setRelation(Row $row): void
{
$modelName = $row->getTable()->getModel();
$this->relations[$modelName] = [$row];
}
/**
* Get relation by model name
*
* @param string $modelName
*
* @return RowInterface
* @throws RelationNotFoundException
* @throws TableNotFoundException
*/
public function getRelation($modelName): ?RowInterface
{
$relations = $this->getRelations($modelName);
return empty($relations) ? null : current($relations);
}
/**
* Get relations by model name
*
* @param string $modelName
*
* @return RowInterface[]
* @throws RelationNotFoundException
* @throws TableNotFoundException
*/
public function getRelations($modelName): array
{
if (!isset($this->relations[$modelName])) {
$this->relations[$modelName] = Relations::findRelation($this, $modelName);
}
return $this->relations[$modelName];
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Insert.php | src/Db/Query/Insert.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
use Bluz\Proxy\Db;
/**
* Builder of INSERT queries
*
* @package Bluz\Db\Query
*/
class Insert extends AbstractBuilder
{
use Traits\Set;
/**
* @var string Table name
*/
protected $table;
/**
* {@inheritdoc}
*
* @param null $sequence
*
* @return integer|string|array
*/
public function execute($sequence = null)
{
$result = Db::query($this->getSql(), $this->params, $this->types);
if ($result) {
return Db::handler()->lastInsertId($sequence);
}
return $result;
}
/**
* {@inheritdoc}
*
* @return string
*/
public function getSql(): string
{
return 'INSERT INTO '
. Db::quoteIdentifier($this->table)
. $this->prepareSet();
}
/**
* Turns the query being built into an insert query that inserts into
* a certain table
*
* Example
* <code>
* $ib = new InsertBuilder();
* $ib
* ->insert('users')
* ->set('name', 'username')
* ->set('password', md5('password'));
* </code>
*
* @param string $table The table into which the rows should be inserted
*
* @return Insert instance
*/
public function insert($table): Insert
{
$this->table = $table;
return $this;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Update.php | src/Db/Query/Update.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
use Bluz\Proxy\Db;
/**
* Builder of UPDATE queries
*
* @package Bluz\Db\Query
*/
class Update extends AbstractBuilder
{
use Traits\Set;
use Traits\Where;
use Traits\Limit;
/**
* @var string Table name
*/
protected $table;
/**
* {@inheritdoc}
*/
public function getSql(): string
{
return 'UPDATE '
. Db::quoteIdentifier($this->table)
. $this->prepareSet()
. $this->prepareWhere()
. $this->prepareLimit();
}
/**
* Turns the query being built into a bulk update query that ranges over
* a certain table
*
* Example
* <code>
* $ub = new UpdateBuilder();
* $ub
* ->update('users')
* ->set('password', md5('password'))
* ->where('id = ?');
* </code>
*
* @param string $table the table whose rows are subject to the update
*
* @return Update instance
*/
public function update($table): Update
{
$this->table = $table;
return $this;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/CompositeBuilder.php | src/Db/Query/CompositeBuilder.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
/**
* Class Expression Builder
*
* @package Bluz\Db\Query
*/
class CompositeBuilder implements \Countable
{
/**
* @var string type AND|OR
*/
private $type;
/**
* @var array parts of the composite expression
*/
private $parts = [];
/**
* Constructor
*
* @param array $parts parts of the composite expression
* @param string $type AND|OR
*/
public function __construct(array $parts = [], string $type = 'AND')
{
$type = strtoupper($type);
$this->type = $type === 'OR' ? 'OR' : 'AND';
$this->addParts($parts);
}
/**
* Adds a set of expressions to composite expression
*
* @param array $parts
*
* @return CompositeBuilder
*/
public function addParts($parts): CompositeBuilder
{
foreach ($parts as $part) {
$this->addPart($part);
}
return $this;
}
/**
* Adds an expression to composite expression
*
* @param mixed $part
*
* @return CompositeBuilder
*/
public function addPart($part): CompositeBuilder
{
if (!empty($part) || ($part instanceof self && $part->count() > 0)) {
$this->parts[] = $part;
}
return $this;
}
/**
* Return type of this composite
*
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* Retrieves the amount of expressions on composite expression.
*
* @return integer
*/
public function count(): int
{
return count($this->parts);
}
/**
* Retrieve the string representation of this composite expression.
*
* @return string
*/
public function __toString()
{
if ($this->count() === 1) {
return (string) $this->parts[0];
}
return '(' . implode(') ' . $this->type . ' (', $this->parts) . ')';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/AbstractBuilder.php | src/Db/Query/AbstractBuilder.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
use Bluz\Proxy\Db;
use PDO;
/**
* Query Builders classes is responsible to dynamically create SQL queries
* Based on Doctrine QueryBuilder code
*
* @package Bluz\Db\Query
* @link https://github.com/bluzphp/framework/wiki/Db-Query
* @link https://github.com/doctrine/dbal/blob/master/lib/Doctrine/DBAL/Query/QueryBuilder.php
*/
abstract class AbstractBuilder
{
/**
* @var array list of table aliases
*/
protected $aliases = [];
/**
* @var array the query parameters
*/
protected $params = [];
/**
* @var array the parameter type map of this query
*/
protected $types = [];
/**
* @var string the complete SQL string for this query
*/
protected $sql;
/**
* Execute this query using the bound parameters and their types
*
* @return integer|string|array
*/
public function execute()
{
return Db::query($this->getSql(), $this->params, $this->types);
}
/**
* Return the complete SQL string formed by the current specifications
*
* Example
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u')
* ->from('User', 'u');
* echo $qb->getSql(); // SELECT u FROM User u
* </code>
*
* @return string The SQL query string
*/
abstract public function getSql(): string;
/**
* Return the complete SQL string formed for use
*
* Example
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u')
* ->from('User', 'u')
* ->where('id = ?', 42);
* echo $qb->getQuery(); // SELECT u FROM User u WHERE id = "42"
* </code>
*
* @return string
*/
public function getQuery(): string
{
$sql = $this->getSql();
$sql = str_replace(['%', '?'], ['%%', '"%s"'], $sql);
// replace mask by data
return vsprintf($sql, $this->getParams());
}
/**
* Gets a (previously set) query parameter of the query being constructed
*
* @param mixed $key The key (index or name) of the bound parameter
*
* @return mixed The value of the bound parameter.
*/
public function getParam($key)
{
return $this->params[$key] ?? null;
}
/**
* Sets a query parameter for the query being constructed
*
* Example
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u')
* ->from('users', 'u')
* ->where('u.id = :user_id')
* ->setParameter(':user_id', 1);
* </code>
*
* @param string|int|null $key The parameter position or name
* @param mixed $value The parameter value
* @param integer $type PDO::PARAM_*
*
* @return self
*/
public function setParam($key, $value, $type = PDO::PARAM_STR): self
{
if (null === $key) {
$key = count($this->params);
}
$this->params[$key] = $value;
$this->types[$key] = $type;
return $this;
}
/**
* Gets all defined query parameters for the query being constructed
*
* @return array The currently defined query parameters
*/
public function getParams(): array
{
return $this->params;
}
/**
* Sets a collection of query parameters for the query being constructed
*
* Example
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u')
* ->from('users', 'u')
* ->where('u.id = :user_id1 OR u.id = :user_id2')
* ->setParameters([
* ':user_id1' => 1,
* ':user_id2' => 2
* ]);
* </code>
*
* @param array $params The query parameters to set
* @param array $types The query parameters types to set
*
* @return self
*/
public function setParams(array $params, array $types = []): self
{
$this->types = $types;
$this->params = $params;
return $this;
}
/**
* Prepare condition
*
* <code>
* $builder->prepareCondition("WHERE id IN (?)", [..,..]);
* </code>
*
* @param array $args
*
* @return string
*/
protected function prepareCondition(array $args = []): string
{
$condition = array_shift($args);
foreach ($args as &$value) {
if (is_array($value)) {
$replace = implode(',', array_fill(0, count($value), ':REPLACE:'));
$condition = preg_replace('/\?/', $replace, $condition, 1);
foreach ($value as $part) {
$this->setParam(null, $part);
}
} else {
$this->setParam(null, $value);
}
}
unset($value);
$condition = preg_replace('/(\:REPLACE\:)/', '?', $condition);
return $condition;
}
/**
* Gets a string representation of this QueryBuilder which corresponds to
* the final SQL query being constructed.
*
* @return string The string representation of this QueryBuilder.
*/
public function __toString()
{
return $this->getSql();
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Delete.php | src/Db/Query/Delete.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
use Bluz\Proxy\Db;
/**
* Builder of DELETE queries
*
* @package Bluz\Db\Query
*/
class Delete extends AbstractBuilder
{
use Traits\Where;
use Traits\Order;
use Traits\Limit;
/**
* @var string Table name
*/
protected $table;
/**
* {@inheritdoc}
*
* @return string
*/
public function getSql(): string
{
return 'DELETE FROM '
. Db::quoteIdentifier($this->table)
. $this->prepareWhere()
. $this->prepareLimit();
}
/**
* Turns the query being built into a bulk delete query that ranges over
* a certain table
*
* Example
* <code>
* $db = new DeleteBuilder();
* $db
* ->delete('users')
* ->where('id = ?');
* </code>
*
* @param string $table The table whose rows are subject to the update
*
* @return Delete instance
*/
public function delete($table): Delete
{
$this->table = $table;
return $this;
}
/**
* Prepare string to apply limit inside SQL query
*
* @return string
*/
protected function prepareLimit(): string
{
return $this->limit ? ' LIMIT ' . $this->limit : '';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Select.php | src/Db/Query/Select.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query;
use Bluz\Db\Exception\DbException;
use Bluz\Proxy\Db;
/**
* Builder of SELECT queries
*
* @package Bluz\Db\Query
*/
class Select extends AbstractBuilder
{
use Traits\From;
use Traits\Where;
use Traits\Order;
use Traits\Limit;
/**
* <code>
* [
* 'u.id', 'u.name',
* 'p.id', 'p.title'
* ]
* </code>
*
* @var array[]
*/
protected $select = [];
protected $groupBy = [];
protected $having = null;
/**
* @var mixed PDO fetch types or object class
*/
protected $fetchType = \PDO::FETCH_ASSOC;
/**
* {@inheritdoc}
*
* @param integer|string|object $fetchType
*
* @return integer|string|array
*/
public function execute($fetchType = null)
{
if (!$fetchType) {
$fetchType = $this->fetchType;
}
switch ($fetchType) {
case (!is_int($fetchType)):
return Db::fetchObjects($this->getSql(), $this->params, $fetchType);
case \PDO::FETCH_CLASS:
return Db::fetchObjects($this->getSql(), $this->params);
case \PDO::FETCH_ASSOC:
default:
return Db::fetchAll($this->getSql(), $this->params);
}
}
/**
* Setup fetch type, any of PDO, or any Class
*
* @param string $fetchType
*
* @return Select instance
*/
public function setFetchType($fetchType): Select
{
$this->fetchType = $fetchType;
return $this;
}
/**
* {@inheritdoc}
*/
public function getSql(): string
{
return $this->prepareSelect()
. $this->prepareFrom()
. $this->prepareWhere()
. $this->prepareGroupBy()
. $this->prepareHaving()
. $this->prepareOrderBy()
. $this->prepareLimit();
}
/**
* Specifies an item that is to be returned in the query result
* Replaces any previously specified selections, if any
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.id', 'p.id')
* ->from('users', 'u')
* ->leftJoin('u', 'phone', 'p', 'u.id = p.user_id');
* </code>
*
* @param string[] $select the selection expressions
*
* @return Select instance
*/
public function select(...$select): Select
{
$this->select = $select;
return $this;
}
/**
* Adds an item that is to be returned in the query result.
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.id')
* ->addSelect('p.id')
* ->from('users', 'u')
* ->leftJoin('u', 'phone', 'u.id = p.user_id');
* </code>
*
* @param string[] $select the selection expression
*
* @return Select instance
*/
public function addSelect(string ...$select): Select
{
$this->select = array_merge($this->select, $select);
return $this;
}
/**
* Get current select query part
*
* @return array
*/
public function getSelect(): array
{
return $this->select;
}
/**
* Specifies a grouping over the results of the query.
* Replaces any previously specified groupings, if any.
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->groupBy('u.id');
* </code>
*
* @param string[] $groupBy the grouping expression
*
* @return Select instance
*/
public function groupBy(string ...$groupBy): Select
{
$this->groupBy = $groupBy;
return $this;
}
/**
* Adds a grouping expression to the query.
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->groupBy('u.lastLogin');
* ->addGroupBy('u.createdAt')
* </code>
*
* @param string[] $groupBy the grouping expression
*
* @return Select instance
*/
public function addGroupBy(string ...$groupBy): Select
{
$this->groupBy = array_merge($this->groupBy, $groupBy);
return $this;
}
/**
* Specifies a restriction over the groups of the query.
* Replaces any previous having restrictions, if any
*
* @param string[] $conditions the query restriction predicates
*
* @return Select
*/
public function having(...$conditions): Select
{
$this->having = $this->prepareCondition($conditions);
return $this;
}
/**
* Adds a restriction over the groups of the query, forming a logical
* conjunction with any existing having restrictions
*
* @param string[] $conditions the query restriction predicates
*
* @return Select
*/
public function andHaving(...$conditions): Select
{
$condition = $this->prepareCondition($conditions);
if (
$this->having instanceof CompositeBuilder
&& $this->having->getType() === 'AND'
) {
$this->having->addPart($condition);
} else {
$this->having = new CompositeBuilder([$this->having, $condition]);
}
return $this;
}
/**
* Adds a restriction over the groups of the query, forming a logical
* disjunction with any existing having restrictions
*
* @param string[] $conditions the query restriction predicates
*
* @return Select
*/
public function orHaving(...$conditions): Select
{
$condition = $this->prepareCondition($conditions);
if (
$this->having instanceof CompositeBuilder
&& $this->having->getType() === 'OR'
) {
$this->having->addPart($condition);
} else {
$this->having = new CompositeBuilder([$this->having, $condition], 'OR');
}
return $this;
}
/**
* Setup offset like a page number, start from 1
*
* @param integer $page
*
* @return Select
* @throws DbException
*/
public function setPage(int $page = 1): Select
{
if (!$this->limit) {
throw new DbException('Please setup limit for use method `setPage`');
}
$this->offset = $this->limit * ($page - 1);
return $this;
}
/**
* Prepare Select query part
*
* @return string
*/
protected function prepareSelect(): string
{
return 'SELECT ' . implode(', ', $this->select);
}
/**
* prepareWhere
*
* @return string
*/
protected function prepareGroupBy(): string
{
return !empty($this->groupBy) ? ' GROUP BY ' . implode(', ', $this->groupBy) : '';
}
/**
* prepareWhere
*
* @return string
*/
protected function prepareHaving(): string
{
return $this->having ? ' HAVING ' . $this->having : '';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Traits/Order.php | src/Db/Query/Traits/Order.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query\Traits;
/**
* Order Trait
*
* Required for:
* - Select Builder
* - Update Builder
* - Delete Builder
*
* @package Bluz\Db\Query\Traits
* @author Anton Shevchuk
*/
trait Order
{
/**
* @var array
*/
protected $orderBy = [];
/**
* Specifies an ordering for the query results
* Replaces any previously specified orderings, if any
*
* @param string $sort Sort expression
* @param string $order Sort direction (ASC or DESC)
*
* @return $this
*/
public function orderBy(string $sort, string $order = 'ASC'): self
{
$order = 'ASC' === strtoupper($order) ? 'ASC' : 'DESC';
$this->orderBy = [$sort => $order];
return $this;
}
/**
* Adds an ordering to the query results
*
* @param string $sort Sort expression
* @param string $order Sort direction (ASC or DESC)
*
* @return $this
*/
public function addOrderBy(string $sort, string $order = 'ASC'): self
{
$order = 'ASC' === strtoupper($order) ? 'ASC' : 'DESC';
$this->orderBy[$sort] = $order;
return $this;
}
/**
* Prepare string to apply it inside SQL query
*
* @return string
*/
protected function prepareOrderBy(): string
{
if (empty($this->orderBy)) {
return '';
}
$orders = [];
foreach ($this->orderBy as $column => $order) {
$orders[] = $column . ' ' . $order;
}
return ' ORDER BY ' . implode(', ', $orders);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Traits/Where.php | src/Db/Query/Traits/Where.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query\Traits;
use Bluz\Db\Query\CompositeBuilder;
/**
* Order Trait
*
* Required for:
* - Select Builder
* - Update Builder
* - Delete Builder
*
* @package Bluz\Db\Query\Traits
* @author Anton Shevchuk
*/
trait Where
{
/**
* @var string|CompositeBuilder|null
*/
protected $where;
/**
* Set WHERE condition
*
* Specifies one or more restrictions to the query result
* Replaces any previously specified restrictions, if any
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->where('u.id = ?', $id)
* ;
* </code>
*
* @param string[] $conditions optional the query restriction predicates
*
* @return $this
*/
public function where(...$conditions): self
{
$this->where = $this->prepareCondition($conditions);
return $this;
}
/**
* Add WHERE .. AND .. condition
*
* Adds one or more restrictions to the query results, forming a logical
* conjunction with any previously specified restrictions.
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u')
* ->from('users', 'u')
* ->where('u.username LIKE ?', '%Smith%')
* ->andWhere('u.is_active = ?', 1);
* </code>
*
* @param string[] $conditions Optional the query restriction predicates
*
* @return $this
*/
public function andWhere(...$conditions): self
{
$condition = $this->prepareCondition($conditions);
if (
$this->where instanceof CompositeBuilder
&& $this->where->getType() === 'AND'
) {
$this->where->addPart($condition);
} else {
$this->where = new CompositeBuilder([$this->where, $condition]);
}
return $this;
}
/**
* Add WHERE .. OR .. condition
*
* Adds one or more restrictions to the query results, forming a logical
* disjunction with any previously specified restrictions.
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->where('u.id = 1')
* ->orWhere('u.id = ?', 2);
* </code>
*
* @param string[] $conditions Optional the query restriction predicates
*
* @return $this
*/
public function orWhere(...$conditions): self
{
$condition = $this->prepareCondition($conditions);
if (
$this->where instanceof CompositeBuilder
&& $this->where->getType() === 'OR'
) {
$this->where->addPart($condition);
} else {
$this->where = new CompositeBuilder([$this->where, $condition], 'OR');
}
return $this;
}
/**
* prepareWhere
*
* @return string
*/
protected function prepareWhere(): string
{
return $this->where ? ' WHERE ' . $this->where : '';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Traits/From.php | src/Db/Query/Traits/From.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query\Traits;
use Bluz\Proxy\Db;
/**
* From Trait
*
* Required for:
* - Select Builder
* - Delete Builder
*
* @package Bluz\Db\Query\Traits
* @author Anton Shevchuk
*/
trait From
{
/**
* <code>
* [
* 'table' => 'users',
* 'alias' => 'u'
* ]
* </code>
*
* @var array
*/
protected $from = [];
/**
* <code>
* [
* 'u' => [
* 'joinType' => 'inner',
* 'joinTable' => $join,
* 'joinAlias' => $alias,
* 'joinCondition' => $condition
* ]
* </code>
*
* @var array[]
*/
protected $join = [];
/**
* Set FROM
*
* Create and add a query root corresponding to the table identified by the
* given alias, forming a cartesian product with any existing query roots
*
* <code>
* $sb = new SelectBuilder();
* $sb
* ->select('u.id')
* ->from('users', 'u')
* </code>
*
* @param string $from The table
* @param string $alias The alias of the table
*
* @return $this
*/
public function from(string $from, string $alias): self
{
$this->aliases[] = $alias;
$this->from[] = [
'table' => $from,
'alias' => $alias
];
return $this;
}
/**
* Creates and adds a join to the query
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->join('u', 'phone', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause
* @param string $join The table name to join
* @param string $alias The alias of the join table
* @param string $condition The condition for the join
*
* @return $this
*/
public function join(string $fromAlias, string $join, string $alias, string $condition = null): self
{
return $this->innerJoin($fromAlias, $join, $alias, $condition);
}
/**
* Creates and adds a join to the query
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->innerJoin('u', 'phone', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause
* @param string $join The table name to join
* @param string $alias The alias of the join table
* @param string $condition The condition for the join
*
* @return $this
*/
public function innerJoin(string $fromAlias, string $join, string $alias, string $condition = null): self
{
return $this->addJoin('inner', $fromAlias, $join, $alias, $condition);
}
/**
* Creates and adds a left join to the query.
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->leftJoin('u', 'phone', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause
* @param string $join The table name to join
* @param string $alias The alias of the join table
* @param string $condition The condition for the join
*
* @return $this
*/
public function leftJoin(string $fromAlias, string $join, string $alias, string $condition = null): self
{
return $this->addJoin('left', $fromAlias, $join, $alias, $condition);
}
/**
* Creates and adds a right join to the query.
*
* Example
* <code>
* $sb = new Select();
* $sb
* ->select('u.name')
* ->from('users', 'u')
* ->rightJoin('u', 'phone', 'p', 'p.is_primary = 1');
* </code>
*
* @param string $fromAlias The alias that points to a from clause
* @param string $join The table name to join
* @param string $alias The alias of the join table
* @param string $condition The condition for the join
*
* @return $this
*/
public function rightJoin(string $fromAlias, string $join, string $alias, string $condition = null): self
{
return $this->addJoin('right', $fromAlias, $join, $alias, $condition);
}
/**
* addJoin()
*
* @param string $type The type of join
* @param string $fromAlias The alias that points to a from clause
* @param string $join The table name to join
* @param string $alias The alias of the join table
* @param string $condition The condition for the join
*
* @return $this
*/
protected function addJoin(
string $type,
string $fromAlias,
string $join,
string $alias,
string $condition = null
): self {
$this->aliases[] = $alias;
$this->join[$fromAlias][] = [
'joinType' => $type,
'joinTable' => $join,
'joinAlias' => $alias,
'joinCondition' => $condition
];
return $this;
}
/**
* setFromQueryPart
*
* @param string $table
*
* @return self
*/
protected function setFromQueryPart($table): self
{
return $this->from($table, $table);
}
/**
* Prepare From query part
*
* @return string
*/
protected function prepareFrom(): string
{
$fromClauses = [];
// Loop through all FROM clauses
foreach ($this->from as $from) {
$fromClause = Db::quoteIdentifier($from['table']) . ' AS ' . Db::quoteIdentifier($from['alias'])
. $this->prepareJoins($from['alias']);
$fromClauses[$from['alias']] = $fromClause;
}
return ' FROM ' . implode(', ', $fromClauses);
}
/**
* Generate SQL string for JOINs
*
* @param string $fromAlias The alias of the table
*
* @return string
*/
protected function prepareJoins($fromAlias): string
{
if (!isset($this->join[$fromAlias])) {
return '';
}
$query = '';
foreach ($this->join[$fromAlias] as $join) {
$query .= ' ' . strtoupper($join['joinType'])
. ' JOIN ' . Db::quoteIdentifier($join['joinTable']) . ' AS ' . Db::quoteIdentifier($join['joinAlias'])
. ' ON ' . $join['joinCondition'];
$query .= $this->prepareJoins($join['joinAlias']);
}
return $query;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Traits/Set.php | src/Db/Query/Traits/Set.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query\Traits;
use Bluz\Proxy\Db;
use PDO;
/**
* Set Trait
*
* Required for:
* - Insert Builder
* - Update Builder
*
* @package Bluz\Db\Query\Traits
* @author Anton Shevchuk
*/
trait Set
{
/**
* <code>
* [
* '`firstName` = ?',
* '`lastName` = ?'
* ]
* </code>
*
* @var array
*/
protected $set = [];
/**
* Set key-value pair
*
* Sets a new value for a column in a insert/update query
* <code>
* $ub = new UpdateBuilder();
* $ub
* ->update('users')
* ->set('password', md5('password'))
* ->where('id = ?');
* </code>
*
* @param string $key The column to set
* @param string|integer $value The value, expression, placeholder, etc
* @param int $type The type of value on of PDO::PARAM_* params
*
* @return $this
*/
public function set(string $key, $value, $type = PDO::PARAM_STR): self
{
$this->setParam(null, $value, $type);
$this->set[] = Db::quoteIdentifier($key) . ' = ?';
return $this;
}
/**
* Set data from array
*
* <code>
* $ub = new UpdateBuilder();
* $ub
* ->update('users')
* ->setArray([
* 'password' => md5('password')
* 'updated' => date('Y-m-d H:i:s')
* ])
* ->where('u.id = ?');
* </code>
*
* @param array $data
*
* @return $this
*/
public function setArray(array $data): self
{
foreach ($data as $key => $value) {
$this->set($key, $value);
}
return $this;
}
/**
* Prepare string to apply it inside SQL query
*
* @return string
*/
protected function prepareSet(): string
{
return ' SET ' . implode(', ', $this->set);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Query/Traits/Limit.php | src/Db/Query/Traits/Limit.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Query\Traits;
/**
* Limit Trait
*
* Required for:
* - Select Builder
* - Update Builder
* - Delete Builder
*
* @package Bluz\Db\Query\Traits
* @author Anton Shevchuk
*/
trait Limit
{
/**
* @var integer the maximum number of results to retrieve/update/delete
*/
protected $limit;
/**
* @var integer the index of the first result to retrieve.
*/
protected $offset = 0;
/**
* Sets the maximum number of results to retrieve/update/delete
*
* @param integer $limit The maximum number of results to retrieve
* @param integer $offset The offset of the query
*
* @return $this
*/
public function limit(int $limit, int $offset = 0): self
{
$this->setLimit($limit);
$this->setOffset($offset);
return $this;
}
/**
* Setup limit for the query
*
* @param integer $limit
*
* @return $this
*/
public function setLimit(int $limit): self
{
$this->limit = $limit;
return $this;
}
/**
* Setup offset for the query
*
* @param integer $offset
*
* @return $this
*/
public function setOffset(int $offset): self
{
$this->offset = $offset;
return $this;
}
/**
* Prepare string to apply limit inside SQL query
*
* @return string
*/
protected function prepareLimit(): string
{
return $this->limit ? ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset : '';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Exception/RelationNotFoundException.php | src/Db/Exception/RelationNotFoundException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Exception;
/**
* Relation Not Found Exception
*
* @package Bluz\Db\Exception
* @author Eugene Zabolotniy <realbaziak@gmail.com>
*/
class RelationNotFoundException extends DbException
{
/**
* Exception message
*
* @var string
*/
public $message = 'Relation not found';
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Exception/TableNotFoundException.php | src/Db/Exception/TableNotFoundException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Exception;
/**
* Table Not Found Exception
*
* @package Bluz\Db\Exception
* @author Eugene Zabolotniy <realbaziak@gmail.com>
*/
class TableNotFoundException extends DbException
{
/**
* Exception message
*
* @var string
*/
public $message = 'Table not found';
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Exception/DbException.php | src/Db/Exception/DbException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Exception;
use Bluz\Common\Exception\CommonException;
/**
* Exception for Db package
*
* @package Bluz\Db\Exception
* @author Anton Shevchuk
*/
class DbException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Db/Exception/InvalidPrimaryKeyException.php | src/Db/Exception/InvalidPrimaryKeyException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Db\Exception;
/**
* Invalid Primary Key Exception
*
* @package Bluz\Db\Exception
* @author Eugene Zabolotniy
*/
class InvalidPrimaryKeyException extends DbException
{
/**
* Exception message
*
* @var string
*/
public $message = 'Wrong primary key';
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Logger/Logger.php | src/Logger/Logger.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Logger;
use Bluz\Common\Options;
use Psr\Log\AbstractLogger;
/**
* Logger
*
* @package Bluz\Logger
* @author Taras Omelianenko <mail@taras.pro>
* @link https://github.com/bluzphp/framework/wiki/Logger
*/
class Logger extends AbstractLogger
{
use Options;
/**
* @var float start time
*/
protected $startTime;
/**
* @var float part time
*/
protected $timer;
/**
* @var integer
*/
protected $memory = 0;
/**
* @var array list of alerts
*/
protected $alert = [];
/**
* @var array list of critical
*/
protected $critical = [];
/**
* @var array list of debug messages
*/
protected $debug = [];
/**
* @var array list of emergency
*/
protected $emergency = [];
/**
* @var array list of errors
*/
protected $error = [];
/**
* @var array list of info
*/
protected $info = [];
/**
* @var array list of notices
*/
protected $notice = [];
/**
* @var array list of warnings
*/
protected $warning = [];
/**
* Interpolates context values into the message placeholders
*
* @param string $message
* @param array $context
*
* @return string
*/
protected function interpolate(string $message, array $context = []): string
{
// build a replacement array with braces around the context keys
$replace = [];
foreach ($context as $key => $val) {
$replace['{' . $key . '}'] = $val;
}
// interpolate replacement values into the message and return
return strtr($message, $replace);
}
/**
* Log info message
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = []): void
{
$message = $this->interpolate($message, $context);
if (!$this->startTime) {
$this->startTime = $this->timer = $_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true);
}
$curTimer = microtime(true);
$curMemory = memory_get_usage();
$key = sprintf(
'%f :: %f :: %d',
$curTimer - $this->startTime,
$curTimer - $this->timer,
$curMemory - $this->memory
);
$this->info[$key] = $message;
$this->timer = $curTimer;
$this->memory = $curMemory;
}
/**
* Logs with an arbitrary level
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = []): void
{
$this->{$level}[] = $this->interpolate($message, $context);
}
/**
* Get logs records by level
*
* @param $level
*
* @return array
*/
public function get($level): array
{
return $this->{$level};
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Mailer/MailerException.php | src/Mailer/MailerException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Mailer;
use Bluz\Common\Exception\CommonException;
/**
* Exception
*
* @package Bluz\Mailer
* @author Pavel Machekhin
*/
class MailerException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Mailer/Mailer.php | src/Mailer/Mailer.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Mailer;
use Bluz\Common\Exception\ComponentException;
use Bluz\Common\Exception\ConfigurationException;
use Bluz\Common\Options;
use Bluz\Proxy\Translator;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
/**
* Wrapper over PHPMailer
*
* @package Bluz\Mailer
* @author Pavel Machekhin
* @link https://github.com/bluzphp/framework/wiki/Mailer
*/
class Mailer
{
use Options;
/**
* Check Mailer configuration
*
* @throws ConfigurationException
* @return void
*/
public function init(): void
{
if (!$this->getOption('from', 'email')) {
throw new ConfigurationException(
"Missed `from.email` option in `mailer` configuration. <br/>\n" .
"Read more: <a href='https://github.com/bluzphp/framework/wiki/Mailer'>" .
'https://github.com/bluzphp/framework/wiki/Mailer</a>'
);
}
}
/**
* Creates new instance of PHPMailer and set default options from config
*
* @return PHPMailer
* @throws ComponentException
* @throws Exception
*/
public function create(): PHPMailer
{
// can initial, can't use
if (!class_exists(PHPMailer::class)) {
throw new ComponentException(
"PHPMailer library is required for `Bluz\\Mailer` package. <br/>\n" .
"Read more: <a href='https://github.com/bluzphp/framework/wiki/Mailer'>" .
"https://github.com/bluzphp/framework/wiki/Mailer</a>"
);
}
$mail = new PHPMailer();
$mail->WordWrap = 920; // RFC 2822 Compliant for Max 998 characters per line
$fromEmail = $this->getOption('from', 'email');
$fromName = $this->getOption('from', 'name') ?: '';
// setup options from config
$mail->setFrom($fromEmail, $fromName, false);
// setup options
if ($settings = $this->getOption('settings')) {
foreach ($settings as $name => $value) {
$mail->set($name, $value);
}
}
// setup custom headers
if ($headers = $this->getOption('headers')) {
foreach ($headers as $header => $value) {
$mail->addCustomHeader($header, $value);
}
}
return $mail;
}
/**
* Send email
*
* @todo Add mail to queue
*
* @param PHPMailer $mail
*
* @return bool
* @throws MailerException
* @throws Exception
*/
public function send(PHPMailer $mail)
{
if ($template = $this->getOption('subjectTemplate')) {
/** @var string $template */
$mail->Subject = Translator::translate($template, $mail->Subject);
}
if (!$mail->send()) {
// Why you don't use "Exception mode" of PHPMailer
// Because we need our Exception in any case
throw new MailerException('Error mail send: ' . $mail->ErrorInfo);
}
return true;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Request/RequestFactory.php | src/Request/RequestFactory.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Request;
use Bluz\Http\RequestMethod;
use Bluz\Proxy\Request;
use Laminas\Diactoros\ServerRequest;
use Laminas\Diactoros\ServerRequestFactory;
/**
* Request Factory
*
* @package Bluz\Request
* @author Anton Shevchuk
*/
class RequestFactory extends ServerRequestFactory
{
/**
* {@inheritdoc}
*/
public static function fromGlobals(
array $server = null,
array $query = null,
array $body = null,
array $cookies = null,
array $files = null
): ServerRequest {
$request = parent::fromGlobals($server, $query, $body, $cookies, $files);
$contentType = current($request->getHeader('Content-Type'));
// support header like "application/json" and "application/json; charset=utf-8"
if (false !== $contentType && false !== stripos($contentType, Request::TYPE_JSON)) {
$input = file_get_contents('php://input');
$data = (array) json_decode($input, false);
} elseif ($request->getMethod() === RequestMethod::POST) {
$data = $_POST;
} else {
$input = file_get_contents('php://input');
parse_str($input, $data);
}
return $request->withParsedBody($body ?: $data);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Grid.php | src/Grid/Grid.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid;
use Bluz\Common\Exception\CommonException;
use Bluz\Common\Helper;
use Bluz\Common\Options;
use Bluz\Proxy\Request;
use Bluz\Proxy\Router;
use Exception;
/**
* Grid
*
* @package Bluz\Grid
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Grid
*
* @method string filter($column, $filter, $value, $reset = true)
* @method string first()
* @method string last()
* @method string limit($limit = 25)
* @method string next()
* @method string order($column, $order = null, $defaultOrder = Grid::ORDER_ASC, $reset = true)
* @method string page($page = 1)
* @method string pages()
* @method string prev()
* @method string reset()
* @method string total()
*/
abstract class Grid
{
use Options;
use Helper;
public const ORDER_ASC = 'asc';
public const ORDER_DESC = 'desc';
public const FILTER_LIKE = 'like'; // like
public const FILTER_ENUM = 'enum'; // one from .., .., ..
public const FILTER_EQ = 'eq'; // equal to ..
public const FILTER_NE = 'ne'; // not equal to ..
public const FILTER_GT = 'gt'; // greater than ..
public const FILTER_GE = 'ge'; // greater than .. or equal
public const FILTER_LT = 'lt'; // less than ..
public const FILTER_LE = 'le'; // less than .. or equal
/**
* @var Source\AbstractSource instance of Source
*/
protected $adapter;
/**
* @var Data instance of Data
*/
protected $data;
/**
* @var string unique identification of grid
*/
protected $uid;
/**
* @var string unique prefix of grid
*/
protected $prefix = '';
/**
* @var string location of Grid
*/
protected $module;
/**
* @var string location of Grid
*/
protected $controller;
/**
* @var array custom array params
*/
protected $params = [];
/**
* @var integer start from first page
*/
protected $page = 1;
/**
* @var integer limit per page
*/
protected $limit = 25;
/**
* @var integer default value of page limit
* @see Grid::$limit
*/
protected $defaultLimit = 25;
/**
* List of orders
*
* Example
* 'first' => 'ASC',
* 'last' => 'ASC'
*
* @var array
*/
protected $orders = [];
/**
* @var array default order
* @see Grid::$orders
*/
protected $defaultOrder = [];
/**
* @var array list of allow orders
* @see Grid::$orders
*/
protected $allowOrders = [];
/**
* @var array list of filters
*/
protected $filters = [];
/**
* List of allow filters
*
* Example
* ['id', 'status' => ['active', 'disable']]
*
* @var array
* @see Grid::$filters
*/
protected $allowFilters = [];
/**
* List of allow filter names
*
* @var array
* @see Grid::$filters
*/
protected $allowFilterNames = [
self::FILTER_LIKE,
self::FILTER_ENUM,
self::FILTER_EQ,
self::FILTER_NE,
self::FILTER_GT,
self::FILTER_GE,
self::FILTER_LT,
self::FILTER_LE
];
/**
* List of aliases for columns in DB
*
* @var array
*/
protected $aliases = [];
/**
* Grid constructor
*
* @param array|null $options
*
* @throws CommonException
*/
public function __construct(array $options = null)
{
// initial default helper path
$this->addHelperPath(__DIR__ . '/Helper/');
if ($options) {
$this->setOptions($options);
}
if ($this->getUid()) {
$this->prefix = $this->getUid() . '-';
}
$this->init();
$this->processRequest();
}
/**
* Initialize Grid
*
* @return void
*/
abstract public function init(): void;
/**
* Set source adapter
*
* @param Source\AbstractSource $adapter
*
* @return void
*/
public function setAdapter(Source\AbstractSource $adapter): void
{
$this->adapter = $adapter;
}
/**
* Get source adapter
*
* @return Source\AbstractSource
* @throws GridException
*/
public function getAdapter(): Source\AbstractSource
{
if (null === $this->adapter) {
throw new GridException('Grid adapter is not initialized');
}
return $this->adapter;
}
/**
* Get unique Grid Id
*
* @return string
*/
public function getUid(): string
{
return $this->uid;
}
/**
* Get prefix
*
* @return string
*/
public function getPrefix(): string
{
return $this->prefix;
}
/**
* Set module
*
* @param string $module
*
* @return void
*/
public function setModule(string $module): void
{
$this->module = $module;
}
/**
* Get module
*
* @return string
*/
public function getModule(): ?string
{
return $this->module;
}
/**
* Set controller
*
* @param string $controller
*
* @return void
*/
public function setController(string $controller): void
{
$this->controller = $controller;
}
/**
* Get controller
*
* @return string
*/
public function getController(): ?string
{
return $this->controller;
}
/**
* Process request
*
* Example of request url
* - http://domain.com/pages/grid/
* - http://domain.com/pages/grid/page/2/
* - http://domain.com/pages/grid/page/2/order-alias/desc/
* - http://domain.com/pages/grid/page/2/order-created/desc/order-alias/asc/
*
* with prefix for support more than one grid on page
* - http://domain.com/users/grid/users-page/2/users-order-created/desc/
* - http://domain.com/users/grid/users-page/2/users-filter-status/active/
*
* hash support
* - http://domain.com/pages/grid/#/page/2/order-created/desc/order-alias/asc/
*
* @return void
* @throws GridException
*/
public function processRequest(): void
{
$this->module = Request::getModule();
$this->controller = Request::getController();
$page = (int)Request::getParam($this->prefix . 'page', 1);
$this->setPage($page);
$limit = (int)Request::getParam($this->prefix . 'limit', $this->limit);
$this->setLimit($limit);
foreach ($this->allowOrders as $column) {
$alias = $this->applyAlias($column);
$order = Request::getParam($this->prefix . 'order-' . $alias);
if (is_array($order)) {
$order = current($order);
}
if (null !== $order) {
$this->addOrder($column, $order);
}
}
foreach ($this->allowFilters as $column) {
$alias = $this->applyAlias($column);
$filters = (array)Request::getParam($this->prefix . 'filter-' . $alias, []);
foreach ($filters as $filter) {
$filter = trim($filter, ' _-');
if (strpos($filter, '-')) {
/**
* Example of filters
* - http://domain.com/users/grid/users-filter-roleId/gt-2 - roleId greater than 2
* - http://domain.com/users/grid/users-filter-roleId/gt-1_lt-4 - 1 < roleId < 4
* - http://domain.com/users/grid/users-filter-login/eq-admin - login == admin
* - http://domain.com/users/grid/users-filter-login/like-adm - login LIKE `adm`
* - http://domain.com/users/grid/users-filter-login/like-od- - login LIKE `od-`
*/
$filters = explode('_', $filter);
foreach ($filters as $rawFilter) {
[$filterName, $filterValue] = explode('-', $rawFilter, 2);
$this->addFilter($column, $filterName, urldecode($filterValue));
}
} else {
/**
* Example of filters
* - http://domain.com/users/grid/users-filter-roleId/2
* - http://domain.com/users/grid/users-filter-login/admin
*/
$this->addFilter($column, self::FILTER_EQ, $filter);
}
}
}
}
/**
* Process source
*
* @return void
* @throws GridException
*/
public function processSource(): void
{
if (null === $this->adapter) {
throw new GridException('Grid Adapter is not initiated, please update method `init()` and try again');
}
try {
$this->data = $this->getAdapter()->process(
$this->getPage(),
$this->getLimit(),
$this->getFilters(),
$this->getOrders()
);
} catch (Exception $e) {
throw new GridException('Grid Adapter can\'t process request: ' . $e->getMessage());
}
}
/**
* Get data
*
* @return Data
* @throws GridException
*/
public function getData(): Data
{
if (!$this->data) {
$this->processSource();
}
return $this->data;
}
/**
* Setup params
*
* @param $params
*
* @return void
*/
public function setParams($params): void
{
$this->params = $params;
}
/**
* Return params prepared for url builder
*
* @param array $rewrite
*
* @return array
*/
public function getParams(array $rewrite = []): array
{
$params = $this->params;
// change page to first for each new grid (with new filters or orders, or other stuff)
$page = $rewrite['page'] ?? 1;
if ($page > 1) {
$params[$this->prefix . 'page'] = $page;
}
// change limit
$limit = $rewrite['limit'] ?? $this->getLimit();
if ($limit !== $this->defaultLimit) {
$params[$this->prefix . 'limit'] = $limit;
}
// change orders
$orders = $rewrite['orders'] ?? $this->getOrders();
foreach ($orders as $column => $order) {
$column = $this->applyAlias($column);
$params[$this->prefix . 'order-' . $column] = $order;
}
// change filters
$filters = $rewrite['filters'] ?? $this->getFilters();
foreach ($filters as $column => $columnFilters) {
/** @var array $columnFilters */
$column = $this->applyAlias($column);
if (count($columnFilters) === 1 && isset($columnFilters[self::FILTER_EQ])) {
$params[$this->prefix . 'filter-' . $column] = $columnFilters[self::FILTER_EQ];
continue;
}
$columnFilter = [];
foreach ($columnFilters as $filterName => $filterValue) {
$columnFilter[] = $filterName . '-' . $filterValue;
}
$params[$this->prefix . 'filter-' . $column] = implode('_', $columnFilter);
}
return $params;
}
/**
* Get Url
*
* @param array $params
*
* @return string
*/
public function getUrl(array $params): string
{
// prepare params
$params = $this->getParams($params);
// retrieve URL
return Router::getUrl(
$this->getModule(),
$this->getController(),
$params
);
}
/**
* Add column name for allow order
*
* @param string $column
*
* @return void
*/
public function addAllowOrder(string $column): void
{
$this->allowOrders[] = $column;
}
/**
* Set allow orders
*
* @param string[] $orders
*
* @return void
*/
public function setAllowOrders(array $orders = []): void
{
$this->allowOrders = [];
foreach ($orders as $column) {
$this->addAllowOrder($column);
}
}
/**
* Get allow orders
*
* @return array
*/
public function getAllowOrders(): array
{
return $this->allowOrders;
}
/**
* Check order column
*
* @param string $column
*
* @return bool
*/
protected function checkOrderColumn(string $column): bool
{
return in_array($column, $this->getAllowOrders(), true);
}
/**
* Check order name
*
* @param string $order
*
* @return bool
*/
protected function checkOrderName(string $order): bool
{
return ($order === self::ORDER_ASC || $order === self::ORDER_DESC);
}
/**
* Add order rule
*
* @param string $column
* @param string $order
*
* @return void
* @throws GridException
*/
public function addOrder(string $column, string $order = self::ORDER_ASC): void
{
if (!$this->checkOrderColumn($column)) {
throw new GridException("Order for column `$column` is not allowed");
}
if (!$this->checkOrderName($order)) {
throw new GridException("Order name for column `$column` is incorrect");
}
$this->orders[$column] = $order;
}
/**
* Add order rules
*
* @param array $orders
*
* @return void
* @throws GridException
*/
public function addOrders(array $orders): void
{
foreach ($orders as $column => $order) {
$this->addOrder($column, $order);
}
}
/**
* Set order
*
* @param string $column
* @param string $order ASC or DESC
*
* @return void
* @throws GridException
*/
public function setOrder(string $column, string $order = self::ORDER_ASC): void
{
$this->orders = [];
$this->addOrder($column, $order);
}
/**
* Set orders
*
* @param array $orders
*
* @return void
* @throws GridException
*/
public function setOrders(array $orders): void
{
$this->orders = [];
$this->addOrders($orders);
}
/**
* Get orders
*
* @return array
*/
public function getOrders(): array
{
if (empty($this->orders)) {
return $this->getDefaultOrder();
}
return $this->orders;
}
/**
* Add column name to allow filter it
*
* @param string $column
*
* @return void
*/
public function addAllowFilter(string $column): void
{
$this->allowFilters[] = $column;
}
/**
* Set allowed filters
*
* @param string[] $filters
*
* @return void
*/
public function setAllowFilters(array $filters = []): void
{
$this->allowFilters = [];
foreach ($filters as $column) {
$this->addAllowFilter($column);
}
}
/**
* Get allow filters
*
* @return array
*/
public function getAllowFilters(): array
{
return $this->allowFilters;
}
/**
* Check filter column
*
* @param string $column
*
* @return bool
*/
protected function checkFilterColumn(string $column): bool
{
return array_key_exists($column, $this->getAllowFilters()) ||
in_array($column, $this->getAllowFilters(), false);
}
/**
* Check filter
*
* @param string $filter
*
* @return bool
*/
protected function checkFilterName(string $filter): bool
{
return in_array($filter, $this->allowFilterNames, false);
}
/**
* Add filter
*
* @param string $column name
* @param string $filter
* @param string $value
*
* @return void
* @throws GridException
*/
public function addFilter(string $column, string $filter, string $value): void
{
if (!$this->checkFilterColumn($column)) {
throw new GridException("Filter for column `$column` is not allowed");
}
if (!$this->checkFilterName($filter)) {
throw new GridException('Filter name is incorrect');
}
if (!isset($this->filters[$column])) {
$this->filters[$column] = [];
}
$this->filters[$column][$filter] = $value;
}
/**
* Get filter
*
* @param string $column
* @param string|null $filter
*
* @return mixed
*/
public function getFilter(string $column, string $filter = null)
{
if (null === $filter) {
return $this->filters[$column] ?? null;
}
return $this->filters[$column][$filter] ?? null;
}
/**
* Get filters
*
* @return array
*/
public function getFilters(): array
{
return $this->filters;
}
/**
* Add alias for column name
*
* @param string $column
* @param string $alias
*
* @return void
*/
public function addAlias(string $column, string $alias): void
{
$this->aliases[$column] = $alias;
}
/**
* Get column name by alias
*
* @param string $alias
*
* @return string
*/
protected function reverseAlias(string $alias): string
{
return array_search($alias, $this->aliases, true) ?: $alias;
}
/**
* Get alias by column name
*
* @param string $column
*
* @return string
*/
public function applyAlias(string $column): string
{
return $this->aliases[$column] ?? $column;
}
/**
* Set page
*
* @param integer $page
*
* @return void
* @throws GridException
*/
public function setPage(int $page = 1): void
{
if ($page < 1) {
throw new GridException('Wrong page number, should be greater than zero');
}
$this->page = $page;
}
/**
* Get page
*
* @return integer
*/
public function getPage(): int
{
return $this->page;
}
/**
* Set limit per page
*
* @param integer $limit
*
* @return void
* @throws GridException
*/
public function setLimit(int $limit): void
{
if ($limit < 1) {
throw new GridException('Wrong limit value, should be greater than zero');
}
$this->limit = $limit;
}
/**
* Get limit per page
*
* @return integer
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* Set default limit
*
* @param integer $limit
*
* @return void
* @throws GridException
*/
public function setDefaultLimit(int $limit): void
{
if ($limit < 1) {
throw new GridException('Wrong default limit value, should be greater than zero');
}
$this->setLimit($limit);
$this->defaultLimit = $limit;
}
/**
* Get default limit
*
* @return integer
*/
public function getDefaultLimit(): int
{
return $this->defaultLimit;
}
/**
* Set default order
*
* @param string $column
* @param string $order ASC or DESC
*
* @return void
*/
public function setDefaultOrder(string $column, string $order = self::ORDER_ASC): void
{
$this->defaultOrder = [$column => $order];
}
/**
* Get default order
*
* @return array
*/
public function getDefaultOrder(): ?array
{
return $this->defaultOrder;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/GridException.php | src/Grid/GridException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid;
use Bluz\Common\Exception\CommonException;
/**
* Exception
*
* @package Bluz\Grid
*/
class GridException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Data.php | src/Grid/Data.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid;
/**
* Grid Data
*
* @package Bluz\Grid
* @author AntonShevchuk
*/
class Data extends \ArrayIterator
{
/**
* @var integer how many data rows w/out limits
*/
protected $total;
/**
* Set total rows
*
* @param integer $total
*
* @return void
*/
public function setTotal(int $total): void
{
$this->total = $total;
}
/**
* Get total rows
*
* @return integer
*/
public function getTotal(): int
{
return $this->total;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Source/ArraySource.php | src/Grid/Source/ArraySource.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Source;
use Bluz\Grid;
use Bluz\Grid\Data;
/**
* Array Source Adapter for Grid package
*
* @package Bluz\Grid
* @author Anton Shevchuk
*
* @method array getSource()
*/
class ArraySource extends AbstractSource
{
/**
* Set array source
*
* @param array $source
*
* @return void
* @throws Grid\GridException
*/
public function setSource($source): void
{
if (!is_array($source) && !($source instanceof \ArrayAccess)) {
throw new Grid\GridException('Source of `ArraySource` should be array or implement ArrayAccess interface');
}
parent::setSource($source);
}
/**
* {@inheritdoc}
* @throws Grid\GridException
*/
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data
{
// process filters
$this->applyFilters($filters);
// process orders
$this->applyOrders($orders);
$data = $this->getSource();
$total = count($data);
// process pages
$data = \array_slice($data, $limit * ($page - 1), $limit);
$gridData = new Data($data);
$gridData->setTotal($total);
return $gridData;
}
/**
* Apply filters to array
*
* @param array $settings
*
* @return void
* @throws Grid\GridException
*/
private function applyFilters(array $settings): void
{
$data = $this->getSource();
$data = array_filter(
$data,
function ($row) use ($settings) {
foreach ($settings as $column => $filters) {
foreach ($filters as $filter => $value) {
// switch statement for filter
switch ($filter) {
case Grid\Grid::FILTER_EQ:
if ($row[$column] != $value) {
return false;
}
break;
case Grid\Grid::FILTER_NE:
if ($row[$column] == $value) {
return false;
}
break;
case Grid\Grid::FILTER_GT:
if ($row[$column] <= $value) {
return false;
}
break;
case Grid\Grid::FILTER_GE:
if ($row[$column] < $value) {
return false;
}
break;
case Grid\Grid::FILTER_LT:
if ($row[$column] >= $value) {
return false;
}
break;
case Grid\Grid::FILTER_LE:
if ($row[$column] > $value) {
return false;
}
break;
case Grid\Grid::FILTER_LIKE:
if (!preg_match('/' . $value . '/', $row[$column])) {
return false;
}
break;
}
}
}
return true;
}
);
$this->setSource($data);
}
/**
* Apply order to array
*
* @param array $settings
*
* @return void
* @throws Grid\GridException
*/
private function applyOrders(array $settings): void
{
$data = $this->getSource();
// Create empty column stack
$orders = [];
foreach ($settings as $column => $order) {
$orders[$column] = [];
}
// Obtain a list of columns
foreach ($data as $key => $row) {
foreach ($settings as $column => $order) {
$orders[$column][$key] = $row[$column];
}
}
// Prepare array of arguments
$funcArgs = [];
foreach ($settings as $column => $order) {
$funcArgs[] = $orders[$column];
$funcArgs[] = ($order === Grid\Grid::ORDER_ASC) ? SORT_ASC : SORT_DESC;
}
$funcArgs[] = &$data;
// Sort the data with volume descending, edition ascending
// Add $data as the last parameter, to sort by the common key
array_multisort(...$funcArgs);
$this->setSource($data);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Source/SqlSource.php | src/Grid/Source/SqlSource.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Source;
use Bluz\Db;
use Bluz\Grid;
use Bluz\Grid\Data;
use Bluz\Grid\GridException;
use Bluz\Proxy;
/**
* SQL Source Adapter for Grid package
*
* @package Bluz\Grid
* @author Anton Shevchuk
*
* @method string getSource() SQL query
*/
class SqlSource extends AbstractSource
{
/**
* Set SQL source
*
* @param string $source
*
* @return void
* @throws GridException
*/
public function setSource($source): void
{
if (!is_string($source)) {
throw new GridException('Source of `SqlSource` should be string with SQL query');
}
parent::setSource($source);
}
/**
* {@inheritdoc}
*/
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data
{
// process filters
$filters = $this->applyFilters($filters);
// process orders
$orders = $this->applyOrders($orders);
// prepare query
$type = Proxy\Db::getOption('connect', 'type');
if (strtolower($type) === 'mysql') {
// MySQL
$dataSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT SQL_CALC_FOUND_ROWS $1 FROM', $this->source, 1);
$totalSql = 'SELECT FOUND_ROWS()';
} else {
// other
$dataSql = $this->source;
$totalSql = preg_replace('/SELECT\s(.*?)\sFROM/is', 'SELECT COUNT(*) FROM', $this->source, 1);
if (count($filters)) {
$totalSql .= ' WHERE ' . implode(' AND ', $filters);
}
}
if (count($filters)) {
$dataSql .= ' WHERE ' . implode(' AND ', $filters);
}
if (count($orders)) {
$dataSql .= ' ORDER BY ' . implode(', ', $orders);
}
// process pages
$dataSql .= ' LIMIT ' . ($page - 1) * $limit . ', ' . $limit;
// run queries
// use transaction to avoid errors
Proxy\Db::transaction(
function () use (&$data, &$total, $dataSql, $totalSql) {
$data = Proxy\Db::fetchAll($dataSql);
$total = (int)Proxy\Db::fetchOne($totalSql);
}
);
$gridData = new Data($data);
$gridData->setTotal($total);
return $gridData;
}
/**
* Apply filters to SQL query
*
* @param array[] $settings
*
* @return array
*/
private function applyFilters(array $settings): array
{
$where = [];
foreach ($settings as $column => $filters) {
foreach ($filters as $filter => $value) {
if ($filter === Grid\Grid::FILTER_LIKE) {
$value = '%' . $value . '%';
}
$where[] = $column . ' ' .
$this->filters[$filter] . ' ' .
Proxy\Db::quote((string)$value);
}
}
return $where;
}
/**
* Apply order to SQL query
*
* @param array $settings
*
* @return array
*/
private function applyOrders(array $settings): array
{
$orders = [];
// Obtain a list of columns
foreach ($settings as $column => $order) {
$column = Proxy\Db::quoteIdentifier($column);
$orders[] = $column . ' ' . $order;
}
return $orders;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Source/SelectSource.php | src/Grid/Source/SelectSource.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Source;
use Bluz\Db;
use Bluz\Grid;
use Bluz\Grid\Data;
use Bluz\Proxy;
/**
* SQL Source Adapter for Grid package
*
* @package Bluz\Grid
* @author Anton Shevchuk
*
* @method Db\Query\Select getSource()
*/
class SelectSource extends AbstractSource
{
/**
* Set Select source
*
* @param Db\Query\Select $source
*
* @throws Grid\GridException
* @return void
*/
public function setSource($source): void
{
if (!$source instanceof Db\Query\Select) {
throw new Grid\GridException('Source of `SelectSource` should be `Db\\Query\\Select` object');
}
parent::setSource($source);
}
/**
* {@inheritdoc}
*
* @throws Grid\GridException
* @throws Db\Exception\DbException
*/
public function process(int $page, int $limit, array $filters = [], array $orders = []): Data
{
// process filters
$this->applyFilters($filters);
// process orders
$this->applyOrders($orders);
// process pages
$this->getSource()->setLimit($limit);
$this->getSource()->setPage($page);
// prepare query
$type = Proxy\Db::getOption('connect', 'type');
if (strtolower($type) === 'mysql') {
// MySQL
$selectPart = $this->getSource()->getSelect();
$selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0];
$this->getSource()->select(...$selectPart);
$totalSql = 'SELECT FOUND_ROWS()';
} else {
// other
$totalSource = clone $this->getSource();
$totalSource->select('COUNT(*)');
$totalSql = $totalSource->getSql();
}
$data = [];
$total = 0;
// run queries
// use transaction to avoid errors
Proxy\Db::transaction(
function () use (&$data, &$total, $totalSql) {
$data = $this->source->execute();
$total = (int)Proxy\Db::fetchOne($totalSql);
}
);
$gridData = new Data($data);
$gridData->setTotal($total);
return $gridData;
}
/**
* Apply filters to Select
*
* @param array $settings
*
* @return void
* @throws Grid\GridException
*/
private function applyFilters(array $settings): void
{
foreach ($settings as $column => $filters) {
foreach ($filters as $filter => $value) {
if ($filter === Grid\Grid::FILTER_LIKE) {
$value = '%' . $value . '%';
}
$this->getSource()->andWhere($column . ' ' . $this->filters[$filter] . ' ?', $value);
}
}
}
/**
* Apply order to Select
*
* @param array $settings
*
* @return void
* @throws Grid\GridException
*/
private function applyOrders(array $settings): void
{
// Obtain a list of columns
foreach ($settings as $column => $order) {
$this->getSource()->addOrderBy($column, $order);
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Source/AbstractSource.php | src/Grid/Source/AbstractSource.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Source;
use Bluz\Grid\Data;
use Bluz\Grid\Grid;
use Bluz\Grid\GridException;
/**
* Adapter
*
* @package Bluz\Grid
* @author Anton Shevchuk
*/
abstract class AbstractSource
{
/**
* @var mixed source for build grid
*/
protected $source;
/**
* @var array available filters
*/
protected $filters = [
Grid::FILTER_EQ => '=',
Grid::FILTER_NE => '!=',
Grid::FILTER_GT => '>',
Grid::FILTER_GE => '>=',
Grid::FILTER_LT => '<',
Grid::FILTER_LE => '<=',
Grid::FILTER_LIKE => 'like',
];
/**
* Process source
*
* @param int $page
* @param int $limit
* @param array $filters
* @param array $orders
*
* @return Data
*/
abstract public function process(int $page, int $limit, array $filters = [], array $orders = []): Data;
/**
* Setup source adapter
*
* @param mixed $source
*
* @return void
*/
public function setSource($source): void
{
$this->source = $source;
}
/**
* Get source adapter
*
* @return mixed
* @throws GridException
*/
public function getSource()
{
if (!$this->source) {
throw new GridException('Source Adapter should be initialized by `setSource` method');
}
return $this->source;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Order.php | src/Grid/Helper/Order.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @param string $column
* @param null $order
* @param string $defaultOrder
* @param bool $reset
*
* @return string|null $url
*/
function (string $column, $order = null, string $defaultOrder = Grid\Grid::ORDER_ASC, bool $reset = true) {
/**
* @var Grid\Grid $this
*/
if (!$this->checkOrderColumn($column)) {
return null;
}
$orders = $this->getOrders();
// change order
if (null === $order) {
if (isset($orders[$column])) {
$order = ($orders[$column] === Grid\Grid::ORDER_ASC) ?
Grid\Grid::ORDER_DESC : Grid\Grid::ORDER_ASC;
} else {
$order = $defaultOrder;
}
}
// reset to additional sort column
if ($reset) {
$rewrite = ['orders' => []];
} else {
$rewrite = ['orders' => $orders];
}
$rewrite['orders'][$column] = $order;
return $this->getUrl($rewrite);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Page.php | src/Grid/Helper/Page.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @param int $page
*
* @return string|null
*/
function (int $page = 1) {
/**
* @var Grid\Grid $this
*/
if ($page < 1 || $page > $this->pages()) {
return null;
}
return $this->getUrl(['page' => $page]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Pages.php | src/Grid/Helper/Pages.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return integer
* @throws Grid\GridException
*/
function () {
/**
* @var Grid\Grid $this
*/
return (int)ceil($this->getData()->getTotal() / $this->getLimit());
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/First.php | src/Grid/Helper/First.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return string
*/
function () {
/**
* @var Grid\Grid $this
*/
return $this->getUrl(['page' => 1]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Reset.php | src/Grid/Helper/Reset.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return string|null $url
*/
function () {
/**
* @var Grid\Grid $this
*/
return $this->getUrl(['page' => 1, 'filters' => []]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Prev.php | src/Grid/Helper/Prev.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return string|null $url
*/
function () {
/**
* @var Grid\Grid $this
*/
if ($this->getPage() <= 1) {
return null;
}
return $this->getUrl(['page' => $this->getPage() - 1]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Total.php | src/Grid/Helper/Total.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return integer
* @throws Grid\GridException
*/
function () {
/**
* @var Grid\Grid $this
*/
return $this->getData()->getTotal();
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Last.php | src/Grid/Helper/Last.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return string
*/
function () {
/**
* @var Grid\Grid $this
*/
return $this->getUrl(['page' => $this->pages()]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Filter.php | src/Grid/Helper/Filter.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @param string $column
* @param string $filter
* @param string $value
* @param bool $reset
*
* @return string|null $url
*/
function (string $column, string $filter, string $value, bool $reset = true) {
/**
* @var Grid\Grid $this
*/
if (
!$this->checkFilterName($filter) ||
!$this->checkFilterColumn($column)
) {
return null;
}
// reset filters
if ($reset) {
$rewrite = ['filters' => []];
} else {
$rewrite = ['filters' => $this->getFilters()];
}
$rewrite['filters'][$column][$filter] = $value;
return $this->getUrl($rewrite);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Next.php | src/Grid/Helper/Next.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @return string|null
*/
function () {
/**
* @var Grid\Grid $this
*/
if ($this->getPage() >= $this->pages()) {
return null;
}
return $this->getUrl(['page' => $this->getPage() + 1]);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Grid/Helper/Limit.php | src/Grid/Helper/Limit.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Grid\Helper;
use Bluz\Grid;
return
/**
* @param int $limit
*
* @return string
*/
function (int $limit = 25) {
/**
* @var Grid\Grid $this
*/
$rewrite = [];
$rewrite['limit'] = $limit;
if ($limit !== $this->getLimit()) {
$rewrite['page'] = 1;
}
return $this->getUrl($rewrite);
};
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/EventManager/Event.php | src/EventManager/Event.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\EventManager;
/**
* Representation of an event
*
* @package Bluz\EventManager
*/
class Event
{
/**
* @var string event name
*/
protected $name;
/**
* @var string|object the event target
*/
protected $target;
/**
* @var array|object the event parameters
*/
protected $params = [];
/**
* Constructor
*
* Accept a target and its parameters.
*
* @param string $name Event name
* @param string|object $target
* @param array|object $params
*
* @throws EventException
*/
public function __construct(string $name, $target = null, $params = null)
{
$this->setName($name);
if (null !== $target) {
$this->setTarget($target);
}
if (null !== $params) {
$this->setParams($params);
}
}
/**
* Get event name
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Get the event target
*
* This may be either an object, or the name of a static method.
*
* @return string|object
*/
public function getTarget()
{
return $this->target;
}
/**
* Overwrites parameters
*
* @param array|object $params
*
* @return void
* @throws EventException
*/
public function setParams($params): void
{
if (!is_array($params) && !is_object($params)) {
throw new EventException(
'Event parameters must be an array or object; received `' . gettype($params) . '`'
);
}
$this->params = $params;
}
/**
* Get all parameters
*
* @return array|object
*/
public function getParams()
{
return $this->params;
}
/**
* Get an individual parameter
*
* If the parameter does not exist, the $default value will be returned.
*
* @param string|int $name
* @param mixed $default
*
* @return mixed
*/
public function getParam($name, $default = null)
{
if (is_array($this->params)) {
// Check in params that are arrays or implement array access
return $this->params[$name] ?? $default;
} elseif (is_object($this->params)) {
// Check in normal objects
return $this->params->{$name} ?? $default;
} else {
// Wrong type, return default value
return $default;
}
}
/**
* Set the event name
*
* @param string $name
*
* @return void
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* Set the event target/context
*
* @param null|string|object $target
*
* @return void
*/
public function setTarget($target): void
{
$this->target = $target;
}
/**
* Set an individual parameter to a value
*
* @param string|int $name
* @param mixed $value
*
* @return void
*/
public function setParam($name, $value): void
{
if (is_array($this->params)) {
// Arrays or objects implementing array access
$this->params[$name] = $value;
} else {
// Objects
$this->params->{$name} = $value;
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/EventManager/EventManager.php | src/EventManager/EventManager.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\EventManager;
/**
* Event manager
*
* @package Bluz\EventManager
* @link https://github.com/bluzphp/framework/wiki/EventManager
*/
class EventManager
{
/**
* @var array list of listeners
*/
protected $listeners = [];
/**
* Attach callback to event
*
* @param string $eventName
* @param callable $callback
* @param integer $priority
*
* @return void
*/
public function attach(string $eventName, callable $callback, int $priority = 1): void
{
if (!isset($this->listeners[$eventName])) {
$this->listeners[$eventName] = [];
}
if (!isset($this->listeners[$eventName][$priority])) {
$this->listeners[$eventName][$priority] = [];
}
$this->listeners[$eventName][$priority][] = $callback;
}
/**
* Trigger event
*
* @param string|Event $event
* @param string|object $target
* @param array|object $params
*
* @return string|object
* @throws EventException
*/
public function trigger($event, $target = null, $params = null)
{
if (!$event instanceof Event) {
$event = new Event($event, $target, $params);
}
if (false !== strpos($event->getName(), ':')) {
$namespace = substr($event->getName(), 0, strpos($event->getName(), ':'));
if (isset($this->listeners[$namespace])) {
$this->fire($this->listeners[$namespace], $event);
}
}
if (isset($this->listeners[$event->getName()])) {
$this->fire($this->listeners[$event->getName()], $event);
}
return $event->getTarget();
}
/**
* Fire!
*
* @param array $listeners
* @param Event $event
*
* @return void
*/
protected function fire(array $listeners, Event $event): void
{
ksort($listeners);
foreach ($listeners as $list) {
foreach ($list as $listener) {
$result = $listener($event);
if (null === $result) {
// continue;
} elseif (false === $result) {
break 2;
} else {
$event->setTarget($result);
}
}
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/EventManager/EventException.php | src/EventManager/EventException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\EventManager;
use Bluz\Common\Exception\CommonException;
/**
* Exception
*
* @package Bluz\EventManager
* @author Anton Shevchuk
*/
class EventException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Translator/Translator.php | src/Translator/Translator.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Translator;
use Bluz\Common\Exception\ConfigurationException;
use Bluz\Common\Options;
/**
* Translator based on gettext library
*
* @package Bluz\Translator
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Translator
*/
class Translator
{
use Options;
/**
* Locale
*
* @var string
* @link http://www.loc.gov/standards/iso639-2/php/code_list.php
*/
protected $locale = 'en_US';
/**
* @var string text domain
*/
protected $domain = 'messages';
/**
* @var string path to text domain files
*/
protected $path;
/**
* Set domain
*
* @param string $domain
*
* @return void
*/
public function setDomain(string $domain): void
{
$this->domain = $domain;
}
/**
* Set locale
*
* @param string $locale
*
* @return void
*/
public function setLocale(string $locale): void
{
$this->locale = $locale;
}
/**
* Set path to l10n
*
* @param string $path
*
* @return void
*/
public function setPath(string $path): void
{
$this->path = $path;
}
/**
* Initialization
*
* @return void
* @throws ConfigurationException
* @throw \Bluz\Config\ConfigException
*/
public function init(): void
{
// Setup locale
putenv('LC_ALL=' . $this->locale);
putenv('LANG=' . $this->locale);
putenv('LANGUAGE=' . $this->locale);
// Windows workaround
\defined('LC_MESSAGES') ?: \define('LC_MESSAGES', 6);
setlocale(LC_MESSAGES, $this->locale);
// For gettext only
if (\function_exists('gettext')) {
// Setup domain path
$this->addTextDomain($this->domain, $this->path);
// Setup default domain
textdomain($this->domain);
}
}
/**
* Add text domain for gettext
*
* @param string $domain of text for gettext setup
* @param string $path on filesystem
*
* @return void
* @throws ConfigurationException
*/
public function addTextDomain(string $domain, string $path): void
{
// check path
if (!is_dir($path)) {
throw new ConfigurationException("Translator configuration path `$path` not found");
}
bindtextdomain($domain, $path);
// @todo: hardcoded codeset
bind_textdomain_codeset($domain, 'UTF-8');
}
/**
* Translate message
*
* Simple example of usage
* equal to gettext('Message')
*
* Translator::translate('Message');
*
* Simple replace of one or more argument(s)
* equal to sprintf(gettext('Message to %s'), 'Username')
*
* Translator::translate('Message to %s', 'Username');
*
* @param string $message
* @param string[] ...$text
*
* @return string
*/
public static function translate(string $message, ...$text): string
{
if (empty($message)) {
return $message;
}
if (\function_exists('gettext')) {
$message = gettext($message);
}
if (\func_num_args() > 1) {
$message = vsprintf($message, $text);
}
return $message;
}
/**
* Translate plural form
*
* Example of usage plural form + sprintf
* equal to sprintf(ngettext('%d comment', '%d comments', 4), 4)
* Translator::translatePlural('%d comment', '%d comments', 4)
*
* Example of usage plural form + sprintf
* equal to sprintf(ngettext('%d comment', '%d comments', 4), 4, 'Topic')
* Translator::translatePlural('%d comment to %s', '%d comments to %s', 4, 'Topic')
*
* @param string $singular
* @param string $plural
* @param integer $number
* @param string[] ...$text
*
* @return string
* @link http://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html
*/
public static function translatePlural(string $singular, string $plural, $number, ...$text): string
{
if (\function_exists('ngettext')) {
$message = ngettext($singular, $plural, $number);
} else {
$message = $singular;
}
if (\func_num_args() > 3) {
// first element is number
array_unshift($text, $number);
$message = vsprintf($message, $text);
}
return $message;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Nil.php | src/Common/Nil.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
/**
* It's just null class
*
* @package Bluz\Common
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Trait-Nil
*
* @method null get($key)
* @method null set($key, $value)
*/
class Nil
{
/**
* Magic call
*
* @param string $method
* @param array $args
*
* @return null
*/
public function __call($method, $args)
{
return null;
}
/**
* Magic call for static
*
* @param string $method
* @param array $args
*
* @return null
*/
public static function __callStatic($method, $args)
{
return null;
}
/**
* Magic __get
*
* @param string $key
*
* @return null
*/
public function __get($key)
{
return null;
}
/**
* Magic __set
*
* @param string $key
* @param mixed $value
*
* @return null
*/
public function __set($key, $value)
{
return null;
}
/**
* Magic __isset
*
* @param string $key
*
* @return false
*/
public function __isset($key)
{
return false;
}
/**
* Cast to empty string
*
* @return string
*/
public function __toString()
{
return '';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Options.php | src/Common/Options.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
use Bluz\Collection\Collection;
/**
* Options Trait
*
* Example of usage
* class Foo
* {
* use \Bluz\Common\Options;
*
* protected $bar = '';
* protected $baz = '';
*
* public function setBar($value)
* {
* $this->bar = $value;
* }
*
* public function setBaz($value)
* {
* $this->baz = $value;
* }
* }
*
* $Foo = new Foo();
* $Foo->setOptions(['bar'=>123, 'baz'=>456]);
*
* @package Bluz\Common
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Trait-Options
*/
trait Options
{
/**
* @var array options store
*/
protected $options = [];
/**
* Get option by key
*
* @param string $key
* @param array $keys
*
* @return mixed
*/
public function getOption(string $key, ...$keys)
{
$method = 'get' . Str::toCamelCase($key);
if (method_exists($this, $method)) {
return $this->$method($key, ...$keys);
}
return Collection::get($this->options, $key, ...$keys);
}
/**
* Set option by key over setter
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function setOption(string $key, $value): void
{
$method = 'set' . Str::toCamelCase($key);
if (method_exists($this, $method)) {
$this->$method($value);
} else {
$this->options[$key] = $value;
}
}
/**
* Get all options
*
* @return array
*/
public function getOptions(): array
{
return $this->options;
}
/**
* Setup, check and init options
*
* Requirements
* - options must be a array
* - options can be null
*
* @param array|null $options
*
* @return void
*/
public function setOptions(?array $options = null): void
{
// store options by default
$this->options = (array)$options;
// apply options
foreach ($this->options as $key => $value) {
$this->setOption($key, $value);
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Helper.php | src/Common/Helper.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
use Bluz\Common\Exception\CommonException;
use Closure;
/**
* Helper trait
*
* @package Bluz\Common
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Trait-Helper
*/
trait Helper
{
/**
* @var array[] list of helpers
*/
protected static $helpers = [];
/**
* @var array[] list of helpers paths
*/
protected static $helpersPath = [];
/**
* Add helper path
*
* @param string $path
*
* @return void
* @throws CommonException
*/
public function addHelperPath(string $path): void
{
$class = static::class;
$realPath = realpath($path);
if (false === $realPath) {
throw new CommonException("Invalid Helper path `$path` for class `$class`");
}
// create store of helpers
if (!isset(static::$helpersPath[$class])) {
static::$helpersPath[$class] = [];
}
if (!in_array($realPath, static::$helpersPath[$class], true)) {
static::$helpersPath[$class][] = $realPath;
}
}
/**
* Call magic helper
*
* @param string $method
* @param array $arguments
*
* @return mixed
* @throws CommonException
*/
public function __call($method, $arguments)
{
$class = static::class;
// Call callable helper structure (function or class)
if (!isset(static::$helpers[$class][$method])) {
$this->loadHelper($method);
}
/** @var Closure $helper */
$helper = static::$helpers[$class][$method];
return $helper->call($this, ...$arguments);
}
/**
* Call helper
*
* @param string $name
*
* @return void
* @throws CommonException
*/
private function loadHelper(string $name): void
{
$class = static::class;
// Somebody forgot to call `addHelperPath`
if (!isset(static::$helpersPath[$class])) {
throw new CommonException("Helper path not found for class `$class`");
}
// Try to find helper file
foreach (static::$helpersPath[$class] as $path) {
if ($helperPath = realpath($path . '/' . ucfirst($name) . '.php')) {
$this->addHelper($name, $helperPath);
return;
}
}
throw new CommonException("Helper `$name` not found for class `$class`");
}
/**
* Add helper callable
*
* @param string $name
* @param string $path
*
* @return void
* @throws CommonException
*/
private function addHelper(string $name, string $path): void
{
$class = static::class;
// create store of helpers for this class
if (!isset(static::$helpers[$class])) {
static::$helpers[$class] = [];
}
$helper = include $path;
if (is_callable($helper)) {
static::$helpers[$class][$name] = $helper;
} else {
throw new CommonException("Helper `$name` not found in file `$path`");
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Instance.php | src/Common/Instance.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
/**
* Instance
*
* @package Bluz\Common
* @author Anton Shevchuk
*/
trait Instance
{
/**
* Get instance
* @return static
*/
public static function getInstance()
{
static $instance;
if (null === $instance) {
$instance = new static();
}
return $instance;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Str.php | src/Common/Str.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
/**
* Line is string :)
*
* @package Bluz\Common
* @author Anton Shevchuk
*/
class Str
{
/**
* Convert string to CamelCase
*
* @param string $subject
*
* @return string
*/
public static function toCamelCase(string $subject): string
{
$subject = str_replace(['_', '-'], ' ', strtolower($subject));
return str_replace(' ', '', ucwords($subject));
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Singleton.php | src/Common/Singleton.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common;
/**
* Singleton
*
* @package Bluz\Common
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Trait-Singleton
*/
trait Singleton
{
/**
* @var static singleton instance
*/
protected static $instance;
/**
* Get instance
*
* @return static
*/
public static function getInstance()
{
return static::$instance ?? (static::$instance = static::initInstance());
}
/**
* Initialization of class instance
*
* @return static
*/
private static function initInstance()
{
return new static();
}
/**
* Reset instance
*
* @return void
*/
public static function resetInstance(): void
{
static::$instance = null;
}
/**
* Disabled by access level
*/
private function __construct()
{
}
/**
* Disabled by access level
*/
private function __clone()
{
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Container/ArrayAccess.php | src/Common/Container/ArrayAccess.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Container;
use InvalidArgumentException;
/**
* Container implements ArrayAccess
*
* @package Bluz\Common
* @author Anton Shevchuk
* @see ArrayAccess
*
* @method void doSetContainer(string $key, $value)
* @method mixed doGetContainer(string $key)
* @method bool doContainsContainer(string $key)
* @method void doDeleteContainer(string $key)
*/
trait ArrayAccess
{
/**
* Offset to set
*
* @param mixed $offset
* @param mixed $value
*
* @throws InvalidArgumentException
*/
public function offsetSet($offset, $value): void
{
if (null === $offset) {
throw new InvalidArgumentException('Class `Common\Container\ArrayAccess` support only associative arrays');
}
$this->doSetContainer($offset, $value);
}
/**
* Offset to retrieve
*
* @param mixed $offset
*
* @return mixed
*/
public function offsetGet($offset)
{
return $this->doGetContainer($offset);
}
/**
* Whether a offset exists
*
* @param mixed $offset
*
* @return bool
*/
public function offsetExists($offset): bool
{
return $this->doContainsContainer($offset);
}
/**
* Offset to unset
*
* @param mixed $offset
*/
public function offsetUnset($offset): void
{
$this->doDeleteContainer($offset);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Container/RegularAccess.php | src/Common/Container/RegularAccess.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Container;
/**
* Implements regular access to container
*
* @package Bluz\Common
* @author Anton Shevchuk
*
* @method void doSetContainer(string $key, $value)
* @method mixed doGetContainer(string $key)
* @method bool doContainsContainer(string $key)
* @method void doDeleteContainer(string $key)
*/
trait RegularAccess
{
/**
* Set key/value pair
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function set($key, $value): void
{
$this->doSetContainer($key, $value);
}
/**
* Get value by key
*
* @param string $key
*
* @return mixed
*/
public function get($key)
{
return $this->doGetContainer($key);
}
/**
* Check contains key in container
*
* @param string $key
*
* @return bool
*/
public function contains($key): bool
{
return $this->doContainsContainer($key);
}
/**
* Delete value by key
*
* @param string $key
*
* @return void
*/
public function delete($key): void
{
$this->doDeleteContainer($key);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Container/Container.php | src/Common/Container/Container.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Container;
/**
* Container of data for object
*
* @package Bluz\Common
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Trait-Container
*/
trait Container
{
/**
* @var array Container of elements
*/
protected $container = [];
/**
* Set key/value pair
*
* @param string $key
* @param mixed $value
*
* @return void
*/
protected function doSetContainer(string $key, $value): void
{
$this->container[$key] = $value;
}
/**
* Get value by key
*
* @param string $key
*
* @return mixed
*/
protected function doGetContainer(string $key)
{
if ($this->doContainsContainer($key)) {
return $this->container[$key];
}
return null;
}
/**
* Check contains key in container
*
* @param string $key
*
* @return bool
*/
protected function doContainsContainer(string $key): bool
{
return array_key_exists($key, $this->container);
}
/**
* Delete value by key
*
* @param string $key
*
* @return void
*/
protected function doDeleteContainer(string $key): void
{
unset($this->container[$key]);
}
/**
* Sets all data in the row from an array
*
* @param array $data
*
* @return void
*/
public function setFromArray(array $data): void
{
foreach ($data as $key => $value) {
$this->container[$key] = $value;
}
}
/**
* Returns the column/value data as an array
*
* @return array
*/
public function toArray(): array
{
return $this->container;
}
/**
* Reset container array
*
* @return void
*/
public function resetArray(): void
{
foreach ($this->container as &$value) {
$value = null;
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Container/MagicAccess.php | src/Common/Container/MagicAccess.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Container;
/**
* Implements magic access to container
*
* @package Bluz\Common
* @author Anton Shevchuk
*
* @method void doSetContainer(string $key, $value)
* @method mixed doGetContainer(string $key)
* @method bool doContainsContainer(string $key)
* @method void doDeleteContainer(string $key)
*/
trait MagicAccess
{
/**
* Magic alias for set() regular method
*
* @param string $key
* @param mixed $value
*
* @return void
*/
public function __set(string $key, $value): void
{
$this->doSetContainer($key, $value);
}
/**
* Magic alias for get() regular method
*
* @param string $key
*
* @return mixed
*/
public function __get(string $key)
{
return $this->doGetContainer($key);
}
/**
* Magic alias for contains() regular method
*
* @param string $key
*
* @return bool
*/
public function __isset(string $key): bool
{
return $this->doContainsContainer($key);
}
/**
* Magic alias for delete() regular method
*
* @param string $key
*
* @return void
*/
public function __unset(string $key): void
{
$this->doDeleteContainer($key);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Container/JsonSerialize.php | src/Common/Container/JsonSerialize.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Container;
/**
* Container implements JsonSerializable interface
*
* @package Bluz\Common
* @author Anton Shevchuk
* @see JsonSerializable
*/
trait JsonSerialize
{
/**
* Specify data which should be serialized to JSON
*
* @return array
*/
public function jsonSerialize()
{
return $this->toArray();
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Exception/ConfigurationException.php | src/Common/Exception/ConfigurationException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Exception;
/**
* Exception throws by component for wrong configuration
*
* @package Bluz\Common\Exception
* @author Anton Shevchuk
*/
class ConfigurationException extends ComponentException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Exception/ComponentException.php | src/Common/Exception/ComponentException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Exception;
/**
* Exception throws by component for wrong requirements
*
* @package Bluz\Common\Exception
* @author Anton Shevchuk
*/
class ComponentException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Common/Exception/CommonException.php | src/Common/Exception/CommonException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Common\Exception;
use Bluz\Http\StatusCode;
/**
* Basic Exception for Bluz framework
*
* @package Bluz\Common\Exception
* @author Anton Shevchuk
*/
class CommonException extends \Exception
{
/**
* @var integer Used as default HTTP code for exceptions
*/
protected $code = StatusCode::INTERNAL_SERVER_ERROR;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Acl/Acl.php | src/Acl/Acl.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Acl;
use Bluz\Common\Options;
use Bluz\Proxy\Auth;
/**
* Acl
*
* @package Bluz\Acl
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Acl
*/
class Acl
{
use Options;
/**
* Check user access by pair module-privilege
*
* @param string $module
* @param string|null $privilege
*
* @return bool
*/
public function isAllowed(string $module, ?string $privilege): bool
{
if ($privilege) {
$user = Auth::getIdentity();
return $user && $user->hasPrivilege($module, $privilege);
}
return true;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Acl/AclException.php | src/Acl/AclException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Acl;
use Bluz\Http\Exception\ForbiddenException;
/**
* Acl Exception
*
* @package Bluz\Acl
* @author Anton Shevchuk
*/
class AclException extends ForbiddenException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/IdentityInterface.php | src/Auth/IdentityInterface.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth;
/**
* Interface EntityInterface
*
* @package Bluz\Auth
*/
interface IdentityInterface
{
/**
* Get an ID that can uniquely identify a user
*
* @return integer
*/
public function getId(): ?int;
/**
* Get user's privileges
*
* @return array
*/
public function getPrivileges(): array;
/**
* Has it privilege?
*
* @param string $module
* @param string $privilege
*
* @return bool
*/
public function hasPrivilege($module, $privilege): bool;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/AbstractIdentity.php | src/Auth/AbstractIdentity.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth;
use Bluz\Db\Row;
/**
* Abstract class for Users\Row
*
* @package Bluz\Auth
*
* @property integer $id
* @property string $login
* @property string $email
*/
abstract class AbstractIdentity extends Row implements IdentityInterface
{
/**
* {@inheritdoc}
*/
abstract public function getPrivileges(): array;
/**
* {@inheritdoc}
*/
public function getId(): ?int
{
return $this->id ? (int)$this->id : null;
}
/**
* {@inheritdoc}
*/
public function hasPrivilege($module, $privilege): bool
{
$privileges = $this->getPrivileges();
return in_array("$module:$privilege", $privileges, true);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/Auth.php | src/Auth/Auth.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth;
use Bluz\Common\Options;
use Bluz\Proxy\Request;
use Bluz\Proxy\Session;
/**
* Auth class
*
* @package Bluz\Auth
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Auth
*/
class Auth
{
use Options;
/**
* @var IdentityInterface Instance of EntityInterface
*/
protected $identity;
/**
* Setup identity
*
* @param IdentityInterface $identity
*
* @return void
*/
public function setIdentity(IdentityInterface $identity): void
{
// save identity to Auth
$this->identity = $identity;
// regenerate session
if (PHP_SAPI !== 'cli') {
Session::regenerateId();
}
// save identity to session
Session::set('auth:identity', $identity);
// save user agent to session
Session::set('auth:agent', Request::getServer('HTTP_USER_AGENT'));
}
/**
* Return identity if user agent is correct
*
* @return IdentityInterface|null
*/
public function getIdentity(): ?IdentityInterface
{
if (!$this->identity) {
// check user agent
if (Session::get('auth:agent') === Request::getServer('HTTP_USER_AGENT')) {
$this->identity = Session::get('auth:identity');
} else {
$this->clearIdentity();
}
}
return $this->identity;
}
/**
* Clear identity and user agent information
*
* @return void
*/
public function clearIdentity(): void
{
$this->identity = null;
Session::delete('auth:identity');
Session::delete('auth:agent');
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/AuthException.php | src/Auth/AuthException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth;
use Bluz\Http\Exception\UnauthorizedException;
/**
* Auth Exception
*
* @package Bluz\Auth
* @author Anton Shevchuk
*/
class AuthException extends UnauthorizedException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/Model/AbstractTable.php | src/Auth/Model/AbstractTable.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth\Model;
use Bluz\Db\Exception\DbException;
use Bluz\Db\Exception\InvalidPrimaryKeyException;
use Bluz\Db\RowInterface;
use Bluz\Db\Table;
use InvalidArgumentException;
/**
* Abstract class for Auth\Table
*
* @package Bluz\Auth
* @author Anton Shevchuk
*/
abstract class AbstractTable extends Table
{
/**
* Types
*/
public const TYPE_ACCESS = 'access';
public const TYPE_REQUEST = 'request';
/**
* Providers
* - equals - login + password
* - token - token with ttl
* - cookie - cookie token with ttl
*/
public const PROVIDER_COOKIE = 'cookie';
public const PROVIDER_EQUALS = 'equals';
public const PROVIDER_FACEBOOK = 'facebook';
public const PROVIDER_GOOGLE = 'google';
public const PROVIDER_LDAP = 'ldap';
public const PROVIDER_TOKEN = 'token';
public const PROVIDER_TWITTER = 'twitter';
/**
* @var string Table
*/
protected $name = 'auth';
/**
* @var array Primary key(s)
*/
protected $primary = ['provider', 'foreignKey'];
/**
* Get AuthRow
*
* @param string $provider
* @param string $foreignKey
*
* @return RowInterface
* @throws InvalidArgumentException
* @throws DbException
* @throws InvalidPrimaryKeyException
*/
public static function getAuthRow(string $provider, string $foreignKey): ?RowInterface
{
return static::findRow(['provider' => $provider, 'foreignKey' => $foreignKey]);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Auth/Model/AbstractRow.php | src/Auth/Model/AbstractRow.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Auth\Model;
use Bluz\Db\Row;
/**
* Abstract class for Auth\Row
*
* @package Bluz\Auth
* @author Anton Shevchuk
*
* @property integer $userId
* @property string $provider
* @property string $foreignKey
* @property string $token
* @property string $tokenSecret
* @property string $tokenType
* @property string $created
* @property string $updated
* @property string $expired
*/
abstract class AbstractRow extends Row
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Router/RouterException.php | src/Router/RouterException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Router;
use Bluz\Common\Exception\CommonException;
/**
* Exception
*
* @package Bluz\Router
* @author Anton Shevchuk
*/
class RouterException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Router/Router.php | src/Router/Router.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Router;
use Bluz\Application\Application;
use Bluz\Common\Exception\CommonException;
use Bluz\Common\Exception\ComponentException;
use Bluz\Common\Options;
use Bluz\Controller\Controller;
use Bluz\Controller\ControllerException;
use Bluz\Proxy\Cache;
use Bluz\Proxy\Request;
use ReflectionException;
/**
* Router
*
* @package Bluz\Router
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Router
*/
class Router
{
use Options;
/**
* Or should be as properties?
*/
private const DEFAULT_MODULE = 'index';
private const DEFAULT_CONTROLLER = 'index';
private const ERROR_MODULE = 'error';
private const ERROR_CONTROLLER = 'index';
/**
* @var string base URL
*/
protected $baseUrl;
/**
* @var string REQUEST_URI minus Base URL
*/
protected $cleanUri;
/**
* @var string default module
*/
protected $defaultModule = self::DEFAULT_MODULE;
/**
* @var string default Controller
*/
protected $defaultController = self::DEFAULT_CONTROLLER;
/**
* @var string error module
*/
protected $errorModule = self::ERROR_MODULE;
/**
* @var string error Controller
*/
protected $errorController = self::ERROR_CONTROLLER;
/**
* @var array instance parameters
*/
protected $params = [];
/**
* @var array instance raw parameters
*/
protected $rawParams = [];
/**
* @var array[] routers map
*/
protected $routers = [];
/**
* @var array[] reverse map
*/
protected $reverse = [];
/**
* Constructor of Router
*/
public function __construct()
{
$routers = Cache::get('router.routers');
$reverse = Cache::get('router.reverse');
if (!$routers || !$reverse) {
[$routers, $reverse] = $this->prepareRouterData();
Cache::set('router.routers', $routers, Cache::TTL_NO_EXPIRY, ['system']);
Cache::set('router.reverse', $reverse, Cache::TTL_NO_EXPIRY, ['system']);
}
$this->routers = $routers;
$this->reverse = $reverse;
}
/**
* Initial routers data from controllers
*
* @return array[]
* @throws CommonException
* @throws ComponentException
* @throws ControllerException
* @throws ReflectionException
*/
private function prepareRouterData(): array
{
$routers = [];
$reverse = [];
$path = Application::getInstance()->getPath() . '/modules/*/controllers/*.php';
foreach (new \GlobIterator($path) as $file) {
/* @var \SplFileInfo $file */
$module = $file->getPathInfo()->getPathInfo()->getBasename();
$controller = $file->getBasename('.php');
$controllerInstance = new Controller($module, $controller);
$meta = $controllerInstance->getMeta();
if ($routes = $meta->getRoute()) {
foreach ($routes as $route => $pattern) {
if (!isset($reverse[$module])) {
$reverse[$module] = [];
}
$reverse[$module][$controller] = ['route' => $route, 'params' => $meta->getParams()];
$rule = [
$route => [
'pattern' => $pattern,
'module' => $module,
'controller' => $controller,
'params' => $meta->getParams()
]
];
// static routers should be first, than routes with variables `$...`
// all routes begin with slash `/`
if (strpos($route, '$')) {
$routers[] = $rule;
} else {
array_unshift($routers, $rule);
}
}
}
}
$routers = array_merge(...$routers);
return [$routers, $reverse];
}
/**
* Get the base URL.
*
* @return string
*/
public function getBaseUrl(): string
{
return $this->baseUrl;
}
/**
* Set the base URL.
*
* @param string $baseUrl
*
* @return void
*/
public function setBaseUrl(string $baseUrl): void
{
$this->baseUrl = str_trim_end($baseUrl, '/');
}
/**
* Get an action parameter
*
* @param mixed $key
* @param mixed $default Default value to use if key not found
*
* @return mixed
*/
public function getParam($key, $default = null)
{
return $this->params[$key] ?? $default;
}
/**
* Set an action parameter
*
* A $value of null will unset the $key if it exists
*
* @param mixed $key
* @param mixed $value
*
* @return void
*/
public function setParam($key, $value): void
{
$key = (string)$key;
if (null === $value) {
unset($this->params[$key]);
} else {
$this->params[$key] = $value;
}
}
/**
* Get parameters
*
* @return array
*/
public function getParams(): array
{
return $this->params;
}
/**
* Get raw params, w/out module and controller
*
* @return array
*/
public function getRawParams(): array
{
return $this->rawParams;
}
/**
* Get default module
*
* @return string
*/
public function getDefaultModule(): string
{
return $this->defaultModule;
}
/**
* Set default module
*
* @param string $defaultModule
*
* @return void
*/
public function setDefaultModule(string $defaultModule): void
{
$this->defaultModule = $defaultModule;
}
/**
* Get default controller
*
* @return string
*/
public function getDefaultController(): string
{
return $this->defaultController;
}
/**
* Set default controller
*
* @param string $defaultController
*
* @return void
*/
public function setDefaultController(string $defaultController): void
{
$this->defaultController = $defaultController;
}
/**
* Get error module
*
* @return string
*/
public function getErrorModule(): string
{
return $this->errorModule;
}
/**
* Set error module
*
* @param string $errorModule
*
* @return void
*/
public function setErrorModule(string $errorModule): void
{
$this->errorModule = $errorModule;
}
/**
* Get error controller
*
* @return string
*/
public function getErrorController(): string
{
return $this->errorController;
}
/**
* Set error controller
*
* @param string $errorController
*
* @return void
*/
public function setErrorController(string $errorController): void
{
$this->errorController = $errorController;
}
/**
* Get the request URI without baseUrl
*
* @return string
*/
public function getCleanUri(): string
{
if ($this->cleanUri === null) {
$uri = Request::getUri()->getPath();
if ($this->getBaseUrl() && strpos($uri, $this->getBaseUrl()) === 0) {
$uri = substr($uri, strlen($this->getBaseUrl()));
}
$this->cleanUri = $uri;
}
return $this->cleanUri;
}
/**
* Build URL to controller
*
* @param string|null $module
* @param string|null $controller
* @param array $params
*
* @return string
*/
public function getUrl(
?string $module = self::DEFAULT_MODULE,
?string $controller = self::DEFAULT_CONTROLLER,
array $params = []
): string {
$module = $module ?? Request::getModule();
$controller = $controller ?? Request::getController();
if (isset($this->reverse[$module][$controller])) {
return $this->urlCustom($module, $controller, $params);
}
return $this->urlRoute($module, $controller, $params);
}
/**
* Build full URL to controller
*
* @param string $module
* @param string $controller
* @param array $params
*
* @return string
*/
public function getFullUrl(
string $module = self::DEFAULT_MODULE,
string $controller = self::DEFAULT_CONTROLLER,
array $params = []
): string {
$scheme = Request::getUri()->getScheme() . '://';
$host = Request::getUri()->getHost();
$port = Request::getUri()->getPort();
if ($port && !in_array($port, [80, 443], true)) {
$host .= ':' . $port;
}
$url = $this->getUrl($module, $controller, $params);
return $scheme . $host . $url;
}
/**
* Build URL by custom route
*
* @param string $module
* @param string $controller
* @param array $params
*
* @return string
*/
protected function urlCustom(string $module, string $controller, array $params): string
{
$url = $this->reverse[$module][$controller]['route'];
$getParams = [];
foreach ($params as $key => $value) {
// sub-array as GET params
if (is_array($value)) {
$getParams[$key] = $value;
continue;
}
if (is_numeric($value)) {
$value = (string) $value;
}
$url = str_replace('{$' . $key . '}', $value, $url, $replaced);
// if not replaced, setup param as GET
if (!$replaced) {
$getParams[$key] = $value;
}
}
// clean optional params
$url = preg_replace('/\{\$[a-z0-9-_]+\}/i', '', $url);
// clean regular expression (.*)
$url = preg_replace('/\(\.\*\)/', '', $url);
// replace "//" with "/"
$url = str_replace('//', '/', $url);
if (!empty($getParams)) {
$url .= '?' . http_build_query($getParams);
}
return $this->getBaseUrl() . ltrim($url, '/');
}
/**
* Build URL by default route
*
* @param string $module
* @param string $controller
* @param array $params
*
* @return string
*/
protected function urlRoute(string $module, string $controller, array $params): string
{
$url = $this->getBaseUrl();
if (empty($params) && $controller === self::DEFAULT_CONTROLLER) {
if ($module === self::DEFAULT_MODULE) {
return $url;
}
return $url . $module;
}
$url .= $module . '/' . $controller;
$getParams = [];
foreach ($params as $key => $value) {
// sub-array as GET params
if (is_array($value)) {
$getParams[$key] = $value;
continue;
}
$url .= '/' . urlencode((string)$key) . '/' . urlencode((string)$value);
}
if (!empty($getParams)) {
$url .= '?' . http_build_query($getParams);
}
return $url;
}
/**
* Process routing
*
* @return void
*/
public function process(): void
{
$this->processDefault() || // try to process default router (homepage)
$this->processCustom() || // or custom routers
$this->processRoute(); // or default router schema
$this->resetRequest();
}
/**
* Process default router
*
* @return bool
*/
protected function processDefault(): bool
{
$uri = $this->getCleanUri();
return empty($uri);
}
/**
* Process custom router
*
* @return bool
*/
protected function processCustom(): bool
{
$uri = '/' . $this->getCleanUri();
foreach ($this->routers as $router) {
if (preg_match($router['pattern'], $uri, $matches)) {
$this->setParam('_module', $router['module']);
$this->setParam('_controller', $router['controller']);
foreach ($router['params'] as $param => $type) {
if (isset($matches[$param])) {
$this->setParam($param, $matches[$param]);
}
}
return true;
}
}
return false;
}
/**
* Process router by default rules
*
* Default routers examples
* /
* /:module/
* /:module/:controller/
* /:module/:controller/:key1/:value1/:key2/:value2...
*
* @return bool
*/
protected function processRoute(): bool
{
$uri = $this->getCleanUri();
$uri = trim($uri, '/');
$raw = explode('/', $uri);
// rewrite module from request
if (count($raw)) {
$this->setParam('_module', array_shift($raw));
}
// rewrite module from controller
if (count($raw)) {
$this->setParam('_controller', array_shift($raw));
}
if ($size = count($raw)) {
// save raw
$this->rawParams = $raw;
// save as index params
foreach ($raw as $i => $value) {
$this->setParam($i, $value);
}
// remove tail
if ($size % 2 === 1) {
array_pop($raw);
$size = count($raw);
}
// or use array_chunk and run another loop?
for ($i = 0; $i < $size; $i += 2) {
$this->setParam($raw[$i], $raw[$i + 1]);
}
}
return true;
}
/**
* Reset Request
*
* @return void
*/
protected function resetRequest(): void
{
$request = Request::getInstance();
// priority:
// - default values
// - from GET query
// - from path
$request = $request->withQueryParams(
array_merge(
[
'_module' => $this->getDefaultModule(),
'_controller' => $this->getDefaultController()
],
$request->getQueryParams(),
$this->params
)
);
Request::setInstance($request);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Response/Response.php | src/Response/Response.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Response;
use Bluz\Common\Options;
use Bluz\Controller\Controller;
use Bluz\Http\StatusCode;
use Bluz\Layout\Layout;
use Bluz\Proxy\Messages;
use DateTime;
use InvalidArgumentException;
use Laminas\Diactoros\Response\EmptyResponse;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Diactoros\Response\JsonResponse;
use Laminas\Diactoros\Response\RedirectResponse;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
/**
* Response Container
*
* @package Bluz\Response
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Response
*/
class Response
{
use Options;
/**
* @var string HTTP protocol version
*/
protected $protocol = '1.1';
/**
* @var integer response code equal to HTTP status codes
*/
protected $code = StatusCode::OK;
/**
* @var string|null HTTP Phrase
*/
protected $phrase;
/**
* @var array list of headers
*/
protected $headers = [];
/**
* @var array list of cookies
*/
protected $cookies = [];
/**
* @var Controller
*/
protected $body;
/**
* @var string CLI|HTML|JSON|FILE
*/
protected $type = 'HTML';
/**
* send
*/
public function send(): void
{
$body = $this->getBody();
$this->sendCookies();
switch (true) {
case 'CLI' === $this->type:
// no CLI response
return;
case null === $body:
case StatusCode::NO_CONTENT === $this->getStatusCode():
$response = new EmptyResponse($this->getStatusCode(), $this->getHeaders());
break;
case StatusCode::MOVED_PERMANENTLY === $this->getStatusCode():
case StatusCode::FOUND === $this->getStatusCode():
$response = new RedirectResponse(
$this->getHeader('Location'),
$this->getStatusCode(),
$this->getHeaders()
);
break;
case 'JSON' === $this->type:
// JSON response
// setup messages
if (Messages::count()) {
$this->setHeader('Bluz-Notify', json_encode(Messages::popAll()));
}
// encode body data to JSON
$response = new JsonResponse(
$body,
$this->getStatusCode(),
$this->getHeaders()
);
break;
case 'FILE' === $this->type:
// File attachment
$response = new AttachmentResponse(
$this->body->getData()->get('FILE'),
$this->getStatusCode(),
$this->getHeaders()
);
break;
case 'HTML' === $this->type:
default:
// HTML response
$response = new HtmlResponse(
(string)$body,
$this->getStatusCode(),
$this->getHeaders()
);
break;
}
$emitter = new SapiEmitter();
$emitter->emit($response);
}
/**
* Get response type
*
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* Set Response Type, one of JSON, HTML or CLI
*
* @param string $type
*/
public function setType(string $type): void
{
// switch statement by content type
switch ($type) {
case 'JSON':
$this->setHeader('Content-Type', 'application/json');
break;
case 'CLI':
case 'FILE':
case 'HTML':
default:
break;
}
$this->type = $type;
}
/**
* Gets the HTTP protocol version as a string
*
* The string MUST contain only the HTTP version number (e.g., "1.1", "1.0").
*
* @return string HTTP protocol version.
*/
public function getProtocolVersion(): string
{
return $this->protocol;
}
/**
* Gets the response Status-Code
*
* The Status-Code is a 3-digit integer result code of the server's attempt
* to understand and satisfy the request.
*
* @return integer status code.
*/
public function getStatusCode(): int
{
return $this->code;
}
/**
* Sets the status code of this response
*
* @param integer $code the 3-digit integer result code to set.
*
* @return void
*/
public function setStatusCode(int $code): void
{
$this->code = $code;
}
/**
* Gets the response Reason-Phrase, a short textual description of the Status-Code
*
* Because a Reason-Phrase is not a required element in response
* Status-Line, the Reason-Phrase value MAY be null. Implementations MAY
* choose to return the default RFC 2616 recommended reason phrase for the
* response's Status-Code.
*
* @return string|null reason phrase, or null if unknown.
*/
public function getReasonPhrase(): ?string
{
return $this->phrase;
}
/**
* Sets the Reason-Phrase of the response
*
* If no Reason-Phrase is specified, implementations MAY choose to default
* to the RFC 2616 recommended reason phrase for the response's Status-Code.
*
* @param string $phrase the Reason-Phrase to set.
*/
public function setReasonPhrase(string $phrase): void
{
$this->phrase = $phrase;
}
/**
* Retrieve a header by the given case-insensitive name as a string
*
* This method returns all of the header values of the given
* case-insensitive header name as a string concatenated together using
* a comma.
*
* @param string $header case-insensitive header name.
*
* @return string
*/
public function getHeader(string $header): string
{
if ($this->hasHeader($header)) {
return implode(', ', $this->headers[$header]);
}
return '';
}
/**
* Retrieves a header by the given case-insensitive name as an array of strings
*
* @param string $header Case-insensitive header name.
*
* @return string[]
*/
public function getHeaderAsArray(string $header): array
{
if ($this->hasHeader($header)) {
return $this->headers[$header];
}
return [];
}
/**
* Checks if a header exists by the given case-insensitive name
*
* @param string $header case-insensitive header name.
*
* @return bool returns true if any header names match the given header
* name using a case-insensitive string comparison. Returns false if
* no matching header name is found in the message.
*/
public function hasHeader(string $header): bool
{
return isset($this->headers[$header]);
}
/**
* Sets a header, replacing any existing values of any headers with the
* same case-insensitive name
*
* The header name is case-insensitive. The header values MUST be a string
* or an array of strings.
*
* @param string $header header name
* @param int|int[]|string|string[] $value header value(s)
*
* @return void
*/
public function setHeader(string $header, $value): void
{
$this->headers[$header] = (array)$value;
}
/**
* Appends a header value for the specified header
*
* Existing values for the specified header will be maintained. The new
* value will be appended to the existing list.
*
* @param string $header header name to add
* @param string|int $value value of the header
*
* @return void
*/
public function addHeader(string $header, $value): void
{
if ($this->hasHeader($header)) {
$this->headers[$header][] = $value;
} else {
$this->setHeader($header, $value);
}
}
/**
* Remove a specific header by case-insensitive name.
*
* @param string $header HTTP header to remove
*
* @return void
*/
public function removeHeader(string $header): void
{
unset($this->headers[$header]);
}
/**
* Gets all message headers
*
* The keys represent the header name as it will be sent over the wire, and
* each value is an array of strings associated with the header.
*
* // Represent the headers as a string
* foreach ($message->getHeaders() as $name => $values) {
* echo $name . ": " . implode(", ", $values);
* }
*
* @return array returns an associative array of the message's headers.
*/
public function getHeaders(): array
{
return $this->headers;
}
/**
* Sets headers, replacing any headers that have already been set on the message
*
* The array keys MUST be a string. The array values must be either a
* string or an array of strings.
*
* @param array $headers Headers to set.
*
* @return void
*/
public function setHeaders(array $headers): void
{
$this->headers = $headers;
}
/**
* Merges in an associative array of headers.
*
* Each array key MUST be a string representing the case-insensitive name
* of a header. Each value MUST be either a string or an array of strings.
* For each value, the value is appended to any existing header of the same
* name, or, if a header does not already exist by the given name, then the
* header is added.
*
* @param array $headers Associative array of headers to add to the message
*
* @return void
*/
public function addHeaders(array $headers): void
{
$this->headers = array_merge_recursive($this->headers, $headers);
}
/**
* Remove all headers
*
* @return void
*/
public function removeHeaders(): void
{
$this->headers = [];
}
/**
* Set response body
*
* @param mixed $body
*
* @return void
*/
public function setBody($body): void
{
$this->body = $body;
}
/**
* Get response body
*
* @return Controller|Layout
*/
public function getBody()
{
return $this->body;
}
/**
* Clear response body
*
* @return void
*/
public function clearBody(): void
{
$this->body = null;
}
/**
* Set Cookie
*
* @param string $name
* @param string $value
* @param int|string|DateTime $expire
* @param string $path
* @param string $domain
* @param bool $secure
* @param bool $httpOnly
*
* @return void
* @throws InvalidArgumentException
*/
public function setCookie(
string $name,
string $value = '',
$expire = 0,
string $path = '/',
string $domain = '',
bool $secure = false,
bool $httpOnly = false
): void {
// from PHP source code
if (preg_match("/[=,; \t\r\n\013\014]/", $name)) {
throw new InvalidArgumentException('The cookie name contains invalid characters.');
}
if (empty($name)) {
throw new InvalidArgumentException('The cookie name cannot be empty.');
}
// convert expiration time to a Unix timestamp
if ($expire instanceof DateTime) {
$expire = $expire->format('U');
} elseif (!is_numeric($expire)) {
$expire = strtotime($expire);
if (false === $expire || -1 === $expire) {
throw new InvalidArgumentException('The cookie expiration time is not valid.');
}
}
$this->cookies[$name] = [
'name' => $name,
'value' => $value,
'expire' => $expire,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httpOnly' => $httpOnly
];
}
/**
* Get Cookie by name
*
* @param string $name
*
* @return array|null
*/
public function getCookie(string $name): ?array
{
return $this->cookies[$name] ?? null;
}
/**
* Process Cookies to Header
*
* Set-Cookie: <name>=<value>[; <name>=<value>]...
* [; expires=<date>][; domain=<domain_name>]
* [; path=<some_path>][; secure][; httponly]
*
* @return void
*/
protected function sendCookies(): void
{
foreach ($this->cookies as $cookie) {
setcookie(...array_values($cookie));
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Response/AttachmentResponse.php | src/Response/AttachmentResponse.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Response;
use Laminas\Diactoros\Response as DiactorsResponse;
use Laminas\Diactoros\Response\InjectContentTypeTrait;
use Laminas\Diactoros\Stream;
/**
* Class AttachmentResponse
*
* @package Bluz\Response
* @link http://www.marco-bunge.com/2016/09/01/file-downloads-with-Laminas-diactoros/
*/
class AttachmentResponse extends DiactorsResponse
{
use InjectContentTypeTrait;
/**
* Create a file attachment response.
*
* Produces a text response with a Content-Type of given file mime type and a default
* status of 200.
*
* @param string $file Valid file path
* @param int $status Integer status code for the response; 200 by default.
* @param array $headers Array of headers to use at initialization.
*
* @throws \InvalidArgumentException
*@internal param StreamInterface|string $text String or stream for the message body.
*/
public function __construct($file, int $status = 200, array $headers = [])
{
$fileInfo = new \SplFileInfo($file);
$headers = array_replace(
$headers,
[
'content-length' => $fileInfo->getSize(),
'content-disposition' => sprintf('attachment; filename=%s', $fileInfo->getFilename()),
]
);
parent::__construct(
new Stream($fileInfo->getRealPath(), 'r'),
$status,
$this->injectContentType((new \finfo(FILEINFO_MIME_TYPE))->file($fileInfo->getRealPath()), $headers)
);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Response/ResponseTrait.php | src/Response/ResponseTrait.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Response;
/**
* Response Trait
*
* @package Bluz\Response
* @author Anton Shevchuk
*/
trait ResponseTrait
{
/**
* @return string
*/
abstract public function jsonSerialize();
/**
* @return string
*/
abstract public function __toString();
/**
* Render object as HTML or JSON
*
* @param string $type
*
* @return string
*/
public function render(string $type = 'HTML'): string
{
// switch statement by response type
switch (strtoupper($type)) {
case 'CLI':
case 'JSON':
return $this->jsonSerialize();
case 'HTML':
default:
return $this->__toString();
}
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Config/Config.php | src/Config/Config.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Config;
use Bluz\Collection\Collection;
use Bluz\Common\Container\Container;
use Bluz\Common\Container\RegularAccess;
/**
* Config
*
* @package Bluz\Config
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Config
*/
class Config
{
use Container;
use RegularAccess;
/**
* Return configuration by key
*
* @param array $keys
*
* @return array|mixed
* @throws ConfigException
*/
public function get(...$keys)
{
// configuration is missed
if (empty($this->container)) {
throw new ConfigException('System configuration is missing');
}
if (!count($keys)) {
return $this->container;
}
return Collection::get($this->container, ...$keys);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Config/ConfigLoader.php | src/Config/ConfigLoader.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Config;
use FilesystemIterator;
use GlobIterator;
/**
* Config
*
* @package Bluz\Config
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Config
*/
class ConfigLoader
{
/**
* @var array configuration data
*/
protected $config;
/**
* @var string path to configuration files
*/
protected $path;
/**
* @var string environment
*/
protected $environment;
/**
* @return array
*/
public function getConfig(): array
{
return $this->config;
}
/**
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* Set path to configuration files
*
* @param string $path
*
* @return void
* @throws ConfigException
*/
public function setPath(string $path): void
{
if (!is_dir($path)) {
throw new ConfigException('Configuration directory is not exists');
}
$this->path = rtrim($path, '/');
}
/**
* @return string
*/
public function getEnvironment(): string
{
return $this->environment;
}
/**
* Set application environment
*
* @param string $environment
*
* @return void
*/
public function setEnvironment(string $environment): void
{
$this->environment = $environment;
}
/**
* Load configuration
*
* @return void
* @throws ConfigException
*/
public function load(): void
{
if (!$this->path) {
throw new ConfigException('Configuration directory is not setup');
}
$this->config = $this->loadFiles($this->path . '/configs/default');
if ($this->environment) {
$customConfig = $this->loadFiles($this->path . '/configs/' . $this->environment);
$this->config = array_replace_recursive($this->config, $customConfig);
}
}
/**
* Load configuration file
*
* @param string $path
*
* @return mixed
* @throws ConfigException
*/
protected function loadFile(string $path)
{
if (!is_file($path) && !is_readable($path)) {
throw new ConfigException("Configuration file `$path` not found");
}
return include $path;
}
/**
* Load configuration files to array
*
* @param string $path
*
* @return array
* @throws ConfigException
*/
protected function loadFiles(string $path): array
{
$config = [];
if (!is_dir($path)) {
throw new ConfigException("Configuration directory `$path` not found");
}
$iterator = new GlobIterator(
$path . '/*.php',
FilesystemIterator::KEY_AS_FILENAME | FilesystemIterator::CURRENT_AS_PATHNAME
);
foreach ($iterator as $name => $file) {
$name = substr($name, 0, -4);
$config[$name] = $this->loadFile($file);
}
return $config;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Config/ConfigException.php | src/Config/ConfigException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Config;
use Bluz\Common\Exception\CommonException;
/**
* Config Exception
*
* @package Bluz\Config
* @author Anton Shevchuk
*/
class ConfigException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Crud/AbstractCrud.php | src/Crud/AbstractCrud.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Crud;
use Bluz\Common\Instance;
use Bluz\Db\RowInterface;
use Bluz\Http\Exception\NotImplementedException;
/**
* Crud
*
* @package Bluz\Crud
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Crud
*/
abstract class AbstractCrud implements CrudInterface
{
use Instance;
/**
* @var array Fields for action
* @todo should be different for Create, Read and Update
*/
protected $fields = [];
/**
* Return primary key signature
*
* @return array
*/
abstract public function getPrimaryKey(): array;
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function readOne($primary)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function readSet(int $offset = 0, int $limit = self::DEFAULT_LIMIT, array $params = [])
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function createOne(array $data)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function createSet(array $data)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function updateOne($primary, array $data)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function updateSet(array $data)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function deleteOne($primary)
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*
* @throws NotImplementedException
*/
public function deleteSet(array $data)
{
throw new NotImplementedException();
}
/**
* @return array
*/
public function getFields(): array
{
return $this->fields;
}
/**
* @param array $fields
*/
public function setFields(array $fields): void
{
$this->fields = $fields;
}
/**
* Filter input Fields
*
* @param array $data Request
*
* @return array
*/
protected function filterData($data): array
{
if (empty($this->getFields())) {
return $data;
}
return array_intersect_key($data, array_flip($this->getFields()));
}
/**
* Filter output Row
*
* @param RowInterface $row from database
*
* @return RowInterface
*/
protected function filterRow(RowInterface $row): RowInterface
{
if (empty($this->getFields())) {
return $row;
}
$fields = array_keys($row->toArray());
$toDelete = array_diff($fields, $this->getFields());
foreach ($toDelete as $field) {
unset($row->$field);
}
return $row;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Crud/Table.php | src/Crud/Table.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Crud;
use Bluz\Application\Exception\ApplicationException;
use Bluz\Db\Exception\InvalidPrimaryKeyException;
use Bluz\Db\Exception\TableNotFoundException;
use Bluz\Http\Exception\NotFoundException;
use Bluz\Db;
use Bluz\Proxy;
/**
* Crud Table
*
* @package Bluz\Crud
* @author AntonShevchuk
* @link https://github.com/bluzphp/framework/wiki/Crud-Table
*/
class Table extends AbstractCrud
{
use Db\Traits\TableProperty;
/**
* {@inheritdoc}
*
* @throws InvalidPrimaryKeyException
* @throws TableNotFoundException
*/
public function getPrimaryKey(): array
{
return $this->getTable()->getPrimaryKey();
}
/**
* Get record from Db or create new object
*
* @param mixed $primary
*
* @return Db\RowInterface
* @throws TableNotFoundException
* @throws NotFoundException
*/
public function readOne($primary)
{
if (!$primary) {
return $this->getTable()::create();
}
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
return $this->filterRow($row);
}
/**
* Get set of records
*
* @param int $offset
* @param int $limit
* @param array $params
*
* @return array[Row[], integer]
* @throws TableNotFoundException
*/
public function readSet(int $offset = 0, int $limit = 10, array $params = [])
{
$select = $this->getTable()::select();
// select only required fields
if (count($this->getFields())) {
$fields = $this->getFields();
$name = $this->getTable()->getName();
$fields = array_map(
function ($field) use ($name) {
return $name . '.' . $field;
},
$fields
);
$select->select(implode(', ', $fields));
}
// switch statement for DB type
$type = Proxy\Db::getOption('connect', 'type');
switch ($type) {
case 'mysql':
$selectPart = $select->getSelect();
$selectPart[0] = 'SQL_CALC_FOUND_ROWS ' . $selectPart[0];
$select->select(...$selectPart);
$totalSQL = 'SELECT FOUND_ROWS()';
break;
case 'pgsql':
default:
$selectTotal = clone $select;
$selectTotal->select('COUNT(*)');
$totalSQL = $selectTotal->getSql();
break;
}
$select->setLimit($limit);
$select->setOffset($offset);
$result = [];
$total = 0;
// run queries
// use transaction to avoid errors
Proxy\Db::transaction(
function () use (&$result, &$total, $select, $totalSQL) {
$result = $select->execute();
$total = Proxy\Db::fetchOne($totalSQL);
}
);
return [$result, $total];
}
/**
* Create item
*
* @param array $data
*
* @return mixed
* @throws TableNotFoundException
*/
public function createOne(array $data)
{
$row = $this->getTable()::create();
$data = $this->filterData($data);
$row->setFromArray($data);
return $row->save();
}
/**
* Update item
*
* @param mixed $primary
* @param array $data
*
* @return integer
* @throws NotFoundException
* @throws TableNotFoundException
*/
public function updateOne($primary, array $data)
{
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
$data = $this->filterData($data);
$row->setFromArray($data);
return $row->save();
}
/**
* Delete item
*
* @param mixed $primary
*
* @return integer
* @throws NotFoundException
* @throws TableNotFoundException
*/
public function deleteOne($primary)
{
$row = $this->getTable()::findRow($primary);
if (!$row) {
throw new NotFoundException('Record not found');
}
return $row->delete();
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Crud/CrudException.php | src/Crud/CrudException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Crud;
use Bluz\Common\Exception\CommonException;
/**
* CRUD Exception
*
* @package Bluz\Crud
*/
class CrudException extends CommonException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Crud/CrudInterface.php | src/Crud/CrudInterface.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Crud;
use Bluz\Http\Exception\NotImplementedException;
/**
* Crud
*
* @package Bluz\Crud
* @author Anton Shevchuk
* @link https://github.com/bluzphp/framework/wiki/Crud
*/
interface CrudInterface
{
/**
* Default limit for READ SET of elements
*/
public const DEFAULT_LIMIT = 10;
/**
* Get item by primary key(s)
*
* @param mixed $primary
*
* @return mixed
*/
public function readOne($primary);
/**
* Get collection of items
*
* @param integer $offset
* @param integer $limit
* @param array $params
*
* @return array[Row[], integer]
*/
public function readSet(int $offset = 0, int $limit = self::DEFAULT_LIMIT, array $params = []);
/**
* Create new item
*
* @param array $data
*
* @return mixed
*/
public function createOne(array $data);
/**
* Create items
*
* @param array $data
*
* @return mixed
*/
public function createSet(array $data);
/**
* Update item
*
* @param mixed $primary
* @param array $data
*
* @return integer
*/
public function updateOne($primary, array $data);
/**
* Update items
*
* @param array $data
*
* @return integer
*/
public function updateSet(array $data);
/**
* Delete item
*
* @param mixed $primary
*
* @return integer
*/
public function deleteOne($primary);
/**
* Delete items
*
* @param array $data
*
* @return integer
*/
public function deleteSet(array $data);
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/ValidatorInterface.php | src/Validator/ValidatorInterface.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator;
use Bluz\Validator\Exception\ValidatorException;
/**
* Validator Rule Interface
*
* @package Bluz\Validator\Rule
* @author Anton Shevchuk
*/
interface ValidatorInterface
{
/**
* Check input data
*
* @param mixed $input
*
* @return bool
*/
public function validate($input): bool;
/**
* Assert
*
* @param mixed $input
*
* @throws ValidatorException
*/
public function assert($input): void;
/**
* Invoke
*
* @param mixed $input
*
* @return bool
*/
public function __invoke($input): bool;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Validator.php | src/Validator/Validator.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator;
use Bluz\Validator\Exception\ComponentException;
use Bluz\Validator\Rule\RuleInterface;
/**
* Validator
*
* @package Bluz\Validator
* @author Anton Shevchuk
* @link https://github.com/Respect/Validation
*
* @method static ValidatorChain alpha($additionalCharacters = '')
* @method static ValidatorChain alphaNumeric($additionalCharacters = '')
* @method static ValidatorChain array($callback)
* @method static ValidatorChain between($min, $max)
* @method static ValidatorChain betweenInclusive($min, $max)
* @method static ValidatorChain callback($callable, $description = null)
* @method static ValidatorChain condition($condition)
* @method static ValidatorChain contains($containsValue)
* @method static ValidatorChain containsStrict($containsValue)
* @method static ValidatorChain countryCode()
* @method static ValidatorChain creditCard()
* @method static ValidatorChain date($format)
* @method static ValidatorChain domain($checkDns = false)
* @method static ValidatorChain email($checkDns = false)
* @method static ValidatorChain equals($compareTo)
* @method static ValidatorChain equalsStrict($compareTo)
* @method static ValidatorChain float()
* @method static ValidatorChain in($haystack)
* @method static ValidatorChain inStrict($haystack)
* @method static ValidatorChain integer()
* @method static ValidatorChain ip($options = null)
* @method static ValidatorChain json()
* @method static ValidatorChain latin($additionalCharacters = '')
* @method static ValidatorChain latinNumeric($additionalCharacters = '')
* @method static ValidatorChain length($min = null, $max = null)
* @method static ValidatorChain less($maxValue)
* @method static ValidatorChain lessOrEqual($maxValue)
* @method static ValidatorChain more($minValue)
* @method static ValidatorChain moreOrEqual($minValue)
* @method static ValidatorChain notEmpty()
* @method static ValidatorChain noWhitespace()
* @method static ValidatorChain numeric()
* @method static ValidatorChain required()
* @method static ValidatorChain regexp($expression, $description = null)
* @method static ValidatorChain slug()
* @method static ValidatorChain string()
*/
class Validator
{
/**
* @var array[] list of rules namespaces
*/
protected static $rulesNamespaces = [
'\\Bluz\\Validator\\Rule\\'
];
/**
* Create new instance if ValidatorChain
*
* @return ValidatorChain
*/
public static function create(): ValidatorChain
{
return new ValidatorChain();
}
/**
* Magic static call for create instance of Validator
*
* @param string $ruleName
* @param array $arguments
*
* @return ValidatorChain
*/
public static function __callStatic($ruleName, $arguments): ValidatorChain
{
$validatorChain = self::create();
return $validatorChain->$ruleName(...$arguments);
}
/**
* Create new rule by name
*
* @param string $ruleName
* @param array $arguments
*
* @return RuleInterface
* @throws Exception\ComponentException
*/
public static function rule(string $ruleName, array $arguments): RuleInterface
{
$ruleName = ucfirst($ruleName) . 'Rule';
foreach (static::$rulesNamespaces as $ruleNamespace) {
$ruleClass = $ruleNamespace . $ruleName;
if (class_exists($ruleClass)) {
return new $ruleClass(...$arguments);
}
}
throw new ComponentException("Class for validator `$ruleName` not found");
}
/**
* Add rules path
*
* @param string $path
*
* @return void
*/
public static function addRuleNamespace(string $path): void
{
static::$rulesNamespaces[] = rtrim($path, '\\') . '\\';
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/ValidatorChain.php | src/Validator/ValidatorChain.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator;
use Bluz\Validator\Exception\ComponentException;
use Bluz\Validator\Exception\ValidatorException;
use Bluz\Validator\Rule\RequiredRule;
use Bluz\Validator\Rule\RuleInterface;
/**
* Chain of Validators
*
* Chain can consists one or more validation rules
*
* @package Bluz\Validator
* @author Anton Shevchuk
*
* @method ValidatorChain alpha($additionalCharacters = '')
* @method ValidatorChain alphaNumeric($additionalCharacters = '')
* @method ValidatorChain array($callback)
* @method ValidatorChain between($min, $max)
* @method ValidatorChain betweenInclusive($min, $max)
* @method ValidatorChain condition($condition)
* @method ValidatorChain contains($containsValue)
* @method ValidatorChain containsStrict($containsValue)
* @method ValidatorChain countryCode()
* @method ValidatorChain creditCard()
* @method ValidatorChain date($format)
* @method ValidatorChain domain($checkDns = false)
* @method ValidatorChain email($checkDns = false)
* @method ValidatorChain equals($compareTo)
* @method ValidatorChain equalsStrict($compareTo)
* @method ValidatorChain float()
* @method ValidatorChain in($haystack)
* @method ValidatorChain inStrict($haystack)
* @method ValidatorChain integer()
* @method ValidatorChain ip($options = null)
* @method ValidatorChain json()
* @method ValidatorChain latin($additionalCharacters = '')
* @method ValidatorChain latinNumeric($additionalCharacters = '')
* @method ValidatorChain length($min = null, $max = null)
* @method ValidatorChain less($maxValue)
* @method ValidatorChain lessOrEqual($maxValue)
* @method ValidatorChain more($minValue)
* @method ValidatorChain moreOrEqual($minValue)
* @method ValidatorChain notEmpty()
* @method ValidatorChain noWhitespace()
* @method ValidatorChain numeric()
* @method ValidatorChain required()
* @method ValidatorChain slug()
* @method ValidatorChain string()
*/
class ValidatorChain implements ValidatorInterface
{
/**
* @var string description of rules chain
*/
protected $description;
/**
* @var RuleInterface[] list of validation rules
*/
protected $rules = [];
/**
* @var string Error message
*/
protected $error;
/**
* Magic call for create new rule
*
* @param string $ruleName
* @param array $arguments
*
* @return ValidatorChain
* @throws Exception\ComponentException
*/
public function __call($ruleName, $arguments): ValidatorChain
{
$this->addRule(Validator::rule($ruleName, $arguments));
return $this;
}
/**
* Add Rule to ValidatorChain
*
* @param RuleInterface $rule
*
* @return ValidatorChain
*/
public function addRule(RuleInterface $rule): ValidatorChain
{
$this->rules[] = $rule;
return $this;
}
/**
* Get required flag
*
* @return bool
*/
public function isRequired(): bool
{
foreach ($this->rules as $rule) {
if ($rule instanceof RequiredRule) {
return true;
}
}
return false;
}
/**
* Add Callback Rule to ValidatorChain
*
* @param mixed $callable
* @param string|null $description
*
* @return ValidatorChain
* @throws ComponentException
*/
public function callback($callable, ?string $description = null): ValidatorChain
{
$rule = Validator::rule('callback', [$callable]);
if (null !== $description) {
$rule->setDescription($description);
}
$this->addRule($rule);
return $this;
}
/**
* Add Regexp Rule to ValidatorChain
*
* @param string $expression
* @param string|null $description
*
* @return ValidatorChain
* @throws ComponentException
*/
public function regexp(string $expression, ?string $description = null): ValidatorChain
{
$rule = Validator::rule('regexp', [$expression]);
if (null !== $description) {
$rule->setDescription($description);
}
$this->addRule($rule);
return $this;
}
/**
* Validate chain of rules
*
* @param mixed $input
*
* @return bool
*/
public function validate($input): bool
{
$this->error = null; // clean
foreach ($this->rules as $rule) {
if (!$rule->validate($input)) {
// apply custom description or use description from rule
$this->setError($this->description ?? $rule->getDescription());
return false;
}
}
return true;
}
/**
* Assert
*
* @param mixed $input
*
* @throws ValidatorException
*/
public function assert($input): void
{
if (!$this->validate($input)) {
throw new ValidatorException($this->getError());
}
}
/**
* @inheritdoc
*/
public function __invoke($input): bool
{
return $this->validate($input);
}
/**
* @inheritdoc
*/
public function __toString(): string
{
return implode("\n", $this->getDescription());
}
/**
* Get error message
*
* @return null|string
*/
public function getError(): ?string
{
return $this->error;
}
/**
* Set error message for replace text from rule
*
* @param string $message
*
* @return ValidatorChain
*/
protected function setError(string $message): ValidatorChain
{
$this->error = $message;
return $this;
}
/**
* Get validation description
*
* @return array
*/
public function getDescription(): array
{
// apply custom description
if ($this->description) {
return [$this->description];
}
// eject description from rules
return array_map('\strval', $this->rules);
}
/**
* Set validation description
*
* @param string $message
*
* @return ValidatorChain
*/
public function setDescription(string $message): ValidatorChain
{
$this->description = $message;
return $this;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/ValidatorForm.php | src/Validator/ValidatorForm.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator;
use Bluz\Validator\Exception\ValidatorException;
/**
* Validator Builder
*
* @package Bluz\Validator
* @author Anton Shevchuk
*/
class ValidatorForm implements ValidatorInterface
{
/**
* Stack of validators
*
* ['foo'] => ValidatorChain
* ['bar'] => ValidatorChain
*
* @var ValidatorChain[]
*/
protected $validators = [];
/**
* Exception with list of validation errors
*
* ['foo'] => "some field error"
* ['bar'] => "some field error"
*
* @var ValidatorException
*/
protected $exception;
/**
* Add chain to form
*
* @param string $name
*
* @return ValidatorChain
*/
public function add(string $name): ValidatorChain
{
$this->validators[$name] = $this->validators[$name] ?? Validator::create();
return $this->validators[$name];
}
/**
* Get chain to form
*
* @param string $name
*
* @return ValidatorChain
*/
public function get(string $name): ValidatorChain
{
return $this->add($name);
}
/**
* Validate chain of rules
*
* @param array $input
*
* @return bool
*/
public function validate($input): bool
{
$this->exception = new ValidatorException();
// run chains
foreach ($this->validators as $key => $validators) {
// skip validation for non required elements
if (!isset($input[$key]) && !$validators->isRequired()) {
continue;
}
$this->validateItem($key, $input[$key] ?? null);
}
return !$this->hasErrors();
}
/**
* Validate chain of rules for single item
*
* @param string $key
* @param mixed $value
*
* @return bool
*/
protected function validateItem(string $key, $value): bool
{
// run validators chain
$result = $this->validators[$key]->validate($value);
if (!$result) {
$this->exception->setError($key, $this->validators[$key]->getError());
}
return $result;
}
/**
* Assert
*
* @param mixed $input
*
* @return void
* @throws ValidatorException
*/
public function assert($input): void
{
if (!$this->validate($input)) {
throw $this->exception;
}
}
/**
* @inheritdoc
*/
public function __invoke($input): bool
{
return $this->validate($input);
}
/**
* Get errors
*
* @return array
*/
public function getErrors(): array
{
return $this->exception->getErrors();
}
/**
* Has errors?
*
* @return bool
*/
public function hasErrors(): bool
{
return $this->exception->hasErrors();
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Traits/Validator.php | src/Validator/Traits/Validator.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Traits;
use Bluz\Validator\Exception\ValidatorException;
use Bluz\Validator\ValidatorChain;
use Bluz\Validator\ValidatorForm;
/**
* Validator trait
*
* Example of usage
* <code>
* use Bluz\Validator\Traits\Validator;
* use Bluz\Validator\Validator as v;
*
* class Row extends Db\Row {
* use Validator;
* function beforeSave()
* {
* $this->addValidator(
* 'login',
* v::required()->latin()->length(3, 255)
* );
* }
* }
* </code>
*
* @package Bluz\Validator\Traits
* @author Anton Shevchuk
*/
trait Validator
{
/**
* @var ValidatorForm instance
*/
private $validatorForm;
/**
* Get ValidatorBuilder
*
* @return ValidatorForm
*/
private function getValidatorForm(): ValidatorForm
{
if (!$this->validatorForm) {
$this->validatorForm = new ValidatorForm();
}
return $this->validatorForm;
}
/**
* Add ValidatorChain
*
* @param string $name
*
* @return ValidatorChain
*/
public function addValidator(string $name): ValidatorChain
{
return $this->getValidatorForm()->add($name);
}
/**
* Get ValidatorChain
*
* @param string $name
*
* @return ValidatorChain
*/
public function getValidator(string $name): ValidatorChain
{
return $this->getValidatorForm()->get($name);
}
/**
* Validate input data
*
* @param array $input
*
* @return bool
*/
public function validate($input): bool
{
return $this->getValidatorForm()->validate($input);
}
/**
* Assert input data
*
* @param array $input
*
* @throws ValidatorException
*/
public function assert($input): void
{
$this->getValidatorForm()->assert($input);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Exception/ComponentException.php | src/Validator/Exception/ComponentException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Exception;
use Bluz\Common\Exception;
/**
* Component Exception
*
* @package Bluz\Validator\Exception
* @author Anton Shevchuk
*/
class ComponentException extends Exception\ComponentException
{
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Exception/ValidatorException.php | src/Validator/Exception/ValidatorException.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Exception;
use Bluz\Http\Exception\BadRequestException;
/**
* Validator Exception
*
* @package Bluz\Validator\Exception
* @author Anton Shevchuk
*/
class ValidatorException extends BadRequestException
{
/**
* @var string exception message
*/
protected $message = 'Invalid Arguments';
/**
* @var array of error's messages
*/
protected $errors = [];
/**
* @return array
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* @param array $errors
*/
public function setErrors(array $errors): void
{
$this->errors = $errors;
}
/**
* Add Error by field name
*
* @param string $name
* @param string $message
*
* @return void
*/
public function setError(string $name, string $message): void
{
$this->errors[$name] = $message;
}
/**
* Has errors?
*
* @return bool
*/
public function hasErrors(): bool
{
return (bool) count($this->errors);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Rule/NoWhitespaceRule.php | src/Validator/Rule/NoWhitespaceRule.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Rule;
/**
* Check for no whitespaces
*
* @package Bluz\Validator\Rule
*/
class NoWhitespaceRule extends AbstractRule
{
/**
* @var string error template
*/
protected $description = 'must not contain whitespace';
/**
* Check input data
*
* @param string $input
*
* @return bool
*/
public function validate($input): bool
{
return null === $input || !preg_match('/\s/', (string)$input);
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Rule/PositiveRule.php | src/Validator/Rule/PositiveRule.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Rule;
/**
* Check for positive number
*
* @package Bluz\Validator\Rule
*/
class PositiveRule extends AbstractRule
{
/**
* @var string error template
*/
protected $description = 'must be positive';
/**
* Check for positive number
*
* @param string $input
*
* @return bool
*/
public function validate($input): bool
{
return is_numeric($input) && $input > 0;
}
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
bluzphp/framework | https://github.com/bluzphp/framework/blob/be908a41e27f50f3786bfa8919d5245efb0d9942/src/Validator/Rule/RuleInterface.php | src/Validator/Rule/RuleInterface.php | <?php
/**
* Bluz Framework Component
*
* @copyright Bluz PHP Team
* @link https://github.com/bluzphp/framework
*/
declare(strict_types=1);
namespace Bluz\Validator\Rule;
use Bluz\Validator\ValidatorInterface;
/**
* Validator Rule Interface
*
* @package Bluz\Validator\Rule
* @author Anton Shevchuk
*/
interface RuleInterface extends ValidatorInterface
{
/**
* Cast to string
*
* @return string
*/
public function __toString(): string;
/**
* Get error template
*
* @return string
*/
public function getDescription(): string;
/**
* Set error template
*
* @param string $description
*
* @return self
*/
public function setDescription(string $description): RuleInterface;
}
| php | MIT | be908a41e27f50f3786bfa8919d5245efb0d9942 | 2026-01-05T04:45:21.018855Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.