Copy of hautelook/alice-bundle v2.9.0

Related tags

API AliceBundle
Overview

AliceBundle

A Symfony bundle to manage fixtures with nelmio/alice and fzaninotto/Faker.

The database support is done in FidryAliceDataFixtures. Check this project to know which database/ORM is supported.

Warning: this is the documentation for HautelookAliceBundle 2.0. If you want to check the documentation for 1.x, head this way.

Package version Build Status SensioLabsInsight Dependency Status Scrutinizer Code Quality Code Coverage Slack

When to use this bundle?

HautelookAliceBundle changed a lot, it first was acting as a simple bundle for nelmio/alice, it then started to ship some additional features to enrich it.

HautelookAliceBundle 1.x was the first milestone reaching a certain level of maturity in its usage:

  • Easily load a set of fixtures from a command
  • Being able to define different sets of fixtures for multiple environments
  • Customize the data generation with custom Faker providers
  • Customize the loading behaviour with processors

HautelookAliceBundle 2.x changes a lot, although not so much. In 1.x, a lot of complexity was brought in the bundle due to nelmio/alice 2.x limitations and were at best workarounds (like the lack of handling of circular references). A lot of that complexity has been pushed back to nelmio/alice 3.x which has a much more flexible design. As a result:

  • nelmio/alice 3.x allows you to easily create PHP objects with random data in an elegant way
  • FidryAliceDataFixtures is a persistence layer for nelmio/alice 3.x. If you need to persist the loaded objects, it is the package you need. It provides you the flexibility to be able to purge the data between each loadings or wrap the loading in a transaction for your tests for example to simply rollback once the test is finished instead of calling an expansive purge.
  • hautelook/alice-bundle 2.x provides high-level features including fixtures discovery (find the appropriate files and load them), and helpers for database testing. If you just need to load specific sets of files for your tests, FidryAliceDataFixtures is enough.

Documentation

  1. Install
  2. Basic usage
  3. Database testing
  4. Advanced usage
    1. Enabling databases
    2. Environment specific fixtures
    3. Fixtures parameters
      1. Alice parameters
      2. Application parameters
    4. Use service factories
    5. Load fixtures in a specific order
      1. Load fixtures in a specific order
      2. Persisting the classes in a specific order
  5. Custom Faker Providers
  6. Custom Alice Processors
  7. Resources

Installation

With Symfony Flex (recommended):

# If you do not have Doctrine installed yet:
composer require doctrine-orm

composer require --dev hautelook/alice-bundle 

You're ready to use AliceBundle, and can jump to the next section!

Without Flex you will have to install doctrine/orm and register the bundles accordingly in app/AppKernel.php or wherever your Kernel class is located:

<?php
// app/AppKernel.php

public function registerBundles()
{
    $bundles = [
        new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
        // ...
        new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
    ];
    
    if (in_array($this->getEnvironment(), ['dev', 'test'])) {
        //...
        $bundles[] = new Nelmio\Alice\Bridge\Symfony\NelmioAliceBundle();
        $bundles[] = new Fidry\AliceDataFixtures\Bridge\Symfony\FidryAliceDataFixturesBundle();
        $bundles[] = new Hautelook\AliceBundle\HautelookAliceBundle();
    }

    return $bundles;
}

Configure the bundle to your needs, for example:

# config/packages/dev/hautelook_alice.yaml

hautelook_alice:
    fixtures_path: 'fixtures' # Path to which to look for fixtures relative to the project directory or the bundle path. May be a string or an array of strings.
    root_dirs:
        - '%kernel.root_dir%'
        - '%kernel.project_dir%'

If you are using a non-flex architecture, you may want to use Resources/fixtures instead of fixtures.

Basic usage

Assuming you are using Doctrine, make sure you have the doctrine/doctrine-bundle and doctrine/data-fixtures packages installed.

Then create a fixture file in one of the following location:

  • fixtures if you are using flex
  • app/Resources/fixtures if you have a non-flex bundle-less Symfony application
  • src/AppBundle/Resources/fixtures or any bundle under which you want to place the fixtures
# fixtures/dummy.yaml

App\Entity\Dummy:
    dummy_{1..10}:
        name: <name()>
        related_dummy: '@related_dummy*'
# fixtures/related_dummy.yaml

App\Entity\RelatedDummy:
    related_dummy_{1..10}:
        name: <name()>

Then simply load your fixtures with the doctrine command php bin/console hautelook:fixtures:load.

If you want to load the fixtures of a bundle only, do php bin/console hautelook:fixtures:load -b MyFirstBundle -b MySecondBundle.

See more.
Next chapter: Advanced usage

Database testing

The bundle provides nice helpers, inspired by Laravel, dedicated for database testing: RefreshDatabaseTrait, ReloadDatabaseTrait and RecreateDatabaseTrait. These traits allow to easily reset the database in a known state before each PHPUnit test: it purges the database then loads the fixtures.

They are particularly helpful when writing functional tests and when using Panther.

To improve performance, RefreshDatabaseTrait populates the database only one time, then wraps every tests in a transaction that will be rolled back at the end after its execution (regardless of if it's a success or a failure):

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RefreshDatabaseTrait;

    public function postCommentTest()
    {
        $client = static::createClient(); // The transaction starts just after the boot of the Symfony kernel
        $crawler = $client->request('GET', '/my-news');
        $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']);
        $client->submit($form);
        // At the end of this test, the transaction will be rolled back (even if the test fails)
    }
}

Sometimes, wrapping tests in transactions is not possible. For instance, when using Panther, changes to the database are made by another PHP process, so it wont work. In such cases, use the ReloadDatabase trait. It will purge the DB and load fixtures before every tests:

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\ReloadDatabaseTrait;
use Symfony\Component\Panther\PantherTestCase;

class NewsTest extends PantherTestCase // Be sure to extends KernelTestCase, WebTestCase or PantherTestCase
{
    use ReloadDatabaseTrait;

    public function postCommentTest()
    {
        $client = static::createPantherClient();// The database will be reset after every boot of the Symfony kernel

        $crawler = $client->request('GET', '/my-news');
        $form = $crawler->filter('#post-comment')->form(['new-comment' => 'Symfony is so cool!']);
        $client->submit($form);
    }
}

This strategy doesn't work when using Panther, because the changes to the database are done by another process, outside of the transaction.

Both traits provide several configuration options as protected static properties:

  • self::$manager: The name of the Doctrine manager to use
  • self::$bundles: The list of bundles where to look for fixtures
  • self::$append: Append fixtures instead of purging
  • self::$purgeWithTruncate: Use TRUNCATE to purge
  • self::$shard: The name of the Doctrine shard to use
  • self::$connection: The name of the Doctrine connection to use

Use them in the setUpBeforeClass method.

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RefreshDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RefreshDatabaseTrait;

    public static function setUpBeforeClass()
    {
        self::$append = true;
    }

    // ...
}

Finally, if you're using in memory SQLite for your tests, use RecreateDatabaseTrait to create the database schema "on the fly":

<?php

namespace App\Tests;

use Hautelook\AliceBundle\PhpUnit\RecreateDatabaseTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class NewsTest extends WebTestCase
{
    use RecreateDatabaseTrait;

    // ...
}

Resources

Credits

This bundle was originaly developped by Baldur RENSCH and HauteLook. It is now maintained by Théo FIDRY.

Other contributors.

License

license

You might also like...
Symfony bundle for EventSauce (WIP)

Symfony EventSauce (WIP) This bundle provides the basic and extended container configuration of symfony for the EventSauce library. Before using it, I

Symfony bundle integrating server-sent native notifications
Symfony bundle integrating server-sent native notifications

Symfony UX Notify Symfony UX Notify is a Symfony bundle integrating server-sent native notifications in Symfony applications using Mercure. It is part

Bundle to integrate Tactician with Symfony projects

TacticianBundle Symfony2 Bundle for the Tactician library https://github.com/thephpleague/tactician/ Installation Step 1: Download the Bundle Open a c

The news bundle adds news functionality to Contao 4

Contao 4 news bundle The news bundle adds news functionality to Contao 4. Contao is an Open Source PHP Content Management System for people who want a

A Symfony bundle that provides #StandWithUkraine banner and has some built-in features to block access to your resource for Russian-speaking users.
A Symfony bundle that provides #StandWithUkraine banner and has some built-in features to block access to your resource for Russian-speaking users.

StandWithUkraineBundle На русском? Смотри README.ru.md This bundle provides a built-in StandWithUkraine banner for your Symfony application and has so

SAML bundle for gateway, self-service, and ra

SURFnet SamlBundle A bundle that adds SAML capabilities to your application using simplesamlphp/saml2 Developed as part of the SURFnet Stepup Gateway

Fork from hautelook/phpass since that repo was deleted.

This repository is a fork from the original hautelook/phpass which seems to have been deleted on 2021-09-09. Openwall Phpass, modernized This is Openw

Copy/Paste Detector (CPD) for PHP code.

PHP Copy/Paste Detector (PHPCPD) phpcpd is a Copy/Paste Detector (CPD) for PHP code. Installation This tool is distributed as a PHP Archive (PHAR): $

Copy missing items from grocy to bring
Copy missing items from grocy to bring

Copy Grocy "Missing Products" to BRING List Build Container First build the container: docker build -t grocy-to-bring . Run Container Insert your Groc

Yab copy to new - A Textpattern plugin. Copies the current article content to a new one.

yab_copy_to_new Displays a new button in article write tab to copy the current article to a new one. Version: 0.2 Table of contents Plugin requirement

Neo Integrator adalah alat bantu untuk import data ke Neo Feeder dengan cara copy paste saja. bersifat free dan opensource. Semoga Bermanfaat.

Neo-Integrator Penerus dari SimpleFeeder, yang berubah jadi Excel2Feeder dan bertransformasi menjadi Neo-integrator Last Update : 16-05-2022 Capture :

This plugin integrates cache functionality into Guzzle Bundle, a bundle for building RESTful web service clients.

Guzzle Bundle Cache Plugin This plugin integrates cache functionality into Guzzle Bundle, a bundle for building RESTful web service clients. Requireme

This bundle provides tools to build a complete GraphQL server in your Symfony App.

OverblogGraphQLBundle This Symfony bundle provides integration of GraphQL using webonyx/graphql-php and GraphQL Relay. It also supports: batching with

Pure PHP implementation of GraphQL Server – Symfony Bundle

Symfony GraphQl Bundle This is a bundle based on the pure PHP GraphQL Server implementation This bundle provides you with: Full compatibility with the

DataTables bundle for Symfony

Symfony DataTables Bundle This bundle provides convenient integration of the popular DataTables jQuery library for realtime Ajax tables in your Symfon

GraphQL Bundle for Symfony 2.

Symfony 2 GraphQl Bundle Use Facebook GraphQL with Symfony 2. This library port laravel-graphql. It is based on the PHP implementation here. Installat

Laravel Twitter Bootstrap Bundle

Bootstrapper Latest stable version: Travis status : Current supported Bootstrap version: 3.2.0 Bootstrapper is a set of classes that allow you to quic

An Unleash bundle for Symfony applications to provide an easy way to use feature flags

Unleash Bundle An Unleash bundle for Symfony applications. This provide an easy way to implement feature flags using Gitlab Feature Flags Feature. Ins

Symfony Health Check Bundle Monitoring Project Status

Symfony Health Check Bundle Version Build Status Code Coverage master develop Installation Step 1: Download the Bundle Open a command console, enter y

Owner
Global4Net Ltd.
Global4Net Ltd.
Pure PHP implementation of GraphQL Server – Symfony Bundle

Symfony GraphQl Bundle This is a bundle based on the pure PHP GraphQL Server implementation This bundle provides you with: Full compatibility with the

null 283 Dec 15, 2022
DataTables bundle for Symfony

Symfony DataTables Bundle This bundle provides convenient integration of the popular DataTables jQuery library for realtime Ajax tables in your Symfon

Omines Internetbureau 199 Jan 3, 2023
GraphQL Bundle for Symfony 2.

Symfony 2 GraphQl Bundle Use Facebook GraphQL with Symfony 2. This library port laravel-graphql. It is based on the PHP implementation here. Installat

Sergey Varibrus 35 Nov 17, 2022
An Unleash bundle for Symfony applications to provide an easy way to use feature flags

Unleash Bundle An Unleash bundle for Symfony applications. This provide an easy way to implement feature flags using Gitlab Feature Flags Feature. Ins

Stogon 7 Oct 20, 2022
Symfony Health Check Bundle Monitoring Project Status

Symfony Health Check Bundle Version Build Status Code Coverage master develop Installation Step 1: Download the Bundle Open a command console, enter y

MacPaw Inc. 27 Jul 7, 2022
A bundle providing routes and glue code between Symfony and a WOPI connector.

WOPI Bundle A Symfony bundle to facilitate the implementation of the WOPI endpoints and protocol. Description The Web Application Open Platform Interf

Champs-Libres 5 Aug 20, 2022
The maker bundle allows you to generate content elements, front end modules

Contao 4 maker bundle The maker bundle allows you to generate content elements, front end modules, event listener, callbacks and hooks using interacti

Contao 7 Aug 3, 2022
Mediator - CQRS Symfony bundle. Auto Command/Query routing to corresponding handlers.

Installation $ composer require whsv26/mediator Bundle configuration // config/packages/mediator.php return static function (MediatorConfig $config)

Alexander Sv. 6 Aug 31, 2022
The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs

NelmioApiDocBundle The NelmioApiDocBundle bundle allows you to generate a decent documentation for your APIs. Migrate from 3.x to 4.0 To migrate from

Nelmio 2.1k Jan 6, 2023
Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project

AmiAirbrakeBundle Airbrake.io & Errbit integration for Symfony 3/4/5. This bundle plugs the Airbrake API client into Symfony project. Prerequisites Th

Anton Minin 8 May 6, 2022