Skip to content

Commit

Permalink
Merge pull request #4 from dekemvrios/master
Browse files Browse the repository at this point in the history
sincronizando com repo original
  • Loading branch information
gabrielrassweiler authored Jun 15, 2022
2 parents ad8b3f8 + de874fb commit 12c0bdb
Show file tree
Hide file tree
Showing 22 changed files with 526 additions and 257 deletions.
31 changes: 31 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,37 @@ Todas as modificações relevantes para phpexoressive serão documentadas neste

O formato é baseado [Keep a CHANGELOG](http://keepachangelog.com/) e esse projeto adere ao [Semantic Versioning 2.0.0](http://semver.org/).

## 1.6.3 - 2018-03-23

## Added
- Adicionado suporte a tipo schema bool e boolean para operadores relacionados ao construir query de consulta der registro.

## Fixed
- Removidos campos json de operadores não suportados ao construir query de consulta de registro.

## 1.6.2 - 2018-03-22

## Added
- Adicionado parâmetro times ao método de replicação, possibilitando retorno de array contendo registros replicados a
partir de model consultado.

## Changed
- Atribuido mensagem explicativa de erro a item mensagem de Exception lançada por operações de persistência, sobrescrevendo
comportamento de classe abstrata TExceptionAbstract.

## 1.6.1 - 2018-02-27

## Changed
- Aprimorado construção de query de métodos select e count de modo a desconsiderar coluna especificada no conjunto de
argumentos quando essa não estiver presente no schema do registro a ser consultado, ou, quando o operador solicitado é
incompatível com o tipo do respectivo campo.

## 1.6.0 - 2018-01-18

## Added
- Implementado método de delação virtual de registro. Se o model possuir uma propredade com nome de 'active', é possível
atribuir false a seu valor por meio do método 'disable' no contexto do model.

## 1.5.0 - 2017-11-07

## Added
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
}
},
"scripts": {
"test": "php vendor/bin/phpunit --testdox",
"test": "php vendor/bin/phpunit",
"check-style": "vendor/bin/phpcs --standard=psr2 src tests",
"fix-style": "vendor/bin/phpcbf --standard=psr2 src tests"
}
Expand Down
4 changes: 2 additions & 2 deletions phpunit.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Expressive Suite Test">
<directory>tests/Expressive/</directory>
<testsuite name="Integration Test">
<directory>tests/Integration/</directory>
</testsuite>
</testsuites>
<filter>
Expand Down
16 changes: 14 additions & 2 deletions src/Abstractions/ExpressiveAbstract.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ public function delete()
return $this->getDatabaseContainer()->delete($this);
}

/**
* @return boolean
*
* @throws TExceptionAbstract
*/
public function disable()
{
return $this->getDatabaseContainer()->disable($this);
}

/**
* @return ExpressiveContract|boolean
*
Expand Down Expand Up @@ -163,10 +173,12 @@ public function patch()
}

/**
* @param int $times
*
* @return ExpressiveContract|boolean
*/
public function replicate()
public function replicate($times = 1)
{
return $this->getDatabaseContainer()->replicate($this);
return $this->getDatabaseContainer()->replicate($this, $times);
}
}
29 changes: 29 additions & 0 deletions src/Classes/Illuminate/Delete/DeleteBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,4 +149,33 @@ private function deleteHasMany($model)
$this->getRelationshipBuilder()->hasMany($model, $dependency);
}
}

/**
* @param ExpressiveContract $model
*
* @return boolean
*
* @throws TExceptionAbstract
*/
public function disable(ExpressiveContract $model)
{
$record = $model->search();
if (!$record || !$this->useSoftDelete($record)) {
return false;
}

$record->active = false;

return $record->update();
}

/**
* @param $record
*
* @return bool
*/
private function useSoftDelete($record): bool
{
return property_exists($record, 'active') && $record->active;
}
}
87 changes: 76 additions & 11 deletions src/Classes/Illuminate/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

use Illuminate\Database\Capsule\Manager as Capsule;
use Solis\Expressive\Contracts\ExpressiveContract;
use Solis\Expressive\Schema\Contracts\SchemaContract;
use Solis\Expressive\Exception;
use Solis\Expressive\Schema\Contracts\Entries\Property\PropertyContract;

/**
* Class StmtBuilder
Expand All @@ -13,6 +15,8 @@
*/
class Builder
{

const PROPERTY_NOT_FOUND = 'PROPRIEDADE %s NÃO ENCONTRADA NA DEFINIÇÃO DO SCHEMA';
/**
* @var string
*/
Expand All @@ -33,22 +37,29 @@ class Builder
*/
private $stmt;

/**
* @var SchemaContract
*/
private $schema;

/**
* StmtBuilder constructor.
*
* @param string $table
* @param array $arguments
* @param array $options
* @param SchemaContract $schema
* @param array $arguments
* @param array $options
*/
public function __construct(string $table, array $arguments = [], array $options = [])
public function __construct(SchemaContract $schema, array $arguments = [], array $options = [])
{
$this->table = $table;
$this->table = $schema->getRepository();

$this->schema = $schema;

$this->arguments = $this->toMultiArray($arguments);

$this->options = $options;

$this->stmt = Capsule::table($table);
$this->stmt = Capsule::table($this->table);
}

/**
Expand Down Expand Up @@ -94,17 +105,55 @@ private function addWhere($stmt, $argument)
* @param array $argument
*
* @return \Illuminate\Database\Query\Builder
*
* @throws Exception
*/
private function addBasicWhere($stmt, $argument)
{
$stmt->where(
$column = $argument['column'];
/**
* @var PropertyContract $entry
*/
if (!$entry = $this->schema->getPropertyEntryByIdentifier($column)) {
throw new Exception(sprintf(self::PROPERTY_NOT_FOUND, $column), 400);
};

if (!$entry->getBehavior()->isPersistent()) {
return $stmt;
}

$operator = strtolower($argument['operator'] ?? '=');
if (!$this->checkOperatorAndType($operator, $entry->getType())) {
return $stmt;
}

return $stmt->where(
$argument['column'],
$argument['operator'] ?? '=',
$operator,
$argument['value'],
$argument['chainType'] ?? 'and'
);
}

return $stmt;
/**
* @param string $operator
* @param string $type
*
* @return bool
*/
private function checkOperatorAndType(string $operator, string $type)
{
$operators = [
'like' => ['string', 'object', 'composition'],
'=' => ['int', 'string', 'float', 'json', 'date', 'bool', 'boolean', 'object', 'composition'],
'<=' => ['int', 'string', 'float', 'date', 'object', 'composition'],
'<' => ['int', 'string', 'float', 'date', 'object', 'composition'],
'>=' => ['int', 'string', 'float', 'date', 'object', 'composition'],
'>' => ['int', 'string', 'float', 'date', 'object', 'composition'],
'!=' => ['int', 'string', 'float', 'date', 'bool', 'boolean'],
];

return in_array($type, $operators[$operator] ?? []);
}

/**
Expand Down Expand Up @@ -195,6 +244,22 @@ public function orderBy()
$orderBy = $this->toMultiArray($orderBy);

foreach ($orderBy as $option) {

/**
* @var PropertyContract $entry
*/
if (!$entry = $this->schema->getPropertyEntryByIdentifier($option['column'])) {
continue;
};

if (!$entry->getBehavior()->isPersistent()) {
continue;
}

if (!in_array(trim(strtolower($option['direction'])), ['asc', 'desc'])) {
continue;
}

$this->stmt->orderBy(
$option['column'],
$option['direction'] ?? 'asc'
Expand Down Expand Up @@ -234,11 +299,11 @@ public function dependencies()
{
$dependencies = $this->options['withDependencies'] ?? false;

if ($dependencies == 'true') {
if ($dependencies == 'true' || $dependencies == 1) {
return true;
}

if ($dependencies == 'false') {
if ($dependencies == 'false' || $dependencies == 0) {
return false;
}

Expand Down
37 changes: 18 additions & 19 deletions src/Classes/Illuminate/Replicate/ReplicateBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Solis\Expressive\Classes\Illuminate\Replicate;

use Illuminate\Database\Capsule\Manager as Capsule;
use Solis\Expressive\Exception;
use Solis\Expressive\Schema\Contracts\Entries\Property\PropertyContract;
use Solis\Expressive\Classes\Illuminate\Insert\InsertBuilder;
use Solis\Expressive\Abstractions\ExpressiveAbstract;
Expand Down Expand Up @@ -45,33 +46,31 @@ public function setInsertBuilder($insertBuilder)
{
$this->insertBuilder = $insertBuilder;
}

/**
* @param ExpressiveContract $model
* @param int $times
*
* @return ExpressiveContract|boolean
* @return ExpressiveContract|boolean|ExpressiveAbstract[]
*
* @throws TExceptionAbstract
* @throws Exception
*/
public function replicate(ExpressiveContract $model)
public function replicate(ExpressiveContract $model, $times = 1)
{
if (empty($model::$schema->getRepository())) {
throw new TException(
__CLASS__,
__METHOD__,
'database schema entry has not been defined for ' . get_class($model),
400
);
if (!$original = $model->search()) {
throw new Exception('Registro original ' . get_class($model) . ' não encontrado na base de dados', 400);
}
$original = $model->search();
if (empty($original)) {
throw new TException(
__CLASS__,
__METHOD__,
'object for ' . get_class($model) . ' has not been found in the database',
400
);

$records = [];
for ($i = 0; $i < $times; $i++) {
if (!$record = $this->create($original)) {
throw new Exception('Erro ao criar réplica de registro', 500);
}

$records[] = $record;
}
return $this->create($original);

return count($records) === 1 ? $records[0] : $records;
}
/**
* @param ExpressiveContract $model
Expand Down
8 changes: 2 additions & 6 deletions src/Classes/Illuminate/Select/SelectBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ public function setRelationshipBuilder($relationshipBuilder)
*/
public function select(ExpressiveContract $model, array $arguments, array $options = [])
{
$table = $model->getSchema()->getRepository();

$Builder = new Builder($table, $arguments, $options);
$Builder = new Builder($model->getSchema(), $arguments, $options);

$stmt = $Builder->where()->orderBy()->limit()->getStmt();

Expand Down Expand Up @@ -154,9 +152,7 @@ public function search(ExpressiveContract $model, $dependencies = true)
*/
public function count(ExpressiveContract $model, array $arguments = [])
{
$table = $model->getSchema()->getRepository();

$Builder = new Builder($table, $arguments);
$Builder = new Builder($model->getSchema(), $arguments);

$stmt = $Builder->where()->getStmt();

Expand Down
15 changes: 13 additions & 2 deletions src/Classes/Illuminate/Wrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,16 @@ public function delete(ExpressiveContract $model)
return boolval($this->getDeleteBuilder()->delete($model));
}

/**
* @param ExpressiveContract $model
*
* @return bool
*/
public function disable(ExpressiveContract $model)
{
return boolval($this->getDeleteBuilder()->disable($model));
}

/**
* @param ExpressiveContract $model
*
Expand Down Expand Up @@ -277,12 +287,13 @@ public function patch(ExpressiveContract $model)

/**
* @param ExpressiveContract $model
* @param int $times
*
* @return ExpressiveContract|boolean
*/
public function replicate(ExpressiveContract $model)
public function replicate(ExpressiveContract $model, $times = 1)
{
return $this->getReplicateBuilder()->replicate($model);
return $this->getReplicateBuilder()->replicate($model, $times);
}

/**
Expand Down
Loading

0 comments on commit 12c0bdb

Please sign in to comment.