Symfony Doctrine: One to Many relationship is deleting parent entity - symfony

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.

Related

Symfony 3.3.2 Doctrine EntityRepository constructor argument

I'm newbie on Symfony. I am trying to update an old project under symfony 2.6 to symfony 3.3.
After multiple bug fixes I am stuck on a point: I have an Error in my EntityRepository.php file with the constructor.
Type error: Too few arguments to function Doctrine\ORM\EntityRepository::__construct(), 1 passed in /Users/.../var/cache/dev/appDevDebugProjectContainer.php on line 3434 and exactly 2 expected
I understand the error, but my EntityRepository file not contain any __construct method. Should I fix something between Symfony 2 and 3 for the consructor to work?
Thanks a lot.
Here is my MilestoneRepository.php file:
namespace MilestonesBundle\Entity\Repository;
use DateTime;
use Doctrine\ORM\EntityRepository;
use Milestones\Entity\Factory\MilestoneFactoryInterface;
use Milestones\Entity\Repository\MilestoneRepositoryInterface;
class MilestoneRepository extends EntityRepository implements MilestoneFactoryInterface, MilestoneRepositoryInterface
{
protected $current = false;
/**
* #see MilestoneFactoryInterface
*/
public function create()
{
$class = $this->getClassName();
return new $class;
}
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
{
if (!$orderBy) {
$orderBy['startsAt'] = 'ASC';
}
return parent::findBy($criteria, $orderBy, $limit, $offset);
}
/**
* #see MilestoneRepositoryInterface
*/
public function findCurrent()
{
$now = new DateTime;
if ($this->current === false) {
$this->current = $this->createQueryBuilder('m')
->where('m.startsAt <= :now')
->andWhere('(m.endsAt IS NULL OR :now < m.endsAt)')
->setParameter('now', $now->format('Y-m-d'))
->orderBy('m.startsAt', 'ASC')
->setMaxResults(1)
->getQuery()
->getOneOrNullResult()
;
}
return $this->current;
}
/**
* #see MilestoneRepositoryInterface
*/
public function isOpen()
{
$current = $this->findCurrent();
return $current && $current->isStart();
}
}
And here is my EntityRepository.php file:
namespace Common\Doctrine\ORM;
use Doctrine\ORM\EntityRepository as BaseEntityRepository;
use Doctrine\ORM\QueryBuilder;
class EntityRepository extends BaseEntityRepository
{
protected $alias = 'x';
public function add($entity)
{
$em = $this->getEntityManager();
$em->persist($entity);
$em->flush();
}
public function remove($entity)
{
$em = $this->getEntityManager();
$em->remove($entity);
$em->flush();
}
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $result = true)
{
$alias = $this->alias;
$builder = $this->createQueryBuilder($alias);
$this->applyCriteria($builder, $alias, $criteria);
$this->applyOrderBy($builder, $alias, $orderBy);
$this->applyLimit($builder, $limit);
$this->applyOffset($builder, $offset);
if (!$result) {
return $builder;
}
return $builder->getQuery()->getResult();
}
public function findOneBy(array $criteria, array $orderBy = null, $result = true)
{
$alias = $this->alias;
$builder = $this->createQueryBuilder($alias);
$this->applyCriteria($builder, $alias, $criteria);
$this->applyOrderBy($builder, $alias, $orderBy);
if (!$result) {
return $builder;
}
return $builder->getQuery()->getOneOrNullResult();
}
protected function applyCriteria(QueryBuilder $builder, $alias, array $criteria)
{
$map = $this->getCriteriaMap();
foreach ($criteria as $property => $value) {
if (array_key_exists($property, $map)) {
call_user_func_array($map[$property], [$builder, $alias, $property, $value]);
} else {
$this->applyDefaultCriterion($builder, $alias, $property, $value);
}
}
}
protected function getCriteriaMap()
{
return [];
}
protected function applyDefaultCriterion($builder, $alias, $property, $value)
{
if (null === $value) {
$builder->andWhere($alias.'.'.$property.' IS NULL');
} else {
$parameter = 'p_' . uniqid();
$builder->andWhere($alias.'.'.$property.' = :'.$parameter);
$builder->setParameter($parameter, $value);
}
}
/**
* Apply order by
*
* #param QueryBuilder $builder
* #param string $alias
* #param array|null $orderBy
* #return void
*/
protected function applyOrderBy(QueryBuilder $builder, $alias, array $orderBy = null)
{
if (empty($orderBy)) {
$orderBy = $this->getDefaultOrder();
}
$map = $this->getOrderingMap();
foreach ($orderBy as $property => $direction) {
if (array_key_exists($property, $map)) {
call_user_func_array($map[$property], [$builder, $alias, $property, $direction]);
} else {
$this->applyDefaultOrder($builder, $alias, $property, $direction);
}
}
}
protected function getDefaultOrder()
{
return [];
}
protected function getOrderingMap()
{
return [];
}
protected function applyDefaultOrder(QueryBuilder $builder, $alias, $property, $direction)
{
$builder->orderBy($alias.'.'.$property, $direction);
}
protected function applyLimit(QueryBuilder $builder, $limit = null)
{
if ($limit) {
$builder->setMaxResults($limit);
}
}
protected function applyOffset(QueryBuilder $builder, $offset = null)
{
if ($offset) {
$builder->setFirstResult($offset);
}
}
}
I think I'm accessing through a service, with this:
services:
# Factories
milestones.factory.milestone:
alias: milestones.repository.milestone
arguments: [ MilestonesBundle\Entity\Milestone ]
# Repositories
milestones.repository.milestone:
class: MilestonesBundle\Entity\Repository\MilestoneRepository
factory_service: doctrine.orm.default_entity_manager
factory_method: getRepository
arguments: [ MilestonesBundle\Entity\Milestone ]
replace this code:
milestones.repository.milestone:
class: MilestonesBundle\Entity\Repository\MilestoneRepository
factory_service: doctrine.orm.default_entity_manager
factory_method: getRepository
arguments: [ MilestonesBundle\Entity\Milestone ]
with this one:
milestones.repository.milestone:
class: MilestonesBundle\Entity\Repository\MilestoneRepository
factory: ['#doctrine.orm.entity_manager', getRepository]
arguments: [ MilestonesBundle\Entity\Milestone ]
factory method - getRepository
I think somewhere in jour code this method is called:
public function create()
{
$class = $this->getClassName();
return new $class;
}
And this is calling the constructor of Doctrine\ORM\EntityRepository:
public function __construct(EntityManagerInterface $em, Mapping\ClassMetadata $class)
{
$this->_entityName = $class->name;
$this->_em = $em;
$this->_class = $class;
}
therefore you will have to inject the arguments if you want to use your create method... I think it should be something like new $class($entityManager, Entity::class)

Display Excerpts of Posts in Wordpress Blog

I have been searching for the answer to my problem and I continually come up with replacing
<?php the_content(); ?>
with
<?php the_excerpt(); ?>
in the index.php file. However, the theme we are using does not contain this line. Anyone have any insight? Here is the code in our index.php file:
<?php $t =& peTheme(); ?>
<?php $content =& $t->content; ?>
<?php $meta =& $content->meta(); ?>
<?php get_header(); ?>
<section class="section-blog section-index" id="<?php $content->slug(); ?>">
<div class="row">
<div class="large-12 columns text-center">
</div>
</div>
<div class="row blog-main">
<div class="large-9 columns blog-left">
<?php $t->content->loop(); ?>
</div>
<?php get_sidebar(); ?>
</div>
</section>
<?php get_footer(); ?>
Source of PeThemeContent.php:
<?php
class PeThemeContent {
protected $master;
protected $loops = array();
protected $current = false;
protected $blogLoop = false;
protected $cols = 0;
public function __construct(&$master) {
$this->master = &$master;
add_filter("pe_post_thumbnail",array(&$this,"post_thumbnail_filter"));
add_filter("wp_tag_cloud",array(&$this,"wp_tag_cloud_filter"));
add_filter("widget_tag_cloud_args",array(&$this,"widget_tag_cloud_args_filter"));
add_filter("previous_post_link",array(&$this,"strip_rel_filter"));
add_filter("next_post_link",array(&$this,"strip_rel_filter"));
add_filter("the_category",array(&$this,"strip_rel_filter"));
add_filter("excerpt_more",array(&$this,"excerpt_more_filter"));
add_filter("the_content_more_link",array(&$this,"the_content_more_link_filter"));
add_filter("edit_post_link",array(&$this,"edit_post_link_filter"));
}
public function instantiate() {
}
public function loop($name = "") {
$view = new PeThemeViewBlog;
$conf = (object) array("settings" => (object) array("layout" => $name));
$conf->settings->pager = "yes";
$conf->settings->media = "yes";
$view->output($conf);
}
public function have_posts() {
if ($this->current) {
//print_r($this->current);
$res = $this->current->have_posts();
} else {
$res = have_posts();
}
return $res;
}
public function idx() {
return $this->wpq->current_post;
}
public function last() {
return $this->wpq->post_count-1;
}
public function count() {
return $this->wpq->post_count;
}
public function is_single() {
return $this->current ? false : is_single();
}
public function the_post() {
if ($this->current) {
$res = $this->current->the_post();
$GLOBALS["more"] = false;
} else {
$res = the_post();
}
return $res;
}
public function beginRow($markup) {
$cols = $this->cols;
$idx = $this->wpq->current_post;
if ($cols > 0 && ($idx % $cols) == 0) {
echo $markup;
}
}
public function endRow($markup = "</div>") {
$cols = $this->cols;
$idx = $this->wpq->current_post;
$last = $this->wpq->post_count-1;
if ($cols > 0 && (($idx == $last) || ($idx % $cols) == ($cols-1))) {
echo $markup;
}
}
public function looping($cols = 0) {
if ($this->have_posts()) {
$this->cols = $cols;
$this->the_post();
return true;
}
return false;
}
public function &wpq() {
global $wp_query;
return $wp_query;
}
public function &__get($what) {
switch ($what) {
case "wpq":
if ($this->current) {
return $this->current;
}
return $this->wpq();
case "qv":
return $this->wpq()->query_vars;
case "page":
$which = (is_front_page() && !is_home()) ? "page" : "paged";
$page = isset($this->qv[$which]) ? intval($this->qv[$which]) : 0;
return $page;
}
}
public function title() {
the_title();
}
public function titleAttribute() {
the_title_attribute();
}
public function getLink() {
$link = get_permalink();
global $post;
if (isset($post) && $post->post_type === "attachment") {
$link = $this->get_origImage();
}
return $link;
}
public function link() {
echo $this->get_link();
}
public function twitterShareLink() {
$link = "http://twitter.com/home?status=";
$link .= urlencode(get_the_title()." - ");
$link .= get_permalink();
echo esc_attr($link);
}
public function facebookShareLink() {
$link = "http://www.facebook.com/sharer/sharer.php?u=";
$link .= get_permalink();
echo esc_attr($link);
}
public function filter($tax,$sep = "",$aclass="label",$template = '%s') {
if (is_array($tax) && isset($tax[1]) && is_a($tax[1],"PeThemeDataLoop")) {
$loop = $tax[1]->main->loop;
$ids = array();
$n = count($loop);
for($i=0;$i<$n;$i++) {
$ids[] = $loop[$i]->id;
}
$terms = wp_get_object_terms($ids,$tax[0]);
} else if ($this->have_posts()) {
$ftax = in_array($tax,array('post_tag','category')) ? strtr($tax,array('post_tag'=>'tag','category' => 'category_name')) : $tax;
if (!empty($this->wpq->query[$ftax])) {
$slugs = explode(",",$this->wpq->query[$ftax]);
$terms = array();
if (!empty($slugs)) {
foreach ($slugs as $slug) {
$term = get_term_by('slug',$slug,$tax);
if (!empty($term) && !empty($term->term_id)) {
$terms[] = $term;
}
}
}
} else {
$posts =& $this->wpq->posts;
$ids = array();
$n = count($posts);
for($i=0;$i<$n;$i++) {
$ids[] = $posts[$i]->ID;
}
$terms = wp_get_object_terms($ids,$tax);
}
} else {
$terms = array();
}
$seen = array();
// to get all terms
//$terms = get_terms($tax);
$output = "";
$buffer = "";
if (is_array($terms) && count($terms) > 0) {
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s active" data-category="" href="#">%s</a>%s',$aclass,__("All",'Pixelentity Theme/Plugin'),"$sep\n"),$aclass,"",__("All",'Pixelentity Theme/Plugin'));
$output = sprintf($template,$buffer);
foreach ($terms as $term) {
$id = $term->term_id;
if (isset($seen[$id])) continue;
$seen[$id] = true;
$buffer = apply_filters("pe_theme_filter_item",sprintf('<a class="%s" data-category="%s" href="#">%s</a>%s',$aclass,$term->slug,$term->name,"$sep\n"),$aclass,$term->slug,$term->name);
$output .= sprintf($template,$buffer);
}
print $output;
}
}
public function filterClasses($tax,$id = null) {
if (empty($tax)) return;
if (empty($id)) {
global $post;
$id = $post->ID;
}
$classes = wp_get_post_terms($id,$tax,array("fields" => "slugs"));
if (is_array($classes) && ($count = count($classes)) > 0) {
while($count--) {
$classes[$count] = "filter-".$classes[$count];
}
echo join(" ",$classes);
}
}
public function thumb($useFilters = true) {
global $post;
if (has_post_thumbnail()) {
$thumb = get_the_post_thumbnail($post->ID,"thumbnail");
if ($useFilters && has_filter("pe_post_thumbnail")) {
echo apply_filters("pe_post_thumbnail",$thumb);
} else {
echo $thumb;
}
}
}
public function post_thumbnail_filter($data) {
return $data;
}
public function hasFeatImage() {
global $post;
return #has_post_thumbnail($post->ID);
}
public function get_origImage($id = null) {
return wp_get_attachment_url(get_post_thumbnail_id($id));
}
public function resizedImg($w,$h,$custom = null) {
$url = empty($custom) ? wp_get_attachment_url(get_post_thumbnail_id()) : $custom;
return $this->master->image->resizedImg($url,$w,$h);
}
public function img($w,$h = null,$custom = null) {
$img = $this->resizedImg($w,$h,$custom);
echo apply_filters("pe_theme_content_img",$img ? $img : "",$w,$h);
}
public function get_thumbImage($thumb) {
if (#has_post_thumbnail()) {
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id(),$thumb);
return $thumb[0];
}
return "";
}
public function origImage() {
echo $this->get_origImage();
}
public function excerpt() {
the_excerpt();
}
public function content($text = null) {
global $post;
if (isset($post) && $post->post_type === "attachment") {
echo apply_filters("wpautop",$post->post_excerpt);
} else {
the_content($text);
}
}
public function builder() {
if (post_password_required() || !PE_THEME_PLUGIN) {
$this->content();
} else {
$meta =& $this->meta();
if (empty($meta->builder)) return;
global $post;
$view = new PeThemeViewLayout();
$conf = (object)
array(
"id" => $post->ID,
"settings" => $meta->builder
);
$view->output($conf);
}
}
public function hasMedia() {
$format = $this->format();
$meta =& $this->meta();
$ret = false;
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
$ret = !empty($gallery->id) && $gallery->id > 0;
break;
case "video":
$video = empty($meta->video) ? false : $meta->video;
$ret = !empty($video->id) && $video->id > 0;
break;
default:
$ret = $this->hasFeatImage();
}
return $ret;
}
public function slider($w,$h) {
if ($this->format() != "gallery") return;
$meta =& $this->meta();
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (empty($gallery->id)) return;
$view =& $this->master->view;
$conf = $view->create("SliderVolo","gallery",array("id" =>$gallery->id),$w,$h);
$view->resize($conf);
}
public function media() {
$format = $this->format();
$meta =& $this->meta();
switch ($format) {
case "gallery":
$gallery = empty($meta->gallery) ? false : $meta->gallery;
if (!empty($gallery->id)) {
$conf =
$this->master->view->create(
$gallery->type,
"gallery",
array("id" => $gallery->id),
$gallery->width,
$gallery->height
);
// use gallery caption
$conf->caption = (object) array("title" => "ititle","description" => "caption");
//$conf->caption->title = "ititle";
//$conf->caption->description = "caption";
$this->master->view->resize($conf);
}
break;
case "video":
$this->master->video->output();
break;
default:
$format = $this->hasFeatImage() ? "image" : false;
}
return $format;
}
public function current($add = 0) {
$page = $this->page;
if ($page > 1) {
$add += $this->qv["posts_per_page"]*($page-1);
}
echo $this->wpq->current_post + $add;
}
public function terms($tax,$sep = ",") {
global $post;
return join($sep,wp_get_post_terms($post->ID,$tax,array("fields" => "names")));
}
public function &getPostsQueryArgs($type,$count,$tax = null,$custom = null,$paged = false) {
$args = array(
"post_type"=>"$type",
"posts_per_page"=>$count
);
if ($tax) {
$custom[$tax] = $this->terms($tax);
}
if (is_array($custom)) {
$args = array_merge($args,$custom);
}
if ($paged) {
$page = $this->page;
$page = $page ? $page - 1 : 0;
$args["offset"] = $count*$page;
} else {
// if pagination is not needed, avoid counting rows to boost performances
$args['no_found_rows'] = true;
}
if ($args["post_type"] === "attachment") {
$args["post_status"] = "inherit";
}
return $args;
}
public function getPostsLoop($type,$count,$tax = null,$custom = null,$paged = false) {
$data = new StdClass();
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
$wpq = new WP_Query();
$data->loop = $wpq->query($args);
$loop =& $this->master->data->create($data,true);
if ($paged) {
$loop->pages = $wpq->max_num_pages;
}
return $loop;
}
public function customLoop($type,$count = 10,$tax = null,$custom = null,$paged = false) {
$args =& $this->getPostsQueryArgs($type,$count,$tax,$custom,$paged);
if ($this->current) {
$this->loops[] = $this->current;
}
$this->master->data->postSave();
$this->current = new WP_Query($args);
return $this->current->post_count > 0;
}
public function related($type,$tax,$count) {
//$settings = new StdClass();
//$settings->post_type = "project";
if ($loop = $this->customLoop($type,$count,$tax)) {
get_template_part("related",$type);
$this->resetLoop();
}
}
public function resetLoop() {
$this->master->data->postReset();
$this->current = (count($this->loops) >0) ? array_pop($this->loops) : false;
}
public function blog($settings,$showpager = true) {
global $post;
$exclude = false;
// prevents nested blogs
if ($this->blogLoop) return;
$this->blogLoop = true;
// prevents loops
if (isset($post) && $post) {
$exclude = $post->ID;
}
if (is_string($settings) && !empty($settings)) {
$id = $settings;
$post = get_post($id);
if (!$post) return;
$meta = $this->master->meta->get($id,$post->post_type);
if (empty($meta->blog)) return true;
$settings = $meta->blog;
}
$settings = (object) shortcode_atts(
array(
"layout" => "",
"count" => get_option("posts_per_page"),
"media" => "yes",
"pager" => "yes",
"sticky" => "yes",
"category" => "",
"tag" => "",
"format" => ""
),
(array) $settings
);
// prevents loops
if ($exclude) {
$custom = array("post__not_in" => array($exclude));
}
$custom["ignore_sticky_posts"] = ($settings->sticky === "no") ? 1 : 0;
if ($settings->category) {
$custom["category_name"] = $settings->category;
}
if ($settings->tag) {
$custom["tag"] = $settings->tag;
}
if ($settings->format) {
$tax_query = array(
array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => array("post-format-{$settings->format}")
)
);
$custom["tax_query"] = $tax_query;
}
$media = $settings->media === "yes";
$this->customLoop("post",$settings->count,null,$custom,$settings->pager === "yes");
$compact = compact("media");
$this->master->template->get_part($compact,"loop",$this->have_posts() ? $settings->layout : "empty");
if ($showpager && $settings->pager === "yes") {
$this->pager();
}
$this->resetLoop();
$this->blogLoop = false;
}
public function getPagerLoop($max = 5,$pages = false) {
$pages = $pages ? $pages : $this->wpq->max_num_pages;
if ($pages <= 1) return false;
for ($p = 0;$p<$pages;$p++) {
$links[] = get_pagenum_link($p+1);
}
return $this->master->data->createPager($this->page,$links,$max);
}
public function pager($class = "span12",$pages = false) {
$loop = $this->getPagerLoop(5,$pages);
if ($loop) $loop->main->class = $class;
$this->master->template->paginate_links($loop);
}
public function comments() {
comments_number('0','1','%');
}
public function body_class($class = "") {
echo 'class="' . apply_filters("pe_theme_body_class",join( ' ', get_body_class( $class ) )) . '"';
}
public function total() {
echo $this->wpq->found_posts;
}
public function hasNextPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page < $max);
}
public function hasPrevPage() {
$max = $this->wpq->max_num_pages;
return ($max > 1 && $this->page > 1);
}
public function tagCloud($number,$orderby="name") {
wp_tag_cloud(array("number"=>$number,"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
}
public function tags($sep = ", ",$tax = false) {
if ($tax) {
echo get_the_term_list(null, $tax, "", $sep, "");
} else {
the_tags("",$sep,"");
}
}
public function category($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_category(", ");
}
public function date($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_time(get_option('date_format'));
}
public function author($prefix="") {
if ($prefix) {
echo "$prefix ";
}
the_author();
}
public function format($is_format = null) {
global $post;
$format = get_post_format($post->ID);
return empty($is_format) ? $format : $format === $is_format;
}
public function pageTemplate($post_id = null) {
if (function_exists("get_page_template_slug")) return get_page_template_slug($post_id);
$post = get_post( $post_id );
if ( 'page' != $post->post_type )
return false;
$template = get_post_meta( $post->ID, '_wp_page_template', true );
if ( ! $template || 'default' == $template )
return '';
}
public function slug() {
global $post;
echo $post->post_name;
}
public function type() {
global $post;
return $post->post_type;
}
public function classes($add="") {
$c = join(" ",get_post_class());
$c = $add ? "$c $add" : "$c";
printf('class="%s"',$c);
}
public function isVideo() {
return get_post_format() === "video";
}
public function includeLoopPart($prefix="looped") {
global $post;
$type = $post->post_type;
get_template_part("$prefix-$type",$this->format());
}
public function getBlogLink() {
$pfp = get_option("page_for_posts");
$pfp = $pfp ? get_page_link($pfp) : "";
return get_option('show_on_front') == 'page' ? $pfp : home_url();
}
public function wp_tag_cloud_filter($data) {
if (is_tag()) {
global $wp_query;
$currentTagID = $wp_query->get_queried_object()->term_id;
$data = str_replace("tag-link-$currentTagID","tag-link-$currentTagID current-tag",$data);
}
return preg_replace('/style=.[^"|\']+./i','',$data);
}
public function widget_tag_cloud_args_filter($args) {
$options =& $this->master->options;
$orderby = $options->get("tagCloudOrder");
$args = array_merge($args,array("number"=>$options->get("tagCloudCount"),"orderby"=>$orderby,"order"=>$orderby == "count" ? "DESC" : "ASC"));
return $args;
}
public function &meta($postID = FALSE) {
global $post;
//print_r($post);
return $this->master->meta->get($postID ? $postID : ($post ? $post->ID : NULL),$post ? $post->post_type : "post");
}
public function strip_rel_filter($content) {
return preg_replace('/rel="/','data-rel="',$content);
}
public function excerpt_more_filter($more) {
return "";
}
public function the_content_more_link_filter($link) {
//$link = sprintf(' %s',get_permalink(),$GLOBALS["post"]->ID,__("more",'Pixelentity Theme/Plugin'));
$link = sprintf(' %s',get_permalink(),__("more",'Pixelentity Theme/Plugin'));
return $link;
}
public function edit_post_link_filter($link) {
return str_replace("post-edit-link","label",$link);
}
public function getSocialLinks($links,$position = "top") {
$html = "";
if (is_array($links)) {
foreach ($links as $link) {
if (empty($link)) continue;
list($icon,$tooltip) = explode("|",$link["icon"]);
$html .= apply_filters("pe_theme_content_get_social_link",sprintf('<i class="%s"></i>',$link["url"],$position,$tooltip,$icon),$link["url"],$tooltip,$icon);
}
}
return $html;
}
public function socialLinks($links,$position = "top") {
$html = apply_filters("pe_theme_social_links",$this->getSocialLinks($links,$position),$position);
echo $html ? $html : "";
}
public function getPagesByTemplate($template) {
$args = array();
if ($template) {
$args =
array(
'meta_key' => '_wp_page_template',
'meta_value' => "page-$template.php"
);
}
$pages = get_pages($args);
return $pages;
}
public function getPagesLinkByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[] = get_page_link($page->ID);
}
return $links;
}
public function getPagesOptionsByTemplate($template) {
$pages = $this->getPagesByTemplate($template);
if (!is_array($pages)) return false;
$links = false;
foreach ($pages as $page) {
$links[$page->post_title] = $page->ID;
}
return $links;
}
public function getPageLinkByTemplate($template) {
$pages = $this->getPagesLinkByTemplate($template);
return $pages ? $pages[0] : "";
}
public function adjPost($previous = false) {
$post = get_adjacent_post(false,"", $previous);
$ret = "";
if ($post) {
$ret = new StdClass;
$ret->title = get_the_title($post);
$ret->link = get_permalink($post);
$ret->date = get_the_time(get_option('date_format'), $post);
}
return $ret;
}
public function breadcrumbs($sep = ' / ') {
$template = '<a class="pe-breadcrumbs-%s" href="%s">%s</a>';
$links[] = sprintf($template,'home',home_url(),__('Home','Pixelentity Theme/Plugin'));
if (is_home()) {
$links[] = sprintf($template,'blog','#',__('Blog','Pixelentity Theme/Plugin'));
} elseif (is_category()) {
$links[] = substr(get_category_parents(get_query_var('cat'),true,$sep), 0, -strlen($sep));
} elseif (is_tag() || is_tax()) {
$term = get_queried_object();
if (!empty($term->term_id)) {
$links[] = sprintf($template,'tax',get_tag_link($term->term_id),single_term_title("",false));
}
} elseif (is_archive()) {
if ( is_day() ) {
$date = get_the_date();
} elseif ( is_month() ) {
$date = get_the_date('F Y');
} elseif ( is_year() ) {
$date = get_the_date('Y');
} else {
$date = __("Archives",'Pixelentity Theme/Plugin');
}
$links[] = sprintf($template,'archive','#',$date);
} elseif (is_page()) {
global $post;
if (!empty($post->ID)) {
$parents = get_post_ancestors($post->ID);
if (!empty($parents) && is_array($parents)) {
$parents = array_reverse($parents);
$parents[] = $post->ID;
$home = trailingslashit(home_url());
foreach ($parents as $id) {
$link = get_permalink($id);
if ($link == $home) continue;
$links[] = sprintf($template,'page',$link,get_the_title($id));
}
}
}
} elseif (is_single()) {
global $post;
if (!empty($post->ID)) {
$taxs = get_object_taxonomies($post,"names");
if (!empty($taxs) && is_array($taxs)) {
while ($tax = array_shift($taxs)) {
if ($tax != "post_format") break;
}
if ($tax) {
$terms = get_the_terms($post->ID,$tax);
if (is_array($terms)) {
reset($terms);
$term = key($terms);
$parents = get_ancestors($terms[$term]->term_id,$tax);
$parents = is_array($parents) ? array_reverse($parents) : array();
$parents[] = $terms[$term]->term_id;
foreach ($parents as $id) {
$term = get_term($id,$tax);
$links[] = sprintf($template,'tax',get_term_link($term),$term->name);
}
}
}
}
$links[] = sprintf($template,'single',get_permalink($post->ID),get_the_title($post->ID));
}
}
print join($links,$sep);
}
public function adjPostLink($previous = false) {
$post = get_adjacent_post(false,"", $previous);
return $post ? get_permalink($post) : "";
}
public function prevPostLink() {
return $this->adjPostLink(true);
}
public function nextPostLink() {
return $this->adjPostLink(false);
}
public function linkPages() {
wp_link_pages(array('before' => '<div class="page-links">' . __('Pages:','Pixelentity Theme/Plugin'), 'after' => '</div>'));
}
}
?>

Retrieve all controller action that have a specific annotation - Symfony2

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 ;
}

Create my own entity generator on symfony using doctrine generator

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

Mock Object variable in PHPUnit

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.

Resources