/** * @see Console\Command\Command */ protected function execute(Console\Input\InputInterface $input, Console\Output\OutputInterface $output) { $em = $this->getHelper('em')->getEntityManager(); $validator = new \Doctrine\ORM\Tools\SchemaValidator($em); $errors = $validator->validateMapping(); $exit = 0; if ($errors) { foreach ($errors as $className => $errorMessages) { $output->write("<error>[Mapping] FAIL - The entity-class '" . $className . "' mapping is invalid:</error>\n"); foreach ($errorMessages as $errorMessage) { $output->write('* ' . $errorMessage . "\n"); } $output->write("\n"); } $exit += 1; } else { $output->write('<info>[Mapping] OK - The mapping files are correct.</info>' . "\n"); } if (!$validator->schemaInSyncWithMetadata()) { $output->write('<error>[Database] FAIL - The database schema is not in sync with the current mapping file.</error>' . "\n"); $exit += 2; } else { $output->write('<info>[Database] OK - The database schema is in sync with the mapping files.</info>' . "\n"); } exit($exit); }
/** * Validates the metadata mapping for Doctrine, using the SchemaValidator * of Doctrine. * * @return array */ public function validateMapping() { try { $validator = new \Doctrine\ORM\Tools\SchemaValidator($this->entityManager); return $validator->validateMapping(); } catch (\Exception $exception) { return array(array($exception->getMessage())); } }
public static function init() { $zf2ModulePaths = [dirname(dirname(__DIR__))]; if ($path = static::findParentPath('vendor')) { $zf2ModulePaths[] = $path; } if ($path = static::findParentPath('module')) { $zf2ModulePaths[] = $path; } if (($path = static::findParentPath('src')) !== $zf2ModulePaths[0]) { $zf2ModulePaths[] = $path; } static::initAutoloader(); $config = (include __DIR__ . '/../config/application.config.php'); $serviceManager = new ServiceManager(new ServiceManagerConfig()); $serviceManager->setService('ApplicationConfig', $config); $serviceManager->get('ModuleManager')->loadModules(); static::$serviceManager = $serviceManager; if (defined("TEST_SUITE") && constant("TEST_SUITE") == 'full') { $entityManager = $serviceManager->get('doctrine.entitymanager.orm_default'); //Validate the schema; $validator = new \Doctrine\ORM\Tools\SchemaValidator($entityManager); $errors = $validator->validateMapping(); if (count($errors) > 0) { foreach ($errors as $entity => $errors) { echo "Error in Entity: '" . $entity . "':\n"; echo implode("\n", $errors); echo "\n"; } die; } //Create the schema $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager); $mdFactory = $entityManager->getMetadataFactory(); $mdFactory->getAllMetadata(); $tool->dropDatabase(); $tool->createSchema($mdFactory->getAllMetadata()); $loader = new Loader(); $loader->addFixture(new \ProjectTest\Fixture\LoadVersionData()); $loader->addFixture(new \ContactTest\Fixture\LoadContactData()); $loader->addFixture(new \ProjectTest\Fixture\LoadProjectLogoData()); $loader->addFixture(new \ProjectTest\Fixture\LoadDocumentData()); $loader->addFixture(new \ProjectTest\Fixture\LoadFundingStatusData()); $loader->addFixture(new \ProjectTest\Fixture\LoadIdeaDocumentData()); $loader->addFixture(new \ProjectTest\Fixture\LoadIdeaImageData()); $loader->addFixture(new \ProjectTest\Fixture\LoadIdeaDescriptionData()); $loader->addFixture(new \ProjectTest\Fixture\LoadInviteData()); $loader->addFixture(new \ProjectTest\Fixture\LoadProjectRationaleData()); $loader->addFixture(new \GeneralTest\Fixture\LoadWebInfoData()); $loader->addFixture(new \OrganisationTest\Fixture\LoadOrganisationData()); $purger = new ORMPurger(); $executor = new ORMExecutor($entityManager, $purger); $executor->execute($loader->getFixtures()); } }
public function testSchemaValidity() { $em = \Codeception\Module\Doctrine2::$em; $schema = new \Doctrine\ORM\Tools\SchemaValidator($em); $errors = $schema->validateMapping(); $valid = count($errors) == 0; if (!$valid) { \Codeception\Util\Debug::debug($errors); } $this->assertEquals(true, $valid); }
public static function init() { $zf2ModulePaths = [dirname(dirname(__DIR__))]; if ($path = static::findParentPath('vendor')) { $zf2ModulePaths[] = $path; } if ($path = static::findParentPath('module')) { $zf2ModulePaths[] = $path; } if (($path = static::findParentPath('src')) !== $zf2ModulePaths[0]) { $zf2ModulePaths[] = $path; } static::initAutoloader(); $config = (include __DIR__ . '/../config/application.config.php'); $serviceManager = new ServiceManager(new ServiceManagerConfig()); $serviceManager->setService('ApplicationConfig', $config); $serviceManager->get('ModuleManager')->loadModules(); static::$serviceManager = $serviceManager; if (defined('TEST_SUITE') && constant('TEST_SUITE') == 'full') { $entityManager = $serviceManager->get('Doctrine\\ORM\\EntityManager'); //Validate the schema; $validator = new \Doctrine\ORM\Tools\SchemaValidator($entityManager); $errors = $validator->validateMapping(); if (count($errors) > 0) { foreach ($errors as $entity => $errors) { echo "Error in Entity: '" . $entity . "':\n"; echo implode("\n", $errors); echo "\n"; } die; } //Create the schema $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager); $mdFactory = $entityManager->getMetadataFactory(); $mdFactory->getAllMetadata(); $tool->dropDatabase(); $tool->createSchema($mdFactory->getAllMetadata()); $loader = new Loader(); $purger = new ORMPurger(); $executor = new ORMExecutor($entityManager, $purger); $executor->execute($loader->getFixtures()); } }
/** * Development / Helper Method for Schema Validation. */ public static function validateSchema() { $em = self::getEntityManager(); $validator = new \Doctrine\ORM\Tools\SchemaValidator($em); $errors = $validator->validateMapping(); \Koch\Debug\Debug::printR($errors); }
protected function validateSchema() { $em = $this->cx->getDb()->getEntityManager(); $validator = new \Doctrine\ORM\Tools\SchemaValidator($em); $errors = $validator->validateMapping(); $exit = 0; if ($errors) { foreach ($errors as $className => $errorMessages) { echo "[Mapping] FAIL - The entity-class '" . $className . "' mapping is invalid:\n"; foreach ($errorMessages as $errorMessage) { echo '* ' . $errorMessage . "\n"; } echo "\n"; } $exit += 1; } else { echo '[Mapping] OK - The mapping files are correct.' . "\n"; } if (!$validator->schemaInSyncWithMetadata()) { echo '[Database] FAIL - The database schema is not in sync with the current mapping file.' . "\n"; $exit += 2; } else { echo '[Database] OK - The database schema is in sync with the mapping files.' . "\n"; } return $exit; }
/** * * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { $error = false; $jazzeeConfiguration = new \Jazzee\Configuration(); $entityManager = $this->getHelper('em')->getEntityManager(); $stub = new AdminStub(); $stub->em = $entityManager; $stub->config = $jazzeeConfiguration; $requiredExtensions = array('ldap', 'apc', 'curl', 'json', 'imagick', 'mbstring', 'xml', 'dom'); $missing = array(); foreach ($requiredExtensions as $re) { if (!extension_loaded($re)) { $missing[] = $re; } } if (count($missing)) { $error = true; foreach ($missing as $m) { $output->write("<error>The PHP {$m} extension is required and it is not installed.</error>" . PHP_EOL); } } //Check that the var direcotry is working $path = $jazzeeConfiguration->getVarPath() ? $jazzeeConfiguration->getVarPath() : __DIR__ . '/../../../var'; if (!($realPath = \realpath($path)) or !\is_dir($realPath)) { if ($realPath) { $path = $realPath; //nicer error message if the path exists } $error = true; $output->write("<error>{$path} is does not exist so we cannot use it as the 'var' directory</error>" . PHP_EOL); } $perms = \substr(\sprintf('%o', \fileperms($realPath)), -4); $owner = \fileowner($realPath); $group = \filegroup($realPath); if (function_exists('posix_getpwuid')) { $arr = posix_getpwuid($owner); $owner = $arr['name']; } if (function_exists('posix_getgrgid')) { $arr = posix_getgrgid($group); $group = $arr['name']; } $output->write("<comment>{$realPath} is owned by {$owner}:{$group} and has permissions {$perms}. Ensure your webserver can write to that directory</comment>" . PHP_EOL); //Check that the schema is correct $validator = new \Doctrine\ORM\Tools\SchemaValidator($entityManager); $errors = $validator->validateMapping(); if ($errors) { $error = true; foreach ($errors as $className => $errorMessages) { $output->write("<error>The entity-class '" . $className . "' mapping is invalid:</error>" . PHP_EOL); foreach ($errorMessages as $errorMessage) { $output->write('* ' . $errorMessage . PHP_EOL); } $output->write(PHP_EOL); } } if (!$validator->schemaInSyncWithMetadata()) { $error = true; $output->write('<error>The database schema is not correct. Run "setup update" to fix this.</error>' . PHP_EOL); } try { $entityManager->getConfiguration()->ensureProductionSettings(); $entityManager->getConnection()->connect(); } catch (\Exception $e) { $error = true; $output->writeln('<error>' . $e->getMessage() . '</error>'); } if ($jazzeeConfiguration->getStatus() == 'DEVELOPMENT') { $error = true; $output->write("<error>Jazzee is in developer mode.</error>" . PHP_EOL); } else { //Check that the cache is setup if (!extension_loaded('apc')) { $error = true; $output->write("<error>APC is required for caching, but it it not installed.</error>" . PHP_EOL); } $metadatas = $entityManager->getMetadataFactory()->getAllMetadata(); $path = $entityManager->getConfiguration()->getProxyDir(); if (!is_dir($path)) { $directory = dirname($path); if (\realpath($directory)) { $directory = \realpath($directory); } $base = basename($path); if (!\is_writable($directory)) { $error = true; $output->write("<error>We do not have permission to create directory {$base} in {$directory}</error>" . PHP_EOL); } else { mkdir($path, 0777, true); } } if (!$error) { $proxyDir = \realpath($path); if (!\is_writable($proxyDir)) { $error = true; $output->write("<error>We do not have permission to write to {$proxyDir}.</error>" . PHP_EOL); } else { $entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxyDir); } } if (!apc_clear_cache() || !apc_clear_cache('user') || !apc_clear_cache('opcode')) { $output->write("<error>Error Clearning APC Cache</error>" . PHP_EOL); } } try { //Test the Authentication service $class = $jazzeeConfiguration->getAdminAuthenticationClass(); $adminAuthentication = new $class($stub); if (!$adminAuthentication instanceof \Jazzee\Interfaces\AdminAuthentication) { $error = true; $output->write("<error>{$class} does not implement AdminAuthentication Interface.</error>" . PHP_EOL); } //Test the directory service $class = $jazzeeConfiguration->getAdminDirectoryClass(); $adminDirectory = new $class($stub); if (!$adminDirectory instanceof \Jazzee\Interfaces\AdminDirectory) { $error = true; $output->write("<error>{$class} does not implement AdminDirectory Interface.</error>" . PHP_EOL); } // This isn't available until we can limit the search returned Issue #90 // $attributes = array( // $jazzeeConfiguration->getLdapLastNameAttribute() => '*' // ); // $results = $adminDirectory->search($attributes); } catch (\Jazzee\Exception $e) { $error = true; $output->writeln('<error>' . $e->getMessage() . '</error>'); } if (!class_exists('HTMLPurifier')) { $error = true; $output->write("<error>HTML Purifier is required and it is not installed.</error>" . PHP_EOL); } if (!class_exists('\\Doctrine\\ORM\\Version')) { $error = true; $output->write("<error>Doctrine ORM is required and it is not installed.</error>" . PHP_EOL); } if (!class_exists('\\Monolog\\Logger')) { $error = true; $output->write("<error>Monolog is required and it is not installed.</error>" . PHP_EOL); } if ($error) { $output->write(PHP_EOL . "<error>Preflight Check Failed</error>" . PHP_EOL); } else { $output->write(PHP_EOL . "<info>Preflight Check Passed</info>" . PHP_EOL); } }
public function processValues() { /** * 2) Create database. * * Has the user requested to create the database? */ if (isset($_POST['config']['database']['create_database']) and $_POST['config']['database']['create_database'] == 'on') { try { // connection without dbname (must be blank for create table) $connectionParams = array('user' => $_POST['config']['database']['user'], 'password' => $_POST['config']['database']['password'], 'host' => $_POST['config']['database']['host'], 'driver' => $_POST['config']['database']['driver']); $config = new \Doctrine\DBAL\Configuration(); $connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config); $connection->setCharset('UTF8'); /** * fetch doctrine schema manager * and create database */ $schema_manager = $connection->getSchemaManager(); $schema_manager->createDatabase($_POST['config']['database']['dbname']); /** * Another way of doing this is via the specific database platform command. * Then for creating the database the platform is asked, which SQL CMD to use. * For "pdo_mysql" it would result in a string like 'CREATE DATABASE name'. */ #$db = $connection->getDatabasePlatform(); #$sql = $db->getCreateDatabaseSQL('databasename'); #$connection->exec($sql); // Drop Connection. unset($connection); } catch (\Exception $e) { // force return $this->setStep(4); $error = $this->language['ERROR_WHILE_CREATING_DATABASE'] . NL . NL; $error .= $e->getMessage() . '.'; $this->setErrorMessage($error); } } /** * 3) Connect to Database */ // Setup Connection Parameters. This time with "dbname". $connectionParams = array('dbname' => $_POST['config']['database']['dbname'], 'user' => $_POST['config']['database']['user'], 'password' => $_POST['config']['database']['password'], 'host' => $_POST['config']['database']['host'], 'driver' => $_POST['config']['database']['driver'], 'prefix' => $_POST['config']['database']['prefix']); $entityManager = Helper::getDoctrineEntityManager($connectionParams); /** * 4) Validate Database Schemas */ try { // instantiate validator $validator = new \Doctrine\ORM\Tools\SchemaValidator($entityManager); // validate $validation_error = $validator->validateMapping(); // handle validation errors if ($validation_error) { // @todo this is experimental... $this->setErrorMessage(var_export($validation_error, false)); } } catch (Exception $e) { // force return $this->setStep(4); $error = $this->language['ERROR_NO_DB_CONNECT'] . NL . $e->getMessage(); $this->setErrorMessage($error); } /** * 5) Insert/Update Schemas * * "recreate" will do a database drop, before schemas are updated. */ try { $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($entityManager); $metadata = $entityManager->getMetadataFactory()->getAllMetadata(); if (isset($_GET['recreate'])) { $schemaTool->dropSchema($metadata); } $schemaTool->updateSchema($metadata); $entityManager->flush(); } catch (Exception $e) { $html = ''; $html .= 'The update failed!' . NL; $html .= 'Do you want to force a database drop (' . $connectionParams['dbname'] . ')?' . NL; $html .= 'This will result in a total loss of all data and database tables.' . NL; $html .= 'It will allow for an clean installation of the database.' . NL; $html .= 'WARNING: Act carefully!' . NL; $html .= '<form action="index.php?step=4&recreate=true" method="post">'; $html .= '<input type="submit" value="Recreate Database" class="retry"></form>'; // force return $this->setStep(4); $error = $this->language['ERROR_NO_DB_CONNECT'] . NL . $e->getMessage(); $error .= NL . NL . $html; $this->setErrorMessage($error); } /** * 6. Write Settings to clansuite.config.php */ if (false === Helper::write_config_settings($_POST['config'])) { // force return $this->setStep(4); $error = 'Config not written.' . NL; $this->setErrorMessage($error); } }
// obtaining the entity manager (7) $evm = new Doctrine\Common\EventManager(); $entityManager = \Doctrine\ORM\EntityManager::create($conn, $config, $evm); // check if the database exists if (!is_file($conn["path"])) { if (!is_dir(dirname($conn["path"]))) { mkdir(dirname($conn["path"])); } $tool = new \Doctrine\ORM\Tools\SchemaTool($entityManager); //find all classes in entities $dir = opendir(__DIR__ . '/model'); $classes = array(); while (false !== ($entry = readdir($dir))) { if (strlen($entry) > 4 && substr($entry, -4) == ".php") { $className = 'Model\\' . substr($entry, 0, strlen($entry) - 4); $classes[] = $entityManager->getClassMetadata($className); } } $tool->createSchema($classes); $validator = new \Doctrine\ORM\Tools\SchemaValidator($entityManager); $errors = $validator->validateMapping(); if (count($errors) > 0) { foreach ($errors as $e) { // Lots of errors! echo implode("\n\n", $e); } unlink(__DIR__ . "/tmp/db.sqlite"); exit; } include __DIR__ . "/exampleData.php"; }