/**
  * Adds a virtual host name to the hosts file of the host system.
  *
  * @param VirtualHost[] $vhosts
  */
 public function addServerToHostsFile(array $vhosts)
 {
     // Get the docker-machine VM ip address.
     $dockerMachineIpAddress = Application::getDocker()->getDockerMachineIpAddress('default');
     $vhostServerNames = [];
     foreach ($vhosts as $vhost) {
         $vhostServerNames[] = $vhost->getServerName();
     }
     $vhostServerNames = join(' ', $vhostServerNames);
     $found = false;
     $hosts = file('/etc/hosts');
     if ($hosts) {
         foreach ($hosts as $line) {
             $line = str_replace(array("\t", '#'), ' ', $line);
             preg_match_all('#^(.*?) (.*)$#', $line, $matches);
             if (!empty($matches[1][0]) && !empty($matches[2][0])) {
                 $ip = trim($matches[1][0]);
                 $host = trim($matches[2][0]);
                 if ($ip == $dockerMachineIpAddress && $host == $vhostServerNames) {
                     $found = true;
                     break;
                 }
             }
         }
         if (!$found) {
             $process = new Process(sprintf('sudo sh -c "echo \'%s %s\' >> /etc/hosts"', $dockerMachineIpAddress, $vhostServerNames . ' '));
             $process->setTty(true);
             $process->run();
             print $process->getOutput();
         }
     }
 }
 /**
  * Wrapper method to ask for input with optional validation.
  *
  * @param string $question
  *      The question to ask.
  *
  * @param \commpress\Cli\InputInterface $input
  *      The input interface.
  * @param \commpress\Cli\OutputInterface $output
  *      The output interface.
  * @param closure|null $validator
  *      (Optional) The closure for the validation.
  *
  * @return string
  *      The answer.
  */
 public static function ask($question, InputInterface $input, OutputInterface $output, $validator = null)
 {
     $question = new Question($question . ' ');
     if ($validator != null) {
         $question->setValidator($validator);
     }
     $helper = self::$instance->getHelperSet()->get('question');
     return $helper->ask($input, $output, $question);
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $acronym = $input->getArgument('acronym');
     $database = new ProjectDatabase(Application::getDatabase());
     try {
         $project = $database->getProjectByAcronym($acronym);
         $database->removeProject($project);
         $output->writeln(sprintf('<info>Successfully</info> unregistered project <info>%s</info>', $acronym));
     } catch (DatabaseQueryException $e) {
         $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Get the project.
     $database = new ProjectDatabase(Application::getDatabase());
     $acronym = $input->getArgument('project_acronym');
     $project = null;
     try {
         $project = $database->getProjectByAcronym($input->getArgument('project_acronym'));
         Application::getDocker()->removeEnvironment($project, $input->getArgument('feature_branch'));
     } catch (DatabaseQueryException $e) {
         $output->writeln(sprintf('Unable to find <error>project</error> by acronym <error>%s</error>.', $acronym));
     }
 }
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Read in the arguments.
     $acronym = $input->getArgument('project_acronym');
     $branch = $input->getArgument('feature_branch');
     $installProfile = $input->getArgument('drupal_install_profile');
     $project = null;
     try {
         // Get the project.
         $projectDatabase = new ProjectDatabase(Application::getDatabase());
         $project = $projectDatabase->getProjectByAcronym($input->getArgument('project_acronym'));
         // Create the docker environment.
         Application::getDocker()->createEnvironment($project, $branch, $installProfile);
     } catch (DockerManagerCreateEnvironmentException $e) {
         $output->writeln(sprintf('<error>Failed</error> to create <error>environment</error> [project: %s, branch: %s]', $acronym, $branch));
     } catch (DatabaseQueryException $e) {
         $output->writeln(sprintf('Unable to find <error>project</error> by acronym <error>%s</error>.', $acronym));
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     // Get all projects.
     try {
         $database = new ProjectDatabase(Application::getDatabase());
         $projects = $database->getProjects();
         if ($projects == array()) {
             $output->writeln('<comment>Currently there are no projects registered.</comment>');
             return;
         }
         $table = new Table($output);
         $table->setHeaders(['ID', 'Project', 'Acronym', 'Git URL', 'Web URL']);
         foreach ($projects as $project) {
             $table->addRow([$project->getId(), $project->getFullName(), $project->getShortName(), $project->getGitRepositoryUrl(), 'http://' . $project->getVhostName()]);
         }
         $table->render();
     } catch (DatabaseQueryException $e) {
         $output->writeln('<error>Failed to retrieve list of registered projects from database.</error>');
     }
 }
 /**
  * @{inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $question = '<info>Please enter the full name of the project:</info>';
     $name = Application::ask($question, $input, $output, function ($answer) {
         if ($answer == null) {
             throw new \RuntimeException('The name of the project can\'t be empty.');
         }
         return $answer;
     });
     $question = '<info>Please enter the short name (acronym) of the project:</info>';
     $acronym = Application::ask($question, $input, $output, function ($answer) {
         if ($answer == null) {
             throw new \RuntimeException('The acronym of the project can\'t be empty.');
         }
         return $answer;
     });
     $question = '<info>Please enter the git repository url:</info>';
     $repositoryUrl = Application::ask($question, $input, $output, function ($answer) {
         if ($answer == null) {
             throw new \RuntimeException('The git repository url can\'t be empty.');
         }
         return $answer;
     });
     $question = '<info>Please enter the url to be able to open the website in your browser:</info>';
     $webserverUrl = Application::ask($question, $input, $output, function ($answer) {
         if ($answer == null) {
             throw new \RuntimeException('The webserver url can\'t be empty.');
         }
         return $answer;
     });
     // Create a new Project
     $project = ProjectModel::buildEntity([Project::FIELD_NAME => $name, Project::FIELD_SHORT_NAME => $acronym, Project::FIELD_REPOSITORY_URL => $repositoryUrl, Project::FIELD_VHOST_NAME => $webserverUrl]);
     $model = new ProjectModel($project);
     $project = $model->persist();
     if ($project) {
         $output->writeln(sprintf('Project <info>%s</info> (Acronym: <info>%s</info>) successful registered.', $project->getFullName(), $project->getShortName()));
     } else {
         $output->writeln(sprintf('Failed to register project <error>%s</error> (Acronym: <error>%s</error>).', $project->getFullName(), $project->getShortName()));
     }
 }
Esempio n. 8
0
 /**
  * Prepares the data for statement execution.
  *
  * @param string $type
  *      The type can be either CREATE or UPDATE.
  * @param array $data
  *      The data array in field => value format.
  * @param $table
  *      The name of the database table.
  *
  * @return bool|\SQLite3Stmt
  *      The statement or false.
  */
 protected function prepareStatement($type, array $data, $table)
 {
     switch ($type) {
         case self::STMT_CREATE:
             $type = 'INSERT INTO';
             break;
         case self::STMT_UPDATE:
             break;
         default:
             return false;
     }
     $database = Application::getDatabase();
     $values = [];
     foreach ($data as $field => $value) {
         $values[':' . $field] = $value;
     }
     // Create the query.
     $query = sprintf('%s %s (%s) VALUES (%s)', $type, $table, join(',', array_keys($data)), join(',', array_keys($values)));
     $stmt = $database->prepare($query);
     foreach ($values as $key => $value) {
         $stmt->bindValue($key, $value);
     }
     return $stmt;
 }
 /**
  * Checks if the entity by id exists already in the database.
  *
  * @return bool
  *      TRUE if the entity is stored in the database, otherwise false.
  */
 public function entityExists()
 {
     // Before we ask the database we want to make sure we have an id.
     if ($this->environment->getId() == null) {
         // No database request is needed in this case.
         return false;
     }
     // Define the query.
     $query = sprintf('SELECT COUNT(id) AS num FROM environments WHERE %s = :id', Environment::FIELD_ID);
     // Get the database instance.
     $database = Application::getDatabase();
     // Prepare the statement.
     $stmt = $database->prepare($query);
     $stmt->bindValue(':id', $this->environment->getId());
     // Get the result from statement execution.
     $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
     // Close the statement to free memory.
     $stmt->close();
     // Check if the project was found.
     if ($result['num'] >= 1) {
         return true;
     }
     return false;
 }
 /**
  * Creates virtual hosts and returns them.
  *
  * @return VirtualHost[]
  *      The created virtual hosts.
  */
 private function createVirtualHosts()
 {
     // Search for the platform configuration folder.
     $configFiles = Application::getPlatformConfigParser()->findConfigFiles($this->localProjectDirectory);
     $fs = Application::getFilesystem();
     $vhosts = $fs->getVirtualHostsFromConfig($configFiles, $this->project);
     $vHostDefinition = $fs->addVirtualHostToServer($vhosts);
     // 2. Start the required containers.
     $this->startProjectContainers($vhosts);
     $this->run(sprintf('docker exec -i %s sh -c "echo \'%s\' > %s"', 'web' . $this->serverSuffix, $vHostDefinition, '/usr/local/apache2/conf/extra/httpd-vhosts.conf'));
     // Restart the apache server in web container.
     $this->run(sprintf('docker exec -i %s sh -c "apachectl restart"', 'web' . $this->serverSuffix));
     foreach ($vhosts as $vhost) {
         $this->triggerVirtualHostDetectedEvent($vhost);
     }
     return $vhosts;
 }
Esempio n. 11
0
<?php

/**
 * @file
 * Contains container.php.
 */
use commpress\Cli\Application;
use commpress\Cli\Service\Database\Database;
use commpress\Cli\Service\Database\Exception\DatabaseNotFoundException;
use Symfony\Component\Filesystem\Filesystem;
$c = new \commpress\Cli\Service\DependencyInjection\DependencyInjectionContainer();
$c->addService('database', function () {
    $database = null;
    try {
        $envMgrPath = Application::getUserHomePath() . '/' . Application::ENVMGR_DIRECTORY;
        // Install the database file if not existing.
        $fs = new Filesystem();
        $fs->copy(Application::ROOT_DIR . '/app/resources/envmgr.db', $envMgrPath . '/envmgr.db');
        // Try to connect to the database.
        $database = new Database($envMgrPath . '/envmgr.db');
    } catch (DatabaseNotFoundException $e) {
        print sprintf('Error: %s' . "\n", $e->getMessage());
        exit;
    } catch (Exception $e) {
        print 'An unknown exception occured while trying to load the database.' . "\n";
        exit;
    }
    return $database;
});
$c->addService('docker', function () {
    return new \commpress\Cli\Service\Docker\DockerManager();