working on it ...

Filters

Explore Public Snippets

Sort by

Found 256 snippets matching: symfony2

    public by jlappano  3241  1  5  2

    Check Content and Status Code in PHP Unit

            $client->request('GET', ‘/create/adviseeSet’);
    
            $content = $client->getResponse()->getContent();
            $status = $client->getResponse()->getStatusCode();
    
            $this->assertEquals('shmee', $content);
            $this->assertEquals(200, $status);
    
    
    Gives a nice failure message which prints out content and status code 

    public by bkozora  847  0  3  0

    Symfony2 Routes YAML

    Symfony2 Routes YAML: symfony2-routes.yaml
    # app/config/routing.yml
    blog_show:
        path:      /blog/{slug}
        defaults:  { _controller: AppBundle:Blog:show }
    
    

    public by bkozora  441  0  3  0

    Symfony2 Routes PHP

    Symfony2 Routes PHP: symfony2-routes.php
    <?php
    // src/AppBundle/Controller/BlogController.php
    namespace AppBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
    
    class BlogController extends Controller
    {
        /**
         * @Route("/blog/{slug}")
         */
        public function showAction($slug)
        {
            // ...
        }
    }
    
    

    external by zajca  281800  23  4  0

    Symfony2 custom command for import CSV

    Symfony2 custom command for import CSV: CSVImportCommand.php
    PHP
    <?php
    
    namespace PRIA\QuizApiBundle\Command;
    
    use PRIA\Bundle\UserBundle\EntityRepository\RoundsRepository;
    use PRIA\QuizApiBundle\Entity\Answers;
    use PRIA\QuizApiBundle\Entity\Questions;
    use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
    use Symfony\Component\Console\Command\Command;
    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\Finder\Finder;
    
    class CSVImportCommand extends ContainerAwareCommand
    {
    // change these options about the file to read
        private $cvsParsingOptions = array(
            'finder_in' => __DIR__,
            'finder_name' => 'ahmad_q.csv',
            'ignoreFirstLine' => true
        );
    
        protected function configure()
        {
            $this->setName('QuizApi:Import')
                ->setDescription('Import csv file')
                ->addArgument(
                'startDate',
                InputArgument::REQUIRED,
                'Date start'
            );
        }
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
    
            // use the parseCSV() function
            $csv = $this->parseCSV();
            $startDate = new \DateTime($input->getArgument('startDate'));
    
            $em = $this->getContainer()->get('doctrine')->getManager();
            /** @var RoundsRepository $rounds */
            $rounds = $em->getRepository("PRIAUserBundle:Rounds");
            $round = $rounds->findOneByName("test");
    
            foreach ($csv as $line) {
                $startDate->format('Y-m-d');
    
                $question = new Questions();
                $question->setIdRound($round);
                $question->setText($line[0]);
                $question->setLink($line[4]);
                $question->setDate(clone $startDate);
    
                $answer = new Answers();
                $answer->setIdQuestion($question);
                $answer->setText($line[1]);
                $answer->setRightAnswer(1);
    
                $answer2 = new Answers();
                $answer2->setIdQuestion($question);
                $answer2->setText($line[2]);
                $answer2->setRightAnswer(2);
    
                $answer3 = new Answers();
                $answer3->setIdQuestion($question);
                $answer3->setText($line[3]);
                $answer3->setRightAnswer(3);
    
                $em->persist($answer);
                $em->persist($answer2);
                $em->persist($answer3);
                $em->persist($question);
    
                $startDate->modify('+1 day');
    
            }
    
            $em->flush();
    
        }
    
        /**
         * Parse a csv file
         *
         * @return array
         * @throws \Exception
         *
         */
        private function parseCSV()
        {
            $ignoreFirstLine = $this->cvsParsingOptions['ignoreFirstLine'];
    
            $finder = new Finder();
            $finder->files()
                ->in($this->cvsParsingOptions['finder_in'])
                ->name($this->cvsParsingOptions['finder_name'])
                ->files();
            foreach ($finder as $file) {
                $csv = $file;
            }
    
            if(empty($csv)){
                throw new \Exception("NO CSV FILE");
            }
    
            $rows = array();
            if (($handle = fopen($csv->getRealPath(), "r")) !== FALSE) {
                $i = 0;
                while (($data = fgetcsv($handle, null, ",")) !== FALSE) {
                    $i++;
                    if ($ignoreFirstLine && $i == 1) {
                        continue;
                    }
                    $rows[] = $data;
                }
                fclose($handle);
            }
    
            return $rows;
        }
    }
    
    

    external by Joiz  17522  191  5  0

    Allow CORS in symfony2

    Allow CORS in symfony2 : gistfile1.txt
    <?php
    /**
     * Joiz IP AG
     *
     * User: efun
     * Date: 07.07.14
     * Time: 13:48
     */
    
    namespace Joiz\PublicApiTokenBundle\Listener;
    
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    
    /**
     *
     * allow to use the api with CORS - defined pre and post controller execution breakpoints
     *
     * Class CorsListener
     * @package Joiz\PublicApiTokenBundle\Listener
     *
     */
    class CorsListener
    {
    
        /**
         *
         * check if we have a options CORS request - dont process anything in this case ! - just say its OK
         *
         *
         *  also check https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
         *
         * @param GetResponseEvent $event
         */
        public function onKernelRequest(GetResponseEvent $event)
        {
    
            $request = $event->getRequest();
            if ($request->headers->has("Access-Control-Request-Headers") && $request->headers->has("Access-Control-Request-Method")) {
    
                $response = new Response();
                //enable CORS - return the requested methods as allowed
                $response->headers->add(
                    array('Access-Control-Allow-Headers' => $request->headers->get("Access-Control-Request-Headers"),
                        'Access-Control-Allow-Methods' => $request->headers->get("Access-Control-Request-Method"),
                        'Access-Control-Allow-Origin' => '*'));
                $event->setResponse($response);
                $event->stopPropagation();
            }
        }
    
    
        /**
         *
         * add CORS crossdomain for all requests accepting JSON
         *
         * @param FilterResponseEvent $event
         */
        public function onKernelResponse(FilterResponseEvent $event)
        {
            $response = $event->getResponse();
            $request = $event->getRequest();
            if ($request->headers->has("Accept") && strstr($request->headers->get("Accept"),"application/json")) {
                $response->headers->add(array('Access-Control-Allow-Origin' => '*'));
            }
        }
    }
    
    
    add this to your service config
    
    
        joiz_public_api_token.cors.listener:
            class: Joiz\PublicApiTokenBundle\Listener\CorsListener
            tags:
                 - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest , priority: 100}
                 - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse, priority: -100}
    
    

    external by brpaz  1140  17  3  0

    Logstash config for Symfony2 #logstash #symfony2

    Logstash config for Symfony2 #logstash #symfony2: logstash-symfony2
    input {
      file {
        # /path/to/APP/app/logs/prod.log
        path => "/srv/*/app/logs/dev.log"
      }  
    }
    
    filter {
      grok {
        match => {
          # match above path to extract appname
          "path" => "/srv/%{GREEDYDATA:appname}/app/logs/dev\.log"
        }
      }
      grok {
        match => {
           "message" => "\[%{TIMESTAMP_ISO8601:timestamp}\] %{DATA}%{LOGLEVEL:level}: %{GREEDYDATA:msg}"
        }
      }
      date {
        match => [ "timestamp" , "yyyy-MM-dd HH:mm:ss" ]
      }
    }
    
    output {
      elasticsearch {
        host => "localhost"
        protocol => http
      }
      stdout { codec => rubydebug }
    }
    
    
    

    external by Yorkie Chadwick  205  0  2  0

    To be used with an initcms and symfony2 based project. Simple script for pulling changes from git, updating dependencies, clearing caches, installing and compiling assets.

    To be used with an initcms and symfony2 based project. Simple script for pulling changes from git, updating dependencies, clearing caches, installing and compiling assets. : initcms-deploy.sh
    #!/bin/bash
    #########################################
    #
    # Make sure the script is executable by
    # running chmod u+x initcms-deploy.sh
    # To run this command, change to same
    # directory as this file, and on the
    # command line type the following:
    # ./initcms-deploy.sh
    #
    #########################################
    
    #########################################
    #Black        0;30     Dark Gray     0;30
    #Red          0;31     Light Red     0;31
    #Green        0;32     Light Green   0;32
    #Brown/Orange 0;33     Yellow        0;33
    #Blue         0;34     Light Blue    0;34
    #Purple       0;35     Light Purple  0;35
    #Cyan         0;36     Light Cyan    0;36
    #Light Gray   0;37     White         0;37
    #########################################
    
    YELLOW='\033[0;33m'
    CYAN='\033[0;36m'
    GREEN='\033[0;32m'
    NC='\033[0m' # No Color
    INSTALL=''
    ENV=$1
    
    #check if should install dependencies
    install_composer(){
        echo -e "${YELLOW}Do you want to do a composer install?${NC} ${CYAN}y/n${NC}"
        read INSTALL
    
        #validate input
        if [ "$INSTALL" != "y" ] && [ "$INSTALL" != "n" ]; then
            install_composer
        fi
    }
    
    #check env parameter
    check_env(){
        echo -e "${YELLOW}Which environment do you want to update?${NC} ${CYAN}dev/prod${NC}"
        read ENV
    
        #validate input
        if [ "$ENV" != "prod" ] && [ "$ENV" != "dev" ]; then
            check_env
        fi
    }
    
    #run all
    run(){
        if [ -z "$ENV" ]; then
            echo -e "${YELLOW}Deploy symfony project${NC}";
        else
            echo -e "${YELLOW}Deploy symfony project in ${GREEN}$ENV${NC} ${YELLOW}environment${NC}";
        fi
        echo "Git pull from repository"
        git pull
    
        install_composer
    
        #Ask if the user wants to do a composer install
        if [ "$INSTALL" == "y" ]; then
            php -d memory_limit=512M composer.phar install --no-dev --optimize-autoloader
        fi
    
        #if no environment is given, ask wich to use
        if [ "$ENV" != "prod" ] && [ "$ENV" != "dev" ]; then
            check_env
        fi
    
        if [ "$INSTALL" == "y" ] && [ "$ENV" == "prod" ]; then
            php -d memory_limit=512M app/console --env=$ENV   cache:clear
        elif [ "$INSTALL" != "y" ]; then
            #if a composer install was not made, then install assets
            php -d memory_limit=512M app/console --env=$ENV   cache:clear
            app/console --env=$ENV assets:install
        fi
    
        app/console --env=$ENV  assetic:dump
    
        echo -e "${GREEN}All set and ready to go! Have fun :) ${NC}"
    }
    
    if [ "$ENV" == "-h" ]; then
        #help text
        echo -e "${YELLOW}To run the script, enter the following:${NC} ./initcms-deploy.sh"
        echo -e "${YELLOW}You can also add the environment directly to the command, for example:${NC}  ./initcms-deploy.sh prod"
    else
        run
    fi
    
    

    external by FlorianKromer  9747  83  5  0

    Bootstrap navbar with knp-menu-bundle for symfony2

    Bootstrap navbar with knp-menu-bundle for symfony2: Memo_KnpMenuBundle_Bootstrap
    # Bootstrap navbar with knp-menu-bundle
    
    ## knp-menu-bundle installation
    
    composer.json
    ```
      "knplabs/knp-menu-bundle": "~2.0",
    ```
    ## Add knp-menu as service
    
    services.yml
    
    ```yml
        cg_main.menu_builder:
            class: CG\MainBundle\Menu\MenuBuilder
            arguments: ["@knp_menu.factory"]
    
        cg_main.menu.footer:
            class: Knp\Menu\MenuItem # the service definition requires setting the class
            factory_service: cg_main.menu_builder
            factory_method: createFooterMenu
            arguments: ["@request"]
            scope: request # needed as we have the request as a dependency here
            tags:
                - { name: knp_menu.menu, alias: footer } # The alias is what is used to retrieve the menu
    ```
    
    ## Create a menu
    
    MenuBuilder.php
    
    ```php
    <?php
    namespace CG\MainBundle\Menu;
    
    use Knp\Menu\FactoryInterface;
    use Symfony\Component\DependencyInjection\ContainerAware;
    use Symfony\Component\HttpFoundation\Request;
    
    class MenuBuilder
    {
        private $factory;
    
        /**
         * @param FactoryInterface $factory
         */
        public function __construct(FactoryInterface $factory)
        {
            $this->factory = $factory;
        }
    
        public function createFooterMenu(Request $request)
        {
            $menu = $this->factory->createItem('root');
            $menu->setChildrenAttributes(array('class' => 'nav navbar-nav navbar-right'));
            $menu->addChild('News', array('route' => 'cg_main_news'));
            $menu->addChild('Informations')->setAttribute('dropdown', true);
            $menu['Informations']->addChild('Services', array('route' => 'cg_main_services'));
            $menu['Informations']->addChild('A propos', array('route' => 'cg_main_about'));
            $menu->addChild('Mon compte', array('route' => 'cg_main_compte'));
            $menu->addChild('Contact', array('route' => 'cg_main_contact'));
            return $menu;
        }
    }
    
    ```
    ## Template for navbar with dropdown
    
    knp_menu.html.twig
    
    ```php
      {% extends 'knp_menu.html.twig' %}
      
      {% block item %}
      {% import "knp_menu.html.twig" as macros %}
      {% if item.displayed %}
      {%- set attributes = item.attributes %}
      {%- set is_dropdown = attributes.dropdown|default(false) %}
      {%- set divider_prepend = attributes.divider_prepend|default(false) %}
      {%- set divider_append = attributes.divider_append|default(false) %}
      
      {# unset bootstrap specific attributes #}
      {%- set attributes = attributes|merge({'dropdown': null, 'divider_prepend': null, 'divider_append': null }) %}
      
      {%- if divider_prepend %}
      {{ block('dividerElement') }}
      {%- endif %}
      
      {# building the class of the item #}
      {%- set classes = item.attribute('class') is not empty ? [item.attribute('class')] : [] %}
      {%- if matcher.isCurrent(item) %}
      {%- set classes = classes|merge([options.currentClass]) %}
      {%- elseif matcher.isAncestor(item, options.depth) %}
      {%- set classes = classes|merge([options.ancestorClass]) %}
      {%- endif %}
      {%- if item.actsLikeFirst %}
      {%- set classes = classes|merge([options.firstClass]) %}
      {%- endif %}
      {%- if item.actsLikeLast %}
      {%- set classes = classes|merge([options.lastClass]) %}
      {%- endif %}
      
      {# building the class of the children #}
      {%- set childrenClasses = item.childrenAttribute('class') is not empty ? [item.childrenAttribute('class')] : [] %}
      {%- set childrenClasses = childrenClasses|merge(['menu_level_' ~ item.level]) %}
      
      {# adding classes for dropdown #}
      {%- if is_dropdown %}
      {%- set classes = classes|merge(['dropdown']) %}
      {%- set childrenClasses = childrenClasses|merge(['dropdown-menu']) %}
      {%- endif %}
      
      {# putting classes together #}
      {%- if classes is not empty %}
      {%- set attributes = attributes|merge({'class': classes|join(' ')}) %}
      {%- endif %}
      {%- set listAttributes = item.childrenAttributes|merge({'class': childrenClasses|join(' ') }) %}
      
      {# displaying the item #}
      <li{{ macros.attributes(attributes) }}>
      {%- if is_dropdown %}
      {{ block('dropdownElement') }}
      {%- elseif item.uri is not empty and (not item.current or options.currentAsLink) %}
      {{ block('linkElement') }}
      {%- else %}
      {{ block('spanElement') }}
      {%- endif %}
      {# render the list of children#}
      {{ block('list') }}
      </li>
      
      {%- if divider_append %}
      {{ block('dividerElement') }}
      {%- endif %}
      {% endif %}
      {% endblock %}
      
      {% block dividerElement %}
      {% if item.level == 1 %}
      <li class="divider-vertical"></li>
      {% else %}
      <li class="divider"></li>
      {% endif %}
      {% endblock %}
      
      {% block linkElement %}
      <a href="{{ item.uri }}"{{ macros.attributes(item.linkAttributes) }}>
      {% if item.attribute('icon') is not empty %}
      <i class="{{ item.attribute('icon') }}"></i>
      {% endif %}
      {{ block('label') }}
      </a>
      {% endblock %}
      
      {% block spanElement %}
      <span>{{ macros.attributes(item.labelAttributes) }}>
      {% if item.attribute('icon') is not empty %}
      <i class="{{ item.attribute('icon') }}"></i>
      {% endif %}
      {{ block('label') }}
      </span>
      {% endblock %}
      
      {% block dropdownElement %}
      {%- set classes = item.linkAttribute('class') is not empty ? [item.linkAttribute('class')] : [] %}
      {%- set classes = classes|merge(['dropdown-toggle']) %}
      {%- set attributes = item.linkAttributes %}
      {%- set attributes = attributes|merge({'class': classes|join(' ')}) %}
      {%- set attributes = attributes|merge({'data-toggle': 'dropdown'}) %}
      <a href="#"{{ macros.attributes(attributes) }}>
      {% if item.attribute('icon') is not empty %}
      <i class="{{ item.attribute('icon') }}"></i>
      {% endif %}
      {{ block('label') }}
      <b class="caret"></b>
      </a>
      {% endblock %}
      
      {% block label %}{{ item.label|trans }}{% endblock %}
    ```
    
    ## A random call in your code
    
    layout.html.twig
    ```php
    {% extends '::base.html.twig' %}
    {% block body %}
    	{% block navbar %}
    	    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <div class="container">
                <!-- Brand and toggle get grouped for better mobile display -->
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="{{ path("cg_main_index") }}">CGdroid</a>
                </div>
                <!-- Collect the nav links, forms, and other content for toggling -->
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                	{{ knp_menu_render('footer',{'currentClass': 'active','template': 'CGMainBundle:Menu:knp_menu.html.twig'}) }}
                </div>
                <!-- /.navbar-collapse -->
            </div>
            <!-- /.container -->
        </nav>
    	{% endblock %}
    	{% block container %}
    	{% endblock %}
    {% endblock body %}
    ```
    
    
    

    external by leonelvsc  114  0  2  0

    Run symfony2 docker image on root of SF2Project folder

    Run symfony2 docker image on root of SF2Project folder: gistfile1.sh
    # 1st file place it in bin/start
    
    #!/bin/bash
      docker run -d \
        -v $(pwd):/var/www \
        -p 8000:80 \
        -p 8001:22 \
        --cidfile app/cache/docker.cid \
        leonelvsc/symfony2
        
        
    #=============================================
    
    # 2nd file bin/stop
    
    #!/bin/bash
    
    docker stop $(cat app/cache/docker.cid)
    
    

    external by brpaz  103  0  2  0

    Symfony2 Model Manager #symfony

    Symfony2 Model Manager #symfony: BaseModelManager.php
    PHP
    <?php
    abstract class BaseModelManager {
    
        protected $em;
        protected $class;
        protected $repository;
        protected $container;
    
        /**
         * Constructor.
         *
         * @param EntityManager  $em
         * @param string   $class
         */
        public function __construct(EntityManager $em, $class) {
            $this->em = $em;
            $this->repository = $em->getRepository($class);
            $metadata = $em->getClassMetadata($class);
            $this->class = $metadata->name;
        }
    
        public function setContainer($container) {
            $this->container = $container;
        }
    
        public function getContainer() {
            return $this->container;
        }
    
        public function getDispatcher() {
            return $this->getContainer()->get('event_dispatcher');
        }
    
        /**
         * Create model object
         *
         * @return BaseModel
         */
        public function create() {
            $class = $this->getClass();
            return new $class;
        }
    
        /**
         * Persist the model
         *
         * @param $model
         * @param boolean $flush
         * @return BaseModel
         */
        public function save($model, $flush= true) {
            $this->getDispatcher()->dispatch('model_before_save', new ModelEvent($model, $this->getContainer()));
            $this->getDispatcher()->dispatch($model->getEventPrefix() . '_before_save', new ModelEvent($model, $this->getContainer()));
            $this->_save($model, $flush);
            $this->getDispatcher()->dispatch('model_after_save', new ModelEvent($model, $this->getContainer()));
            $this->getDispatcher()->dispatch($model->getEventPrefix() . '_after_save', new ModelEvent($model, $this->getContainer()));
            return $model;
        }
    
        /**
         *	This is basic save function. Child model can overwrite this.
         */
        protected function _save($model, $flush=true) {
            $this->em->persist($model);
            if ($flush) {
                $this->em->flush();
            }
        }
    
        /**
         * Delete a model.
         *
         * @param BaseModel $model
         */
        public function delete($model, $flush = true) {
            $this->getDispatcher()->dispatch('model_before_delete', new ModelEvent($model, $this->getContainer()));
            $this->getDispatcher()->dispatch($model->getEventPrefix() . '_before_delete', new ModelEvent($model, $this->getContainer()));
            $this->_delete($model, $flush);
            $this->getDispatcher()->dispatch('model_after_delete', new ModelEvent($model, $this->getContainer()));
            $this->getDispatcher()->dispatch($model->getEventPrefix() . '_after_delete', new ModelEvent($model, $this->getContainer()));
        }
    
        /**
         * Remove model.
         */
        public function _delete($model, $flush = true) {
            $this->em->remove($model);
            if ($flush) {
                $this->em->flush();
            }
        }
    
        /**
         * Reload the model data.
         */
        public function reload($model) {
            $this->em->refresh($model);
        }
    
        /**
         * Returns the user's fully qualified class name.
         *
         * @return string
         */
        public function getClass() {
            return $this->class;
        }
    
        /**
         * @param $id
         * @return BaseModel
         */
        public function find($id) {
            return $this->repository->findOneBy(array('id' => $id));
        }
    
        public function isDebug() {
            return $this->container->get('kernel')->isDebug();
        }
    
    }
    
    
    • Public Snippets
    • Channels Snippets