Code style fixes

This commit is contained in:
Dmitry Khomutov 2016-04-20 21:39:48 +06:00
parent 6c4c669492
commit 0868eb9c69
63 changed files with 1360 additions and 1441 deletions

View file

@ -5,424 +5,376 @@
*/
namespace b8\Database;
use b8\Database;
class Generator
{
protected $_db = null;
protected $_map = null;
protected $_tables = null;
protected $_ns = null;
protected $_path = null;
public function __construct(Database $db, $namespace, $path)
{
$this->_db = $db;
$this->_ns = $namespace;
$this->_path = $path;
$this->_map = new Map($this->_db);
$this->_tables = $this->_map->generate();
}
public function generate()
{
error_reporting(E_ERROR & E_WARNING);
$di = new \DirectoryIterator($this->_path);
$this->_todo = array(
'drop_fk' => array(),
'drop_index'=> array(),
'create' => array(),
'alter' => array(),
'add_index' => array(),
'add_fk' => array(),
);
foreach($di as $file)
{
if($file->isDot())
{
continue;
}
$fileName = explode('.', $file->getBasename());
if ($fileName[count($fileName)-1] != 'php')
{
continue;
}
$modelName = '\\' . $this->_ns . '\\Model\\Base\\' . str_replace('.php', '', $file->getFilename());
require_once($this->_path . $file->getFilename());
$model = new $modelName();
$columns = $model->columns;
$indexes = $model->indexes;
$foreignKeys = $model->foreignKeys;
$tableName = $model->getTableName();
if(!array_key_exists($tableName, $this->_tables))
{
$this->_createTable($tableName, $columns, $indexes, $foreignKeys);
continue;
}
else
{
$table = $this->_tables[$tableName];
$this->_updateColumns($tableName, $table, $columns);
$this->_updateRelationships($tableName, $table, $foreignKeys);
$this->_updateIndexes($tableName, $table, $indexes);
}
}
print 'DROP FK: ' . count($this->_todo['drop_fk']) . PHP_EOL;
print 'DROP INDEX: ' . count($this->_todo['drop_index']) . PHP_EOL;
print 'CREATE TABLE: ' . count($this->_todo['create']) . PHP_EOL;
print 'ALTER TABLE: ' . count($this->_todo['alter']) . PHP_EOL;
print 'ADD INDEX: ' . count($this->_todo['add_index']) . PHP_EOL;
print 'ADD FK: ' . count($this->_todo['add_fk']) . PHP_EOL;
$order = array_keys($this->_todo);
while($group = array_shift($order))
{
if(!isset($this->_todo[$group]) || !is_array($this->_todo[$group]) || !count($this->_todo[$group]))
{
continue;
}
foreach($this->_todo[$group] as $query)
{
try
{
//print $query . PHP_EOL;
$this->_db->query($query);
}
catch(\Exception $ex)
{
print 'FAILED TO EXECUTE: ' . $query . PHP_EOL;
print $ex->getMessage().PHP_EOL.PHP_EOL;
}
}
}
}
protected function _createTable($tbl, $cols, $idxs, $fks)
{
$defs = array();
$pks = array();
foreach($cols as $colName => $def)
{
$add = '`' . $colName . '` ' . $def['type'];
switch($def['type'])
{
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($def['length']) ? '(' . $def['length'] . ')' : '';
break;
}
if(empty($def['nullable']) || !$def['nullable'])
{
$add .= ' NOT NULL ';
}
if(!empty($def['default']))
{
$add .= ' DEFAULT ' . (is_numeric($def['default']) ? $def['default'] : '\'' . $def['default'] . '\'');
}
if(!empty($def['auto_increment']) && $def['auto_increment'])
{
$add .= ' AUTO_INCREMENT ';
}
if(!empty($def['primary_key']) && $def['primary_key'])
{
$pks[] = '`' . $colName . '`';
}
$defs[] = $add;
}
if(count($pks))
{
$defs[] = 'PRIMARY KEY (' . implode(', ', $pks) . ')';
}
$stmt = 'CREATE TABLE `' . $tbl . '` (' . PHP_EOL;
$stmt .= implode(", \n", $defs);
$stmt .= PHP_EOL . ') ENGINE=InnoDB DEFAULT CHARSET=utf8';
$stmt .= PHP_EOL;
$this->_todo['create'][] = $stmt;
foreach($idxs as $name => $idx)
{
$this->_addIndex($tbl, $name, $idx);
}
foreach($fks as $name => $fk)
{
$this->_addFk($tbl, $name, $fk);
}
}
protected function _updateColumns($tableName, $table, $columns)
{
$currentColumns = $table['columns'];
while($column = array_shift($currentColumns))
{
if(!array_key_exists($column['name'], $columns))
{
$this->_todo['alter'][$tableName.'.'.$column['name']] = 'ALTER TABLE `' . $tableName . '` DROP COLUMN `' . $column['name'] . '`';
}
else
{
$model = $columns[$column['name']];
$model['nullable'] = !isset($model['nullable']) ? false : $model['nullable'];
$model['default'] = !isset($model['default']) ? false : $model['default'];
$model['auto_increment'] = !isset($model['auto_increment']) ? false : $model['auto_increment'];
$model['primary_key'] = !isset($model['primary_key']) ? false : $model['primary_key'];
$column['is_primary_key'] = !isset($column['is_primary_key']) ? false : $column['is_primary_key'];
if( $column['type'] != $model['type'] ||
($column['length'] != $model['length'] && !in_array($model['type'], array('text', 'longtext', 'mediumtext', 'date', 'datetime', 'float'))) ||
$column['null'] != $model['nullable'] ||
$column['default'] != $model['default'] ||
$column['auto'] != $model['auto_increment'])
{
$this->_updateColumn($tableName, $column['name'], $column['name'], $model);
}
}
unset($columns[$column['name']]);
}
if(count($columns))
{
foreach($columns as $name => $model)
{
// Check if we're renaming a column:
if(isset($model['rename']))
{
unset($this->_todo['alter'][$tableName.'.'.$model['rename']]);
$this->_updateColumn($tableName, $model['rename'], $name, $model);
continue;
}
// New column
$add = '`' . $name . '` ' . $model['type'];;
switch($model['type'])
{
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($model['length']) ? '(' . $model['length'] . ')' : '';
break;
}
if(empty($model['nullable']) || !$model['nullable'])
{
$add .= ' NOT NULL ';
}
if(!empty($model['default']))
{
$add .= ' DEFAULT ' . (is_numeric($model['default']) ? $model['default'] : '\'' . $model['default'] . '\'');
}
if(!empty($model['auto_increment']) && $model['auto_increment'])
{
$add .= ' AUTO_INCREMENT ';
}
if(!empty($model['primary_key']) && $model['primary_key'] && !isset($table['indexes']['PRIMARY']))
{
$add .= ' PRIMARY KEY ';
}
$this->_todo['alter'][] = 'ALTER TABLE `' . $tableName . '` ADD COLUMN ' . $add;
}
}
}
protected function _updateColumn($tableName, $prevName, $newName, $model)
{
$add = '`' . $newName . '` ' . $model['type'];;
switch($model['type'])
{
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($model['length']) ? '(' . $model['length'] . ')' : '';
break;
}
if(empty($model['nullable']) || !$model['nullable'])
{
$add .= ' NOT NULL ';
}
if(!empty($model['default']))
{
$add .= ' DEFAULT ' . (is_numeric($model['default']) ? $model['default'] : '\'' . $model['default'] . '\'');
}
if(!empty($model['auto_increment']) && $model['auto_increment'])
{
$add .= ' AUTO_INCREMENT ';
}
$this->_todo['alter'][] = 'ALTER TABLE `' . $tableName . '` CHANGE COLUMN `' . $prevName . '` ' . $add;
}
protected function _updateRelationships($tableName, $table, $foreignKeys)
{
$current = $table['relationships']['toOne'];
while($foreignKey = array_shift($current))
{
if(!array_key_exists($foreignKey['fk_name'], $foreignKeys))
{
$this->_dropFk($tableName, $foreignKey['fk_name']);
}
elseif( $foreignKey['from_col'] != $foreignKeys[$foreignKey['fk_name']]['local_col'] ||
$foreignKey['table'] != $foreignKeys[$foreignKey['fk_name']]['table'] ||
$foreignKey['col'] != $foreignKeys[$foreignKey['fk_name']]['col'] ||
$foreignKey['fk_update'] != $foreignKeys[$foreignKey['fk_name']]['update'] ||
$foreignKey['fk_delete'] != $foreignKeys[$foreignKey['fk_name']]['delete'])
{
$this->_alterFk($tableName, $foreignKey['fk_name'], $foreignKeys[$foreignKey['fk_name']]);
}
unset($foreignKeys[$foreignKey['fk_name']]);
}
if(count($foreignKeys))
{
foreach($foreignKeys as $name => $foreignKey)
{
// New column
$this->_addFk($tableName, $name, $foreignKey);
}
}
}
protected function _updateIndexes($tableName, $table, $indexes)
{
$current = $table['indexes'];
while($index = array_shift($current))
{
if(!array_key_exists($index['name'], $indexes))
{
$this->_dropIndex($tableName, $index['name']);
}
elseif( $index['unique'] != $indexes[$index['name']]['unique'] ||
$index['columns'] != $indexes[$index['name']]['columns'])
{
$this->_alterIndex($tableName, $index['name'], $index);
}
unset($indexes[$index['name']]);
}
if(count($indexes))
{
foreach($indexes as $name => $index)
{
if($name == 'PRIMARY')
{
continue;
}
// New index
$this->_addIndex($tableName, $name, $index);
}
}
}
protected function _addIndex($table, $name, $idx, $stage = 'add_index')
{
if($name == 'PRIMARY')
{
return;
}
$q = 'CREATE ' . (isset($idx['unique']) && $idx['unique'] ? 'UNIQUE' : '') . ' INDEX `' . $name . '` ON `' . $table . '` (' . $idx['columns'] . ')';
$this->_todo[$stage][] = $q;
}
protected function _alterIndex($table, $name, $idx, $stage = 'index')
{
$this->_dropIndex($table, $name, $stage);
$this->_addIndex($table, $name, $idx, $stage);
}
protected function _dropIndex($table, $idxName, $stage = 'drop_index')
{
if($idxName == 'PRIMARY')
{
return;
}
$q = 'DROP INDEX `' . $idxName . '` ON `' . $table . '`';
$this->_todo[$stage][] = $q;
}
protected function _addFk($table, $name, $fk)
{
$q = 'ALTER TABLE `' . $table . '` ADD CONSTRAINT `' . $name . '` FOREIGN KEY (`' . $fk['local_col'] . '`) REFERENCES `'.$fk['table'].'` (`'.$fk['col'].'`)';
if(!empty($fk['delete']))
{
$q .= ' ON DELETE ' . $fk['delete'] . ' ';
}
if(!empty($fk['update']))
{
$q .= ' ON UPDATE ' . $fk['update'] . ' ';
}
$this->_todo['add_fk'][] = $q;
}
protected function _alterFk($table, $name, $fk)
{
$this->_dropFk($table, $name);
$this->_addFk($table, $name, $fk);
}
protected function _dropFk($table, $name)
{
$q = 'ALTER TABLE `'.$table.'` DROP FOREIGN KEY `' . $name . '`';
$this->_todo['drop_fk'][] = $q;
}
protected $_db = null;
protected $_map = null;
protected $_tables = null;
protected $_ns = null;
protected $_path = null;
public function __construct(Database $db, $namespace, $path)
{
$this->_db = $db;
$this->_ns = $namespace;
$this->_path = $path;
$this->_map = new Map($this->_db);
$this->_tables = $this->_map->generate();
}
public function generate()
{
error_reporting(E_ERROR & E_WARNING);
$di = new \DirectoryIterator($this->_path);
$this->_todo = [
'drop_fk' => [],
'drop_index' => [],
'create' => [],
'alter' => [],
'add_index' => [],
'add_fk' => [],
];
foreach ($di as $file) {
if ($file->isDot()) {
continue;
}
$fileName = explode('.', $file->getBasename());
if ($fileName[count($fileName) - 1] != 'php') {
continue;
}
$modelName = '\\' . $this->_ns . '\\Model\\Base\\' . str_replace('.php', '', $file->getFilename());
require_once($this->_path . $file->getFilename());
$model = new $modelName();
$columns = $model->columns;
$indexes = $model->indexes;
$foreignKeys = $model->foreignKeys;
$tableName = $model->getTableName();
if (!array_key_exists($tableName, $this->_tables)) {
$this->_createTable($tableName, $columns, $indexes, $foreignKeys);
continue;
} else {
$table = $this->_tables[$tableName];
$this->_updateColumns($tableName, $table, $columns);
$this->_updateRelationships($tableName, $table, $foreignKeys);
$this->_updateIndexes($tableName, $table, $indexes);
}
}
print 'DROP FK: ' . count($this->_todo['drop_fk']) . PHP_EOL;
print 'DROP INDEX: ' . count($this->_todo['drop_index']) . PHP_EOL;
print 'CREATE TABLE: ' . count($this->_todo['create']) . PHP_EOL;
print 'ALTER TABLE: ' . count($this->_todo['alter']) . PHP_EOL;
print 'ADD INDEX: ' . count($this->_todo['add_index']) . PHP_EOL;
print 'ADD FK: ' . count($this->_todo['add_fk']) . PHP_EOL;
$order = array_keys($this->_todo);
while ($group = array_shift($order)) {
if (!isset($this->_todo[$group]) || !is_array($this->_todo[$group]) || !count($this->_todo[$group])) {
continue;
}
foreach ($this->_todo[$group] as $query) {
try {
//print $query . PHP_EOL;
$this->_db->query($query);
} catch (\Exception $ex) {
print 'FAILED TO EXECUTE: ' . $query . PHP_EOL;
print $ex->getMessage() . PHP_EOL . PHP_EOL;
}
}
}
}
protected function _createTable($tbl, $cols, $idxs, $fks)
{
$defs = [];
$pks = [];
foreach ($cols as $colName => $def) {
$add = '`' . $colName . '` ' . $def['type'];
switch ($def['type']) {
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($def['length']) ? '(' . $def['length'] . ')' : '';
break;
}
if (empty($def['nullable']) || !$def['nullable']) {
$add .= ' NOT NULL ';
}
if (!empty($def['default'])) {
$add .= ' DEFAULT ' . (is_numeric($def['default']) ? $def['default'] : '\'' . $def['default'] . '\'');
}
if (!empty($def['auto_increment']) && $def['auto_increment']) {
$add .= ' AUTO_INCREMENT ';
}
if (!empty($def['primary_key']) && $def['primary_key']) {
$pks[] = '`' . $colName . '`';
}
$defs[] = $add;
}
if (count($pks)) {
$defs[] = 'PRIMARY KEY (' . implode(', ', $pks) . ')';
}
$stmt = 'CREATE TABLE `' . $tbl . '` (' . PHP_EOL;
$stmt .= implode(", \n", $defs);
$stmt .= PHP_EOL . ') ENGINE=InnoDB DEFAULT CHARSET=utf8';
$stmt .= PHP_EOL;
$this->_todo['create'][] = $stmt;
foreach ($idxs as $name => $idx) {
$this->_addIndex($tbl, $name, $idx);
}
foreach ($fks as $name => $fk) {
$this->_addFk($tbl, $name, $fk);
}
}
protected function _updateColumns($tableName, $table, $columns)
{
$currentColumns = $table['columns'];
while ($column = array_shift($currentColumns)) {
if (!array_key_exists($column['name'], $columns)) {
$this->_todo['alter'][$tableName . '.' . $column['name']] = 'ALTER TABLE `' . $tableName . '` DROP COLUMN `' . $column['name'] . '`';
} else {
$model = $columns[$column['name']];
$model['nullable'] = !isset($model['nullable']) ? false : $model['nullable'];
$model['default'] = !isset($model['default']) ? false : $model['default'];
$model['auto_increment'] = !isset($model['auto_increment']) ? false : $model['auto_increment'];
$model['primary_key'] = !isset($model['primary_key']) ? false : $model['primary_key'];
$column['is_primary_key'] = !isset($column['is_primary_key']) ? false : $column['is_primary_key'];
if (
$column['type'] != $model['type'] || (
$column['length'] != $model['length'] &&
!in_array($model['type'], ['text', 'longtext', 'mediumtext', 'date', 'datetime', 'float'])
) ||
$column['null'] != $model['nullable'] ||
$column['default'] != $model['default'] ||
$column['auto'] != $model['auto_increment']
) {
$this->_updateColumn($tableName, $column['name'], $column['name'], $model);
}
}
unset($columns[$column['name']]);
}
if (count($columns)) {
foreach ($columns as $name => $model) {
// Check if we're renaming a column:
if (isset($model['rename'])) {
unset($this->_todo['alter'][$tableName . '.' . $model['rename']]);
$this->_updateColumn($tableName, $model['rename'], $name, $model);
continue;
}
// New column
$add = '`' . $name . '` ' . $model['type'];;
switch ($model['type']) {
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($model['length']) ? '(' . $model['length'] . ')' : '';
break;
}
if (empty($model['nullable']) || !$model['nullable']) {
$add .= ' NOT NULL ';
}
if (!empty($model['default'])) {
$add .= ' DEFAULT ' . (is_numeric($model['default']) ? $model['default'] : '\'' . $model['default'] . '\'');
}
if (!empty($model['auto_increment']) && $model['auto_increment']) {
$add .= ' AUTO_INCREMENT ';
}
if (!empty($model['primary_key']) && $model['primary_key'] && !isset($table['indexes']['PRIMARY'])) {
$add .= ' PRIMARY KEY ';
}
$this->_todo['alter'][] = 'ALTER TABLE `' . $tableName . '` ADD COLUMN ' . $add;
}
}
}
protected function _updateColumn($tableName, $prevName, $newName, $model)
{
$add = '`' . $newName . '` ' . $model['type'];;
switch ($model['type']) {
case 'text':
case 'longtext':
case 'mediumtext':
case 'date':
case 'datetime':
case 'float':
$add .= '';
break;
default:
$add .= !empty($model['length']) ? '(' . $model['length'] . ')' : '';
break;
}
if (empty($model['nullable']) || !$model['nullable']) {
$add .= ' NOT NULL ';
}
if (!empty($model['default'])) {
$add .= ' DEFAULT ' . (is_numeric($model['default']) ? $model['default'] : '\'' . $model['default'] . '\'');
}
if (!empty($model['auto_increment']) && $model['auto_increment']) {
$add .= ' AUTO_INCREMENT ';
}
$this->_todo['alter'][] = 'ALTER TABLE `' . $tableName . '` CHANGE COLUMN `' . $prevName . '` ' . $add;
}
protected function _updateRelationships($tableName, $table, $foreignKeys)
{
$current = $table['relationships']['toOne'];
while ($foreignKey = array_shift($current)) {
if (!array_key_exists($foreignKey['fk_name'], $foreignKeys)) {
$this->_dropFk($tableName, $foreignKey['fk_name']);
} elseif ($foreignKey['from_col'] != $foreignKeys[$foreignKey['fk_name']]['local_col'] ||
$foreignKey['table'] != $foreignKeys[$foreignKey['fk_name']]['table'] ||
$foreignKey['col'] != $foreignKeys[$foreignKey['fk_name']]['col'] ||
$foreignKey['fk_update'] != $foreignKeys[$foreignKey['fk_name']]['update'] ||
$foreignKey['fk_delete'] != $foreignKeys[$foreignKey['fk_name']]['delete']
) {
$this->_alterFk($tableName, $foreignKey['fk_name'], $foreignKeys[$foreignKey['fk_name']]);
}
unset($foreignKeys[$foreignKey['fk_name']]);
}
if (count($foreignKeys)) {
foreach ($foreignKeys as $name => $foreignKey) {
// New column
$this->_addFk($tableName, $name, $foreignKey);
}
}
}
protected function _updateIndexes($tableName, $table, $indexes)
{
$current = $table['indexes'];
while ($index = array_shift($current)) {
if (!array_key_exists($index['name'], $indexes)) {
$this->_dropIndex($tableName, $index['name']);
} elseif ($index['unique'] != $indexes[$index['name']]['unique'] ||
$index['columns'] != $indexes[$index['name']]['columns']
) {
$this->_alterIndex($tableName, $index['name'], $index);
}
unset($indexes[$index['name']]);
}
if (count($indexes)) {
foreach ($indexes as $name => $index) {
if ($name == 'PRIMARY') {
continue;
}
// New index
$this->_addIndex($tableName, $name, $index);
}
}
}
protected function _addIndex($table, $name, $idx, $stage = 'add_index')
{
if ($name == 'PRIMARY') {
return;
}
$q = 'CREATE ' . (isset($idx['unique']) && $idx['unique'] ? 'UNIQUE' : '') . ' INDEX `' . $name . '` ON `' . $table . '` (' . $idx['columns'] . ')';
$this->_todo[$stage][] = $q;
}
protected function _alterIndex($table, $name, $idx, $stage = 'index')
{
$this->_dropIndex($table, $name, $stage);
$this->_addIndex($table, $name, $idx, $stage);
}
protected function _dropIndex($table, $idxName, $stage = 'drop_index')
{
if ($idxName == 'PRIMARY') {
return;
}
$q = 'DROP INDEX `' . $idxName . '` ON `' . $table . '`';
$this->_todo[$stage][] = $q;
}
protected function _addFk($table, $name, $fk)
{
$q = 'ALTER TABLE `' . $table . '` ADD CONSTRAINT `' . $name . '` FOREIGN KEY (`' . $fk['local_col'] . '`) REFERENCES `' . $fk['table'] . '` (`' . $fk['col'] . '`)';
if (!empty($fk['delete'])) {
$q .= ' ON DELETE ' . $fk['delete'] . ' ';
}
if (!empty($fk['update'])) {
$q .= ' ON UPDATE ' . $fk['update'] . ' ';
}
$this->_todo['add_fk'][] = $q;
}
protected function _alterFk($table, $name, $fk)
{
$this->_dropFk($table, $name);
$this->_addFk($table, $name, $fk);
}
protected function _dropFk($table, $name)
{
$q = 'ALTER TABLE `' . $table . '` DROP FOREIGN KEY `' . $name . '`';
$this->_todo['drop_fk'][] = $q;
}
}

View file

@ -1,12 +1,13 @@
<?php
namespace b8\Database;
use b8\Database;
class Map
{
protected $_db = null;
protected $_tables = array();
protected $_db = null;
protected $_tables = [];
public function __construct(Database $db)
{
@ -18,10 +19,9 @@ class Map
$tables = $this->_getTables();
foreach($tables as $table)
{
$this->_tables[$table] = array();
$this->_tables[$table]['php_name'] = $this->_generatePhpName($table);
foreach ($tables as $table) {
$this->_tables[$table] = [];
$this->_tables[$table]['php_name'] = $this->_generatePhpName($table);
}
$this->_getRelationships();
@ -35,10 +35,9 @@ class Map
{
$details = $this->_db->getDetails();
$rtn = array();
$rtn = [];
foreach($this->_db->query('SHOW TABLES')->fetchAll(\PDO::FETCH_ASSOC) as $tbl)
{
foreach ($this->_db->query('SHOW TABLES')->fetchAll(\PDO::FETCH_ASSOC) as $tbl) {
$rtn[] = $tbl['Tables_in_' . $details['db']];
}
@ -47,47 +46,63 @@ class Map
protected function _getRelationships()
{
foreach($this->_tables as $table => $t)
{
$res = $this->_db->query('SHOW CREATE TABLE `'.$table.'`')->fetchAll(\PDO::FETCH_ASSOC);
foreach ($this->_tables as $table => $t) {
$res = $this->_db->query('SHOW CREATE TABLE `' . $table . '`')->fetchAll(\PDO::FETCH_ASSOC);
foreach($res as $r)
{
foreach ($res as $r) {
$str = $r['Create Table'];
$matches = array();
if(preg_match_all('/CONSTRAINT\s+\`([a-zA-Z0-9_]+)\`\s+FOREIGN\s+KEY\s+\(\`([a-zA-Z0-9_]+)\`\)\s+REFERENCES\s+\`([a-zA-Z0-9_]+)\`\s+\(\`([a-zA-Z0-9_]+)\`\)(\s+ON (DELETE|UPDATE) (SET NULL|NO ACTION|CASCADE|RESTRICT))?(\s+ON (DELETE|UPDATE) (SET NULL|NO ACTION|CASCADE|RESTRICT))?/', $str, $matches))
{
for($i = 0; $i < count($matches[0]); $i++)
{
$fromTable = $table;
$fromCol = $matches[2][$i];
$toTable = $matches[3][$i];
$toCol = $matches[4][$i];
$fkName = $matches[1][$i];
$fk = array();
$matches = [];
if (preg_match_all('/CONSTRAINT\s+\`([a-zA-Z0-9_]+)\`\s+FOREIGN\s+KEY\s+\(\`([a-zA-Z0-9_]+)\`\)\s+REFERENCES\s+\`([a-zA-Z0-9_]+)\`\s+\(\`([a-zA-Z0-9_]+)\`\)(\s+ON (DELETE|UPDATE) (SET NULL|NO ACTION|CASCADE|RESTRICT))?(\s+ON (DELETE|UPDATE) (SET NULL|NO ACTION|CASCADE|RESTRICT))?/',
$str, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$fromTable = $table;
$fromCol = $matches[2][$i];
$toTable = $matches[3][$i];
$toCol = $matches[4][$i];
$fkName = $matches[1][$i];
$fk = [];
if(isset($matches[6][$i]))
{
if (isset($matches[6][$i])) {
$fk[$matches[6][$i]] = $matches[7][$i];
}
if(isset($matches[9][$i]))
{
if (isset($matches[9][$i])) {
$fk[$matches[9][$i]] = $matches[10][$i];
}
$fk['UPDATE'] = empty($fk['UPDATE']) ? '' : $fk['UPDATE'];
$fk['DELETE'] = empty($fk['DELETE']) ? '' : $fk['DELETE'];
if(isset($this->_tables[$fromTable]) && isset($this->_tables[$toTable]))
{
if (isset($this->_tables[$fromTable]) && isset($this->_tables[$toTable])) {
$phpName = $this->_generateFkName($fromCol, $this->_tables[$fromTable]['php_name']);
$this->_tables[$fromTable]['relationships']['toOne'][$fromCol] = array('fk_name' => $fkName, 'fk_delete' => $fk['DELETE'], 'fk_update' => $fk['UPDATE'], 'table_php_name' => $this->_tables[$toTable]['php_name'], 'from_col_php' => $this->_generatePhpName($fromCol), 'from_col' => $fromCol, 'php_name' => $phpName, 'table' => $toTable, 'col' => $toCol, 'col_php' => $this->_generatePhpName($toCol));
$this->_tables[$fromTable]['relationships']['toOne'][$fromCol] = [
'fk_name' => $fkName,
'fk_delete' => $fk['DELETE'],
'fk_update' => $fk['UPDATE'],
'table_php_name' => $this->_tables[$toTable]['php_name'],
'from_col_php' => $this->_generatePhpName($fromCol),
'from_col' => $fromCol,
'php_name' => $phpName,
'table' => $toTable,
'col' => $toCol,
'col_php' => $this->_generatePhpName($toCol)
];
$phpName = $this->_generateFkName($fromCol, $this->_tables[$fromTable]['php_name']) . $this->_tables[$fromTable]['php_name'].'s';
$this->_tables[$toTable]['relationships']['toMany'][] = array('from_col_php' => $this->_generatePhpName($fromCol), 'php_name' => $phpName, 'thisCol' => $toCol, 'table' => $fromTable, 'table_php' => $this->_generatePhpName($fromTable), 'fromCol' => $fromCol, 'col_php' => $this->_generatePhpName($toCol));
$phpName = $this->_generateFkName(
$fromCol,
$this->_tables[$fromTable]['php_name']
) . $this->_tables[$fromTable]['php_name'] . 's';
$this->_tables[$toTable]['relationships']['toMany'][] = [
'from_col_php' => $this->_generatePhpName($fromCol),
'php_name' => $phpName,
'thisCol' => $toCol,
'table' => $fromTable,
'table_php' => $this->_generatePhpName($fromTable),
'fromCol' => $fromCol,
'col_php' => $this->_generatePhpName($toCol)
];
}
}
}
@ -97,12 +112,10 @@ class Map
protected function _getColumns()
{
foreach($this->_tables as $key => &$val)
{
$cols = array();
foreach($this->_db->query('DESCRIBE `' . $key . '`')->fetchAll(\PDO::FETCH_ASSOC) as $column)
{
$col = $this->_processColumn(array(), $column, $val);
foreach ($this->_tables as $key => &$val) {
$cols = [];
foreach ($this->_db->query('DESCRIBE `' . $key . '`')->fetchAll(\PDO::FETCH_ASSOC) as $column) {
$col = $this->_processColumn([], $column, $val);
$cols[$col['name']] = $col;
}
@ -113,25 +126,21 @@ class Map
protected function _getIndexes()
{
foreach($this->_tables as $key => &$val)
{
$indexes = array();
foreach ($this->_tables as $key => &$val) {
$indexes = [];
foreach($this->_db->query('SHOW INDEXES FROM `' . $key . '`')->fetchAll(\PDO::FETCH_ASSOC) as $idx)
{
if(!isset($indexes[$idx['Key_name']]))
{
$indexes[$idx['Key_name']] = array();
$indexes[$idx['Key_name']]['name'] = $idx['Key_name'];
$indexes[$idx['Key_name']]['unique'] = ($idx['Non_unique'] == '0') ? true : false;
$indexes[$idx['Key_name']]['columns'] = array();
foreach ($this->_db->query('SHOW INDEXES FROM `' . $key . '`')->fetchAll(\PDO::FETCH_ASSOC) as $idx) {
if (!isset($indexes[$idx['Key_name']])) {
$indexes[$idx['Key_name']] = [];
$indexes[$idx['Key_name']]['name'] = $idx['Key_name'];
$indexes[$idx['Key_name']]['unique'] = ($idx['Non_unique'] == '0') ? true : false;
$indexes[$idx['Key_name']]['columns'] = [];
}
$indexes[$idx['Key_name']]['columns'][$idx['Seq_in_index']] = $idx['Column_name'];
}
$indexes = array_map(function($idx)
{
$indexes = array_map(function ($idx) {
ksort($idx['columns']);
$idx['columns'] = implode(', ', $idx['columns']);
@ -144,21 +153,20 @@ class Map
protected function _processColumn($col, $column, &$table)
{
$col['name'] = $column['Field'];
$col['php_name']= $this->_generatePhpName($col['name']);
$matches = array();
$col['name'] = $column['Field'];
$col['php_name'] = $this->_generatePhpName($col['name']);
$matches = [];
preg_match('/^([a-zA-Z]+)(\()?([0-9\,]+)?(\))?/', $column['Type'], $matches);
$col['type'] = strtolower($matches[1]);
$col['type'] = strtolower($matches[1]);
if(isset($matches[3]))
{
if (isset($matches[3])) {
$col['length'] = $matches[3];
}
$col['null'] = strtolower($column['Null']) == 'yes' ? true : false;
$col['auto'] = strtolower($column['Extra']) == 'auto_increment' ? true : false;
$col['null'] = strtolower($column['Null']) == 'yes' ? true : false;
$col['auto'] = strtolower($column['Extra']) == 'auto_increment' ? true : false;
if ($column['Default'] == 'NULL' || is_null($column['Default'])) {
$col['default_is_null'] = true;
@ -167,63 +175,56 @@ class Map
$col['default'] = $column['Default'];
}
if(!empty($column['Key']))
{
if($column['Key'] == 'PRI')
{
$col['is_primary_key'] = true;
$table['primary_key'] = array('column' => $col['name'], 'php_name' => $col['php_name']);
if (!empty($column['Key'])) {
if ($column['Key'] == 'PRI') {
$col['is_primary_key'] = true;
$table['primary_key'] = ['column' => $col['name'], 'php_name' => $col['php_name']];
}
if($column['Key'] == 'PRI' || $column['Key'] == 'UNI')
{
$col['unique_indexed'] = true;
}
else
{
$col['many_indexed'] = true;
if ($column['Key'] == 'PRI' || $column['Key'] == 'UNI') {
$col['unique_indexed'] = true;
} else {
$col['many_indexed'] = true;
}
}
$col['validate']= array();
$col['validate'] = [];
if(!$col['null'])
{
if (!$col['null']) {
$col['validate_null'] = true;
}
switch($col['type'])
{
switch ($col['type']) {
case 'tinyint':
case 'smallint':
case 'int':
case 'mediumint':
case 'bigint':
$col['php_type'] = 'int';
$col['to_php'] = '_sqlToInt';
$col['validate_int']= true;
$col['php_type'] = 'int';
$col['to_php'] = '_sqlToInt';
$col['validate_int'] = true;
break;
case 'float':
case 'decimal':
$col['php_type'] = 'float';
$col['to_php'] = '_sqlToFloat';
$col['php_type'] = 'float';
$col['to_php'] = '_sqlToFloat';
$col['validate_float'] = true;
break;
case 'datetime':
case 'date':
$col['php_type'] = 'DateTime';
$col['to_php'] = '_sqlToDateTime';
$col['to_sql'] = '_dateTimeToSql';
$col['php_type'] = 'DateTime';
$col['to_php'] = '_sqlToDateTime';
$col['to_sql'] = '_dateTimeToSql';
$col['validate_date'] = true;
break;
case 'varchar':
case 'text':
default:
$col['php_type'] = 'string';
$col['validate_string'] = true;
$col['php_type'] = 'string';
$col['validate_string'] = true;
break;
}
@ -244,8 +245,7 @@ class Map
{
$fkMethod = substr($sqlName, 0, strripos($sqlName, '_'));
if(empty($fkMethod))
{
if (empty($fkMethod)) {
$fkMethod = (substr(strtolower($sqlName), -2) == 'id') ? substr($sqlName, 0, -2) : $tablePhpName;
}

View file

@ -1,21 +1,21 @@
<?php
namespace b8\Form\Element;
use b8\View,
b8\Form\Input;
use b8\View, b8\Form\Input;
class Select extends Input
{
protected $_options = array();
protected $_options = [];
public function setOptions(array $options)
{
$this->_options = $options;
}
public function setOptions(array $options)
{
$this->_options = $options;
}
protected function _onPreRender(View &$view)
{
parent::_onPreRender($view);
$view->options = $this->_options;
}
protected function _onPreRender(View &$view)
{
parent::_onPreRender($view);
$view->options = $this->_options;
}
}

View file

@ -1,106 +1,84 @@
<?php
namespace b8\Form;
use b8\Form\Element,
b8\Form\Input,
b8\View;
use b8\Form\Element, b8\View;
class FieldSet extends Element
{
protected $_children = array();
protected $_children = [];
public function getValues()
{
$rtn = array();
public function getValues()
{
$rtn = [];
foreach ($this->_children as $field) {
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
foreach($this->_children as $field)
{
if($field instanceof FieldSet)
{
$fieldName = $field->getName();
if (empty($fieldName)) {
$rtn = array_merge($rtn, $field->getValues());
} else {
$rtn[$fieldName] = $field->getValues();
}
} elseif ($field instanceof Input) {
if ($field->getName()) {
$rtn[$field->getName()] = $field->getValue();
}
}
}
if(empty($fieldName))
{
$rtn = array_merge($rtn, $field->getValues());
}
else
{
$rtn[$fieldName] = $field->getValues();
}
}
elseif($field instanceof Input)
{
if($field->getName())
{
$rtn[$field->getName()] = $field->getValue();
}
}
}
return $rtn;
}
return $rtn;
}
public function setValues(array $values)
{
foreach ($this->_children as $field) {
if ($field instanceof FieldSet) {
$fieldName = $field->getName();
public function setValues(array $values)
{
foreach($this->_children as $field)
{
if($field instanceof FieldSet)
{
$fieldName = $field->getName();
if (empty($fieldName) || !isset($values[$fieldName])) {
$field->setValues($values);
} else {
$field->setValues($values[$fieldName]);
}
} elseif ($field instanceof Input) {
$fieldName = $field->getName();
if(empty($fieldName) || !isset($values[$fieldName]))
{
$field->setValues($values);
}
else
{
$field->setValues($values[$fieldName]);
}
}
elseif($field instanceof Input)
{
$fieldName = $field->getName();
if (isset($values[$fieldName])) {
$field->setValue($values[$fieldName]);
}
}
}
}
if(isset($values[$fieldName]))
{
$field->setValue($values[$fieldName]);
}
}
}
}
public function addField(Element $field)
{
$this->_children[$field->getName()] = $field;
$field->setParent($this);
}
public function addField(Element $field)
{
$this->_children[$field->getName()] = $field;
$field->setParent($this);
}
public function validate()
{
$rtn = true;
public function validate()
{
$rtn = true;
foreach ($this->_children as $child) {
if (!$child->validate()) {
$rtn = false;
}
}
foreach($this->_children as $child)
{
if(!$child->validate())
{
$rtn = false;
}
}
return $rtn;
}
return $rtn;
}
protected function _onPreRender(View &$view)
{
$rendered = [];
foreach ($this->_children as $child) {
$rendered[] = $child->render();
}
protected function _onPreRender(View &$view)
{
$rendered = array();
foreach($this->_children as $child)
{
$rendered[] = $child->render();
}
$view->children = $rendered;
}
$view->children = $rendered;
}
public function getChildren()
{

View file

@ -1,16 +1,17 @@
<?php
namespace b8\Form;
use b8\Form\Element,
b8\View;
b8\View;
class Input extends Element
{
protected $_required = false;
protected $_pattern;
protected $_validator;
protected $_value;
protected $_error;
protected $_required = false;
protected $_pattern;
protected $_validator;
protected $_value;
protected $_error;
protected $_customError = false;
public static function create($name, $label, $required = false)
@ -23,89 +24,82 @@ class Input extends Element
return $el;
}
public function getValue()
{
return $this->_value;
}
public function getValue()
{
return $this->_value;
}
public function setValue($value)
{
$this->_value = $value;
public function setValue($value)
{
$this->_value = $value;
return $this;
}
}
public function getRequired()
{
return $this->_required;
}
public function getRequired()
{
return $this->_required;
}
public function setRequired($required)
{
$this->_required = (bool)$required;
public function setRequired($required)
{
$this->_required = (bool)$required;
return $this;
}
}
public function getValidator()
{
return $this->_validator;
}
public function getValidator()
{
return $this->_validator;
}
public function setValidator($validator)
{
if(is_callable($validator) || $validator instanceof \Closure)
{
$this->_validator = $validator;
}
public function setValidator($validator)
{
if (is_callable($validator) || $validator instanceof \Closure) {
$this->_validator = $validator;
}
return $this;
}
}
public function getPattern()
{
return $this->_pattern;
}
public function getPattern()
{
return $this->_pattern;
}
public function setPattern($pattern)
{
$this->_pattern = $pattern;
public function setPattern($pattern)
{
$this->_pattern = $pattern;
return $this;
}
}
public function validate()
{
if($this->getRequired() && empty($this->_value))
{
$this->_error = $this->getLabel() . ' is required.';
return false;
}
public function validate()
{
if ($this->getRequired() && empty($this->_value)) {
$this->_error = $this->getLabel() . ' is required.';
return false;
}
if($this->getPattern() && !preg_match('/'.$this->getPattern().'/', $this->_value))
{
$this->_error = 'Invalid value entered.';
return false;
}
if ($this->getPattern() && !preg_match('/' . $this->getPattern() . '/', $this->_value)) {
$this->_error = 'Invalid value entered.';
return false;
}
$validator = $this->getValidator();
$validator = $this->getValidator();
if(is_callable($validator))
{
try
{
call_user_func_array($validator, array($this->_value));
}
catch(\Exception $ex)
{
$this->_error = $ex->getMessage();
return false;
}
}
if (is_callable($validator)) {
try {
call_user_func_array($validator, [$this->_value]);
} catch (\Exception $ex) {
$this->_error = $ex->getMessage();
return false;
}
}
if ($this->_customError) {
return false;
}
return true;
}
return true;
}
public function setError($message)
{
@ -114,11 +108,11 @@ class Input extends Element
return $this;
}
protected function _onPreRender(View &$view)
{
$view->value = $this->getValue();
$view->error = $this->_error;
$view->pattern = $this->_pattern;
$view->required = $this->_required;
}
protected function _onPreRender(View &$view)
{
$view->value = $this->getValue();
$view->error = $this->_error;
$view->pattern = $this->_pattern;
$view->required = $this->_required;
}
}

View file

@ -5,18 +5,18 @@ namespace b8\Http;
class Request
{
/**
* @var array
*/
protected $params = array();
* @var array
*/
protected $params = [];
/**
* Request data.
*/
protected $data = array();
* Request data.
*/
protected $data = [];
/**
* Set up the request.
*/
* Set up the request.
*/
public function __construct()
{
$this->parseInput();
@ -40,7 +40,7 @@ class Request
}
// Remove index.php from the URL if it is present:
$path = str_replace(array('/index.php', 'index.php'), '', $path);
$path = str_replace(['/index.php', 'index.php'], '', $path);
// Also cut out the query string:
$path = explode('?', $path);
@ -50,22 +50,20 @@ class Request
}
/**
* Parse incoming variables, incl. $_GET, $_POST and also reads php://input for PUT/DELETE.
*/
* Parse incoming variables, incl. $_GET, $_POST and also reads php://input for PUT/DELETE.
*/
protected function parseInput()
{
$params = $_REQUEST;
if(!isset($_SERVER['REQUEST_METHOD']) || in_array($_SERVER['REQUEST_METHOD'], array('PUT', 'DELETE')))
{
if (!isset($_SERVER['REQUEST_METHOD']) || in_array($_SERVER['REQUEST_METHOD'], ['PUT', 'DELETE'])) {
$vars = file_get_contents('php://input');
if(!is_string($vars) || strlen(trim($vars)) === 0)
{
if (!is_string($vars) || strlen(trim($vars)) === 0) {
$vars = '';
}
$inputData = array();
$inputData = [];
parse_str($vars, $inputData);
$params = array_merge($params, $inputData);
@ -75,17 +73,17 @@ class Request
}
/**
* Returns all request parameters.
* @return array
*/
* Returns all request parameters.
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* Return a specific request parameter, or a default value if not set.
*/
* Return a specific request parameter, or a default value if not set.
*/
public function getParam($key, $default = null)
{
if (isset($this->params[$key])) {
@ -96,24 +94,24 @@ class Request
}
/**
* Set or override a request parameter.
*/
* Set or override a request parameter.
*/
public function setParam($key, $value = null)
{
$this->params[$key] = $value;
}
/**
* Set an array of request parameters.
*/
* Set an array of request parameters.
*/
public function setParams(array $params)
{
$this->params = array_merge($this->params, $params);
}
/**
* Un-set a specific parameter.
*/
* Un-set a specific parameter.
*/
public function unsetParam($key)
{
unset($this->params[$key]);

View file

@ -4,129 +4,128 @@ namespace b8\Http;
class Response
{
protected $data = array();
protected $data = [];
public function __construct(Response $createFrom = null)
{
if (!is_null($createFrom)) {
$this->data = $createFrom->getData();
}
}
public function __construct(Response $createFrom = null)
{
if (!is_null($createFrom)) {
$this->data = $createFrom->getData();
}
}
public function hasLayout()
{
return !isset($this->data['layout']) ? true : $this->data['layout'];
}
public function hasLayout()
{
return !isset($this->data['layout']) ? true : $this->data['layout'];
}
public function disableLayout()
{
$this->data['layout'] = false;
}
public function disableLayout()
{
$this->data['layout'] = false;
}
public function enableLayout()
{
$this->data['layout'] = true;
}
public function enableLayout()
{
$this->data['layout'] = true;
}
public function getData()
{
return $this->data;
}
public function getData()
{
return $this->data;
}
public function setResponseCode($code)
{
$this->data['code'] = (int)$code;
}
public function setResponseCode($code)
{
$this->data['code'] = (int)$code;
}
public function setHeader($key, $val)
{
$this->data['headers'][$key] = $val;
}
public function setHeader($key, $val)
{
$this->data['headers'][$key] = $val;
}
public function clearHeaders()
{
$this->data['headers'] = array();
}
public function clearHeaders()
{
$this->data['headers'] = [];
}
public function setContent($content)
{
$this->data['body'] = $content;
}
public function setContent($content)
{
$this->data['body'] = $content;
}
public function getContent()
{
return $this->data['body'];
}
public function getContent()
{
return $this->data['body'];
}
public function flush()
{
$this->sendResponseCode();
public function flush()
{
$this->sendResponseCode();
if (isset($this->data['headers'])) {
foreach ($this->data['headers'] as $header => $val) {
header($header . ': ' . $val, true);
}
}
return $this->flushBody();
}
if (isset($this->data['headers'])) {
foreach ($this->data['headers'] as $header => $val) {
header($header . ': ' . $val, true);
}
}
protected function sendResponseCode()
{
if (!isset($this->data['code'])) {
$this->data['code'] = 200;
}
return $this->flushBody();
}
switch ($this->data['code'])
{
// 300 class
case 301:
$text = 'Moved Permanently';
break;
case 302:
$text = 'Moved Temporarily';
break;
protected function sendResponseCode()
{
if (!isset($this->data['code'])) {
$this->data['code'] = 200;
}
// 400 class errors
case 400:
$text = 'Bad Request';
break;
case 401:
$text = 'Not Authorized';
break;
case 403:
$text = 'Forbidden';
break;
case 404:
$text = 'Not Found';
break;
switch ($this->data['code']) {
// 300 class
case 301:
$text = 'Moved Permanently';
break;
case 302:
$text = 'Moved Temporarily';
break;
// 500 class errors
case 500:
$text = 'Internal Server Error';
break;
// 400 class errors
case 400:
$text = 'Bad Request';
break;
case 401:
$text = 'Not Authorized';
break;
case 403:
$text = 'Forbidden';
break;
case 404:
$text = 'Not Found';
break;
// OK
case 200:
default:
$text = 'OK';
break;
}
// 500 class errors
case 500:
$text = 'Internal Server Error';
break;
header('HTTP/1.1 ' . $this->data['code'] . ' ' . $text, true, $this->data['code']);
}
// OK
case 200:
default:
$text = 'OK';
break;
}
protected function flushBody()
{
if (isset($this->data['body'])) {
return $this->data['body'];
}
header('HTTP/1.1 ' . $this->data['code'] . ' ' . $text, true, $this->data['code']);
}
return '';
}
protected function flushBody()
{
if (isset($this->data['body'])) {
return $this->data['body'];
}
public function __toString()
{
return $this->flush();
}
return '';
}
public function __toString()
{
return $this->flush();
}
}

View file

@ -6,25 +6,25 @@ use b8\Http\Response;
class JsonResponse extends Response
{
public function __construct(Response $createFrom = null)
{
parent::__construct($createFrom);
public function __construct(Response $createFrom = null)
{
parent::__construct($createFrom);
$this->setContent(array());
$this->setHeader('Content-Type', 'application/json');
}
$this->setContent([]);
$this->setHeader('Content-Type', 'application/json');
}
public function hasLayout()
{
return false;
}
public function hasLayout()
{
return false;
}
protected function flushBody()
{
if (isset($this->data['body'])) {
return json_encode($this->data['body']);
}
protected function flushBody()
{
if (isset($this->data['body'])) {
return json_encode($this->data['body']);
}
return json_encode(null);
}
return json_encode(null);
}
}

View file

@ -26,7 +26,7 @@ class Router
/**
* @var array
*/
protected $routes = array(array('route' => '/:controller/:action', 'callback' => null, 'defaults' => array()));
protected $routes = [['route' => '/:controller/:action', 'callback' => null, 'defaults' => []]];
public function __construct(Application $application, Request $request, Config $config)
{
@ -37,7 +37,7 @@ class Router
public function clearRoutes()
{
$this->routes = array();
$this->routes = [];
}
/**
@ -46,13 +46,13 @@ class Router
* @param callable $callback
* @throws \InvalidArgumentException
*/
public function register($route, $options = array(), $callback = null)
public function register($route, $options = [], $callback = null)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException('$callback must be callable.');
}
array_unshift($this->routes, array('route' => $route, 'callback' => $callback, 'defaults' => $options));
array_unshift($this->routes, ['route' => $route, 'callback' => $callback, 'defaults' => $options]);
}
public function dispatch()
@ -110,7 +110,13 @@ class Router
$thisArgs = $pathParts;
if ($routeMatches) {
$route = array('namespace' => $thisNamespace, 'controller' => $thisController, 'action' => $thisAction, 'args' => $thisArgs, 'callback' => $route['callback']);
$route = [
'namespace' => $thisNamespace,
'controller' => $thisController,
'action' => $thisAction,
'args' => $thisArgs,
'callback' => $route['callback']
];
if ($this->application->isValidRoute($route)) {
return $route;

View file

@ -1,65 +1,64 @@
<?php
namespace b8\Store;
use b8\Config;
class Factory
{
/**
* @var \b8\Store\Factory
*/
protected static $instance;
/**
* @var \b8\Store\Factory
*/
protected static $instance;
/**
* A collection of the stores currently loaded by the factory.
* @var \b8\Store[]
*/
protected $loadedStores = array();
/**
* A collection of the stores currently loaded by the factory.
* @var \b8\Store[]
*/
protected $loadedStores = [];
/**
* @return Factory
*/
public static function getInstance()
{
if(!isset(self::$instance))
{
self::$instance = new self();
}
/**
* @return Factory
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
return self::$instance;
}
/**
* @param $storeName string Store name (should match a model name).
*
* @return \b8\Store
*/
public static function getStore($storeName, $namespace = null)
{
$factory = self::getInstance();
return $factory->loadStore($storeName, $namespace);
}
/**
* @param $storeName string Store name (should match a model name).
*
* @return \b8\Store
*/
public static function getStore($storeName, $namespace = null)
{
$factory = self::getInstance();
return $factory->loadStore($storeName, $namespace);
}
protected function __construct()
{
}
protected function __construct()
{
}
/**
* @param $store
*
* @return \b8\Store;
*/
public function loadStore($store, $namespace = null)
{
if(!isset($this->loadedStores[$store]))
{
/**
* @param $store
*
* @return \b8\Store;
*/
public function loadStore($store, $namespace = null)
{
if (!isset($this->loadedStores[$store])) {
$namespace = is_null($namespace) ? Config::getInstance()->get('b8.app.namespace') : $namespace;
$class = $namespace . '\\Store\\' . $store . 'Store';
$obj = new $class();
$class = $namespace . '\\Store\\' . $store . 'Store';
$obj = new $class();
$this->loadedStores[$store] = $obj;
}
$this->loadedStores[$store] = $obj;
}
return $this->loadedStores[$store];
}
return $this->loadedStores[$store];
}
}

View file

@ -1,21 +1,25 @@
<?php
namespace b8\View;
use b8\View;
class Template extends View
{
public static $templateFunctions = array();
protected static $extension = 'html';
public static $templateFunctions = [];
protected static $extension = 'html';
public function __construct($viewCode)
{
$this->viewCode = $viewCode;
public function __construct($viewCode)
{
$this->viewCode = $viewCode;
if (!count(self::$templateFunctions)) {
self::$templateFunctions = array('include' => array($this, 'includeTemplate'), 'call' => array($this, 'callHelperFunction'));
self::$templateFunctions = [
'include' => [$this, 'includeTemplate'],
'call' => [$this, 'callHelperFunction']
];
}
}
}
public static function createFromFile($file, $path = null)
{
@ -42,113 +46,113 @@ class Template extends View
unset(self::$templateFunctions[$name]);
}
public function render()
{
return $this->parse($this->viewCode);
}
public function render()
{
return $this->parse($this->viewCode);
}
protected function parse($string)
{
$lastCond = null;
$keywords = array('ifnot', 'if', 'else', 'for', 'loop', '@', '/ifnot', '/if', '/for', '/loop');
protected function parse($string)
{
$lastCond = null;
$keywords = ['ifnot', 'if', 'else', 'for', 'loop', '@', '/ifnot', '/if', '/for', '/loop'];
foreach (self::$templateFunctions as $function => $handler) {
$keywords[] = $function;
}
$stack = array('children' => array(array('type' => 'string', 'body' => '')));
$stack['children'][0]['parent'] =& $stack;
$current =& $stack['children'][0];
$stack = ['children' => [['type' => 'string', 'body' => '']]];
$stack['children'][0]['parent'] =& $stack;
$current =& $stack['children'][0];
while (!empty($string)) {
$current['body'] .= $this->readUntil('{', $string);
while (!empty($string)) {
$current['body'] .= $this->readUntil('{', $string);
if (!empty($string)) {
$gotKeyword = false;
if (!empty($string)) {
$gotKeyword = false;
foreach($keywords as $keyword) {
$kwLen = strlen($keyword) + 1;
foreach ($keywords as $keyword) {
$kwLen = strlen($keyword) + 1;
if (substr($string, 0, $kwLen) == '{' . $keyword) {
$gotKeyword = true;
$item = array('type' => $keyword, 'cond' => '', 'children' => '');
$string = substr($string, $kwLen);
if (substr($string, 0, $kwLen) == '{' . $keyword) {
$gotKeyword = true;
$item = ['type' => $keyword, 'cond' => '', 'children' => ''];
$string = substr($string, $kwLen);
$cond = trim($this->readUntil('}', $string));
$item['cond'] = $cond;
$lastCond = $cond;
$string = substr($string, 1);
$cond = trim($this->readUntil('}', $string));
$item['cond'] = $cond;
$lastCond = $cond;
$string = substr($string, 1);
if (array_key_exists($keyword, self::$templateFunctions)) {
$item['function_name'] = $keyword;
$item['type'] = 'function';
}
$str = array('type' => 'string', 'body' => '');
$parent =& $current['parent'];
$str = ['type' => 'string', 'body' => ''];
$parent =& $current['parent'];
if (substr($current['body'], (0 - strlen(PHP_EOL))) === PHP_EOL) {
$current['body'] = substr($current['body'], 0, strlen($current['body']) - strlen(PHP_EOL));
}
if (substr($current['body'], (0 - strlen(PHP_EOL))) === PHP_EOL) {
$current['body'] = substr($current['body'], 0, strlen($current['body']) - strlen(PHP_EOL));
}
$item['parent'] =& $parent;
$item['parent'] =& $parent;
$parent['children'][] = $item;
$parent['children'][] = $item;
if ($keyword == '@' || $item['type'] == 'function') {
// If we're processing a variable, add a string to the parent and move up to that as current.
$parent['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1];
$current['parent'] =& $parent;
} elseif (substr($keyword, 0, 1) == '/') {
// If we're processing the end of a block (if/loop), add a string to the parent's parent and move up to that.
$parent =& $parent['parent'];
$parent['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1];
$current['parent'] =& $parent;
} else {
$parent['children'][count($parent['children']) - 1]['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1]['children'][0];
$current['parent'] =& $parent['children'][count($parent['children']) - 1];
}
if ($keyword == '@' || $item['type'] == 'function') {
// If we're processing a variable, add a string to the parent and move up to that as current.
$parent['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1];
$current['parent'] =& $parent;
} elseif (substr($keyword, 0, 1) == '/') {
// If we're processing the end of a block (if/loop), add a string to the parent's parent and move up to that.
$parent =& $parent['parent'];
$parent['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1];
$current['parent'] =& $parent;
} else {
$parent['children'][count($parent['children']) - 1]['children'][] = $str;
$current =& $parent['children'][count($parent['children']) - 1]['children'][0];
$current['parent'] =& $parent['children'][count($parent['children']) - 1];
}
break;
}
}
break;
}
}
if (!$gotKeyword) {
$current['body'] .= substr($string, 0, 1);
$string = substr($string, 1);
}
}
}
if (!$gotKeyword) {
$current['body'] .= substr($string, 0, 1);
$string = substr($string, 1);
}
}
}
return $this->processStack($stack);
}
return $this->processStack($stack);
}
protected function processStack($stack)
{
$res = '';
protected function processStack($stack)
{
$res = '';
while (count($stack['children'])) {
$current = array_shift($stack['children']);
while (count($stack['children'])) {
$current = array_shift($stack['children']);
switch ($current['type']) {
case 'string':
$res .= $current['body'];
break;
switch ($current['type']) {
case 'string':
$res .= $current['body'];
break;
case '@':
$res .= $this->doParseVar($current['cond']);
break;
case '@':
$res .= $this->doParseVar($current['cond']);
break;
case 'if':
$res .= $this->doParseIf($current['cond'], $current);
break;
case 'if':
$res .= $this->doParseIf($current['cond'], $current);
break;
case 'ifnot':
$res .= $this->doParseIfNot($current['cond'], $current);
break;
case 'ifnot':
$res .= $this->doParseIfNot($current['cond'], $current);
break;
case 'loop':
$res .= $this->doParseLoop($current['cond'], $current);
@ -161,64 +165,64 @@ class Template extends View
case 'function':
$res .= $this->doParseFunction($current);
break;
}
}
}
}
return $res;
}
return $res;
}
protected function readUntil($until, &$string)
{
$read = '';
protected function readUntil($until, &$string)
{
$read = '';
while (!empty($string)) {
$char = substr($string, 0, 1);
while (!empty($string)) {
$char = substr($string, 0, 1);
if ($char == $until) {
break;
}
if ($char == $until) {
break;
}
$read .= $char;
$string = substr($string, 1);
}
$read .= $char;
$string = substr($string, 1);
}
return $read;
}
return $read;
}
protected function doParseVar($var)
{
if($var == 'year')
{
return date('Y');
}
protected function doParseVar($var)
{
if ($var == 'year') {
return date('Y');
}
$val = $this->processVariableName($var);
return $val;
}
$val = $this->processVariableName($var);
return $val;
}
protected function doParseIf($condition, $stack)
{
protected function doParseIf($condition, $stack)
{
if ($this->ifConditionIsTrue($condition)) {
return $this->processStack($stack);
} else {
return '';
}
}
}
protected function doParseIfNot($condition, $stack)
{
protected function doParseIfNot($condition, $stack)
{
if (!$this->ifConditionIsTrue($condition)) {
return $this->processStack($stack);
} else {
return '';
}
}
}
protected function ifConditionIsTrue($condition)
{
$matches = array();
$matches = [];
if (preg_match('/([a-zA-Z0-9_\-\(\):\s.\"]+)\s+?([\!\=\<\>]+)?\s+?([a-zA-Z0-9\(\)_\-:\s.\"]+)?/', $condition, $matches)) {
if (preg_match('/([a-zA-Z0-9_\-\(\):\s.\"]+)\s+?([\!\=\<\>]+)?\s+?([a-zA-Z0-9\(\)_\-:\s.\"]+)?/', $condition,
$matches)) {
$left = is_numeric($matches[1]) ? intval($matches[1]) : $this->processVariableName($matches[1]);
$right = is_numeric($matches[3]) ? intval($matches[3]) : $this->processVariableName($matches[3]);
$operator = $matches[2];
@ -248,42 +252,40 @@ class Template extends View
}
}
protected function doParseLoop($var, $stack)
{
$working = $this->processVariableName($var);
protected function doParseLoop($var, $stack)
{
$working = $this->processVariableName($var);
if(is_null($working))
{
return '';
}
if (is_null($working)) {
return '';
}
if(!is_array($working))
{
$working = array($working);
}
if (!is_array($working)) {
$working = [$working];
}
$rtn = '';
foreach ($working as $key => $val) {
$rtn = '';
foreach ($working as $key => $val) {
// Make sure we support nesting loops:
$keyWas = isset($this->key) ? $this->key : null;
$valWas = isset($this->value) ? $this->value : null;
$itemWas = isset($this->item) ? $this->item : null;
$keyWas = isset($this->key) ? $this->key : null;
$valWas = isset($this->value) ? $this->value : null;
$itemWas = isset($this->item) ? $this->item : null;
// Set up the necessary variables within the stack:
$this->parent = $this;
$this->item = $val;
$this->parent = $this;
$this->item = $val;
$this->key = $key;
$this->value = $val;
$rtn .= $this->processStack($stack);
$rtn .= $this->processStack($stack);
// Restore state for any parent nested loops:
$this->item = $itemWas;
$this->key = $keyWas;
$this->value = $valWas;
}
}
return $rtn;
}
return $rtn;
}
/**
* Processes loops in templates, of the following styles:
@ -325,7 +327,7 @@ class Template extends View
// Process variable & incrementor / decrementor:
$parts[1] = trim($parts[1]);
$matches = array();
$matches = [];
if (preg_match('/([a-zA-Z0-9_]+)(\+\+|\-\-)/', $parts[1], $matches)) {
$varName = $matches[1];
$direction = $matches[2] == '++' ? 'increment' : 'decrement';
@ -367,8 +369,8 @@ class Template extends View
throw new \Exception('Invalid range in for loop: ' . $part);
}
public function processVariableName($varName)
{
public function processVariableName($varName)
{
// Case one - Test for function calls:
if (substr($varName, 0, 1) == '(' && substr($varName, -1) == ')') {
@ -403,23 +405,21 @@ class Template extends View
return null;
}
// Case five - Process as a variable:
$varPart = explode('.', $varName);
$thisPart = array_shift($varPart);
// Case five - Process as a variable:
$varPart = explode('.', $varName);
$thisPart = array_shift($varPart);
if(!array_key_exists($thisPart, $this->_vars))
{
return null;
}
if (!array_key_exists($thisPart, $this->_vars)) {
return null;
}
$working = $this->{$thisPart};
$working = $this->{$thisPart};
while(count($varPart))
{
$thisPart = array_shift($varPart);
while (count($varPart)) {
$thisPart = array_shift($varPart);
if(is_object($working)) {
if (is_object($working)) {
// Check if we're working with an actual property:
if (property_exists($working, $thisPart)) {
$working = $working->{$thisPart};
@ -434,34 +434,30 @@ class Template extends View
}
if(is_array($working) && array_key_exists($thisPart, $working))
{
$working = $working[$thisPart];
continue;
}
if (is_array($working) && array_key_exists($thisPart, $working)) {
$working = $working[$thisPart];
continue;
}
if($thisPart == 'toLowerCase')
{
$working = strtolower($working);
continue;
}
if ($thisPart == 'toLowerCase') {
$working = strtolower($working);
continue;
}
if($thisPart == 'toUpperCase')
{
$working = strtoupper($working);
continue;
}
if ($thisPart == 'toUpperCase') {
$working = strtoupper($working);
continue;
}
if ($thisPart == 'isNumeric')
{
return is_numeric($working);
}
if ($thisPart == 'isNumeric') {
return is_numeric($working);
}
return null;
}
return null;
}
return $working;
}
return $working;
}
protected function doParseFunction($stack)
{
@ -481,7 +477,7 @@ class Template extends View
protected function processFunctionArguments($args)
{
$rtn = array();
$rtn = [];
$args = explode(';', $args);
@ -515,7 +511,7 @@ class Template extends View
if (isset($args['variables'])) {
if (!is_array($args['variables'])) {
$args['variables'] = array($args['variables']);
$args['variables'] = [$args['variables']];
}
foreach ($args['variables'] as $variable) {

View file

@ -32,8 +32,8 @@ class Application extends b8\Application
public function init()
{
$request =& $this->request;
$route = '/:controller/:action';
$opts = array('controller' => 'Home', 'action' => 'index');
$route = '/:controller/:action';
$opts = ['controller' => 'Home', 'action' => 'index'];
// Inlined as a closure to fix "using $this when not in object context" on 5.3
$validateSession = function () {
@ -51,11 +51,11 @@ class Application extends b8\Application
return false;
};
$skipAuth = array($this, 'shouldSkipAuth');
$skipAuth = [$this, 'shouldSkipAuth'];
// Handler for the route we're about to register, checks for a valid session where necessary:
$routeHandler = function (&$route, Response &$response) use (&$request, $validateSession, $skipAuth) {
$skipValidation = in_array($route['controller'], array('session', 'webhook', 'build-status'));
$skipValidation = in_array($route['controller'], ['session', 'webhook', 'build-status']);
if (!$skipValidation && !$validateSession() && (!is_callable($skipAuth) || !$skipAuth())) {
if ($request->isAjax()) {
@ -121,10 +121,10 @@ class Application extends b8\Application
*/
protected function loadController($class)
{
$controller = parent::loadController($class);
$controller->layout = new View('layout');
$controller->layout->title = 'PHPCI';
$controller->layout->breadcrumb = array();
$controller = parent::loadController($class);
$controller->layout = new View('layout');
$controller->layout->title = 'PHPCI';
$controller->layout->breadcrumb = [];
return $controller;
}
@ -135,12 +135,12 @@ class Application extends b8\Application
*/
protected function setLayoutVariables(View &$layout)
{
$groups = array();
$groups = [];
$groupStore = b8\Store\Factory::getStore('ProjectGroup');
$groupList = $groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
$groupList = $groupStore->getWhere([], 100, 0, [], ['title' => 'ASC']);
foreach ($groupList['items'] as $group) {
$thisGroup = array('title' => $group->getTitle());
$thisGroup = ['title' => $group->getTitle()];
$projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$groups[] = $thisGroup;

View file

@ -35,7 +35,7 @@ class Builder implements LoggerAwareInterface
/**
* @var string[]
*/
public $ignore = array();
public $ignore = [];
/**
* @var string
@ -201,7 +201,7 @@ class Builder implements LoggerAwareInterface
$this->setupBuild();
// Run the core plugin stages:
foreach (array('setup', 'test') as $stage) {
foreach (['setup', 'test'] as $stage) {
$success &= $this->pluginExecutor->executePlugins($this->config, $stage);
}
@ -350,7 +350,7 @@ class Builder implements LoggerAwareInterface
* @param string $level
* @param array $context
*/
public function log($message, $level = LogLevel::INFO, $context = array())
public function log($message, $level = LogLevel::INFO, $context = [])
{
$this->buildLogger->log($message, $level, $context);
}

View file

@ -67,13 +67,13 @@ class DaemonCommand extends Command
'pid-file', 'p', InputOption::VALUE_REQUIRED,
'Path of the PID file',
implode(DIRECTORY_SEPARATOR,
array(PHPCI_DIR, 'daemon', 'daemon.pid'))
[PHPCI_DIR, 'daemon', 'daemon.pid'])
)
->addOption(
'log-file', 'l', InputOption::VALUE_REQUIRED,
'Path of the log file',
implode(DIRECTORY_SEPARATOR,
array(PHPCI_DIR, 'daemon', 'daemon.log'))
[PHPCI_DIR, 'daemon', 'daemon.log'])
);
}
@ -107,7 +107,7 @@ class DaemonCommand extends Command
{
$pid = $this->getRunningPid();
if ($pid) {
$this->logger->notice("Daemon already started", array('pid' => $pid));
$this->logger->notice("Daemon already started", ['pid' => $pid]);
return "alreadystarted";
}
@ -132,7 +132,7 @@ class DaemonCommand extends Command
return "notstarted";
}
$this->logger->notice("Daemon started", array('pid' => $pid));
$this->logger->notice("Daemon started", ['pid' => $pid]);
return "started";
}
@ -144,7 +144,7 @@ class DaemonCommand extends Command
return "notstarted";
}
$this->logger->info("Trying to terminate the daemon", array('pid' => $pid));
$this->logger->info("Trying to terminate the daemon", ['pid' => $pid]);
$this->processControl->kill($pid);
for ($i = 0; ($pid = $this->getRunningPid()) && $i < 5; $i++) {
@ -152,7 +152,7 @@ class DaemonCommand extends Command
}
if ($pid) {
$this->logger->warning("The daemon is resiting, trying to kill it", array('pid' => $pid));
$this->logger->warning("The daemon is resiting, trying to kill it", ['pid' => $pid]);
$this->processControl->kill($pid, true);
for ($i = 0; ($pid = $this->getRunningPid()) && $i < 5; $i++) {

View file

@ -76,7 +76,7 @@ class DaemoniseCommand extends Command
$runner->setMaxBuilds(1);
$runner->setDaemon(true);
$emptyInput = new ArgvInput(array());
$emptyInput = new ArgvInput([]);
while ($this->run) {

View file

@ -37,8 +37,8 @@ class GenerateCommand extends Command
{
$gen = new CodeGenerator(
Database::getConnection(),
array('default' => 'PHPCI'),
array('default' => PHPCI_DIR),
['default' => 'PHPCI'],
['default' => PHPCI_DIR],
false
);

View file

@ -90,7 +90,7 @@ class InstallCommand extends Command
$output->writeln('');
$conf = array();
$conf = [];
$conf['b8']['database'] = $db;
// ----
@ -123,7 +123,7 @@ class InstallCommand extends Command
}
// Check required extensions are present:
$requiredExtensions = array('PDO', 'pdo_mysql');
$requiredExtensions = ['PDO', 'pdo_mysql'];
foreach ($requiredExtensions as $extension) {
if (!extension_loaded($extension)) {
@ -134,7 +134,7 @@ class InstallCommand extends Command
}
// Check required functions are callable:
$requiredFunctions = array('exec', 'shell_exec');
$requiredFunctions = ['exec', 'shell_exec'];
foreach ($requiredFunctions as $function) {
if (!function_exists($function)) {
@ -167,7 +167,7 @@ class InstallCommand extends Command
*/
protected function getAdminInformation(InputInterface $input, OutputInterface $output)
{
$admin = array();
$admin = [];
/**
* @var \Symfony\Component\Console\Helper\DialogHelper
@ -211,7 +211,7 @@ class InstallCommand extends Command
*/
protected function getPhpciConfigInformation(InputInterface $input, OutputInterface $output)
{
$phpci = array();
$phpci = [];
/**
* @var \Symfony\Component\Console\Helper\DialogHelper
@ -282,7 +282,7 @@ class InstallCommand extends Command
*/
protected function getDatabaseInformation(InputInterface $input, OutputInterface $output)
{
$db = array();
$db = [];
/**
* @var \Symfony\Component\Console\Helper\DialogHelper
@ -327,12 +327,12 @@ class InstallCommand extends Command
'mysql:host='.$db['servers']['write'].';dbname='.$db['name'],
$db['username'],
$db['password'],
array(
\PDO::ATTR_PERSISTENT => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 2,
[
\PDO::ATTR_PERSISTENT => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_TIMEOUT => 2,
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
)
]
);
unset($pdo);

View file

@ -70,7 +70,7 @@ class PollCommand extends Command
foreach ($result['items'] as $project) {
$http = new HttpClient('https://api.github.com');
$commits = $http->get('/repos/' . $project->getReference() . '/commits', array('access_token' => $token));
$commits = $http->get('/repos/' . $project->getReference() . '/commits', ['access_token' => $token]);
$last_commit = $commits['body'][0]['sha'];
$last_committer = $commits['body'][0]['commit']['committer']['email'];

View file

@ -79,7 +79,7 @@ class RebuildCommand extends Command
$lastBuild = array_shift($builds);
$service->createDuplicateBuild($lastBuild);
$runner->run(new ArgvInput(array()), $output);
$runner->run(new ArgvInput([]), $output);
}
/**

View file

@ -148,9 +148,9 @@ class RunCommand extends Command
protected function validateRunningBuilds()
{
/** @var \PHPCI\Store\BuildStore $store */
$store = Factory::getStore('Build');
$store = Factory::getStore('Build');
$running = $store->getByStatus(1);
$rtn = array();
$rtn = [];
$timeout = Config::getInstance()->get('phpci.build.failed_after', 1800);

View file

@ -107,7 +107,7 @@ class BuildController extends \PHPCI\Controller
*/
protected function getUiPlugins()
{
$rtn = array();
$rtn = [];
$path = APPLICATION_PATH . 'public/assets/js/build-plugins/';
$dir = opendir($path);
@ -132,7 +132,7 @@ class BuildController extends \PHPCI\Controller
if (!$build) {
$response->setResponseCode(404);
$response->setContent(array());
$response->setContent([]);
return $response;
}
@ -164,7 +164,7 @@ class BuildController extends \PHPCI\Controller
*/
protected function getBuildData(Build $build)
{
$data = array();
$data = [];
$data['status'] = (int)$build->getStatus();
$data['log'] = $this->cleanLog($build->getLog());
$data['created'] = !is_null($build->getCreated()) ? $build->getCreated()->format('Y-m-d H:i:s') : null;
@ -242,10 +242,10 @@ class BuildController extends \PHPCI\Controller
*/
public function latest()
{
$rtn = array(
$rtn = [
'pending' => $this->formatBuilds($this->buildStore->getByStatus(Build::STATUS_NEW)),
'running' => $this->formatBuilds($this->buildStore->getByStatus(Build::STATUS_RUNNING)),
);
];
$response = new JsonResponse();
$response->setContent($rtn);
@ -259,9 +259,9 @@ class BuildController extends \PHPCI\Controller
*/
protected function formatBuilds($builds)
{
Project::$sleepable = array('id', 'title', 'reference', 'type');
Project::$sleepable = ['id', 'title', 'reference', 'type'];
$rtn = array('count' => $builds['count'], 'items' => array());
$rtn = ['count' => $builds['count'], 'items' => []];
foreach ($builds['items'] as $build) {
$item = $build->toArray(1);

View file

@ -57,7 +57,7 @@ class BuildStatusController extends \PHPCI\Controller
}
if (isset($project) && $project instanceof Project) {
$build = $project->getLatestBuild($branch, array(2,3));
$build = $project->getLatestBuild($branch, [2,3]);
if (isset($build) && $build instanceof Build && $build->getStatus() != 2) {
$status = 'failed';
@ -92,7 +92,7 @@ class BuildStatusController extends \PHPCI\Controller
$branchList = $this->buildStore->getBuildBranches($projectId);
if (!$branchList) {
$branchList = array($project->getBranch());
$branchList = [$project->getBranch()];
}
foreach ($branchList as $branch) {
@ -191,9 +191,9 @@ class BuildStatusController extends \PHPCI\Controller
*/
protected function getLatestBuilds($projectId)
{
$criteria = array('project_id' => $projectId);
$order = array('id' => 'DESC');
$builds = $this->buildStore->getWhere($criteria, 10, 0, array(), $order);
$criteria = ['project_id' => $projectId];
$order = ['id' => 'DESC'];
$builds = $this->buildStore->getWhere($criteria, 10, 0, [], $order);
foreach ($builds['items'] as &$build) {
$build = BuildFactory::getBuild($build);

View file

@ -44,14 +44,14 @@ class GroupController extends Controller
{
$this->requireAdmin();
$groups = array();
$groupList = $this->groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
$groups = [];
$groupList = $this->groupStore->getWhere([], 100, 0, [], ['title' => 'ASC']);
foreach ($groupList['items'] as $group) {
$thisGroup = array(
$thisGroup = [
'title' => $group->getTitle(),
'id' => $group->getId(),
);
'id' => $group->getId(),
];
$projects = b8\Store\Factory::getStore('Project')->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$groups[] = $thisGroup;

View file

@ -81,7 +81,7 @@ class HomeController extends \PHPCI\Controller
public function summary()
{
$this->response->disableLayout();
$projects = $this->projectStore->getWhere(array(), 50, 0, array(), array('title' => 'ASC'));
$projects = $this->projectStore->getWhere([], 50, 0, [], ['title' => 'ASC']);
$this->response->setContent($this->getSummaryHtml($projects));
return $this->response;
}
@ -93,20 +93,20 @@ class HomeController extends \PHPCI\Controller
*/
protected function getSummaryHtml($projects)
{
$summaryBuilds = array();
$successes = array();
$failures = array();
$counts = array();
$summaryBuilds = [];
$successes = [];
$failures = [];
$counts = [];
foreach ($projects as $project) {
$summaryBuilds[$project->getId()] = $this->buildStore->getLatestBuilds($project->getId());
$count = $this->buildStore->getWhere(
array('project_id' => $project->getId()),
['project_id' => $project->getId()],
1,
0,
array(),
array('id' => 'DESC')
[],
['id' => 'DESC']
);
$counts[$project->getId()] = $count['count'];
@ -132,7 +132,7 @@ class HomeController extends \PHPCI\Controller
*/
protected function getLatestBuildsHtml()
{
$builds = $this->buildStore->getWhere(array(), 5, 0, array(), array('id' => 'DESC'));
$builds = $this->buildStore->getWhere([], 5, 0, [], ['id' => 'DESC']);
$view = new b8\View('BuildsTable');
foreach ($builds['items'] as &$build) {
@ -150,11 +150,11 @@ class HomeController extends \PHPCI\Controller
*/
protected function getGroupInfo()
{
$rtn = array();
$groups = $this->groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
$rtn = [];
$groups = $this->groupStore->getWhere([], 100, 0, [], ['title' => 'ASC']);
foreach ($groups['items'] as $group) {
$thisGroup = array('title' => $group->getTitle());
$thisGroup = ['title' => $group->getTitle()];
$projects = $this->projectStore->getByGroupId($group->getId());
$thisGroup['projects'] = $projects['items'];
$thisGroup['summary'] = $this->getSummaryHtml($thisGroup['projects']);

View file

@ -163,14 +163,14 @@ class ProjectController extends PHPCI\Controller
*/
protected function getLatestBuildsHtml($projectId, $branch = '', $start = 0)
{
$criteria = array('project_id' => $projectId);
$criteria = ['project_id' => $projectId];
if (!empty($branch)) {
$criteria['branch'] = $branch;
}
$order = array('id' => 'DESC');
$builds = $this->buildStore->getWhere($criteria, 10, $start, array(), $order);
$view = new b8\View('BuildsTable');
$order = ['id' => 'DESC'];
$builds = $this->buildStore->getWhere($criteria, 10, $start, [], $order);
$view = new b8\View('BuildsTable');
foreach ($builds['items'] as &$build) {
$build = BuildFactory::getBuild($build);
@ -178,7 +178,7 @@ class ProjectController extends PHPCI\Controller
$view->builds = $builds['items'];
return array($view->render(), $builds['count']);
return [$view->render(), $builds['count']];
}
/**
@ -214,18 +214,18 @@ class ProjectController extends PHPCI\Controller
return $view->render();
} else {
$title = $this->getParam('title', 'New Project');
$title = $this->getParam('title', 'New Project');
$reference = $this->getParam('reference', null);
$type = $this->getParam('type', null);
$type = $this->getParam('type', null);
$options = array(
'ssh_private_key' => $this->getParam('key', null),
'ssh_public_key' => $this->getParam('pubkey', null),
'build_config' => $this->getParam('build_config', null),
$options = [
'ssh_private_key' => $this->getParam('key', null),
'ssh_public_key' => $this->getParam('pubkey', null),
'build_config' => $this->getParam('build_config', null),
'allow_public_status' => $this->getParam('allow_public_status', 0),
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
);
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
];
$project = $this->projectService->createProject($title, $type, $reference, $options);
@ -282,15 +282,15 @@ class ProjectController extends PHPCI\Controller
$reference = $this->getParam('reference', null);
$type = $this->getParam('type', null);
$options = array(
'ssh_private_key' => $this->getParam('key', null),
'ssh_public_key' => $this->getParam('pubkey', null),
'build_config' => $this->getParam('build_config', null),
$options = [
'ssh_private_key' => $this->getParam('key', null),
'ssh_public_key' => $this->getParam('pubkey', null),
'build_config' => $this->getParam('build_config', null),
'allow_public_status' => $this->getParam('allow_public_status', 0),
'archived' => $this->getParam('archived', 0),
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
);
'archived' => $this->getParam('archived', 0),
'branch' => $this->getParam('branch', null),
'group' => $this->getParam('group_id', null),
];
$project = $this->projectService->updateProject($project, $title, $type, $reference, $options);
@ -310,16 +310,16 @@ class ProjectController extends PHPCI\Controller
$form->addField(new Form\Element\Csrf('csrf'));
$form->addField(new Form\Element\Hidden('pubkey'));
$options = array(
'choose' => Lang::get('select_repository_type'),
'github' => Lang::get('github'),
$options = [
'choose' => Lang::get('select_repository_type'),
'github' => Lang::get('github'),
'bitbucket' => Lang::get('bitbucket'),
'gitlab' => Lang::get('gitlab'),
'remote' => Lang::get('remote'),
'local' => Lang::get('local'),
'hg' => Lang::get('hg'),
'svn' => Lang::get('svn'),
);
'gitlab' => Lang::get('gitlab'),
'remote' => Lang::get('remote'),
'local' => Lang::get('local'),
'hg' => Lang::get('hg'),
'svn' => Lang::get('svn'),
];
$field = Form\Element\Select::create('type', Lang::get('where_hosted'), true);
$field->setPattern('^(github|bitbucket|gitlab|remote|local|hg|svn)');
@ -361,9 +361,9 @@ class ProjectController extends PHPCI\Controller
$field = Form\Element\Select::create('group_id', 'Project Group', true);
$field->setClass('form-control')->setContainerClass('form-group')->setValue(1);
$groups = array();
$groups = [];
$groupStore = b8\Store\Factory::getStore('ProjectGroup');
$groupList = $groupStore->getWhere(array(), 100, 0, array(), array('title' => 'ASC'));
$groupList = $groupStore->getWhere([], 100, 0, [], ['title' => 'ASC']);
foreach ($groupList['items'] as $group) {
$groups[$group->getId()] = $group->getTitle();
@ -416,28 +416,28 @@ class ProjectController extends PHPCI\Controller
return function ($val) use ($values) {
$type = $values['type'];
$validators = array(
'hg' => array(
'regex' => '/^(https?):\/\//',
$validators = [
'hg' => [
'regex' => '/^(https?):\/\//',
'message' => Lang::get('error_mercurial')
),
'remote' => array(
'regex' => '/^(git|https?):\/\//',
],
'remote' => [
'regex' => '/^(git|https?):\/\//',
'message' => Lang::get('error_remote')
),
'gitlab' => array(
'regex' => '`^(.*)@(.*):(.*)/(.*)\.git`',
],
'gitlab' => [
'regex' => '`^(.*)@(.*):(.*)/(.*)\.git`',
'message' => Lang::get('error_gitlab')
),
'github' => array(
'regex' => '/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-\.]+$/',
],
'github' => [
'regex' => '/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-\.]+$/',
'message' => Lang::get('error_github')
),
'bitbucket' => array(
'regex' => '/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-\.]+$/',
],
'bitbucket' => [
'regex' => '/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9_\-\.]+$/',
'message' => Lang::get('error_bitbucket')
),
);
],
];
if (in_array($type, $validators) && !preg_match($validators[$type]['regex'], $val)) {
throw new \Exception($validators[$type]['message']);

View file

@ -56,33 +56,33 @@ class SettingsController extends Controller
$this->view->settings = $this->settings;
$basicSettings = array();
$basicSettings = [];
if (isset($this->settings['phpci']['basic'])) {
$basicSettings = $this->settings['phpci']['basic'];
}
$buildSettings = array();
$buildSettings = [];
if (isset($this->settings['phpci']['build'])) {
$buildSettings = $this->settings['phpci']['build'];
}
$emailSettings = array();
$emailSettings = [];
if (isset($this->settings['phpci']['email_settings'])) {
$emailSettings = $this->settings['phpci']['email_settings'];
}
$authSettings = array();
$authSettings = [];
if (isset($this->settings['phpci']['authentication_settings'])) {
$authSettings = $this->settings['phpci']['authentication_settings'];
}
$this->view->configFile = PHPCI_CONFIG_FILE;
$this->view->basicSettings = $this->getBasicForm($basicSettings);
$this->view->buildSettings = $this->getBuildForm($buildSettings);
$this->view->github = $this->getGithubForm();
$this->view->emailSettings = $this->getEmailForm($emailSettings);
$this->view->configFile = PHPCI_CONFIG_FILE;
$this->view->basicSettings = $this->getBasicForm($basicSettings);
$this->view->buildSettings = $this->getBuildForm($buildSettings);
$this->view->github = $this->getGithubForm();
$this->view->emailSettings = $this->getEmailForm($emailSettings);
$this->view->authenticationSettings = $this->getAuthenticationForm($authSettings);
$this->view->isWriteable = $this->canWriteConfig();
$this->view->isWriteable = $this->canWriteConfig();
if (!empty($this->settings['phpci']['github']['token'])) {
$this->view->githubUser = $this->getGithubUser($this->settings['phpci']['github']['token']);
@ -213,7 +213,7 @@ class SettingsController extends Controller
if (!is_null($code)) {
$http = new HttpClient();
$url = 'https://github.com/login/oauth/access_token';
$params = array('client_id' => $github['id'], 'client_secret' => $github['secret'], 'code' => $code);
$params = ['client_id' => $github['id'], 'client_secret' => $github['secret'], 'code' => $code];
$resp = $http->post($url, $params);
if ($resp['success']) {
@ -298,7 +298,7 @@ class SettingsController extends Controller
* @param array $values
* @return Form
*/
protected function getEmailForm($values = array())
protected function getEmailForm($values = [])
{
$form = new Form();
$form->setMethod('POST');
@ -351,7 +351,7 @@ class SettingsController extends Controller
$form->addField($field);
$field = new Form\Element\Select('smtp_encryption');
$field->setOptions(array('' => Lang::get('none'), 'tls' => Lang::get('tls'), 'ssl' => Lang::get('ssl')));
$field->setOptions(['' => Lang::get('none'), 'tls' => Lang::get('tls'), 'ssl' => Lang::get('ssl')]);
$field->setRequired(false);
$field->setLabel(Lang::get('use_smtp_encryption'));
$field->setContainerClass('form-group');
@ -376,7 +376,7 @@ class SettingsController extends Controller
protected function getGithubUser($token)
{
$http = new HttpClient('https://api.github.com');
$user = $http->get('/user', array('access_token' => $token));
$user = $http->get('/user', ['access_token' => $token]);
return $user['body'];
}
@ -395,7 +395,7 @@ class SettingsController extends Controller
* @param array $values
* @return Form
*/
protected function getBuildForm($values = array())
protected function getBuildForm($values = [])
{
$form = new Form();
$form->setMethod('POST');
@ -406,13 +406,13 @@ class SettingsController extends Controller
$field->setLabel(Lang::get('failed_after'));
$field->setClass('form-control');
$field->setContainerClass('form-group');
$field->setOptions(array(
$field->setOptions([
300 => Lang::get('5_mins'),
900 => Lang::get('15_mins'),
1800 => Lang::get('30_mins'),
3600 => Lang::get('1_hour'),
10800 => Lang::get('3_hours'),
));
]);
$field->setValue(1800);
$form->addField($field);
@ -432,7 +432,7 @@ class SettingsController extends Controller
* @param array $values
* @return Form
*/
protected function getBasicForm($values = array())
protected function getBasicForm($values = [])
{
$form = new Form();
$form->setMethod('POST');
@ -464,7 +464,7 @@ class SettingsController extends Controller
* @param array $values
* @return Form
*/
protected function getAuthenticationForm($values = array())
protected function getAuthenticationForm($values = [])
{
$form = new Form();
$form->setMethod('POST');

View file

@ -48,9 +48,8 @@ class UserController extends Controller
*/
public function index()
{
$users = $this->userStore->getWhere(array(), 1000, 0, array(), array('email' => 'ASC'));
$this->view->users = $users;
$users = $this->userStore->getWhere([], 1000, 0, [], ['email' => 'ASC']);
$this->view->users = $users;
$this->layout->title = Lang::get('manage_users');
return $this->view->render();
@ -152,16 +151,16 @@ class UserController extends Controller
if ($method == 'POST') {
$values = $this->getParams();
} else {
$values = array();
$values = [];
}
$form = $this->userForm($values);
if ($method != 'POST' || ($method == 'POST' && !$form->validate())) {
$view = new b8\View('UserForm');
$view->type = 'add';
$view->user = null;
$view->form = $form;
$view = new b8\View('UserForm');
$view->type = 'add';
$view->user = null;
$view->form = $form;
return $view->render();
}

View file

@ -76,7 +76,7 @@ class WebhookController extends \b8\Controller
$response->setContent($data);
} catch (Exception $ex) {
$response->setResponseCode(500);
$response->setContent(array('status' => 'failed', 'error' => $ex->getMessage()));
$response->setContent(['status' => 'failed', 'error' => $ex->getMessage()]);
}
return $response;
}
@ -142,8 +142,8 @@ class WebhookController extends \b8\Controller
{
$payload = json_decode($this->getParam('payload'), true);
$results = array();
$status = 'failed';
$results = [];
$status = 'failed';
foreach ($payload['commits'] as $commit) {
try {
$email = $commit['raw_author'];
@ -159,11 +159,11 @@ class WebhookController extends \b8\Controller
);
$status = 'ok';
} catch (Exception $ex) {
$results[$commit['raw_node']] = array('status' => 'failed', 'error' => $ex->getMessage());
$results[$commit['raw_node']] = ['status' => 'failed', 'error' => $ex->getMessage()];
}
}
return array('status' => $status, 'commits' => $results);
return ['status' => $status, 'commits' => $results];
}
/**
@ -173,7 +173,7 @@ class WebhookController extends \b8\Controller
*/
public function git($projectId)
{
$project = $this->fetchProject($projectId, array('local', 'remote'));
$project = $this->fetchProject($projectId, ['local', 'remote']);
$branch = $this->getParam('branch', $project->getBranch());
$commit = $this->getParam('commit');
$commitMessage = $this->getParam('message');
@ -197,7 +197,7 @@ class WebhookController extends \b8\Controller
$payload = json_decode($this->getParam('payload'), true);
break;
default:
return array('status' => 'failed', 'error' => 'Content type not supported.', 'responseCode' => 401);
return ['status' => 'failed', 'error' => 'Content type not supported.', 'responseCode' => 401];
}
// Handle Pull Request web hooks:
@ -210,7 +210,7 @@ class WebhookController extends \b8\Controller
return $this->githubCommitRequest($project, $payload);
}
return array('status' => 'ignored', 'message' => 'Unusable payload.');
return ['status' => 'ignored', 'message' => 'Unusable payload.'];
}
/**
@ -227,17 +227,17 @@ class WebhookController extends \b8\Controller
// Github sends a payload when you close a pull request with a
// non-existent commit. We don't want this.
if (array_key_exists('after', $payload) && $payload['after'] === '0000000000000000000000000000000000000000') {
return array('status' => 'ignored');
return ['status' => 'ignored'];
}
if (isset($payload['commits']) && is_array($payload['commits'])) {
// If we have a list of commits, then add them all as builds to be tested:
$results = array();
$status = 'failed';
$results = [];
$status = 'failed';
foreach ($payload['commits'] as $commit) {
if (!$commit['distinct']) {
$results[$commit['id']] = array('status' => 'ignored');
$results[$commit['id']] = ['status' => 'ignored'];
continue;
}
@ -253,10 +253,10 @@ class WebhookController extends \b8\Controller
);
$status = 'ok';
} catch (Exception $ex) {
$results[$commit['id']] = array('status' => 'failed', 'error' => $ex->getMessage());
$results[$commit['id']] = ['status' => 'failed', 'error' => $ex->getMessage()];
}
}
return array('status' => $status, 'commits' => $results);
return ['status' => $status, 'commits' => $results];
}
if (substr($payload['ref'], 0, 10) == 'refs/tags/') {
@ -267,7 +267,7 @@ class WebhookController extends \b8\Controller
return $this->createBuild($project, $payload['after'], $branch, $committer, $message);
}
return array('status' => 'ignored', 'message' => 'Unusable payload.');
return ['status' => 'ignored', 'message' => 'Unusable payload.'];
}
/**
@ -279,12 +279,12 @@ class WebhookController extends \b8\Controller
protected function githubPullRequest(Project $project, array $payload)
{
// We only want to know about open pull requests:
if (!in_array($payload['action'], array('opened', 'synchronize', 'reopened'))) {
return array('status' => 'ok');
if (!in_array($payload['action'], ['opened', 'synchronize', 'reopened'])) {
return ['status' => 'ok'];
}
$headers = array();
$token = \b8\Config::getInstance()->get('phpci.github.token');
$headers = [];
$token = \b8\Config::getInstance()->get('phpci.github.token');
if (!empty($token)) {
$headers[] = 'Authorization: token ' . $token;
@ -300,39 +300,39 @@ class WebhookController extends \b8\Controller
throw new Exception('Could not get commits, failed API request.');
}
$results = array();
$status = 'failed';
$results = [];
$status = 'failed';
foreach ($response['body'] as $commit) {
// Skip all but the current HEAD commit ID:
$id = $commit['sha'];
if ($id != $payload['pull_request']['head']['sha']) {
$results[$id] = array('status' => 'ignored', 'message' => 'not branch head');
$results[$id] = ['status' => 'ignored', 'message' => 'not branch head'];
continue;
}
try {
$branch = str_replace('refs/heads/', '', $payload['pull_request']['base']['ref']);
$branch = str_replace('refs/heads/', '', $payload['pull_request']['base']['ref']);
$committer = $commit['commit']['author']['email'];
$message = $commit['commit']['message'];
$message = $commit['commit']['message'];
$remoteUrlKey = $payload['pull_request']['head']['repo']['private'] ? 'ssh_url' : 'clone_url';
$extra = array(
'build_type' => 'pull_request',
'pull_request_id' => $payload['pull_request']['id'],
$extra = [
'build_type' => 'pull_request',
'pull_request_id' => $payload['pull_request']['id'],
'pull_request_number' => $payload['number'],
'remote_branch' => $payload['pull_request']['head']['ref'],
'remote_url' => $payload['pull_request']['head']['repo'][$remoteUrlKey],
);
'remote_branch' => $payload['pull_request']['head']['ref'],
'remote_url' => $payload['pull_request']['head']['repo'][$remoteUrlKey],
];
$results[$id] = $this->createBuild($project, $id, $branch, $committer, $message, $extra);
$status = 'ok';
} catch (Exception $ex) {
$results[$id] = array('status' => 'failed', 'error' => $ex->getMessage());
$results[$id] = ['status' => 'failed', 'error' => $ex->getMessage()];
}
}
return array('status' => $status, 'commits' => $results);
return ['status' => $status, 'commits' => $results];
}
/**
@ -361,8 +361,8 @@ class WebhookController extends \b8\Controller
if (isset($payload['commits']) && is_array($payload['commits'])) {
// If we have a list of commits, then add them all as builds to be tested:
$results = array();
$status = 'failed';
$results = [];
$status = 'failed';
foreach ($payload['commits'] as $commit) {
try {
$branch = str_replace('refs/heads/', '', $payload['ref']);
@ -376,13 +376,13 @@ class WebhookController extends \b8\Controller
);
$status = 'ok';
} catch (Exception $ex) {
$results[$commit['id']] = array('status' => 'failed', 'error' => $ex->getMessage());
$results[$commit['id']] = ['status' => 'failed', 'error' => $ex->getMessage()];
}
}
return array('status' => $status, 'commits' => $results);
return ['status' => $status, 'commits' => $results];
}
return array('status' => 'ignored', 'message' => 'Unusable payload.');
return ['status' => 'ignored', 'message' => 'Unusable payload.'];
}
/**
@ -411,16 +411,16 @@ class WebhookController extends \b8\Controller
$builds = $this->buildStore->getByProjectAndCommit($project->getId(), $commitId);
if ($builds['count']) {
return array(
'status' => 'ignored',
return [
'status' => 'ignored',
'message' => sprintf('Duplicate of build #%d', $builds['items'][0]->getId())
);
];
}
// If not, create a new build job for it:
$build = $this->buildService->createBuild($project, $commitId, $branch, $committer, $commitMessage, $extra);
return array('status' => 'ok', 'buildID' => $build->getID());
return ['status' => 'ok', 'buildID' => $build->getID()];
}
/**

View file

@ -19,7 +19,7 @@ class ErrorHandler
/**
* @var array
*/
protected $levels = array(
protected $levels = [
E_WARNING => 'Warning',
E_NOTICE => 'Notice',
E_USER_ERROR => 'User Error',
@ -29,7 +29,7 @@ class ErrorHandler
E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User Deprecated',
);
];
/**
* Registers an instance of the error handler to throw ErrorException.
@ -37,7 +37,7 @@ class ErrorHandler
public static function register()
{
$handler = new static();
set_error_handler(array($handler, 'handleError'));
set_error_handler([$handler, 'handleError']);
}
/**

View file

@ -61,8 +61,8 @@ abstract class BaseCommandExecutor implements CommandExecutor
{
$this->logger = $logger;
$this->quiet = $quiet;
$this->verbose = $verbose;
$this->lastOutput = array();
$this->verbose = $verbose;
$this->lastOutput = [];
$this->rootDir = rtrim($rootDir, '/\\') . DIRECTORY_SEPARATOR;
}
@ -71,9 +71,9 @@ abstract class BaseCommandExecutor implements CommandExecutor
* @param array $args
* @return bool Indicates success
*/
public function executeCommand($args = array())
public function executeCommand($args = [])
{
$this->lastOutput = array();
$this->lastOutput = [];
$command = call_user_func_array('sprintf', $args);
$this->logger->logDebug($command);
@ -83,13 +83,13 @@ abstract class BaseCommandExecutor implements CommandExecutor
}
$status = 0;
$descriptorSpec = array(
0 => array("pipe", "r"), // stdin
1 => array("pipe", "w"), // stdout
2 => array("pipe", "w"), // stderr
);
$descriptorSpec = [
0 => ["pipe", "r"], // stdin
1 => ["pipe", "w"], // stdout
2 => ["pipe", "w"], // stderr
];
$pipes = array();
$pipes = [];
$process = proc_open($command, $descriptorSpec, $pipes, $this->buildPath, null);
if (is_resource($process)) {
@ -152,7 +152,7 @@ abstract class BaseCommandExecutor implements CommandExecutor
$composerBin = $this->getComposerBinDir(realpath($this->buildPath));
if (is_string($binary)) {
$binary = array($binary);
$binary = [$binary];
}
foreach ($binary as $bin) {

View file

@ -23,7 +23,7 @@ class BuildInterpolator
* @var mixed[]
* @see setupInterpolationVars()
*/
protected $interpolation_vars = array();
protected $interpolation_vars = [];
/**
* Sets the variables that will be used for interpolation.
@ -33,7 +33,7 @@ class BuildInterpolator
*/
public function setupInterpolationVars(Build $build, $buildPath, $phpCiUrl)
{
$this->interpolation_vars = array();
$this->interpolation_vars = [];
$this->interpolation_vars['%PHPCI%'] = 1;
$this->interpolation_vars['%COMMIT%'] = $build->getCommitId();
$this->interpolation_vars['%SHORT_COMMIT%'] = substr($build->getCommitId(), 0, 7);

View file

@ -30,7 +30,7 @@ class Diff
return null;
}
$rtn = array();
$rtn = [];
$diffLines = explode(PHP_EOL, $diff);

View file

@ -20,11 +20,11 @@ class Email
{
const DEFAULT_FROM = 'PHPCI <no-reply@phptesting.org>';
protected $emailTo = array();
protected $emailCc = array();
protected $emailTo = [];
protected $emailCc = [];
protected $subject = 'Email from PHPCI';
protected $body = '';
protected $isHtml = false;
protected $body = '';
protected $isHtml = false;
protected $config;
/**
@ -126,7 +126,7 @@ class Email
$headers .= 'From: ' . $this->getFrom() . PHP_EOL;
$emailTo = array();
$emailTo = [];
foreach ($this->emailTo as $email => $name) {
$thisTo = $email;

View file

@ -42,7 +42,7 @@ class Github
*
* @return array
*/
public function makeRecursiveRequest($url, $params, $results = array())
public function makeRecursiveRequest($url, $params, $results = [])
{
$http = new HttpClient('https://api.github.com');
$res = $http->get($url, $params);
@ -80,17 +80,17 @@ class Github
$rtn = $cache->get('phpci_github_repos');
if (!$rtn) {
$orgs = $this->makeRequest('/user/orgs', array('access_token' => $token));
$orgs = $this->makeRequest('/user/orgs', ['access_token' => $token]);
$params = array('type' => 'all', 'access_token' => $token);
$repos = array('user' => array());
$params = ['type' => 'all', 'access_token' => $token];
$repos = ['user' => []];
$repos['user'] = $this->makeRecursiveRequest('/user/repos', $params);
foreach ($orgs as $org) {
$repos[$org['login']] = $this->makeRecursiveRequest('/orgs/'.$org['login'].'/repos', $params);
}
$rtn = array();
$rtn = [];
foreach ($repos as $repoGroup) {
foreach ($repoGroup as $repo) {
$rtn['repos'][] = $repo['full_name'];
@ -123,18 +123,18 @@ class Github
$url = '/repos/' . strtolower($repo) . '/pulls/' . $pullId . '/comments';
$params = array(
'body' => $comment,
$params = [
'body' => $comment,
'commit_id' => $commitId,
'path' => $file,
'position' => $line,
);
'path' => $file,
'position' => $line,
];
$http = new HttpClient('https://api.github.com');
$http->setHeaders(array(
$http->setHeaders([
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode($token . ':x-oauth-basic'),
));
]);
$http->post($url, json_encode($params));
}
@ -158,17 +158,17 @@ class Github
$url = '/repos/' . strtolower($repo) . '/commits/' . $commitId . '/comments';
$params = array(
'body' => $comment,
'path' => $file,
$params = [
'body' => $comment,
'path' => $file,
'position' => $line,
);
];
$http = new HttpClient('https://api.github.com');
$http->setHeaders(array(
$http->setHeaders([
'Content-Type: application/x-www-form-urlencoded',
'Authorization: Basic ' . base64_encode($token . ':x-oauth-basic'),
));
]);
$http->post($url, json_encode($params));
}

View file

@ -26,17 +26,17 @@ class Lang
/**
* @var array
*/
protected static $languages = array();
protected static $languages = [];
/**
* @var array
*/
protected static $strings = array();
protected static $strings = [];
/**
* @var array
*/
protected static $en_strings = array();
protected static $en_strings = [];
/**
* Get a specific string from the language file.
@ -64,7 +64,7 @@ class Lang
*/
public static function out()
{
print call_user_func_array(array('PHPCI\Helper\Lang', 'get'), func_get_args());
print call_user_func_array(['PHPCI\Helper\Lang', 'get'], func_get_args());
}
/**
@ -102,10 +102,10 @@ class Lang
*/
public static function getLanguageOptions()
{
$languages = array();
$languages = [];
foreach (self::$languages as $language) {
$strings = array();
$strings = [];
require(PHPCI_DIR . 'src/PHPCI/Languages/lang.' . $language . '.php');
$languages[$language] = $strings['language_name'];
}
@ -195,7 +195,7 @@ class Lang
*/
protected static function loadAvailableLanguages()
{
$matches = array();
$matches = [];
foreach (glob(PHPCI_DIR . 'src/PHPCI/Languages/lang.*.php') as $file) {
if (preg_match('/lang\.([a-z]{2}\-?[a-z]*)\.php/', $file, $matches)) {
self::$languages[] = $matches[1];

View file

@ -25,7 +25,7 @@ class LoginIsDisabled
* @param array $params
* @return mixed|null
*/
public function __call($method, $params = array())
public function __call($method, $params = [])
{
unset($method, $params);

View file

@ -24,13 +24,13 @@ class MailerFactory
* Set the mailer factory configuration.
* @param array $config
*/
public function __construct($config = array())
public function __construct($config = [])
{
if (!is_array($config)) {
$config = array();
$config = [];
}
$this->emailConfig = isset($config['email_settings']) ? $config['email_settings'] : array();
$this->emailConfig = isset($config['email_settings']) ? $config['email_settings'] : [];
}
/**

View file

@ -37,7 +37,7 @@ class SshKey
mkdir($tempPath);
}
$return = array('private_key' => '', 'public_key' => '');
$return = ['private_key' => '', 'public_key' => ''];
$output = @shell_exec('ssh-keygen -t rsa -b 2048 -f '.$keyFile.' -N "" -C "deploy@phpci"');

View file

@ -23,7 +23,7 @@ class User
* @param array $params
* @return mixed|null
*/
public function __call($method, $params = array())
public function __call($method, $params = [])
{
$user = $_SESSION['phpci_user'];
@ -31,6 +31,6 @@ class User
return null;
}
return call_user_func_array(array($user, $method), $params);
return call_user_func_array([$user, $method], $params);
}
}

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Dansk',
'language' => 'Sprog',
@ -394,4 +394,4 @@ Kontrollér venligst nedenstående fejl før du fortsætter.',
'property_file_missing' => 'Den angivne property-fil findes ikke',
'could_not_process_report' => 'Kunne ikke behandle rapporten, som dette værktøj genererede.',
'shell_not_enabled' => 'Shell-plugin er ikke aktiveret. Aktivér det via config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Deutsch',
'language' => 'Sprache',
@ -430,4 +430,4 @@ generiert. Um es zu verwenden, fügen Sie einfach den folgenden Public Key im Ab
'php_unit' => 'PHP Unit',
'php_cpd' => 'PHP Copy/Paste Detector',
'php_docblock_checker' => 'PHP Docblock Checker',
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Ελληνικά',
'language' => 'Γλώσσα',
@ -396,4 +396,4 @@ Services</a> του Bitbucket αποθετηρίου σας.',
'property_file_missing' => 'Καθορισμένο αρχείο ιδιοκτησίας δεν υπάρχει.',
'could_not_process_report' => 'Δεν ήταν δυνατή η επεξεργασία της έκθεσης που δημιουργείται από αυτό το εργαλείο.',
'shell_not_enabled' => 'Το πρόσθετο για το κέλυφος δεν είναι ενεργοποιημένο. Παρακαλούμε ενεργοποιήστε το μέσω του αρχείου config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings =[
'language_name' => 'English',
'language' => 'Language',
@ -451,5 +451,4 @@ PHPCI',
'php_docblock_checker' => 'PHP Docblock Checker',
'behat' => 'Behat',
'technical_debt' => 'Technical Debt',
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Español',
'language' => 'Lenguaje',
@ -384,4 +384,4 @@ PHPCI',
'property_file_missing' => 'El archivo de propiedades especificado no existe.',
'could_not_process_report' => 'Imposible procesar el reporte generado por la herramienta.',
'shell_not_enabled' => 'El plugin shell no está habilitado. Por favor, habilitalo desde config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Français',
'language' => 'Langue',
@ -407,4 +407,4 @@ PHPCI',
'property_file_missing' => 'Le fichier de propriété spécifié n\'existe pas.',
'could_not_process_report' => 'Impossible de traiter le rapport généré par cet outil.',
'shell_not_enabled' => 'Le plugn shell n\'est pas activé. Merci de l\'activer via le fichier config.yml.'
);
];

View file

@ -7,8 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Italiano',
'language' => 'Lingua',
@ -398,4 +397,4 @@ PHPCI',
'property_file_missing' => 'Il file di proprietà specificato non esiste.',
'could_not_process_report' => 'Non è possibile processare il report generato da questo tool.',
'shell_not_enabled' => 'Il plugin shell non è attivato. Per favore attivalo tramite config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Nederlands',
'language' => 'Taal',
@ -396,4 +396,4 @@ Gelieve de fouten na te kijken vooraleer verder te gaan.',
'property_file_missing' => 'Opgegeven bestand bestaat niet',
'could_not_process_report' => 'Het is niet mogelijk om het gegenereerde rapport van deze tool te verwerken.',
'shell_not_enabled' => 'De shell plugin is niet ingeschakeld, schakel deze a.u.b. in via het config.yml bestand.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Polski',
'language' => 'Język',
@ -397,4 +397,4 @@ Przejrzyj powyższą listę błędów przed kontynuowaniem.',
'property_file_missing' => 'Podany plik właściwości nie istnieje.',
'could_not_process_report' => 'Nie udało się przetworzyć raportu wygenerowanego przez to narzędzie.',
'shell_not_enabled' => 'Plugin powłoki jest nieaktywny. Aktywuj go poprzez config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Pусский',
'language' => 'язык',
@ -419,4 +419,4 @@ PHPCI',
'property_file_missing' => 'Указанного файла сборки не существует.',
'could_not_process_report' => 'Невозможно обработать отчет этой утилиты.',
'shell_not_enabled' => 'Плагин shell не включен. Пожалуйста, включите его в файле config.yml.'
);
];

View file

@ -7,7 +7,7 @@
* @link https://www.phptesting.org/
*/
$strings = array(
$strings = [
'language_name' => 'Українська',
'language' => 'Мова',
@ -396,4 +396,4 @@ PHPCI',
'property_file_missing' => 'Вказаний файл властивості не існує.',
'could_not_process_report' => 'Неможливо обробити звіт, згенерований цією утилітою.',
'shell_not_enabled' => 'Плагін shell не увімкнений. Будь ласка, увімкніть його через config.yml.'
);
];

View file

@ -47,7 +47,7 @@ class BuildLogger implements LoggerAwareInterface
* @param string $level
* @param mixed[] $context
*/
public function log($message, $level = LogLevel::INFO, $context = array())
public function log($message, $level = LogLevel::INFO, $context = [])
{
// Skip if no logger has been loaded.
if (!$this->logger) {
@ -55,7 +55,7 @@ class BuildLogger implements LoggerAwareInterface
}
if (!is_array($message)) {
$message = array($message);
$message = [$message];
}
// The build is added to the context so the logger can use
@ -79,18 +79,18 @@ class BuildLogger implements LoggerAwareInterface
/**
* Add a failure-coloured message to the log.
* @param string $message
* @param \Exception $exception The exception that caused the error.
* @param \Exception $exception The exception that caused the error.
*/
public function logFailure($message, \Exception $exception = null)
{
$context = array();
$context = [];
// The psr3 log interface stipulates that exceptions should be passed
// as the exception key in the context array.
if ($exception) {
$context['exception'] = $exception;
}
$this->log(
"\033[0;31m" . $message . "\033[0m",
LogLevel::ERROR,

View file

@ -20,7 +20,7 @@ class Handler
/**
* @var array
*/
protected $levels = array(
protected $levels = [
E_WARNING => 'Warning',
E_NOTICE => 'Notice',
E_USER_ERROR => 'User Error',
@ -30,7 +30,7 @@ class Handler
E_RECOVERABLE_ERROR => 'Catchable Fatal Error',
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User Deprecated',
);
];
/**
* @var LoggerInterface
@ -53,10 +53,10 @@ class Handler
{
$handler = new static($logger);
set_error_handler(array($handler, 'handleError'));
register_shutdown_function(array($handler, 'handleFatalError'));
set_error_handler([$handler, 'handleError']);
register_shutdown_function([$handler, 'handleFatalError']);
set_exception_handler(array($handler, 'handleException'));
set_exception_handler([$handler, 'handleException']);
}
/**
@ -147,7 +147,7 @@ class Handler
$exception->getLine()
);
$this->logger->error($message, array('exception' => $exception));
$this->logger->error($message, ['exception' => $exception]);
}
}
}

View file

@ -20,7 +20,7 @@ class LoggerConfig
{
const KEY_ALWAYS_LOADED = "_";
private $config;
private $cache = array();
private $cache = [];
/**
* The filepath is expected to return an array which will be
@ -34,7 +34,7 @@ class LoggerConfig
if (file_exists($filePath)) {
$configArray = require($filePath);
} else {
$configArray = array();
$configArray = [];
}
return new self($configArray);
}
@ -45,7 +45,7 @@ class LoggerConfig
* array of LogHandlers.
* @param array $configArray
*/
public function __construct(array $configArray = array())
public function __construct(array $configArray = [])
{
$this->config = $configArray;
}
@ -81,7 +81,7 @@ class LoggerConfig
*/
protected function getHandlers($key)
{
$handlers = array();
$handlers = [];
// They key is expected to either be an array or
// a callable function that returns an array

View file

@ -22,7 +22,7 @@ class InitialMigration extends AbstractMigration
$build = $this->table('build');
if (!$build->hasForeignKey('project_id')) {
$build->addForeignKey('project_id', 'project', 'id', array('delete'=> 'CASCADE', 'update' => 'CASCADE'));
$build->addForeignKey('project_id', 'project', 'id', ['delete'=> 'CASCADE', 'update' => 'CASCADE']);
}
$build->save();
@ -30,11 +30,11 @@ class InitialMigration extends AbstractMigration
$buildMeta = $this->table('build_meta');
if (!$buildMeta->hasForeignKey('build_id')) {
$buildMeta->addForeignKey('build_id', 'build', 'id', array('delete'=> 'CASCADE', 'update' => 'CASCADE'));
$buildMeta->addForeignKey('build_id', 'build', 'id', ['delete'=> 'CASCADE', 'update' => 'CASCADE']);
}
if (!$buildMeta->hasForeignKey('project_id')) {
$buildMeta->addForeignKey('project_id', 'project', 'id', array('delete'=> 'CASCADE', 'update' => 'CASCADE'));
$buildMeta->addForeignKey('project_id', 'project', 'id', ['delete'=> 'CASCADE', 'update' => 'CASCADE']);
}
$buildMeta->save();
@ -61,11 +61,11 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('commit_id')) {
$table->addColumn('commit_id', 'string', array('limit' => 50));
$table->addColumn('commit_id', 'string', ['limit' => 50]);
}
if (!$table->hasColumn('status')) {
$table->addColumn('status', 'integer', array('limit' => 4));
$table->addColumn('status', 'integer', ['limit' => 4]);
}
if (!$table->hasColumn('log')) {
@ -73,7 +73,7 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('branch')) {
$table->addColumn('branch', 'string', array('limit' => 50));
$table->addColumn('branch', 'string', ['limit' => 50]);
}
if (!$table->hasColumn('created')) {
@ -89,7 +89,7 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('committer_email')) {
$table->addColumn('committer_email', 'string', array('limit' => 250));
$table->addColumn('committer_email', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('commit_message')) {
@ -104,12 +104,12 @@ class InitialMigration extends AbstractMigration
$table->removeColumn('plugins');
}
if (!$table->hasIndex(array('project_id'))) {
$table->addIndex(array('project_id'));
if (!$table->hasIndex(['project_id'])) {
$table->addIndex(['project_id']);
}
if (!$table->hasIndex(array('status'))) {
$table->addIndex(array('status'));
if (!$table->hasIndex(['status'])) {
$table->addIndex(['status']);
}
$table->save();
@ -132,15 +132,15 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('meta_key')) {
$table->addColumn('meta_key', 'string', array('limit' => 250));
$table->addColumn('meta_key', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('meta_value')) {
$table->addColumn('meta_value', 'text');
}
if (!$table->hasIndex(array('build_id', 'meta_key'))) {
$table->addIndex(array('build_id', 'meta_key'));
if (!$table->hasIndex(['build_id', 'meta_key'])) {
$table->addIndex(['build_id', 'meta_key']);
}
$table->save();
@ -155,11 +155,11 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('title')) {
$table->addColumn('title', 'string', array('limit' => 250));
$table->addColumn('title', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('reference')) {
$table->addColumn('reference', 'string', array('limit' => 250));
$table->addColumn('reference', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('git_key')) {
@ -171,15 +171,15 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('type')) {
$table->addColumn('type', 'string', array('limit' => 50));
$table->addColumn('type', 'string', ['limit' => 50]);
}
if (!$table->hasColumn('access_information')) {
$table->addColumn('access_information', 'string', array('limit' => 250));
$table->addColumn('access_information', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('last_commit')) {
$table->addColumn('last_commit', 'string', array('limit' => 250));
$table->addColumn('last_commit', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('build_config')) {
@ -194,8 +194,8 @@ class InitialMigration extends AbstractMigration
$table->removeColumn('token');
}
if (!$table->hasIndex(array('title'))) {
$table->addIndex(array('title'));
if (!$table->hasIndex(['title'])) {
$table->addIndex(['title']);
}
$table->save();
@ -210,23 +210,23 @@ class InitialMigration extends AbstractMigration
}
if (!$table->hasColumn('email')) {
$table->addColumn('email', 'string', array('limit' => 250));
$table->addColumn('email', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('hash')) {
$table->addColumn('hash', 'string', array('limit' => 250));
$table->addColumn('hash', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('name')) {
$table->addColumn('name', 'string', array('limit' => 250));
$table->addColumn('name', 'string', ['limit' => 250]);
}
if (!$table->hasColumn('is_admin')) {
$table->addColumn('is_admin', 'integer');
}
if (!$table->hasIndex(array('email'))) {
$table->addIndex(array('email'));
if (!$table->hasIndex(['email'])) {
$table->addIndex(['email']);
}
$table->save();

View file

@ -23,10 +23,10 @@ class ChooseBranch extends AbstractMigration
public function up()
{
$project = $this->table('project');
$project->addColumn('branch', 'string', array(
$project->addColumn('branch', 'string', [
'after' => 'reference',
'limit' => 250
))->save();
])->save();
}
/**

View file

@ -17,41 +17,41 @@ class FixDatabaseColumns extends AbstractMigration
}
$build = $this->table('build');
$build->changeColumn('project_id', 'integer', array('null' => false));
$build->changeColumn('commit_id', 'string', array('limit' => 50, 'null' => false));
$build->changeColumn('status', 'integer', array('null' => false));
$build->changeColumn('log', 'text', array('null' => true));
$build->changeColumn('branch', 'string', array('limit' => 50, 'null' => false, 'default' => 'master'));
$build->changeColumn('created', 'datetime', array('null' => true));
$build->changeColumn('started', 'datetime', array('null' => true));
$build->changeColumn('finished', 'datetime', array('null' => true));
$build->changeColumn('committer_email', 'string', array('limit' => 512, 'null' => true));
$build->changeColumn('commit_message', 'text', array('null' => true));
$build->changeColumn('extra', 'text', array('null' => true));
$build->changeColumn('project_id', 'integer', ['null' => false]);
$build->changeColumn('commit_id', 'string', ['limit' => 50, 'null' => false]);
$build->changeColumn('status', 'integer', ['null' => false]);
$build->changeColumn('log', 'text', ['null' => true, 'default' => '']);
$build->changeColumn('branch', 'string', ['limit' => 50, 'null' => false, 'default' => 'master']);
$build->changeColumn('created', 'datetime', ['null' => true]);
$build->changeColumn('started', 'datetime', ['null' => true]);
$build->changeColumn('finished', 'datetime', ['null' => true]);
$build->changeColumn('committer_email', 'string', ['limit' => 512, 'null' => true]);
$build->changeColumn('commit_message', 'text', ['null' => true]);
$build->changeColumn('extra', 'text', ['null' => true]);
$buildMeta = $this->table('build_meta');
$buildMeta->changeColumn('project_id', 'integer', array('null' => false));
$buildMeta->changeColumn('build_id', 'integer', array('null' => false));
$buildMeta->changeColumn('meta_key', 'string', array('limit' => 250, 'null' => false));
$buildMeta->changeColumn('meta_value', 'text', array('null' => false));
$buildMeta->changeColumn('project_id', 'integer', ['null' => false]);
$buildMeta->changeColumn('build_id', 'integer', ['null' => false]);
$buildMeta->changeColumn('meta_key', 'string', ['limit' => 250, 'null' => false]);
$buildMeta->changeColumn('meta_value', 'text', ['null' => false]);
$project = $this->table('project');
$project->changeColumn('title', 'string', array('limit' => 250, 'null' => false));
$project->changeColumn('reference', 'string', array('limit' => 250, 'null' => false));
$project->changeColumn('branch', 'string', array('limit' => 50, 'null' => false, 'default' => 'master'));
$project->changeColumn('ssh_private_key', 'text', array('null' => true, 'default' => null));
$project->changeColumn('ssh_public_key', 'text', array('null' => true, 'default' => null));
$project->changeColumn('type', 'string', array('limit' => 50, 'null' => false));
$project->changeColumn('access_information', 'string', array('limit' => 250, 'null' => true, 'default' => null));
$project->changeColumn('last_commit', 'string', array('limit' => 250, 'null' => true, 'default' => null));
$project->changeColumn('ssh_public_key', 'text', array('null' => true, 'default' => null));
$project->changeColumn('allow_public_status', 'integer', array('null' => false, 'default' => 0));
$project->changeColumn('title', 'string', ['limit' => 250, 'null' => false]);
$project->changeColumn('reference', 'string', ['limit' => 250, 'null' => false]);
$project->changeColumn('branch', 'string', ['limit' => 50, 'null' => false, 'default' => 'master']);
$project->changeColumn('ssh_private_key', 'text', ['null' => true, 'default' => null]);
$project->changeColumn('ssh_public_key', 'text', ['null' => true, 'default' => null]);
$project->changeColumn('type', 'string', ['limit' => 50, 'null' => false]);
$project->changeColumn('access_information', 'string', ['limit' => 250, 'null' => true, 'default' => null]);
$project->changeColumn('last_commit', 'string', ['limit' => 250, 'null' => true, 'default' => null]);
$project->changeColumn('ssh_public_key', 'text', ['null' => true, 'default' => null]);
$project->changeColumn('allow_public_status', 'integer', ['null' => false, 'default' => 0]);
$user = $this->table('user');
$user->changeColumn('email', 'string', array('limit' => 250, 'null' => false));
$user->changeColumn('hash', 'string', array('limit' => 250, 'null' => false));
$user->changeColumn('is_admin', 'integer', array('null' => false, 'default' => 0));
$user->changeColumn('name', 'string', array('limit' => 250, 'null' => false));
$user->changeColumn('email', 'string', ['limit' => 250, 'null' => false]);
$user->changeColumn('hash', 'string', ['limit' => 250, 'null' => false]);
$user->changeColumn('is_admin', 'integer', ['null' => false, 'default' => 0]);
$user->changeColumn('name', 'string', ['limit' => 250, 'null' => false]);
if ($dbAdapter instanceof \Phinx\Db\Adapter\PdoAdapter) {
$pdo = $dbAdapter->getConnection();

View file

@ -12,16 +12,17 @@ class FixColumnTypes extends AbstractMigration
{
// Update the build log column to MEDIUMTEXT:
$build = $this->table('build');
$build->changeColumn('log', 'text', array(
'null' => true,
'limit' => MysqlAdapter::TEXT_MEDIUM,
));
$build->changeColumn('log', 'text', [
'null' => true,
'default' => '',
'limit' => MysqlAdapter::TEXT_MEDIUM,
]);
// Update the build meta value column to MEDIUMTEXT:
$buildMeta = $this->table('build_meta');
$buildMeta->changeColumn('meta_value', 'text', array(
'null' => false,
$buildMeta->changeColumn('meta_value', 'text', [
'null' => false,
'limit' => MysqlAdapter::TEXT_MEDIUM,
));
]);
}
}

View file

@ -11,8 +11,8 @@ class UniqueEmailAndNameUserFields extends AbstractMigration
{
$user_table = $this->table('user');
$user_table
->addIndex('email', array('unique' => true))
->addIndex('name', array('unique' => true))
->addIndex('email', ['unique' => true])
->addIndex('name', ['unique' => true])
->save();
}
@ -23,8 +23,8 @@ class UniqueEmailAndNameUserFields extends AbstractMigration
{
$user_table = $this->table('user');
$user_table
->removeIndex('email', array('unique' => true))
->removeIndex('name', array('unique' => true))
->removeIndex('email', ['unique' => true])
->removeIndex('name', ['unique' => true])
->save();
}
}

View file

@ -7,7 +7,7 @@ class AddProjectGroups extends AbstractMigration
public function change()
{
$table = $this->table('project_group');
$table->addColumn('title', 'string', array('limit' => 100, 'null' => false));
$table->addColumn('title', 'string', ['limit' => 100, 'null' => false]);
$table->save();
$group = new \PHPCI\Model\ProjectGroup();
@ -17,13 +17,13 @@ class AddProjectGroups extends AbstractMigration
$group = \b8\Store\Factory::getStore('ProjectGroup')->save($group);
$table = $this->table('project');
$table->addColumn('group_id', 'integer', array(
'signed' => true,
'null' => false,
$table->addColumn('group_id', 'integer', [
'signed' => true,
'null' => false,
'default' => $group->getId(),
));
]);
$table->addForeignKey('group_id', 'project_group', 'id', array('delete'=> 'RESTRICT', 'update' => 'CASCADE'));
$table->addForeignKey('group_id', 'project_group', 'id', ['delete'=> 'RESTRICT', 'update' => 'CASCADE']);
$table->save();
}
}

View file

@ -29,12 +29,12 @@ class RemoveUniqueNameIndex extends AbstractMigration
{
$user = $this->table('user');
if ($user->hasIndex('name', array('unique' => true))) {
$user->removeIndex('name', array('unique' => true));
if ($user->hasIndex('name', ['unique' => true])) {
$user->removeIndex('name', ['unique' => true]);
$user->save();
}
$user->addIndex('name', array('unique' => false));
$user->addIndex('name', ['unique' => false]);
$user->save();
}
}

View file

@ -8,16 +8,16 @@ class ErrorsTable extends AbstractMigration
public function change()
{
$table = $this->table('build_error');
$table->addColumn('build_id', 'integer', array('signed' => true));
$table->addColumn('plugin', 'string', array('limit' => 100));
$table->addColumn('file', 'string', array('limit' => 250, 'null' => true));
$table->addColumn('line_start', 'integer', array('signed' => false, 'null' => true));
$table->addColumn('line_end', 'integer', array('signed' => false, 'null' => true));
$table->addColumn('severity', 'integer', array('signed' => false, 'limit' => MysqlAdapter::INT_TINY));
$table->addColumn('message', 'string', array('limit' => 250));
$table->addColumn('build_id', 'integer', ['signed' => true]);
$table->addColumn('plugin', 'string', ['limit' => 100]);
$table->addColumn('file', 'string', ['limit' => 250, 'null' => true]);
$table->addColumn('line_start', 'integer', ['signed' => false, 'null' => true]);
$table->addColumn('line_end', 'integer', ['signed' => false, 'null' => true]);
$table->addColumn('severity', 'integer', ['signed' => false, 'limit' => MysqlAdapter::INT_TINY]);
$table->addColumn('message', 'string', ['limit' => 250]);
$table->addColumn('created_date', 'datetime');
$table->addIndex(array('build_id', 'created_date'), array('unique' => false));
$table->addForeignKey('build_id', 'build', 'id', array('delete'=> 'CASCADE', 'update' => 'CASCADE'));
$table->addIndex(['build_id', 'created_date'], ['unique' => false]);
$table->addForeignKey('build_id', 'build', 'id', ['delete'=> 'CASCADE', 'update' => 'CASCADE']);
$table->save();
}

View file

@ -138,13 +138,13 @@ class Build extends BuildBase
$pluginDir = PHPCI_DIR . 'PHPCI/Plugin/';
$dir = new \DirectoryIterator($pluginDir);
$config = array(
'build_settings' => array(
'ignore' => array(
$config = [
'build_settings' => [
'ignore' => [
'vendor',
)
)
);
]
]
];
foreach ($dir as $item) {
if ($item->isDot()) {
@ -167,11 +167,11 @@ class Build extends BuildBase
continue;
}
foreach (array('setup', 'test', 'complete', 'success', 'failure') as $stage) {
foreach (['setup', 'test', 'complete', 'success', 'failure'] as $stage) {
if ($className::canExecute($stage, $builder, $this)) {
$config[$stage][$className] = array(
$config[$stage][$className] = [
'zero_config' => true
);
];
}
}
}

View file

@ -30,14 +30,14 @@ class Project extends ProjectBase
*/
public function getLatestBuild($branch = 'master', $status = null)
{
$criteria = array('branch' => $branch, 'project_id' => $this->getId());
$criteria = ['branch' => $branch, 'project_id' => $this->getId()];
if (isset($status)) {
$criteria['status'] = $status;
}
$order = array('id' => 'DESC');
$builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 0, array(), $order);
$order = ['id' => 'DESC'];
$builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 0, [], $order);
if (is_array($builds['items']) && count($builds['items'])) {
$latest = array_shift($builds['items']);
@ -57,10 +57,9 @@ class Project extends ProjectBase
*/
public function getPreviousBuild($branch = 'master')
{
$criteria = array('branch' => $branch, 'project_id' => $this->getId());
$order = array('id' => 'DESC');
$builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 1, array(), $order);
$criteria = ['branch' => $branch, 'project_id' => $this->getId()];
$order = ['id' => 'DESC'];
$builds = Store\Factory::getStore('Build')->getWhere($criteria, 1, 1, [], $order);
if (is_array($builds['items']) && count($builds['items'])) {
$previous = array_shift($builds['items']);