Skip to content

simplify code according with cakephp 2.xx Cookbook #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 3 additions & 73 deletions Model/Behavior/SubQueryBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,79 +72,9 @@ public function subQuery(Model $model, array $query, $virtualField = true) {
* @return string Raw SQL.
*/
protected function _getQuery(Model $model, array $query) {
$this->_setDataSource($model);
$model->find('all', $query);
$result = $model->getDataSource()->getSql();
$this->_resetDataSource($model);
$db = $model->getDataSource();
$query['table'] = $db->fullTableName($model);
$result = $db->buildStatement($query, $model);
return $result;
}

/**
* Switches the datasource to one that can return raw SQL.
*
* @param Model $model Instance of the model to do the switch on.
*/
protected function _setDataSource(Model $model) {
$ds = $model->getDataSource();
$sourceName = $this->_nameMap[$model->alias] = ConnectionManager::getSourceName($ds);
$dummyName = "_sub_query_$sourceName";
if (!in_array($dummyName, ConnectionManager::sourceList())) {
$config = $ds->config;
$config['datasource'] = $this->_createDatasource($ds);
App::uses($config['datasource'], 'Model/Datasource');
$new = ConnectionManager::create($dummyName, $config);
$new->setConnection($ds->getConnection());
}
$model->setDataSource($dummyName);
}

/**
* Returns the datasource to its original state.
*
* @param Model $model Instance of the model to reset.
*/
protected function _resetDataSource(Model $model) {
$model->setDataSource($this->_nameMap[$model->alias]);
}

/**
* Creates a dummy datasource which can return SQL.
*
* @param DataSource $ds The datasource to fake.
* @return string Name of the created class.
*/
protected function _createDataSource(DataSource $ds) {
$base = get_class($ds);
$class = "SubQuery$base";
if (class_exists($class)) {
return $class;
}
$code = <<<CODE

class $class extends $base {

protected \$_sql = null;

public function connect() {
return true;
}

public function execute(\$sql, \$options = array(), \$params = array()) {
\$this->_sql = \$sql;
return true;
}

public function getSql() {
return \$this->_sql;
}

public function setConnection(\$connection) {
\$this->_connection = \$connection;
}
}

CODE;
eval($code);
return $class;
}
}