This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,19 @@
<?php
namespace Test\Tool;
use PHPUnit_Framework_TestCase;
/**
* Base test case
*/
abstract class BaseTestCase extends PHPUnit_Framework_TestCase
{
/**
* {@inheritdoc}
*/
protected function setUp()
{
}
}

View File

@@ -0,0 +1,162 @@
<?php
namespace Test\Tool;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\Common\EventManager;
use Doctrine\MongoDB\Connection;
/**
* Base test case contains common mock objects
*/
abstract class BaseTestCaseMongoODM extends \PHPUnit_Framework_TestCase
{
/**
* @var DocumentManager
*/
protected $dm;
/**
* {@inheritdoc}
*/
protected function setUp()
{
if (!class_exists('MongoClient')) {
$this->markTestSkipped('Missing Mongo extension.');
}
}
/**
* {@inheritdoc}
*/
protected function tearDown()
{
if ($this->dm) {
foreach ($this->dm->getDocumentDatabases() as $db) {
foreach ($db->listCollections() as $collection) {
$collection->drop();
}
}
$this->dm->getConnection()->close();
$this->dm = null;
}
}
/**
* DocumentManager mock object together with
* annotation mapping driver and database
*
* @param EventManager $evm
* @return DocumentManager
*/
protected function getMockDocumentManager(EventManager $evm = null)
{
$conn = new Connection;
$config = $this->getMockAnnotatedConfig();
try {
$this->dm = DocumentManager::create($conn, $config, $evm ?: $this->getEventManager());
$this->dm->getConnection()->connect();
} catch (\MongoException $e) {
$this->markTestSkipped('Doctrine MongoDB ODM failed to connect');
}
return $this->dm;
}
/**
* DocumentManager mock object with
* annotation mapping driver
*
* @param EventManager $evm
* @return DocumentManager
*/
protected function getMockMappedDocumentManager(EventManager $evm = null)
{
$conn = $this->getMock('Doctrine\\MongoDB\\Connection');
$config = $this->getMockAnnotatedConfig();
$this->dm = DocumentManager::create($conn, $config, $evm ?: $this->getEventManager());
return $this->dm;
}
/**
* Creates default mapping driver
*
* @return \Doctrine\ORM\Mapping\Driver\Driver
*/
protected function getMetadataDriverImplementation()
{
return new AnnotationDriver($_ENV['annotation_reader']);
}
/**
* Build event manager
*
* @return EventManager
*/
private function getEventManager()
{
$evm = new EventManager;
return $evm;
}
/**
* Get annotation mapping configuration
*
* @return Doctrine\ORM\Configuration
*/
private function getMockAnnotatedConfig()
{
$config = $this->getMock('Doctrine\\ODM\\MongoDB\\Configuration');
$config->expects($this->once())
->method('getProxyDir')
->will($this->returnValue(__DIR__.'/../../temp'));
$config->expects($this->once())
->method('getProxyNamespace')
->will($this->returnValue('Proxy'));
$config->expects($this->once())
->method('getHydratorDir')
->will($this->returnValue(__DIR__.'/../../temp'));
$config->expects($this->once())
->method('getHydratorNamespace')
->will($this->returnValue('Hydrator'));
$config->expects($this->any())
->method('getDefaultDB')
->will($this->returnValue('knp_pager_tests'));
$config->expects($this->once())
->method('getAutoGenerateProxyClasses')
->will($this->returnValue(true));
$config->expects($this->once())
->method('getAutoGenerateHydratorClasses')
->will($this->returnValue(true));
$config->expects($this->once())
->method('getClassMetadataFactoryName')
->will($this->returnValue('Doctrine\\ODM\\MongoDB\\Mapping\\ClassMetadataFactory'));
$config->expects($this->any())
->method('getMongoCmd')
->will($this->returnValue('$'));
$config
->expects($this->any())
->method('getDefaultCommitOptions')
->will($this->returnValue(array('safe' => true)))
;
$mappingDriver = $this->getMetadataDriverImplementation();
$config->expects($this->any())
->method('getMetadataDriverImpl')
->will($this->returnValue($mappingDriver));
return $config;
}
}

View File

@@ -0,0 +1,264 @@
<?php
namespace Test\Tool;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\Mapping\DefaultNamingStrategy;
use Doctrine\ORM\Mapping\DefaultQuoteStrategy;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\EntityManager;
use Doctrine\Common\EventManager;
use Doctrine\ORM\Tools\SchemaTool;
/**
* Base test case contains common mock objects
* and functionality among all extensions using
* ORM object manager
*
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @package Gedmo
* @subpackage BaseTestCase
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
abstract class BaseTestCaseORM extends \PHPUnit_Framework_TestCase
{
/**
* @var EntityManager
*/
protected $em;
/**
* @var QueryAnalyzer
*/
protected $queryAnalyzer;
/**
* {@inheritdoc}
*/
protected function setUp()
{
}
/**
* EntityManager mock object together with
* annotation mapping driver and pdo_sqlite
* database in memory
*
* @param EventManager $evm
* @return EntityManager
*/
protected function getMockSqliteEntityManager(EventManager $evm = null)
{
$conn = array(
'driver' => 'pdo_sqlite',
'memory' => true,
);
$config = $this->getMockAnnotatedConfig();
$em = EntityManager::create($conn, $config, $evm ?: $this->getEventManager());
$schema = array_map(function($class) use ($em) {
return $em->getClassMetadata($class);
}, (array)$this->getUsedEntityFixtures());
$schemaTool = new SchemaTool($em);
$schemaTool->dropSchema(array());
$schemaTool->createSchema($schema);
return $this->em = $em;
}
/**
* EntityManager mock object together with
* annotation mapping driver and custom
* connection
*
* @param array $conn
* @param EventManager $evm
* @return EntityManager
*/
protected function getMockCustomEntityManager(array $conn, EventManager $evm = null)
{
$config = $this->getMockAnnotatedConfig();
$em = EntityManager::create($conn, $config, $evm ?: $this->getEventManager());
$schema = array_map(function($class) use ($em) {
return $em->getClassMetadata($class);
}, (array)$this->getUsedEntityFixtures());
$schemaTool = new SchemaTool($em);
$schemaTool->dropSchema(array());
$schemaTool->createSchema($schema);
return $this->em = $em;
}
/**
* EntityManager mock object with
* annotation mapping driver
*
* @param EventManager $evm
* @return EntityManager
*/
protected function getMockMappedEntityManager(EventManager $evm = null)
{
$driver = $this->getMock('Doctrine\DBAL\Driver');
$driver->expects($this->once())
->method('getDatabasePlatform')
->will($this->returnValue($this->getMock('Doctrine\DBAL\Platforms\MySqlPlatform')));
$conn = $this->getMock('Doctrine\DBAL\Connection', array(), array(array(), $driver));
$conn->expects($this->once())
->method('getEventManager')
->will($this->returnValue($evm ?: $this->getEventManager()));
$config = $this->getMockAnnotatedConfig();
$this->em = EntityManager::create($conn, $config);
return $this->em;
}
/**
* Starts query statistic log
*
* @throws \RuntimeException
*/
protected function startQueryLog()
{
if (!$this->em || !$this->em->getConnection()->getDatabasePlatform()) {
throw new \RuntimeException('EntityManager and database platform must be initialized');
}
$this->queryAnalyzer = new QueryAnalyzer($this->em->getConnection()->getDatabasePlatform());
$this->em
->getConfiguration()
->expects($this->any())
->method('getSQLLogger')
->will($this->returnValue($this->queryAnalyzer));
}
/**
* Stops query statistic log and outputs
* the data to screen or file
*
* @param boolean $dumpOnlySql
* @param boolean $writeToLog
* @throws \RuntimeException
*/
protected function stopQueryLog($dumpOnlySql = false, $writeToLog = false)
{
if ($this->queryAnalyzer) {
$output = $this->queryAnalyzer->getOutput($dumpOnlySql);
if ($writeToLog) {
$fileName = __DIR__.'/../../temp/query_debug_'.time().'.log';
if (($file = fopen($fileName, 'w+')) !== false) {
fwrite($file, $output);
fclose($file);
} else {
throw new \RuntimeException('Unable to write to the log file');
}
} else {
echo $output;
}
}
}
/**
* Creates default mapping driver
*
* @return \Doctrine\ORM\Mapping\Driver\Driver
*/
protected function getMetadataDriverImplementation()
{
return new AnnotationDriver($_ENV['annotation_reader']);
}
/**
* Get a list of used fixture classes
*
* @return array
*/
abstract protected function getUsedEntityFixtures();
/**
* Build event manager
*
* @return EventManager
*/
private function getEventManager()
{
$evm = new EventManager;
return $evm;
}
/**
* Get annotation mapping configuration
*
* @return Doctrine\ORM\Configuration
*/
private function getMockAnnotatedConfig()
{
$config = $this->getMock('Doctrine\ORM\Configuration');
$config
->expects($this->once())
->method('getProxyDir')
->will($this->returnValue(__DIR__.'/../../temp'))
;
$config
->expects($this->once())
->method('getProxyNamespace')
->will($this->returnValue('Proxy'))
;
$config
->expects($this->once())
->method('getAutoGenerateProxyClasses')
->will($this->returnValue(true))
;
$config
->expects($this->once())
->method('getClassMetadataFactoryName')
->will($this->returnValue('Doctrine\\ORM\\Mapping\\ClassMetadataFactory'))
;
$mappingDriver = $this->getMetadataDriverImplementation();
$config
->expects($this->any())
->method('getMetadataDriverImpl')
->will($this->returnValue($mappingDriver))
;
$config
->expects($this->any())
->method('getDefaultRepositoryClassName')
->will($this->returnValue('Doctrine\\ORM\\EntityRepository'))
;
$config
->expects($this->any())
->method('getQuoteStrategy')
->will($this->returnValue(new DefaultQuoteStrategy()))
;
$config
->expects($this->any())
->method('getNamingStrategy')
->will($this->returnValue(new DefaultNamingStrategy()))
;
$config
->expects($this->any())
->method('getCustomHydrationMode')
->will($this->returnValue('Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\Query\AsIsHydrator'))
;
$config
->expects($this->any())
->method('getDefaultQueryHints')
->will($this->returnValue(array()))
;
return $config;
}
}

View File

@@ -0,0 +1,88 @@
<?php
namespace Test\Tool;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\DBAL\DriverManager;
use Doctrine\ODM\PHPCR\Mapping\Driver\AnnotationDriver;
use Doctrine\ODM\PHPCR\DocumentManager;
use Doctrine\Common\EventManager;
use Doctrine\MongoDB\Connection;
use Jackalope\RepositoryFactoryDoctrineDBAL;
use Jackalope\Session;
use Jackalope\Transport\DoctrineDBAL\RepositorySchema;
/**
* Base test case contains common mock objects
*/
abstract class BaseTestCasePHPCRODM extends \PHPUnit_Framework_TestCase
{
/**
* @var DocumentManager
*/
protected $dm;
protected function setUp()
{
if (!class_exists('Doctrine\ODM\PHPCR\Query\Query')) {
$this->markTestSkipped('Doctrine PHPCR-ODM is not available');
}
}
protected function tearDown()
{
if ($this->dm) {
$this->dm = null;
}
}
protected function getMockDocumentManager(EventManager $evm = null)
{
$config = new \Doctrine\ODM\PHPCR\Configuration();
$config->setMetadataDriverImpl($this->getMetadataDriverImplementation());
$this->dm = DocumentManager::create($this->getSession(), $config, $evm ?: $this->getEventManager());
return $this->dm;
}
protected function getMetadataDriverImplementation()
{
return new AnnotationDriver($_ENV['annotation_reader']);
}
private function getSession()
{
$connection = DriverManager::getConnection(array(
'driver' => 'pdo_sqlite',
'path' => ':memory:',
));
$factory = new RepositoryFactoryDoctrineDBAL();
$repository = $factory->getRepository(array(
'jackalope.doctrine_dbal_connection' => $connection,
));
$schema = new RepositorySchema(array('disable_fks' => true), $connection);
$schema->reset();
$session = $repository->login(new \PHPCR\SimpleCredentials('', ''));
$cnd = <<<CND
<phpcr='http://www.doctrine-project.org/projects/phpcr_odm'>
[phpcr:managed]
mixin
- phpcr:class (STRING)
- phpcr:classparents (STRING) multiple
CND;
$session->getWorkspace()->getNodeTypeManager()->registerNodeTypesCnd($cnd, true);
return $session;
}
private function getEventManager()
{
$evm = new EventManager();
return $evm;
}
}

View File

@@ -0,0 +1,242 @@
<?php
namespace Test\Tool;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
* @package Gedmo.Tool.Logging.DBAL
* @subpackage QueryAnalyzer
* @link http://www.gediminasm.org
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
class QueryAnalyzer implements SQLLogger
{
/**
* Used database platform
*
* @var AbstractPlatform
*/
protected $platform;
/**
* Start time of currently executed query
*
* @var integer
*/
private $queryStartTime = null;
/**
* Total execution time of all queries
*
* @var integer
*/
private $totalExecutionTime = 0;
/**
* List of queries executed
*
* @var array
*/
private $queries = array();
/**
* Query execution times indexed
* in same order as queries
*
* @var array
*/
private $queryExecutionTimes = array();
/**
* Initialize log listener with database
* platform, which is needed for parameter
* conversion
*
* @param AbstractPlatform $platform
*/
public function __construct(AbstractPlatform $platform)
{
$this->platform = $platform;
}
/**
* {@inheritdoc}
*/
public function startQuery($sql, array $params = null, array $types = null)
{
$this->queryStartTime = microtime(true);
$this->queries[] = $this->generateSql($sql, $params, $types);
}
/**
* {@inheritdoc}
*/
public function stopQuery()
{
$ms = round(microtime(true) - $this->queryStartTime, 4) * 1000;
$this->queryExecutionTimes[] = $ms;
$this->totalExecutionTime += $ms;
}
/**
* Clean all collected data
*
* @return QueryAnalyzer
*/
public function cleanUp()
{
$this->queries = array();
$this->queryExecutionTimes = array();
$this->totalExecutionTime = 0;
return $this;
}
/**
* Dump the statistics of executed queries
*
* @param boolean $dumpOnlySql
* @return void
*/
public function getOutput($dumpOnlySql = false)
{
$output = '';
if (!$dumpOnlySql) {
$output .= 'Platform: ' . $this->platform->getName() . PHP_EOL;
$output .= 'Executed queries: ' . count($this->queries) . ', total time: ' . $this->totalExecutionTime . ' ms' . PHP_EOL;
}
foreach ($this->queries as $index => $sql) {
if (!$dumpOnlySql) {
$output .= 'Query(' . ($index+1) . ') - ' . $this->queryExecutionTimes[$index] . ' ms' . PHP_EOL;
}
$output .= $sql . ';' . PHP_EOL;
}
$output .= PHP_EOL;
return $output;
}
/**
* Index of the slowest query executed
*
* @return integer
*/
public function getSlowestQueryIndex()
{
$index = 0;
$slowest = 0;
foreach ($this->queryExecutionTimes as $i => $time) {
if ($time > $slowest) {
$slowest = $time;
$index = $i;
}
}
return $index;
}
/**
* Get total execution time of queries
*
* @return integer
*/
public function getTotalExecutionTime()
{
return $this->totalExecutionTime;
}
/**
* Get all queries
*
* @return array
*/
public function getExecutedQueries()
{
return $this->queries;
}
/**
* Get number of executed queries
*
* @return integer
*/
public function getNumExecutedQueries()
{
return count($this->queries);
}
/**
* Get all query execution times
*
* @return array
*/
public function getExecutionTimes()
{
return $this->queryExecutionTimes;
}
/**
* Create the SQL with mapped parameters
*
* @param string $sql
* @param array $params
* @param array $types
* @return sql
*/
private function generateSql($sql, $params, $types)
{
if (!count($params)) {
return $sql;
}
$converted = $this->getConvertedParams($params, $types);
if (is_int(key($params))) {
$index = key($converted);
$sql = preg_replace_callback('@\?@sm', function($match) use (&$index, $converted) {
return implode(' ', $converted[$index++]);
}, $sql);
} else {
foreach ($converted as $key => $value) {
$sql = str_replace(':' . $key, $value, $sql);
}
}
return $sql;
}
/**
* Get the converted parameter list
*
* @param array $params
* @param array $types
* @return array
*/
private function getConvertedParams($params, $types)
{
$result = array();
foreach ($params as $position => $value) {
if (isset($types[$position])) {
$type = $types[$position];
if (is_string($type)) {
$type = Type::getType($type);
}
if ($type instanceof Type) {
$value = $type->convertToDatabaseValue($value, $this->platform);
}
} else {
if (is_object($value) && $value instanceof \DateTime) {
$value = $value->format($this->platform->getDateTimeFormatString());
} elseif (!is_null($value)) {
$type = Type::getType(gettype($value));
$value = $type->convertToDatabaseValue($value, $this->platform);
}
}
if (is_string($value)) {
$value = "'{$value}'";
} elseif (is_null($value)) {
$value = 'NULL';
}
$result[$position] = $value;
}
return $result;
}
}