Skip to content
This repository was archived by the owner on Feb 4, 2023. It is now read-only.
Merged
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
37 changes: 37 additions & 0 deletions .php_cs.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

$header = <<<'EOF'
This file is part of the SgDatatablesBundle package.

(c) stwe <https://github.com/stwe/DatatablesBundle>

For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;

$finder = PhpCsFixer\Finder::create()
->exclude('vendor/')
->in(__DIR__)
->append([__DIR__.'/php-cs-fixer'])
;

$config = PhpCsFixer\Config::create()
->setRiskyAllowed(true)
->setRules([
'@PHP56Migration' => true,
'@PhpCsFixer' => true,
'@PhpCsFixer:risky' => true,
'@PHPUnit60Migration:risky' => true,
'@Symfony' => true,
'array_syntax' => ['syntax' => 'short'],
'header_comment' => ['header' => $header],
'list_syntax' => ['syntax' => 'long'],
'no_php4_constructor' => true,
'no_superfluous_phpdoc_tags' => true,
'no_useless_return' => true,
'not_operator_with_successor_space' => true,
])
->setFinder($finder)
;

return $config;
52 changes: 23 additions & 29 deletions Command/CreateDatatableCommand.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

/**
/*
* This file is part of the SgDatatablesBundle package.
*
* (c) stwe <https://github.com/stwe/DatatablesBundle>
Expand All @@ -11,23 +11,17 @@

namespace Sg\DatatablesBundle\Command;

use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Exception;
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCommand;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
use Sg\DatatablesBundle\Generator\DatatableGenerator;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCommand;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Exception;

/**
* Class CreateDatatableCommand
*
* @package Sg\DatatablesBundle\Command
*/
class CreateDatatableCommand extends GenerateDoctrineCommand
{
//-------------------------------------------------
Expand All @@ -41,11 +35,12 @@ protected function configure()
{
$this
->setName('sg:datatable:generate')
->setAliases(array('sg:datatables:generate', 'sg:generate:datatable', 'sg:generate:datatables'))
->setAliases(['sg:datatables:generate', 'sg:generate:datatable', 'sg:generate:datatables'])
->setDescription('Generates a new Datatable based on a Doctrine entity.')
->addArgument('entity', InputArgument::REQUIRED, 'The entity class name (shortcut notation).')
->addOption('fields', 'f', InputOption::VALUE_OPTIONAL, 'The fields to create columns in the new Datatable.')
->addOption('overwrite', 'o', InputOption::VALUE_NONE, 'Allow to overwrite an existing Datatable.');
->addOption('overwrite', 'o', InputOption::VALUE_NONE, 'Allow to overwrite an existing Datatable.')
;
}

/**
Expand All @@ -58,7 +53,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
list($bundle, $entity) = $this->parseShortcutNotation($entity);

// get entity's metadata
$entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle)."\\".$entity;
$entityClass = $this->getContainer()->get('doctrine')->getAliasNamespace($bundle).'\\'.$entity;
$metadata = $this->getEntityMetadata($entityClass);

// get fields option
Expand Down Expand Up @@ -100,7 +95,7 @@ protected function createGenerator()
*/
protected function getSkeletonDirs(BundleInterface $bundle = null)
{
$skeletonDirs = array();
$skeletonDirs = [];
$skeletonDirs[] = $this->getContainer()->get('kernel')->locateResource('@SgDatatablesBundle/Resources/views/skeleton');

return $skeletonDirs;
Expand All @@ -119,12 +114,12 @@ protected function getSkeletonDirs(BundleInterface $bundle = null)
*/
private static function parseFields($input)
{
$fields = array();
$fields = [];

foreach (explode(' ', $input) as $value) {
$elements = explode(':', $value);

$row = array();
$row = [];
$row['property'] = $elements[0];
$row['column_type'] = 'Column::class';
$row['data'] = null;
Expand All @@ -134,9 +129,11 @@ private static function parseFields($input)
switch ($elements[1]) {
case 'datetime':
$row['column_type'] = 'DateTimeColumn::class';

break;
case 'boolean':
$row['column_type'] = 'BooleanColumn::class';

break;
}
}
Expand All @@ -150,14 +147,11 @@ private static function parseFields($input)
/**
* Get Id from metadata.
*
* @param array $metadata
*
* @return mixed
* @throws Exception
*/
private function getIdentifierFromMetadata(array $metadata)
{
if (count($metadata[0]->identifier) > 1) {
if (\count($metadata[0]->identifier) > 1) {
throw new Exception('CreateDatatableCommand::getIdentifierFromMetadata(): The Datatable generator does not support entities with multiple primary keys.');
}

Expand All @@ -168,24 +162,24 @@ private function getIdentifierFromMetadata(array $metadata)
* Returns an array of fields. Fields can be both column fields and
* association fields.
*
* @param ClassMetadataInfo $metadata
*
* @return array $fields
*/
private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
{
$fields = array();
$fields = [];

foreach ($metadata->fieldMappings as $field) {
$row = array();
$row = [];
$row['property'] = $field['fieldName'];

switch ($field['type']) {
case 'datetime':
$row['column_type'] = 'DateTimeColumn::class';

break;
case 'boolean':
$row['column_type'] = 'BooleanColumn::class';

break;
default:
$row['column_type'] = 'Column::class';
Expand All @@ -201,11 +195,11 @@ private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
$targetMetadata = $this->getEntityMetadata($targetClass);

foreach ($targetMetadata[0]->fieldMappings as $field) {
$row = array();
$row = [];
$row['property'] = $relation['fieldName'].'.'.$field['fieldName'];
$row['column_type'] = 'Column::class';
$row['title'] = ucwords(str_replace('.', ' ', $row['property']));
if ($relation['type'] === ClassMetadataInfo::ONE_TO_MANY || $relation['type'] === ClassMetadataInfo::MANY_TO_MANY) {
if (ClassMetadataInfo::ONE_TO_MANY === $relation['type'] || ClassMetadataInfo::MANY_TO_MANY === $relation['type']) {
$row['data'] = $relation['fieldName'].'[, ].'.$field['fieldName'];
} else {
$row['data'] = null;
Expand Down
68 changes: 29 additions & 39 deletions Controller/DatatableController.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

/**
/*
* This file is part of the SgDatatablesBundle package.
*
* (c) stwe <https://github.com/stwe/DatatablesBundle>
Expand All @@ -11,22 +11,17 @@

namespace Sg\DatatablesBundle\Controller;

use DateTime;
use Doctrine\DBAL\Types\Type;
use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessor;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\DBAL\Types\Type;
use Exception;
use DateTime;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
* Class DatatableController
*
* @package Sg\DatatablesBundle\Controller
*/
class DatatableController extends Controller
{
//-------------------------------------------------
Expand All @@ -36,12 +31,11 @@ class DatatableController extends Controller
/**
* Edit field.
*
* @param Request $request
*
* @Route("/datatables/edit/field", methods={"POST"}, name="sg_datatables_edit")
*
* @return Response
* @throws Exception
*
* @return Response
*/
public function editAction(Request $request)
{
Expand All @@ -58,7 +52,7 @@ public function editAction(Request $request)
$path = $request->request->get('path'); // for toMany - the current element

// check token
if (!$this->isCsrfTokenValid('sg-datatables-editable', $token)) {
if (! $this->isCsrfTokenValid('sg-datatables-editable', $token)) {
throw new AccessDeniedException('DatatableController::editAction(): The CSRF token is invalid.');
}

Expand All @@ -69,7 +63,8 @@ public function editAction(Request $request)
/** @noinspection PhpUndefinedMethodInspection */
$accessor = PropertyAccess::createPropertyAccessorBuilder()
->enableMagicCall()
->getPropertyAccessor();
->getPropertyAccessor()
;

// normalize the new value
$value = $this->normalizeValue($originalTypeOfField, $value);
Expand All @@ -96,53 +91,51 @@ public function editAction(Request $request)
* Finds an object by its primary key / identifier.
*
* @param string $entityClassName
* @param mixed $pk
*
* @return object
*/
private function getEntityByPk($entityClassName, $pk)
private function getEntityByPk($entityClassName, $pk): object
{
$em = $this->getDoctrine()->getManager();

$entity = $em->getRepository($entityClassName)->find($pk);
if (!$entity) {
if (! $entity) {
throw $this->createNotFoundException('DatatableController::getEntityByPk(): The entity does not exist.');
}

return $entity;
}

/**
* Normalize value.
*
* @param string $originalTypeOfField
* @param mixed $value
*
* @return bool|DateTime|float|int|null|string
* @throws Exception
*
* @return bool|DateTime|float|int|string|null
*/
private function normalizeValue($originalTypeOfField, $value)
private function normalizeValue(string $originalTypeOfField, $value)
{
switch ($originalTypeOfField) {
case Type::DATETIME:
$value = new DateTime($value);

break;
case Type::BOOLEAN:
$value = $this->strToBool($value);

break;
case Type::TEXT:
case Type::STRING:
break;
case Type::SMALLINT:
case Type::INTEGER:
$value = (int) $value;

break;
case Type::BIGINT:
$value = (string) $value;

break;
case Type::FLOAT:
case Type::DECIMAL:
$value = (float) $value;

break;
default:
throw new Exception("DatatableController::prepareValue(): The field type {$originalTypeOfField} is not editable.");
Expand All @@ -152,27 +145,24 @@ private function normalizeValue($originalTypeOfField, $value)
}

/**
* String to boolean.
*
* @param string $str
*
* @return null|bool
* @throws Exception
*/
private function strToBool($str)
private function strToBool(string $str): ?bool
{
$str = strtolower($str);

if ('null' === $str) {
return null;
}

if ($str === 'true' || $str === '1') {
if ('true' === $str || '1' === $str) {
return true;
} elseif ($str === 'false' || $str === '0') {
}

if ('false' === $str || '0' === $str) {
return false;
} else {
throw new Exception('DatatableController::strToBool(): Cannot convert string to boolean, expected string "true" or "false".');
}

throw new Exception('DatatableController::strToBool(): Cannot convert string to boolean, expected string "true" or "false".');
}
}
Loading