public function register(Application $application) { $applicationConfig = $application['app_config']; $providerConfig = $applicationConfig['service_providers']['salvo']; //load twig extensions $application['twig']->addExtension(new Extension\Twig($application)); //see if we need to register the unit test namespace if (defined('UNIT_TESTING') && UNIT_TESTING === true) { $applicationConfig['autoloader']->registerNamespace('SalvoTests', __DIR__ . '/../vendor/salvo/salvo/tests'); } //barrage configuration file is required for barrage to work if (!isset($providerConfig['barrage_configuration_file_path'])) { throw new \Exception('Configuration file path not given for Barrage'); } else { if (!file_exists(SALVO_ROOT_PATH . '/' . $providerConfig['barrage_configuration_file_path'])) { $filePath = SALVO_ROOT_PATH . '/' . $providerConfig['barrage_configuration_file_path']; throw new \Exception("Unable to locate the configuration file given for Barrage ({$filePath})"); } } \Salvo\Barrage\Configuration::load(SALVO_ROOT_PATH . '/' . $providerConfig['barrage_configuration_file_path']); //barrage console configuration file is required for barrage to work if (!isset($providerConfig['barrage_console_configuration_file_path'])) { throw new \Exception('Console configuration file path not given for Barrage'); } else { if (!file_exists(SALVO_ROOT_PATH . '/' . $providerConfig['barrage_console_configuration_file_path'])) { $filePath = SALVO_ROOT_PATH . '/' . $providerConfig['barrage_console_configuration_file_path']; throw new \Exception("Unable to locate the console configuration file given for Barrage ({$filePath})"); } } \Salvo\Barrage\Configuration::load(SALVO_ROOT_PATH . '/' . $providerConfig['barrage_console_configuration_file_path']); $application['session']->start(); }
/** * @static * @param $configurationName * @return IDataSource */ public static function buildFromConfiguration($configurationName) { //get the connection data object $connectionData = ConnectionDataFactory::buildFromConfiguration($configurationName); //figure out which driver we need to build the data source object from $dataSourceConfiguration = Configuration::getDataSourceConfiguration($configurationName); $dataSourceClassName = 'Salvo\\Barrage\\DataSource\\Relational\\Driver\\' . $dataSourceConfiguration['driver'] . '\\' . 'DataSource'; return $dataSourceClassName::getInstance($connectionData); }
public function __construct() { $host = '127.0.0.1'; $username = '******'; $password = ''; $database = ''; $testDatabaseConnection = Mysql\DataSource::getInstance(new Mysql\ConnectionData($host, $username, $password, $database)); parent::__construct($testDatabaseConnection->getPdoConnection()); \Salvo\Barrage\Configuration::load(__DIR__ . '/../../configuration.yml'); }
/** * @static * @param $configurationName * @return IConnectionData */ public static function buildFromConfiguration($configurationName) { $dataSourceConfiguration = Configuration::getDataSourceConfiguration($configurationName); $connectionDataClassName = 'Salvo\\Barrage\\DataSource\\Relational\\Driver\\' . $dataSourceConfiguration['driver'] . '\\' . 'ConnectionData'; $host = $dataSourceConfiguration['host']; $username = $dataSourceConfiguration['username']; $password = $dataSourceConfiguration['password']; $database = $dataSourceConfiguration['database']; $port = !empty($dataSourceConfiguration['port']) ? $dataSourceConfiguration['port'] : null; $options = !empty($dataSourceConfiguration['options']) ? $dataSourceConfiguration['options'] : array(); return new $connectionDataClassName($host, $username, $password, $database, $port, $options); }
/** * Constructor * * @param string $host The host of the server * @param string $username The connection username * @param string $password The connection password * @param string $database The database to connect to by default * @param int|null $port The port the server is listen to * @param array $options PDO options * @return \Salvo\Barrage\DataSource\Relational\Driver\Mysql\ConnectionData */ public function __construct($host, $username, $password, $database, $port = null, $options = array()) { $this->host = $host; $this->username = $username; $this->password = $password; $this->database = \Salvo\Barrage\Configuration::getRealDatabaseName($database); $this->port = !empty($port) ? $port : self::DEFAULT_PORT; $convertedOptions = array(); if (!empty($options)) { foreach ($options as $option => $value) { $convertedOptions[constant($option)] = $value; } } $this->options = $convertedOptions; }
/** * Create an array will the valid items for search and replacing with templates * * @static * * @param $type * @param $database * @param $table * @param $class * @param $namespace * * @return array * * @throws \Exception */ private static function buildSearchReplaceArray($type, $database, $table, $class, $namespace) { $database = Configuration::getTrueDatabaseName($database); $builderConfiguration = Configuration::getOption('model_builder'); $tableConfiguration = $builderConfiguration['relational']['databases'][$database]['tables']; $tableAlias = !empty($tableConfiguration[$table]['alias']) ? $tableConfiguration[$table]['alias'] : $table; $dataSource = DataSourceFactory::buildFromConfiguration('default'); $parsingTokens = array(); $stringReplaceArray = array(); if ($type == 'full') { foreach (self::$templateTokens as $tokens) { $parsingTokens = array_merge($parsingTokens, $tokens); } } else { if (array_key_exists($type, self::$templateTokens)) { $parsingTokens = self::$templateTokens[$type]; } else { throw new \Exception("Invalid type ({$type}) for building token list"); } } $autoIncrementField = null; $primaryKeyArray = array(); $tableArray = array('name' => $table, 'alias' => $tableAlias); $fieldsArray = array(); $skipSaveMembersArray = !empty($tableConfiguration[$table]['skip_save_members']) ? $tableConfiguration[$table]['skip_save_members'] : array(); $tableFieldDetails = $dataSource->getTableFieldsDetails($table, $database); foreach ($tableFieldDetails as $fieldDetails) { if ($fieldDetails['auto_increment'] === true) { $autoIncrementField = $fieldDetails['field']; } if ($fieldDetails['key_type'] == 'primary') { $primaryKeyArray[] = $fieldDetails['field']; } $memberNameParts = explode('_', RegexHelper::toUnderscore($fieldDetails['field'])); $memberName = ''; foreach ($memberNameParts as $part) { $memberName .= ucwords(strtolower($part)); } $memberName = lcfirst($memberName); $fieldsArray[$memberName] = array('name' => $fieldDetails['field']); if (in_array($fieldDetails['field_type'], array('enum', 'set'))) { $fieldsArray[$memberName]['values'] = $dataSource->getFieldValues($table, $fieldDetails['field'], $database); } } //add in join fields if (!empty($tableConfiguration[$table]['join_fields'])) { foreach ($tableConfiguration[$table]['join_fields'] as $joinTable => $fields) { foreach ($fields as $options) { $memberName = !empty($options['member_name']) ? $options['member_name'] : $options['field']; $field = $options['field']; $as = $options['field']; if (!empty($options['as'])) { $as = $options['as']; } else { if (!empty($options['member_name'])) { $as = $options['member_name']; } } $joinFieldData = array('name' => $field, 'join_table' => $joinTable); if ($as != $options['field']) { $joinFieldData['name'] .= ' AS ' . $as; } $fieldsArray[$memberName] = $joinFieldData; } } } foreach ($parsingTokens as $token) { $trueValue = null; switch ($token) { case 'namespace': $trueValue = $namespace; break; case 'class': $trueValue = $class; break; case 'database': $trueValue = $database; break; case 'primaryKeyArray': $trueValue = self::arrayToPhpCodeString($primaryKeyArray); break; case 'autoIncrementField': $trueValue = $autoIncrementField; break; case 'tableArray': $trueValue = self::arrayToPhpCodeString($tableArray); break; case 'joinsArray': $joinsArray = array(); if (!empty($tableConfiguration[$table]['joins'])) { foreach ($tableConfiguration[$table]['joins'] as $joinTable => $config) { $temp['alias'] = !empty($tableConfiguration[$joinTable]['alias']) ? $tableConfiguration[$joinTable]['alias'] : $joinTable; $temp['type'] = !empty($config['type']) ? $config['type'] : 'inner'; $temp['on'] = "`{$temp['alias']}`.`{$config['join_field']}` = `{$tableAlias}`.`{$config['field']}`"; if (!empty($config['database'])) { $temp['database'] = $config['database']; } $joinsArray[$joinTable] = $temp; } } $trueValue = self::arrayToPhpCodeString($joinsArray); break; case 'fieldsArray': $trueValue = self::arrayToPhpCodeString($fieldsArray); break; case 'dataSourceConfiguration': $trueValue = 'default'; break; case 'skipSaveMembersArray': $trueValue = self::arrayToPhpCodeString($skipSaveMembersArray); break; case 'fields': $trueValue = ''; foreach ($fieldsArray as $member => $options) { if (!empty($trueValue)) { $trueValue .= "\n"; } else { $trueValue .= "\n\n"; } $trueValue .= " protected \${$member};"; } break; default: throw new \Exception("Token passed ({$token}) is not a valid token"); break; } $stringReplaceArray[self::$tokenWrapper . $token . self::$tokenWrapper] = $trueValue; } return $stringReplaceArray; }
public function __construct() { parent::__construct(); $this->trueDatabase1 = Configuration::getRealDatabaseName($this->database1); $this->trueDatabase2 = Configuration::getRealDatabaseName($this->database2); }
/** * @test */ public function getTrueDatabaseName() { $this->assertEquals('TrueTest', \Salvo\Barrage\Configuration::getTrueDatabaseName('TrueTest2')); }
/** * The implementation of what the command should do when executed * * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output) { $builderConfiguration = Configuration::getOption('model_builder'); $basePath = $builderConfiguration['base_source_path']; $basePath = substr($basePath, 0, 1) === DIRECTORY_SEPARATOR ? $basePath : __DIR__ . DIRECTORY_SEPARATOR . $basePath; /*echo "\n\n"; var_dump($basePath); echo "\n\n"; exit();*/ $defaultNamespace = $builderConfiguration['relational']['default_namespace']; $dataSource = DataSourceFactory::buildFromConfiguration('default'); $options = $input->getOptions(); $databases = $options['database'] ? array($options['database']) : array(); if (empty($databases)) { foreach ($builderConfiguration['relational']['databases'] as $databaseName => $databaseOptions) { $databases[] = $databaseName; } } foreach ($databases as $database) { $tableConfiguration = $builderConfiguration['relational']['databases'][$database]['tables']; $table = $input->getArgument('table'); if (!empty($table)) { $tables = array($input->getArgument('table')); } else { $tables = $dataSource->getTables($database); } $dialog = $this->getHelperSet()->get('dialog'); $output->writeln(''); $output->writeln("Writing models for {$database} database:"); foreach ($tables as $table) { if (isset($tableConfiguration[$table])) { $classDefault = !empty($tableConfiguration[$table]['class_name']) ? $tableConfiguration[$table]['class_name'] : null; //todo: add in the ability to get class name during this process if one if not set $class = $options['default'] === true ? $classDefault : $options['class']; if (!empty($class)) { $namespace = $options['default'] === true ? $builderConfiguration['relational']['default_namespace'] : $options['namespace']; $namespace .= "\\{$database}"; while (empty($namespace)) { if ($namespace === null) { $output->writeln('You must specify a namespace for the class'); } $message = "What would you like the namespace name for class {$class} to be"; if (!empty($defaultNamespace)) { $message .= ' [' . $defaultNamespace . ']'; } $namespace = $dialog->ask($output, "{$message}? "); if (!empty($defaultNamespace) && empty($namespace)) { $namespace = $defaultNamespace; } } if (empty($database)) { $output->writeln("ERROR: Can't build model without database being specified int he command of in the connection\\s configuration"); return; } $namespaceParts = explode('\\', $namespace); $extraFilePath = implode('/', $namespaceParts); $filePath = "{$basePath}/{$extraFilePath}/{$class}.php"; //make sure that directory exists if (!is_dir("{$basePath}/{$extraFilePath}")) { //todo: make directory mode configurable mkdir("{$basePath}/{$extraFilePath}", 0777, true); } if (file_exists($filePath)) { $phpCode = \Salvo\Barrage\Utility\ModelBuilder::updateModelClass($filePath, $database, $table, $class, $namespace); } else { $phpCode = \Salvo\Barrage\Utility\ModelBuilder::buildModelClass($database, $table, $class, $namespace); } $this->writeFile($filePath, $phpCode); $output->writeln("Writing model for the {$table} table as class {$class} to {$filePath}"); } } } $output->writeln(''); } }
/** * Generate a sql where condition * * @param $key * @param $options * @param $fromAlias * * @return string * * @throws \Salvo\Barrage\DataSource\Relational\Exception\RelationalSqlException */ private function getWhereCondition($key, $options, $fromAlias) { /** * Allows us to parse simple sql like where statements when used as values for fields. Supported conditional types: * * = * != * > * >= * < * <= * like * notlike * in * notin * between */ if (empty($options) && $options !== null) { return ''; } if (is_string($options)) { $statementParts = explode(' ', trim($options), 2); switch ($statementParts[0]) { case '=': case '!=': case '>': case '>=': case '<': case '<=': case 'like': case 'notlike': $options = array('condition' => $statementParts[0], 'value' => str_replace("'", '', $statementParts[1])); break; case 'in': case 'notin': $condition = $statementParts[0] == 'in' ? '=' : '!='; $values = explode(',', $statementParts[1]); $options = array('condition' => $condition, 'value' => $values); break; case 'between': $values = explode(' and ', $statementParts[1]); $options = array('condition' => $statementParts[0], 'value' => $values); break; default: break; } } if (is_array($options) && !isset($options['value'])) { $options = array('value' => $options); } if (is_array($options) && (!empty($options['value']) || $options['value'] === null)) { $condition = !empty($options['condition']) ? $options['condition'] : '='; $alias = !empty($options['database']) ? \Salvo\Barrage\Configuration::getRealDatabaseName($options['database']) : $fromAlias; $value = $options['value']; if (!$this->validateWhereCondition($condition)) { throw new RelationalSqlException("Invalid where condition given : {$condition}"); } switch ($condition) { case '=': if ($value !== null) { $condition = is_array($value) ? 'IN' : $condition; $value = is_array($value) ? '(' . $this->arrayToCleanStringSql($value) . ')' : " '{$value}'"; $condition = $condition . $value; } else { $condition = 'IS NULL'; } break; case '!=': if ($value !== null) { $condition = is_array($value) ? 'NOT IN' : $condition; $value = is_array($value) ? '(' . $this->arrayToCleanStringSql($value) . ')' : " '{$value}'"; $condition = $condition . $value; } else { $condition = 'IS NOT NULL'; } break; case 'between': if (empty($value[0]) || empty($value[1])) { throw new RelationalSqlException("Between requires the value that is passed is an array with 2 values"); } $value1 = $this->cleanQuote($value[0]); $value2 = $this->cleanQuote($value[1]); $condition = strtoupper($condition) . ' ' . $value1 . ' AND ' . $value2; break; default: $value = $this->cleanQuote($value); $condition = strtoupper($condition) . ' ' . $value; break; } } else { $alias = $fromAlias; /*if(is_array($options)) { $value = $this->arrayToCleanStringSql($options); $condition = '= ' . $value; } else */ if ($options === null) { $condition = 'IS NULL'; } else { $value = $this->cleanQuote($options); $condition = '= ' . $value; } } //if the dot character (.) is not present, assume it is associated to the main table otherwise, assume the key is fully qualified and escaped properly if (strpos($key, '.') === false) { return "`{$alias}`.`{$key}` {$condition}"; } else { return $key . ' ' . $condition; } }
protected function getDatabaseName($database) { $database = !empty($database) ? $database : $this->defaultDatabase; //return $database; return \Salvo\Barrage\Configuration::getRealDatabaseName($database); }