Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor data type #22

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,15 @@
{
"type": "composer",
"url": "https://asset-packagist.org"
},
{
"type": "vcs",
"url": "[email protected]:tecnocen-com/yii2-roa.git"
}
],
"require": {
"php": "^7.1",
"tecnocen/yii2-roa": ">0.4.0",
"tecnocen/yii2-roa": "dev-typecast as 0.5.x-dev",
"tecnocen/yii2-rmdb": "*",
"yiisoft/yii2": "~2.0.10"
},
Expand Down
36 changes: 19 additions & 17 deletions docs/guide-es/data-type.php
Original file line number Diff line number Diff line change
@@ -1,30 +1,32 @@
Data Type (Tipo de Dato)
=========
========================

Cada campo tiene un tipo de dato que ayuda a convertir los valores y
organizarlos en como deben ser almacenados internamente en la base de datos.

Cada registro de 'tipo de dato' contiene un name unico y un cast valido

El cast debe de ser el nombre de un metodo estatico de la clase
`tecnocen\formgenerator\models\DataType` o una firma del tipo
`ruta\completa\Clase:metodo` donde `ruta\completa\Clase` es una clase auto
cargable incluyendo namespace y `metodo` es el nombre de un metodo estatico y
publico en la clase anterior.
Cada registro de 'tipo de dato' contiene un name unico y el nombre completo de
una clase la cual implementa la interfaz
`tecnocen\formgenerator\dataTypes\DataTypeInterface`

Ejemplos

- `stringCast`
- `app\models\DataType:json`
- `tecnocen\formgenerator\dataTypes\BooleanDataType`
- `app\JsonDataType`
- `common\dataTypes\ProtectedFileDataType`

Para habilitar los tipos de datos soportados por defectos necesitas correr el
fixture `tecnocen\formgenerator\fixtures\DataTypeFixture` que proporciona Ejemplos
fixture `tecnocen\formgenerator\fixtures\DataTypeFixture` que proporciona
tipos de datos.

- String tipo de dato con cast como string
- Integer tipo de dato con cast como integer
- Decimal tipo de dato con cast como float
- Boolean tipo de dato con cast como boolean
- File tipo de dato con cast como yii\web\UploadedFile
- `string`
- `integer`
- `decimal`
- `boolean`
- `public-file` almacena archivos en la carpeta `@webroot` y muestra la url para
su lectura.

Puedes encontrar la lista completa de tipos de datos en el recurso de solo
lectura `data-type`.

Puedes encontrar la lista completa de tipos de datos en el recurso `data-type`.
Traducciones
------------
24 changes: 13 additions & 11 deletions src/behaviors/Positionable.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use yii\base\InvalidConfigException;
use yii\db\ActiveRecord;
use yii\db\ActiveQuery;
use yii\db\Expression as DbExpression;
use yii\validators\Validator;

Expand Down Expand Up @@ -99,6 +100,7 @@ public function attachValidators()
if (!$this->attachValidators) {
return;
}

$this->owner->validators[] = Validator::createValidator(
'default',
$this->owner,
Expand All @@ -121,9 +123,9 @@ public function attachValidators()
}

/**
* @return \yii\db\ActiveQuery
* @return ActiveQuery
*/
public function getSiblings()
public function getSiblings(): ActiveQuery
{
return $this->owner->hasMany(get_class($this->owner), [
$this->parentAttribute => $this->parentAttribute
Expand Down Expand Up @@ -188,15 +190,15 @@ public function afterDelete()

/**
* Update the position of siblings on the database.
* @param integer|DbExpression $position the new position.
* @param int|DbExpression $position the new position.
* @param array $condition the extra condition to update siblings.
* @return integer the number of updated siblings.
* @return int the number of updated siblings.
*/
protected function updateSiblingsPosition(
$position,
array $condition,
array $orderBy = []
) {
): int {
$params = [];
$queryBuilder = $this->owner->getDb()->getQueryBuilder();
return $this->owner->getDb()->createCommand(
Expand All @@ -222,10 +224,10 @@ protected function updateSiblingsPosition(
/**
* Increases the position of siblings by 1.
*
* @var array $conditoin the extra condition to update siblings.
* @return integer the number of updated siblings.
* @param array $conditoin the extra condition to update siblings.
* @return int the number of updated siblings.
*/
protected function increaseSiblingsPosition(array $condition)
protected function increaseSiblingsPosition(array $condition): int
{
return $this->updateSiblingsPosition(
$this->positionIncrease,
Expand All @@ -237,10 +239,10 @@ protected function increaseSiblingsPosition(array $condition)
/**
* Decreases the position of siblings by 1.
*
* @var array $conditoin the extra condition to update siblings.
* @return integer the number of updated siblings.
* @param array $conditoin the extra condition to update siblings.
* @return int the number of updated siblings.
*/
protected function decreaseSiblingsPosition(array $condition)
protected function decreaseSiblingsPosition(array $condition): int
{
return $this->updateSiblingsPosition(
$this->positionDecrease,
Expand Down
51 changes: 51 additions & 0 deletions src/dataStrategies/BaseDataStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

namespace tecnocen\formgenerator\dataStrategies;

use tecnocen\formgenerator\models\SolicitudeValue;
use yii\helpers\ArrayHelper;

abstract class BaseDataStrategy implements DataStrategy
{
/**
* @inheritdoc
*/
public function __construct()
{
}

/**
* @inheritdoc
*/
public function load(
SolicitudeValue $model,
?array $data,
?string $formName = null
): bool {
$scope = $formName === null ? $model->formName() : $formName;
if (empty($data)) {
return false;
}

if ($scope === '') {
if (isset($data['raw'])) {
$model->raw = $data['raw'];
return true;
}

return false;
} elseif (isset($data[$scope]['raw'])) {
$model->raw = $data[$scope]['raw'];
return true;
}

return false;
}

/**
* @inheritdoc
*/
public function erase($raw)
{
}
}
41 changes: 41 additions & 0 deletions src/dataStrategies/BooleanDataStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

namespace tecnocen\formgenerator\dataStrategies;

use tecnocen\formgenerator\models\SolicitudeValue;
use yii\helpers\ArrayHelper;

class BooleanDataStrategy extends BaseDataStrategy
{
/**
* @inheritdoc
*/
public function store(SolicitudeValue $model, $value)
{
if (null === $raw || '' === $raw) {
return null;
}

if (0 == $raw) {
return 0;
}

return 1;
}

/**
* @inheritdoc
*/
public function read($raw)
{
if (null === $raw) {
return null;
}

if (0 == $raw) {
return false;
}

return true;
}
}
89 changes: 89 additions & 0 deletions src/dataStrategies/BucketDataStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

namespace tecnocen\formgenerator\dataStrategies;

use tecnocen\formgenerator\models\SolicitudeValue;
use yii2tech\filestorage\BucketInterface;
use yii\web\UploadedFile;

/**
* Data strategy which utilizes the `BucketInterface` to store uploaded files.
*
* Needs to extends this class and implement the `getBucket()` method.
*
* ```php
* class ImageBucketDataStrategy extends BucketDataStrategy
* {
* public function getBucket(): BucketInterface
* {
* return Yii::$app->fileStorage->getBucket('images');
* }
* }
* ```
*
* This assumes there is a component `fileStorage` configured in the application
* and it contains a bucket named 'images'.
*
* > Requires yii2tech/file-storage
*
* @author Angel (Faryshta) Guevara <[email protected]>
*/
abstract class BucketDataStrategy extends BaseDataStrategy
{
/**
* @return BucketInterface the bucket which will be used to store uploaded
* files.
*/
abstract public getBucket(): BucketInterface;

/**
* @inheritdoc
*/
public function load(
SolicitudeValue $model,
?array $data,
?string $formName = null
): bool {
$scope = $formName === null ? $model->formName() : $formName;
$model->raw = UploadedFile::getInstanceByName(
$scope ? $scope '[raw]' : 'raw'
);

return null !== $model->raw;
}

/**
* @inheritdoc
*/
public function store(SolicitudeValue $model, $value)
{
$name = $this->getName($value);
$this->getBucket()->copyFileIn($value->tempName, $name);

return $name;
}

/**
* @inheritdoc
*/
public function read($raw)
{
return $this->getBucket()->getFileUrl($raw);
}

/**
* @inheritdoc
*/
public function erase($raw)
{
$this->getBucket()->deleteFile($raw);
}

/**
* @return string name used to store the file into the folder and database.
*/
protected function getName(UploadedFile $value): string
{
return $value->getName();
}
}
55 changes: 55 additions & 0 deletions src/dataStrategies/DataStrategy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

namespace tecnocen\formgenerator\dataStrategies;

use tecnocen\formgenerator\models\SolicitudeValue;

/**
* Strategy to load, store and read information for each data type.
*/
interface DataStrategy
{
/**
* Construct the strategy.
*/
public function __construct();

/**
* Loads information from the data in the request to the model.
*
* @param SolicitudeValue $model
* @param ?array $data
* @param ?string $formName
* @return bool whether the data was loaded
*/
public function load(
SolicitudeValue $model,
?array $data,
?string $formName = null
): bool;

/**
* Process the information from the request for its storage.
*
* @param Model $model
* @param mixed $value
* @return mixed the value to be stored on the database
*/
public function store(SolicitudeValue $model, $value);

/**
* Takes the information stored in the database and process it to be
* presented to the end user.
*
* @param mixed $raw the raw value stored in the database
* @return mixed the processed value shown to the end user.
*/
public function read($raw);

/**
* Called after deleting a SolicitudeValue record.
*
* @param mixed $raw
*/
public function erase($raw);
}
Loading