diff --git a/CHANGELOG.md b/CHANGELOG.md index 62a8df5..6a91da9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,12 @@ # Changelog +#### 1.9.0 + +* Add base console controller *2017-06-08* + #### 1.8.0 -* Support PHP version 7 *2017-06-05* +* Add base controller, model and text utils *2017-06-05* #### 1.7.0 diff --git a/src/Controller/BaseConsoleController.php b/src/Controller/BaseConsoleController.php new file mode 100644 index 0000000..8ac7423 --- /dev/null +++ b/src/Controller/BaseConsoleController.php @@ -0,0 +1,120 @@ + + * @author Adeyemi Olaoye + * @codeCoverageIgnore + */ +class BaseConsoleController extends Controller +{ + /** @var Connection */ + protected $db; + + /** @var Transaction */ + protected $transaction; + + /** + * @author Olawale Lawal + * @param \yii\base\Action $action + * @return bool + */ + public function beforeAction($action) + { + if (is_null($this->db)) { + $this->db = \Yii::$app->db; + } + return parent::beforeAction($action); + } + + /** + * @author Olawale Lawal + */ + public function beginTransaction() + { + $this->transaction = $this->db->beginTransaction(); + } + + /** + * @author Olawale Lawal + */ + public function commitTransaction() + { + $this->transaction->commit(); + } + + /** + * @author Olawale Lawal + */ + public function rollbackTransaction() + { + $this->transaction->rollBack(); + } + + /** + * @author Olawale Lawal + * @param $table + * @param $field + * @param $value + * @param string $returnColumn + * @return false|null|string + */ + public static function getColumnByField($table, $field, $value, $returnColumn = 'id') + { + return (new Query)->select($returnColumn) + ->from($table)->filterWhere([$field => $value]) + ->scalar(); + } + + public function getRandomOne($table, $column, $conditions = []) + { + return (new Query)->select($column) + ->from($table)->filterWhere($conditions)->orderBy('rand()')->one(); + } + + public function getAll($table, $columns, $conditions = []) + { + return (new Query)->select($columns) + ->from($table)->andFilterWhere($conditions)->all(); + } + + /** + * @author Olawale Lawal + * @param $table + * @param array $columns + * @return int + */ + public function insert($table, array $columns) + { + return $this->db->createCommand()->insert($table, $columns)->execute(); + } + + /** + * @author Olawale Lawal + * @param $table + * @param array $columns + * @param array $rows + * @return int + */ + public function batchInsert($table, array $columns, array $rows) + { + if (empty($rows)) { + return true; + } + + return $this->db->createCommand()->batchInsert($table, $columns, $rows)->execute(); + } + + public function stdout($string) + { + parent::stdout($string . PHP_EOL); + } +}