I want to create a test for the following function in Cakephp2.0 with PHPUnit:
public function matching($check, $field) {
$return = true;
foreach ($check as $c) {
if ($c != $this->data['User'][$field]) {
$return = false;
}
}
return $return;
}
How do I set the value of:
$this->data['User'][$field]
My test function is:
public function testMatching() {
$this->data['User']['password'] = 'testpass';
$check = array('testpass');
$result = $this->User->matching($check, 'password');
$this->assertEquals(true, $result);
}
Thanks.
Related
I have parent and child entity. After all child entities are deleted, symfony delete my parent entity too. I don't like such behavior, parent entity must exist whenever there are some children or not. Here is my code for parent:
/**
* #OneToMany(targetEntity="Gallery", mappedBy="promotion", cascade={"persist", "remove"})
*/
private $galleries;
public function __construct() {
$this->galleries = new ArrayCollection();
}
public function getGalleries() {
return $this->galleries;
}
public function addGallery($gallery)
{
$gallery->setPromotion($this);
$this->galleries[] = $gallery;
return $this;
}
public function removeGallery($gallery)
{
$gallery->setPromotion(null);
$this->galleries->removeElement($gallery);
}
And here for child:
/**
* #ManyToOne(targetEntity="Promotion", inversedBy="galleries")
*/
private $promotion;
I don't know what to do, I have already spend hours on this.
It is handled by easy admin bundle, so it won't help you:
namespace AppBundle\Controller;
use JavierEguiluz\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
use Symfony\Component\Security\Acl\Exception\Exception;
use AppBundle\Entity\Promotion;
use Symfony\Component\HttpFoundation\JsonResponse;
class PromotionController extends PageController {
protected $folder = 'promotions';
protected $htmlFileName = 'default-template.html';
protected function rearangeAction() {
$ids = json_decode($this->request->get('ids'));
$order = 1;
foreach($ids as $id) {
$this->em->createQuery('UPDATE AppBundle:Promotion p SET p.order = :order WHERE p.id = :id')
->setParameter('order', $order++)
->setParameter('id', $id)
->execute();
}
return $this->redirectToRoute('easyadmin', $this->prepareRouteParams());
}
protected function checkFolderAction() {
$row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.language = :language AND p.subfolder = :subfolder')
->setParameter('language', $this->language)
->setParameter('subfolder', $this->request->get('subfolder'))
->getOneOrNullResult();
if($row) {
return new JsonResponse(array('duplicity' => 1));
} else {
return new JsonResponse(array('duplicity' => 0));
}
}
protected function deleteFiles($databaseSubFolders) {
$mainFolder = $this->baseDir.'/'.$this->folder.'/'.$this->language;
$databaseSubFolders[] = '..';
$databaseSubFolders[] = '.';
$subFolders = array_diff(scandir($mainFolder), $databaseSubFolders);
foreach($subFolders as $subFolder) {
$this->deleteFolder($mainFolder.'/'.$subFolder);
}
}
protected function exportAction() {
$query = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.language = :language')
->setParameter('language', $this->language);
$subFolders = array();
foreach($query->getArrayResult() as $key => $val) {
$subFolders[] = $val['subfolder'];
// pridanie novych a uprava starych
$image = basename($val['headerImage']);
$imageName = substr($image, 0 ,strpos($image,'.'));
$all = '<div class="header">
<div class="row">
<h2>
'.$val['headerTitle'].'
</h2>
<p>
'.$val['headerTeaser'].'
</p>
</div>
</div><img src="{{::promo.imgPath}}/'.$image.'" alt="'.$imageName.'">';
$all .= $this->changeMarkdownToHtml($val['html']);
$all .= $this->changeMarkdownToHtml($val['terms']);
file_put_contents($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$val['subfolder'].'/html/'.$val['filename'], $all);
}
// zmazanie starych zloziek
$this->deleteFiles($subFolders);
parent::exportAction();
return $this->redirectToRoute('easyadmin', $this->prepareRouteParams());
}
private function actualImage($id, $i) {
$row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.id = :id')
->setParameter('id', $id)
->getOneOrNullResult();
return call_user_func_array(array($row,'getImage'.$i), array());
}
protected function preDeleteEntity($id) {
// mazanie obrazkov
}
protected function preSearchEntity($entity) {
$entity['search']['dql_filter'] = "entity.language = '".$this->language."'";
return $entity;
}
protected function prePersistEntity($entity) {
// ukladanie dalsich dat
$entity->setLanguage($this->language);
$entity->setFilename($this->htmlFileName);
$row = $this->em->createQuery('SELECT MAX(p.order)+1 FROM AppBundle:Promotion p')
->getOneOrNullResult();
$entity->setOrder($row[1]);
return $entity;
}
protected function postPersistEntity($entity) {
if(!is_dir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder())) {
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder());
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'header');
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'html');
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'img');
}
// presun obrazkov
$images = array();
foreach($entity->getGalleries()->getSnapshot() as $snapshot) {
$image = $snapshot->getImage();
$from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($image);
$to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/img/'.$image;
$this->copyFile($from, $to);
$images[] = $image;
}
$getImage = $entity->getHeaderImage();
$from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($getImage);
$to = $this->baseDir.'/'.$this->folder.'/'.$this->language.$getImage;
$this->copyFile($from, $to);
$entity->setHtml($this->replaceImages($entity->getHtml(), $images));
return $entity;
}
protected function preRemoveEntity($entity) {
//if($_POST['_method'] != 'DELETE') {
// var_dump($entity);
// die();
//}
return $entity;
}
protected function editAction() {
$id = $this->request->query->get('id');
$this->dispatch(EasyAdminEvents::PRE_EDIT);
$this->executeDynamicMethod('preEdit<EntityName>Entity', array($id));
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
$newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
$fieldsMetadata = $this->entity['list']['fields'];
if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
}
$this->updateEntityProperty($entity, $property, $newValue);
return new Response((string) $newValue);
}
$fields = $this->entity['edit']['fields'];
$editForm = $this->executeDynamicMethod('create<EntityName>EditForm', array($entity, $fields));
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
// kontrola pre presun
$row = $this->em->createQuery('SELECT p FROM AppBundle:Promotion p WHERE p.id = :id')
->setParameter('id', $id)
->getOneOrNullResult();
$previousSubfolder = $row->getSubfolder();
$editForm->handleRequest($this->request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_UPDATE, array('entity' => $entity));
$entity = $this->executeDynamicMethod('preUpdate2<EntityName>Entity', array($entity,$previousSubfolder));
$this->em->flush();
$this->dispatch(EasyAdminEvents::POST_UPDATE, array('entity' => $entity));
$entity = $this->executeDynamicMethod('postUpdate2<EntityName>Entity', array($entity,$previousSubfolder));
$refererUrl = $this->request->query->get('referer', '');
return !empty($refererUrl)
? $this->redirect(urldecode($refererUrl))
: $this->redirect($this->generateUrl('easyadmin', array('action' => 'list', 'entity' => $this->entity['name'])));
}
$this->dispatch(EasyAdminEvents::POST_EDIT);
$entity = $this->executeDynamicMethod('postEdit<EntityName>Entity', array($entity));
return $this->render($this->entity['templates']['edit'], array(
'form' => $editForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
protected function preUpdate2Entity($entity, $previousSubfolder) {
// if($_POST['delete_form']['_easyadmin_delete_flag'] == 1) {
// $this->em->createQuery('DELETE FROM AppBundle:Gallery g WHERE g.promotion = :id')
// ->setParameter('id', $id)
// ->execute();
// }
$images = array();
foreach($entity->getGalleries()->getSnapshot() as $snapshot) {
$image = $snapshot->getImage();
$images[] = $image;
}
$entity->setHtml($this->replaceImages($entity->getHtml(), $images));
return $entity;
}
protected function postUpdate2Entity($entity, $previousSubfolder) {
if(!is_dir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder())) {
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder());
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'header');
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'html');
mkdir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/'.'img');
}
// presun obrazkov
$images = array();
foreach($entity->getGalleries()->getSnapshot() as $snapshot) {
$image = $snapshot->getImage();
$from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($image);
$to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/img/'.$image;
if(!file_exists($from)) {
$from = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'.$image;
}
$this->copyFile($from, $to);
$images[] = $image;
}
// zmazanie obrazkov
$folderImages = array_diff(scandir($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'), array('..', '.'));
foreach($folderImages as $folderImage) {
if(!in_array($folderImage, $images)) {
unlink($this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$previousSubfolder.'/img/'.$folderImage);
}
}
$getImage = $entity->getHeaderImage();
$from = $this->get('kernel')->getRootDir().'/../web/uploads/temp/'.basename($getImage);
if(!file_exists($from)) {
$from = $this->baseDir.'/'.$this->folder.'/'.$this->language.$getImage;
}
$to = $this->baseDir.'/'.$this->folder.'/'.$this->language.'/'.$entity->getSubfolder().'/header/'.basename($getImage);
$this->copyFile($from, $to);
return $entity;
}
protected function postEditEntity($entity) {
// cesta pre obrazky
$entity->setHeaderImage(null, '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language.$entity->getHeaderImage());
return $entity;
}
protected function preListEntity($entity) {
$entity['list']['dql_filter'] = "entity.language = '".$this->language."'";
return $entity;
}
protected function postListEntity($fields) {
// cesta pre obrazky
$fields['headerImage']['base_path'] = '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language;
return $fields;
}
protected function postSearchEntity($fields) {
// cesta pre obrazky
$fields['headerImage']['base_path'] = '/uploads/'.$this->container->getParameter('repo.folder').'/'.$this->folder.'/'.$this->language;
return $fields;
}
}
Try to remove cascade annotation at all. The rest looks good.
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 make some var_dump() of the variable $attr = $response->getResponse(); that I am getting from google api for example. But I was not able to do that.
Is it possible to make it written on the the app/log/dev.log for example?
Below is
public function loadUserByOAuthUserResponse(UserResponseInterface $response) {
$username = $response->getUsername();
$nickname= $response->getNickname();
//$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
$user = $this->userManager->findUserBy(array("email" => $response->getEmail()));
$attr = $response->getResponse();
//when the user is registrating
if (null === $user) {
// init some setter functions
$service = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($service);
$setter_id = $setter . 'Id';
$setter_token = $setter . 'AccessToken';
// create new user here indepently of which service we are using!
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
$user->setUsername($response->getUsername());
//$user->setUsernameCanonical($response->getNickname());
$user->setEmail($response->getEmail());
$user->setEmailCanonical($response->getEmail());
switch ($service) {
case 'facebook':
if (isset($attr['gender'])) {
if ($attr['gender'] == 'male')
$user->setGender(true);
else
$user->setGender(false);
}
if (isset($attr['first_name'])) {
$user->setName($attr['first_name']);
}
if (isset($attr['last_name'])) {
$user->setFamilyname($attr['last_name']);
}
if (isset($attr['location'])) {
if (isset($attr['location']['name'])) {
if ($attr['location']['name']) {
$user->setLocation($attr['location']['name']);
}
}
}
if (isset($attr['hometown'])) {
if (isset($attr['hometown']['name'])) {
if ($attr['hometown']['name']) {
$user->setHometown($attr['hometown']['name']);
}
}
}
if (isset($attr['birthday'])) {
$user->setBirthday(new \DateTime($attr['birthday']));
}
if ($nickname) {
$user->setPassword("aa" . $nickname);
}else $user->setPassword($attr['name']);
break;
case 'google':
if (isset($attr['gender'])) {
if ($attr['gender'] == 'male')
$user->setGender(true);
else
$user->setGender(false);
}
if (isset($attr['birthday'])) {
$user->setPassword($attr['birthday']);
} else $user->setPassword("google on the play");
break;
}
$user->setAccept(true);
$user->setEnabled(true);
// update the user here
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
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
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;
}