Skip to content
This repository has been archived by the owner on Feb 24, 2021. It is now read-only.

Commit

Permalink
Working STOF and Fixtures
Browse files Browse the repository at this point in the history
  • Loading branch information
Pavel Šrytr committed Mar 1, 2020
1 parent 6fc8183 commit 5524c00
Show file tree
Hide file tree
Showing 14 changed files with 645 additions and 2 deletions.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"vich/uploader-bundle": "^1.13"
},
"require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.3",
"symfony/debug-pack": "*",
"symfony/profiler-pack": "*",
"symfony/test-pack": "*"
Expand Down
133 changes: 132 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions config/bundles.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@
Knp\Bundle\TimeBundle\KnpTimeBundle::class => ['all' => true],
Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle::class => ['all' => true],
Vich\UploaderBundle\VichUploaderBundle::class => ['all' => true],
Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle::class => ['dev' => true, 'test' => true],
];
7 changes: 7 additions & 0 deletions config/packages/security.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@ security:
security: false
main:
anonymous: lazy
guard:
authenticators:
- App\Security\LoginAuthenticator
logout:
path: app_logout
# where to redirect after logout
# target: app_any_route

# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
Expand Down
6 changes: 5 additions & 1 deletion config/packages/stof_doctrine_extensions.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# Read the documentation: https://symfony.com/doc/current/bundles/StofDoctrineExtensionsBundle/index.html
# See the official DoctrineExtensions documentation for more details: https://github.com/Atlantic18/DoctrineExtensions/tree/master/doc/
stof_doctrine_extensions:
default_locale: en_US
default_locale: cs_CZ
orm:
default:
sluggable: true;
timestampable: true
36 changes: 36 additions & 0 deletions src/Controller/SecurityController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }

// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();

return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}

/**
* @Route("/logout", name="app_logout")
*/
public function logout()
{
throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
}
}
17 changes: 17 additions & 0 deletions src/DataFixtures/AppFixtures.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace App\DataFixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;

class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
// $product = new Product();
// $manager->persist($product);

$manager->flush();
}
}
91 changes: 91 additions & 0 deletions src/DataFixtures/BaseFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

namespace App\DataFixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use Faker\Factory;
use Faker\Generator;

abstract class BaseFixture extends Fixture
{
/** @var ObjectManager */
private $manager;

/** @var Generator */
protected $faker;

private $referencesIndex = [];

abstract protected function loadData(ObjectManager $manager);

public function load(ObjectManager $manager)
{
$this->manager = $manager;
$this->faker = Factory::create();

$this->loadData($manager);
}

/**
* Create many objects at once:
*
* $this->createMany(10, function(int $i) {
* $user = new User();
* $user->setFirstName('Ryan');
*
* return $user;
* });
*
* @param int $count
* @param string $groupName Tag these created objects with this group name,
* and use this later with getRandomReference(s)
* to fetch only from this specific group.
* @param callable $factory
*/
protected function createMany(int $count, string $groupName, callable $factory)
{
for ($i = 0; $i < $count; $i++) {
$entity = $factory($i);

if (null === $entity) {
throw new \LogicException('Did you forget to return the entity object from your callback to BaseFixture::createMany()?');
}

$this->manager->persist($entity);

// store for usage later as groupName_#COUNT#
$this->addReference(sprintf('%s_%d', $groupName, $i), $entity);
}
}

protected function getRandomReference(string $groupName) {
if (!isset($this->referencesIndex[$groupName])) {
$this->referencesIndex[$groupName] = [];

foreach ($this->referenceRepository->getReferences() as $key => $ref) {
if (strpos($key, $groupName.'_') === 0) {
$this->referencesIndex[$groupName][] = $key;
}
}
}

if (empty($this->referencesIndex[$groupName])) {
throw new \InvalidArgumentException(sprintf('Did not find any references saved with the group name "%s"', $groupName));
}

$randomReferenceKey = $this->faker->randomElement($this->referencesIndex[$groupName]);

return $this->getReference($randomReferenceKey);
}

protected function getRandomReferences(string $className, int $count)
{
$references = [];
while (count($references) < $count) {
$references[] = $this->getRandomReference($className);
}

return $references;
}
}
39 changes: 39 additions & 0 deletions src/DataFixtures/UserFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace App\DataFixtures;

use App\Entity\User;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Faker\Provider\Base;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class UserFixture extends BaseFixture
{
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;

public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{

$this->passwordEncoder = $passwordEncoder;
}

protected function loadData(\Doctrine\Persistence\ObjectManager $manager)
{
$this->createMany(20, 'users', function ($i){
$user = new User();
$user->setName($this->faker->firstName());
$user->setSurname($this->faker->lastName);
$user->setEmail(sprintf("user%[email protected]",$i));
$user->setPassword($this->passwordEncoder->encodePassword($user,"engage"));
$user->changeKarma($this->faker->numberBetween(-5,350));

return $user;
});

$manager->flush();
}
}
Loading

0 comments on commit 5524c00

Please sign in to comment.