Compare commits

..

No commits in common. "9f7ce7e9b6385b365eda69effb08b4cd7980ae81" and "d0ce9e47af189821bb6a3b7f54e228fb8c129aa3" have entirely different histories.

7 changed files with 309 additions and 512 deletions

View File

@ -1,3 +1,3 @@
# PHP 8.3 Framework for working with ArangoDB # PHP 8.2 Framework for working with ArangoDB
🤟 Very simple and flexible, easy to scale and integrate 🤟 Very simple and flexible, easy to scale and integrate

View File

@ -5,7 +5,7 @@
"keywords": [ "keywords": [
"ArangoDB" "ArangoDB"
], ],
"type": "framework", "type": "library",
"license": "WTFPL", "license": "WTFPL",
"homepage": "https://git.hood.su/mirzaev/arangodb", "homepage": "https://git.hood.su/mirzaev/arangodb",
"authors": [ "authors": [

View File

@ -4,59 +4,51 @@ declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
// Files of the project use mirzaev\arangodb\terminal;
use mirzaev\arangodb\connection,
mirzaev\arangodb\terminal,
mirzaev\arangodb\enumerations\collection\type;
// Library for ArangoDB use ArangoDBClient\Connection as _connection;
use ArangoDBClient\Statement as _statement, use ArangoDBClient\Collection as _collection;
ArangoDBClient\Document as _document, use ArangoDBClient\Statement as _statement;
ArangoDBClient\CollectionHandler as _collection_handler; use ArangoDBClient\Document as _document;
use ArangoDBClient\CollectionHandler as _collection_handler;
// Built-in libraries
use exception;
/** /**
* Collection * Коллекция
* *
* @package mirzaev\arangodb * @package mirzaev\arangodb
*
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy> * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/ */
class collection class collection
{ {
/** /**
* Initialize a collection * Инициализация
* *
* @param string $collection Name of the collection * @param _connection $session Сессия соединения с базой данных
* @param type $type Type of the collection * @param string $name Название
* @param bool $edge Обрабатывать как ребро? (иначе: вершина)
* @param ?terminal $terminal Инстанция терминала * @param ?terminal $terminal Инстанция терминала
* @param array &$errors Registry of errors
* *
* @return string|null Identifier of the collection * @return string|null Идентификатор коллекции
*/ */
public static function initialize(string $name, type $type = type::document, ?terminal $terminal = null, array &$errors = []): ?string public static function init(_connection $session, string $name, bool $edge = false, ?terminal $terminal = null): ?string
{ {
try {
// Инициализация // Инициализация
$collections = new _collection_handler(connection::$session); $collections = new _collection_handler($session);
if (!$collections->has($name)) { if (!$collections->has($name)) {
// Не найдана коллекция // Не найдана коллекция
// Запись в вывод // Запись в вывод
if ($terminal instanceof terminal) $terminal::write("Not found $type collection: $name"); if ($terminal instanceof terminal) $terminal::write("Коллекция \"$name\" не найдена");
// Запись коллекции на сервер и его ответ в буфер возврата // Запись коллекции на сервер и его ответ в буфер возврата
$id = $collections->create($name, ['type' => $type->code()]); $id = $collections->create($name, ['type' => $edge ? _collection::TYPE_EDGE : _collection::TYPE_DOCUMENT]);
if ($collections->has($name)) { if ($collections->has($name)) {
// Коллекция найдена (записана) // Коллекция найдена (записана)
// Запись в вывод // Запись в вывод
if ($terminal instanceof terminal) $terminal::write("Created $type collection: $name"); if ($terminal instanceof terminal) $terminal::write("Создана коллекция \"$name\" с типом " . ($edge ? 'ребро' : 'документ'));
// Возврат идентификатора коллекции // Возврат идентификатора коллекции
return $id; return $id;
@ -67,34 +59,24 @@ class collection
// Возврат идентификатора коллекции // Возврат идентификатора коллекции
return $name; return $name;
} }
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
return null; return null;
} }
/** /**
* Execute * Поиск
* *
* @param string $query Query (AQL) * @param _connection $session Сессия соединения с базой данных
* @param array $parameters Binded parameters for placeholders [placholder => parameter] * @param string $query AQL-запрос
* @param array &$errors Registry of errors * @param array $binds Binds for query [bind => value]
* *
* @return _document|array|string|int|null Instance of the document * @return _document|array|string|int|null Инстанция документа
*/ */
public static function execute(string $query, array $parameters = [], array &$errors = []): _document|string|array|int|null public static function search(_connection $session, string $query, array $binds = []): _document|string|array|int|null
{ {
try {
// Statement instance initialization // Statement instance initialization
$instance = new _statement( $instance = new _statement(
connection::$session, $session,
[ [
'query' => $query, 'query' => $query,
"batchSize" => 1000, "batchSize" => 1000,
@ -103,7 +85,7 @@ class collection
); );
// Binds application // Binds application
$instance->bind($parameters); $instance->bind($binds);
// Sending the request // Sending the request
$response = $instance->execute(); $response = $instance->execute();
@ -115,87 +97,29 @@ class collection
$buffer[$key] = $value; $buffer[$key] = $value;
} }
// Exit (success)
return is_array($buffer) && count($buffer) > 1 ? $buffer : $buffer[0] ?? null; return is_array($buffer) && count($buffer) > 1 ? $buffer : $buffer[0] ?? null;
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
// Exit (fail)
return null;
} }
/** /**
* Truncate * Очистка
* *
* @param string $name Name of the collection * @param _connection $session Сессия соединения с базой данных
* @param array &$errors Registry of errors * @param string $name Название
* *
* @return bool Статус выполнения * @return bool Статус выполнения
*/ */
public static function truncate(string $collection, array &$errors = []): bool public static function truncate(_connection $session, string $name): bool
{ {
try { // Инициализация
// Initizlizing of the collection handler $collections = new _collection_handler($session);
$collections = new _collection_handler(connection::$session);
if ($collections->has($collection)) { if ($collections->has($name)) {
// Fount the collection // Найдена коллекция
// Truncate and exit (success) // Очистка
return $collections->truncate($collection); return $collections->truncate($name);
}
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
} }
// Exit (fail)
return false; return false;
} }
/**
* Count documents in ArangoDB
*
* @param string $collection Name of the collection
* @param array &$errors Registry of errors
*
* @return int|null Amount of documents in ArangoDB
*/
public static function count(string $collection, array &$errors = []): ?int
{
try {
// Count and exit (success)
return static::execute(
<<<'AQL'
RETURN LENGTH(@collection)
AQL,
[
'collection' => $collection
]
);
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
// Exit (fail)
return null;
}
} }

View File

@ -4,21 +4,17 @@ declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
// Library for ArangoDB use ArangoDBClient\Connection as _connection;
use ArangoDBClient\Connection as _connection, use ArangoDBClient\Exception as _exception;
ArangoDBClient\Exception as _exception, use ArangoDBClient\UpdatePolicy as _update;
ArangoDBClient\UpdatePolicy as _update, use ArangoDBClient\ConnectionOptions as _options;
ArangoDBClient\ConnectionOptions as _options;
// Built-in libraries
use exception; use exception;
/** /**
* Connection * Подключение
* *
* @package mirzaev\arangodb * @package mirzaev\arangodb
*
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy> * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/ */
final class connection final class connection
@ -86,7 +82,7 @@ final class connection
/** /**
* Сессия соединения * Сессия соединения
*/ */
public static _connection $session; protected _connection $session;
/** /**
* Конструктор * Конструктор
@ -116,7 +112,7 @@ final class connection
} }
// Подключение // Подключение
static::$session = new _connection([ $this->session = new _connection([
_options::OPTION_ENDPOINT => $this->adress, _options::OPTION_ENDPOINT => $this->adress,
_options::OPTION_DATABASE => $this->storage, _options::OPTION_DATABASE => $this->storage,
_options::OPTION_AUTH_TYPE => $this->auth, _options::OPTION_AUTH_TYPE => $this->auth,
@ -175,6 +171,7 @@ final class connection
'reconnect' => $this->reconnect, 'reconnect' => $this->reconnect,
'create' => $this->create, 'create' => $this->create,
'update', 'policy' => $this->update, 'update', 'policy' => $this->update,
'session' => $this->session,
'journal' => $this->journal, 'journal' => $this->journal,
default => throw new exception("Свойство \"$name\" не найдено", 404) default => throw new exception("Свойство \"$name\" не найдено", 404)
}; };
@ -199,6 +196,7 @@ final class connection
'reconnect' => isset($this->reconnect), 'reconnect' => isset($this->reconnect),
'create' => isset($this->create), 'create' => isset($this->create),
'update', 'policy' => isset($this->update), 'update', 'policy' => isset($this->update),
'session' => isset($this->session),
'journal' => isset($this->journal), 'journal' => isset($this->journal),
default => throw new exception("Свойство \"$name\" не найдено", 404) default => throw new exception("Свойство \"$name\" не найдено", 404)
}; };

View File

@ -4,63 +4,43 @@ declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
// Files of the project use mirzaev\arangodb\terminal;
use mirzaev\arangodb\terminal,
mirzaev\arangodb\connection,
mirzaev\arangodb\enumerations\collection\type;
// Librsry for ArangoDB use ArangoDBClient\Connection as _connection;
use ArangoDBClient\Connection as _connection, use ArangoDBClient\Document as _document;
ArangoDBClient\Document as _document, use ArangoDBClient\Edge as _edge;
ArangoDBClient\Edge as _edge, use ArangoDBClient\DocumentHandler as _document_handler;
ArangoDBClient\DocumentHandler as _document_handler, use ArangoDBClient\EdgeHandler as _edge_handler;
ArangoDBClient\EdgeHandler as _edge_handler;
// Built-in libraries
use exception;
/** /**
* Document * Документ
*
* Handlers of document in ArangoDB
* *
* @package mirzaev\arangodb * @package mirzaev\arangodb
*
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy> * @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/ */
class document class document
{ {
/** /**
* Write * Записать
* *
* @param _connection $session Сессия соединения с базой данных
* @param string $collection Коллекция * @param string $collection Коллекция
* @param ?array $data Данные * @param ?array $data Данные
* @param bool $check Проверка на запись в базу данных * @param bool $check Проверка на запись в базу данных
* @param ?terminal $terminal Instance of the terminal * @param ?terminal $terminal Инстанция терминала
* @param array &$errors Registry of errors
* *
* @return string|null Идентификатор * @return string|null Идентификатор
*
* @todo
* 1. Bind parameters
*/ */
public static function write( public static function write(_connection $session, string $collection, ?array $data = [], bool $check = false, ?terminal $terminal = null): ?string
string $collection, {
?array $data = [],
bool $check = false,
?terminal $terminal = null,
array &$errors = []
): ?string {
try {
// Инициализация коллекции // Инициализация коллекции
collection::initialize($collection, isset($data['_from'], $data['_to']) ? type::edge : type::document); collection::init($session, $collection, isset($data['_from'], $data['_to']));
if (isset($data['_from'], $data['_to'])) { if (isset($data['_from'], $data['_to'])) {
// Ребро // Ребро
// Инициализация обработчика рёбер // Инициализация обработчика рёбер
$documents = new _edge_handler(connection::$session); $documents = new _edge_handler($session);
// Инициализация ребра // Инициализация ребра
$document = new _edge(); $document = new _edge();
@ -75,7 +55,7 @@ class document
// Вершина // Вершина
// Инициализация обработчика вершин // Инициализация обработчика вершин
$documents = new _document_handler(connection::$session); $documents = new _document_handler($session);
// Инициализация вершины // Инициализация вершины
$document = new _document(); $document = new _document();
@ -110,80 +90,25 @@ class document
// Возврат идентификатора коллекции // Возврат идентификатора коллекции
return $id; return $id;
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
// Exit (fail)
return false;
} }
/** /**
* Update * Обновить
* *
* @param array &$errors Registry of errors * @param _connection $session Сессия соединения с базой данных
* @param _document $document Instance of the document * @param _document $document Инстанция документа вершины
* *
* @return bool Has the document been updated? * @return bool Статус обработки
*/ */
public static function update(_document $document, array &$errors = []): bool public static function update(_connection $session, _document $document): bool
{ {
try { // Инициализация обработчика вершин
// Initialize the handler of documents $documents = new _document_handler($session);
$documents = new _document_handler(connection::$session);
// Writing date of the updating to the updating document // Запись даты обновления в инстанцию документа
$document->set('updated', time()); $document->set('updated', time());
// Writing and exit (success) // Запись в базу данных
return $documents->update($document); return $documents->update($document);
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
// Exit (fail)
return false;
}
/**
* Delete
*
* @param _document $document Instance of the document
* @param array &$errors Registry of errors
*
* @return bool Has the document been deleted?
*/
public static function delete(_document $document, array &$errors = []): bool
{
try {
// Initialize the handler of documents
$documents = new _document_handler(connection::$session);
// Delete abd exit (success)
return $documents->remove($document);
} catch (exception $e) {
// Writing to registry of errors
$errors[] = [
'text' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'stack' => $e->getTrace()
];
}
// Exit (fail)
return false;
} }
} }

View File

@ -1,36 +0,0 @@
<?php
declare(strict_types=1);
namespace mirzaev\arangodb\enumerations\collection;
// Library for ArangoDB
use ArangoDBClient\Collection as _collection;
/**
* Types of collections
*
* @package mirzaev\arangodb\enumerations\collection
*
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
enum type
{
case document;
case edge;
/**
* Read code of the type from library for ArangoDB
*
* @return int Code of the type
*/
public function code(): int
{
// Exit (success)
return match ($this) {
type::document => _collection::TYPE_DOCUMENT,
type::edge => _collection::TYPE_EDGE
};
}
}

View File

@ -4,26 +4,12 @@ declare(strict_types=1);
namespace mirzaev\arangodb; namespace mirzaev\arangodb;
// Built-in libraries
use exception;
/**
* Terminal
*
* lol sorry
* i did not want to do this
*
* @package mirzaev\arangodb
*
* @license http://www.wtfpl.net/ Do What The Fuck You Want To Public License
* @author Arsen Mirzaev Tatyano-Muradovich <arsen@mirzaev.sexy>
*/
class terminal class terminal
{ {
/** /**
* Префикс * Префикс
*/ */
protected const string PREFIX = 'arangodb'; protected const PREFIX = 'arangodb';
/** /**
* Запись в вывод * Запись в вывод