Skip to content

Instantly share code, notes, and snippets.

@leblanc-simon
Created April 7, 2018 21:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leblanc-simon/d610160d70a81cf830175906431a5a74 to your computer and use it in GitHub Desktop.
Save leblanc-simon/d610160d70a81cf830175906431a5a74 to your computer and use it in GitHub Desktop.
Install and conifgure Vich with LiipImagine
#!/bin/bash
# Install Symfony 3.4
symfony new vich lts
# Go to the directory
cd vich
# Remove the parameters.yml to populate with good value
rm app/config/parameters.yml
# Update in last version
composer update
# Install Vich and Liip
composer require liip/imagine-bundle vich/uploader-bundle
# Register the bundles
cat << 'EOF' > app/AppKernel.php
<?php
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Liip\ImagineBundle\LiipImagineBundle(),
new Vich\UploaderBundle\VichUploaderBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new AppBundle\AppBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
if ('dev' === $this->getEnvironment()) {
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
$bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
}
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(function (ContainerBuilder $container) {
$container->setParameter('container.autowiring.strict_mode', true);
$container->setParameter('container.dumper.inline_class_loader', true);
$container->addObjectResource($this);
});
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
EOF
# Add the routing for Liip
echo "_liip_imagine:" >> app/config/routing.yml
echo ' resource: "@LiipImagineBundle/Resources/config/routing.xml"' >> app/config/routing.yml
# Add the configuration for Vich and Liip
cat << 'EOF' > app/config/config.yml
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
parameters:
locale: en
framework:
secret: '%secret%'
router:
resource: '%kernel.project_dir%/app/config/routing.yml'
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
default_locale: '%locale%'
trusted_hosts: ~
session:
handler_id: session.handler.native_file
save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
fragments: ~
http_method_override: true
assets: ~
php_errors:
log: true
# Twig Configuration
twig:
debug: '%kernel.debug%'
strict_variables: '%kernel.debug%'
form_themes:
- "@VichUploader/Form/fields.html.twig"
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: '%database_host%'
port: '%database_port%'
dbname: '%database_name%'
user: '%database_user%'
password: '%database_password%'
charset: UTF8
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: '%mailer_transport%'
host: '%mailer_host%'
username: '%mailer_user%'
password: '%mailer_password%'
spool: { type: memory }
vich_uploader:
db_driver: orm
mappings:
image:
uri_prefix: /uploads/images
upload_destination: '%kernel.project_dir%/web/uploads/images'
inject_on_load: false
delete_on_update: true
delete_on_remove: true
namer: 'vich_uploader.namer_origname'
directory_namer:
service: 'vich_uploader.directory_namer_subdir'
options: {chars_per_dir: 2, dirs: 3}
liip_imagine:
filter_sets:
test:
quality: 90
filters:
thumbnail:
size: [50, 50]
EOF
# Create the entity
mkdir src/AppBundle/Entity
cat << 'EOF' > src/AppBundle/Entity/Test.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @ORM\Entity
* @ORM\Table(name="test")
* @Vich\Uploadable
*/
class Test
{
/**
* @ORM\Id
* @ORM\Column(name="id", type="integer", options={"unsigned":true})
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="`label`", type="string", length=255, unique=true)
*/
protected $label;
/**
* @ORM\Column(name="pictogram", type="string", length=255, nullable=true)
*/
protected $image;
/**
* @Vich\UploadableField(mapping="image", fileNameProperty="image")
*/
protected $image_file;
public function getId(): ? int
{
return $this->id;
}
public function setLabel(string $label): self
{
$this->label = $label;
return $this;
}
public function getLabel(): ? string
{
return $this->label;
}
public function setImage(? string $image): self
{
$this->image = $image;
return $this;
}
public function getImage(): ? string
{
return $this->image;
}
public function setImageFile(File $image_file = null): self
{
$this->image_file = $image_file;
if (null !== $image_file) {
$this->setLabel(rand(0, 999999));
}
return $this;
}
/**
* @return File|null
*/
public function getImageFile(): ? File
{
return $this->image_file;
}
}
EOF
# Create the form
mkdir src/AppBundle/Form/
cat << 'EOF' > src/AppBundle/Form/TestType.php
<?php
namespace AppBundle\Form;
use AppBundle\Entity\Test;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;
class TestType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('label', null, [
])
->add('image_file', VichImageType::class, [
'imagine_pattern' => 'test',
])
->add('submit', SubmitType::class)
;
}
/**
* {@inheritdoc}
**/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults([
'data_class' => Test::class,
]);
}
}
EOF
# Create the controller
cat << 'EOF' > src/AppBundle/Controller/DefaultController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Test;
use AppBundle\Form\TestType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
class DefaultController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
$test = new Test();
$form = $this->createForm(TestType::class, $test);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->get('doctrine.orm.default_entity_manager')->persist($test);
$this->get('doctrine.orm.default_entity_manager')->flush();
return $this->redirectToRoute('edit');
}
return $this->render('default/index.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/edit", name="edit")
*/
public function editAction(Request $request)
{
$test = $this->get('doctrine.orm.default_entity_manager')->getRepository(Test::class)->find(1);
$form = $this->createForm(TestType::class, $test);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->get('doctrine.orm.default_entity_manager')->persist($test);
$this->get('doctrine.orm.default_entity_manager')->flush();
}
return $this->render('default/index.html.twig', [
'form' => $form->createView(),
]);
}
}
EOF
# Create the template
cat << 'EOF' > app/Resources/views/default/index.html.twig
{% extends 'base.html.twig' %}
{% block body %}
{{ form(form) }}
{% endblock %}
EOF
# Build database
bin/console doctrine:schema:create
# Launch server
bin/console server:run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment