repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
yiisoft/yii2-mongodb | src/QueryBuilder.php | QueryBuilder.buildBetweenCondition | public function buildBetweenCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1], $operands[2])) {
throw new InvalidParamException("Operator '$operator' requires three operands.");
}
list($column, $value1, $value2) = $operands;
if (strncmp('NOT', $operator, 3) === 0) {
return [
$column => [
'$lt' => $value1,
'$gt' => $value2,
]
];
}
return [
$column => [
'$gte' => $value1,
'$lte' => $value2,
]
];
} | php | public function buildBetweenCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1], $operands[2])) {
throw new InvalidParamException("Operator '$operator' requires three operands.");
}
list($column, $value1, $value2) = $operands;
if (strncmp('NOT', $operator, 3) === 0) {
return [
$column => [
'$lt' => $value1,
'$gt' => $value2,
]
];
}
return [
$column => [
'$gte' => $value1,
'$lte' => $value2,
]
];
} | [
"public",
"function",
"buildBetweenCondition",
"(",
"$",
"operator",
",",
"$",
"operands",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"operands",
"[",
"0",
"]",
",",
"$",
"operands",
"[",
"1",
"]",
",",
"$",
"operands",
"[",
"2",
"]",
")",
")",
... | Creates an Mongo condition, which emulates the `BETWEEN` operator.
@param string $operator the operator to use
@param array $operands the first operand is the column name. The second and third operands
describe the interval that column value should be in.
@return array the generated Mongo condition.
@throws InvalidParamException if wrong number of operands have been given. | [
"Creates",
"an",
"Mongo",
"condition",
"which",
"emulates",
"the",
"BETWEEN",
"operator",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/QueryBuilder.php#L729-L750 |
yiisoft/yii2-mongodb | src/QueryBuilder.php | QueryBuilder.buildInCondition | public function buildInCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $values) = $operands;
$values = (array) $values;
$operator = $this->normalizeConditionKeyword($operator);
if (!is_array($column)) {
$columns = [$column];
$values = [$column => $values];
} elseif (count($column) > 1) {
return $this->buildCompositeInCondition($operator, $column, $values);
} else {
$columns = $column;
$values = [$column[0] => $values];
}
$result = [];
foreach ($columns as $column) {
if ($column == '_id') {
$inValues = $this->ensureMongoId($values[$column]);
} else {
$inValues = $values[$column];
}
$inValues = array_values($inValues);
if (count($inValues) === 1 && $operator === '$in') {
$result[$column] = $inValues[0];
} else {
$result[$column][$operator] = $inValues;
}
}
return $result;
} | php | public function buildInCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $values) = $operands;
$values = (array) $values;
$operator = $this->normalizeConditionKeyword($operator);
if (!is_array($column)) {
$columns = [$column];
$values = [$column => $values];
} elseif (count($column) > 1) {
return $this->buildCompositeInCondition($operator, $column, $values);
} else {
$columns = $column;
$values = [$column[0] => $values];
}
$result = [];
foreach ($columns as $column) {
if ($column == '_id') {
$inValues = $this->ensureMongoId($values[$column]);
} else {
$inValues = $values[$column];
}
$inValues = array_values($inValues);
if (count($inValues) === 1 && $operator === '$in') {
$result[$column] = $inValues[0];
} else {
$result[$column][$operator] = $inValues;
}
}
return $result;
} | [
"public",
"function",
"buildInCondition",
"(",
"$",
"operator",
",",
"$",
"operands",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"operands",
"[",
"0",
"]",
",",
"$",
"operands",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidParamException",
... | Creates an Mongo condition with the `IN` operator.
@param string $operator the operator to use (e.g. `IN` or `NOT IN`)
@param array $operands the first operand is the column name. If it is an array
a composite IN condition will be generated.
The second operand is an array of values that column value should be among.
@return array the generated Mongo condition.
@throws InvalidParamException if wrong number of operands have been given. | [
"Creates",
"an",
"Mongo",
"condition",
"with",
"the",
"IN",
"operator",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/QueryBuilder.php#L761-L799 |
yiisoft/yii2-mongodb | src/QueryBuilder.php | QueryBuilder.buildRegexCondition | public function buildRegexCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (!($value instanceof Regex)) {
if (preg_match('~\/(.+)\/(.*)~', $value, $matches)) {
$value = new Regex($matches[1], $matches[2]);
} else {
$value = new Regex($value, '');
}
}
return [$column => $value];
} | php | public function buildRegexCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (!($value instanceof Regex)) {
if (preg_match('~\/(.+)\/(.*)~', $value, $matches)) {
$value = new Regex($matches[1], $matches[2]);
} else {
$value = new Regex($value, '');
}
}
return [$column => $value];
} | [
"public",
"function",
"buildRegexCondition",
"(",
"$",
"operator",
",",
"$",
"operands",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"operands",
"[",
"0",
"]",
",",
"$",
"operands",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidParamException"... | Creates a Mongo regular expression condition.
@param string $operator the operator to use
@param array $operands the first operand is the column name.
The second operand is a single value that column value should be compared with.
@return array the generated Mongo condition.
@throws InvalidParamException if wrong number of operands have been given. | [
"Creates",
"a",
"Mongo",
"regular",
"expression",
"condition",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/QueryBuilder.php#L841-L856 |
yiisoft/yii2-mongodb | src/QueryBuilder.php | QueryBuilder.buildLikeCondition | public function buildLikeCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (!($value instanceof Regex)) {
$value = new Regex(preg_quote($value), 'i');
}
return [$column => $value];
} | php | public function buildLikeCondition($operator, $operands)
{
if (!isset($operands[0], $operands[1])) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (!($value instanceof Regex)) {
$value = new Regex(preg_quote($value), 'i');
}
return [$column => $value];
} | [
"public",
"function",
"buildLikeCondition",
"(",
"$",
"operator",
",",
"$",
"operands",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"operands",
"[",
"0",
"]",
",",
"$",
"operands",
"[",
"1",
"]",
")",
")",
"{",
"throw",
"new",
"InvalidParamException",... | Creates a Mongo condition, which emulates the `LIKE` operator.
@param string $operator the operator to use
@param array $operands the first operand is the column name.
The second operand is a single value that column value should be compared with.
@return array the generated Mongo condition.
@throws InvalidParamException if wrong number of operands have been given. | [
"Creates",
"a",
"Mongo",
"condition",
"which",
"emulates",
"the",
"LIKE",
"operator",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/QueryBuilder.php#L866-L877 |
yiisoft/yii2-mongodb | src/QueryBuilder.php | QueryBuilder.buildSimpleCondition | public function buildSimpleCondition($operator, $operands)
{
if (count($operands) !== 2) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (strncmp('$', $operator, 1) !== 0) {
static $operatorMap = [
'>' => '$gt',
'<' => '$lt',
'>=' => '$gte',
'<=' => '$lte',
'!=' => '$ne',
'<>' => '$ne',
'=' => '$eq',
'==' => '$eq',
];
if (isset($operatorMap[$operator])) {
$operator = $operatorMap[$operator];
} else {
throw new InvalidParamException("Unsupported operator '{$operator}'");
}
}
return [$column => [$operator => $value]];
} | php | public function buildSimpleCondition($operator, $operands)
{
if (count($operands) !== 2) {
throw new InvalidParamException("Operator '$operator' requires two operands.");
}
list($column, $value) = $operands;
if (strncmp('$', $operator, 1) !== 0) {
static $operatorMap = [
'>' => '$gt',
'<' => '$lt',
'>=' => '$gte',
'<=' => '$lte',
'!=' => '$ne',
'<>' => '$ne',
'=' => '$eq',
'==' => '$eq',
];
if (isset($operatorMap[$operator])) {
$operator = $operatorMap[$operator];
} else {
throw new InvalidParamException("Unsupported operator '{$operator}'");
}
}
return [$column => [$operator => $value]];
} | [
"public",
"function",
"buildSimpleCondition",
"(",
"$",
"operator",
",",
"$",
"operands",
")",
"{",
"if",
"(",
"count",
"(",
"$",
"operands",
")",
"!==",
"2",
")",
"{",
"throw",
"new",
"InvalidParamException",
"(",
"\"Operator '$operator' requires two operands.\""... | Creates an Mongo condition like `{$operator:{field:value}}`.
@param string $operator the operator to use. Besides regular MongoDB operators, aliases like `>`, `<=`,
and so on, can be used here.
@param array $operands the first operand is the column name.
The second operand is a single value that column value should be compared with.
@return string the generated Mongo condition.
@throws InvalidParamException if wrong number of operands have been given. | [
"Creates",
"an",
"Mongo",
"condition",
"like",
"{",
"$operator",
":",
"{",
"field",
":",
"value",
"}}",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/QueryBuilder.php#L888-L915 |
yiisoft/yii2-mongodb | src/Database.php | Database.getCollection | public function getCollection($name, $refresh = false)
{
if ($refresh || !array_key_exists($name, $this->_collections)) {
$this->_collections[$name] = $this->selectCollection($name);
}
return $this->_collections[$name];
} | php | public function getCollection($name, $refresh = false)
{
if ($refresh || !array_key_exists($name, $this->_collections)) {
$this->_collections[$name] = $this->selectCollection($name);
}
return $this->_collections[$name];
} | [
"public",
"function",
"getCollection",
"(",
"$",
"name",
",",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"!",
"array_key_exists",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"_collections",
")",
")",
"{",
"$",
"this",
"->"... | Returns the Mongo collection with the given name.
@param string $name collection name
@param bool $refresh whether to reload the collection instance even if it is found in the cache.
@return Collection Mongo collection instance. | [
"Returns",
"the",
"Mongo",
"collection",
"with",
"the",
"given",
"name",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Database.php#L48-L55 |
yiisoft/yii2-mongodb | src/Database.php | Database.getFileCollection | public function getFileCollection($prefix = 'fs', $refresh = false)
{
if ($refresh || !array_key_exists($prefix, $this->_fileCollections)) {
$this->_fileCollections[$prefix] = $this->selectFileCollection($prefix);
}
return $this->_fileCollections[$prefix];
} | php | public function getFileCollection($prefix = 'fs', $refresh = false)
{
if ($refresh || !array_key_exists($prefix, $this->_fileCollections)) {
$this->_fileCollections[$prefix] = $this->selectFileCollection($prefix);
}
return $this->_fileCollections[$prefix];
} | [
"public",
"function",
"getFileCollection",
"(",
"$",
"prefix",
"=",
"'fs'",
",",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"!",
"array_key_exists",
"(",
"$",
"prefix",
",",
"$",
"this",
"->",
"_fileCollections",
")",
")",
... | Returns Mongo GridFS collection with given prefix.
@param string $prefix collection prefix.
@param bool $refresh whether to reload the collection instance even if it is found in the cache.
@return file\Collection Mongo GridFS collection. | [
"Returns",
"Mongo",
"GridFS",
"collection",
"with",
"given",
"prefix",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Database.php#L63-L70 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.init | public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::className());
}
} | php | public function init()
{
parent::init();
$this->db = Instance::ensure($this->db, Connection::className());
if ($this->cache !== null) {
$this->cache = Instance::ensure($this->cache, Cache::className());
}
} | [
"public",
"function",
"init",
"(",
")",
"{",
"parent",
"::",
"init",
"(",
")",
";",
"$",
"this",
"->",
"db",
"=",
"Instance",
"::",
"ensure",
"(",
"$",
"this",
"->",
"db",
",",
"Connection",
"::",
"className",
"(",
")",
")",
";",
"if",
"(",
"$",
... | Initializes the application component.
This method overrides the parent implementation by establishing the MongoDB connection. | [
"Initializes",
"the",
"application",
"component",
".",
"This",
"method",
"overrides",
"the",
"parent",
"implementation",
"by",
"establishing",
"the",
"MongoDB",
"connection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L95-L102 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.checkAccess | public function checkAccess($userId, $permissionName, $params = [])
{
$assignments = $this->getAssignments($userId);
$this->loadFromCache();
return $this->items !== null
? $this->checkAccessFromCache($userId, $permissionName, $params, $assignments)
: $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
} | php | public function checkAccess($userId, $permissionName, $params = [])
{
$assignments = $this->getAssignments($userId);
$this->loadFromCache();
return $this->items !== null
? $this->checkAccessFromCache($userId, $permissionName, $params, $assignments)
: $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
} | [
"public",
"function",
"checkAccess",
"(",
"$",
"userId",
",",
"$",
"permissionName",
",",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"assignments",
"=",
"$",
"this",
"->",
"getAssignments",
"(",
"$",
"userId",
")",
";",
"$",
"this",
"->",
"loadFromCa... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L107-L114 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.checkAccessFromCache | protected function checkAccessFromCache($user, $itemName, $params, $assignments)
{
if (!isset($this->items[$itemName])) {
return false;
}
$item = $this->items[$itemName];
Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
if (!$this->executeRule($user, $item, $params)) {
return false;
}
if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
return true;
}
if (!empty($item->parents)) {
foreach ($item->parents as $parent) {
if ($this->checkAccessFromCache($user, $parent, $params, $assignments)) {
return true;
}
}
}
return false;
} | php | protected function checkAccessFromCache($user, $itemName, $params, $assignments)
{
if (!isset($this->items[$itemName])) {
return false;
}
$item = $this->items[$itemName];
Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
if (!$this->executeRule($user, $item, $params)) {
return false;
}
if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
return true;
}
if (!empty($item->parents)) {
foreach ($item->parents as $parent) {
if ($this->checkAccessFromCache($user, $parent, $params, $assignments)) {
return true;
}
}
}
return false;
} | [
"protected",
"function",
"checkAccessFromCache",
"(",
"$",
"user",
",",
"$",
"itemName",
",",
"$",
"params",
",",
"$",
"assignments",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"items",
"[",
"$",
"itemName",
"]",
")",
")",
"{",
"retur... | Performs access check for the specified user based on the data loaded from cache.
This method is internally called by [[checkAccess()]] when [[cache]] is enabled.
@param string|int $user the user ID. This should can be either an integer or a string representing
the unique identifier of a user. See [[\yii\web\User::id]].
@param string $itemName the name of the operation that need access check
@param array $params name-value pairs that would be passed to rules associated
with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
which holds the value of `$userId`.
@param Assignment[] $assignments the assignments to the specified user
@return bool whether the operations can be performed by the user. | [
"Performs",
"access",
"check",
"for",
"the",
"specified",
"user",
"based",
"on",
"the",
"data",
"loaded",
"from",
"cache",
".",
"This",
"method",
"is",
"internally",
"called",
"by",
"[[",
"checkAccess",
"()",
"]]",
"when",
"[[",
"cache",
"]]",
"is",
"enabl... | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L128-L155 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.addItem | protected function addItem($item)
{
$time = time();
if ($item->createdAt === null) {
$item->createdAt = $time;
}
if ($item->updatedAt === null) {
$item->updatedAt = $time;
}
$this->db->getCollection($this->itemCollection)
->insert([
'name' => $item->name,
'type' => $item->type,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'created_at' => $item->createdAt,
'updated_at' => $item->updatedAt,
]);
$this->invalidateCache();
return true;
} | php | protected function addItem($item)
{
$time = time();
if ($item->createdAt === null) {
$item->createdAt = $time;
}
if ($item->updatedAt === null) {
$item->updatedAt = $time;
}
$this->db->getCollection($this->itemCollection)
->insert([
'name' => $item->name,
'type' => $item->type,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'created_at' => $item->createdAt,
'updated_at' => $item->updatedAt,
]);
$this->invalidateCache();
return true;
} | [
"protected",
"function",
"addItem",
"(",
"$",
"item",
")",
"{",
"$",
"time",
"=",
"time",
"(",
")",
";",
"if",
"(",
"$",
"item",
"->",
"createdAt",
"===",
"null",
")",
"{",
"$",
"item",
"->",
"createdAt",
"=",
"$",
"time",
";",
"}",
"if",
"(",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L240-L264 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeItem | protected function removeItem($item)
{
$this->db->getCollection($this->assignmentCollection)
->remove(['item_name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->remove(['name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$pull' => [
'parents' => [
'$in' => [$item->name],
]
]
],
[
'multi' => true
]
);
$this->invalidateCache();
return true;
} | php | protected function removeItem($item)
{
$this->db->getCollection($this->assignmentCollection)
->remove(['item_name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->remove(['name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$pull' => [
'parents' => [
'$in' => [$item->name],
]
]
],
[
'multi' => true
]
);
$this->invalidateCache();
return true;
} | [
"protected",
"function",
"removeItem",
"(",
"$",
"item",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"assignmentCollection",
")",
"->",
"remove",
"(",
"[",
"'item_name'",
"=>",
"$",
"item",
"->",
"name",
"]",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L294-L324 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeRule | protected function removeRule($rule)
{
$this->db->getCollection($this->itemCollection)
->update(['rule_name' => $rule->name], ['rule_name' => null]);
$this->db->getCollection($this->ruleCollection)
->remove(['name' => $rule->name]);
$this->invalidateCache();
return true;
} | php | protected function removeRule($rule)
{
$this->db->getCollection($this->itemCollection)
->update(['rule_name' => $rule->name], ['rule_name' => null]);
$this->db->getCollection($this->ruleCollection)
->remove(['name' => $rule->name]);
$this->invalidateCache();
return true;
} | [
"protected",
"function",
"removeRule",
"(",
"$",
"rule",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"update",
"(",
"[",
"'rule_name'",
"=>",
"$",
"rule",
"->",
"name",
"]",
",",
"[",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L329-L340 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.updateItem | protected function updateItem($name, $item)
{
if ($item->name !== $name) {
$this->db->getCollection($this->assignmentCollection)
->update(['item_name' => $name], ['item_name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$pull' => [
'parents' => [
'$in' => [$item->name],
]
],
],
[
'multi' => true
]
);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$push' => [
'parents' => $name
]
],
[
'multi' => true
]
);
}
$item->updatedAt = time();
$this->db->getCollection($this->itemCollection)
->update(
[
'name' => $name,
],
[
'name' => $item->name,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'updated_at' => $item->updatedAt,
]
);
$this->invalidateCache();
return true;
} | php | protected function updateItem($name, $item)
{
if ($item->name !== $name) {
$this->db->getCollection($this->assignmentCollection)
->update(['item_name' => $name], ['item_name' => $item->name]);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$pull' => [
'parents' => [
'$in' => [$item->name],
]
],
],
[
'multi' => true
]
);
$this->db->getCollection($this->itemCollection)
->update(
[
'parents' => [
'$in' => [$item->name]
],
],
[
'$push' => [
'parents' => $name
]
],
[
'multi' => true
]
);
}
$item->updatedAt = time();
$this->db->getCollection($this->itemCollection)
->update(
[
'name' => $name,
],
[
'name' => $item->name,
'description' => $item->description,
'rule_name' => $item->ruleName,
'data' => $item->data === null ? null : serialize($item->data),
'updated_at' => $item->updatedAt,
]
);
$this->invalidateCache();
return true;
} | [
"protected",
"function",
"updateItem",
"(",
"$",
"name",
",",
"$",
"item",
")",
"{",
"if",
"(",
"$",
"item",
"->",
"name",
"!==",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"assignmentCollection",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L345-L407 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.updateRule | protected function updateRule($name, $rule)
{
if ($rule->name !== $name) {
$this->db->getCollection($this->itemCollection)
->update(['rule_name' => $name], ['rule_name' => $rule->name]);
}
$rule->updatedAt = time();
$this->db->getCollection($this->ruleCollection)
->update(
[
'name' => $name,
],
[
'name' => $rule->name,
'data' => serialize($rule),
'updated_at' => $rule->updatedAt,
]
);
$this->invalidateCache();
return true;
} | php | protected function updateRule($name, $rule)
{
if ($rule->name !== $name) {
$this->db->getCollection($this->itemCollection)
->update(['rule_name' => $name], ['rule_name' => $rule->name]);
}
$rule->updatedAt = time();
$this->db->getCollection($this->ruleCollection)
->update(
[
'name' => $name,
],
[
'name' => $rule->name,
'data' => serialize($rule),
'updated_at' => $rule->updatedAt,
]
);
$this->invalidateCache();
return true;
} | [
"protected",
"function",
"updateRule",
"(",
"$",
"name",
",",
"$",
"rule",
")",
"{",
"if",
"(",
"$",
"rule",
"->",
"name",
"!==",
"$",
"name",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L412-L436 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getRolesByUser | public function getRolesByUser($userId)
{
if (!isset($userId) || $userId === '') {
return [];
}
$roles = $this->instantiateDefaultRoles();
$rows = (new Query())
->select(['item_name'])
->from($this->assignmentCollection)
->where(['user_id' => (string) $userId])
->all($this->db);
if (empty($rows)) {
return $roles;
}
$itemNames = ArrayHelper::getColumn($rows, 'item_name');
$query = (new Query())
->from($this->itemCollection)
->where(['name' => $itemNames])
->andWhere(['type' => Item::TYPE_ROLE]);
foreach ($query->all($this->db) as $row) {
$roles[$row['name']] = $this->populateItem($row);
}
return $roles;
} | php | public function getRolesByUser($userId)
{
if (!isset($userId) || $userId === '') {
return [];
}
$roles = $this->instantiateDefaultRoles();
$rows = (new Query())
->select(['item_name'])
->from($this->assignmentCollection)
->where(['user_id' => (string) $userId])
->all($this->db);
if (empty($rows)) {
return $roles;
}
$itemNames = ArrayHelper::getColumn($rows, 'item_name');
$query = (new Query())
->from($this->itemCollection)
->where(['name' => $itemNames])
->andWhere(['type' => Item::TYPE_ROLE]);
foreach ($query->all($this->db) as $row) {
$roles[$row['name']] = $this->populateItem($row);
}
return $roles;
} | [
"public",
"function",
"getRolesByUser",
"(",
"$",
"userId",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"userId",
")",
"||",
"$",
"userId",
"===",
"''",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"roles",
"=",
"$",
"this",
"->",
"instantiateDefa... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L441-L471 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getPermissionsByUser | public function getPermissionsByUser($userId)
{
if (empty($userId)) {
return [];
}
$this->getAssignments($userId);
$rows = (new Query)
->select(['item_name'])
->from($this->assignmentCollection)
->where(['user_id' => (string) $userId])
->all($this->db);
if (empty($rows)) {
return [];
}
$names = ArrayHelper::getColumn($rows, 'item_name');
$childrenList = $this->getChildrenList();
$result = [];
foreach ($names as $roleName) {
$this->getChildrenRecursive($roleName, $childrenList, $result);
}
$names = array_merge($names, array_keys($result));
$query = (new Query)
->from($this->itemCollection)
->where([
'type' => Item::TYPE_PERMISSION,
'name' => $names,
]);
$permissions = [];
foreach ($query->all($this->db) as $row) {
$permissions[$row['name']] = $this->populateItem($row);
}
return $permissions;
} | php | public function getPermissionsByUser($userId)
{
if (empty($userId)) {
return [];
}
$this->getAssignments($userId);
$rows = (new Query)
->select(['item_name'])
->from($this->assignmentCollection)
->where(['user_id' => (string) $userId])
->all($this->db);
if (empty($rows)) {
return [];
}
$names = ArrayHelper::getColumn($rows, 'item_name');
$childrenList = $this->getChildrenList();
$result = [];
foreach ($names as $roleName) {
$this->getChildrenRecursive($roleName, $childrenList, $result);
}
$names = array_merge($names, array_keys($result));
$query = (new Query)
->from($this->itemCollection)
->where([
'type' => Item::TYPE_PERMISSION,
'name' => $names,
]);
$permissions = [];
foreach ($query->all($this->db) as $row) {
$permissions[$row['name']] = $this->populateItem($row);
}
return $permissions;
} | [
"public",
"function",
"getPermissionsByUser",
"(",
"$",
"userId",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"userId",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"this",
"->",
"getAssignments",
"(",
"$",
"userId",
")",
";",
"$",
"rows",
"=",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L525-L565 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getRule | public function getRule($name)
{
if ($this->rules !== null) {
return isset($this->rules[$name]) ? $this->rules[$name] : null;
}
$row = (new Query)->select(['data'])
->from($this->ruleCollection)
->where(['name' => $name])
->one($this->db);
return $row === false ? null : unserialize($row['data']);
} | php | public function getRule($name)
{
if ($this->rules !== null) {
return isset($this->rules[$name]) ? $this->rules[$name] : null;
}
$row = (new Query)->select(['data'])
->from($this->ruleCollection)
->where(['name' => $name])
->one($this->db);
return $row === false ? null : unserialize($row['data']);
} | [
"public",
"function",
"getRule",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"rules",
"!==",
"null",
")",
"{",
"return",
"isset",
"(",
"$",
"this",
"->",
"rules",
"[",
"$",
"name",
"]",
")",
"?",
"$",
"this",
"->",
"rules",
"[",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L570-L581 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getRules | public function getRules()
{
if ($this->rules !== null) {
return $this->rules;
}
$query = (new Query)->from($this->ruleCollection);
$rules = [];
foreach ($query->all($this->db) as $row) {
$rules[$row['name']] = unserialize($row['data']);
}
return $rules;
} | php | public function getRules()
{
if ($this->rules !== null) {
return $this->rules;
}
$query = (new Query)->from($this->ruleCollection);
$rules = [];
foreach ($query->all($this->db) as $row) {
$rules[$row['name']] = unserialize($row['data']);
}
return $rules;
} | [
"public",
"function",
"getRules",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"rules",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"rules",
";",
"}",
"$",
"query",
"=",
"(",
"new",
"Query",
")",
"->",
"from",
"(",
"$",
"this",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L586-L600 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.addChild | public function addChild($parent, $child)
{
if ($parent->name === $child->name) {
throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
}
if ($parent instanceof Permission && $child instanceof Role) {
throw new InvalidParamException('Cannot add a role as a child of a permission.');
}
if ($this->detectLoop($parent, $child)) {
throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
}
$result = $this->db->getCollection($this->itemCollection)
->update(
[
'name' => $child->name,
],
[
'$push' => [
'parents' => $parent->name
]
],
[
'multi' => false
]
) > 0;
$this->invalidateCache();
return $result;
} | php | public function addChild($parent, $child)
{
if ($parent->name === $child->name) {
throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
}
if ($parent instanceof Permission && $child instanceof Role) {
throw new InvalidParamException('Cannot add a role as a child of a permission.');
}
if ($this->detectLoop($parent, $child)) {
throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
}
$result = $this->db->getCollection($this->itemCollection)
->update(
[
'name' => $child->name,
],
[
'$push' => [
'parents' => $parent->name
]
],
[
'multi' => false
]
) > 0;
$this->invalidateCache();
return $result;
} | [
"public",
"function",
"addChild",
"(",
"$",
"parent",
",",
"$",
"child",
")",
"{",
"if",
"(",
"$",
"parent",
"->",
"name",
"===",
"$",
"child",
"->",
"name",
")",
"{",
"throw",
"new",
"InvalidParamException",
"(",
"\"Cannot add '{$parent->name}' as a child of ... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L613-L645 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeChild | public function removeChild($parent, $child)
{
$result = $this->db->getCollection($this->itemCollection)
->update(
[
'name' => $child->name,
],
[
'$pull' => [
'parents' => [
'$in' => [$parent->name]
]
]
],
[
'multi' => false
]
) > 0;
$this->invalidateCache();
return $result;
} | php | public function removeChild($parent, $child)
{
$result = $this->db->getCollection($this->itemCollection)
->update(
[
'name' => $child->name,
],
[
'$pull' => [
'parents' => [
'$in' => [$parent->name]
]
]
],
[
'multi' => false
]
) > 0;
$this->invalidateCache();
return $result;
} | [
"public",
"function",
"removeChild",
"(",
"$",
"parent",
",",
"$",
"child",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"update",
"(",
"[",
"'name'",
"=>",
"$",
"c... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L650-L672 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeChildren | public function removeChildren($parent)
{
$result = $this->db->getCollection($this->itemCollection)
->update(
[],
[
'$pull' => [
'parents' => [
'$in' => [$parent->name]
]
]
],
[
'multi' => true
]
) > 0;
$this->invalidateCache();
return $result;
} | php | public function removeChildren($parent)
{
$result = $this->db->getCollection($this->itemCollection)
->update(
[],
[
'$pull' => [
'parents' => [
'$in' => [$parent->name]
]
]
],
[
'multi' => true
]
) > 0;
$this->invalidateCache();
return $result;
} | [
"public",
"function",
"removeChildren",
"(",
"$",
"parent",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"update",
"(",
"[",
"]",
",",
"[",
"'$pull'",
"=>",
"[",
"'... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L677-L697 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.hasChild | public function hasChild($parent, $child)
{
return (new Query)
->from($this->itemCollection)
->where([
'name' => $child->name
])
->andWhere([
'parents' => [
'$in' => [$parent->name]
]
])
->one($this->db) !== false;
} | php | public function hasChild($parent, $child)
{
return (new Query)
->from($this->itemCollection)
->where([
'name' => $child->name
])
->andWhere([
'parents' => [
'$in' => [$parent->name]
]
])
->one($this->db) !== false;
} | [
"public",
"function",
"hasChild",
"(",
"$",
"parent",
",",
"$",
"child",
")",
"{",
"return",
"(",
"new",
"Query",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"where",
"(",
"[",
"'name'",
"=>",
"$",
"child",
"->",
"name",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L702-L715 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getChildren | public function getChildren($name)
{
$query = (new Query)
->from($this->itemCollection)
->where([
'parents' => [
'$in' => [$name]
]
]);
$children = [];
foreach ($query->all($this->db) as $row) {
$children[$row['name']] = $this->populateItem($row);
}
return $children;
} | php | public function getChildren($name)
{
$query = (new Query)
->from($this->itemCollection)
->where([
'parents' => [
'$in' => [$name]
]
]);
$children = [];
foreach ($query->all($this->db) as $row) {
$children[$row['name']] = $this->populateItem($row);
}
return $children;
} | [
"public",
"function",
"getChildren",
"(",
"$",
"name",
")",
"{",
"$",
"query",
"=",
"(",
"new",
"Query",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"where",
"(",
"[",
"'parents'",
"=>",
"[",
"'$in'",
"=>",
"[",
"$",
"na... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L720-L736 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.assign | public function assign($role, $userId)
{
$assignment = new Assignment([
'userId' => (string)$userId,
'roleName' => $role->name,
'createdAt' => time(),
]);
$this->db->getCollection($this->assignmentCollection)
->insert([
'user_id' => $assignment->userId,
'item_name' => $assignment->roleName,
'created_at' => $assignment->createdAt,
]);
return $assignment;
} | php | public function assign($role, $userId)
{
$assignment = new Assignment([
'userId' => (string)$userId,
'roleName' => $role->name,
'createdAt' => time(),
]);
$this->db->getCollection($this->assignmentCollection)
->insert([
'user_id' => $assignment->userId,
'item_name' => $assignment->roleName,
'created_at' => $assignment->createdAt,
]);
return $assignment;
} | [
"public",
"function",
"assign",
"(",
"$",
"role",
",",
"$",
"userId",
")",
"{",
"$",
"assignment",
"=",
"new",
"Assignment",
"(",
"[",
"'userId'",
"=>",
"(",
"string",
")",
"$",
"userId",
",",
"'roleName'",
"=>",
"$",
"role",
"->",
"name",
",",
"'cre... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L741-L757 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.revoke | public function revoke($role, $userId)
{
if (empty($userId)) {
return false;
}
return $this->db->getCollection($this->assignmentCollection)
->remove(['user_id' => (string) $userId, 'item_name' => $role->name]) > 0;
} | php | public function revoke($role, $userId)
{
if (empty($userId)) {
return false;
}
return $this->db->getCollection($this->assignmentCollection)
->remove(['user_id' => (string) $userId, 'item_name' => $role->name]) > 0;
} | [
"public",
"function",
"revoke",
"(",
"$",
"role",
",",
"$",
"userId",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"userId",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L762-L770 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.revokeAll | public function revokeAll($userId)
{
if (empty($userId)) {
return false;
}
return $this->db->getCollection($this->assignmentCollection)
->remove(['user_id' => (string) $userId]) > 0;
} | php | public function revokeAll($userId)
{
if (empty($userId)) {
return false;
}
return $this->db->getCollection($this->assignmentCollection)
->remove(['user_id' => (string) $userId]) > 0;
} | [
"public",
"function",
"revokeAll",
"(",
"$",
"userId",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"userId",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"assignmentCollection... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L775-L783 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getUserIdsByRole | public function getUserIdsByRole($roleName)
{
if (empty($roleName)) {
return [];
}
$rows = (new Query)->select(['user_id'])
->from($this->assignmentCollection)
->where(['item_name' => $roleName])
->all($this->db);
return ArrayHelper::getColumn($rows, 'user_id');
} | php | public function getUserIdsByRole($roleName)
{
if (empty($roleName)) {
return [];
}
$rows = (new Query)->select(['user_id'])
->from($this->assignmentCollection)
->where(['item_name' => $roleName])
->all($this->db);
return ArrayHelper::getColumn($rows, 'user_id');
} | [
"public",
"function",
"getUserIdsByRole",
"(",
"$",
"roleName",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"roleName",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"rows",
"=",
"(",
"new",
"Query",
")",
"->",
"select",
"(",
"[",
"'user_id'",
"]",... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L837-L849 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeAll | public function removeAll()
{
$this->removeAllAssignments();
$this->db->getCollection($this->itemCollection)->remove();
$this->db->getCollection($this->ruleCollection)->remove();
$this->invalidateCache();
} | php | public function removeAll()
{
$this->removeAllAssignments();
$this->db->getCollection($this->itemCollection)->remove();
$this->db->getCollection($this->ruleCollection)->remove();
$this->invalidateCache();
} | [
"public",
"function",
"removeAll",
"(",
")",
"{",
"$",
"this",
"->",
"removeAllAssignments",
"(",
")",
";",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"remove",
"(",
")",
";",
"$",
"this",
"->",... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L854-L860 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeAllRules | public function removeAllRules()
{
$this->db->getCollection($this->itemCollection)
->update([], ['rule_name' => null]);
$this->db->getCollection($this->ruleCollection)->remove();
$this->invalidateCache();
} | php | public function removeAllRules()
{
$this->db->getCollection($this->itemCollection)
->update([], ['rule_name' => null]);
$this->db->getCollection($this->ruleCollection)->remove();
$this->invalidateCache();
} | [
"public",
"function",
"removeAllRules",
"(",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"update",
"(",
"[",
"]",
",",
"[",
"'rule_name'",
"=>",
"null",
"]",
")",
";",
"$",
"this",
"-... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L881-L889 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.populateItem | protected function populateItem($row)
{
$class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
$data = null;
}
return new $class([
'name' => $row['name'],
'type' => $row['type'],
'description' => $row['description'],
'ruleName' => $row['rule_name'],
'data' => $data,
'createdAt' => $row['created_at'],
'updatedAt' => $row['updated_at'],
'parents' => isset($row['parents']) ? $row['parents'] : null,
]);
} | php | protected function populateItem($row)
{
$class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
$data = null;
}
return new $class([
'name' => $row['name'],
'type' => $row['type'],
'description' => $row['description'],
'ruleName' => $row['rule_name'],
'data' => $data,
'createdAt' => $row['created_at'],
'updatedAt' => $row['updated_at'],
'parents' => isset($row['parents']) ? $row['parents'] : null,
]);
} | [
"protected",
"function",
"populateItem",
"(",
"$",
"row",
")",
"{",
"$",
"class",
"=",
"$",
"row",
"[",
"'type'",
"]",
"==",
"Item",
"::",
"TYPE_PERMISSION",
"?",
"Permission",
"::",
"className",
"(",
")",
":",
"Role",
"::",
"className",
"(",
")",
";",... | Populates an auth item with the data fetched from collection
@param array $row the data from the auth item collection
@return Item the populated auth item instance (either Role or Permission) | [
"Populates",
"an",
"auth",
"item",
"with",
"the",
"data",
"fetched",
"from",
"collection"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L916-L934 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.removeAllItems | protected function removeAllItems($type)
{
$rows = (new Query)
->select(['name'])
->from($this->itemCollection)
->where(['type' => $type])
->all($this->db);
if (empty($rows)) {
return;
}
$names = ArrayHelper::getColumn($rows, 'name');
$this->db->getCollection($this->assignmentCollection)
->remove(['item_name' => $names]);
$this->db->getCollection($this->itemCollection)
->remove(['type' => $type]);
$this->db->getCollection($this->itemCollection)
->update(
[],
[
'$pull' => [
'parents' => [
'$in' => $names,
]
],
],
[
'multi' => true
]
);
$this->invalidateCache();
} | php | protected function removeAllItems($type)
{
$rows = (new Query)
->select(['name'])
->from($this->itemCollection)
->where(['type' => $type])
->all($this->db);
if (empty($rows)) {
return;
}
$names = ArrayHelper::getColumn($rows, 'name');
$this->db->getCollection($this->assignmentCollection)
->remove(['item_name' => $names]);
$this->db->getCollection($this->itemCollection)
->remove(['type' => $type]);
$this->db->getCollection($this->itemCollection)
->update(
[],
[
'$pull' => [
'parents' => [
'$in' => $names,
]
],
],
[
'multi' => true
]
);
$this->invalidateCache();
} | [
"protected",
"function",
"removeAllItems",
"(",
"$",
"type",
")",
"{",
"$",
"rows",
"=",
"(",
"new",
"Query",
")",
"->",
"select",
"(",
"[",
"'name'",
"]",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"itemCollection",
")",
"->",
"where",
"(",
"[",
"... | Removes all auth items of the specified type.
@param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE) | [
"Removes",
"all",
"auth",
"items",
"of",
"the",
"specified",
"type",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L940-L975 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.loadFromCache | public function loadFromCache()
{
if ($this->items !== null || !$this->cache instanceof Cache) {
return;
}
$data = $this->cache->get($this->cacheKey);
if (is_array($data) && isset($data[0], $data[1])) {
list ($this->items, $this->rules) = $data;
return;
}
$query = (new Query)->from($this->itemCollection);
$this->items = [];
foreach ($query->all($this->db) as $row) {
$this->items[$row['name']] = $this->populateItem($row);
}
$query = (new Query)->from($this->ruleCollection);
$this->rules = [];
foreach ($query->all($this->db) as $row) {
$this->rules[$row['name']] = unserialize($row['data']);
}
$this->cache->set($this->cacheKey, [$this->items, $this->rules]);
} | php | public function loadFromCache()
{
if ($this->items !== null || !$this->cache instanceof Cache) {
return;
}
$data = $this->cache->get($this->cacheKey);
if (is_array($data) && isset($data[0], $data[1])) {
list ($this->items, $this->rules) = $data;
return;
}
$query = (new Query)->from($this->itemCollection);
$this->items = [];
foreach ($query->all($this->db) as $row) {
$this->items[$row['name']] = $this->populateItem($row);
}
$query = (new Query)->from($this->ruleCollection);
$this->rules = [];
foreach ($query->all($this->db) as $row) {
$this->rules[$row['name']] = unserialize($row['data']);
}
$this->cache->set($this->cacheKey, [$this->items, $this->rules]);
} | [
"public",
"function",
"loadFromCache",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"items",
"!==",
"null",
"||",
"!",
"$",
"this",
"->",
"cache",
"instanceof",
"Cache",
")",
"{",
"return",
";",
"}",
"$",
"data",
"=",
"$",
"this",
"->",
"cache",
"-... | Loads data from cache | [
"Loads",
"data",
"from",
"cache"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L980-L1005 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.getChildrenList | protected function getChildrenList()
{
$query = (new Query)
->select(['name', 'parents'])
->from($this->itemCollection);
$children = [];
foreach ($query->all($this->db) as $row) {
if (!empty($row['parents'])) {
foreach ($row['parents'] as $name) {
$children[$name][] = $row['name'];
}
}
}
return $children;
} | php | protected function getChildrenList()
{
$query = (new Query)
->select(['name', 'parents'])
->from($this->itemCollection);
$children = [];
foreach ($query->all($this->db) as $row) {
if (!empty($row['parents'])) {
foreach ($row['parents'] as $name) {
$children[$name][] = $row['name'];
}
}
}
return $children;
} | [
"protected",
"function",
"getChildrenList",
"(",
")",
"{",
"$",
"query",
"=",
"(",
"new",
"Query",
")",
"->",
"select",
"(",
"[",
"'name'",
",",
"'parents'",
"]",
")",
"->",
"from",
"(",
"$",
"this",
"->",
"itemCollection",
")",
";",
"$",
"children",
... | Returns the children for every parent.
@return array the children list. Each array key is a parent item name,
and the corresponding array value is a list of child item names. | [
"Returns",
"the",
"children",
"for",
"every",
"parent",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L1012-L1026 |
yiisoft/yii2-mongodb | src/rbac/MongoDbManager.php | MongoDbManager.instantiateDefaultRoles | private function instantiateDefaultRoles()
{
// this method can be removed in favor of `yii\rbac\BaseManager::getDefaultRoles()` in case
// extension dependency on `yii2` is raised up to 2.0.12
$result = [];
foreach ($this->defaultRoles as $roleName) {
$result[$roleName] = $this->createRole($roleName);
}
return $result;
} | php | private function instantiateDefaultRoles()
{
// this method can be removed in favor of `yii\rbac\BaseManager::getDefaultRoles()` in case
// extension dependency on `yii2` is raised up to 2.0.12
$result = [];
foreach ($this->defaultRoles as $roleName) {
$result[$roleName] = $this->createRole($roleName);
}
return $result;
} | [
"private",
"function",
"instantiateDefaultRoles",
"(",
")",
"{",
"// this method can be removed in favor of `yii\\rbac\\BaseManager::getDefaultRoles()` in case",
"// extension dependency on `yii2` is raised up to 2.0.12",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"thi... | Returns defaultRoles as array of Role objects
@since 2.1.3
@return Role[] default roles. The array is indexed by the role names | [
"Returns",
"defaultRoles",
"as",
"array",
"of",
"Role",
"objects"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/rbac/MongoDbManager.php#L1068-L1077 |
yiisoft/yii2-mongodb | src/debug/MongoDbPanel.php | MongoDbPanel.getDetail | public function getDetail()
{
$searchModel = new Db();
if (!$searchModel->load(Yii::$app->request->getQueryParams())) {
$searchModel->load($this->defaultFilter, '');
}
$dataProvider = $searchModel->search($this->getModels());
$dataProvider->getSort()->defaultOrder = $this->defaultOrder;
return Yii::$app->view->render('@yii/mongodb/debug/views/detail', [
'panel' => $this,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
} | php | public function getDetail()
{
$searchModel = new Db();
if (!$searchModel->load(Yii::$app->request->getQueryParams())) {
$searchModel->load($this->defaultFilter, '');
}
$dataProvider = $searchModel->search($this->getModels());
$dataProvider->getSort()->defaultOrder = $this->defaultOrder;
return Yii::$app->view->render('@yii/mongodb/debug/views/detail', [
'panel' => $this,
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
]);
} | [
"public",
"function",
"getDetail",
"(",
")",
"{",
"$",
"searchModel",
"=",
"new",
"Db",
"(",
")",
";",
"if",
"(",
"!",
"$",
"searchModel",
"->",
"load",
"(",
"Yii",
"::",
"$",
"app",
"->",
"request",
"->",
"getQueryParams",
"(",
")",
")",
")",
"{",... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/debug/MongoDbPanel.php#L61-L77 |
yiisoft/yii2-mongodb | src/debug/MongoDbPanel.php | MongoDbPanel.getQueryType | protected function getQueryType($timing)
{
$timing = ltrim($timing);
$timing = mb_substr($timing, 0, mb_strpos($timing, '('), 'utf8');
$matches = explode('.', $timing);
return count($matches) ? array_pop($matches) : '';
} | php | protected function getQueryType($timing)
{
$timing = ltrim($timing);
$timing = mb_substr($timing, 0, mb_strpos($timing, '('), 'utf8');
$matches = explode('.', $timing);
return count($matches) ? array_pop($matches) : '';
} | [
"protected",
"function",
"getQueryType",
"(",
"$",
"timing",
")",
"{",
"$",
"timing",
"=",
"ltrim",
"(",
"$",
"timing",
")",
";",
"$",
"timing",
"=",
"mb_substr",
"(",
"$",
"timing",
",",
"0",
",",
"mb_strpos",
"(",
"$",
"timing",
",",
"'('",
")",
... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/debug/MongoDbPanel.php#L105-L112 |
yiisoft/yii2-mongodb | src/validators/MongoIdValidator.php | MongoIdValidator.validateAttribute | public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$mongoId = $this->parseMongoId($value);
if (is_object($mongoId)) {
if ($this->forceFormat !== null) {
switch ($this->forceFormat) {
case 'string' : {
$model->$attribute = $mongoId->__toString();
break;
}
case 'object' : {
$model->$attribute = $mongoId;
break;
}
default: {
throw new InvalidConfigException("Unrecognized format '{$this->forceFormat}'");
}
}
}
} else {
$this->addError($model, $attribute, $this->message, []);
}
} | php | public function validateAttribute($model, $attribute)
{
$value = $model->$attribute;
$mongoId = $this->parseMongoId($value);
if (is_object($mongoId)) {
if ($this->forceFormat !== null) {
switch ($this->forceFormat) {
case 'string' : {
$model->$attribute = $mongoId->__toString();
break;
}
case 'object' : {
$model->$attribute = $mongoId;
break;
}
default: {
throw new InvalidConfigException("Unrecognized format '{$this->forceFormat}'");
}
}
}
} else {
$this->addError($model, $attribute, $this->message, []);
}
} | [
"public",
"function",
"validateAttribute",
"(",
"$",
"model",
",",
"$",
"attribute",
")",
"{",
"$",
"value",
"=",
"$",
"model",
"->",
"$",
"attribute",
";",
"$",
"mongoId",
"=",
"$",
"this",
"->",
"parseMongoId",
"(",
"$",
"value",
")",
";",
"if",
"(... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/validators/MongoIdValidator.php#L67-L90 |
yiisoft/yii2-mongodb | src/ActiveRecord.php | ActiveRecord.insert | public function insert($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
return false;
}
$result = $this->insertInternal($attributes);
return $result;
} | php | public function insert($runValidation = true, $attributes = null)
{
if ($runValidation && !$this->validate($attributes)) {
return false;
}
$result = $this->insertInternal($attributes);
return $result;
} | [
"public",
"function",
"insert",
"(",
"$",
"runValidation",
"=",
"true",
",",
"$",
"attributes",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"runValidation",
"&&",
"!",
"$",
"this",
"->",
"validate",
"(",
"$",
"attributes",
")",
")",
"{",
"return",
"false",
... | Inserts a row into the associated Mongo collection using the attribute values of this record.
This method performs the following steps in order:
1. call [[beforeValidate()]] when `$runValidation` is true. If validation
fails, it will skip the rest of the steps;
2. call [[afterValidate()]] when `$runValidation` is true.
3. call [[beforeSave()]]. If the method returns false, it will skip the
rest of the steps;
4. insert the record into collection. If this fails, it will skip the rest of the steps;
5. call [[afterSave()]];
In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
[[EVENT_BEFORE_INSERT]], [[EVENT_AFTER_INSERT]] and [[EVENT_AFTER_VALIDATE]]
will be raised by the corresponding methods.
Only the [[dirtyAttributes|changed attribute values]] will be inserted into database.
If the primary key is null during insertion, it will be populated with the actual
value after insertion.
For example, to insert a customer record:
```php
$customer = new Customer();
$customer->name = $name;
$customer->email = $email;
$customer->insert();
```
@param bool $runValidation whether to perform validation before saving the record.
If the validation fails, the record will not be inserted into the collection.
@param array $attributes list of attributes that need to be saved. Defaults to null,
meaning all attributes that are loaded will be saved.
@return bool whether the attributes are valid and the record is inserted successfully.
@throws \Exception in case insert failed. | [
"Inserts",
"a",
"row",
"into",
"the",
"associated",
"Mongo",
"collection",
"using",
"the",
"attribute",
"values",
"of",
"this",
"record",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveRecord.php#L206-L214 |
yiisoft/yii2-mongodb | src/ActiveRecord.php | ActiveRecord.delete | public function delete()
{
$result = false;
if ($this->beforeDelete()) {
$result = $this->deleteInternal();
$this->afterDelete();
}
return $result;
} | php | public function delete()
{
$result = false;
if ($this->beforeDelete()) {
$result = $this->deleteInternal();
$this->afterDelete();
}
return $result;
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"result",
"=",
"false",
";",
"if",
"(",
"$",
"this",
"->",
"beforeDelete",
"(",
")",
")",
"{",
"$",
"result",
"=",
"$",
"this",
"->",
"deleteInternal",
"(",
")",
";",
"$",
"this",
"->",
"afterDele... | Deletes the document corresponding to this active record from the collection.
This method performs the following steps in order:
1. call [[beforeDelete()]]. If the method returns false, it will skip the
rest of the steps;
2. delete the document from the collection;
3. call [[afterDelete()]].
In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
will be raised by the corresponding methods.
@return int|bool the number of documents deleted, or false if the deletion is unsuccessful for some reason.
Note that it is possible the number of documents deleted is 0, even though the deletion execution is successful.
@throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
being deleted is outdated.
@throws \Exception in case delete failed. | [
"Deletes",
"the",
"document",
"corresponding",
"to",
"this",
"active",
"record",
"from",
"the",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveRecord.php#L309-L318 |
yiisoft/yii2-mongodb | src/ActiveRecord.php | ActiveRecord.equals | public function equals($record)
{
if ($this->isNewRecord || $record->isNewRecord) {
return false;
}
return $this->collectionName() === $record->collectionName() && (string) $this->getPrimaryKey() === (string) $record->getPrimaryKey();
} | php | public function equals($record)
{
if ($this->isNewRecord || $record->isNewRecord) {
return false;
}
return $this->collectionName() === $record->collectionName() && (string) $this->getPrimaryKey() === (string) $record->getPrimaryKey();
} | [
"public",
"function",
"equals",
"(",
"$",
"record",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isNewRecord",
"||",
"$",
"record",
"->",
"isNewRecord",
")",
"{",
"return",
"false",
";",
"}",
"return",
"$",
"this",
"->",
"collectionName",
"(",
")",
"===",
... | Returns a value indicating whether the given active record is the same as the current one.
The comparison is made by comparing the collection names and the primary key values of the two active records.
If one of the records [[isNewRecord|is new]] they are also considered not equal.
@param ActiveRecord $record record to compare to
@return bool whether the two active records refer to the same row in the same Mongo collection. | [
"Returns",
"a",
"value",
"indicating",
"whether",
"the",
"given",
"active",
"record",
"is",
"the",
"same",
"as",
"the",
"current",
"one",
".",
"The",
"comparison",
"is",
"made",
"by",
"comparing",
"the",
"collection",
"names",
"and",
"the",
"primary",
"key",... | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveRecord.php#L349-L356 |
yiisoft/yii2-mongodb | src/ActiveRecord.php | ActiveRecord.toArray | public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
$data = parent::toArray($fields, $expand, false);
if (!$recursive) {
return $data;
}
return $this->toArrayInternal($data);
} | php | public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
$data = parent::toArray($fields, $expand, false);
if (!$recursive) {
return $data;
}
return $this->toArrayInternal($data);
} | [
"public",
"function",
"toArray",
"(",
"array",
"$",
"fields",
"=",
"[",
"]",
",",
"array",
"$",
"expand",
"=",
"[",
"]",
",",
"$",
"recursive",
"=",
"true",
")",
"{",
"$",
"data",
"=",
"parent",
"::",
"toArray",
"(",
"$",
"fields",
",",
"$",
"exp... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveRecord.php#L361-L368 |
yiisoft/yii2-mongodb | src/ActiveRecord.php | ActiveRecord.dumpBsonObject | private function dumpBsonObject(Type $object)
{
if ($object instanceof Binary) {
return $object->getData();
}
if (method_exists($object, '__toString')) {
return $object->__toString();
}
return ArrayHelper::toArray($object);
} | php | private function dumpBsonObject(Type $object)
{
if ($object instanceof Binary) {
return $object->getData();
}
if (method_exists($object, '__toString')) {
return $object->__toString();
}
return ArrayHelper::toArray($object);
} | [
"private",
"function",
"dumpBsonObject",
"(",
"Type",
"$",
"object",
")",
"{",
"if",
"(",
"$",
"object",
"instanceof",
"Binary",
")",
"{",
"return",
"$",
"object",
"->",
"getData",
"(",
")",
";",
"}",
"if",
"(",
"method_exists",
"(",
"$",
"object",
","... | Converts MongoDB BSON object to readable value.
@param Type $object MongoDB BSON object.
@return array|string object dump value.
@since 2.1 | [
"Converts",
"MongoDB",
"BSON",
"object",
"to",
"readable",
"value",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveRecord.php#L404-L413 |
yiisoft/yii2-mongodb | src/Session.php | Session.regenerateID | public function regenerateID($deleteOldSession = false)
{
$oldID = session_id();
// if no session is started, there is nothing to regenerate
if (empty($oldID)) {
return;
}
parent::regenerateID(false);
$newID = session_id();
$collection = $this->db->getCollection($this->sessionCollection);
$row = $collection->findOne(['id' => $oldID]);
if ($row !== null) {
if ($deleteOldSession) {
$collection->update(['id' => $oldID], ['id' => $newID]);
} else {
unset($row['_id']);
$row['id'] = $newID;
$collection->insert($row);
}
} else {
// shouldn't reach here normally
$collection->insert($this->composeFields($newID, ''));
}
} | php | public function regenerateID($deleteOldSession = false)
{
$oldID = session_id();
// if no session is started, there is nothing to regenerate
if (empty($oldID)) {
return;
}
parent::regenerateID(false);
$newID = session_id();
$collection = $this->db->getCollection($this->sessionCollection);
$row = $collection->findOne(['id' => $oldID]);
if ($row !== null) {
if ($deleteOldSession) {
$collection->update(['id' => $oldID], ['id' => $newID]);
} else {
unset($row['_id']);
$row['id'] = $newID;
$collection->insert($row);
}
} else {
// shouldn't reach here normally
$collection->insert($this->composeFields($newID, ''));
}
} | [
"public",
"function",
"regenerateID",
"(",
"$",
"deleteOldSession",
"=",
"false",
")",
"{",
"$",
"oldID",
"=",
"session_id",
"(",
")",
";",
"// if no session is started, there is nothing to regenerate",
"if",
"(",
"empty",
"(",
"$",
"oldID",
")",
")",
"{",
"retu... | Updates the current session ID with a newly generated one.
Please refer to <http://php.net/session_regenerate_id> for more details.
@param bool $deleteOldSession Whether to delete the old associated session file or not. | [
"Updates",
"the",
"current",
"session",
"ID",
"with",
"a",
"newly",
"generated",
"one",
".",
"Please",
"refer",
"to",
"<http",
":",
"//",
"php",
".",
"net",
"/",
"session_regenerate_id",
">",
"for",
"more",
"details",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Session.php#L76-L102 |
yiisoft/yii2-mongodb | src/Session.php | Session.readSession | public function readSession($id)
{
$collection = $this->db->getCollection($this->sessionCollection);
$condition = [
'id' => $id,
'expire' => ['$gt' => time()],
];
if (isset($this->readCallback)) {
$doc = $collection->findOne($condition);
return $doc === null ? '' : $this->extractData($doc);
}
$doc = $collection->findOne(
$condition,
['data' => 1, '_id' => 0]
);
return isset($doc['data']) ? $doc['data'] : '';
} | php | public function readSession($id)
{
$collection = $this->db->getCollection($this->sessionCollection);
$condition = [
'id' => $id,
'expire' => ['$gt' => time()],
];
if (isset($this->readCallback)) {
$doc = $collection->findOne($condition);
return $doc === null ? '' : $this->extractData($doc);
}
$doc = $collection->findOne(
$condition,
['data' => 1, '_id' => 0]
);
return isset($doc['data']) ? $doc['data'] : '';
} | [
"public",
"function",
"readSession",
"(",
"$",
"id",
")",
"{",
"$",
"collection",
"=",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"sessionCollection",
")",
";",
"$",
"condition",
"=",
"[",
"'id'",
"=>",
"$",
"id",
",",
"'... | Session read handler.
Do not call this method directly.
@param string $id session ID
@return string the session data | [
"Session",
"read",
"handler",
".",
"Do",
"not",
"call",
"this",
"method",
"directly",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Session.php#L110-L128 |
yiisoft/yii2-mongodb | src/Session.php | Session.writeSession | public function writeSession($id, $data)
{
// exception must be caught in session write handler
// http://us.php.net/manual/en/function.session-set-save-handler.php
try {
$this->db->getCollection($this->sessionCollection)->update(
['id' => $id],
$this->composeFields($id, $data),
['upsert' => true]
);
} catch (\Exception $e) {
Yii::$app->errorHandler->handleException($e);
return false;
}
return true;
} | php | public function writeSession($id, $data)
{
// exception must be caught in session write handler
// http://us.php.net/manual/en/function.session-set-save-handler.php
try {
$this->db->getCollection($this->sessionCollection)->update(
['id' => $id],
$this->composeFields($id, $data),
['upsert' => true]
);
} catch (\Exception $e) {
Yii::$app->errorHandler->handleException($e);
return false;
}
return true;
} | [
"public",
"function",
"writeSession",
"(",
"$",
"id",
",",
"$",
"data",
")",
"{",
"// exception must be caught in session write handler",
"// http://us.php.net/manual/en/function.session-set-save-handler.php",
"try",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",... | Session write handler.
Do not call this method directly.
@param string $id session ID
@param string $data session data
@return bool whether session write is successful | [
"Session",
"write",
"handler",
".",
"Do",
"not",
"call",
"this",
"method",
"directly",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Session.php#L137-L153 |
yiisoft/yii2-mongodb | src/Session.php | Session.destroySession | public function destroySession($id)
{
$this->db->getCollection($this->sessionCollection)->remove(
['id' => $id],
['justOne' => true]
);
return true;
} | php | public function destroySession($id)
{
$this->db->getCollection($this->sessionCollection)->remove(
['id' => $id],
['justOne' => true]
);
return true;
} | [
"public",
"function",
"destroySession",
"(",
"$",
"id",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"sessionCollection",
")",
"->",
"remove",
"(",
"[",
"'id'",
"=>",
"$",
"id",
"]",
",",
"[",
"'justOne'",
"=>",
"... | Session destroy handler.
Do not call this method directly.
@param string $id session ID
@return bool whether session is destroyed successfully | [
"Session",
"destroy",
"handler",
".",
"Do",
"not",
"call",
"this",
"method",
"directly",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Session.php#L161-L169 |
yiisoft/yii2-mongodb | src/Session.php | Session.gcSession | public function gcSession($maxLifetime)
{
$this->db->getCollection($this->sessionCollection)
->remove(['expire' => ['$lt' => time()]]);
return true;
} | php | public function gcSession($maxLifetime)
{
$this->db->getCollection($this->sessionCollection)
->remove(['expire' => ['$lt' => time()]]);
return true;
} | [
"public",
"function",
"gcSession",
"(",
"$",
"maxLifetime",
")",
"{",
"$",
"this",
"->",
"db",
"->",
"getCollection",
"(",
"$",
"this",
"->",
"sessionCollection",
")",
"->",
"remove",
"(",
"[",
"'expire'",
"=>",
"[",
"'$lt'",
"=>",
"time",
"(",
")",
"]... | Session GC (garbage collection) handler.
Do not call this method directly.
@param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
@return bool whether session is GCed successfully | [
"Session",
"GC",
"(",
"garbage",
"collection",
")",
"handler",
".",
"Do",
"not",
"call",
"this",
"method",
"directly",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Session.php#L177-L183 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.getChunkCollection | public function getChunkCollection($refresh = false)
{
if ($refresh || !is_object($this->_chunkCollection)) {
$this->_chunkCollection = Yii::createObject([
'class' => 'yii\mongodb\Collection',
'database' => $this->database,
'name' => $this->getPrefix() . '.chunks'
]);
}
return $this->_chunkCollection;
} | php | public function getChunkCollection($refresh = false)
{
if ($refresh || !is_object($this->_chunkCollection)) {
$this->_chunkCollection = Yii::createObject([
'class' => 'yii\mongodb\Collection',
'database' => $this->database,
'name' => $this->getPrefix() . '.chunks'
]);
}
return $this->_chunkCollection;
} | [
"public",
"function",
"getChunkCollection",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"!",
"is_object",
"(",
"$",
"this",
"->",
"_chunkCollection",
")",
")",
"{",
"$",
"this",
"->",
"_chunkCollection",
"=",
"Yii",
"::"... | Returns the MongoDB collection for the file chunks.
@param bool $refresh whether to reload the collection instance even if it is found in the cache.
@return \yii\mongodb\Collection mongo collection instance. | [
"Returns",
"the",
"MongoDB",
"collection",
"for",
"the",
"file",
"chunks",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L103-L114 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.getFileCollection | public function getFileCollection($refresh = false)
{
if ($refresh || !is_object($this->_fileCollection)) {
$this->_fileCollection = Yii::createObject([
'class' => 'yii\mongodb\Collection',
'database' => $this->database,
'name' => $this->name
]);
}
return $this->_fileCollection;
} | php | public function getFileCollection($refresh = false)
{
if ($refresh || !is_object($this->_fileCollection)) {
$this->_fileCollection = Yii::createObject([
'class' => 'yii\mongodb\Collection',
'database' => $this->database,
'name' => $this->name
]);
}
return $this->_fileCollection;
} | [
"public",
"function",
"getFileCollection",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"!",
"is_object",
"(",
"$",
"this",
"->",
"_fileCollection",
")",
")",
"{",
"$",
"this",
"->",
"_fileCollection",
"=",
"Yii",
"::",
... | Returns the MongoDB collection for the files.
@param bool $refresh whether to reload the collection instance even if it is found in the cache.
@return \yii\mongodb\Collection mongo collection instance.
@since 2.1 | [
"Returns",
"the",
"MongoDB",
"collection",
"for",
"the",
"files",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L122-L133 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.find | public function find($condition = [], $fields = [], $options = [])
{
return new Cursor($this, parent::find($condition, $fields, $options));
} | php | public function find($condition = [], $fields = [], $options = [])
{
return new Cursor($this, parent::find($condition, $fields, $options));
} | [
"public",
"function",
"find",
"(",
"$",
"condition",
"=",
"[",
"]",
",",
"$",
"fields",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"new",
"Cursor",
"(",
"$",
"this",
",",
"parent",
"::",
"find",
"(",
"$",
"condition",
... | {@inheritdoc}
@return Cursor cursor for the search results | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L147-L150 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.remove | public function remove($condition = [], $options = [])
{
$fileCollection = $this->getFileCollection();
$chunkCollection = $this->getChunkCollection();
if (empty($condition) && empty($options['limit'])) {
// truncate :
$deleteCount = $fileCollection->remove([], $options);
$chunkCollection->remove([], $options);
return $deleteCount;
}
$batchSize = 200;
$options['batchSize'] = $batchSize;
$cursor = $fileCollection->find($condition, ['_id'], $options);
unset($options['limit']);
$deleteCount = 0;
$deleteCallback = function ($ids) use ($fileCollection, $chunkCollection, $options) {
$chunkCollection->remove(['files_id' => ['$in' => $ids]], $options);
return $fileCollection->remove(['_id' => ['$in' => $ids]], $options);
};
$ids = [];
$idsCount = 0;
foreach ($cursor as $row) {
$ids[] = $row['_id'];
$idsCount++;
if ($idsCount >= $batchSize) {
$deleteCount += $deleteCallback($ids);
$ids = [];
$idsCount = 0;
}
}
if (!empty($ids)) {
$deleteCount += $deleteCallback($ids);
}
return $deleteCount;
} | php | public function remove($condition = [], $options = [])
{
$fileCollection = $this->getFileCollection();
$chunkCollection = $this->getChunkCollection();
if (empty($condition) && empty($options['limit'])) {
// truncate :
$deleteCount = $fileCollection->remove([], $options);
$chunkCollection->remove([], $options);
return $deleteCount;
}
$batchSize = 200;
$options['batchSize'] = $batchSize;
$cursor = $fileCollection->find($condition, ['_id'], $options);
unset($options['limit']);
$deleteCount = 0;
$deleteCallback = function ($ids) use ($fileCollection, $chunkCollection, $options) {
$chunkCollection->remove(['files_id' => ['$in' => $ids]], $options);
return $fileCollection->remove(['_id' => ['$in' => $ids]], $options);
};
$ids = [];
$idsCount = 0;
foreach ($cursor as $row) {
$ids[] = $row['_id'];
$idsCount++;
if ($idsCount >= $batchSize) {
$deleteCount += $deleteCallback($ids);
$ids = [];
$idsCount = 0;
}
}
if (!empty($ids)) {
$deleteCount += $deleteCallback($ids);
}
return $deleteCount;
} | [
"public",
"function",
"remove",
"(",
"$",
"condition",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"fileCollection",
"=",
"$",
"this",
"->",
"getFileCollection",
"(",
")",
";",
"$",
"chunkCollection",
"=",
"$",
"this",
"->",
"ge... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L155-L194 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.insertFile | public function insertFile($filename, $metadata = [], $options = [])
{
$options['document'] = $metadata;
$document = $this->createUpload($options)->addFile($filename)->complete();
return $document['_id'];
} | php | public function insertFile($filename, $metadata = [], $options = [])
{
$options['document'] = $metadata;
$document = $this->createUpload($options)->addFile($filename)->complete();
return $document['_id'];
} | [
"public",
"function",
"insertFile",
"(",
"$",
"filename",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"[",
"'document'",
"]",
"=",
"$",
"metadata",
";",
"$",
"document",
"=",
"$",
"this",
"->",... | Creates new file in GridFS collection from given local filesystem file.
Additional attributes can be added file document using $metadata.
@param string $filename name of the file to store.
@param array $metadata other metadata fields to include in the file document.
@param array $options list of options in format: optionName => optionValue
@return mixed the "_id" of the saved file document. This will be a generated [[\MongoId]]
unless an "_id" was explicitly specified in the metadata.
@throws Exception on failure. | [
"Creates",
"new",
"file",
"in",
"GridFS",
"collection",
"from",
"given",
"local",
"filesystem",
"file",
".",
"Additional",
"attributes",
"can",
"be",
"added",
"file",
"document",
"using",
"$metadata",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L206-L211 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.insertFileContent | public function insertFileContent($bytes, $metadata = [], $options = [])
{
$options['document'] = $metadata;
$document = $this->createUpload($options)->addContent($bytes)->complete();
return $document['_id'];
} | php | public function insertFileContent($bytes, $metadata = [], $options = [])
{
$options['document'] = $metadata;
$document = $this->createUpload($options)->addContent($bytes)->complete();
return $document['_id'];
} | [
"public",
"function",
"insertFileContent",
"(",
"$",
"bytes",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"[",
"'document'",
"]",
"=",
"$",
"metadata",
";",
"$",
"document",
"=",
"$",
"this",
"... | Creates new file in GridFS collection with specified content.
Additional attributes can be added file document using $metadata.
@param string $bytes string of bytes to store.
@param array $metadata other metadata fields to include in the file document.
@param array $options list of options in format: optionName => optionValue
@return mixed the "_id" of the saved file document. This will be a generated [[\MongoId]]
unless an "_id" was explicitly specified in the metadata.
@throws Exception on failure. | [
"Creates",
"new",
"file",
"in",
"GridFS",
"collection",
"with",
"specified",
"content",
".",
"Additional",
"attributes",
"can",
"be",
"added",
"file",
"document",
"using",
"$metadata",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L223-L228 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.insertUploads | public function insertUploads($name, $metadata = [], $options = [])
{
$uploadedFile = UploadedFile::getInstanceByName($name);
if ($uploadedFile === null) {
throw new Exception("Uploaded file '{$name}' does not exist.");
}
$options['filename'] = $uploadedFile->name;
$options['document'] = $metadata;
$document = $this->createUpload($options)->addFile($uploadedFile->tempName)->complete();
return $document['_id'];
} | php | public function insertUploads($name, $metadata = [], $options = [])
{
$uploadedFile = UploadedFile::getInstanceByName($name);
if ($uploadedFile === null) {
throw new Exception("Uploaded file '{$name}' does not exist.");
}
$options['filename'] = $uploadedFile->name;
$options['document'] = $metadata;
$document = $this->createUpload($options)->addFile($uploadedFile->tempName)->complete();
return $document['_id'];
} | [
"public",
"function",
"insertUploads",
"(",
"$",
"name",
",",
"$",
"metadata",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"uploadedFile",
"=",
"UploadedFile",
"::",
"getInstanceByName",
"(",
"$",
"name",
")",
";",
"if",
"(",
"$... | Creates new file in GridFS collection from uploaded file.
Additional attributes can be added file document using $metadata.
@param string $name name of the uploaded file to store. This should correspond to
the file field's name attribute in the HTML form.
@param array $metadata other metadata fields to include in the file document.
@param array $options list of options in format: optionName => optionValue
@return mixed the "_id" of the saved file document. This will be a generated [[\MongoId]]
unless an "_id" was explicitly specified in the metadata.
@throws Exception on failure. | [
"Creates",
"new",
"file",
"in",
"GridFS",
"collection",
"from",
"uploaded",
"file",
".",
"Additional",
"attributes",
"can",
"be",
"added",
"file",
"document",
"using",
"$metadata",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L241-L252 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.get | public function get($id)
{
$document = $this->getFileCollection()->findOne(['_id' => $id]);
return empty($document) ? null : $this->createDownload($document);
} | php | public function get($id)
{
$document = $this->getFileCollection()->findOne(['_id' => $id]);
return empty($document) ? null : $this->createDownload($document);
} | [
"public",
"function",
"get",
"(",
"$",
"id",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"getFileCollection",
"(",
")",
"->",
"findOne",
"(",
"[",
"'_id'",
"=>",
"$",
"id",
"]",
")",
";",
"return",
"empty",
"(",
"$",
"document",
")",
"?",
... | Retrieves the file with given _id.
@param mixed $id _id of the file to find.
@return Download|null found file, or null if file does not exist
@throws Exception on failure. | [
"Retrieves",
"the",
"file",
"with",
"given",
"_id",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L260-L264 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.ensureIndexes | public function ensureIndexes($force = false)
{
if (!$force && $this->indexesEnsured) {
return $this;
}
$this->ensureFileIndexes();
$this->ensureChunkIndexes();
$this->indexesEnsured = true;
return $this;
} | php | public function ensureIndexes($force = false)
{
if (!$force && $this->indexesEnsured) {
return $this;
}
$this->ensureFileIndexes();
$this->ensureChunkIndexes();
$this->indexesEnsured = true;
return $this;
} | [
"public",
"function",
"ensureIndexes",
"(",
"$",
"force",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"force",
"&&",
"$",
"this",
"->",
"indexesEnsured",
")",
"{",
"return",
"$",
"this",
";",
"}",
"$",
"this",
"->",
"ensureFileIndexes",
"(",
")",
";... | Makes sure that indexes, which are crucial for the file processing,
exist at this collection and [[chunkCollection]].
The check result is cached per collection instance.
@param bool $force whether to ignore internal collection instance cache.
@return $this self reference. | [
"Makes",
"sure",
"that",
"indexes",
"which",
"are",
"crucial",
"for",
"the",
"file",
"processing",
"exist",
"at",
"this",
"collection",
"and",
"[[",
"chunkCollection",
"]]",
".",
"The",
"check",
"result",
"is",
"cached",
"per",
"collection",
"instance",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L285-L296 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.ensureFileIndexes | private function ensureFileIndexes()
{
$indexKey = ['filename' => 1, 'uploadDate' => 1];
foreach ($this->listIndexes() as $index) {
if ($index['key'] === $indexKey) {
return;
}
}
$this->createIndex($indexKey);
} | php | private function ensureFileIndexes()
{
$indexKey = ['filename' => 1, 'uploadDate' => 1];
foreach ($this->listIndexes() as $index) {
if ($index['key'] === $indexKey) {
return;
}
}
$this->createIndex($indexKey);
} | [
"private",
"function",
"ensureFileIndexes",
"(",
")",
"{",
"$",
"indexKey",
"=",
"[",
"'filename'",
"=>",
"1",
",",
"'uploadDate'",
"=>",
"1",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"listIndexes",
"(",
")",
"as",
"$",
"index",
")",
"{",
"if",
"... | Ensures indexes at file collection. | [
"Ensures",
"indexes",
"at",
"file",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L301-L311 |
yiisoft/yii2-mongodb | src/file/Collection.php | Collection.ensureChunkIndexes | private function ensureChunkIndexes()
{
$chunkCollection = $this->getChunkCollection();
$indexKey = ['files_id' => 1, 'n' => 1];
foreach ($chunkCollection->listIndexes() as $index) {
if (!empty($index['unique']) && $index['key'] === $indexKey) {
return;
}
}
$chunkCollection->createIndex($indexKey, ['unique' => true]);
} | php | private function ensureChunkIndexes()
{
$chunkCollection = $this->getChunkCollection();
$indexKey = ['files_id' => 1, 'n' => 1];
foreach ($chunkCollection->listIndexes() as $index) {
if (!empty($index['unique']) && $index['key'] === $indexKey) {
return;
}
}
$chunkCollection->createIndex($indexKey, ['unique' => true]);
} | [
"private",
"function",
"ensureChunkIndexes",
"(",
")",
"{",
"$",
"chunkCollection",
"=",
"$",
"this",
"->",
"getChunkCollection",
"(",
")",
";",
"$",
"indexKey",
"=",
"[",
"'files_id'",
"=>",
"1",
",",
"'n'",
"=>",
"1",
"]",
";",
"foreach",
"(",
"$",
"... | Ensures indexes at chunk collection. | [
"Ensures",
"indexes",
"at",
"chunk",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Collection.php#L316-L326 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.getChunkCursor | public function getChunkCursor($refresh = false)
{
if ($refresh || $this->_chunkCursor === null) {
$file = $this->getDocument();
$this->_chunkCursor = $this->collection->getChunkCollection()->find(
['files_id' => $file['_id']],
[],
['sort' => ['n' => 1]]
);
}
return $this->_chunkCursor;
} | php | public function getChunkCursor($refresh = false)
{
if ($refresh || $this->_chunkCursor === null) {
$file = $this->getDocument();
$this->_chunkCursor = $this->collection->getChunkCollection()->find(
['files_id' => $file['_id']],
[],
['sort' => ['n' => 1]]
);
}
return $this->_chunkCursor;
} | [
"public",
"function",
"getChunkCursor",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"$",
"this",
"->",
"_chunkCursor",
"===",
"null",
")",
"{",
"$",
"file",
"=",
"$",
"this",
"->",
"getDocument",
"(",
")",
";",
"$",
... | Returns file chunks read cursor.
@param bool $refresh whether to recreate cursor, if it is already exist.
@return \MongoDB\Driver\Cursor chuck list cursor.
@throws InvalidConfigException | [
"Returns",
"file",
"chunks",
"read",
"cursor",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L128-L139 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.getChunkIterator | public function getChunkIterator($refresh = false)
{
if ($refresh || $this->_chunkIterator === null) {
$this->_chunkIterator = new \IteratorIterator($this->getChunkCursor($refresh));
$this->_chunkIterator->rewind();
}
return $this->_chunkIterator;
} | php | public function getChunkIterator($refresh = false)
{
if ($refresh || $this->_chunkIterator === null) {
$this->_chunkIterator = new \IteratorIterator($this->getChunkCursor($refresh));
$this->_chunkIterator->rewind();
}
return $this->_chunkIterator;
} | [
"public",
"function",
"getChunkIterator",
"(",
"$",
"refresh",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"refresh",
"||",
"$",
"this",
"->",
"_chunkIterator",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"_chunkIterator",
"=",
"new",
"\\",
"IteratorIterator",... | Returns iterator for the file chunks cursor.
@param bool $refresh whether to recreate iterator, if it is already exist.
@return \Iterator chuck cursor iterator. | [
"Returns",
"iterator",
"for",
"the",
"file",
"chunks",
"cursor",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L146-L153 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.toStream | public function toStream($stream)
{
$bytesWritten = 0;
foreach ($this->getChunkCursor() as $chunk) {
$bytesWritten += fwrite($stream, $chunk['data']->getData());
}
return $bytesWritten;
} | php | public function toStream($stream)
{
$bytesWritten = 0;
foreach ($this->getChunkCursor() as $chunk) {
$bytesWritten += fwrite($stream, $chunk['data']->getData());
}
return $bytesWritten;
} | [
"public",
"function",
"toStream",
"(",
"$",
"stream",
")",
"{",
"$",
"bytesWritten",
"=",
"0",
";",
"foreach",
"(",
"$",
"this",
"->",
"getChunkCursor",
"(",
")",
"as",
"$",
"chunk",
")",
"{",
"$",
"bytesWritten",
"+=",
"fwrite",
"(",
"$",
"stream",
... | Saves file into the given stream.
@param resource $stream stream, which file should be saved to.
@return int number of written bytes. | [
"Saves",
"file",
"into",
"the",
"given",
"stream",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L160-L167 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.toFile | public function toFile($filename)
{
$filename = Yii::getAlias($filename);
FileHelper::createDirectory(dirname($filename));
return $this->toStream(fopen($filename, 'w+'));
} | php | public function toFile($filename)
{
$filename = Yii::getAlias($filename);
FileHelper::createDirectory(dirname($filename));
return $this->toStream(fopen($filename, 'w+'));
} | [
"public",
"function",
"toFile",
"(",
"$",
"filename",
")",
"{",
"$",
"filename",
"=",
"Yii",
"::",
"getAlias",
"(",
"$",
"filename",
")",
";",
"FileHelper",
"::",
"createDirectory",
"(",
"dirname",
"(",
"$",
"filename",
")",
")",
";",
"return",
"$",
"t... | Saves download to the physical file.
@param string $filename name of the physical file.
@return int number of written bytes. | [
"Saves",
"download",
"to",
"the",
"physical",
"file",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L174-L179 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.toString | public function toString()
{
$result = '';
foreach ($this->getChunkCursor() as $chunk) {
$result .= $chunk['data']->getData();
}
return $result;
} | php | public function toString()
{
$result = '';
foreach ($this->getChunkCursor() as $chunk) {
$result .= $chunk['data']->getData();
}
return $result;
} | [
"public",
"function",
"toString",
"(",
")",
"{",
"$",
"result",
"=",
"''",
";",
"foreach",
"(",
"$",
"this",
"->",
"getChunkCursor",
"(",
")",
"as",
"$",
"chunk",
")",
"{",
"$",
"result",
".=",
"$",
"chunk",
"[",
"'data'",
"]",
"->",
"getData",
"("... | Returns a string of the bytes in the associated file.
@return string file content. | [
"Returns",
"a",
"string",
"of",
"the",
"bytes",
"in",
"the",
"associated",
"file",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L185-L192 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.toResource | public function toResource()
{
$protocol = $this->collection->database->connection->registerFileStreamWrapper();
$context = stream_context_create([
$protocol => [
'download' => $this,
]
]);
$document = $this->getDocument();
$url = "{$protocol}://{$this->collection->database->name}.{$this->collection->prefix}?_id={$document['_id']}";
return fopen($url, 'r', false, $context);
} | php | public function toResource()
{
$protocol = $this->collection->database->connection->registerFileStreamWrapper();
$context = stream_context_create([
$protocol => [
'download' => $this,
]
]);
$document = $this->getDocument();
$url = "{$protocol}://{$this->collection->database->name}.{$this->collection->prefix}?_id={$document['_id']}";
return fopen($url, 'r', false, $context);
} | [
"public",
"function",
"toResource",
"(",
")",
"{",
"$",
"protocol",
"=",
"$",
"this",
"->",
"collection",
"->",
"database",
"->",
"connection",
"->",
"registerFileStreamWrapper",
"(",
")",
";",
"$",
"context",
"=",
"stream_context_create",
"(",
"[",
"$",
"pr... | Returns an opened stream resource, which can be used to read file.
Note: each invocation of this method will create new file resource.
@return resource stream resource. | [
"Returns",
"an",
"opened",
"stream",
"resource",
"which",
"can",
"be",
"used",
"to",
"read",
"file",
".",
"Note",
":",
"each",
"invocation",
"of",
"this",
"method",
"will",
"create",
"new",
"file",
"resource",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L199-L212 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.substr | public function substr($start, $length)
{
$document = $this->getDocument();
if ($start < 0) {
$start = max($document['length'] + $start, 0);
}
if ($start > $document['length']) {
return false;
}
if ($length < 0) {
$length = $document['length'] - $start + $length;
if ($length < 0) {
return false;
}
}
$chunkSize = $document['chunkSize'];
$startChunkNumber = floor($start / $chunkSize);
$chunkIterator = $this->getChunkIterator();
if (!$chunkIterator->valid()) {
// invalid iterator state - recreate iterator
// unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
$chunkIterator = $this->getChunkIterator(true);
}
if ($chunkIterator->key() > $startChunkNumber) {
// unable to go back by iterator
// unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
$chunkIterator = $this->getChunkIterator(true);
}
$result = '';
$chunkDataOffset = $start - $startChunkNumber * $chunkSize;
while ($chunkIterator->valid()) {
if ($chunkIterator->key() >= $startChunkNumber) {
$chunk = $chunkIterator->current();
$data = $chunk['data']->getData();
$readLength = min($chunkSize - $chunkDataOffset, $length);
$result .= StringHelper::byteSubstr($data, $chunkDataOffset, $readLength);
$length -= $readLength;
if ($length <= 0) {
break;
}
$chunkDataOffset = 0;
}
$chunkIterator->next();
}
return $result;
} | php | public function substr($start, $length)
{
$document = $this->getDocument();
if ($start < 0) {
$start = max($document['length'] + $start, 0);
}
if ($start > $document['length']) {
return false;
}
if ($length < 0) {
$length = $document['length'] - $start + $length;
if ($length < 0) {
return false;
}
}
$chunkSize = $document['chunkSize'];
$startChunkNumber = floor($start / $chunkSize);
$chunkIterator = $this->getChunkIterator();
if (!$chunkIterator->valid()) {
// invalid iterator state - recreate iterator
// unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
$chunkIterator = $this->getChunkIterator(true);
}
if ($chunkIterator->key() > $startChunkNumber) {
// unable to go back by iterator
// unable to use `rewind` due to error "Cursors cannot rewind after starting iteration"
$chunkIterator = $this->getChunkIterator(true);
}
$result = '';
$chunkDataOffset = $start - $startChunkNumber * $chunkSize;
while ($chunkIterator->valid()) {
if ($chunkIterator->key() >= $startChunkNumber) {
$chunk = $chunkIterator->current();
$data = $chunk['data']->getData();
$readLength = min($chunkSize - $chunkDataOffset, $length);
$result .= StringHelper::byteSubstr($data, $chunkDataOffset, $readLength);
$length -= $readLength;
if ($length <= 0) {
break;
}
$chunkDataOffset = 0;
}
$chunkIterator->next();
}
return $result;
} | [
"public",
"function",
"substr",
"(",
"$",
"start",
",",
"$",
"length",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"getDocument",
"(",
")",
";",
"if",
"(",
"$",
"start",
"<",
"0",
")",
"{",
"$",
"start",
"=",
"max",
"(",
"$",
"document",
... | Return part of a file.
@param int $start reading start position.
If non-negative, the returned string will start at the start'th position in file, counting from zero.
If negative, the returned string will start at the start'th character from the end of file.
@param int $length number of bytes to read.
If given and is positive, the string returned will contain at most length characters beginning from start (depending on the length of file).
If given and is negative, then that many characters will be omitted from the end of file (after the start position has been calculated when a start is negative).
@return string|false the extracted part of file or `false` on failure | [
"Return",
"part",
"of",
"a",
"file",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L224-L285 |
yiisoft/yii2-mongodb | src/file/Download.php | Download.getResource | public function getResource()
{
if ($this->_resource === null) {
$this->_resource = $this->toResource();
}
return $this->_resource;
} | php | public function getResource()
{
if ($this->_resource === null) {
$this->_resource = $this->toResource();
}
return $this->_resource;
} | [
"public",
"function",
"getResource",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_resource",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"_resource",
"=",
"$",
"this",
"->",
"toResource",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"_resource"... | Returns persistent stream resource, which can be used to read file.
@return resource file stream resource. | [
"Returns",
"persistent",
"stream",
"resource",
"which",
"can",
"be",
"used",
"to",
"read",
"file",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Download.php#L312-L318 |
yiisoft/yii2-mongodb | src/file/ActiveQuery.php | ActiveQuery.getCollection | public function getCollection($db = null)
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
if ($this->from === null) {
$this->from = $modelClass::collectionName();
}
return $db->getFileCollection($this->from);
} | php | public function getCollection($db = null)
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
if ($this->from === null) {
$this->from = $modelClass::collectionName();
}
return $db->getFileCollection($this->from);
} | [
"public",
"function",
"getCollection",
"(",
"$",
"db",
"=",
"null",
")",
"{",
"/* @var $modelClass ActiveRecord */",
"$",
"modelClass",
"=",
"$",
"this",
"->",
"modelClass",
";",
"if",
"(",
"$",
"db",
"===",
"null",
")",
"{",
"$",
"db",
"=",
"$",
"modelC... | Returns the Mongo collection for this query.
@param \yii\mongodb\Connection $db Mongo connection.
@return Collection collection instance. | [
"Returns",
"the",
"Mongo",
"collection",
"for",
"this",
"query",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveQuery.php#L138-L150 |
yiisoft/yii2-mongodb | src/file/ActiveQuery.php | ActiveQuery.populate | public function populate($rows)
{
if (empty($rows)) {
return [];
}
$indexBy = $this->indexBy;
$this->indexBy = null;
$rows = parent::populate($rows);
$this->indexBy = $indexBy;
$models = $this->createModels($rows);
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
if (!$this->asArray) {
foreach ($models as $model) {
$model->afterFind();
}
}
return parent::populate($models);
} | php | public function populate($rows)
{
if (empty($rows)) {
return [];
}
$indexBy = $this->indexBy;
$this->indexBy = null;
$rows = parent::populate($rows);
$this->indexBy = $indexBy;
$models = $this->createModels($rows);
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
if (!$this->asArray) {
foreach ($models as $model) {
$model->afterFind();
}
}
return parent::populate($models);
} | [
"public",
"function",
"populate",
"(",
"$",
"rows",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"rows",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"indexBy",
"=",
"$",
"this",
"->",
"indexBy",
";",
"$",
"this",
"->",
"indexBy",
"=",
"null",
... | Converts the raw query results into the format as specified by this query.
This method is internally used to convert the data fetched from MongoDB
into the format as required by this query.
@param array $rows the raw query result from MongoDB
@return array the converted query result | [
"Converts",
"the",
"raw",
"query",
"results",
"into",
"the",
"format",
"as",
"specified",
"by",
"this",
"query",
".",
"This",
"method",
"is",
"internally",
"used",
"to",
"convert",
"the",
"data",
"fetched",
"from",
"MongoDB",
"into",
"the",
"format",
"as",
... | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/ActiveQuery.php#L159-L182 |
yiisoft/yii2-mongodb | src/file/Cursor.php | Cursor.current | public function current()
{
$value = parent::current();
if (!isset($value['file'])) {
$value['file'] = $this->collection->createDownload(array_intersect_key($value, ['_id' => true, 'filename' => true, 'length' => true, 'chunkSize' => true]));
}
return $value;
} | php | public function current()
{
$value = parent::current();
if (!isset($value['file'])) {
$value['file'] = $this->collection->createDownload(array_intersect_key($value, ['_id' => true, 'filename' => true, 'length' => true, 'chunkSize' => true]));
}
return $value;
} | [
"public",
"function",
"current",
"(",
")",
"{",
"$",
"value",
"=",
"parent",
"::",
"current",
"(",
")",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"value",
"[",
"'file'",
"]",
")",
")",
"{",
"$",
"value",
"[",
"'file'",
"]",
"=",
"$",
"this",
"->"... | Return the current element
This method is required by the interface [[\Iterator]].
@return mixed current row | [
"Return",
"the",
"current",
"element",
"This",
"method",
"is",
"required",
"by",
"the",
"interface",
"[[",
"\\",
"Iterator",
"]]",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Cursor.php#L43-L50 |
yiisoft/yii2-mongodb | src/file/Cursor.php | Cursor.toArray | public function toArray()
{
$result = [];
foreach ($this as $key => $value) {
$result[$key] = $value;
}
return $result;
} | php | public function toArray()
{
$result = [];
foreach ($this as $key => $value) {
$result[$key] = $value;
}
return $result;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"result",
"[",
"$",
"key",
"]",
"=",
"$",
"value",
";",
"}",
"return",
"$",
"... | Returns an array containing all results for this cursor
@return array containing all results for this cursor. | [
"Returns",
"an",
"array",
"containing",
"all",
"results",
"for",
"this",
"cursor"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Cursor.php#L68-L75 |
yiisoft/yii2-mongodb | src/ActiveQuery.php | ActiveQuery.prepare | public function prepare()
{
if ($this->primaryModel !== null) {
// lazy loading
if ($this->via instanceof self) {
// via pivot collection
$viaModels = $this->via->findJunctionRows([$this->primaryModel]);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveQuery */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->multiple) {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
$viaModels = $model === null ? [] : [$model];
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
}
return parent::prepare();
} | php | public function prepare()
{
if ($this->primaryModel !== null) {
// lazy loading
if ($this->via instanceof self) {
// via pivot collection
$viaModels = $this->via->findJunctionRows([$this->primaryModel]);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveQuery */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->multiple) {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
$viaModels = $model === null ? [] : [$model];
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
}
return parent::prepare();
} | [
"public",
"function",
"prepare",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"primaryModel",
"!==",
"null",
")",
"{",
"// lazy loading",
"if",
"(",
"$",
"this",
"->",
"via",
"instanceof",
"self",
")",
"{",
"// via pivot collection",
"$",
"viaModels",
"=",... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveQuery.php#L99-L126 |
yiisoft/yii2-mongodb | src/ActiveQuery.php | ActiveQuery.modify | public function modify($update, $options = [], $db = null)
{
$row = parent::modify($update, $options, $db);
if ($row !== null) {
$models = $this->populate([$row]);
return reset($models) ?: null;
}
return null;
} | php | public function modify($update, $options = [], $db = null)
{
$row = parent::modify($update, $options, $db);
if ($row !== null) {
$models = $this->populate([$row]);
return reset($models) ?: null;
}
return null;
} | [
"public",
"function",
"modify",
"(",
"$",
"update",
",",
"$",
"options",
"=",
"[",
"]",
",",
"$",
"db",
"=",
"null",
")",
"{",
"$",
"row",
"=",
"parent",
"::",
"modify",
"(",
"$",
"update",
",",
"$",
"options",
",",
"$",
"db",
")",
";",
"if",
... | Performs 'findAndModify' query and returns a single row of result.
Warning: in case 'new' option is set to 'false' (which is by default) usage of this method may lead
to unexpected behavior at some Active Record features, because object will be populated by outdated data.
@param array $update update criteria
@param array $options list of options in format: optionName => optionValue.
@param Connection $db the Mongo connection used to execute the query.
@return ActiveRecord|array|null the original document, or the modified document when $options['new'] is set.
Depending on the setting of [[asArray]], the query result may be either an array or an ActiveRecord object.
Null will be returned if the query results in nothing. | [
"Performs",
"findAndModify",
"query",
"and",
"returns",
"a",
"single",
"row",
"of",
"result",
".",
"Warning",
":",
"in",
"case",
"new",
"option",
"is",
"set",
"to",
"false",
"(",
"which",
"is",
"by",
"default",
")",
"usage",
"of",
"this",
"method",
"may"... | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/ActiveQuery.php#L168-L176 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.createCollection | public function createCollection($collection, $options = [])
{
if (is_array($collection)) {
list($database, $collectionName) = $collection;
} else {
$database = null;
$collectionName = $collection;
}
$this->beginProfile($token = " > create collection " . $this->composeCollectionLogName($collection) . " ...");
$this->db->getDatabase($database)->createCollection($collectionName, $options);
$this->endProfile($token);
} | php | public function createCollection($collection, $options = [])
{
if (is_array($collection)) {
list($database, $collectionName) = $collection;
} else {
$database = null;
$collectionName = $collection;
}
$this->beginProfile($token = " > create collection " . $this->composeCollectionLogName($collection) . " ...");
$this->db->getDatabase($database)->createCollection($collectionName, $options);
$this->endProfile($token);
} | [
"public",
"function",
"createCollection",
"(",
"$",
"collection",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"collection",
")",
")",
"{",
"list",
"(",
"$",
"database",
",",
"$",
"collectionName",
")",
"=",
"$",
"co... | Creates new collection with the specified options.
@param string|array $collection name of the collection
@param array $options collection options in format: "name" => "value" | [
"Creates",
"new",
"collection",
"with",
"the",
"specified",
"options",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L66-L77 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.dropCollection | public function dropCollection($collection)
{
$this->beginProfile($token = " > drop collection " . $this->composeCollectionLogName($collection) . " ...");
$this->db->getCollection($collection)->drop();
$this->endProfile($token);
} | php | public function dropCollection($collection)
{
$this->beginProfile($token = " > drop collection " . $this->composeCollectionLogName($collection) . " ...");
$this->db->getCollection($collection)->drop();
$this->endProfile($token);
} | [
"public",
"function",
"dropCollection",
"(",
"$",
"collection",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > drop collection \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
"$",
"collection",
")",
".",
"\" ...\"",
... | Drops existing collection.
@param string|array $collection name of the collection | [
"Drops",
"existing",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L83-L88 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.createIndexes | public function createIndexes($collection, $indexes)
{
$this->beginProfile($token = " > create indexes on " . $this->composeCollectionLogName($collection) . " (" . Json::encode($indexes) . ") ...");
$this->db->getCollection($collection)->createIndexes($indexes);
$this->endProfile($token);
} | php | public function createIndexes($collection, $indexes)
{
$this->beginProfile($token = " > create indexes on " . $this->composeCollectionLogName($collection) . " (" . Json::encode($indexes) . ") ...");
$this->db->getCollection($collection)->createIndexes($indexes);
$this->endProfile($token);
} | [
"public",
"function",
"createIndexes",
"(",
"$",
"collection",
",",
"$",
"indexes",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > create indexes on \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
"$",
"collection",
... | Creates indexes in the collection.
@param string|array $collection name of the collection
@param array $indexes indexes specifications.
@since 2.1 | [
"Creates",
"indexes",
"in",
"the",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L96-L101 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.dropIndexes | public function dropIndexes($collection, $indexes)
{
$this->beginProfile($token = " > drop indexes '{$indexes}' on " . $this->composeCollectionLogName($collection) . ") ...");
$this->db->getCollection($collection)->dropIndexes($indexes);
$this->endProfile($token);
} | php | public function dropIndexes($collection, $indexes)
{
$this->beginProfile($token = " > drop indexes '{$indexes}' on " . $this->composeCollectionLogName($collection) . ") ...");
$this->db->getCollection($collection)->dropIndexes($indexes);
$this->endProfile($token);
} | [
"public",
"function",
"dropIndexes",
"(",
"$",
"collection",
",",
"$",
"indexes",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > drop indexes '{$indexes}' on \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
"$",
"colle... | Drops collection indexes by name.
@param string|array $collection name of the collection
@param string $indexes wildcard for name of the indexes to be dropped.
@since 2.1 | [
"Drops",
"collection",
"indexes",
"by",
"name",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L109-L114 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.createIndex | public function createIndex($collection, $columns, $options = [])
{
$this->beginProfile($token = " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...");
$this->db->getCollection($collection)->createIndex($columns, $options);
$this->endProfile($token);
} | php | public function createIndex($collection, $columns, $options = [])
{
$this->beginProfile($token = " > create index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . empty($options) ? "" : ", " . Json::encode($options) . ") ...");
$this->db->getCollection($collection)->createIndex($columns, $options);
$this->endProfile($token);
} | [
"public",
"function",
"createIndex",
"(",
"$",
"collection",
",",
"$",
"columns",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > create index on \"",
".",
"$",
"this",
"->",
"composeCollect... | Creates an index on the collection and the specified fields.
@param string|array $collection name of the collection
@param array|string $columns column name or list of column names.
@param array $options list of options in format: optionName => optionValue. | [
"Creates",
"an",
"index",
"on",
"the",
"collection",
"and",
"the",
"specified",
"fields",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L122-L127 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.dropIndex | public function dropIndex($collection, $columns)
{
$this->beginProfile($token = " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . ") ...");
$this->db->getCollection($collection)->dropIndex($columns);
$this->endProfile($token);
} | php | public function dropIndex($collection, $columns)
{
$this->beginProfile($token = " > drop index on " . $this->composeCollectionLogName($collection) . " (" . Json::encode((array) $columns) . ") ...");
$this->db->getCollection($collection)->dropIndex($columns);
$this->endProfile($token);
} | [
"public",
"function",
"dropIndex",
"(",
"$",
"collection",
",",
"$",
"columns",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > drop index on \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
"$",
"collection",
")",
... | Drop indexes for specified column(s).
@param string|array $collection name of the collection
@param string|array $columns column name or list of column names. | [
"Drop",
"indexes",
"for",
"specified",
"column",
"(",
"s",
")",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L134-L139 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.dropAllIndexes | public function dropAllIndexes($collection)
{
$this->beginProfile($token = " > drop all indexes on " . $this->composeCollectionLogName($collection) . ") ...");
$this->db->getCollection($collection)->dropAllIndexes();
$this->endProfile($token);
} | php | public function dropAllIndexes($collection)
{
$this->beginProfile($token = " > drop all indexes on " . $this->composeCollectionLogName($collection) . ") ...");
$this->db->getCollection($collection)->dropAllIndexes();
$this->endProfile($token);
} | [
"public",
"function",
"dropAllIndexes",
"(",
"$",
"collection",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > drop all indexes on \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
"$",
"collection",
")",
".",
"\") ...\... | Drops all indexes for specified collection.
@param string|array $collection name of the collection. | [
"Drops",
"all",
"indexes",
"for",
"specified",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L145-L150 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.batchInsert | public function batchInsert($collection, $rows, $options = [])
{
$this->beginProfile($token = " > insert into " . $this->composeCollectionLogName($collection) . ") ...");
$rows = $this->db->getCollection($collection)->batchInsert($rows, $options);
$this->endProfile($token);
return $rows;
} | php | public function batchInsert($collection, $rows, $options = [])
{
$this->beginProfile($token = " > insert into " . $this->composeCollectionLogName($collection) . ") ...");
$rows = $this->db->getCollection($collection)->batchInsert($rows, $options);
$this->endProfile($token);
return $rows;
} | [
"public",
"function",
"batchInsert",
"(",
"$",
"collection",
",",
"$",
"rows",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > insert into \"",
".",
"$",
"this",
"->",
"composeCollectionLogN... | Inserts several new rows into collection.
@param array|string $collection collection name.
@param array $rows array of arrays or objects to be inserted.
@param array $options list of options in format: optionName => optionValue.
@return array inserted data, each row will have "_id" key assigned to it. | [
"Inserts",
"several",
"new",
"rows",
"into",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L174-L180 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.update | public function update($collection, $condition, $newData, $options = [])
{
$this->beginProfile($token = " > update " . $this->composeCollectionLogName($collection) . ") ...");
$result = $this->db->getCollection($collection)->update($condition, $newData, $options);
$this->endProfile($token);
return $result;
} | php | public function update($collection, $condition, $newData, $options = [])
{
$this->beginProfile($token = " > update " . $this->composeCollectionLogName($collection) . ") ...");
$result = $this->db->getCollection($collection)->update($condition, $newData, $options);
$this->endProfile($token);
return $result;
} | [
"public",
"function",
"update",
"(",
"$",
"collection",
",",
"$",
"condition",
",",
"$",
"newData",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > update \"",
".",
"$",
"this",
"->",
... | Updates the rows, which matches given criteria by given data.
Note: for "multiple" mode Mongo requires explicit strategy "$set" or "$inc"
to be specified for the "newData". If no strategy is passed "$set" will be used.
@param array|string $collection collection name.
@param array $condition description of the objects to update.
@param array $newData the object with which to update the matching records.
@param array $options list of options in format: optionName => optionValue.
@return int|bool number of updated documents or whether operation was successful. | [
"Updates",
"the",
"rows",
"which",
"matches",
"given",
"criteria",
"by",
"given",
"data",
".",
"Note",
":",
"for",
"multiple",
"mode",
"Mongo",
"requires",
"explicit",
"strategy",
"$set",
"or",
"$inc",
"to",
"be",
"specified",
"for",
"the",
"newData",
".",
... | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L192-L198 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.save | public function save($collection, $data, $options = [])
{
$this->beginProfile($token = " > save " . $this->composeCollectionLogName($collection) . ") ...");
$id = $this->db->getCollection($collection)->save($data, $options);
$this->endProfile($token);
return $id;
} | php | public function save($collection, $data, $options = [])
{
$this->beginProfile($token = " > save " . $this->composeCollectionLogName($collection) . ") ...");
$id = $this->db->getCollection($collection)->save($data, $options);
$this->endProfile($token);
return $id;
} | [
"public",
"function",
"save",
"(",
"$",
"collection",
",",
"$",
"data",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > save \"",
".",
"$",
"this",
"->",
"composeCollectionLogName",
"(",
... | Update the existing database data, otherwise insert this data
@param array|string $collection collection name.
@param array|object $data data to be updated/inserted.
@param array $options list of options in format: optionName => optionValue.
@return \MongoDB\BSON\ObjectID updated/new record id instance. | [
"Update",
"the",
"existing",
"database",
"data",
"otherwise",
"insert",
"this",
"data"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L207-L213 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.remove | public function remove($collection, $condition = [], $options = [])
{
$this->beginProfile($token = " > remove " . $this->composeCollectionLogName($collection) . ") ...");
$result = $this->db->getCollection($collection)->remove($condition, $options);
$this->endProfile($token);
return $result;
} | php | public function remove($collection, $condition = [], $options = [])
{
$this->beginProfile($token = " > remove " . $this->composeCollectionLogName($collection) . ") ...");
$result = $this->db->getCollection($collection)->remove($condition, $options);
$this->endProfile($token);
return $result;
} | [
"public",
"function",
"remove",
"(",
"$",
"collection",
",",
"$",
"condition",
"=",
"[",
"]",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"this",
"->",
"beginProfile",
"(",
"$",
"token",
"=",
"\" > remove \"",
".",
"$",
"this",
"->",
"compo... | Removes data from the collection.
@param array|string $collection collection name.
@param array $condition description of records to remove.
@param array $options list of options in format: optionName => optionValue.
@return int|bool number of updated documents or whether operation was successful. | [
"Removes",
"data",
"from",
"the",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L222-L228 |
yiisoft/yii2-mongodb | src/Migration.php | Migration.composeCollectionLogName | protected function composeCollectionLogName($collection)
{
if (is_array($collection)) {
list($database, $collection) = $collection;
return $database . '.' . $collection;
}
return $collection;
} | php | protected function composeCollectionLogName($collection)
{
if (is_array($collection)) {
list($database, $collection) = $collection;
return $database . '.' . $collection;
}
return $collection;
} | [
"protected",
"function",
"composeCollectionLogName",
"(",
"$",
"collection",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"collection",
")",
")",
"{",
"list",
"(",
"$",
"database",
",",
"$",
"collection",
")",
"=",
"$",
"collection",
";",
"return",
"$",
"d... | Composes string representing collection name.
@param array|string $collection collection name.
@return string collection name. | [
"Composes",
"string",
"representing",
"collection",
"name",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/Migration.php#L235-L242 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.rules | public function rules()
{
return array_merge(parent::rules(), [
[['db', 'ns', 'collectionName', 'databaseName', 'attributeList', 'modelClass', 'baseClass'], 'filter', 'filter' => 'trim'],
[['ns'], 'filter', 'filter' => function($value) { return trim($value, '\\'); }],
[['db', 'ns', 'collectionName', 'baseClass'], 'required'],
[['db', 'modelClass'], 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'],
[['ns', 'baseClass'], 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'],
[['collectionName'], 'match', 'pattern' => '/^[^$ ]+$/', 'message' => 'Collection name can not contain spaces or "$" symbols.'],
[['databaseName'], 'match', 'pattern' => '/^[^\\/\\\\\\. "*:?\\|<>]+$/', 'message' => 'Database name can not contain spaces or any of "/\."*<>:|?" symbols.'],
[['db'], 'validateDb'],
[['ns'], 'validateNamespace'],
[['collectionName'], 'validateCollectionName'],
[['attributeList'], 'match', 'pattern' => '/^(\w+\,[ ]*)*([\w]+)$/', 'message' => 'Attributes should contain only word characters, and should be separated by coma.'],
[['modelClass'], 'validateModelClass', 'skipOnEmpty' => false],
[['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]],
[['enableI18N'], 'boolean'],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
]);
} | php | public function rules()
{
return array_merge(parent::rules(), [
[['db', 'ns', 'collectionName', 'databaseName', 'attributeList', 'modelClass', 'baseClass'], 'filter', 'filter' => 'trim'],
[['ns'], 'filter', 'filter' => function($value) { return trim($value, '\\'); }],
[['db', 'ns', 'collectionName', 'baseClass'], 'required'],
[['db', 'modelClass'], 'match', 'pattern' => '/^\w+$/', 'message' => 'Only word characters are allowed.'],
[['ns', 'baseClass'], 'match', 'pattern' => '/^[\w\\\\]+$/', 'message' => 'Only word characters and backslashes are allowed.'],
[['collectionName'], 'match', 'pattern' => '/^[^$ ]+$/', 'message' => 'Collection name can not contain spaces or "$" symbols.'],
[['databaseName'], 'match', 'pattern' => '/^[^\\/\\\\\\. "*:?\\|<>]+$/', 'message' => 'Database name can not contain spaces or any of "/\."*<>:|?" symbols.'],
[['db'], 'validateDb'],
[['ns'], 'validateNamespace'],
[['collectionName'], 'validateCollectionName'],
[['attributeList'], 'match', 'pattern' => '/^(\w+\,[ ]*)*([\w]+)$/', 'message' => 'Attributes should contain only word characters, and should be separated by coma.'],
[['modelClass'], 'validateModelClass', 'skipOnEmpty' => false],
[['baseClass'], 'validateClass', 'params' => ['extends' => ActiveRecord::className()]],
[['enableI18N'], 'boolean'],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
]);
} | [
"public",
"function",
"rules",
"(",
")",
"{",
"return",
"array_merge",
"(",
"parent",
"::",
"rules",
"(",
")",
",",
"[",
"[",
"[",
"'db'",
",",
"'ns'",
",",
"'collectionName'",
",",
"'databaseName'",
",",
"'attributeList'",
",",
"'modelClass'",
",",
"'base... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L53-L73 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.autoCompleteData | public function autoCompleteData()
{
$db = $this->getDbConnection();
if ($db !== null) {
return [
'collectionName' => function () use ($db) {
$collections = $db->getDatabase()->createCommand()->listCollections();
return ArrayHelper::getColumn($collections, 'name');
},
];
}
return [];
} | php | public function autoCompleteData()
{
$db = $this->getDbConnection();
if ($db !== null) {
return [
'collectionName' => function () use ($db) {
$collections = $db->getDatabase()->createCommand()->listCollections();
return ArrayHelper::getColumn($collections, 'name');
},
];
}
return [];
} | [
"public",
"function",
"autoCompleteData",
"(",
")",
"{",
"$",
"db",
"=",
"$",
"this",
"->",
"getDbConnection",
"(",
")",
";",
"if",
"(",
"$",
"db",
"!==",
"null",
")",
"{",
"return",
"[",
"'collectionName'",
"=>",
"function",
"(",
")",
"use",
"(",
"$... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L113-L125 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.generate | public function generate()
{
$files = [];
$collectionName = $this->collectionName;
$attributes = ['_id'];
if (!empty($this->attributeList)) {
$customAttributes = explode(',', $this->attributeList);
$customAttributes = array_map('trim', $customAttributes);
$attributes = array_merge(['_id'], $customAttributes);
}
$className = $this->generateClassName($collectionName);
$params = [
'collectionName' => $collectionName,
'className' => $className,
'attributes' => $attributes,
'labels' => $this->generateLabels($attributes),
'rules' => $this->generateRules($attributes),
];
$files[] = new CodeFile(
Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php',
$this->render('model.php', $params)
);
return $files;
} | php | public function generate()
{
$files = [];
$collectionName = $this->collectionName;
$attributes = ['_id'];
if (!empty($this->attributeList)) {
$customAttributes = explode(',', $this->attributeList);
$customAttributes = array_map('trim', $customAttributes);
$attributes = array_merge(['_id'], $customAttributes);
}
$className = $this->generateClassName($collectionName);
$params = [
'collectionName' => $collectionName,
'className' => $className,
'attributes' => $attributes,
'labels' => $this->generateLabels($attributes),
'rules' => $this->generateRules($attributes),
];
$files[] = new CodeFile(
Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php',
$this->render('model.php', $params)
);
return $files;
} | [
"public",
"function",
"generate",
"(",
")",
"{",
"$",
"files",
"=",
"[",
"]",
";",
"$",
"collectionName",
"=",
"$",
"this",
"->",
"collectionName",
";",
"$",
"attributes",
"=",
"[",
"'_id'",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->"... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L146-L172 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.generateLabels | public function generateLabels($attributes)
{
$labels = [];
foreach ($attributes as $attribute) {
if (!strcasecmp($attribute, '_id')) {
$label = 'ID';
} else {
$label = Inflector::camel2words($attribute);
if (substr_compare($label, ' id', -3, 3, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
}
$labels[$attribute] = $label;
}
return $labels;
} | php | public function generateLabels($attributes)
{
$labels = [];
foreach ($attributes as $attribute) {
if (!strcasecmp($attribute, '_id')) {
$label = 'ID';
} else {
$label = Inflector::camel2words($attribute);
if (substr_compare($label, ' id', -3, 3, true) === 0) {
$label = substr($label, 0, -3) . ' ID';
}
}
$labels[$attribute] = $label;
}
return $labels;
} | [
"public",
"function",
"generateLabels",
"(",
"$",
"attributes",
")",
"{",
"$",
"labels",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"!",
"strcasecmp",
"(",
"$",
"attribute",
",",
"'_id'",
")",
... | Generates the attribute labels for the specified attributes list.
@param array $attributes the list of attributes
@return array the generated attribute labels (name => label) | [
"Generates",
"the",
"attribute",
"labels",
"for",
"the",
"specified",
"attributes",
"list",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L179-L195 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.generateRules | public function generateRules($attributes)
{
$rules = [];
$safeAttributes = [];
foreach ($attributes as $attribute) {
if ($attribute == '_id') {
continue;
}
$safeAttributes[] = $attribute;
}
if (!empty($safeAttributes)) {
$rules[] = "[['" . implode("', '", $safeAttributes) . "'], 'safe']";
}
return $rules;
} | php | public function generateRules($attributes)
{
$rules = [];
$safeAttributes = [];
foreach ($attributes as $attribute) {
if ($attribute == '_id') {
continue;
}
$safeAttributes[] = $attribute;
}
if (!empty($safeAttributes)) {
$rules[] = "[['" . implode("', '", $safeAttributes) . "'], 'safe']";
}
return $rules;
} | [
"public",
"function",
"generateRules",
"(",
"$",
"attributes",
")",
"{",
"$",
"rules",
"=",
"[",
"]",
";",
"$",
"safeAttributes",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"attributes",
"as",
"$",
"attribute",
")",
"{",
"if",
"(",
"$",
"attribute",
"=... | Generates validation rules for the specified collection.
@param array $attributes the list of attributes
@return array the generated validation rules | [
"Generates",
"validation",
"rules",
"for",
"the",
"specified",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L202-L216 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.validateNamespace | public function validateNamespace()
{
$this->ns = ltrim($this->ns, '\\');
$path = Yii::getAlias('@' . str_replace('\\', '/', $this->ns), false);
if ($path === false) {
$this->addError('ns', 'Namespace must be associated with an existing directory.');
}
} | php | public function validateNamespace()
{
$this->ns = ltrim($this->ns, '\\');
$path = Yii::getAlias('@' . str_replace('\\', '/', $this->ns), false);
if ($path === false) {
$this->addError('ns', 'Namespace must be associated with an existing directory.');
}
} | [
"public",
"function",
"validateNamespace",
"(",
")",
"{",
"$",
"this",
"->",
"ns",
"=",
"ltrim",
"(",
"$",
"this",
"->",
"ns",
",",
"'\\\\'",
")",
";",
"$",
"path",
"=",
"Yii",
"::",
"getAlias",
"(",
"'@'",
".",
"str_replace",
"(",
"'\\\\'",
",",
"... | Validates the [[ns]] attribute. | [
"Validates",
"the",
"[[",
"ns",
"]]",
"attribute",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L233-L240 |
yiisoft/yii2-mongodb | src/gii/model/Generator.php | Generator.validateCollectionName | public function validateCollectionName()
{
if (empty($this->modelClass)) {
$class = $this->generateClassName($this->collectionName);
if ($this->isReservedKeyword($class)) {
$this->addError('collectionName', "Collection '{$this->collectionName}' will generate a class which is a reserved PHP keyword.");
}
}
} | php | public function validateCollectionName()
{
if (empty($this->modelClass)) {
$class = $this->generateClassName($this->collectionName);
if ($this->isReservedKeyword($class)) {
$this->addError('collectionName', "Collection '{$this->collectionName}' will generate a class which is a reserved PHP keyword.");
}
}
} | [
"public",
"function",
"validateCollectionName",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"modelClass",
")",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"generateClassName",
"(",
"$",
"this",
"->",
"collectionName",
")",
";",
"if",
... | Validates the [[collectionName]] attribute. | [
"Validates",
"the",
"[[",
"collectionName",
"]]",
"attribute",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/gii/model/Generator.php#L255-L263 |
yiisoft/yii2-mongodb | src/LogBuilder.php | LogBuilder.processData | protected function processData($data)
{
if (is_object($data)) {
if ($data instanceof ObjectID ||
$data instanceof Regex ||
$data instanceof UTCDateTime ||
$data instanceof Timestamp
) {
$data = get_class($data) . '(' . $data->__toString() . ')';
} elseif ($data instanceof Javascript) {
$data = $this->processJavascript($data);
} elseif ($data instanceof MinKey || $data instanceof MaxKey) {
$data = get_class($data);
} elseif ($data instanceof Binary) {
if (in_array($data->getType(), [Binary::TYPE_MD5, Binary::TYPE_UUID, Binary::TYPE_OLD_UUID], true)) {
$data = $data->getData();
} else {
$data = get_class($data) . '(...)';
}
} elseif ($data instanceof Type) {
// Covers 'Binary', 'DBRef' and others
$data = get_class($data) . '(...)';
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$data[$key] = $this->processData($value);
}
}
}
return $data;
} | php | protected function processData($data)
{
if (is_object($data)) {
if ($data instanceof ObjectID ||
$data instanceof Regex ||
$data instanceof UTCDateTime ||
$data instanceof Timestamp
) {
$data = get_class($data) . '(' . $data->__toString() . ')';
} elseif ($data instanceof Javascript) {
$data = $this->processJavascript($data);
} elseif ($data instanceof MinKey || $data instanceof MaxKey) {
$data = get_class($data);
} elseif ($data instanceof Binary) {
if (in_array($data->getType(), [Binary::TYPE_MD5, Binary::TYPE_UUID, Binary::TYPE_OLD_UUID], true)) {
$data = $data->getData();
} else {
$data = get_class($data) . '(...)';
}
} elseif ($data instanceof Type) {
// Covers 'Binary', 'DBRef' and others
$data = get_class($data) . '(...)';
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$data[$key] = $this->processData($value);
}
}
}
return $data;
} | [
"protected",
"function",
"processData",
"(",
"$",
"data",
")",
"{",
"if",
"(",
"is_object",
"(",
"$",
"data",
")",
")",
"{",
"if",
"(",
"$",
"data",
"instanceof",
"ObjectID",
"||",
"$",
"data",
"instanceof",
"Regex",
"||",
"$",
"data",
"instanceof",
"U... | Pre-processes the log data before sending it to `json_encode()`.
@param mixed $data raw data.
@return mixed the processed data. | [
"Pre",
"-",
"processes",
"the",
"log",
"data",
"before",
"sending",
"it",
"to",
"json_encode",
"()",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/LogBuilder.php#L58-L102 |
yiisoft/yii2-mongodb | src/LogBuilder.php | LogBuilder.processJavascript | private function processJavascript(Javascript $javascript)
{
$dump = print_r($javascript, true);
$beginPos = strpos($dump, '[javascript] => ');
if ($beginPos === false) {
$beginPos = strpos($dump, '[code] => ');
if ($beginPos === false) {
return $dump;
}
$beginPos += strlen('[code] => ');
} else {
$beginPos += strlen('[javascript] => ');
}
$endPos = strrpos($dump, '[scope] => ');
if ($endPos === false || $beginPos > $endPos) {
return $dump;
}
$content = substr($dump, $beginPos, $endPos - $beginPos);
return get_class($javascript) . '(' . trim($content, " \n\t") . ')';
} | php | private function processJavascript(Javascript $javascript)
{
$dump = print_r($javascript, true);
$beginPos = strpos($dump, '[javascript] => ');
if ($beginPos === false) {
$beginPos = strpos($dump, '[code] => ');
if ($beginPos === false) {
return $dump;
}
$beginPos += strlen('[code] => ');
} else {
$beginPos += strlen('[javascript] => ');
}
$endPos = strrpos($dump, '[scope] => ');
if ($endPos === false || $beginPos > $endPos) {
return $dump;
}
$content = substr($dump, $beginPos, $endPos - $beginPos);
return get_class($javascript) . '(' . trim($content, " \n\t") . ')';
} | [
"private",
"function",
"processJavascript",
"(",
"Javascript",
"$",
"javascript",
")",
"{",
"$",
"dump",
"=",
"print_r",
"(",
"$",
"javascript",
",",
"true",
")",
";",
"$",
"beginPos",
"=",
"strpos",
"(",
"$",
"dump",
",",
"'[javascript] => '",
")",
";",
... | Processes [[Javascript]] composing recoverable value.
@param Javascript $javascript javascript BSON object.
@return string processed javascript. | [
"Processes",
"[[",
"Javascript",
"]]",
"composing",
"recoverable",
"value",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/LogBuilder.php#L109-L130 |
yiisoft/yii2-mongodb | src/log/MongoDbTarget.php | MongoDbTarget.export | public function export()
{
$rows = [];
foreach ($this->messages as $message) {
list($text, $level, $category, $timestamp) = $message;
if (!is_string($text)) {
// exceptions may not be serializable if in the call stack somewhere is a Closure
if ($text instanceof \Throwable || $text instanceof \Exception) {
$text = (string) $text;
} else {
$text = VarDumper::export($text);
}
}
$rows[] = [
'level' => $level,
'category' => $category,
'log_time' => $timestamp,
'prefix' => $this->getMessagePrefix($message),
'message' => $text,
];
}
$this->db->getCollection($this->logCollection)->batchInsert($rows);
} | php | public function export()
{
$rows = [];
foreach ($this->messages as $message) {
list($text, $level, $category, $timestamp) = $message;
if (!is_string($text)) {
// exceptions may not be serializable if in the call stack somewhere is a Closure
if ($text instanceof \Throwable || $text instanceof \Exception) {
$text = (string) $text;
} else {
$text = VarDumper::export($text);
}
}
$rows[] = [
'level' => $level,
'category' => $category,
'log_time' => $timestamp,
'prefix' => $this->getMessagePrefix($message),
'message' => $text,
];
}
$this->db->getCollection($this->logCollection)->batchInsert($rows);
} | [
"public",
"function",
"export",
"(",
")",
"{",
"$",
"rows",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"messages",
"as",
"$",
"message",
")",
"{",
"list",
"(",
"$",
"text",
",",
"$",
"level",
",",
"$",
"category",
",",
"$",
"timestamp... | Stores log messages to MongoDB collection. | [
"Stores",
"log",
"messages",
"to",
"MongoDB",
"collection",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/log/MongoDbTarget.php#L55-L78 |
yiisoft/yii2-mongodb | src/file/Upload.php | Upload.init | public function init()
{
$this->_hashContext = hash_init('md5');
if (isset($this->document['_id'])) {
if ($this->document['_id'] instanceof ObjectID) {
$this->_documentId = $this->document['_id'];
} else {
try {
$this->_documentId = new ObjectID($this->document['_id']);
} catch (InvalidArgumentException $e) {
// invalid id format
$this->_documentId = $this->document['_id'];
}
}
} else {
$this->_documentId = new ObjectID();
}
$this->collection->ensureIndexes();
} | php | public function init()
{
$this->_hashContext = hash_init('md5');
if (isset($this->document['_id'])) {
if ($this->document['_id'] instanceof ObjectID) {
$this->_documentId = $this->document['_id'];
} else {
try {
$this->_documentId = new ObjectID($this->document['_id']);
} catch (InvalidArgumentException $e) {
// invalid id format
$this->_documentId = $this->document['_id'];
}
}
} else {
$this->_documentId = new ObjectID();
}
$this->collection->ensureIndexes();
} | [
"public",
"function",
"init",
"(",
")",
"{",
"$",
"this",
"->",
"_hashContext",
"=",
"hash_init",
"(",
"'md5'",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"document",
"[",
"'_id'",
"]",
")",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"doc... | {@inheritdoc} | [
"{"
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L103-L123 |
yiisoft/yii2-mongodb | src/file/Upload.php | Upload.addContent | public function addContent($content)
{
$freeBufferLength = $this->chunkSize - StringHelper::byteLength($this->_buffer);
$contentLength = StringHelper::byteLength($content);
if ($contentLength > $freeBufferLength) {
$this->_buffer .= StringHelper::byteSubstr($content, 0, $freeBufferLength);
$this->flushBuffer(true);
return $this->addContent(StringHelper::byteSubstr($content, $freeBufferLength));
} else {
$this->_buffer .= $content;
$this->flushBuffer();
}
return $this;
} | php | public function addContent($content)
{
$freeBufferLength = $this->chunkSize - StringHelper::byteLength($this->_buffer);
$contentLength = StringHelper::byteLength($content);
if ($contentLength > $freeBufferLength) {
$this->_buffer .= StringHelper::byteSubstr($content, 0, $freeBufferLength);
$this->flushBuffer(true);
return $this->addContent(StringHelper::byteSubstr($content, $freeBufferLength));
} else {
$this->_buffer .= $content;
$this->flushBuffer();
}
return $this;
} | [
"public",
"function",
"addContent",
"(",
"$",
"content",
")",
"{",
"$",
"freeBufferLength",
"=",
"$",
"this",
"->",
"chunkSize",
"-",
"StringHelper",
"::",
"byteLength",
"(",
"$",
"this",
"->",
"_buffer",
")",
";",
"$",
"contentLength",
"=",
"StringHelper",
... | Adds string content to the upload.
This method can invoked several times before [[complete()]] is called.
@param string $content binary content.
@return $this self reference. | [
"Adds",
"string",
"content",
"to",
"the",
"upload",
".",
"This",
"method",
"can",
"invoked",
"several",
"times",
"before",
"[[",
"complete",
"()",
"]]",
"is",
"called",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L131-L145 |
yiisoft/yii2-mongodb | src/file/Upload.php | Upload.addStream | public function addStream($stream)
{
while (!feof($stream)) {
$freeBufferLength = $this->chunkSize - StringHelper::byteLength($this->_buffer);
$streamChunk = fread($stream, $freeBufferLength);
if ($streamChunk === false) {
break;
}
$this->_buffer .= $streamChunk;
$this->flushBuffer();
}
return $this;
} | php | public function addStream($stream)
{
while (!feof($stream)) {
$freeBufferLength = $this->chunkSize - StringHelper::byteLength($this->_buffer);
$streamChunk = fread($stream, $freeBufferLength);
if ($streamChunk === false) {
break;
}
$this->_buffer .= $streamChunk;
$this->flushBuffer();
}
return $this;
} | [
"public",
"function",
"addStream",
"(",
"$",
"stream",
")",
"{",
"while",
"(",
"!",
"feof",
"(",
"$",
"stream",
")",
")",
"{",
"$",
"freeBufferLength",
"=",
"$",
"this",
"->",
"chunkSize",
"-",
"StringHelper",
"::",
"byteLength",
"(",
"$",
"this",
"->"... | Adds stream content to the upload.
This method can invoked several times before [[complete()]] is called.
@param resource $stream data source stream.
@return $this self reference. | [
"Adds",
"stream",
"content",
"to",
"the",
"upload",
".",
"This",
"method",
"can",
"invoked",
"several",
"times",
"before",
"[[",
"complete",
"()",
"]]",
"is",
"called",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L153-L167 |
yiisoft/yii2-mongodb | src/file/Upload.php | Upload.addFile | public function addFile($filename)
{
if ($this->filename === null) {
$this->filename = basename($filename);
}
$stream = fopen($filename, 'r+');
if ($stream === false) {
throw new InvalidParamException("Unable to read file '{$filename}'");
}
return $this->addStream($stream);
} | php | public function addFile($filename)
{
if ($this->filename === null) {
$this->filename = basename($filename);
}
$stream = fopen($filename, 'r+');
if ($stream === false) {
throw new InvalidParamException("Unable to read file '{$filename}'");
}
return $this->addStream($stream);
} | [
"public",
"function",
"addFile",
"(",
"$",
"filename",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"filename",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"filename",
"=",
"basename",
"(",
"$",
"filename",
")",
";",
"}",
"$",
"stream",
"=",
"fopen",
"(... | Adds a file content to the upload.
This method can invoked several times before [[complete()]] is called.
@param string $filename source file name.
@return $this self reference. | [
"Adds",
"a",
"file",
"content",
"to",
"the",
"upload",
".",
"This",
"method",
"can",
"invoked",
"several",
"times",
"before",
"[[",
"complete",
"()",
"]]",
"is",
"called",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L175-L186 |
yiisoft/yii2-mongodb | src/file/Upload.php | Upload.complete | public function complete()
{
$this->flushBuffer(true);
$document = $this->insertFile();
$this->_isComplete = true;
return $document;
} | php | public function complete()
{
$this->flushBuffer(true);
$document = $this->insertFile();
$this->_isComplete = true;
return $document;
} | [
"public",
"function",
"complete",
"(",
")",
"{",
"$",
"this",
"->",
"flushBuffer",
"(",
"true",
")",
";",
"$",
"document",
"=",
"$",
"this",
"->",
"insertFile",
"(",
")",
";",
"$",
"this",
"->",
"_isComplete",
"=",
"true",
";",
"return",
"$",
"docume... | Completes upload.
@return array saved document. | [
"Completes",
"upload",
"."
] | train | https://github.com/yiisoft/yii2-mongodb/blob/7f8d9862ac6c133d63afda171860ca9b61563d27/src/file/Upload.php#L192-L201 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.