public function testFixture() { $this->tags = Helper::reindex($this->getRepository('Psc\\Doctrine\\TestEntities\\Tag')->findAll(), 'label'); $this->assertEquals(5, $this->tags['Wahl']->getIdentifier()); $this->assertEquals(2, $this->tags['Demonstration']->getIdentifier()); $this->assertEquals(1, $this->tags['Russland']->getIdentifier()); }
protected function execute(InputInterface $input, OutputInterface $output) { $this->initDoctrine($input, $output); if ($this->transactional) { $this->em->getConnection()->beginTransaction(); } try { $ret = parent::execute($input, $output); if ($ret <= 0) { if ($this->echoLog) { DoctrineHelper::enableSQLLogging('echo', $this->em); } if ($input->getOption('dry-run')) { $this->warn('DryRun: nothing is flushed'); } else { $this->em->flush(); } if ($this->transactional) { $this->em->getConnection()->commit(); } } else { if ($this->transactional) { $this->em->getConnection()->rollback(); } } } catch (\Exception $e) { if ($this->transactional) { $this->em->getConnection()->rollback(); } $this->em->close(); throw $e; } return $ret; }
public function __construct($entityName, $idName = 'id', $em = NULL) { if (!isset($em)) { $em = DoctrineHelper::em(); } $this->em = $em; $this->idName = $idName; $this->entityName = DoctrineHelper::getEntityName($entityName); }
/** * @return Doctrine\Common\Collections\Collection */ public function collection(array $identifiers, $reindex = NULL, $checkCardinality = TRUE, &$found = NULL) { $idname = $reindex ?: 'id'; $entities = $this->byList($identifiers, $idname, $checkCardinality, $found); if ($reindex !== NULL) { $entities = Helper::reindex($entities, $reindex); } return $entities; }
protected function expectRepositoryPersists($entity, $times = NULL) { if (is_array($entity)) { $entities = \Psc\Doctrine\Helper::reindex($entity); $this->repository->expects($times ?: $this->exactly(count($entities)))->method('persist')->will($this->returnCallback(function (\Psc\CMS\Entity $entity) use($entities) { return $entities[$entity->getIdentifier()]; })); } else { $this->repository->expects($times ?: $this->once())->method('persist')->with($this->equalTo($entity))->will($this->returnSelf()); } }
protected function execute(InputInterface $input, OutputInterface $output) { $con = $this->initDoctrine($input, $output); $force = $input->getOption('force') === TRUE ? DoctrineHelper::FORCE : NULL; if ($force == DoctrineHelper::FORCE) { $output->writeln('Updating Schema (forced)'); } else { $output->writeln("Printing Update-Schema SQL"); } $output->writeln($log = DoctrineHelper::updateSchema($force, "\n", $this->em)); if ($force != DoctrineHelper::FORCE && empty($log)) { $output->writeln('nothing to do'); } return 0; }
public function getLinksByHoster() { return DoctrineHelper::reindex($this->getLinks()->toArray(), 'hoster'); }
public function saveFormular(array $flat) { \Psc\Doctrine\Helper::enableSQLLogging('stack', $em = $this->dc->getEntityManager()); $logger = $this->persistFromUI($flat, $this->dc->getModule()); return array('status' => TRUE, 'log' => $logger->toString(), 'context' => $this->repository->getContext(), 'sql' => \Psc\Doctrine\Helper::printSQLLog('/^(INSERT|UPDATE|DELETE)/', TRUE, $em), 'flat' => $this->getFlat()); }
/** * Asserted 2 Collections mit einem Feld als vergleicher */ public function assertCollection($expected, $actual, $compareFieldGetter = 'identifier') { $this->assertEquals(DoctrineHelper::map($expected, $compareFieldGetter), DoctrineHelper::map($actual, $compareFieldGetter), 'Collections sind nicht gleich'); }
/** * Gibt eine Collection von Objekten auf ein Feld reduziert zurück * */ public function reduceCollection($collection, $field = 'identifier') { return \Psc\Doctrine\Helper::map($collection, $field); }
public function debug($withResponse = TRUE, $withResponseBody = TRUE) { $text = "== Request Headers ===============================\n"; if ($this->isGet() && count((array) $this->data) > 0) { $text .= 'URL: ' . $this->url . "?" . http_build_query((array) $this->data) . "\n"; } else { $text .= 'URL: ' . $this->url . "\n"; } if (isset($this->response)) { // aka request wurde schon abgeschickt, dann zeige hier die gesendeten headers an $text .= $this->getHeaders() . "\n"; } else { foreach ($this->httpHeaders as $name => $value) { $text .= $name . ': ' . $value . "\n"; } } $text .= "== Body (Type: " . $this->type . ") =================\n"; if (array_key_exists('Content-Type', $this->httpHeaders) && mb_strpos($this->httpHeaders['Content-Type'], 'multipart/form-data') !== FALSE) { $text .= '<cannot display multipart body on debug>' . "\n"; } else { $text .= \Psc\Doctrine\Helper::getDump($this->data, 8); } $text .= "=================================================\n"; if ($withResponse) { $text .= "\n"; $text .= "== Response =====================================\n"; if (isset($this->response)) { $text .= $this->getResponseHeader()->debug() . "\n"; if ($withResponseBody) { $text .= "== Body =========================================\n"; $text .= $this->response->getRaw() . "\n"; } } else { $text .= '[noch keine Response]' . "\n"; } $text .= "=================================================\n"; } return $text; }
/** * @return array */ public function findAllByIds(array $ids, $idname = 'id') { if (count($ids) == 0) { return array(); } $dql = 'SELECT e FROM ' . $this->_entityName . ' as e '; $dql .= 'WHERE e.' . $idname; $dql .= ' IN (' . DoctrineHelper::implodeIdentifiers($ids) . ') '; // wenn ids ein verschalter array ist mit einem weiteren array mit strings drin, kommt hier ein notice $q = $this->_em->createQuery($dql); return $q->getResult(); }
public function __toString() { try { $str = 'Event[' . $this->getIdentifier() . '] ' . "\n"; $str .= 'Target: ' . Code::varInfo($this->target) . "\n"; $str .= 'Daten: ' . \Psc\Doctrine\Helper::getDump($this->data, $maxDepth = 1) . "\n"; } catch (\Exception $e) { print $e; exit; } return $str; }
/** * @group coll */ public function testCollectionsDebug() { $this->assertNotEmpty(DoctrineHelper::debugCollectionDiff($this->collection, $this->actualItems)); }
public function debug() { $text = "== Psc\\Net\\HTTP\\Response =========================\n"; //$text .= $this->getCode().' : '.$this->getReason()."\n"; $text .= $this->getHeader() . "\n"; $text .= "== Response-Body =================================\n"; $text .= \Psc\Doctrine\Helper::getDump((array) $this->body, 4); $text .= "=================================================\n"; /* $text .= "\n"; $text .= "== Response =====================================\n"; $text .= $this->getResponseHeader()."\n"; $text .= "== Body =========================================\n"; $text .= $this->response->getRaw()."\n"; $text .= "=================================================\n"; */ return $text; }
public static function debugCollection($collection, $glue = "\n", $label = NULL) { $ret = $label ? 'Collection ' . $label . $glue : NULL; if (count($collection) === 0) { $ret .= '[leere Collection]'; } else { $ret .= \Webforge\Common\ArrayUtil::implode(Code::castArray($collection), $glue, function ($item, $key) { return sprintf('[%s] %s', $key, \Psc\Doctrine\Helper::debugEntity($item)); }); } return $ret; }
/** * Synchronisiert eine Collection eines Entities mit Entities in der Datenbank (deprecated) * * Diese Art der Synchroniserung ist deprecated, weil es mittlerweile ausgelagerte Funktionen dafür gibt * (siehe Psc\Doctrine\*Synchro*) * * also es werden für die bestehenden Objekte in $entity->$collectionProperty die objekte gelöscht * die nicht in newCollection drin sind und die, die in $newCollection drin sind aber nicht in * $entity->$collectionProperty gelöscht * * - Achtung(!): dies führt persist() auf den Entitys der Collection (also quasi andere Seite der Association) aus, wenn $this->entity nicht die Owning-Side der CollectionAssociation ist * - Dies führt persist für items in newCollection, die neu sind * * Die Basis für eine erfolgreiche Synchronization ist eine $newCollection die wirklich die gleichen Objekte enthält, für die Updates gemacht werden sollen. Also vorsicht mit serialisierten Einträgen und clones * * @param string $associationName der Name des Properties der Collection in $entity */ public function synchronizeCollection($associationName, $newCollection) { if (!is_string($associationName)) { throw new \Psc\Exception('string erwartet: ' . Code::varInfo($associationName)); } /* $mapping = $coll->getMapping(); $targetClass = $this->_em->getClassMetadata($mapping['targetEntity']); $sourceClass = $this->_em->getClassMetadata($mapping['sourceEntity']); $id = $this->_em->getUnitOfWork()->getEntityIdentifier($coll->getOwner()); */ if ($this->entity instanceof \Psc\Doctrine\Object) { $entityClass = $this->entity->getDoctrineMetadata(); // Sound } elseif ($this->entity instanceof \Psc\Doctrine\Entity) { $entityClass = $this->em->getClassMetadata($this->entity->getEntityName()); } else { throw new \InvalidArgumentException('$this->entity ist von der Klasse: ' . Code::getClass($this->entity) . ' und diese ist unbekannt'); } $entityAssoc = $entityClass->getAssociationMapping($associationName); // speakers $owning = $entityAssoc['isOwningSide']; // true $targetClass = $this->em->getClassMetadata($entityAssoc['targetEntity']); // Metadata:Speaker if ($owning) { $entityProperty = $entityAssoc['inversedBy']; $collectionProperty = $entityAssoc['fieldName']; } else { $entityProperty = $entityAssoc['mappedBy']; $collectionProperty = $entityAssoc['fieldName']; } // entityProperty = sounds // collectionProperty = speakers $getter = Code::castGetter($collectionProperty); //getSpeakers $collection = $getter($this->entity); // $this->entity->getSpeakers() $collection = Code::castCollection($collection); $newCollection = Code::castCollection($newCollection); $this->log(sprintf("synchronizeCollection '%s'", $associationName)); $this->log('in DBCollection:'); $this->log(DoctrineHelper::debugCollection($collection)); $this->log(NULL); $this->log('in FormCollection:'); $this->log(DoctrineHelper::debugCollection($newCollection)); $this->log(NULL); $this->log('Processing:'); /* Wir synchronisieren hier auf der Owning Side oder Reverse Side jenachdem müssen wir auf der owning oder reverse side die add + remove funktionen aufrufen */ if ($owning) { $remove = 'remove' . ucfirst(Inflector::singular($collectionProperty)); // removeSpeaker $add = 'add' . ucfirst(Inflector::singular($collectionProperty)); // addSpeaker } else { $remove = 'remove' . ucfirst(Inflector::singular($entityProperty)); // removeSound $add = 'add' . ucfirst(Inflector::singular($entityProperty)); // addSound } $logThis = Code::getClassName($entityClass->getName()); // @TODO hier mit reflection prüfen //if (!->hasMethod($remove)) { // throw new \Psc\Exception('Es gibt keine '.$remove.' Methode im Entity: '.$owningEntity); //} //if (!$this->entity->hasMethod($add)) { // throw new \Psc\Exception('Es gibt keine '.$add.' Methode im Entity: '.$owningEntity); //} // foreach ($collection->deleteDiff($newCollection, ArrayCollection::COMPARE_OBJECTS) as $entity) { if ($owning) { $this->entity->{$remove}($entity); // $sound->removeSpeaker($speaker) } else { $this->em->persist($entity); // $speaker persist $entity->{$remove}($this->entity); // $speaker->removeSound($sound) } } foreach ($collection->insertDiff($newCollection, ArrayCollection::COMPARE_OBJECTS) as $entity) { if ($owning) { $this->entity->{$add}($entity); $this->em->persist($entity); } else { $entity->{$add}($this->entity); $this->em->persist($entity); } } }
/** * @return CoMun\Entities\ContentStream[] */ public function getContentStreamsByLocale($revision = 'default') { return \Psc\Doctrine\Helper::reindex($this->getContentStreamsByRevision($revision), 'locale'); }
public function findAllIndexByEmail() { return DoctrineHelper::reindex($this->findAll(), 'getEmail'); }
protected function resetEntityManager() { $this->em = DoctrineHelper::reCreateEm(); }
<?php use Psc\Doctrine\Helper as DoctrineHelper; require __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'bootstrap.php'; $doctrine = $container->getModule('Doctrine'); print DoctrineHelper::updateSchema(DoctrineHelper::FORCE, "\n", $doctrine->getEntityManager('tests')); print DoctrineHelper::updateSchema(DoctrineHelper::FORCE, "\n", $doctrine->getEntityManager('default'));
public function __wakeup() { $this->entityName = DoctrineHelper::getEntityName($this->entityName); }
/** * Verändert die aktuelle Reihenfolge der Componenten * * $sorting kann entweder ein Closure sein welches als Parameter 2 Komponenten bekommt und dann entscheidet welche weiter vorne stehen soll. * oder ein array von property Names. Diese werden dann in der Reihenfolge wie im Array gesetzt, alle restlichen (nicht im array angegebenen) Componenten werden ans Ende gehängt * @param Closure|array $sorting kann ein Array von property-Names sein oder eine Closure die 2 Parameter erhält und eine Sortierfunktion ist returns: -1|0|1 */ public function sortComponents($sorting) { if (is_array($sorting)) { $order = array_flip($sorting); // $name => $position // wir erstellen unseren name => componenten index $components = \Psc\Doctrine\Helper::reindex($this->components->toArray(), 'getFormName'); // wir fügen alle Komponenten hinzu, die nicht in dem Index drin sind (hängen sie nach hinten an) foreach ($components as $name => $component) { if (!array_key_exists($name, $order)) { $order[$name] = count($order); } } $sorting = function ($c1, $c2) use($order) { // @TODO formName kann auch ein array sein? if (($n1 = $c1->getFormName()) === ($n2 = $c2->getFormName())) { return 0; } return $order[$n1] > $order[$n2] ? 1 : -1; }; } if (!$sorting instanceof \Closure) { throw new \InvalidArgumentException('sortComponents muss eine Closure als Parameter haben (oder ein Array)'); } $this->components->sortBy($sorting); return $this; }
/** * Dynamic Index * * Laufzeit O(2*n) und Queries O(1) (nur benötigte im Datenspeicher, dafür komplexeres query (allerdings nach unique-index)) * * Vorteile: * speicher-effizient wenn nicht alle Objekte aus der Tabelle geladen werden müssen * soft-fail für ids möglich wenn man mit OR und DQL selected, auswertung jedoch komplizierter ( und Laufzeit O((2+uniques)*n) * * Nachteile: * geht nicht für unique-kriterien die aus mehreren Spalten bestehen (denn das geht nicht mit findby), höchstens mit DQL und string verkettung - das würde aber ein where auf einem nicht-index bedeuten, etc * */ protected function hydrateTagsDynamicSelect(array $tagNames) { $toCollection = array(); $avaibleTags = \Psc\Doctrine\Helper::reindex($this->tagRepository->findBy(array('name' => $tagNames)), 'label'); foreach ($tagNames as $tagName) { if (array_key_exists($name, $indexTags)) { $toCollection[] = $indexTags[$name]; } else { $toCollection[] = new Tag($name); } } }