I am building an entity generator in order to update my DB's structure and data according to a distant one (DB), via SOAP WS...
I get the structure from an array, and am currently writing my entity classes by myself, with a file_put_content().
But as I advance, I can't help noticing that the Doctrine\ORM\Tools\EntityGenerator already does what I intend to do, way better I would ever be able to!!
So i was wondering if there was a way to use this implemented generator from my controller?
I mean, this is what Symfony is all about right? Using existing classes & bundles from anywhere in my code? :)
Any idea someOne?
Thx :)
You can use this code:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Bundle\BundleInterface;
use Sensio\Bundle\GeneratorBundle\Generator\DoctrineEntityGenerator;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
class MyController extends Controller
{
private $generator;
public function generateEntityAction()
{
$format = "annotation"; //it can also be yml/php/xml
$fields = "title:string(255) body:text";
$withRepository = false; //true/false
$entity = Validators::validateEntityName("MyBundle:EntityName");
list($bundle, $entity) = $this->parseShortcutNotation($entity);
$format = Validators::validateFormat($format);
$fields = $this->parseFields($fields);
$bundle = $this->get('service_container')->get('kernel')->getBundle($bundle);
$generator = $this->getGenerator();
$generator->generate($bundle, $entity, $format, array_values($fields), $withRepository);
}
protected function createGenerator()
{
return new DoctrineEntityGenerator($this->get('service_container')->get('filesystem'), $this->get('service_container')->get('doctrine'));
}
protected function getSkeletonDirs(BundleInterface $bundle = null)
{
$skeletonDirs = array();
if (isset($bundle) && is_dir($dir = $bundle->getPath() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
if (is_dir($dir = $this->get('service_container')->get('kernel')->getRootdir() . '/Resources/SensioGeneratorBundle/skeleton')) {
$skeletonDirs[] = $dir;
}
$skeletonDirs[] = __DIR__ . '/../Resources/skeleton';
$skeletonDirs[] = __DIR__ . '/../Resources';
return $skeletonDirs;
}
protected function getGenerator(BundleInterface $bundle = null)
{
if (null === $this->generator) {
$this->generator = $this->createGenerator();
$this->generator->setSkeletonDirs($this->getSkeletonDirs($bundle));
}
return $this->generator;
}
protected function parseShortcutNotation($shortcut)
{
$entity = str_replace('/', '\\', $shortcut);
if (false === $pos = strpos($entity, ':')) {
throw new \InvalidArgumentException(sprintf('The entity name must contain a : ("%s" given, expecting something like AcmeBlogBundle:Blog/Post)', $entity));
}
return array(substr($entity, 0, $pos), substr($entity, $pos + 1));
}
private function parseFields($input)
{
if (is_array($input)) {
return $input;
}
$fields = array();
foreach (explode(' ', $input) as $value) {
$elements = explode(':', $value);
$name = $elements[0];
if (strlen($name)) {
$type = isset($elements[1]) ? $elements[1] : 'string';
preg_match_all('/(.*)\((.*)\)/', $type, $matches);
$type = isset($matches[1][0]) ? $matches[1][0] : $type;
$length = isset($matches[2][0]) ? $matches[2][0] : null;
$fields[$name] = array('fieldName' => $name, 'type' => $type, 'length' => $length);
}
}
return $fields;
}
}
Mostly, it comes from Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineEntityCommand and Sensio\Bundle\GeneratorBundle\Command\GeneratorCommand
Related
I have created an annotation class called #Module, and a command GenerateModulesCommand. What I want is to find all controller actions that have the #Module annotation.
Example :
/**
*
* #Module(name='sidebar', enabled=true')
*/
public function sidebarAction($name) {
$ape = new ArrayParamsExtension ();
return $this->render('ModuleManagerBundle:Default:sidebar.html.twig', $ape->getArrayParams($name));
}
I want to be able to look at the specific properties in the #Module (name, enabled, etc...)
So far, this is my execute method from my Command :
protected function execute(InputInterface $input, OutputInterface $output) {
$path = $this->getApplication()->getKernel()->locateResource('#ModuleManagerBundle');
$driver = new PHPDriver($path);
$classes = $driver->getAllClassNames();
foreach ($classes as $key => $class) {
$reader = new AnnotationReader();
$annotationReader = new CachedReader(
$reader, new ArrayCache()
);
$reflClass = new ReflectionClass("\Controller\\" . $reportableClass);
$annotation = $annotationReader->getClassAnnotation(
$reflClass, 'Custom_Annotation'
);
if (is_null($annotation)) {
unset($classes[$key]);
}
}
$output->writeln($path);
}
I found this code on sof, but I don't know how to search all Controller classes and all the Actions inside them..
You can try this in your function
use Doctrine\Common\Annotations\AnnotationReader;
your function
public function getControllersWithAnnotationModules()
{
$allAnnotations = new AnnotationReader();
$controllers = array();
foreach ($this->container->get('router')->getRouteCollection()->all() as $route) {
$defaults = $route->getDefaults();
if (isset($defaults['_controller'])) {
$controllerAction = explode(':', $defaults['_controller']);
$controller = $controllerAction[0];
if (!isset($controllers[$controller]) && class_exists($controller)) {
$controllers[$controller] = $controller;
}
}
}
$controllersWithModules = array();
foreach($controllers as $controller){
$reflectionClass = new \ReflectionClass($controller);
$module = $allAnnotations->getClassAnnotation($reflectionClass,'Acme\YourBundle\Module');
if($module)
$controllersWithModules[] = $controller;
}
return $controllersWithModules ;
}
I want to be able to access a code from all my controllers so what is the best way of doing it? The code below is to handle form errors and I've been replicating it in every single controller in my project.
So I want to keep getErrorMessages() somewhere else and access it in controller below.
Note: I read about services but got confused and this example!
Example Controller:
class HelloController extends Controller
{
public function processAction(Request $request)
{
//More code here
if ($form->isValid() !== true)
{
$errors = $this->getErrorMessages($form);
return $this->render('SayHelloBundle:hello.html.twig',
array(
'page' => 'Say Hello',
'form' => $form->createView(),
'form_errors' => $errors
));
}
//More code here
}
private function getErrorMessages(FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $error)
{
$errors[] = $error->getMessage();
}
foreach ($form->all() as $child)
{
if (! $child->isValid())
{
$options = $child->getConfig()->getOptions();
$field = $options['label'] ? $options['label'] : $child->getName();
$errors[$field] = implode('; ', $this->getErrorMessages($child));
}
}
return $errors;
}
}
You could create a class that has all the base operations in it and call that class (or set of classes) in your controllers.
OK did it :)
/var/www/html/local/sport/app/config/config.yml
imports:
- { resource: services.yml }
/var/www/html/local/sport/app/config/services.yml
parameters:
form_errors.class: Football\TeamBundle\Services\FormErrors
services:
form_errors:
class: %form_errors.class%
/var/www/html/local/sport/src/Football/TeamBundle/Services/FormErrors.php
namespace Football\TeamBundle\Services;
use Symfony\Component\Form\FormInterface;
class FormErrors
{
public function getErrors(FormInterface $form)
{
$errors = array();
//This part get global form errors (like csrf token error)
foreach ($form->getErrors() as $error)
{
$errors[] = $error->getMessage();
}
//This part get errors for form fields
foreach ($form->all() as $child)
{
if (! $child->isValid())
{
$options = $child->getConfig()->getOptions();
$field = $options['label'] ? $options['label'] : ucwords($child->getName());
//There can be more than one field error, that's why implode is here
$errors[strtolower($field)] = implode('; ', $this->getErrors($child));
}
}
return $errors;
}
}
controller
if ($form->isValid() !== true) {
$errors = $this->get('form_errors')->getErrors($form);
echo '<pre>'; print_r($errors); exit;
}
I am trying to write a Unit Test using dataProvider to test a controller method.
However the $this->contents always return null. Does dataProvider work in CakePHP's controller test case?
public function initValidateDataProvider() {
$data['Event']['event_type'] = 1;
$data['Event']['event_id'] = 1;
$data['Event']['year'] = date('Y');
$data['Event']['name'] = 'test';
$param[0] = $data;
$provider[0] = $param;
return $provider;
}
/**
* #dataProvider initValidateDataProvider
*
*/
public function testInitValidationAll($data) {
$this->testAction(
'/sb_organizers/events/init',array(
'return' => 'contents',
'data' => $data,
'method' => 'POST'
)
);
debug($this->contents);
}
debug($this->contents); always return null.
But if I run it without dataProvider:
public function testInitValidateAll() {
$data['Event']['event_type'] = '';
$data['Event']['etag_id'] = 0;
$data['Event']['year'] = '';
$data['Event']['name'] = '';
$this->testAction(
'/sb_organizers/events/init',array(
'return' => 'contents',
'data'=>$data
)
);
debug($this->contents);
}
It works fine. Does dataProvider work in CakePHP's controller test case? I suspect it is the $this->testAction does not work with dataProvider.
i have filter in twig :
class AcmeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'priceFilter')),
);
}
public function priceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
{
$price = number_format($number, $decimals, $decPoint, $thousandsSep);
$price = '$'.$price;
return $price;
}
}
but how can call price filter inside other filter? in symfony 2.0 declared filter with 'price' => new \Twig_Filter_Method($this, 'priceFilter')
and could from within another filter call this.
thanks and sorry for my english
if you want the returned value of the other filter into your price filter, you can chain them in twig:
{{ value|acme_filter|price }}
Or in the other direction, if you need the return value of the price filter in your other filter:
{{ value|price|acme_filter }}
If you really need the price filter inside your other filter, no problem. The extension is a plain php class.
public function acmeFilter($whatever)
{
// do something with $whatever
$priceExtentsion = new PriceExtenstion();
$whatever = $priceExtension->priceFilter($whatever);
// do something with $whatever
return $whatever;
}
class SomeExtension extends \Twig_Extension {
function getName() {
return 'some_extension';
}
function getFilters() {
return [
new \Twig_SimpleFilter(
'filterOne',
function(\Twig_Environment $env, $input) {
$output = dosmth($input);
$filter2Func = $env->getFilter('filterTwo')->getCallable();
$output = call_user_func($filter2Func, $output);
return $output;
},
['needs_environment' => true]
),
new \Twig_SimpleFilter(
'filterTwo',
function ($input) {
$output = dosmth($input);
return $output;
}
)
];
}
}
Your use callback function as "static".
You can define your function as static, or replace to \Twig_Filter_Method($this, 'priceFilter')
I am using the following code to get all the errors in a form:
// get all the errors in the form in an array
public static function getErrorMessages(\Symfony\Component\Form\Form $form) {
$errors = array();
// actual errors
foreach ($form->getErrors() as $key => $error) {
$errors[] = $error->getMessage();
}
// find children that are not valid
if ($form->count()>0) {
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = formHelper::getErrorMessages($child);
}
}
}
That works. The only issue is for FOSUser: I've defined my validation group and the errors aren't getting translated. Instead of getting "The password is too short" I am getting "fos_user.password.short". The issue is with the line:
$errors[] = $error->getMessage();
That does not translate the error. Anybody could help me out figure out this issue?
You should use translator service to translate messages
Try this:
public function getFormErrorsAssoc(FormInterface $form) {
$errors = array();
/* #var \Symfony\Component\Form\FormError $error*/
foreach ($form->getErrors() as $key => $error) {
$message = $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators');
if ($message) {
$errors[$key] = $message;
}
}
if ($form->hasChildren()) {
/* #var FormInterface $child*/
foreach ($form->getChildren() as $child) {
$label = $child->getAttribute('label') ? : $child->getName();
if (!$child->isValid()) {
$errors[$label] = $this->getFormErrorsAssoc($child);
}
}
}
return $errors;
}