/**
  * Change the property on the given node.
  *
  * @param NodeData $node
  * @return void
  */
 public function execute(NodeData $node)
 {
     foreach ($node->getNodeType()->getProperties() as $propertyName => $propertyConfiguration) {
         if (isset($propertyConfiguration['type']) && in_array(trim($propertyConfiguration['type']), $this->getHandledObjectTypes())) {
             if (!isset($nodeProperties)) {
                 $nodeRecordQuery = $this->entityManager->getConnection()->prepare('SELECT properties FROM typo3_typo3cr_domain_model_nodedata WHERE persistence_object_identifier=?');
                 $nodeRecordQuery->execute([$this->persistenceManager->getIdentifierByObject($node)]);
                 $nodeRecord = $nodeRecordQuery->fetch(\PDO::FETCH_ASSOC);
                 $nodeProperties = unserialize($nodeRecord['properties']);
             }
             if (!isset($nodeProperties[$propertyName]) || !is_object($nodeProperties[$propertyName])) {
                 continue;
             }
             /** @var Asset $assetObject */
             $assetObject = $nodeProperties[$propertyName];
             $nodeProperties[$propertyName] = null;
             $stream = $assetObject->getResource()->getStream();
             if ($stream === false) {
                 continue;
             }
             fclose($stream);
             $objectType = TypeHandling::getTypeForValue($assetObject);
             $objectIdentifier = ObjectAccess::getProperty($assetObject, 'Persistence_Object_Identifier', true);
             $nodeProperties[$propertyName] = array('__flow_object_type' => $objectType, '__identifier' => $objectIdentifier);
         }
     }
     if (isset($nodeProperties)) {
         $nodeUpdateQuery = $this->entityManager->getConnection()->prepare('UPDATE typo3_typo3cr_domain_model_nodedata SET properties=? WHERE persistence_object_identifier=?');
         $nodeUpdateQuery->execute([serialize($nodeProperties), $this->persistenceManager->getIdentifierByObject($node)]);
     }
 }
 public function createTable($name)
 {
     // remove table
     $pdo = $this->pdo->query('DROP TABLE IF EXISTS `' . $name . '`;');
     $pdo->execute();
     // create table
     $newSchema = new \Doctrine\DBAL\Schema\Schema();
     $newTable = $newSchema->createTable($name);
     $newTable->addColumn('container_id', 'integer');
     $newTable->addColumn('context_id', 'integer');
     $newTable->addColumn('module_id', 'integer');
     $newTable->addColumn('resource_id', 'integer')->setNotnull(false);
     $newTable->addColumn('by_resource_id', 'integer')->setNotnull(false);
     $newTable->addColumn('sequence', 'integer')->setNotnull(false);
     $newTable->addColumn('deleted', 'datetime')->setNotnull(false);
     $newTable->addColumn('display', 'boolean')->setNotnull(true);
     $newTable->addColumn('expire_temporary_date', 'datetime')->setNotnull(false);
     $newTable->addColumn('culture', 'string')->setLength(11);
     foreach ($this->eavColumns->getColumns() as $column) {
         if ($this->getTypeToColumn($column['column'])) {
             $newTable->addColumn($column['identifier'], $this->getTypeToColumn($column['column']))->setNotnull(false);
             $columnsToFill[] = $column['identifier'];
         }
     }
     $newTable->addForeignKeyConstraint($this->objectManager->getClassMetadata('BigfishEavBundle:Container')->getTablename(), array('container_id'), array('container_id'), array('onDelete' => 'CASCADE'));
     $newTable->addForeignKeyConstraint($this->objectManager->getClassMetadata('BigfishEavBundle:Module')->getTablename(), array('module_id'), array('module_id'), array('onDelete' => 'CASCADE'));
     $newTable->addForeignKeyConstraint($this->objectManager->getClassMetadata('BigfishContextBundle:Context')->getTablename(), array('context_id'), array('context_id'), array('onDelete' => 'CASCADE'));
     $newTable->addForeignKeyConstraint($this->objectManager->getClassMetadata('BigfishResourceBundle:Resource')->getTablename(), array('resource_id'), array('resource_id'), array('onDelete' => 'CASCADE'));
     $newTable->addForeignKeyConstraint($this->objectManager->getClassMetadata('BigfishResourceBundle:Resource')->getTablename(), array('by_resource_id'), array('resource_id'), array('onDelete' => 'CASCADE'));
     foreach ($newSchema->toSql($this->objectManager->getConnection()->getDatabasePlatform()) as $l) {
         $pdo = $this->pdo->prepare($l);
         $pdo->execute();
     }
 }
 /**
  * @param DoctrineSqlFilter $sqlFilter
  * @param ClassMetadata $targetEntity Metadata object for the target entity to create the constraint for
  * @param string $targetTableAlias The target table alias used in the current query
  * @return string
  */
 public function getSql(DoctrineSqlFilter $sqlFilter, ClassMetadata $targetEntity, $targetTableAlias)
 {
     $quotedCollectionTitle = $this->entityManager->getConnection()->quote($this->collectionTitle);
     return $targetTableAlias . '.persistence_object_identifier IN (
         SELECT ' . $targetTableAlias . '_a.persistence_object_identifier
         FROM typo3_media_domain_model_asset AS ' . $targetTableAlias . '_a
         LEFT JOIN typo3_media_domain_model_assetcollection_assets_join ' . $targetTableAlias . '_acj ON ' . $targetTableAlias . '_a.persistence_object_identifier = ' . $targetTableAlias . '_acj.media_asset
         LEFT JOIN typo3_media_domain_model_assetcollection ' . $targetTableAlias . '_ac ON ' . $targetTableAlias . '_ac.persistence_object_identifier = ' . $targetTableAlias . '_acj.media_assetcollection
         WHERE ' . $targetTableAlias . '_ac.title = ' . $quotedCollectionTitle . ')';
 }
 /**
  * Load data fixtures with the passed EntityManager
  *
  * @param \Doctrine\Common\Persistence\ObjectManager $manager
  */
 public function load(ObjectManager $manager)
 {
     $query = $manager->createQuery('SELECT COUNT(f) FROM \\Acme\\Bundle\\AppBundle\\Entity\\Fabric f');
     if (0 === $query->getSingleScalarResult()) {
         $stmt = $manager->getConnection()->prepare($this->getFabricsSql());
         $stmt->execute();
     }
     $query = $manager->createQuery('SELECT COUNT(c) FROM \\Acme\\Bundle\\AppBundle\\Entity\\Color c');
     if (0 === $query->getSingleScalarResult()) {
         $stmt = $manager->getConnection()->prepare($this->getColorSql());
         $stmt->execute();
     }
 }
 /**
  * Runs garbage collection for the ResourcePointers and their associated physical files
  * 
  * @return void
  */
 public function collectResourcePointersCommand()
 {
     $connection = $this->entityManager->getConnection();
     $path = FLOW_PATH_DATA . "Persistent/Resources/";
     // Find and delete all orphaned ResourcePointers
     $stmt = $connection->executeQuery('SELECT `hash` ' . 'FROM `typo3_flow_resource_resourcepointer` AS `rp` ' . 'LEFT OUTER JOIN `typo3_flow_resource_resource` AS `r` ON `r`.`resourcepointer` = `rp`.`hash` ' . 'WHERE `r`.`persistence_object_identifier` IS NULL ');
     foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
         $hash = $row["hash"];
         $this->outputLine("Found orphaned ResourcePointer: %s", array($hash));
         // Remove ResoursePointer from database
         $result = $connection->executeUpdate('DELETE FROM `typo3_flow_resource_resourcepointer` ' . 'WHERE `hash` = "' . $hash . '"');
         if ($result) {
             $this->outputLine("...deleted entity");
         } else {
             $this->outputLine("...COULD NOT DELETE ENTITY!");
         }
         // Remove physical file
         if (file_exists($path . $hash)) {
             if (unlink($path . $hash)) {
                 $this->outputLine("...deleted physical file");
             } else {
                 $this->outputLine("...COULD NOT DELETE PHYSICAL FILE!");
             }
         } else {
             $this->outputLine("...physical file already deleted");
         }
     }
     // Find and delete all orphaned physical files
     $files = scandir($path);
     $files = array_filter($files, function ($elem) {
         return preg_match('/^[0-9a-f]+$/', $elem);
     });
     // Create temporary table in memory and fill it with physical file hashes
     $connection->executeUpdate('CREATE TEMPORARY TABLE `etg24_cleanup_command_garbage_files` (`hash` CHAR(40)) ENGINE=MEMORY');
     if (!empty($files)) {
         $connection->executeUpdate('INSERT INTO `etg24_cleanup_command_garbage_files` (`hash`) VALUES ("' . implode('"), ("', $files) . '")');
     }
     $stmt = $connection->executeQuery('SELECT `f`.`hash` ' . 'FROM `etg24_cleanup_command_garbage_files` AS `f` ' . 'LEFT OUTER JOIN `typo3_flow_resource_resourcepointer` AS `rp` USING(`hash`) ' . 'WHERE `rp`.`hash` IS NULL ');
     foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
         $hash = $row["hash"];
         $this->outputLine("Found orphaned physical file: %s", array($hash));
         // Remove physical file
         if (unlink($path . $hash)) {
             $this->outputLine("...deleted physical file");
         } else {
             $this->outputLine("...COULD NOT DELETE PHYSICAL FILE!");
         }
     }
 }
 /**
  * Derive maximum identifier length from doctrine DBAL
  *
  * @return integer
  */
 protected function getMaxIdentifierLength()
 {
     if ($this->tableNameLengthLimit === null) {
         $this->tableNameLengthLimit = $this->entityManager->getConnection()->getDatabasePlatform()->getMaxIdentifierLength();
     }
     return $this->tableNameLengthLimit;
 }
 public function load(ObjectManager $manager)
 {
     $filename = "src/ESN/AdministrationBundle/DataFixtures/SQL/University.sql";
     $sql = file_get_contents($filename);
     $manager->getConnection()->exec($sql);
     $manager->flush();
 }
 /**
  *
  * @param ObjectManager|EntityManager $manager            
  * @param
  *            $class
  * @return bool
  */
 public static function truncate(ObjectManager $manager, $class)
 {
     /**
      * @var $connection \Doctrine\DBAL\Connection
      */
     $connection = $manager->getConnection();
     /**
      * @var $cmd ClassMetadata
      */
     $cmd = $manager->getClassMetadata($class);
     $connection->beginTransaction();
     try {
         if ($connection->getDatabasePlatform()->getName() !== 'sqlite') {
             $connection->query('SET FOREIGN_KEY_CHECKS=0');
             $connection->executeUpdate($connection->getDatabasePlatform()->getTruncateTableSql($cmd->getTableName()));
             $connection->query('SET FOREIGN_KEY_CHECKS=1');
         } else {
             $connection->executeUpdate($connection->getDatabasePlatform()->getTruncateTableSql($cmd->getTableName()));
         }
         $connection->commit();
         return true;
     } catch (\Exception $e) {
         $connection->rollback();
         return false;
     }
 }
Beispiel #9
0
 public function load(ObjectManager $manager)
 {
     $conn = $manager->getConnection();
     $stmt = $conn->prepare('select id from lots');
     $stmt->execute();
     $lotIds = [];
     while ($lotId = $stmt->fetchColumn()) {
         $lotIds[] = (int) $lotId;
     }
     $stmt = $conn->prepare('select id from users');
     $stmt->execute();
     $usrIds = [];
     while ($usrId = $stmt->fetchColumn()) {
         $usrIds[] = (int) $usrId;
     }
     for ($i = 0, $l = count($lotIds) * count($usrIds); $i < $l; $i++) {
         $lot = $manager->getRepository('BankrotSiteBundle:Lot')->find($lotIds[array_rand($lotIds)]);
         if ($lot->getBeginDate()) {
             if (0 === rand(0, 2)) {
                 $lw = new LotWatch();
                 $lw->setOwner($manager->getRepository('BankrotSiteBundle:User')->find($usrIds[array_rand($usrIds)]));
                 $lw->setLot($lot);
                 $lw->setPrice(rand(0, 1000000));
                 $lw->setCutOffPrice(rand(10, 5000));
                 $lw->setDay(new \DateTime('@' . rand($lot->getBeginDate()->getTimestamp(), $lot->getEndDate()->getTimestamp())));
                 $manager->persist($lw);
             }
         }
     }
     $manager->flush();
 }
 public function load(ObjectManager $manager)
 {
     $data = (include __DIR__ . '/../fixtures/user/users.php');
     $encoder = $this->container->get('security.password_encoder');
     $userManager = $this->container->get('medievistes.user_manager');
     $connection = $manager->getConnection();
     if ($connection->getDatabasePlatform()->getName() === 'mysql') {
         $connection->exec("ALTER TABLE {$manager->getClassMetadata(User::class)->getTableName()} AUTO_INCREMENT = 1;");
     }
     foreach ($data as $userData) {
         $class = $userManager->getUserClass($userData['type']);
         $user = (new $class())->setId((int) $userData['id'])->setUsername($userData['username'])->setEmail($userData['email'])->setPlainPassword($userData['plain_password'])->setSalt(md5(uniqid(null, true)))->enable((bool) $userData['is_active'])->setCreatedAt(new \DateTime($userData['created_at']))->setUpdatedAt(new \DateTime($userData['updated_at']));
         if (!empty($userData['activation_link_id'])) {
             $user->setActivationLink($this->getReference("activation-link-{$userData['activation_link_id']}"));
         }
         foreach ($userData['roles'] as $role) {
             $user->addRole($role);
         }
         foreach ($userData['troops'] as $troop) {
             $association = (new Association())->setUser($user)->setTroop($this->getReference("troop-{$troop['troop_id']}"))->setRole($this->getReference("troop-role-{$troop['role_id']}"));
             $user->addTroopAssociation($association);
             $manager->persist($association);
         }
         $password = $encoder->encodePassword($user, $userData['plain_password']);
         $user->setPassword($password);
         $manager->persist($user);
         $manager->flush();
         $this->addReference("user-{$user->getId()}", $user);
     }
     $manager->clear($class);
     $manager->clear(Association::class);
 }
 public function load(ObjectManager $manager)
 {
     $filename = "src/BuddySystem/MainBundle/DataFixtures/SQL/sections.sql";
     $sql = file_get_contents($filename);
     $manager->getConnection()->exec($sql);
     $manager->flush();
 }
Beispiel #12
0
 /**
  * {@inheritDoc}
  */
 public function load(ObjectManager $manager)
 {
     $manager->getConnection()->executeQuery("SET foreign_key_checks = 0;");
     $pageEtat = new PageEtat();
     $pageEtat->setLibelle('brouillon');
     $manager->persist($pageEtat);
     $manager->flush();
     $pageEtat = new PageEtat();
     $pageEtat->setLibelle('A valider');
     $manager->persist($pageEtat);
     $manager->flush();
     $pageEtat = new PageEtat();
     $pageEtat->setLibelle('Validée');
     $manager->persist($pageEtat);
     $manager->flush();
     $manager->getConnection()->executeQuery("SET foreign_key_checks = 1;");
 }
 /**
  */
 public function alisInkKlosterImportCommand()
 {
     /** @var DataImportController $importer */
     $importer = new DataImportController($this->logger, $this->settings);
     /** @var \Doctrine\DBAL\Connection $sqlConnection */
     $sqlConnection = $this->entityManager->getConnection();
     $sql = 'SET unique_checks = 0';
     $sqlConnection->executeUpdate($sql);
     $sql = 'SET foreign_key_checks = 0';
     $sqlConnection->executeUpdate($sql);
     $importer->delAccessKlosterTabAction();
     $importer->importAccessInkKlosterDataAction();
     $importer->importKlosterAction();
     $sql = 'SET foreign_key_checks = 1';
     $sqlConnection->executeUpdate($sql);
     $time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
     $this->logger->log('Import completed in ' . $time . ' seconds.');
 }
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     /** @var \Doctrine\ORM\EntityManagerInterface $manager */
     $connection = $manager->getConnection();
     $date = (new \DateTime('-3 days'))->format('Y-m-d H:i:s');
     // we need to use bare sql
     // since the auth process is difficult to build when using the domain models
     $connection->exec("\nINSERT INTO SEN_Token (apiKey, tokenId) VALUES (PASSWORD(RAND()), 1);\nINSERT INTO SEN_User (credentials_username, credentials_password, profile_email, profile_realName, profile_registrationDate, profile_lastAction, profile_locked, profile_locale, tokenId)  VALUES ('Ma27', PASSWORD('test-password'), '*****@*****.**', '', '" . $date . "', '" . $date . "', 0, 'en', 1);");
 }
    /**
     * Initializes the DBAL connection which is currently bound to the Doctrine Entity Manager
     *
     * @return void
     */
    protected function initializeConnection()
    {
        if (!$this->entityManager instanceof EntityManager) {
            $this->outputLine('This command only supports database connections provided by the Doctrine ORM Entity Manager.
				However, the current entity manager is an instance of %s.', array(get_class($this->entityManager)));
            $this->quit(1);
        }
        $this->dbalConnection = $this->entityManager->getConnection();
    }
 /**
  * @param ObjectManager    $objectManager
  * @param LanguageManager  $languageManager
  * @param ModuleRepository $moduleRepository
  * @param FlatternTable    $flatternTable
  */
 public function __construct(ObjectManager $objectManager, LanguageManager $languageManager, ModuleRepository $moduleRepository, FlatternTable $flatternTable)
 {
     $this->objectManager = $objectManager;
     $this->pdo = $objectManager->getConnection();
     $this->languageManager = $languageManager;
     $this->moduleRepository = $moduleRepository;
     $this->flatternTable = $flatternTable;
     return $this;
 }
 public static function truncate(array $tables, ObjectManager $om)
 {
     $connection = $om->getConnection();
     $platform = $connection->getDatabasePlatform();
     $connection->query("SET foreign_key_checks = 0");
     foreach ($tables as $table) {
         $connection->executeUpdate($platform->getTruncateTableSQL($table));
     }
     $connection->query("SET foreign_key_checks = 1");
 }
 /**
  * @param $shortIdentifier
  * @return string
  * @throws \Exception
  */
 protected function getNodeIdentifierByShortIdentifier($shortIdentifier)
 {
     /** @var Connection $connection */
     $connection = $this->entityManager->getConnection();
     /** @var Statement $query */
     $query = $connection->prepare('SELECT identifier FROM typo3_typo3cr_domain_model_nodedata WHERE identifier LIKE :identifier');
     $query->execute([':identifier' => $shortIdentifier . '-%']);
     $rows = $query->fetchAll(\PDO::FETCH_COLUMN);
     // Assume we will never have duplicates
     if (!empty($rows)) {
         return current($rows);
     }
     throw new \Exception('Could not find full node identifier for short identifier "' . $shortIdentifier . '"');
 }
 /**
  * {@inheritDoc}
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     $url = $request->getPathInfo();
     $collection = new RouteCollection();
     /** @var $connection \Doctrine\DBAL\Connection */
     $connection = $this->objectManager->getConnection();
     try {
         $connection->connect();
     } catch (\Exception $e) {
         return $collection;
     }
     if (!$connection->isConnected()) {
         return $collection;
     }
     $searchUrl = substr($url, -1) != '/' ? $url . '/' : $url;
     $params = array('path' => $searchUrl);
     try {
         $contentRoutes = $this->repository->findBy($params);
     } catch (\Doctrine\DBAL\DBALException $e) {
         return $collection;
     }
     if (empty($contentRoutes)) {
         return $collection;
     }
     $filterByLocale = function (ContentRouteInterface $var) use($request) {
         if ($request) {
             return $var->getLocale() == $request->getLocale();
         } else {
             return true;
         }
     };
     $tempContentRoutes = array_filter($contentRoutes, $filterByLocale);
     if (empty($tempContentRoutes)) {
         $tempContentRoutes = $contentRoutes;
     }
     foreach ($tempContentRoutes as $key => $contentRoute) {
         $viewStatus = $request ? $request->getSession()->get('_viewStatus', VersionableInterface::STATUS_PUBLISHED) : VersionableInterface::STATUS_PUBLISHED;
         $test = new \ReflectionClass($contentRoute->getClassType());
         if ($viewStatus == VersionableInterface::STATUS_DRAFT && $test->implementsInterface(ResourceVersionInterface::class)) {
             continue;
         } elseif ($viewStatus == VersionableInterface::STATUS_PUBLISHED && $test->implementsInterface(VersionableInterface::class)) {
             continue;
         }
         /** @var \Networking\InitCmsBundle\Model\ContentRouteInterface $contentRoute */
         $content = $this->getRouteContent($contentRoute);
         $collection->add(sprintf('%s/%s', $contentRoute->getLocale(), $searchUrl), static::generateRoute($contentRoute, $url, $content));
     }
     return $collection;
 }
Beispiel #20
0
 /**
  * Load country from Elcodi files Repository
  *
  * @param OutputInterface $output  Output
  * @param string          $country Country name
  *
  * @return $this Self object
  */
 private function loadLocation(OutputInterface $output, $country)
 {
     try {
         $url = "https://raw.githubusercontent.com/elcodi/LocationDumps/master/" . $country . ".sql";
         $content = file_get_contents($url);
         if ($content) {
             $stmt = $this->locationEntityManager->getConnection()->prepare($content);
             $stmt->execute();
             $this->printMessage($output, 'Elcodi', 'Country ' . $country . ' installed');
         }
     } catch (Exception $e) {
         $this->printMessageFail($output, 'Elcodi', 'Country ' . $country . ' not installed');
     }
     return $this;
 }
 /**
  * Saves the given array as a node data entity without using the ORM.
  *
  * If the node data already exists (same dimensions, same identifier, same workspace)
  * it is replaced.
  *
  * @param array $nodeData node data to save as an associative array ( $column_name => $value )
  * @throws ImportException
  * @return void
  */
 protected function persistNodeData($nodeData)
 {
     if ($nodeData['workspace'] !== 'live') {
         throw new ImportException('Saving NodeData with workspace != "live" using direct SQL not supported yet. Workspace is "' . $nodeData['workspace'] . '".');
     }
     if ($nodeData['path'] === '/') {
         return;
     }
     // cleanup old data
     /** @var \Doctrine\DBAL\Connection $connection */
     $connection = $this->entityManager->getConnection();
     // prepare node dimensions
     $dimensionValues = $nodeData['dimensionValues'];
     $dimensionsHash = Utility::sortDimensionValueArrayAndReturnDimensionsHash($dimensionValues);
     $jsonPropertiesDataTypeHandler = JsonArrayType::getType(JsonArrayType::FLOW_JSON_ARRAY);
     // post-process node data
     $nodeData['dimensionsHash'] = $dimensionsHash;
     $nodeData['dimensionValues'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($dimensionValues, $connection->getDatabasePlatform());
     $nodeData['properties'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($nodeData['properties'], $connection->getDatabasePlatform());
     $nodeData['accessRoles'] = $jsonPropertiesDataTypeHandler->convertToDatabaseValue($nodeData['accessRoles'], $connection->getDatabasePlatform());
     $connection->executeQuery('DELETE FROM typo3_typo3cr_domain_model_nodedimension' . ' WHERE nodedata IN (' . '   SELECT persistence_object_identifier FROM typo3_typo3cr_domain_model_nodedata' . '   WHERE identifier = :identifier' . '   AND workspace = :workspace' . '   AND dimensionshash = :dimensionsHash' . ' )', array('identifier' => $nodeData['identifier'], 'workspace' => $nodeData['workspace'], 'dimensionsHash' => $nodeData['dimensionsHash']));
     /** @var \Doctrine\ORM\QueryBuilder $queryBuilder */
     $queryBuilder = $this->entityManager->createQueryBuilder();
     $queryBuilder->delete()->from('TYPO3\\TYPO3CR\\Domain\\Model\\NodeData', 'n')->where('n.identifier = :identifier')->andWhere('n.dimensionsHash = :dimensionsHash')->andWhere('n.workspace = :workspace')->setParameter('identifier', $nodeData['identifier'])->setParameter('workspace', $nodeData['workspace'])->setParameter('dimensionsHash', $nodeData['dimensionsHash']);
     $queryBuilder->getQuery()->execute();
     // insert new data
     // we need to use executeUpdate to execute the INSERT -- else the data types are not taken into account.
     // That's why we build a DQL INSERT statement which is then executed.
     $queryParts = array();
     $queryArguments = array();
     $queryTypes = array();
     foreach ($this->nodeDataPropertyNames as $propertyName => $propertyConfig) {
         if (isset($nodeData[$propertyName])) {
             $queryParts[$propertyName] = ':' . $propertyName;
             $queryArguments[$propertyName] = $nodeData[$propertyName];
             if (isset($propertyConfig['columnType'])) {
                 $queryTypes[$propertyName] = $propertyConfig['columnType'];
             }
         }
     }
     $connection->executeUpdate('INSERT INTO typo3_typo3cr_domain_model_nodedata (' . implode(', ', array_keys($queryParts)) . ') VALUES (' . implode(', ', $queryParts) . ')', $queryArguments, $queryTypes);
     foreach ($dimensionValues as $dimension => $values) {
         foreach ($values as $value) {
             $nodeDimension = array('persistence_object_identifier' => Algorithms::generateUUID(), 'nodedata' => $nodeData['Persistence_Object_Identifier'], 'name' => $dimension, 'value' => $value);
             $connection->insert('typo3_typo3cr_domain_model_nodedimension', $nodeDimension);
         }
     }
 }
Beispiel #22
0
 /**
  * Return all the subjects available after filtering by a list of quiz filters
  *
  * @param string $option
  * @param array $filters
  * @param int $type
  * @param \_OurBrand_\My\Domain\Model\User $user
  * @return array
  */
 public function findFilterOptionsByFilters($option, $filters, $type, $user)
 {
     // Don't filter on the options we want
     unset($filters[$option]);
     /** @var $conn \Doctrine\DBAL\Connection * */
     $conn = $this->entityManager->getConnection();
     /** @var $queryBuilder \Doctrine\DBAL\Query\QueryBuilder * */
     $queryBuilder = $conn->createQueryBuilder();
     $queryBuilder->select($option . '.persistence_object_identifier as identifier');
     switch ($option) {
         case "examTypes":
             $queryBuilder->from('_OurBrand__quiz_domain_model_examtype', $option)->join($option, '_OurBrand__quiz_domain_model_quiz', 'quiz', 'quiz.examtype = ' . $option . '.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_levels_join', 'quiz_levels', 'quiz_levels.quiz_quiz = quiz.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_subjects_join', 'quiz_subjects', 'quiz_subjects.quiz_quiz = quiz.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quizcategory', 'category', 'category.persistence_object_identifier = quiz.quizcategory');
             break;
         case "subjects":
             $queryBuilder->from('_OurBrand__quiz_domain_model_subject', $option)->join($option, '_OurBrand__quiz_domain_model_quiz_subjects_join', 'quiz_subjects', 'quiz_subjects.quiz_subject = ' . $option . '.persistence_object_identifier')->join('quiz_subjects', '_OurBrand__quiz_domain_model_quiz', 'quiz', 'quiz.persistence_object_identifier = quiz_subjects.quiz_quiz')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_levels_join', 'quiz_levels', 'quiz_levels.quiz_quiz = quiz.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quizcategory', 'category', 'category.persistence_object_identifier = quiz.quizcategory');
             break;
         case "teamLevels":
             $queryBuilder->from('_OurBrand__quiz_domain_model_teamlevel', $option)->join($option, '_OurBrand__quiz_domain_model_quiz_levels_join', 'quiz_levels', 'quiz_levels.quiz_teamlevel = ' . $option . '.persistence_object_identifier')->join('quiz_levels', '_OurBrand__quiz_domain_model_quiz', 'quiz', 'quiz.persistence_object_identifier = quiz_levels.quiz_quiz')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_subjects_join', 'quiz_subjects', 'quiz_subjects.quiz_quiz = quiz.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quizcategory', 'category', 'category.persistence_object_identifier = quiz.quizcategory');
             break;
         case "categories":
             $queryBuilder->from('_OurBrand__quiz_domain_model_quizcategory', $option)->join($option, '_OurBrand__quiz_domain_model_quiz', 'quiz', 'quiz.quizcategory = ' . $option . '.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_levels_join', 'quiz_levels', 'quiz_levels.quiz_quiz = quiz.persistence_object_identifier')->leftJoin('quiz', '_OurBrand__quiz_domain_model_quiz_subjects_join', 'quiz_subjects', 'quiz_subjects.quiz_quiz = quiz.persistence_object_identifier');
             break;
     }
     if ($user->isWorker()) {
         $expression = $queryBuilder->expr()->eq('quiz.Quiz', 1);
     } else {
         $expression = $queryBuilder->expr()->andX($queryBuilder->expr()->eq('quiz.Quiz', 1), $queryBuilder->expr()->eq('quiz.isDraft', 0));
     }
     $constraints = array();
     $constraints[] = $queryBuilder->expr()->andX($queryBuilder->expr()->orX($queryBuilder->expr()->eq('quiz.creator', '"' . $user->getIdentifier() . '"'), $expression));
     $constraints[] = $queryBuilder->expr()->andX($queryBuilder->expr()->isNull('quiz.snapshotOf'), $queryBuilder->expr()->eq('quiz.type', intval($type)), $queryBuilder->expr()->eq('quiz.isDeleted', 0));
     $expression = $queryBuilder->expr()->andX();
     foreach ($constraints as $expr) {
         $expression->add($expr);
     }
     $queryBuilder->where($expression);
     $queryBuilder = $this->applyFilters($queryBuilder, $filters);
     $queryBuilder->groupBy('identifier');
     $queryBuilder->orderBy('identifier', 'ASC');
     $data = $conn->fetchAll($queryBuilder->getSQL());
     $results = array();
     foreach ($data as $row) {
         $results[] = $row['identifier'];
     }
     return $results;
 }
 /**
  * {@inheritDoc}
  */
 public function findContentRoutesBy($url)
 {
     $collection = new RouteCollection();
     /** @var $connection \Doctrine\DBAL\Connection */
     $connection = $this->objectManager->getConnection();
     try {
         $connection->connect();
     } catch (\Exception $e) {
         return $collection;
     }
     if (!$connection->isConnected()) {
         return $collection;
     }
     $searchUrl = substr($url, -1) != '/' ? $url . '/' : $url;
     $params = array('path' => $searchUrl);
     try {
         $contentRoutes = $this->repository->findBy($params);
     } catch (\Doctrine\DBAL\DBALException $e) {
         return $collection;
     }
     if (empty($contentRoutes)) {
         return $collection;
     }
     $tempContentRoutes = array_filter($contentRoutes, array($this, 'filterByLocale'));
     if (empty($tempContentRoutes)) {
         $tempContentRoutes = $contentRoutes;
     }
     foreach ($tempContentRoutes as $key => $contentRoute) {
         $viewStatus = $this->request ? $this->request->getSession()->get('_viewStatus', VersionableInterface::STATUS_PUBLISHED) : VersionableInterface::STATUS_PUBLISHED;
         $test = new \ReflectionClass($contentRoute->getClassType());
         if ($viewStatus == VersionableInterface::STATUS_DRAFT && $test->implementsInterface('Networking\\InitCmsBundle\\Doctrine\\Extensions\\Versionable\\ResourceVersionInterface')) {
             continue;
         } elseif ($viewStatus == VersionableInterface::STATUS_PUBLISHED && $test->implementsInterface('Networking\\InitCmsBundle\\Doctrine\\Extensions\\Versionable\\VersionableInterface')) {
             continue;
         }
         /** @var \Networking\InitCmsBundle\Model\ContentRouteInterface $contentRoute */
         $content = $this->getRouteContent($contentRoute);
         $contentRoute->setContent($content);
         $contentRoute->setPath($url);
         $collection->add(self::ROUTE_GENERATE_DUMMY_NAME . preg_replace('/[^a-z0-9A-Z_.]/', '_', $key), $contentRoute);
     }
     return $collection;
 }
 /**
  * @param DoctrineSqlFilter $sqlFilter
  * @param QuoteStrategy $quoteStrategy
  * @param ClassMetadata $targetEntity
  * @param string $targetTableAlias
  * @param string $targetEntityPropertyName
  * @return string
  * @throws InvalidQueryRewritingConstraintException
  * @throws \Exception
  */
 protected function getSqlForManyToOneAndOneToOneRelationsWithPropertyPath(DoctrineSqlFilter $sqlFilter, QuoteStrategy $quoteStrategy, ClassMetadata $targetEntity, $targetTableAlias, $targetEntityPropertyName)
 {
     $subselectQuery = $this->getSubselectQuery($targetEntity, $targetEntityPropertyName);
     $associationMapping = $targetEntity->getAssociationMapping($targetEntityPropertyName);
     $subselectConstraintQueries = array();
     foreach ($associationMapping['joinColumns'] as $joinColumn) {
         $rootAliases = $subselectQuery->getQueryBuilder()->getRootAliases();
         $subselectQuery->getQueryBuilder()->select($rootAliases[0] . '.' . $targetEntity->getFieldForColumn($joinColumn['referencedColumnName']));
         $subselectSql = $subselectQuery->getSql();
         foreach ($subselectQuery->getParameters() as $parameter) {
             $parameterValue = $parameter->getValue();
             if (is_object($parameterValue)) {
                 $parameterValue = $this->persistenceManager->getIdentifierByObject($parameter->getValue());
             }
             $subselectSql = preg_replace('/\\?/', $this->entityManager->getConnection()->quote($parameterValue, $parameter->getType()), $subselectSql, 1);
         }
         $quotedColumnName = $quoteStrategy->getJoinColumnName($joinColumn, $targetEntity, $this->entityManager->getConnection()->getDatabasePlatform());
         $subselectIdentifier = 'subselect' . md5($subselectSql);
         $subselectConstraintQueries[] = $targetTableAlias . '.' . $quotedColumnName . ' IN (SELECT ' . $subselectIdentifier . '.' . $joinColumn['referencedColumnName'] . '0 FROM (' . $subselectSql . ') AS ' . $subselectIdentifier . ' ) ';
     }
     return ' (' . implode(' ) AND ( ', $subselectConstraintQueries) . ') ';
 }
Beispiel #25
0
 /**
  * {@inheritdoc}
  */
 public function load(ObjectManager $manager)
 {
     // disable the SQL logger
     // @link http://stackoverflow.com/a/30924545
     $manager->getConnection()->getConfiguration()->setSQLLogger(null);
     $fileName = $this->getKey() . '.csv';
     $path = $this->container->get('ilioscore.dataimport_filelocator')->getDataFilePath($fileName);
     // honor the given entity identifiers.
     // @link http://www.ens.ro/2012/07/03/symfony2-doctrine-force-entity-id-on-persist/
     $manager->getClassMetaData(get_class($this->createEntity()))->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
     $i = 0;
     if (($handle = fopen($path, 'r')) !== false) {
         while (($data = fgetcsv($handle)) !== false) {
             $i++;
             // step over the first row
             // since it contains the field names
             if (1 === $i) {
                 continue;
             }
             $entity = $this->populateEntity($this->createEntity(), $data);
             $manager->persist($entity);
             if ($i % self::BATCH_SIZE === 0) {
                 $manager->flush();
                 $manager->clear();
             }
             if ($this->storeReference) {
                 $this->addReference($this->getKey() . $entity->getId(), $entity);
             }
         }
         $manager->flush();
         $manager->clear();
         fclose($handle);
     }
     // Force PHP's GC
     if (function_exists('gc_collect_cycles')) {
         gc_collect_cycles();
     }
 }
 /**
  * Get name of current database platform
  *
  * @return string
  */
 public function getDatabasePlatformName()
 {
     return ucfirst($this->entityManager->getConnection()->getDatabasePlatform()->getName());
 }
 /**
  * @param ObjectManager $objectManager
  */
 public function injectObjectManager(ObjectManager $objectManager)
 {
     $this->databaseConnection = $objectManager->getConnection();
 }
 protected function init()
 {
     $this->context = $this->contextFactory->create(array('workspaceName' => 'live'));
     $this->connection = $this->entityManager->getConnection();
 }
 /**
  * Import access incremental kloster data dump
  * @throws \Exception
  */
 public function importAccessInkDumpAction()
 {
     if (!is_dir($this->dumpDirectory)) {
         \TYPO3\Flow\Utility\Files::createDirectoryRecursively($this->dumpDirectory);
     }
     if (!file_exists($this->inkKlosterDumpFilenamePath)) {
         throw new \TYPO3\Flow\Resource\Exception('File ' . $this->inkKlosterDumpFilenamePath . ' not found in ' . $this->dumpDirectory, 1398846324);
     }
     $sql = file_get_contents($this->inkKlosterDumpFilenamePath);
     $sql = str_replace('CREATE DATABASE IF NOT EXISTS `Klosterdatenbank`;', '', $sql);
     $sql = str_replace('USE `Klosterdatenbank`;', '', $sql);
     $sql = str_replace('Bearbeitet von', 'Bearbeiter', $sql);
     $sql = str_replace('tblBundesländer', 'Land', $sql);
     $sql = str_replace('tblalleOrte', 'Ort', $sql);
     $sql = str_replace('tblBistum', 'Bistum', $sql);
     $sql = str_replace('tblGSBaende', 'Band', $sql);
     $sql = str_replace('tblKlosterStammblatt', 'Kloster', $sql);
     $sql = str_replace('tblKlosterStandort', 'Klosterstandort', $sql);
     $sql = str_replace('tblOrden', 'Orden', $sql);
     $sql = str_replace('tblKlosterOrden', 'Klosterorden', $sql);
     $sql = str_replace('`Wüstung`', '`Wuestung`', $sql);
     $sql = str_replace('`Datensatz angelegt`', '`Datensatz_angelegt`', $sql);
     $sql = str_replace('`Ordenszugehörigkeit`', '`Orden`', $sql);
     $sql = str_replace('`Ordenszugehörigkeit_von_von`', '`von_von`', $sql);
     $sql = str_replace('`Ordenszugehörigkeitvon__bis`', '`von_bis`', $sql);
     $sql = str_replace('`OrdenszugehörigkeitVerbal_von`', '`verbal_von`', $sql);
     $sql = str_replace('`Ordenszugehörigkeit_bis_von`', '`bis_von`', $sql);
     $sql = str_replace('`Ordenzugehörigkeit_bis_bis`', '`bis_bis`', $sql);
     $sql = str_replace('`OrdenszugehörigkeitVerbal_bis`', '`verbal_bis`', $sql);
     /** @var \Doctrine\DBAL\Connection $sqlConnection */
     $sqlConnection = $this->entityManager->getConnection();
     $sqlConnection->executeUpdate($sql);
 }
Beispiel #30
-1
 /**
  * Insert new users
  *
  * @param Collection $users
  */
 private function insertUsers(Collection $users)
 {
     set_time_limit(60);
     $this->manager->getConnection()->getConfiguration()->setSQLLogger(null);
     // Get existan user from DB
     $existantUsers = $this->repository->findBy(['email' => $this->extractEmails($users)->toArray()]);
     // Create an array of emails
     $existantEmails = array_map(function ($user) {
         return $user->getEmail();
     }, $existantUsers);
     unset($existantUsers);
     // Get not existant users ready to import
     $nonExistantUsers = $users->filter(function ($user) use($existantEmails) {
         return !in_array($user->getEmail(), $existantEmails);
     });
     unset($existantEmails);
     foreach ($nonExistantUsers as $user) {
         $user->addRole('ROLE_USER');
         $this->manager->persist($user);
         $this->manager->flush();
         $this->manager->clear();
         $this->manager->detach($user);
         gc_enable();
         gc_collect_cycles();
     }
 }