public function getCustomBreadrumbs(Model $model, $action) { if ($action == 'change_password') { list(, , $update) = $model->getAdminNames($model); return [['name' => $update, 'url' => $this->getAdminUrl('update', ['pk' => $model->pk])], ['name' => $this->getModule()->t('Change password')]]; } return parent::getCustomBreadrumbs($model, $action); }
public function getQuerySet() { if ($this->_qs === null) { $qs = parent::getQuerySet(); $this->_qs = $qs->filter(array_merge([$this->to => $this->primaryModel->{$this->from}], $this->extra)); if ($this->primaryModel->getIsNewRecord()) { $this->_qs->distinct(); } } return $this->_qs; }
public function getSafeDown() { if (count($this->getMigrations()) == 0) { return $this->space . '$this->dropTable("' . $this->_model->tableName() . '");'; } else { $lines = []; $deleted = []; $fields = $this->getFields(); $lastMigrationFields = $this->getLastMigration(); foreach ($lastMigrationFields as $name => $field) { if (array_key_exists($name, $fields) === false) { $added[$name] = $field; } } foreach ($fields as $name => $field) { if (array_key_exists($name, $lastMigrationFields) === false) { $deleted[$name] = $field; continue; } if ($field['hash'] == $lastMigrationFields[$name]['hash']) { continue; } if ($field['sqlType'] != $lastMigrationFields[$name]['sqlType']) { $lines[] = $this->space . '$this->alterColumn("' . $this->_model->tableName() . '", "' . $name . '", "' . $lastMigrationFields[$name]['sqlType'] . '");'; } elseif ($field['sqlType'] == $lastMigrationFields[$name]['sqlType'] && $fields['length'] != $lastMigrationFields[$name]['length']) { $lines[] = $this->space . '$this->alterColumn("' . $this->_model->tableName() . '", "' . $name . '", "' . $lastMigrationFields[$name]['sqlType'] . '");'; } } foreach ($deleted as $name => $field) { $lines[] = $this->space . '$this->dropColumn("' . $this->_model->tableName() . '", "' . $name . '");'; } return implode("\n", $lines); } }
protected function getModels($module = null) { $checkModule = $module !== null; $models = []; $modelFiles = glob(Alias::get('Modules') . '/*/Models/*.php'); foreach (Alias::find('Contrib.*') as $alias) { $contribModels = glob($alias . '/*/Models/*.php'); if ($contribModels) { $modelFiles = array_merge($modelFiles, $contribModels); } } $modules = []; foreach ($modelFiles as $file) { $moduleName = basename(dirname(dirname($file))); if ($checkModule && $module == $moduleName && Mindy::app()->hasModule($moduleName) || !$checkModule && Mindy::app()->hasModule($moduleName)) { $modules[] = $moduleName; $class = str_replace('.php', '', substr($file, strpos($file, 'Modules'))); $class = str_replace('/', '\\', $class); if (is_subclass_of($class, Model::className())) { $reflectClass = new ReflectionClass($class); if ($reflectClass->isAbstract()) { continue; } $models[$class] = new $class(); } } } echo "Modules:" . PHP_EOL; echo implode(PHP_EOL, array_unique($modules)) . PHP_EOL; return $models; }
protected function linkUnlinkProcess(Model $model, $link = true, array $extra = []) { if ($this->primaryModel->pk === null) { throw new Exception('Unable to unlink models: the primary key of ' . get_class($this->primaryModel) . ' is null.'); } $method = $link ? 'insert' : 'delete'; if ($this->primaryModel->pk === null) { throw new Exception('Unable to ' . ($link ? 'link' : 'unlink') . ' models: the primary key of ' . get_class($this->primaryModel) . ' is null.'); } if ($this->through && $link) { $throughModel = new $this->through(); list($through, $created) = $throughModel->objects()->getOrCreate([$this->primaryModelColumn => $this->primaryModel->pk, $this->modelColumn => $model->pk]); return $through->pk; } else { $db = $this->primaryModel->getDb(); /** @var $command \Mindy\Query\Command */ $command = $db->createCommand()->{$method}($this->relatedTable, array_merge([$this->primaryModelColumn => $this->primaryModel->pk, $this->modelColumn => $model->pk], $extra)); return $command->execute(); } }
/** * Example: * >>> $user = User::objects()->get(['pk' => 1]); * >>> $pages = Page::object()->filter(['user__in' => [$user]])->all(); * @param array $query * @param bool $aliased * @throws \Mindy\Exception\Exception * @return array */ protected function parseLookup(array $query, $aliased = true, $autoGroup = true) { $queryBuilder = $this->getQueryBuilder(); $lookupQuery = []; $lookupParams = []; $resultQuery = []; foreach ($query as $key => $queryItem) { if ($queryItem instanceof Q) { $queryCondition = $queryItem->getQueryCondition(); $expressionQueryJoin = $queryItem->getQueryJoinCondition(); $expressionConditionGroups = $queryItem->getConditions(); $expressionParams = []; $expressionQuery = []; foreach ($expressionConditionGroups as $expressionConditions) { list($conditionQuery, $conditionParams) = $this->parseLookup($expressionConditions, $aliased, $autoGroup); $expressionQuery[] = array_merge($expressionQueryJoin, $conditionQuery); $expressionParams = array_merge($expressionParams, $conditionParams); } $lookupParams = array_merge($lookupParams, $expressionParams); $lookupQuery[] = array_merge($queryCondition, $expressionQuery); } else { $resultQuery[$key] = $queryItem; } } $query = $resultQuery; $lookup = new LookupBuilder($query); foreach ($lookup->parse() as $data) { list($prefix, $field, $condition, $params) = $data; /** @var Model $model */ list($alias, $model) = $this->getOrCreateChainAlias($prefix, false, $autoGroup); if ($field === 'pk') { $field = $model->getPkName(); } if (is_object($params) && ($params instanceof QuerySet || $params instanceof Manager)) { if ($condition != 'in') { throw new Exception("QuerySet object can be used as a parameter only in case of 'in' condition"); } else { if ($params instanceof Manager) { $params = $params->getQuerySet(); } $params->prepareConditions(); } } // https://github.com/studio107/Mindy_Orm/issues/26 if ($model->hasField($field)) { if ($condition == 'in' || $condition == 'exact') { $initField = $model->getField($field); if (is_a($initField, $model::$foreignField)) { $initFieldModelClass = $initField->modelClass; $field .= '_' . $initFieldModelClass::primaryKeyName(); // https://github.com/studio107/Mindy_Orm/issues/29 if ($condition == 'exact') { if (is_a($params, Model::className())) { $params = $params->pk; } } } } } if ($aliased === true || is_string($aliased)) { if (strpos($field, '.') === false) { if (is_string($aliased)) { $field = $aliased . '.' . $field; } else { if ($alias) { $field = $alias . '.' . $field; } } } } $method = 'build' . ucfirst($condition); if (method_exists($this, $method)) { list($query, $params) = $this->{$method}($field, $params); } else { list($query, $params) = $queryBuilder->{$method}($field, $params); } $lookupParams = array_merge($lookupParams, $params); $lookupQuery[] = $query; } return [$lookupQuery, $lookupParams]; }
/** * Truncate table * @return int * @throws \Mindy\Query\Exception */ public function truncate() { return $this->createCommand()->truncateTable($this->model->tableName())->execute(); }
/** * @param $model \Mindy\Orm\Model */ public function dropIndexes(Model $model) { $command = $this->db->createCommand(); try { // checkIntegrity is not supported by SQLite // $command->checkIntegrity(false)->execute(); } catch (NotSupportedException $e) { } foreach ($model->getFields() as $name => $field) { if (is_a($field, '\\Mindy\\Orm\\Fields\\ForeignField')) { /* @var $modelClass Orm */ /* @var $field \Mindy\Orm\Fields\ForeignField */ // $modelClass = $field->relation->modelClass; $command->dropForeignKey("fk_{$name}", $model::tableName()); } } try { // checkIntegrity is not supported by SQLite // $command->checkIntegrity(true)->execute(); } catch (NotSupportedException $e) { } }
/** * Deletes node and it's descendants. * @throws \Exception. * @return boolean whether the deletion is successful. */ public function delete() { if ($this->isLeaf()) { $result = parent::delete(); } else { $result = $this->objects()->filter(['lft__gte' => $this->lft, 'rgt__lte' => $this->rgt, 'root' => $this->root])->delete(); } $this->shiftLeftRight($this->rgt + 1, $this->lft - $this->rgt - 1); return (bool) $result; }
public function login(Model $model, $duration = null) { $time = $model->getDb()->getQueryBuilder()->convertToDateTime(time()); $model->last_login = $time; $model->save(['last_login']); if ($duration === null) { $duration = Mindy::app()->getModule('User')->loginDuration; } $this->saveToCookie($model, $duration); if ($this->absoluteAuthTimeout) { $this->getStorage()->add(self::AUTH_ABSOLUTE_TIMEOUT_VAR, time() + $this->absoluteAuthTimeout); } $model->setIsGuest(false); $this->setModel($model); $sessionId = Mindy::app()->session->getId(); $session = Session::objects()->get(['id' => $sessionId]); if ($session) { $session->user = $model; $session->save(); } $this->getEventManager()->send($this, 'onAuth', $model); if (class_exists('\\Modules\\UserActions\\Models\\UserLog')) { \Modules\UserActions\Models\UserLog::objects()->create(['message' => UserModule::t('User <a href="{url}">{name}</a> logged in', ['{url}' => $model->getAbsoluteUrl(), '{name}' => (string) $model]), 'module' => $model->getModuleName(), 'ip' => $model->getIp(), 'user' => $model]); } return !$this->getIsGuest(); }
/** * @param Model $model * @return QuerySet */ public function getQuerySet(Model $model) { return $model->objects()->getQuerySet()->filter($this->getFilter()); }
* All rights reserved. * * @author Falaleev Maxim * @email max@studio107.ru * @version 1.0 * @company Studio107 * @site http://studio107.ru * @date 03/03/14.03.2014 13:12 */ if (is_dir(__DIR__ . '/../vendor')) { include __DIR__ . '/../vendor/autoload.php'; } else { require __DIR__ . '/../src.php'; } use Mindy\Orm\Model; use Mindy\Orm\Sync; use Mindy\Query\Connection; // Set connection to database Model::setConnection(new Connection(['dsn' => 'mysql:host=localhost;dbname=tmp', 'username' => 'root', 'password' => '123456', 'charset' => 'utf8'])); class MyModel extends Model { } $model = new MyModel(); // Create tables in database $sync = new Sync([$model]); $sync->create(); assert(true == $sync->hasTable($model)); // TODO https://github.com/studio107/Mindy_Orm/issues/9 // assert(0 === $model->objects()->count()); assert('0' === $model->objects()->count()); assert([] === $model->objects()->all());
public function getInfoFields(Model $model) { return array_keys($model->getFieldsInit()); }