Skip to content

Commit

Permalink
minor symfony#727 Revamped the data fixtures (javiereguiluz)
Browse files Browse the repository at this point in the history
This PR was squashed before being merged into the master branch (closes symfony#727).

Discussion
----------

Revamped the data fixtures

After symfony#724 and symfony#725 I realized that our fixtures are not following the modern best practices recommended by DoctrineFixturesBundle ([explained here](https://symfony.com/doc/master/bundles/DoctrineFixturesBundle/index.html)):

* Use 1 class to load all fixtures unless you have lots of fixtures.
* Make the fixture class extend from Symfony's `Fixture` class instead of the complicated Doctrine's classes.
* Inject services in the constructor and rely on autowiring.
* etc.

Commits
-------

adb76fc Revamped the data fixtures
  • Loading branch information
javiereguiluz committed Dec 11, 2017
2 parents 3bdaac0 + adb76fc commit 30f4ccd
Show file tree
Hide file tree
Showing 7 changed files with 179 additions and 322 deletions.
235 changes: 163 additions & 72 deletions src/DataFixtures/FixturesTrait.php → src/DataFixtures/AppFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,49 +11,131 @@

namespace App\DataFixtures;

/**
* Helper class to create fixtures contents.
*/
trait FixturesTrait
use App\Entity\Comment;
use App\Entity\Post;
use App\Entity\Tag;
use App\Entity\User;
use App\Utils\Slugger;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class AppFixtures extends Fixture
{
private function getPostContent(): string
private $passwordEncoder;

public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
return <<<'MARKDOWN'
Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et **dolore magna aliqua**: Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
$this->passwordEncoder = $passwordEncoder;
}

* Ut enim ad minim veniam
* Quis nostrud exercitation *ullamco laboris*
* Nisi ut aliquip ex ea commodo consequat
public function load(ObjectManager $manager)
{
$this->loadUsers($manager);
$this->loadTags($manager);
$this->loadPosts($manager);
}

Praesent id fermentum lorem. Ut est lorem, fringilla at accumsan nec, euismod at
nunc. Aenean mattis sollicitudin mattis. Nullam pulvinar vestibulum bibendum.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Fusce nulla purus, gravida ac interdum ut, blandit eget ex. Duis a
luctus dolor.
private function loadUsers(ObjectManager $manager)
{
foreach ($this->getUserData() as [$fullname, $username, $password, $email, $roles]) {
$user = new User();
$user->setFullName($fullname);
$user->setUsername($username);
$user->setPassword($this->passwordEncoder->encodePassword($user, $password));
$user->setEmail($email);
$user->setRoles($roles);

$manager->persist($user);
$this->addReference($username, $user);
}

Integer auctor massa maximus nulla scelerisque accumsan. *Aliquam ac malesuada*
ex. Pellentesque tortor magna, vulputate eu vulputate ut, venenatis ac lectus.
Praesent ut lacinia sem. Mauris a lectus eget felis mollis feugiat. Quisque
efficitur, mi ut semper pulvinar, urna urna blandit massa, eget tincidunt augue
nulla vitae est.
$manager->flush();
}

Ut posuere aliquet tincidunt. Aliquam erat volutpat. **Class aptent taciti**
sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi
arcu orci, gravida eget aliquam eu, suscipit et ante. Morbi vulputate metus vel
ipsum finibus, ut dapibus massa feugiat. Vestibulum vel lobortis libero. Sed
tincidunt tellus et viverra scelerisque. Pellentesque tincidunt cursus felis.
Sed in egestas erat.
private function loadTags(ObjectManager $manager)
{
foreach ($this->getTagData() as $index => $name) {
$tag = new Tag();
$tag->setName($name);

Aliquam pulvinar interdum massa, vel ullamcorper ante consectetur eu. Vestibulum
lacinia ac enim vel placerat. Integer pulvinar magna nec dui malesuada, nec
congue nisl dictum. Donec mollis nisl tortor, at congue erat consequat a. Nam
tempus elit porta, blandit elit vel, viverra lorem. Sed sit amet tellus
tincidunt, faucibus nisl in, aliquet libero.
MARKDOWN;
$manager->persist($tag);
$this->addReference('tag-'.$name, $tag);
}

$manager->flush();
}

private function loadPosts(ObjectManager $manager)
{
foreach ($this->getPostData() as [$title, $slug, $summary, $content, $publishedAt, $author, $tags]) {
$post = new Post();
$post->setTitle($title);
$post->setSlug($slug);
$post->setSummary($summary);
$post->setContent($content);
$post->setPublishedAt($publishedAt);
$post->setAuthor($author);
$post->addTag(...$tags);

foreach (range(1, 5) as $i) {
$comment = new Comment();
$comment->setAuthor($this->getReference('john_user'));
$comment->setContent($this->getRandomText(random_int(255, 512)));
$comment->setPublishedAt(new \DateTime('now + '.($i).'seconds'));

$post->addComment($comment);
}

$manager->persist($post);
}

$manager->flush();
}

private function getUserData(): array
{
return [
// $userData = [$fullname, $username, $password, $email, $roles];
['Jane Doe', 'jane_admin', 'kitten', '[email protected]', ['ROLE_ADMIN']],
['Tom Doe', 'tom_admin', 'kitten', '[email protected]', ['ROLE_ADMIN']],
['John Doe', 'john_user', 'kitten', '[email protected]', ['ROLE_USER']],
];
}

private function getTagData(): array
{
return [
'lorem',
'ipsum',
'consectetur',
'adipiscing',
'incididunt',
'labore',
'voluptate',
'dolore',
'pariatur',
];
}

private function getPostData()
{
$posts = [];
foreach ($this->getPhrases() as $i => $title) {
// $postData = [$title, $slug, $summary, $content, $publishedAt, $author, $tags, $comments];
$posts[] = [
$title,
Slugger::slugify($title),
$this->getRandomText(),
$this->getPostContent(),
new \DateTime('now - '.$i.'days'),
// Ensure that the first post is written by Jane Doe to simplify tests
$this->getReference(['jane_admin', 'tom_admin'][0 === $i ? 0 : random_int(0, 1)]),
$this->getRandomTags(),
];
}

return $posts;
}

private function getPhrases(): array
Expand Down Expand Up @@ -92,55 +174,64 @@ private function getPhrases(): array
];
}

private function getTagNames(): array
{
return [
'lorem',
'ipsum',
'consectetur',
'adipiscing',
'incididunt',
'labore',
'voluptate',
'dolore',
'pariatur',
];
}

private function getRandomPostTitles(): array
private function getRandomText(int $maxLength = 255): string
{
$phrases = $this->getPhrases();

// this ensures that the first title is always 'Lorem Ipsum...'
$loremIpsumPhrase = array_shift($phrases);
shuffle($phrases);
array_unshift($phrases, $loremIpsumPhrase);

return $phrases;
while (mb_strlen($text = implode('. ', $phrases).'.') > $maxLength) {
array_pop($phrases);
}

return $text;
}

private function getRandomPostSummary(int $maxLength = 255): string
private function getPostContent(): string
{
$phrases = $this->getPhrases();
return <<<'MARKDOWN'
Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et **dolore magna aliqua**: Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
$numPhrases = random_int(6, 12);
shuffle($phrases);
$phrases = array_slice($phrases, 0, $numPhrases - 1);
* Ut enim ad minim veniam
* Quis nostrud exercitation *ullamco laboris*
* Nisi ut aliquip ex ea commodo consequat
while (mb_strlen($summary = implode('. ', $phrases).'.') > $maxLength) {
array_pop($phrases);
}
Praesent id fermentum lorem. Ut est lorem, fringilla at accumsan nec, euismod at
nunc. Aenean mattis sollicitudin mattis. Nullam pulvinar vestibulum bibendum.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Fusce nulla purus, gravida ac interdum ut, blandit eget ex. Duis a
luctus dolor.
Integer auctor massa maximus nulla scelerisque accumsan. *Aliquam ac malesuada*
ex. Pellentesque tortor magna, vulputate eu vulputate ut, venenatis ac lectus.
Praesent ut lacinia sem. Mauris a lectus eget felis mollis feugiat. Quisque
efficitur, mi ut semper pulvinar, urna urna blandit massa, eget tincidunt augue
nulla vitae est.
return $summary;
Ut posuere aliquet tincidunt. Aliquam erat volutpat. **Class aptent taciti**
sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi
arcu orci, gravida eget aliquam eu, suscipit et ante. Morbi vulputate metus vel
ipsum finibus, ut dapibus massa feugiat. Vestibulum vel lobortis libero. Sed
tincidunt tellus et viverra scelerisque. Pellentesque tincidunt cursus felis.
Sed in egestas erat.
Aliquam pulvinar interdum massa, vel ullamcorper ante consectetur eu. Vestibulum
lacinia ac enim vel placerat. Integer pulvinar magna nec dui malesuada, nec
congue nisl dictum. Donec mollis nisl tortor, at congue erat consequat a. Nam
tempus elit porta, blandit elit vel, viverra lorem. Sed sit amet tellus
tincidunt, faucibus nisl in, aliquet libero.
MARKDOWN;
}

private function getRandomCommentContent(): string
private function getRandomTags(): array
{
$phrases = $this->getPhrases();

$numPhrases = random_int(2, 15);
shuffle($phrases);
$tagNames = $this->getTagData();
shuffle($tagNames);
$selectedTags = array_slice($tagNames, 0, random_int(2, 4));

return implode(' ', array_slice($phrases, 0, $numPhrases - 1));
return array_map(function ($tagName) { return $this->getReference('tag-'.$tagName); }, $selectedTags);
}
}
117 changes: 0 additions & 117 deletions src/DataFixtures/PostFixtures.php

This file was deleted.

Loading

0 comments on commit 30f4ccd

Please sign in to comment.