References : working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
Inheritance: extends Sonata\UserBundle\Entity\BaseUser
Esempio n. 1
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $user = new User();
     $user->setUsername('admin')->setPlainPassword('admin123')->setSuperAdmin(true)->setEmail('*****@*****.**')->setRoles(['ROLE_SUPER_ADMIN'])->setEnabled(true);
     $manager->persist($user);
     $manager->flush($user);
     $user = new User();
     $user->setUsername('user')->setPlainPassword('user123')->setSuperAdmin(false)->setEmail('*****@*****.**')->setRoles(['ROLE_ADMIN', 'ROLE_USER'])->setEnabled(true);
     $manager->persist($user);
     $manager->flush($user);
 }
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $factory = $this->getSecurityManager();
     $userAdmin = new User();
     $userAdmin->setUsername('admin');
     $encoder = $factory->getEncoder($userAdmin);
     $encodedPassword = $encoder->encodePassword('admin', $userAdmin->getSalt());
     $userAdmin->setPassword($encodedPassword);
     $userAdmin->setEmail('*****@*****.**');
     $userAdmin->setEnabled(true);
     $userAdmin->setSuperAdmin(true);
     $manager->persist($userAdmin);
     $manager->flush();
 }
Esempio n. 3
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $objectManager)
 {
     $user = new User();
     $user->addRole("ROLE_SUPER_ADMIN");
     $user->setEnabled(true);
     $user->setUsername("AlexL");
     $user->setPlainPassword("alexl");
     $user->setEmail("*****@*****.**");
     $user->setFirstName("Alexandre");
     $user->setLastname("Lesage");
     $user->setDateOfBirth(\DateTime::createFromFormat('j/m/Y', '23/08/1994'));
     $objectManager->persist($user);
     $objectManager->flush();
 }
Esempio n. 4
0
 /**
  * Tests User->addSitesAnalysis() User->removeSitesAnalysis() User->getSitesAnalyses().
  */
 public function testAddSitesAnalysis()
 {
     $sitesAnalysis[0] = new Site();
     $sitesAnalysis[1] = new Site();
     $sitesAnalysis[2] = new Site();
     $this->assertTrue($this->user->getSitesAnalyses() instanceof Collection);
     $this->assertEquals(0, $this->user->getSitesAnalyses()->count());
     $this->user->addSitesAnalysis($sitesAnalysis[0]);
     $this->assertEquals(1, $this->user->getSitesAnalyses()->count());
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[0]));
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[1]));
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[2]));
     $this->user->addSitesAnalysis($sitesAnalysis[1]);
     $this->assertEquals(2, $this->user->getSitesAnalyses()->count());
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[0]));
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[1]));
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[2]));
     $this->user->removeSitesAnalysis($sitesAnalysis[2]);
     $this->assertEquals(2, $this->user->getSitesAnalyses()->count());
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[0]));
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[1]));
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[2]));
     $this->user->removeSitesAnalysis($sitesAnalysis[0]);
     $this->assertEquals(1, $this->user->getSitesAnalyses()->count());
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[0]));
     $this->assertTrue($this->user->getSitesAnalyses()->contains($sitesAnalysis[1]));
     $this->assertFalse($this->user->getSitesAnalyses()->contains($sitesAnalysis[2]));
 }
Esempio n. 5
0
 /**
  * Test manipulation of votes collection.
  *
  * @covers Application\Sonata\UserBundle\Entity\User::addVote()
  * @covers Application\Sonata\UserBundle\Entity\User::removeVote()
  * @covers Application\Sonata\UserBundle\Entity\User::getVotes()
  */
 public function testAddVote()
 {
     $votes[0] = new Vote();
     $votes[1] = new Vote();
     $votes[2] = new Vote();
     $this->assertTrue($this->object->getVotes() instanceof Collection);
     $this->assertEquals(0, $this->object->getVotes()->count());
     $this->object->addVote($votes[0]);
     $this->assertEquals(1, $this->object->getVotes()->count());
     $this->assertTrue($this->object->getVotes()->contains($votes[0]));
     $this->assertFalse($this->object->getVotes()->contains($votes[1]));
     $this->assertFalse($this->object->getVotes()->contains($votes[2]));
     $this->object->addVote($votes[1]);
     $this->assertEquals(2, $this->object->getVotes()->count());
     $this->assertTrue($this->object->getVotes()->contains($votes[0]));
     $this->assertTrue($this->object->getVotes()->contains($votes[1]));
     $this->assertFalse($this->object->getVotes()->contains($votes[2]));
     $this->object->removeVote($votes[2]);
     $this->assertEquals(2, $this->object->getVotes()->count());
     $this->assertTrue($this->object->getVotes()->contains($votes[0]));
     $this->assertTrue($this->object->getVotes()->contains($votes[1]));
     $this->assertFalse($this->object->getVotes()->contains($votes[2]));
     $this->object->removeVote($votes[0]);
     $this->assertEquals(1, $this->object->getVotes()->count());
     $this->assertFalse($this->object->getVotes()->contains($votes[0]));
     $this->assertTrue($this->object->getVotes()->contains($votes[1]));
     $this->assertFalse($this->object->getVotes()->contains($votes[2]));
 }
 private function manageFileUpload(User $user)
 {
     if ($user->fil) {
         $user->preUpload();
         $user->upload();
     }
 }
 /**
  * Renvoit le fichier pour une pièce justificative 
  * donnée et un utilisateur donné.
  *
  * @param integer $type_file de pièce justificative
  * @param User $user instance d'un "User" qui possède le fichier que l'on souhaite télécharger
  * @return Response renvoit la réponse HTTP.
  */
 private function download($type_file, User $user)
 {
     if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
         throw $this->createAccessDeniedException();
     }
     // ensure the type file is in the accepted range
     if (!preg_match('/^[1-6]$/', $type_file)) {
         throw $this->createAccessDeniedException();
     }
     $paths = array(User::TYPE_DOMICILE => $user->getAbsolutePathDomicile(), User::TYPE_PRESTATIONS => $user->getAbsolutePathPrestations(), User::TYPE_SALAIRE1 => $user->getAbsolutePathSalaire1(), User::TYPE_SALAIRE2 => $user->getAbsolutePathSalaire2(), User::TYPE_SALAIRE3 => $user->getAbsolutePathSalaire3(), User::TYPE_IMPOTS => $user->getAbsolutePathImpot());
     $ext = strtolower(pathinfo($paths[$type_file], PATHINFO_EXTENSION));
     $content_types = array('pdf' => 'application/pdf', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png');
     // check the extension
     if (!array_key_exists($ext, $content_types)) {
         throw $this->createAccessDeniedException();
     }
     $new_filenames = array(User::TYPE_DOMICILE => "justif_domicile." . $ext, User::TYPE_PRESTATIONS => "justif_prestations." . $ext, User::TYPE_SALAIRE1 => "justif_salaire_1." . $ext, User::TYPE_SALAIRE2 => "justif_salaire_2." . $ext, User::TYPE_SALAIRE3 => "justif_salaire_3." . $ext, User::TYPE_IMPOTS => "justif_impots." . $ext);
     // build the HTTP response
     $response = new Response();
     $response->headers->set('Cache-Control', 'no-cache');
     $response->headers->set('Content-Type', $content_types[$ext]);
     $response->headers->set('Content-Length', filesize($paths[$type_file]));
     $response->headers->set('Content-Disposition', 'inline; filename="' . $new_filenames[$type_file] . '"');
     $response->setContent(file_get_contents($paths[$type_file]));
     return $response;
 }
Esempio n. 8
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $user = new User();
     $user->setUsername('admin');
     $user->setEmail('*****@*****.**');
     $user->setEnabled(true);
     $user->setRoles(array('ROLE_SUPER_ADMIN'));
     $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
     $user->setPassword($encoder->encodePassword('admin', $user->getSalt()));
     $manager->persist($user);
     $manager->flush();
     $this->addReference('user1', $user);
     $user = new User();
     $user->setUsername('o.quiroz');
     $user->setEmail('*****@*****.**');
     $user->setEnabled(true);
     $user->setRoles(array('ROLE_SUPER_ADMIN'));
     $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
     $user->setPassword($encoder->encodePassword('o.quiroz', $user->getSalt()));
     $manager->persist($user);
     $manager->flush();
     $this->addReference('user2', $user);
     $user = new User();
     $user->setUsername('n.ramirez');
     $user->setEmail('*****@*****.**');
     $user->setEnabled(true);
     $user->setRoles(array('ROLE_SUPER_ADMIN'));
     $encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
     $user->setPassword($encoder->encodePassword('o.quiroz', $user->getSalt()));
     $manager->persist($user);
     $manager->flush();
     $this->addReference('user3', $user);
 }
 public function testLoginNewUser()
 {
     $client = static::createClient();
     $kernel = static::createKernel();
     $kernel->boot();
     $em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
     $fonction = $em->getRepository('IuchBundle:Fonction')->findOneByNom('testFonction');
     $service = $em->getRepository('IuchBundle:Service')->findOneByNom('testService');
     // On Créé un nouvel utilisateur
     $user = new User();
     $user->setUsername('TestUser');
     $user->setPlainPassword('081187');
     $user->setFonction($fonction);
     $user->setService($service);
     $em->persist($user);
     $em->flush();
     $crawler = $client->request('GET', '/login');
     $form = $crawler->selectButton('_submit')->form();
     // set some values
     $form['_username'] = '******';
     $form['_password'] = '******';
     // submit the form
     $crawler = $client->submit($form);
     $this->assertTrue($client->getResponse()->isRedirect('/logout/change-password'));
     // On kill le nouvel utilisateur
     $em->remove($user);
     $em->flush();
 }
Esempio n. 10
0
 /**
  * Generates a Customer with his addresses.
  *
  * @param ObjectManager $manager
  * @param int $i Random number to avoid username collision
  *
  * @return Customer
  */
 protected function generateCustomer(ObjectManager $manager, $i)
 {
     $faker = $this->getFaker();
     $firstName = $faker->firstName();
     $lastName = $faker->lastName();
     $email = $faker->email();
     $username = $faker->userName();
     if (0 === $i % 50 && $this->hasReference('customer-johndoe')) {
         return $this->getReference('customer-johndoe');
     }
     // Customer
     $customer = new Customer();
     $customer->setTitle(array_rand(array(BaseCustomer::TITLE_MLLE, BaseCustomer::TITLE_MME, BaseCustomer::TITLE_MR)));
     $customer->setFirstname($firstName);
     $customer->setLastname($lastName);
     $customer->setEmail($email);
     $customer->setBirthDate($faker->datetime());
     $customer->getBirthPlace($faker->city());
     $customer->setPhoneNumber($faker->phoneNumber());
     $customer->setMobileNumber($faker->phoneNumber());
     $customer->setFaxNumber($faker->phoneNumber());
     $customer->setLocale('fr');
     $customer->setIsFake(true);
     // Customer billing address
     $customerBillingAddress = new Address();
     $customerBillingAddress->setType(BaseAddress::TYPE_BILLING);
     $customerBillingAddress->setCustomer($customer);
     $customerBillingAddress->setCurrent(true);
     $customerBillingAddress->setName('My billing address');
     $customerBillingAddress->setFirstname($customer->getFirstname());
     $customerBillingAddress->setLastname($customer->getLastname());
     $customerBillingAddress->setAddress1($faker->address());
     $customerBillingAddress->setPostcode($faker->postcode());
     $customerBillingAddress->setCity($faker->city());
     $customerBillingAddress->setCountryCode(0 === $i % 50 ? 'FR' : $faker->countryCode());
     $customerBillingAddress->setPhone($faker->phoneNumber());
     // Customer contact address
     $customerContactAddress = new Address();
     $customerContactAddress->setType(BaseAddress::TYPE_CONTACT);
     $customerContactAddress->setCustomer($customer);
     $customerContactAddress->setCurrent(true);
     $customerContactAddress->setName('My contact address');
     $customerContactAddress->setFirstname($customer->getFirstname());
     $customerContactAddress->setLastname($customer->getLastname());
     $customerContactAddress->setAddress1($faker->address());
     $customerContactAddress->setPostcode($faker->postcode());
     $customerContactAddress->setCity($faker->city());
     $customerContactAddress->setCountryCode(0 === $i % 50 ? 'FR' : $faker->countryCode());
     $customerContactAddress->setPhone($customer->getPhoneNumber());
     // Customer delivery address
     $customerDeliveryAddress = new Address();
     $customerDeliveryAddress->setType(BaseAddress::TYPE_DELIVERY);
     $customerDeliveryAddress->setCustomer($customer);
     $customerDeliveryAddress->setCurrent(true);
     $customerDeliveryAddress->setName('My delivery address');
     $customerDeliveryAddress->setFirstname($customer->getFirstname());
     $customerDeliveryAddress->setLastname($customer->getLastname());
     $customerDeliveryAddress->setAddress1($faker->address());
     $customerDeliveryAddress->setPostcode($faker->postcode());
     $customerDeliveryAddress->setCity($faker->city());
     $customerDeliveryAddress->setCountryCode(0 === $i % 50 ? 'FR' : $faker->countryCode());
     $customerDeliveryAddress->setPhone($faker->phoneNumber());
     $customer->addAddress($customerBillingAddress);
     $customer->addAddress($customerContactAddress);
     $customer->addAddress($customerDeliveryAddress);
     // User
     if (0 === $i % 10) {
         $user = $this->getReference('user-johndoe');
         $this->setReference('customer-johndoe', $customer);
     } else {
         /** @var \Sonata\UserBundle\Model\User $user */
         $user = new User();
         $user->setUsername($i . '-' . $username);
         $user->setUsernameCanonical($i . '-' . $username);
         $user->setEmail($i . '_' . $email);
         $user->setEmailCanonical($email);
         $user->setPlainPassword('customer');
     }
     $customer->setUser($user);
     $manager->persist($customerBillingAddress);
     $manager->persist($customerContactAddress);
     $manager->persist($customerDeliveryAddress);
     $manager->persist($user);
     $manager->persist($customer);
     return $customer;
 }
 /**
  * @param $user
  * @param $nbChildrenVoyageInscrits
  * @return array
  */
 private function getFiles(User $user, $nbChildrenVoyageInscrits)
 {
     $filesArray = array();
     $filesArray[User::TYPE_PRESTATIONS] = array('libelle_justif' => 'Justificatif de CAF', 'exists' => is_file($user->getAbsolutePathPrestations()));
     $filesArray[User::TYPE_DOMICILE] = array('libelle_justif' => 'Justificatif de domicile', 'exists' => is_file($user->getAbsolutePathDomicile()));
     $filesArray[User::TYPE_SALAIRE1] = array('libelle_justif' => 'Justificatif de salaire 1', 'exists' => is_file($user->getAbsolutePathSalaire1()));
     $filesArray[User::TYPE_SALAIRE2] = array('libelle_justif' => 'Justificatif de salaire 2', 'exists' => is_file($user->getAbsolutePathSalaire2()));
     $filesArray[User::TYPE_SALAIRE3] = array('libelle_justif' => 'Justificatif de salaire 3', 'exists' => is_file($user->getAbsolutePathSalaire3()));
     if ($nbChildrenVoyageInscrits) {
         $filesArray[User::TYPE_IMPOTS] = array('libelle_justif' => "Justificatif avis d'imposition", 'exists' => is_file($user->getAbsolutePathImpot()));
     }
     return $filesArray;
 }
Esempio n. 12
0
 public function load(ObjectManager $manager)
 {
     $admin = new User();
     $admin->setCreatedAt(new \DateTime());
     $admin->setUpdatedAt(new \DateTime());
     $admin->setUsername('admin');
     $admin->setUsernameCanonical('admin');
     $admin->setEmail('*****@*****.**');
     $admin->setEmailCanonical('*****@*****.**');
     $admin->setEnabled(1);
     $admin->setPlainPassword('admin');
     $admin->setSuperAdmin(true);
     //$admin->addRole(static::ROLE_SUPER_ADMIN);
     $manager->persist($admin);
     $manager->flush();
     $this->addReference('admin', $admin);
 }
Esempio n. 13
0
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $user = new User();
        $user->setUsername('svid');
        $user->setEmail('*****@*****.**');
        $encoder = $this->container->get('security.password_encoder');
        $password = $encoder->encodePassword($user, 'svid');
        $user->setPassword($password);
        $manager->persist($user);
        $tagManager = $this->container->get('fpn_tag.tag_manager');
        $rootCategory = new Category();
        $rootCategory->setTitle('Главная');
        $webCategory = new Category();
        $webCategory->setTitle('Web-разработка');
        $webCategory->setParent($rootCategory);
        $manager->persist($rootCategory);
        $manager->persist($webCategory);
        $posts = [];
        $p1 = new Post();
        $p1->setTitle('Пробный тестовый пост');
        $p1->setPreviewText('В этом разделе мы будем ссылаться на файлы конфигурации служб, как на некоторые ресурсы.' . ' Это подчёркивает тот факт, что, хотя большинство ресурсов конфигурации будут представлены в виде файлов' . ' (например, YAML, XML, PHP), Symfony2 настолько гибок, что конфигурация может быть загружена' . ' практически отовсюду (например, из базы данных или даже через внешний веб-сервис).');
        $p1->setPreviewImg('symfony.png');
        $p1->setBody('При инициализации Symfony2 он создаёт контейнер служб, используя конфигурацию приложения (по умолчанию app/config/config.yml). ' . 'Файл, который будет загружен, определяется методом AppKernel::registerContainerConfiguration(), который загружает файл, ' . 'относящийся к конкретному окружению (например, config_dev.yml для dev или же config_prod.yml для prod). ' . 'Экземпляр объекта Acme\\HelloBundle\\Mailer теперь можно получить через контейнер служб. ' . 'контроллере Symfony2 при помощи вспомогательного метода get():  ' . 'Когда запрашивается служба my_mailer, контейнер создаёт её объект и возвращает её. ' . 'Это ещё одно преимущество от использования контейнера служб.  ' . 'А именно, служба не создаётся вплоть до того момента, когда она будет нужна вам.');
        $p1->setDescription('Проба пера');
        $p1->setKeywords('тест, symfony2');
        $symfonyTag = $tagManager->loadOrCreateTag('symfony2');
        $testTag = $tagManager->loadOrCreateTag('тест');
        $tagManager->addTag($symfonyTag, $p1);
        $tagManager->addTag($testTag, $p1);
        $posts[] = $p1;
        $p2 = new Post();
        $p2->setTitle('Объекты в PHP 7');
        $p2->setPreviewText('На сегодняшний день разработчики PHP ведут ' . 'работу над API уровня С. И в этом посте я буду по большей части рассказывать ' . 'о внутренней разработке PHP, хотя если по ходу повествования встретится что-то ' . 'интересное с точки зрения пользовательского уровня, то я буду делать отступление и объяснять.');
        $p2->setPreviewImg('symfony.png');
        $p2->setBody('Изменения в объектах по сравнению с PHP 5

Чтобы полностью вникнуть в тему объектов в PHP, рекомендую сначала ознакомиться с постом Подробно об объектах и классах в PHP.

Итак, что же изменилось в седьмой версии по сравнению с пятой?

    На пользовательском уровне почти ничего не изменилось. Иными словами, в PHP 7 объекты остались такими же, как и в PHP 5. Не было сделано каких-то глубоких изменений, ничего такого, что вы могли бы заметить в своей повседневной работе. Объекты ведут себя точно так же. Почему ничего не было изменено? Мы считаем, что наша объектная модель является зрелой, она очень активно используется, и мы не видим нужды вносить смуту в новых версиях PHP.
    Но всё же было несколько низкоуровневых улучшений. Изменения небольшие, тем не менее они требуют патчей расширений. В принципе, в PHP 7 внутренние объекты стали гораздо выразительнее, яснее и логичнее, чем в PHP 5. Самое главное нововведение связано с основным изменением в PHP 7: обновлением zval и управлением сборкой мусора. Но в этом посте мы не будем рассматривать последний, потому что тема поста — объекты. Однако нужно помнить, что сама природа новых zval и механизма сборки мусора оказывает влияние на внутреннее управление объектами.


Структура объекта и управление памятью

В первую очередь можете попрощаться с zend_object_value, от этой структуры в PHP 7 отказались.

Давайте посмотрим пример определения объекта zend_object:
<pre><code class="C++">
/* in PHP 5 */
typedef struct _zend_object {
    zend_class_entry *ce;
    HashTable *properties;
    zval **properties_table;
    HashTable *guards;
} zend_object;

/* in PHP 7 */
struct _zend_object {
    zend_refcounted_h gc;
    uint32_t          handle;
    zend_class_entry *ce;
    const zend_object_handlers *handlers;
    HashTable        *properties;
    zval              properties_table[1]; /* C struct hack */
};
</pre></code>

Как видите, есть небольшие отличия от PHP 5.

Во-первых, здесь содержится заголовок zend_refcounted_h, являющийся частью нового zval и механизма сборки мусора.

Во-вторых, теперь объект содержит свой handle, в то время как в PHP 5 эту задачу выполнял zend_object_store. А в PHP 7 у объектного хранилища (object store) уже гораздо меньше обязанностей.

В-третьих, для замещения properties_table вектора zval используется структурный хак на языке С, он пригодится при создании кастомных объектов.');
        $p2->setKeywords('Веб-разработка, PHP');
        $p2->setDescription('На сегодняшний день разработчики PHP ведут работу над API уровня С. И в этом посте я буду по большей части рассказывать о внутренней разработке PHP, хотя если...');
        $phpTag = $tagManager->loadOrCreateTag('php');
        $tagManager->addTag($phpTag, $p2);
        $posts[] = $p2;
        $p3 = new Post();
        $p3->setTitle('DoctrineFixturesBundle ');
        $p3->setPreviewText('Fixtures are used to load a controlled set of data into a database. This data can be used for testing or could be the initial data required for the application to run smoothly. Symfony has no built in way to manage fixtures but Doctrine2 has a library to help you write fixtures for the Doctrine ORM or ODM.
Setup and Configuration¶

Doctrine fixtures for Symfony are maintained in the DoctrineFixturesBundle, which uses external Doctrine Data Fixtures library.

Follow these steps to install the bundle in your Symfony applications:
Step 1: Download the Bundle¶

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:');
        $p3->setPreviewImg('symfony.png');
        $p3->setBody('
Setup and Configuration¶

Doctrine fixtures for Symfony are maintained in the DoctrineFixturesBundle, which uses external Doctrine Data Fixtures library.

Follow these steps to install the bundle in your Symfony applications:
Step 1: Download the Bundle¶

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:
<pre><code class="php">
composer require --dev doctrine/doctrine-fixtures-bundle
</pre></code>

This command requires you to have Composer installed globally, as explained in the installation chapter of the Composer documentation.
Step 2: Enable the Bundle¶

Then, add the following line in the app/AppKernel.php file to enable this bundle only for the dev and test environments:

<pre><code class="php">
// app/AppKernel.php
// ...

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        // ...
        if (in_array($this->getEnvironment(), array(\'dev\', \'test\'))) {
            $bundles[] = new Doctrine\\Bundle\\FixturesBundle\\DoctrineFixturesBundle();
        }

        return $bundles
    }

    // ...
}
</pre></code>
Writing Simple Fixtures¶

Doctrine2 fixtures are PHP classes where you can create objects and persist them to the database. Like all classes in Symfony, fixtures should live inside one of your application bundles.

For a bundle located at src/AppBundle, the fixture classes should live inside src/AppBundle/DataFixtures/ORM or src/AppBundle/DataFixtures/MongoDB respectively for the ORM and ODM. This tutorial assumes that you are using the ORM, but fixtures can be added just as easily if you\'re using the ODM.

Imagine that you have a User class, and you\'d like to load one User entry:');
        $p3->setKeywords('symfony2, symfony, project, framework, php, php5, open-source, components, symphony, symfony framework, symfony tutorial');
        $p3->setDescription('Fixtures are used to load a controlled set of data into a database.');
        $symfonyOfTag = $tagManager->loadOrCreateTag('symfony documentation');
        $tagManager->addTag($symfonyTag, $p3);
        $tagManager->addTag($symfonyOfTag, $p3);
        $posts[] = $p3;
        foreach ($posts as $post) {
            $post->setAuthor($user);
            $post->setCategory($webCategory);
            $manager->persist($post);
        }
        $post = null;
        $manager->flush();
        foreach ($posts as $post) {
            $tagManager->saveTagging($post);
        }
    }
Esempio n. 14
0
 /**
  * Is the given User the author of this Post?
  *
  * @param User $user
  *
  * @return bool
  */
 public function isAuthor(User $user = null)
 {
     return $user->getEmail() == $this->getAuthorEmail();
 }
 /**
  * Import the row into the user object
  *
  * @param array - associative array containing all columns for one row
  * @param User - the user that will be updated and for whom the files will be imported
  * @return bool
  */
 private function importRow($row, User $user)
 {
     $success = true;
     // replace every item of an associative array that contain "\\N" (NULL) by "".
     foreach ($row as &$d) {
         if ($d == "\\N") {
             $d = "";
         }
     }
     // import files in the appropriate directory and in the database
     $subdirs_to_import = array(self::MH_ADDRESS_EVIDENCE => 'address_evidence/' . $row[self::MH_ID], self::MH_CAF_EVIDENCE => 'caf_evidence/' . $row[self::MH_ID], self::MH_SALARY_EVIDENCE => 'salary_evidence/' . $row[self::MH_ID], self::MH_SALARY_EVIDENCE_2 => 'salary_evidence_2/' . $row[self::MH_ID], self::MH_SALARY_EVIDENCE_3 => 'salary_evidence_3/' . $row[self::MH_ID]);
     $filenames_to_import = array(self::MH_ADDRESS_EVIDENCE => $row[self::MH_ADDRESS_EVIDENCE], self::MH_CAF_EVIDENCE => $row[self::MH_CAF_EVIDENCE], self::MH_SALARY_EVIDENCE => $row[self::MH_SALARY_EVIDENCE], self::MH_SALARY_EVIDENCE_2 => $row[self::MH_SALARY_EVIDENCE_2], self::MH_SALARY_EVIDENCE_3 => $row[self::MH_SALARY_EVIDENCE_3]);
     $filenames_currently_in_db = array(self::MH_ADDRESS_EVIDENCE => $user->getPathDomicile(), self::MH_CAF_EVIDENCE => $user->getPathPrestations(), self::MH_SALARY_EVIDENCE => $user->getPathSalaire1(), self::MH_SALARY_EVIDENCE_2 => $user->getPathSalaire2(), self::MH_SALARY_EVIDENCE_3 => $user->getPathSalaire3());
     $user_method_set_paths = array(self::MH_ADDRESS_EVIDENCE => 'setPathDomicile', self::MH_CAF_EVIDENCE => 'setPathPrestations', self::MH_SALARY_EVIDENCE => 'setPathSalaire1', self::MH_SALARY_EVIDENCE_2 => 'setPathSalaire2', self::MH_SALARY_EVIDENCE_3 => 'setPathSalaire3');
     foreach ($user_method_set_paths as $key => $user_method_set_path) {
         $newFilename = $this->copyFile(array('subdir_to_import' => $subdirs_to_import[$key], 'filename_to_import' => $filenames_to_import[$key], 'filename_currently_in_db' => $filenames_currently_in_db[$key]));
         // on success, update the filename in the User instance with the appropriate setter method
         if (!empty($newFilename)) {
             $user->{$user_method_set_path}($newFilename);
         }
     }
     return $success;
 }
Esempio n. 16
0
 /**
  * 
  * @param UserDrawGeometries $usergeometries
  * @param array $req_params
  * @param User $user
  * @param string $icon_path
  * @return UserDrawGeometries
  */
 private function moveuploadedMarkerIcon(UserDrawGeometries $usergeometries, array $req_params, User $user, $icon_path)
 {
     if ($req_params['upload_marker_icon']) {
         if (!file_exists($icon_path . "/" . $user->getId())) {
             mkdir($icon_path . "/" . $user->getId(), 0755, true);
         }
         move_uploaded_file($req_params['upload_marker_icon']->getPathname(), $icon_path . "/" . $user->getId() . "/" . $req_params['upload_marker_icon']->getClientOriginalName());
         $selected_marker = $user->getId() . "/" . $req_params['upload_sldfile']->getClientOriginalName();
         $usergeometries->setMarkerIcon($selected_marker);
     } else {
         if (isset($req_params['selected_marker'])) {
             $usergeometries->setMarkerIcon($req_params['selected_marker']);
         }
     }
     return $usergeometries;
 }
Esempio n. 17
0
 public function load(ObjectManager $em)
 {
     $factory = $this->getSecurityManager();
     $faker = $this->getFaker();
     // user romain
     $user1 = new User();
     $user1->addGroup($em->merge($this->getReference('group-admin')));
     $user1->setFirstname('Romain');
     $user1->setLastname('Coeur');
     $user1->setFirstname('Romain');
     $user1->setLastname('Coeur');
     $user1->setEmail('*****@*****.**');
     $user1->setUsername('romain');
     $user1->setEnabled(true);
     $user1->setSuperAdmin(true);
     $user1->setLocked(false);
     $this->addReference('user-romain', $user1);
     $encoder = $factory->getEncoder($user1);
     $encodedPassword = $encoder->encodePassword('Rogvog4', $user1->getSalt());
     $user1->setPassword($encodedPassword);
     $em->persist($user1);
     // user admin
     $user2 = new User();
     $user2->addGroup($em->merge($this->getReference('group-admin')));
     $user2->setEmail('*****@*****.**');
     $user2->setUsername('admin');
     $user2->setFirstname('Steeve');
     $user2->setLastname('Jobs');
     $user2->setEnabled(true);
     $user2->setSuperAdmin(true);
     $user2->setLocked(false);
     $this->addReference('user-admin', $user2);
     $encoder = $factory->getEncoder($user2);
     $encodedPassword = $encoder->encodePassword('password', $user2->getSalt());
     $user2->setPassword($encodedPassword);
     $em->persist($user2);
     // user user
     $user3 = new User();
     $user3->addGroup($em->merge($this->getReference('group-user')));
     $user3->setEmail('*****@*****.**');
     $user3->setUsername('user');
     $user3->setFirstname('User');
     $user3->setLastname('Jobs');
     $user3->setEnabled(true);
     $user3->setSuperAdmin(true);
     $user3->setLocked(false);
     $this->addReference('user-user', $user3);
     $encoder = $factory->getEncoder($user3);
     $encodedPassword = $encoder->encodePassword('password', $user3->getSalt());
     $user3->setPassword($encodedPassword);
     $em->persist($user3);
     // user tom
     $user4 = new User();
     $user4->addGroup($em->merge($this->getReference('group-admin')));
     $user4->setFirstname('Tom');
     $user4->setLastname('Nana');
     $user4->setEmail('*****@*****.**');
     $user4->setEnabled(true);
     $user4->setUsername('tom');
     $user4->setSuperAdmin(false);
     $user4->setLocked(false);
     $this->addReference('user-tom', $user4);
     $encoder = $factory->getEncoder($user4);
     $encodedPassword = $encoder->encodePassword('azerty', $user4->getSalt());
     $user4->setPassword($encodedPassword);
     $em->persist($user4);
     foreach (range(1, 43) as $id) {
         $user = new User();
         $user->addGroup($em->merge($this->getReference('group-user')));
         $user->setFirstname($faker->firstName);
         $user->setLastname($faker->lastName);
         $user->setEmail($faker->safeEmail);
         $user->setPhone($faker->phoneNumber);
         $user->setUsername($faker->userName);
         $user->setPassword('');
         $user->setEnabled(true);
         $user->setLocked(false);
         $this->addReference('user-' . $id, $user);
         $em->persist($user);
     }
     $em->flush();
 }
Esempio n. 18
0
 public function __construct()
 {
     parent::__construct();
 }
Esempio n. 19
0
 public function __construct()
 {
     parent::__construct();
     $this->schoolClasses = new \Doctrine\Common\Collections\ArrayCollection();
 }
Esempio n. 20
0
 /**
  * Create token
  * 
  * @param \Application\Sonata\UserBundle\Entity\User $user
  * 
  * @param string $palinPassword
  * 
  * @return string
  */
 public function createBaseWsse(User $user, $palinPassword, $truePassword = true)
 {
     $username = $user->getUsername();
     $password = $palinPassword;
     $created = date('c');
     $nonce = substr(md5(uniqid('nonce_', true)), 0, 16);
     $nonceHigh = base64_encode($nonce);
     $factory = $this->get('security.encoder_factory');
     $encoder = $factory->getEncoder($user);
     if ($truePassword) {
         // encode password
         $password = $encoder->encodePassword($password, $user->getSalt());
     }
     $passwordDigest = base64_encode(sha1($nonce . $created . $password, true));
     $token = "UsernameToken Username=\"{$username}\", " . "PasswordDigest=\"{$passwordDigest}\", Nonce=\"{$nonceHigh}\"," . " Created=\"{$created}\"";
     return $token;
 }
Esempio n. 21
0
 /**
  * @ParamConverter("user", class="ApplicationSonataUserBundle:User")
  * Show a post by Author
  * 
  * @param int Application\Sonata\UserBundle\Entity\User $user
  * 
  * @throws NotFoundHttpException
  * @return array
  * 
  */
 public function showByAuthorAction(User $user)
 {
     $latestPosts = $this->getDoctrine()->getRepository('BeluhaBlogBundle:Post')->findLatest(5);
     $posts = $user->getPosts();
     return $this->render('BeluhaBlogBundle:Post:index.html.twig', ['posts' => $posts, 'latestPosts' => $latestPosts]);
 }
Esempio n. 22
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $config = new Config();
     $config->setName('Footer copyright');
     $config->setValue('© 2015 Bellon Company');
     $config->setKeyValue('FOOTER_COPYRIGHT');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Footer описание');
     $config->setValue('By Alexey');
     $config->setKeyValue('FOOTER_DESCRIPTION');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Адресс');
     $config->setValue('ул. Чапаева 3 офис 303	Минск Беларусь');
     $config->setKeyValue('ADDRESS');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Телефон');
     $config->setValue('(123) 456-7890');
     $config->setKeyValue('PHONE_1');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Телефон');
     $config->setValue('(123) 456-7890');
     $config->setKeyValue('PHONE_2');
     $manager->persist($config);
     $config = new Config();
     $config->setName('email');
     $config->setValue('*****@*****.**');
     $config->setKeyValue('EMAIL');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Куда будет отправлено сообщение');
     $config->setValue('*****@*****.**');
     $config->setKeyValue('EMAIL_TO');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Страница о нас');
     $config->setValue('');
     $config->setKeyValue('ABOUT');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-title на главной');
     $config->setValue('Meta-title на главной');
     $config->setKeyValue('META_TITLE_MAIN');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-description на главной');
     $config->setValue('Meta-description на главной');
     $config->setKeyValue('META_DESCRIPTION_MAIN');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-keywords на главной');
     $config->setValue('Meta-keywords на главной');
     $config->setKeyValue('META_KEYWORDS_MAIN');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-title на О нас');
     $config->setValue('Meta-title на О нас');
     $config->setKeyValue('META_TITLE_ABOUT');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-description на О нас');
     $config->setValue('Meta-description на О нас');
     $config->setKeyValue('META_DESCRIPTION_ABOUT');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-keywords на О нас');
     $config->setValue('Meta-keywords на О нас');
     $config->setKeyValue('META_KEYWORDS_ABOUT');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-title на Контактах');
     $config->setValue('Meta-title на Контактах');
     $config->setKeyValue('META_TITLE_CONTACTS');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-description на Контактах');
     $config->setValue('Meta-description на Контактах');
     $config->setKeyValue('META_DESCRIPTION_CONTACTS');
     $manager->persist($config);
     $config = new Config();
     $config->setName('Meta-keywords на Контактах');
     $config->setValue('Meta-keywords на Контактах');
     $config->setKeyValue('META_KEYWORDS_CONTACTS');
     $manager->persist($config);
     $User = new User();
     $User->setEmail("*****@*****.**");
     $User->setPlainPassword("admin");
     $User->setSuperAdmin(true);
     $User->setUsername("admin");
     $User->setEnabled(true);
     $manager->persist($User);
     $manager->flush();
 }
Esempio n. 23
0
 private function onCreateNewUser($nameArray)
 {
     $user = new User();
     $user->setCreatedAt(new \DateTime());
     $user->setUsername($nameArray['nickname']);
     $user->setFacebookName($nameArray['realname']);
     $user->setEmail($nameArray['email']);
     $user->setPlainPassword($nameArray['email']);
     $user->setFacebookData($nameArray['avatar']);
     $user->setFacebookUid($nameArray['facebook_id']);
     $em = $this->doctrine->getManager();
     $em->persist($user);
     return $em->flush();
 }
 /**
  * {@inheritDoc}
  */
 public function removeGroup(\FOS\UserBundle\Model\GroupInterface $group)
 {
     $this->__initializer__ && $this->__initializer__->__invoke($this, 'removeGroup', array($group));
     return parent::removeGroup($group);
 }