repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
locomotivemtl/charcoal-cache | src/Charcoal/Cache/CacheBuilder.php | CacheBuilder.setPoolClass | private function setPoolClass($class)
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
sprintf('Pool class %s does not exist', $class)
);
}
$interfaces = class_implements($class, true);
if (!in_array(PoolInterface::class, $interfaces)) {
throw new InvalidArgumentException(sprintf(
'Pool class %s must inherit from %s',
$class,
PoolInterface::class
));
}
$this->poolClass = $class;
} | php | private function setPoolClass($class)
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
sprintf('Pool class %s does not exist', $class)
);
}
$interfaces = class_implements($class, true);
if (!in_array(PoolInterface::class, $interfaces)) {
throw new InvalidArgumentException(sprintf(
'Pool class %s must inherit from %s',
$class,
PoolInterface::class
));
}
$this->poolClass = $class;
} | [
"private",
"function",
"setPoolClass",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Pool class %s does not exist'",
",",
"$",
"class",
")",
"... | Sets the specific Pool class generated by the cache builder.
Using this function developers can have the builder generate custom Pool objects.
@param string $class The pool class name.
@throws InvalidArgumentException When passed an invalid or nonexistant class.
@return void | [
"Sets",
"the",
"specific",
"Pool",
"class",
"generated",
"by",
"the",
"cache",
"builder",
"."
] | 38d04f6f21c6a826c28e08a5ac48b02c37e8da85 | https://github.com/locomotivemtl/charcoal-cache/blob/38d04f6f21c6a826c28e08a5ac48b02c37e8da85/src/Charcoal/Cache/CacheBuilder.php#L332-L351 | train |
locomotivemtl/charcoal-cache | src/Charcoal/Cache/CacheBuilder.php | CacheBuilder.setItemClass | private function setItemClass($class)
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
sprintf('Item class %s does not exist', $class)
);
}
$interfaces = class_implements($class, true);
if (!in_array(ItemInterface::class, $interfaces)) {
throw new InvalidArgumentException(sprintf(
'Item class %s must inherit from %s',
$class,
ItemInterface::class
));
}
$this->itemClass = $class;
} | php | private function setItemClass($class)
{
if (!class_exists($class)) {
throw new InvalidArgumentException(
sprintf('Item class %s does not exist', $class)
);
}
$interfaces = class_implements($class, true);
if (!in_array(ItemInterface::class, $interfaces)) {
throw new InvalidArgumentException(sprintf(
'Item class %s must inherit from %s',
$class,
ItemInterface::class
));
}
$this->itemClass = $class;
} | [
"private",
"function",
"setItemClass",
"(",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"$",
"class",
")",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"sprintf",
"(",
"'Item class %s does not exist'",
",",
"$",
"class",
")",
"... | Changes the specific Item class generated by the Pool objects.
Using this function developers can have the pool class generate custom Item objects.
@param string $class The item class name.
@throws InvalidArgumentException When passed an invalid or nonexistant class.
@return void | [
"Changes",
"the",
"specific",
"Item",
"class",
"generated",
"by",
"the",
"Pool",
"objects",
"."
] | 38d04f6f21c6a826c28e08a5ac48b02c37e8da85 | https://github.com/locomotivemtl/charcoal-cache/blob/38d04f6f21c6a826c28e08a5ac48b02c37e8da85/src/Charcoal/Cache/CacheBuilder.php#L362-L381 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/ObjectProperty.php | ObjectProperty.objType | public function objType()
{
if ($this->objType === null) {
throw new RuntimeException(sprintf(
'Missing object type ("obj_type"). Invalid property "%s".',
$this->ident()
));
}
return $this->objType;
} | php | public function objType()
{
if ($this->objType === null) {
throw new RuntimeException(sprintf(
'Missing object type ("obj_type"). Invalid property "%s".',
$this->ident()
));
}
return $this->objType;
} | [
"public",
"function",
"objType",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"objType",
"===",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sprintf",
"(",
"'Missing object type (\"obj_type\"). Invalid property \"%s\".'",
",",
"$",
"this",
"->",
"... | Retrieve the object type to build the choices from.
@throws RuntimeException If the object type was not previously set.
@return string | [
"Retrieve",
"the",
"object",
"type",
"to",
"build",
"the",
"choices",
"from",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/ObjectProperty.php#L152-L162 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/ObjectProperty.php | ObjectProperty.parseChoices | protected function parseChoices($objs)
{
if (!is_array($objs) && !$objs instanceof Traversable) {
throw new InvalidArgumentException('Must be iterable');
}
$parsed = [];
foreach ($objs as $choice) {
$choice = $this->parseChoice($choice);
if ($choice !== null) {
$choiceIdent = $choice['value'];
$parsed[$choiceIdent] = $choice;
}
}
return $parsed;
} | php | protected function parseChoices($objs)
{
if (!is_array($objs) && !$objs instanceof Traversable) {
throw new InvalidArgumentException('Must be iterable');
}
$parsed = [];
foreach ($objs as $choice) {
$choice = $this->parseChoice($choice);
if ($choice !== null) {
$choiceIdent = $choice['value'];
$parsed[$choiceIdent] = $choice;
}
}
return $parsed;
} | [
"protected",
"function",
"parseChoices",
"(",
"$",
"objs",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"objs",
")",
"&&",
"!",
"$",
"objs",
"instanceof",
"Traversable",
")",
"{",
"throw",
"new",
"InvalidArgumentException",
"(",
"'Must be iterable'",
")",... | Parse the given objects into choice structures.
@param ModelInterface[]|Traversable $objs One or more objects to format.
@throws InvalidArgumentException If the collection of objects is not iterable.
@return array Returns a collection of choice structures. | [
"Parse",
"the",
"given",
"objects",
"into",
"choice",
"structures",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/ObjectProperty.php#L656-L672 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/ObjectProperty.php | ObjectProperty.collectionModelLoader | protected function collectionModelLoader()
{
$loader = $this->collectionLoader();
if (!$loader->hasModel()) {
$loader->setModel($this->proto());
$pagination = $this->pagination();
if (!empty($pagination)) {
$loader->setPagination($pagination);
}
$orders = $this->orders();
if (!empty($orders)) {
$loader->setOrders($orders);
}
$filters = $this->filters();
if (!empty($filters)) {
$loader->setFilters($filters);
}
}
return $loader;
} | php | protected function collectionModelLoader()
{
$loader = $this->collectionLoader();
if (!$loader->hasModel()) {
$loader->setModel($this->proto());
$pagination = $this->pagination();
if (!empty($pagination)) {
$loader->setPagination($pagination);
}
$orders = $this->orders();
if (!empty($orders)) {
$loader->setOrders($orders);
}
$filters = $this->filters();
if (!empty($filters)) {
$loader->setFilters($filters);
}
}
return $loader;
} | [
"protected",
"function",
"collectionModelLoader",
"(",
")",
"{",
"$",
"loader",
"=",
"$",
"this",
"->",
"collectionLoader",
"(",
")",
";",
"if",
"(",
"!",
"$",
"loader",
"->",
"hasModel",
"(",
")",
")",
"{",
"$",
"loader",
"->",
"setModel",
"(",
"$",
... | Retrieve the prepared model collection loader.
@return CollectionLoader | [
"Retrieve",
"the",
"prepared",
"model",
"collection",
"loader",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/ObjectProperty.php#L721-L745 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/ObjectProperty.php | ObjectProperty.loadObject | protected function loadObject($objId)
{
if ($objId instanceof ModelInterface) {
return $objId;
}
$obj = $this->modelLoader()->load($objId);
if (!$obj->id()) {
return null;
} else {
return $obj;
}
} | php | protected function loadObject($objId)
{
if ($objId instanceof ModelInterface) {
return $objId;
}
$obj = $this->modelLoader()->load($objId);
if (!$obj->id()) {
return null;
} else {
return $obj;
}
} | [
"protected",
"function",
"loadObject",
"(",
"$",
"objId",
")",
"{",
"if",
"(",
"$",
"objId",
"instanceof",
"ModelInterface",
")",
"{",
"return",
"$",
"objId",
";",
"}",
"$",
"obj",
"=",
"$",
"this",
"->",
"modelLoader",
"(",
")",
"->",
"load",
"(",
"... | Retrieve an object by its ID.
Loads the object from the cache store or from the storage source.
@param mixed $objId Object id.
@return ModelInterface | [
"Retrieve",
"an",
"object",
"by",
"its",
"ID",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/ObjectProperty.php#L808-L820 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/ObjectProperty.php | ObjectProperty.modelLoader | protected function modelLoader($objType = null)
{
if ($objType === null) {
$objType = $this->objType();
} elseif (!is_string($objType)) {
throw new InvalidArgumentException(
'Object type must be a string.'
);
}
if (isset(self::$modelLoaders[$objType])) {
return self::$modelLoaders[$objType];
}
self::$modelLoaders[$objType] = new ModelLoader([
'logger' => $this->logger,
'obj_type' => $objType,
'factory' => $this->modelFactory(),
'cache' => $this->cachePool()
]);
return self::$modelLoaders[$objType];
} | php | protected function modelLoader($objType = null)
{
if ($objType === null) {
$objType = $this->objType();
} elseif (!is_string($objType)) {
throw new InvalidArgumentException(
'Object type must be a string.'
);
}
if (isset(self::$modelLoaders[$objType])) {
return self::$modelLoaders[$objType];
}
self::$modelLoaders[$objType] = new ModelLoader([
'logger' => $this->logger,
'obj_type' => $objType,
'factory' => $this->modelFactory(),
'cache' => $this->cachePool()
]);
return self::$modelLoaders[$objType];
} | [
"protected",
"function",
"modelLoader",
"(",
"$",
"objType",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"objType",
"===",
"null",
")",
"{",
"$",
"objType",
"=",
"$",
"this",
"->",
"objType",
"(",
")",
";",
"}",
"elseif",
"(",
"!",
"is_string",
"(",
"$"... | Retrieve the model loader.
@param string $objType The object type.
@throws InvalidArgumentException If the object type is invalid.
@return ModelLoader | [
"Retrieve",
"the",
"model",
"loader",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/ObjectProperty.php#L829-L851 | train |
cmsgears/module-core | common/models/traits/base/SlugTypeTrait.php | SlugTypeTrait.queryBySlug | public static function queryBySlug( $slug, $config = [] ) {
$ignoreSite = isset( $config[ 'ignoreSite' ] ) ? $config[ 'ignoreSite' ] : false;
if( static::isMultiSite() && !$ignoreSite ) {
$siteId = isset( $config[ 'siteId' ] ) ? $config[ 'siteId' ] : Yii::$app->core->siteId;
return static::find()->where( 'slug=:slug AND siteId=:siteId', [ ':slug' => $slug, ':siteId' => $siteId ] );
}
else {
return static::find()->where( 'slug=:slug', [ ':slug' => $slug ] );
}
} | php | public static function queryBySlug( $slug, $config = [] ) {
$ignoreSite = isset( $config[ 'ignoreSite' ] ) ? $config[ 'ignoreSite' ] : false;
if( static::isMultiSite() && !$ignoreSite ) {
$siteId = isset( $config[ 'siteId' ] ) ? $config[ 'siteId' ] : Yii::$app->core->siteId;
return static::find()->where( 'slug=:slug AND siteId=:siteId', [ ':slug' => $slug, ':siteId' => $siteId ] );
}
else {
return static::find()->where( 'slug=:slug', [ ':slug' => $slug ] );
}
} | [
"public",
"static",
"function",
"queryBySlug",
"(",
"$",
"slug",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"ignoreSite",
"=",
"isset",
"(",
"$",
"config",
"[",
"'ignoreSite'",
"]",
")",
"?",
"$",
"config",
"[",
"'ignoreSite'",
"]",
":",
"fals... | Return query to find the models by given slug.
@param string $slug
@param array $config
@return \yii\db\ActiveQuery to query by slug. | [
"Return",
"query",
"to",
"find",
"the",
"models",
"by",
"given",
"slug",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/traits/base/SlugTypeTrait.php#L67-L81 | train |
cmsgears/module-core | common/models/traits/base/SlugTypeTrait.php | SlugTypeTrait.isExistBySlugType | public static function isExistBySlugType( $slug, $type, $config = [] ) {
$model = static::findBySlugType( $slug, $type, $config );
return isset( $model );
} | php | public static function isExistBySlugType( $slug, $type, $config = [] ) {
$model = static::findBySlugType( $slug, $type, $config );
return isset( $model );
} | [
"public",
"static",
"function",
"isExistBySlugType",
"(",
"$",
"slug",
",",
"$",
"type",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"model",
"=",
"static",
"::",
"findBySlugType",
"(",
"$",
"slug",
",",
"$",
"type",
",",
"$",
"config",
")",
... | check whether model exist for given slug and type.
@param string $slug
@param string $type
@param array $config
@return boolean | [
"check",
"whether",
"model",
"exist",
"for",
"given",
"slug",
"and",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/traits/base/SlugTypeTrait.php#L154-L159 | train |
Innmind/CLI | src/Command/Pattern.php | Pattern.clean | public function clean(StreamInterface $arguments): StreamInterface
{
return $this->inputs->reduce(
$arguments,
static function(StreamInterface $arguments, Option $option): StreamInterface {
return $option->clean($arguments);
}
);
} | php | public function clean(StreamInterface $arguments): StreamInterface
{
return $this->inputs->reduce(
$arguments,
static function(StreamInterface $arguments, Option $option): StreamInterface {
return $option->clean($arguments);
}
);
} | [
"public",
"function",
"clean",
"(",
"StreamInterface",
"$",
"arguments",
")",
":",
"StreamInterface",
"{",
"return",
"$",
"this",
"->",
"inputs",
"->",
"reduce",
"(",
"$",
"arguments",
",",
"static",
"function",
"(",
"StreamInterface",
"$",
"arguments",
",",
... | Remove all options from the list of arguments so the arguments can be
correctly extracted
@param StreamInterface<string> $arguments
@return StreamInterface<string> | [
"Remove",
"all",
"options",
"from",
"the",
"list",
"of",
"arguments",
"so",
"the",
"arguments",
"can",
"be",
"correctly",
"extracted"
] | c15d13aa5155fef7eed24016a33b5862dae65bdd | https://github.com/Innmind/CLI/blob/c15d13aa5155fef7eed24016a33b5862dae65bdd/src/Command/Pattern.php#L123-L131 | train |
ethical-jobs/ethical-jobs-foundation-php | src/Utils/RequestUtil.php | RequestUtil.getSelectFields | public static function getSelectFields()
{
if ($select = request()->input('fields')) {
$httpRequestSelectFields = explode(',', $select);
if (strpos($select, '*') !== false) {
$httpRequestSelectFields = ['*'];
}
}
return $httpRequestSelectFields ?? [];
} | php | public static function getSelectFields()
{
if ($select = request()->input('fields')) {
$httpRequestSelectFields = explode(',', $select);
if (strpos($select, '*') !== false) {
$httpRequestSelectFields = ['*'];
}
}
return $httpRequestSelectFields ?? [];
} | [
"public",
"static",
"function",
"getSelectFields",
"(",
")",
"{",
"if",
"(",
"$",
"select",
"=",
"request",
"(",
")",
"->",
"input",
"(",
"'fields'",
")",
")",
"{",
"$",
"httpRequestSelectFields",
"=",
"explode",
"(",
"','",
",",
"$",
"select",
")",
";... | Parses request select fields into an array
@return array | [
"Parses",
"request",
"select",
"fields",
"into",
"an",
"array"
] | 35dafc2172dc8ba44c0ace4a58a7c0a9b63455a8 | https://github.com/ethical-jobs/ethical-jobs-foundation-php/blob/35dafc2172dc8ba44c0ace4a58a7c0a9b63455a8/src/Utils/RequestUtil.php#L18-L29 | train |
cmsgears/module-core | common/actions/meta/Delete.php | Delete.run | public function run( $cid ) {
$parent = $this->model;
if( isset( $parent ) ) {
$meta = $this->metaService->getById( $cid );
$belongsTo = $meta->hasAttribute( 'modelId' ) ? $meta->belongsTo( $parent ) : $meta->belongsTo( $parent, $this->modelService->getParentType() );
if( isset( $meta ) && $belongsTo ) {
$this->metaService->delete( $meta );
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => $meta->value ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | php | public function run( $cid ) {
$parent = $this->model;
if( isset( $parent ) ) {
$meta = $this->metaService->getById( $cid );
$belongsTo = $meta->hasAttribute( 'modelId' ) ? $meta->belongsTo( $parent ) : $meta->belongsTo( $parent, $this->modelService->getParentType() );
if( isset( $meta ) && $belongsTo ) {
$this->metaService->delete( $meta );
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => $meta->value ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | [
"public",
"function",
"run",
"(",
"$",
"cid",
")",
"{",
"$",
"parent",
"=",
"$",
"this",
"->",
"model",
";",
"if",
"(",
"isset",
"(",
"$",
"parent",
")",
")",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"metaService",
"->",
"getById",
"(",
"$",
"... | Delete meta for given meta id, parent slug and parent type. | [
"Delete",
"meta",
"for",
"given",
"meta",
"id",
"parent",
"slug",
"and",
"parent",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/actions/meta/Delete.php#L75-L97 | train |
mcaskill/charcoal-support | src/Property/ParsableValueTrait.php | ParsableValueTrait.parseAsMultiple | protected function parseAsMultiple($value, $separator = ',')
{
if (is_array($value) || $value instanceof Traversable) {
$parsed = [];
foreach ($value as $val) {
if (empty($val) && !is_numeric($val)) {
continue;
}
$parsed[] = $val;
}
return $parsed;
}
if ($separator instanceof PropertyInterface) {
$separator = $separator->multipleSeparator();
}
if (is_object($value) && method_exists($value, '__toString')) {
$value = strval($value);
}
if (empty($value) && !is_numeric($value)) {
return [];
}
/**
* This property is marked as "multiple".
* Manually handling the resolution to array
* until the property itself manages this.
*/
if (is_string($value)) {
return explode($separator, $value);
}
/**
* If the parameter isn't an array yet,
* means we might be dealing with an integer,
* an empty string, or an object.
*/
if (!is_array($value)) {
return (array)$value;
}
return $value;
} | php | protected function parseAsMultiple($value, $separator = ',')
{
if (is_array($value) || $value instanceof Traversable) {
$parsed = [];
foreach ($value as $val) {
if (empty($val) && !is_numeric($val)) {
continue;
}
$parsed[] = $val;
}
return $parsed;
}
if ($separator instanceof PropertyInterface) {
$separator = $separator->multipleSeparator();
}
if (is_object($value) && method_exists($value, '__toString')) {
$value = strval($value);
}
if (empty($value) && !is_numeric($value)) {
return [];
}
/**
* This property is marked as "multiple".
* Manually handling the resolution to array
* until the property itself manages this.
*/
if (is_string($value)) {
return explode($separator, $value);
}
/**
* If the parameter isn't an array yet,
* means we might be dealing with an integer,
* an empty string, or an object.
*/
if (!is_array($value)) {
return (array)$value;
}
return $value;
} | [
"protected",
"function",
"parseAsMultiple",
"(",
"$",
"value",
",",
"$",
"separator",
"=",
"','",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
"||",
"$",
"value",
"instanceof",
"Traversable",
")",
"{",
"$",
"parsed",
"=",
"[",
"]",
";",
"... | Parse the property value as a "multiple" value type.
@param mixed $value The value being converted to an array.
@param string|PropertyInterface $separator The boundary string.
@return array | [
"Parse",
"the",
"property",
"value",
"as",
"a",
"multiple",
"value",
"type",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Property/ParsableValueTrait.php#L36-L82 | train |
mcaskill/charcoal-support | src/Property/ParsableValueTrait.php | ParsableValueTrait.parseAsJson | protected function parseAsJson($value)
{
if (is_string($value)) {
$value = json_decode($value, true);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
switch ($error) {
case JSON_ERROR_DEPTH:
$message = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$message = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$message = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$message = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$message = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$message = 'Unknown error';
break;
}
throw new InvalidArgumentException(sprintf(
'Value "%s" could not be parsed as JSON: "%s"',
is_object($value) ? get_class($value) : gettype($value),
$message
));
}
}
return $value;
} | php | protected function parseAsJson($value)
{
if (is_string($value)) {
$value = json_decode($value, true);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
switch ($error) {
case JSON_ERROR_DEPTH:
$message = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$message = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$message = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$message = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$message = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$message = 'Unknown error';
break;
}
throw new InvalidArgumentException(sprintf(
'Value "%s" could not be parsed as JSON: "%s"',
is_object($value) ? get_class($value) : gettype($value),
$message
));
}
}
return $value;
} | [
"protected",
"function",
"parseAsJson",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"json_decode",
"(",
"$",
"value",
",",
"true",
")",
";",
"$",
"error",
"=",
"json_last_error",
"(",
")",... | Parse the property value as a JSON object.
@param mixed $value The JSONable value.
@throws InvalidArgumentException If the value is invalid.
@return array | [
"Parse",
"the",
"property",
"value",
"as",
"a",
"JSON",
"object",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Property/ParsableValueTrait.php#L91-L127 | train |
mcaskill/charcoal-support | src/Property/ParsableValueTrait.php | ParsableValueTrait.parseAsTranslatable | protected function parseAsTranslatable($value)
{
trigger_error('parseAsTranslatable() is deprecated. Use Translator::translation() instead.', E_USER_DEPRECATED);
$value = $this->translator()->translation($value);
return $value === null ? '' : $value;
} | php | protected function parseAsTranslatable($value)
{
trigger_error('parseAsTranslatable() is deprecated. Use Translator::translation() instead.', E_USER_DEPRECATED);
$value = $this->translator()->translation($value);
return $value === null ? '' : $value;
} | [
"protected",
"function",
"parseAsTranslatable",
"(",
"$",
"value",
")",
"{",
"trigger_error",
"(",
"'parseAsTranslatable() is deprecated. Use Translator::translation() instead.'",
",",
"E_USER_DEPRECATED",
")",
";",
"$",
"value",
"=",
"$",
"this",
"->",
"translator",
"(",... | Parse the property value as a "L10N" value type.
@deprecated In favor of 'locomotivemtl/charcoal-translator'
@param mixed $value The value being localized.
@return Translation|string|null | [
"Parse",
"the",
"property",
"value",
"as",
"a",
"L10N",
"value",
"type",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Property/ParsableValueTrait.php#L169-L176 | train |
mcaskill/charcoal-support | src/Property/ParsableValueTrait.php | ParsableValueTrait.parseAsTranslatableFallback | protected function parseAsTranslatableFallback($value, array $parameters = [])
{
$fallback = $this->translator()->translate($value, $parameters);
if (empty($fallback) && !is_numeric($fallback) && (is_array($value) || ($value instanceof ArrayAccess))) {
foreach ($this->translator()->getFallbackLocales() as $lang) {
$trans = $value[$lang];
if (!empty($trans) || is_numeric($trans)) {
$fallback = strtr($trans, $parameters);
break;
}
}
}
return $fallback;
} | php | protected function parseAsTranslatableFallback($value, array $parameters = [])
{
$fallback = $this->translator()->translate($value, $parameters);
if (empty($fallback) && !is_numeric($fallback) && (is_array($value) || ($value instanceof ArrayAccess))) {
foreach ($this->translator()->getFallbackLocales() as $lang) {
$trans = $value[$lang];
if (!empty($trans) || is_numeric($trans)) {
$fallback = strtr($trans, $parameters);
break;
}
}
}
return $fallback;
} | [
"protected",
"function",
"parseAsTranslatableFallback",
"(",
"$",
"value",
",",
"array",
"$",
"parameters",
"=",
"[",
"]",
")",
"{",
"$",
"fallback",
"=",
"$",
"this",
"->",
"translator",
"(",
")",
"->",
"translate",
"(",
"$",
"value",
",",
"$",
"paramet... | Retrieve a fallback value from a translatable value.
Note: Fallbacks are determined in your application settings, "locales.fallback_languages".
@param mixed $value A translatable value.
@param array $parameters An array of parameters for the message.
@return string|null | [
"Retrieve",
"a",
"fallback",
"value",
"from",
"a",
"translatable",
"value",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Property/ParsableValueTrait.php#L187-L201 | train |
mcaskill/charcoal-support | src/Property/ParsableValueTrait.php | ParsableValueTrait.pairTranslatableArrayItems | protected function pairTranslatableArrayItems($value, $separator = ',')
{
if (empty($value) && !is_numeric($value)) {
return null;
}
if ($value instanceof Translation) {
$value = $value->data();
}
if ($separator instanceof \Closure) {
$value = $separator($value);
} else {
// Parse each locale's collection into an array
foreach ($value as $k => $v) {
$value[$k] = $this->parseAsMultiple($v, $separator);
}
}
// Retrieve the highest collection count among the locales
$count = max(array_map('count', $value));
// Pair the items across locales
$result = [];
for ($i = 0; $i < $count; $i++) {
$entry = [];
foreach ($value as $lang => $arr) {
if (isset($arr[$i])) {
$entry[$lang] = $arr[$i];
}
}
$result[] = $this->translator()->translation($entry);
}
return $result;
} | php | protected function pairTranslatableArrayItems($value, $separator = ',')
{
if (empty($value) && !is_numeric($value)) {
return null;
}
if ($value instanceof Translation) {
$value = $value->data();
}
if ($separator instanceof \Closure) {
$value = $separator($value);
} else {
// Parse each locale's collection into an array
foreach ($value as $k => $v) {
$value[$k] = $this->parseAsMultiple($v, $separator);
}
}
// Retrieve the highest collection count among the locales
$count = max(array_map('count', $value));
// Pair the items across locales
$result = [];
for ($i = 0; $i < $count; $i++) {
$entry = [];
foreach ($value as $lang => $arr) {
if (isset($arr[$i])) {
$entry[$lang] = $arr[$i];
}
}
$result[] = $this->translator()->translation($entry);
}
return $result;
} | [
"protected",
"function",
"pairTranslatableArrayItems",
"(",
"$",
"value",
",",
"$",
"separator",
"=",
"','",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
"&&",
"!",
"is_numeric",
"(",
"$",
"value",
")",
")",
"{",
"return",
"null",
";",
"}",
... | Pair the translatable array items.
Converts this:
```
{
"en": [ "Item A", "Item B", "Item C", "Item D" ],
"fr": [ "Élément A", "Élément B", "Élément C" ]
}
```
Into:
```
[
{
"en": "Item A",
"fr": "Élément A",
},
{
"en": "Item B",
"fr": "Élément B",
},
{
"en": "Item C",
"fr": "Élément C",
},
{
"en": "Item D",
"fr": "",
}
],
```
@param mixed $value The value being converted to an array.
@param mixed $separator The item delimiter. This can be a string or a function.
@return array | [
"Pair",
"the",
"translatable",
"array",
"items",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Property/ParsableValueTrait.php#L240-L277 | train |
phPoirot/Std | src/Hydrator/HydrateGetters.php | HydrateGetters._getIgnoredByDocBlock | function _getIgnoredByDocBlock()
{
if ($this->_c_ignored_docblock)
// DocBlock Parsed To Cache Previously !!
return $this->_c_ignored_docblock;
$ignoredMethods = array();
$ref = $this->_newReflection();
$refuseIgnore = $this->getRefuseIgnore();
// ignored methods from Class DocComment:
$classDocComment = $ref->getDocComment();
if ($classDocComment !== false && preg_match_all('/.*[\n]?/', $classDocComment, $lines)) {
$lines = $lines[0];
$regex = '/.+(@method).+((?P<method_name>\b\w+)\(.*\))\s@'.self::HYDRATE_IGNORE.'\s/';
foreach($lines as $line) {
if (preg_match($regex, $line, $matches)) {
if (! in_array($matches['method_name'], $refuseIgnore) )
$ignoredMethods[] = $matches['method_name'];
}
}
}
// ignored methods from Method DocBlock
$methods = $ref->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach($methods as $m)
{
if (!(
('get' == substr($m->getName(), 0, 3) && $prefix = 'get')
|| ('is' == substr($m->getName(), 0, 2) && $prefix = 'is' )
))
// It's Not Getter Method
continue;
if (! in_array($m->getName(), $refuseIgnore) ) {
// it's not refused so check for ignore sign docblock
$mc = $m->getDocComment();
if ($mc !== false && preg_match('/@'.self::HYDRATE_IGNORE.'\s/', $mc, $matches))
$ignoredMethods[] = $m->getName();
}
}
return $this->_c_ignored_docblock = $ignoredMethods;
} | php | function _getIgnoredByDocBlock()
{
if ($this->_c_ignored_docblock)
// DocBlock Parsed To Cache Previously !!
return $this->_c_ignored_docblock;
$ignoredMethods = array();
$ref = $this->_newReflection();
$refuseIgnore = $this->getRefuseIgnore();
// ignored methods from Class DocComment:
$classDocComment = $ref->getDocComment();
if ($classDocComment !== false && preg_match_all('/.*[\n]?/', $classDocComment, $lines)) {
$lines = $lines[0];
$regex = '/.+(@method).+((?P<method_name>\b\w+)\(.*\))\s@'.self::HYDRATE_IGNORE.'\s/';
foreach($lines as $line) {
if (preg_match($regex, $line, $matches)) {
if (! in_array($matches['method_name'], $refuseIgnore) )
$ignoredMethods[] = $matches['method_name'];
}
}
}
// ignored methods from Method DocBlock
$methods = $ref->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach($methods as $m)
{
if (!(
('get' == substr($m->getName(), 0, 3) && $prefix = 'get')
|| ('is' == substr($m->getName(), 0, 2) && $prefix = 'is' )
))
// It's Not Getter Method
continue;
if (! in_array($m->getName(), $refuseIgnore) ) {
// it's not refused so check for ignore sign docblock
$mc = $m->getDocComment();
if ($mc !== false && preg_match('/@'.self::HYDRATE_IGNORE.'\s/', $mc, $matches))
$ignoredMethods[] = $m->getName();
}
}
return $this->_c_ignored_docblock = $ignoredMethods;
} | [
"function",
"_getIgnoredByDocBlock",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_c_ignored_docblock",
")",
"// DocBlock Parsed To Cache Previously !!",
"return",
"$",
"this",
"->",
"_c_ignored_docblock",
";",
"$",
"ignoredMethods",
"=",
"array",
"(",
")",
";",
... | Attain Ignored Methods From DockBlock
@ignore
@return []string | [
"Attain",
"Ignored",
"Methods",
"From",
"DockBlock"
] | 67883b1b1dd2cea80fec3d98a199c403b8a23b4d | https://github.com/phPoirot/Std/blob/67883b1b1dd2cea80fec3d98a199c403b8a23b4d/src/Hydrator/HydrateGetters.php#L260-L308 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/SelectablePropertyTrait.php | SelectablePropertyTrait.addChoices | public function addChoices(array $choices)
{
foreach ($choices as $choiceIdent => $choice) {
$this->addChoice($choiceIdent, $choice);
}
return $this;
} | php | public function addChoices(array $choices)
{
foreach ($choices as $choiceIdent => $choice) {
$this->addChoice($choiceIdent, $choice);
}
return $this;
} | [
"public",
"function",
"addChoices",
"(",
"array",
"$",
"choices",
")",
"{",
"foreach",
"(",
"$",
"choices",
"as",
"$",
"choiceIdent",
"=>",
"$",
"choice",
")",
"{",
"$",
"this",
"->",
"addChoice",
"(",
"$",
"choiceIdent",
",",
"$",
"choice",
")",
";",
... | Merge the available choices.
@param array $choices One or more choice structures.
@return self | [
"Merge",
"the",
"available",
"choices",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/SelectablePropertyTrait.php#L43-L50 | train |
locomotivemtl/charcoal-property | src/Charcoal/Property/SelectablePropertyTrait.php | SelectablePropertyTrait.parseChoices | protected function parseChoices(array $choices)
{
$parsed = [];
foreach ($choices as $choiceIdent => $choice) {
$choice = $this->parseChoice($choice, (string)$choiceIdent);
$choiceIdent = $choice['value'];
$parsed[$choiceIdent] = $choice;
}
return $parsed;
} | php | protected function parseChoices(array $choices)
{
$parsed = [];
foreach ($choices as $choiceIdent => $choice) {
$choice = $this->parseChoice($choice, (string)$choiceIdent);
$choiceIdent = $choice['value'];
$parsed[$choiceIdent] = $choice;
}
return $parsed;
} | [
"protected",
"function",
"parseChoices",
"(",
"array",
"$",
"choices",
")",
"{",
"$",
"parsed",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"choices",
"as",
"$",
"choiceIdent",
"=>",
"$",
"choice",
")",
"{",
"$",
"choice",
"=",
"$",
"this",
"->",
"parse... | Parse the given values into choice structures.
@param array $choices One or more values to format.
@return array Returns a collection of choice structures. | [
"Parse",
"the",
"given",
"values",
"into",
"choice",
"structures",
"."
] | 5ff339a0edb78a909537a9d2bb7f9b783255316b | https://github.com/locomotivemtl/charcoal-property/blob/5ff339a0edb78a909537a9d2bb7f9b783255316b/src/Charcoal/Property/SelectablePropertyTrait.php#L163-L174 | train |
Finesse/MicroDB | src/Exceptions/PDOException.php | PDOException.wrapBaseException | public static function wrapBaseException(BasePDOException $exception, string $query = null, array $values = null)
{
$newException = new static($exception->getMessage(), $exception->getCode(), $exception, $query, $values);
$newException->errorInfo = $exception->errorInfo;
return $newException;
} | php | public static function wrapBaseException(BasePDOException $exception, string $query = null, array $values = null)
{
$newException = new static($exception->getMessage(), $exception->getCode(), $exception, $query, $values);
$newException->errorInfo = $exception->errorInfo;
return $newException;
} | [
"public",
"static",
"function",
"wrapBaseException",
"(",
"BasePDOException",
"$",
"exception",
",",
"string",
"$",
"query",
"=",
"null",
",",
"array",
"$",
"values",
"=",
"null",
")",
"{",
"$",
"newException",
"=",
"new",
"static",
"(",
"$",
"exception",
... | Makes a self instance based on a base PDOException instance.
@param BasePDOException $exception Original exception
@param string|null $query SQL query which caused the error (if caused by a query)
@param array|null $values Bound values (if caused by a query)
@return self | [
"Makes",
"a",
"self",
"instance",
"based",
"on",
"a",
"base",
"PDOException",
"instance",
"."
] | 839ee9b2bbf7bf9811f946325ae7a0eb03d0c063 | https://github.com/Finesse/MicroDB/blob/839ee9b2bbf7bf9811f946325ae7a0eb03d0c063/src/Exceptions/PDOException.php#L61-L66 | train |
Finesse/MicroDB | src/Exceptions/PDOException.php | PDOException.valueToString | protected function valueToString($value): string
{
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
if ($value === null) {
return 'null';
}
if (is_string($value)) {
if (call_user_func(function_exists('mb_strlen') ? 'mb_strlen' : 'strlen', $value) > 100) {
$value = call_user_func(function_exists('mb_substr') ? 'mb_substr' : 'substr', $value, 0, 97).'...';
}
return '"'.$value.'"';
}
if (is_object($value)) {
return 'a '.get_class($value).' instance';
}
if (is_array($value)) {
$keys = array_keys($value);
$isAssociative = $keys !== array_keys($keys);
$valuesStrings = [];
foreach ($value as $key => $subValue) {
$valuesStrings[] = ($isAssociative ? $this->valueToString($key).' => ' : '')
. $this->valueToString($subValue);
}
return '['.implode(', ', $valuesStrings).']';
}
if (is_resource($value)) {
return 'a resource';
}
return (string)$value;
} | php | protected function valueToString($value): string
{
if ($value === false) {
return 'false';
}
if ($value === true) {
return 'true';
}
if ($value === null) {
return 'null';
}
if (is_string($value)) {
if (call_user_func(function_exists('mb_strlen') ? 'mb_strlen' : 'strlen', $value) > 100) {
$value = call_user_func(function_exists('mb_substr') ? 'mb_substr' : 'substr', $value, 0, 97).'...';
}
return '"'.$value.'"';
}
if (is_object($value)) {
return 'a '.get_class($value).' instance';
}
if (is_array($value)) {
$keys = array_keys($value);
$isAssociative = $keys !== array_keys($keys);
$valuesStrings = [];
foreach ($value as $key => $subValue) {
$valuesStrings[] = ($isAssociative ? $this->valueToString($key).' => ' : '')
. $this->valueToString($subValue);
}
return '['.implode(', ', $valuesStrings).']';
}
if (is_resource($value)) {
return 'a resource';
}
return (string)$value;
} | [
"protected",
"function",
"valueToString",
"(",
"$",
"value",
")",
":",
"string",
"{",
"if",
"(",
"$",
"value",
"===",
"false",
")",
"{",
"return",
"'false'",
";",
"}",
"if",
"(",
"$",
"value",
"===",
"true",
")",
"{",
"return",
"'true'",
";",
"}",
... | Converts an arbitrary value to string for a debug message.
@param mixed $value
@return string | [
"Converts",
"an",
"arbitrary",
"value",
"to",
"string",
"for",
"a",
"debug",
"message",
"."
] | 839ee9b2bbf7bf9811f946325ae7a0eb03d0c063 | https://github.com/Finesse/MicroDB/blob/839ee9b2bbf7bf9811f946325ae7a0eb03d0c063/src/Exceptions/PDOException.php#L90-L126 | train |
fxpio/fxp-cache | Adapter/AdapterDeferredTrait.php | AdapterDeferredTrait.clearDeferredByPrefixes | protected function clearDeferredByPrefixes(array $prefixes): void
{
$deferred = AdapterUtil::getPropertyValue($this, 'deferred');
foreach ($prefixes as $prefix) {
foreach ($deferred as $key => $value) {
if ('' === $prefix || 0 === strpos($key, $prefix)) {
unset($deferred[$key]);
}
}
}
AdapterUtil::setPropertyValue($this, 'deferred', $deferred);
} | php | protected function clearDeferredByPrefixes(array $prefixes): void
{
$deferred = AdapterUtil::getPropertyValue($this, 'deferred');
foreach ($prefixes as $prefix) {
foreach ($deferred as $key => $value) {
if ('' === $prefix || 0 === strpos($key, $prefix)) {
unset($deferred[$key]);
}
}
}
AdapterUtil::setPropertyValue($this, 'deferred', $deferred);
} | [
"protected",
"function",
"clearDeferredByPrefixes",
"(",
"array",
"$",
"prefixes",
")",
":",
"void",
"{",
"$",
"deferred",
"=",
"AdapterUtil",
"::",
"getPropertyValue",
"(",
"$",
"this",
",",
"'deferred'",
")",
";",
"foreach",
"(",
"$",
"prefixes",
"as",
"$"... | Clear the deferred by prefixes.
@param string[] $prefixes The prefixes | [
"Clear",
"the",
"deferred",
"by",
"prefixes",
"."
] | 55abf44a954890080fa2bfb080914ce7228ea769 | https://github.com/fxpio/fxp-cache/blob/55abf44a954890080fa2bfb080914ce7228ea769/Adapter/AdapterDeferredTrait.php#L26-L39 | train |
tyam/bamboo | src/Engine.php | Engine.render | public function render(string $template, array $variables = null, ArrayAccess $sections = null)
{
if (is_null($sections)) {
$sections = new ArrayObject();
}
$renderer = new Renderer([$this, 'resolve'], $sections);
$output = $renderer->render($template, $variables);
return $output;
} | php | public function render(string $template, array $variables = null, ArrayAccess $sections = null)
{
if (is_null($sections)) {
$sections = new ArrayObject();
}
$renderer = new Renderer([$this, 'resolve'], $sections);
$output = $renderer->render($template, $variables);
return $output;
} | [
"public",
"function",
"render",
"(",
"string",
"$",
"template",
",",
"array",
"$",
"variables",
"=",
"null",
",",
"ArrayAccess",
"$",
"sections",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"sections",
")",
")",
"{",
"$",
"sections",
"=",
... | Renders a specified template.
@param string $template path to the template. The path is relative from basedirs
@param array|null $variables template variables to be passed to template
@param ArrayAccess|null $sections array like object to hold section values | [
"Renders",
"a",
"specified",
"template",
"."
] | cd2745cebb6376fe5e36072e265ef66ead5e6ccf | https://github.com/tyam/bamboo/blob/cd2745cebb6376fe5e36072e265ef66ead5e6ccf/src/Engine.php#L69-L77 | train |
tyam/bamboo | src/Engine.php | Engine.resolve | public function resolve(string $template, array $variables = null)
{
return [
$this->resolvePath($template),
$this->resolveEnv($template, $variables)
];
} | php | public function resolve(string $template, array $variables = null)
{
return [
$this->resolvePath($template),
$this->resolveEnv($template, $variables)
];
} | [
"public",
"function",
"resolve",
"(",
"string",
"$",
"template",
",",
"array",
"$",
"variables",
"=",
"null",
")",
"{",
"return",
"[",
"$",
"this",
"->",
"resolvePath",
"(",
"$",
"template",
")",
",",
"$",
"this",
"->",
"resolveEnv",
"(",
"$",
"templat... | Resolves a template path and template variables. You should not call this method. | [
"Resolves",
"a",
"template",
"path",
"and",
"template",
"variables",
".",
"You",
"should",
"not",
"call",
"this",
"method",
"."
] | cd2745cebb6376fe5e36072e265ef66ead5e6ccf | https://github.com/tyam/bamboo/blob/cd2745cebb6376fe5e36072e265ef66ead5e6ccf/src/Engine.php#L82-L88 | train |
tyam/bamboo | src/Engine.php | Engine.resolvePath | public function resolvePath(string $template)
{
foreach ($this->basedirs as $basedir) {
$path = $basedir . self::SEPARATOR . $template . self::SUFFIX;
$path = str_replace(self::SEPARATOR, DIRECTORY_SEPARATOR, $path);
if (file_exists($path)) {
return $path;
}
}
// template not found
throw new \LogicException('template not found: '.$template);
} | php | public function resolvePath(string $template)
{
foreach ($this->basedirs as $basedir) {
$path = $basedir . self::SEPARATOR . $template . self::SUFFIX;
$path = str_replace(self::SEPARATOR, DIRECTORY_SEPARATOR, $path);
if (file_exists($path)) {
return $path;
}
}
// template not found
throw new \LogicException('template not found: '.$template);
} | [
"public",
"function",
"resolvePath",
"(",
"string",
"$",
"template",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"basedirs",
"as",
"$",
"basedir",
")",
"{",
"$",
"path",
"=",
"$",
"basedir",
".",
"self",
"::",
"SEPARATOR",
".",
"$",
"template",
".",
... | Resolves a template path. You should not call this method. | [
"Resolves",
"a",
"template",
"path",
".",
"You",
"should",
"not",
"call",
"this",
"method",
"."
] | cd2745cebb6376fe5e36072e265ef66ead5e6ccf | https://github.com/tyam/bamboo/blob/cd2745cebb6376fe5e36072e265ef66ead5e6ccf/src/Engine.php#L93-L104 | train |
tyam/bamboo | src/Engine.php | Engine.resolveEnv | public function resolveEnv(string $template, array $variables = null)
{
if (is_null($variables)) {
$variables = [];
}
$env = $this->getAutoBindings($template);
// explicit-bound variables precedes to auto-bound variables.
return array_merge($env, $variables);
} | php | public function resolveEnv(string $template, array $variables = null)
{
if (is_null($variables)) {
$variables = [];
}
$env = $this->getAutoBindings($template);
// explicit-bound variables precedes to auto-bound variables.
return array_merge($env, $variables);
} | [
"public",
"function",
"resolveEnv",
"(",
"string",
"$",
"template",
",",
"array",
"$",
"variables",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"variables",
")",
")",
"{",
"$",
"variables",
"=",
"[",
"]",
";",
"}",
"$",
"env",
"=",
"$",
... | Resolves a template variables. You should not call this method. | [
"Resolves",
"a",
"template",
"variables",
".",
"You",
"should",
"not",
"call",
"this",
"method",
"."
] | cd2745cebb6376fe5e36072e265ef66ead5e6ccf | https://github.com/tyam/bamboo/blob/cd2745cebb6376fe5e36072e265ef66ead5e6ccf/src/Engine.php#L109-L118 | train |
tyam/bamboo | src/Engine.php | Engine.getAutoBindings | protected function getAutoBindings(string $template)
{
if (is_null($this->variableProvider)) {
return [];
}
$bindings = $this->variableProvider->provideVariables($template);
return $bindings;
} | php | protected function getAutoBindings(string $template)
{
if (is_null($this->variableProvider)) {
return [];
}
$bindings = $this->variableProvider->provideVariables($template);
return $bindings;
} | [
"protected",
"function",
"getAutoBindings",
"(",
"string",
"$",
"template",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"variableProvider",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"bindings",
"=",
"$",
"this",
"->",
"variableProvide... | Pulls template variables from variableProvider, if there. | [
"Pulls",
"template",
"variables",
"from",
"variableProvider",
"if",
"there",
"."
] | cd2745cebb6376fe5e36072e265ef66ead5e6ccf | https://github.com/tyam/bamboo/blob/cd2745cebb6376fe5e36072e265ef66ead5e6ccf/src/Engine.php#L123-L132 | train |
cmsgears/module-core | common/actions/meta/Update.php | Update.run | public function run( $cid ) {
$parent = $this->model;
if( isset( $parent ) ) {
$meta = $this->metaService->getById( $cid );
$belongsTo = $meta->hasAttribute( 'modelId' ) ? $meta->belongsTo( $parent ) : $meta->belongsTo( $parent, $this->modelService->getParentType() );
if( isset( $meta ) && $belongsTo ) {
if( $meta->load( Yii::$app->request->post(), $meta->getClassName() ) && $meta->validate() ) {
$this->metaService->update( $meta );
$meta->refresh();
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => HtmlPurifier::process( $meta->value ) ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
// Generate Errors
$errors = AjaxUtil::generateErrorMessage( $model );
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_REQUEST ), $errors );
}
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->cmgCoreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | php | public function run( $cid ) {
$parent = $this->model;
if( isset( $parent ) ) {
$meta = $this->metaService->getById( $cid );
$belongsTo = $meta->hasAttribute( 'modelId' ) ? $meta->belongsTo( $parent ) : $meta->belongsTo( $parent, $this->modelService->getParentType() );
if( isset( $meta ) && $belongsTo ) {
if( $meta->load( Yii::$app->request->post(), $meta->getClassName() ) && $meta->validate() ) {
$this->metaService->update( $meta );
$meta->refresh();
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => HtmlPurifier::process( $meta->value ) ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
// Generate Errors
$errors = AjaxUtil::generateErrorMessage( $model );
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_REQUEST ), $errors );
}
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->cmgCoreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | [
"public",
"function",
"run",
"(",
"$",
"cid",
")",
"{",
"$",
"parent",
"=",
"$",
"this",
"->",
"model",
";",
"if",
"(",
"isset",
"(",
"$",
"parent",
")",
")",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"metaService",
"->",
"getById",
"(",
"$",
"... | Update Meta for given Meta id, parent slug and parent type. | [
"Update",
"Meta",
"for",
"given",
"Meta",
"id",
"parent",
"slug",
"and",
"parent",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/actions/meta/Update.php#L76-L109 | train |
975L/IncludeLibraryBundle | Twig/IncludeLibraryFont.php | IncludeLibraryFont.Font | public function Font(Environment $environment, $name)
{
//Returns the font code
$render = $environment->render('@c975LIncludeLibrary/fragments/font.html.twig', array(
'name' => str_replace(' ', '+', $name),
));
return str_replace(array("\n", ' ', ' ', ' ', ' ', ' '), ' ', $render);
} | php | public function Font(Environment $environment, $name)
{
//Returns the font code
$render = $environment->render('@c975LIncludeLibrary/fragments/font.html.twig', array(
'name' => str_replace(' ', '+', $name),
));
return str_replace(array("\n", ' ', ' ', ' ', ' ', ' '), ' ', $render);
} | [
"public",
"function",
"Font",
"(",
"Environment",
"$",
"environment",
",",
"$",
"name",
")",
"{",
"//Returns the font code",
"$",
"render",
"=",
"$",
"environment",
"->",
"render",
"(",
"'@c975LIncludeLibrary/fragments/font.html.twig'",
",",
"array",
"(",
"'name'",
... | Returns the font code to be included
@return string | [
"Returns",
"the",
"font",
"code",
"to",
"be",
"included"
] | 74f9140551d6f20c1308213c4c142f7fff43eb52 | https://github.com/975L/IncludeLibraryBundle/blob/74f9140551d6f20c1308213c4c142f7fff43eb52/Twig/IncludeLibraryFont.php#L40-L48 | train |
cmsgears/module-core | common/models/traits/base/NameTypeTrait.php | NameTypeTrait.findByNameType | public static function findByNameType( $name, $type, $config = [] ) {
return self::queryByNameType( $name, $type, $config )->all();
} | php | public static function findByNameType( $name, $type, $config = [] ) {
return self::queryByNameType( $name, $type, $config )->all();
} | [
"public",
"static",
"function",
"findByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"return",
"self",
"::",
"queryByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
")",
"->",
"all",
... | Find and return models using given name and type.
@param string $name
@param string $type
@param array $config
@return \cmsgears\core\common\models\base\ActiveRecord[] | [
"Find",
"and",
"return",
"models",
"using",
"given",
"name",
"and",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/traits/base/NameTypeTrait.php#L196-L199 | train |
cmsgears/module-core | common/models/traits/base/NameTypeTrait.php | NameTypeTrait.findFirstByNameType | public static function findFirstByNameType( $name, $type, $config = [] ) {
return self::queryByNameType( $name, $type, $config )->one();
} | php | public static function findFirstByNameType( $name, $type, $config = [] ) {
return self::queryByNameType( $name, $type, $config )->one();
} | [
"public",
"static",
"function",
"findFirstByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"return",
"self",
"::",
"queryByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
")",
"->",
"one... | Find and return first model using given name and type.
@param string $name
@param string $type
@param array $config
@return \cmsgears\core\common\models\base\ActiveRecord | [
"Find",
"and",
"return",
"first",
"model",
"using",
"given",
"name",
"and",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/traits/base/NameTypeTrait.php#L209-L212 | train |
cmsgears/module-core | common/models/traits/base/NameTypeTrait.php | NameTypeTrait.isExistByNameType | public static function isExistByNameType( $name, $type, $config = [] ) {
$model = self::findByNameType( $name, $type, $config );
return isset( $model );
} | php | public static function isExistByNameType( $name, $type, $config = [] ) {
$model = self::findByNameType( $name, $type, $config );
return isset( $model );
} | [
"public",
"static",
"function",
"isExistByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"model",
"=",
"self",
"::",
"findByNameType",
"(",
"$",
"name",
",",
"$",
"type",
",",
"$",
"config",
")",
";... | Check whether model exist for given name and type.
@param string $name
@param string $type
@param array $config
@return boolean | [
"Check",
"whether",
"model",
"exist",
"for",
"given",
"name",
"and",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/traits/base/NameTypeTrait.php#L222-L227 | train |
cmsgears/module-core | common/services/traits/base/MultiSiteTrait.php | MultiSiteTrait.getSiteStats | public function getSiteStats( $config = [] ) {
$status = isset( $config[ 'status' ] ) ? $config[ 'status' ] : null;
$type = isset( $config[ 'type' ] ) ? $config[ 'type' ] : null;
$limit = isset( $config[ 'limit' ] ) ? $config[ 'limit' ] : 0;
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$query = new Query();
$query->select( [ 'siteId', 'count(id) as total' ] )
->from( $modelTable );
// Filter Status
if( isset( $status ) ) {
$query->where( "$modelTable.status=:status", [ ':status' => $status ] );
}
// Filter Type
if( isset( $type ) ) {
$query->andWhere( "$modelTable.type=:type", [ ':type' => $type ] );
}
// Limit
if( $limit > 0 ) {
$query->limit( $limit );
}
// Group and Order
$query->groupBy( 'siteId' )->orderBy( 'total DESC' );
return $query->all();
} | php | public function getSiteStats( $config = [] ) {
$status = isset( $config[ 'status' ] ) ? $config[ 'status' ] : null;
$type = isset( $config[ 'type' ] ) ? $config[ 'type' ] : null;
$limit = isset( $config[ 'limit' ] ) ? $config[ 'limit' ] : 0;
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$query = new Query();
$query->select( [ 'siteId', 'count(id) as total' ] )
->from( $modelTable );
// Filter Status
if( isset( $status ) ) {
$query->where( "$modelTable.status=:status", [ ':status' => $status ] );
}
// Filter Type
if( isset( $type ) ) {
$query->andWhere( "$modelTable.type=:type", [ ':type' => $type ] );
}
// Limit
if( $limit > 0 ) {
$query->limit( $limit );
}
// Group and Order
$query->groupBy( 'siteId' )->orderBy( 'total DESC' );
return $query->all();
} | [
"public",
"function",
"getSiteStats",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"status",
"=",
"isset",
"(",
"$",
"config",
"[",
"'status'",
"]",
")",
"?",
"$",
"config",
"[",
"'status'",
"]",
":",
"null",
";",
"$",
"type",
"=",
"isset",
... | Returns model count of active models.
@param type $config
@return type | [
"Returns",
"model",
"count",
"of",
"active",
"models",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/traits/base/MultiSiteTrait.php#L50-L86 | train |
cmsgears/module-core | common/actions/meta/Create.php | Create.run | public function run() {
$parent = $this->model;
if( isset( $parent ) ) {
$metaClass = $this->metaService->getModelClass();
$meta = new $metaClass;
if( $meta->hasAttribute( 'modelId' ) ) {
$meta->modelId = $parent->id;
}
else {
$meta->parentId = $parent->id;
$meta->parentType = $this->modelService->getParentType();
}
if( empty( $meta->type ) ) {
$meta->type = CoreGlobal::TYPE_DEFAULT;
}
if( empty( $meta->valueType ) ) {
$meta->valueType = IMeta::VALUE_TYPE_TEXT;
}
if( $meta->load( Yii::$app->request->post(), $meta->getClassName() ) && $meta->validate() ) {
$this->metaService->create( $meta );
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => HtmlPurifier::process( $meta->value ) ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
// Generate Errors
$errors = AjaxUtil::generateErrorMessage( $meta );
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_REQUEST ), $errors );
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | php | public function run() {
$parent = $this->model;
if( isset( $parent ) ) {
$metaClass = $this->metaService->getModelClass();
$meta = new $metaClass;
if( $meta->hasAttribute( 'modelId' ) ) {
$meta->modelId = $parent->id;
}
else {
$meta->parentId = $parent->id;
$meta->parentType = $this->modelService->getParentType();
}
if( empty( $meta->type ) ) {
$meta->type = CoreGlobal::TYPE_DEFAULT;
}
if( empty( $meta->valueType ) ) {
$meta->valueType = IMeta::VALUE_TYPE_TEXT;
}
if( $meta->load( Yii::$app->request->post(), $meta->getClassName() ) && $meta->validate() ) {
$this->metaService->create( $meta );
$data = [ 'id' => $meta->id, 'name' => $meta->name, 'value' => HtmlPurifier::process( $meta->value ) ];
// Trigger Ajax Success
return AjaxUtil::generateSuccess( Yii::$app->coreMessage->getMessage( CoreGlobal::MESSAGE_REQUEST ), $data );
}
// Generate Errors
$errors = AjaxUtil::generateErrorMessage( $meta );
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_REQUEST ), $errors );
}
// Trigger Ajax Failure
return AjaxUtil::generateFailure( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | [
"public",
"function",
"run",
"(",
")",
"{",
"$",
"parent",
"=",
"$",
"this",
"->",
"model",
";",
"if",
"(",
"isset",
"(",
"$",
"parent",
")",
")",
"{",
"$",
"metaClass",
"=",
"$",
"this",
"->",
"metaService",
"->",
"getModelClass",
"(",
")",
";",
... | Create Meta for given parent slug and parent type. | [
"Create",
"Meta",
"for",
"given",
"parent",
"slug",
"and",
"parent",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/actions/meta/Create.php#L78-L127 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.boot | public function boot()
{
$app = $this;
$container = $this->getContainer();
if (is_api_request())
{
$this->loadDatabaseConnection();
$this->loadApiLibraries();
if (file_exists(system_path("registered-libraries-api.php")))
{
require system_path("registered-libraries-api.php");
}
if (file_exists(system_path("registered-global-middlewares-api.php")))
{
require system_path("registered-global-middlewares-api.php");
}
$app->group('/api', function() {
require base_path("routes/api.php");
});
}
else
{
$this->loadDatabaseConnection(true);
$this->loadLibraries();
require system_path("registered-libraries.php");
require system_path("registered-global-middlewares.php");
$this->loadMiddlewares($app, $container);
require base_path("routes/api.php");
require base_path("routes/web.php");
Profiler::finish("Application Done!");
}
} | php | public function boot()
{
$app = $this;
$container = $this->getContainer();
if (is_api_request())
{
$this->loadDatabaseConnection();
$this->loadApiLibraries();
if (file_exists(system_path("registered-libraries-api.php")))
{
require system_path("registered-libraries-api.php");
}
if (file_exists(system_path("registered-global-middlewares-api.php")))
{
require system_path("registered-global-middlewares-api.php");
}
$app->group('/api', function() {
require base_path("routes/api.php");
});
}
else
{
$this->loadDatabaseConnection(true);
$this->loadLibraries();
require system_path("registered-libraries.php");
require system_path("registered-global-middlewares.php");
$this->loadMiddlewares($app, $container);
require base_path("routes/api.php");
require base_path("routes/web.php");
Profiler::finish("Application Done!");
}
} | [
"public",
"function",
"boot",
"(",
")",
"{",
"$",
"app",
"=",
"$",
"this",
";",
"$",
"container",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
";",
"if",
"(",
"is_api_request",
"(",
")",
")",
"{",
"$",
"this",
"->",
"loadDatabaseConnection",
"("... | Boot the application.
@return void | [
"Boot",
"the",
"application",
"."
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L368-L405 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.loadLibraries | private function loadLibraries()
{
/**
* Setup for 'respect/validation'
*/
Validator::with("SkeletonCore\\Validation\\Rules\\");
Validator::with(get_app_namespace() . "\\Validation\\Rules\\");
/**
* Enable tracy debug bar
*/
$debugbar_enabled = filter_var(app_env('DEBUG_BAR_ON', false), FILTER_VALIDATE_BOOLEAN);
if (is_dev() && $debugbar_enabled && PHP_SAPI !== "cli")
{
Debugger::enable(Debugger::DEVELOPMENT, storage_path('logs'));
Debugger::timer();
if (file_exists($directory = app_path("Debugbars")))
{
$debugbar_files = get_files($directory);
if (!empty($debugbar_files))
{
$debugbars = array_map(function($debugbar) use($directory) {
$new_debugbar = str_replace("{$directory}/", "", $debugbar);
return basename(str_replace("/", "\\", $new_debugbar), ".php");
}, $debugbar_files);
foreach ($debugbars as $debugbar) {
$classPanel = get_app_namespace() . "Debugbars\\{$debugbar}";
Debugger::getBar()->addPanel(new $classPanel);
}
}
}
}
} | php | private function loadLibraries()
{
/**
* Setup for 'respect/validation'
*/
Validator::with("SkeletonCore\\Validation\\Rules\\");
Validator::with(get_app_namespace() . "\\Validation\\Rules\\");
/**
* Enable tracy debug bar
*/
$debugbar_enabled = filter_var(app_env('DEBUG_BAR_ON', false), FILTER_VALIDATE_BOOLEAN);
if (is_dev() && $debugbar_enabled && PHP_SAPI !== "cli")
{
Debugger::enable(Debugger::DEVELOPMENT, storage_path('logs'));
Debugger::timer();
if (file_exists($directory = app_path("Debugbars")))
{
$debugbar_files = get_files($directory);
if (!empty($debugbar_files))
{
$debugbars = array_map(function($debugbar) use($directory) {
$new_debugbar = str_replace("{$directory}/", "", $debugbar);
return basename(str_replace("/", "\\", $new_debugbar), ".php");
}, $debugbar_files);
foreach ($debugbars as $debugbar) {
$classPanel = get_app_namespace() . "Debugbars\\{$debugbar}";
Debugger::getBar()->addPanel(new $classPanel);
}
}
}
}
} | [
"private",
"function",
"loadLibraries",
"(",
")",
"{",
"/**\n * Setup for 'respect/validation'\n */",
"Validator",
"::",
"with",
"(",
"\"SkeletonCore\\\\Validation\\\\Rules\\\\\"",
")",
";",
"Validator",
"::",
"with",
"(",
"get_app_namespace",
"(",
")",
".",... | Load the libraries of the application.
@return void | [
"Load",
"the",
"libraries",
"of",
"the",
"application",
"."
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L436-L471 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.loadMiddlewares | private function loadMiddlewares($app, $container)
{
# Tracy debugbar
$debugbar_enabled = filter_var(app_env('DEBUG_BAR_ON', false), FILTER_VALIDATE_BOOLEAN);
if (is_dev() && $debugbar_enabled && PHP_SAPI !== "cli")
{
$app->add(new TracyMiddleware($app));
}
# Determine Route Before Application middleware
$app->add(new AppMiddleware($container));
# Global Error middleware
$app->add(new GlobalErrorsMiddleware($container));
# Old Input middleware
$app->add(new OldInputMiddleware($container));
# Global Csrf middleware
$app->add(new GlobalCsrfMiddleware($container));
$app->add($container->get('csrf'));
# Shared Server middleware
$app->add(new SharedServerMiddleware($container));
# Application Mode middleware
$app->add(new AppModeMiddleware($container));
# Remove Trailing Slash middleware
$app->add(new RemoveTrailingSlashMiddleware($container));
} | php | private function loadMiddlewares($app, $container)
{
# Tracy debugbar
$debugbar_enabled = filter_var(app_env('DEBUG_BAR_ON', false), FILTER_VALIDATE_BOOLEAN);
if (is_dev() && $debugbar_enabled && PHP_SAPI !== "cli")
{
$app->add(new TracyMiddleware($app));
}
# Determine Route Before Application middleware
$app->add(new AppMiddleware($container));
# Global Error middleware
$app->add(new GlobalErrorsMiddleware($container));
# Old Input middleware
$app->add(new OldInputMiddleware($container));
# Global Csrf middleware
$app->add(new GlobalCsrfMiddleware($container));
$app->add($container->get('csrf'));
# Shared Server middleware
$app->add(new SharedServerMiddleware($container));
# Application Mode middleware
$app->add(new AppModeMiddleware($container));
# Remove Trailing Slash middleware
$app->add(new RemoveTrailingSlashMiddleware($container));
} | [
"private",
"function",
"loadMiddlewares",
"(",
"$",
"app",
",",
"$",
"container",
")",
"{",
"# Tracy debugbar",
"$",
"debugbar_enabled",
"=",
"filter_var",
"(",
"app_env",
"(",
"'DEBUG_BAR_ON'",
",",
"false",
")",
",",
"FILTER_VALIDATE_BOOLEAN",
")",
";",
"if",
... | Load the middlewares of the application.
@param SlimApp $app
@param ContainerInterface $container
@return void | [
"Load",
"the",
"middlewares",
"of",
"the",
"application",
"."
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L494-L524 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.pushControllersInDefinition | private function pushControllersInDefinition($alias_namespace, $controllers_directory, &$default_definitions)
{
$controller_files = get_files($controllers_directory);
if (!empty($controller_files))
{
$controllers = array_map(function($controller) use($controllers_directory) {
$new_controller = str_replace("{$controllers_directory}/", "", $controller);
return basename(str_replace("/", "\\", $new_controller), ".php");
}, $controller_files);
$errors = [];
foreach ($controllers as $controller) {
if ($alias_namespace === "\\")
{
$controller_definition = $controller;
$controller_definition_value = get_app_namespace() . "Controllers\\{$controller}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$controller_sub_namespace = str_replace(app_path() . "/{$module_name}/Controllers", "", $controllers_directory);
$controller_sub_namespace = str_replace("/", "\\", $controller_sub_namespace);
$controller_definition = "{$alias_namespace}{$controller}";
$controller_definition_value = "{$alias_namespace}Controllers\\{$controller}";
}
if (!array_key_exists("{$controller_definition}", $default_definitions))
{
$default_definitions["{$controller_definition}"] = function(ContainerInterface $c) use ($controller_definition_value)
{
return new $controller_definition_value($c);
};
}
else
{
$errors[] = "{$controller} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No controller found in {$controllers_directory} path.");
}
} | php | private function pushControllersInDefinition($alias_namespace, $controllers_directory, &$default_definitions)
{
$controller_files = get_files($controllers_directory);
if (!empty($controller_files))
{
$controllers = array_map(function($controller) use($controllers_directory) {
$new_controller = str_replace("{$controllers_directory}/", "", $controller);
return basename(str_replace("/", "\\", $new_controller), ".php");
}, $controller_files);
$errors = [];
foreach ($controllers as $controller) {
if ($alias_namespace === "\\")
{
$controller_definition = $controller;
$controller_definition_value = get_app_namespace() . "Controllers\\{$controller}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$controller_sub_namespace = str_replace(app_path() . "/{$module_name}/Controllers", "", $controllers_directory);
$controller_sub_namespace = str_replace("/", "\\", $controller_sub_namespace);
$controller_definition = "{$alias_namespace}{$controller}";
$controller_definition_value = "{$alias_namespace}Controllers\\{$controller}";
}
if (!array_key_exists("{$controller_definition}", $default_definitions))
{
$default_definitions["{$controller_definition}"] = function(ContainerInterface $c) use ($controller_definition_value)
{
return new $controller_definition_value($c);
};
}
else
{
$errors[] = "{$controller} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No controller found in {$controllers_directory} path.");
}
} | [
"private",
"function",
"pushControllersInDefinition",
"(",
"$",
"alias_namespace",
",",
"$",
"controllers_directory",
",",
"&",
"$",
"default_definitions",
")",
"{",
"$",
"controller_files",
"=",
"get_files",
"(",
"$",
"controllers_directory",
")",
";",
"if",
"(",
... | Push controllers in default definition
@param string $alias_namespace
@param string $controllers_directory
@param array &$default_definitions
@return void | [
"Push",
"controllers",
"in",
"default",
"definition"
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L584-L635 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.pushMiddlewaresInDefinition | private function pushMiddlewaresInDefinition($alias_namespace, $middlewares_directory, &$default_definitions)
{
$middleware_files = get_files($middlewares_directory);
if (!empty($middleware_files))
{
$middlewares = array_map(function($middleware) use($middlewares_directory) {
$new_middleware = str_replace("{$middlewares_directory}/", "", $middleware);
return basename(str_replace("/", "\\", $new_middleware), ".php");
}, $middleware_files);
$errors = [];
foreach ($middlewares as $middleware) {
if ($alias_namespace === "\\")
{
$middleware_definition = $middleware;
$middleware_definition_value = get_app_namespace() . "Middlewares\\{$middleware}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$middleware_sub_namespace = str_replace(app_path() . "/{$module_name}/Middlewares", "", $middlewares_directory);
$middleware_sub_namespace = str_replace("/", "\\", $middleware_sub_namespace);
$middleware_definition = "{$alias_namespace}{$middleware}";
$middleware_definition_value = "{$alias_namespace}Middlewares\\{$middleware}";
}
if (!array_key_exists("{$middleware_definition}", $default_definitions))
{
$default_definitions["{$middleware_definition}"] = function(ContainerInterface $c) use ($middleware_definition_value)
{
return new $middleware_definition_value($c);
};
}
else
{
$errors[] = "{$middleware} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No middleware found in {$middlewares_directory} path.");
}
} | php | private function pushMiddlewaresInDefinition($alias_namespace, $middlewares_directory, &$default_definitions)
{
$middleware_files = get_files($middlewares_directory);
if (!empty($middleware_files))
{
$middlewares = array_map(function($middleware) use($middlewares_directory) {
$new_middleware = str_replace("{$middlewares_directory}/", "", $middleware);
return basename(str_replace("/", "\\", $new_middleware), ".php");
}, $middleware_files);
$errors = [];
foreach ($middlewares as $middleware) {
if ($alias_namespace === "\\")
{
$middleware_definition = $middleware;
$middleware_definition_value = get_app_namespace() . "Middlewares\\{$middleware}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$middleware_sub_namespace = str_replace(app_path() . "/{$module_name}/Middlewares", "", $middlewares_directory);
$middleware_sub_namespace = str_replace("/", "\\", $middleware_sub_namespace);
$middleware_definition = "{$alias_namespace}{$middleware}";
$middleware_definition_value = "{$alias_namespace}Middlewares\\{$middleware}";
}
if (!array_key_exists("{$middleware_definition}", $default_definitions))
{
$default_definitions["{$middleware_definition}"] = function(ContainerInterface $c) use ($middleware_definition_value)
{
return new $middleware_definition_value($c);
};
}
else
{
$errors[] = "{$middleware} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No middleware found in {$middlewares_directory} path.");
}
} | [
"private",
"function",
"pushMiddlewaresInDefinition",
"(",
"$",
"alias_namespace",
",",
"$",
"middlewares_directory",
",",
"&",
"$",
"default_definitions",
")",
"{",
"$",
"middleware_files",
"=",
"get_files",
"(",
"$",
"middlewares_directory",
")",
";",
"if",
"(",
... | Push middlewares in default definition
@param string $alias_namespace
@param string $middlewares_directory
@param array &$default_definitions
@return void | [
"Push",
"middlewares",
"in",
"default",
"definition"
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L645-L696 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.pushRequestsInDefinition | private function pushRequestsInDefinition($alias_namespace, $requests_directory, &$default_definitions)
{
$request_files = get_files($requests_directory);
if (!empty($request_files))
{
$requests = array_map(function($request) use($requests_directory) {
$new_request = str_replace("{$requests_directory}/", "", $request);
return basename(str_replace("/", "\\", $new_request), ".php");
}, $request_files);
$errors = [];
foreach ($requests as $request) {
if ($alias_namespace === "\\")
{
$request_definition = get_app_namespace() . "Requests\\{$request}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$request_sub_namespace = str_replace(app_path() . "/{$module_name}/Requests", "", $requests_directory);
$request_sub_namespace = str_replace("/", "\\", $request_sub_namespace);
$request_definition = "{$alias_namespace}Requests\\{$request}";
}
if (!array_key_exists("{$request_definition}", $default_definitions))
{
$default_definitions["{$request_definition}"] = function(ContainerInterface $c) use ($request_definition)
{
return new $request_definition($c->get('request'));
};
}
else
{
$errors[] = "{$request} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No request found in {$requests_directory} path.");
}
} | php | private function pushRequestsInDefinition($alias_namespace, $requests_directory, &$default_definitions)
{
$request_files = get_files($requests_directory);
if (!empty($request_files))
{
$requests = array_map(function($request) use($requests_directory) {
$new_request = str_replace("{$requests_directory}/", "", $request);
return basename(str_replace("/", "\\", $new_request), ".php");
}, $request_files);
$errors = [];
foreach ($requests as $request) {
if ($alias_namespace === "\\")
{
$request_definition = get_app_namespace() . "Requests\\{$request}";
}
else
{
$module_name = str_replace("App\\", "", $alias_namespace);
$request_sub_namespace = str_replace(app_path() . "/{$module_name}/Requests", "", $requests_directory);
$request_sub_namespace = str_replace("/", "\\", $request_sub_namespace);
$request_definition = "{$alias_namespace}Requests\\{$request}";
}
if (!array_key_exists("{$request_definition}", $default_definitions))
{
$default_definitions["{$request_definition}"] = function(ContainerInterface $c) use ($request_definition)
{
return new $request_definition($c->get('request'));
};
}
else
{
$errors[] = "{$request} is already exist inside of definitions.";
}
}
if (!empty($errors))
{
exit("Error: Please fix the ff. before run the application: <li>" . implode("</li><li>", $errors));
}
}
else
{
exit("Error: No request found in {$requests_directory} path.");
}
} | [
"private",
"function",
"pushRequestsInDefinition",
"(",
"$",
"alias_namespace",
",",
"$",
"requests_directory",
",",
"&",
"$",
"default_definitions",
")",
"{",
"$",
"request_files",
"=",
"get_files",
"(",
"$",
"requests_directory",
")",
";",
"if",
"(",
"!",
"emp... | Push requests in default definition
@param string $alias_namespace
@param string $requests_directory
@param array &$default_definitions
@return void | [
"Push",
"requests",
"in",
"default",
"definition"
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L706-L755 | train |
rodrigoiii/skeleton-core | src/classes/App.php | App.loadEnvironment | public static function loadEnvironment()
{
/**
* Application Environment
*/
$required_env = [
# application configuration
'APP_NAME', 'APP_ENV', 'APP_KEY',
# database configuration
'DB_HOSTNAME', 'DB_PORT', 'DB_USERNAME', 'DB_PASSWORD', 'DB_NAME',
# debugging
'DEBUG_ON', 'DEBUG_BAR_ON',
# application mode
'APP_MODE',
# flag whether use dist or not
'USE_DIST'
];
$is_own_server = count(glob($_SERVER['DOCUMENT_ROOT'] . "/.env")) === 0;
$root = $_SERVER['DOCUMENT_ROOT'] . ($is_own_server ? "/.." : "");
if (is_api_request())
{
// remove DEBUG_BAR_ON, USE_DIST on api request
unset($required_env[array_search("DEBUG_BAR_ON", $required_env)]);
unset($required_env[array_search("USE_DIST", $required_env)]);
}
$dotenv = new \Dotenv\Dotenv($root);
$dotenv->overload();
$dotenv->required($required_env);
} | php | public static function loadEnvironment()
{
/**
* Application Environment
*/
$required_env = [
# application configuration
'APP_NAME', 'APP_ENV', 'APP_KEY',
# database configuration
'DB_HOSTNAME', 'DB_PORT', 'DB_USERNAME', 'DB_PASSWORD', 'DB_NAME',
# debugging
'DEBUG_ON', 'DEBUG_BAR_ON',
# application mode
'APP_MODE',
# flag whether use dist or not
'USE_DIST'
];
$is_own_server = count(glob($_SERVER['DOCUMENT_ROOT'] . "/.env")) === 0;
$root = $_SERVER['DOCUMENT_ROOT'] . ($is_own_server ? "/.." : "");
if (is_api_request())
{
// remove DEBUG_BAR_ON, USE_DIST on api request
unset($required_env[array_search("DEBUG_BAR_ON", $required_env)]);
unset($required_env[array_search("USE_DIST", $required_env)]);
}
$dotenv = new \Dotenv\Dotenv($root);
$dotenv->overload();
$dotenv->required($required_env);
} | [
"public",
"static",
"function",
"loadEnvironment",
"(",
")",
"{",
"/**\n * Application Environment\n */",
"$",
"required_env",
"=",
"[",
"# application configuration",
"'APP_NAME'",
",",
"'APP_ENV'",
",",
"'APP_KEY'",
",",
"# database configuration",
"'DB_HOST... | Load the environment of the application.
@return void | [
"Load",
"the",
"environment",
"of",
"the",
"application",
"."
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/App.php#L762-L797 | train |
cmsgears/module-core | common/models/resources/ModelHierarchy.php | ModelHierarchy.findChild | public static function findChild( $parentId, $parentType, $childId ) {
return self::find()->where( 'parentId=:pid AND parentType=:type AND childId=:cid', [ ':pid' => $parentId, ':type' => $parentType, ':cid' => $childId ] )->one();
} | php | public static function findChild( $parentId, $parentType, $childId ) {
return self::find()->where( 'parentId=:pid AND parentType=:type AND childId=:cid', [ ':pid' => $parentId, ':type' => $parentType, ':cid' => $childId ] )->one();
} | [
"public",
"static",
"function",
"findChild",
"(",
"$",
"parentId",
",",
"$",
"parentType",
",",
"$",
"childId",
")",
"{",
"return",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"'parentId=:pid AND parentType=:type AND childId=:cid'",
",",
"[",
"':pid'",
... | Find and return the child using parent id, parent type and child id.
@param integer $parentId
@param string $parentType
@param integer $childId
@return ModelHierarchy | [
"Find",
"and",
"return",
"the",
"child",
"using",
"parent",
"id",
"parent",
"type",
"and",
"child",
"id",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/resources/ModelHierarchy.php#L148-L151 | train |
spiral/exceptions | src/Highlighter.php | Highlighter.highlightLines | public function highlightLines(string $source, int $line, int $around = 5): string
{
$lines = explode("\n", str_replace("\r\n", "\n", $this->highlight($source)));
$result = "";
foreach ($lines as $number => $code) {
$human = $number + 1;
if (!empty($around) && ($human < $line - $around || $human >= $line + $around + 1)) {
//Not included in a range
continue;
}
$result .= $this->r->line($human, mb_convert_encoding($code, 'utf-8'), $human === $line);
}
return $result;
} | php | public function highlightLines(string $source, int $line, int $around = 5): string
{
$lines = explode("\n", str_replace("\r\n", "\n", $this->highlight($source)));
$result = "";
foreach ($lines as $number => $code) {
$human = $number + 1;
if (!empty($around) && ($human < $line - $around || $human >= $line + $around + 1)) {
//Not included in a range
continue;
}
$result .= $this->r->line($human, mb_convert_encoding($code, 'utf-8'), $human === $line);
}
return $result;
} | [
"public",
"function",
"highlightLines",
"(",
"string",
"$",
"source",
",",
"int",
"$",
"line",
",",
"int",
"$",
"around",
"=",
"5",
")",
":",
"string",
"{",
"$",
"lines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"str_replace",
"(",
"\"\\r\\n\"",
",",
"\"\\... | Highlight PHP source and return N lines around target line.
@param string $source
@param int $line
@param int $around
@return string | [
"Highlight",
"PHP",
"source",
"and",
"return",
"N",
"lines",
"around",
"target",
"line",
"."
] | 9735a00b189ce61317cd49a9d6ec630f68cee381 | https://github.com/spiral/exceptions/blob/9735a00b189ce61317cd49a9d6ec630f68cee381/src/Highlighter.php#L36-L52 | train |
spiral/exceptions | src/Highlighter.php | Highlighter.highlight | public function highlight(string $source): string
{
$result = '';
$previous = [];
foreach ($this->getTokens($source) as $token) {
$result .= $this->r->token($token, $previous);
$previous = $token;
}
return $result;
} | php | public function highlight(string $source): string
{
$result = '';
$previous = [];
foreach ($this->getTokens($source) as $token) {
$result .= $this->r->token($token, $previous);
$previous = $token;
}
return $result;
} | [
"public",
"function",
"highlight",
"(",
"string",
"$",
"source",
")",
":",
"string",
"{",
"$",
"result",
"=",
"''",
";",
"$",
"previous",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"getTokens",
"(",
"$",
"source",
")",
"as",
"$",
"token... | Returns highlighted PHP source.
@param string $source
@return string | [
"Returns",
"highlighted",
"PHP",
"source",
"."
] | 9735a00b189ce61317cd49a9d6ec630f68cee381 | https://github.com/spiral/exceptions/blob/9735a00b189ce61317cd49a9d6ec630f68cee381/src/Highlighter.php#L60-L70 | train |
spiral/exceptions | src/Highlighter.php | Highlighter.getTokens | private function getTokens(string $source): array
{
$tokens = [];
$line = 0;
foreach (token_get_all($source) as $token) {
if (isset($token[2])) {
$line = $token[2];
}
if (!is_array($token)) {
$token = [$token, $token, $line];
}
$tokens[] = $token;
}
return $tokens;
} | php | private function getTokens(string $source): array
{
$tokens = [];
$line = 0;
foreach (token_get_all($source) as $token) {
if (isset($token[2])) {
$line = $token[2];
}
if (!is_array($token)) {
$token = [$token, $token, $line];
}
$tokens[] = $token;
}
return $tokens;
} | [
"private",
"function",
"getTokens",
"(",
"string",
"$",
"source",
")",
":",
"array",
"{",
"$",
"tokens",
"=",
"[",
"]",
";",
"$",
"line",
"=",
"0",
";",
"foreach",
"(",
"token_get_all",
"(",
"$",
"source",
")",
"as",
"$",
"token",
")",
"{",
"if",
... | Get all tokens from PHP source normalized to always include line number.
@param string $source
@return array | [
"Get",
"all",
"tokens",
"from",
"PHP",
"source",
"normalized",
"to",
"always",
"include",
"line",
"number",
"."
] | 9735a00b189ce61317cd49a9d6ec630f68cee381 | https://github.com/spiral/exceptions/blob/9735a00b189ce61317cd49a9d6ec630f68cee381/src/Highlighter.php#L78-L96 | train |
cmsgears/module-core | common/models/entities/ObjectData.php | ObjectData.findByType | public static function findByType( $type, $config = [] ) {
$ignoreSite = isset( $config[ 'ignoreSite' ] ) ? $config[ 'ignoreSite' ] : false;
if( static::isMultiSite() && !$ignoreSite ) {
$siteId = isset( $config[ 'siteId' ] ) ? $config[ 'siteId' ] : Yii::$app->core->siteId;
return static::find()->where( 'type=:type AND siteId=:siteId', [ ':type' => $type, ':siteId' => $siteId ] )->orderBy( [ 'order' => SORT_ASC ] )->all();
}
else {
return static::find()->where( 'type=:type', [ ':type' => $type ] )->orderBy( [ 'order' => SORT_ASC ] )->all();
}
} | php | public static function findByType( $type, $config = [] ) {
$ignoreSite = isset( $config[ 'ignoreSite' ] ) ? $config[ 'ignoreSite' ] : false;
if( static::isMultiSite() && !$ignoreSite ) {
$siteId = isset( $config[ 'siteId' ] ) ? $config[ 'siteId' ] : Yii::$app->core->siteId;
return static::find()->where( 'type=:type AND siteId=:siteId', [ ':type' => $type, ':siteId' => $siteId ] )->orderBy( [ 'order' => SORT_ASC ] )->all();
}
else {
return static::find()->where( 'type=:type', [ ':type' => $type ] )->orderBy( [ 'order' => SORT_ASC ] )->all();
}
} | [
"public",
"static",
"function",
"findByType",
"(",
"$",
"type",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"ignoreSite",
"=",
"isset",
"(",
"$",
"config",
"[",
"'ignoreSite'",
"]",
")",
"?",
"$",
"config",
"[",
"'ignoreSite'",
"]",
":",
"false... | Find and returns the objects with given type.
@param string $type
@param array $config
@return ObjectData[] | [
"Find",
"and",
"returns",
"the",
"objects",
"with",
"given",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/ObjectData.php#L420-L434 | train |
cmsgears/module-core | common/models/entities/City.php | City.findUniqueByZone | public static function findUniqueByZone( $name, $countryId, $provinceId, $zone ) {
return self::find()->where( 'name=:name AND countryId=:cid AND provinceId=:pid AND zone=:zone', [ ':name' => $name, ':cid' => $countryId, ':pid' => $provinceId, ':zone' => $zone ] )->one();
} | php | public static function findUniqueByZone( $name, $countryId, $provinceId, $zone ) {
return self::find()->where( 'name=:name AND countryId=:cid AND provinceId=:pid AND zone=:zone', [ ':name' => $name, ':cid' => $countryId, ':pid' => $provinceId, ':zone' => $zone ] )->one();
} | [
"public",
"static",
"function",
"findUniqueByZone",
"(",
"$",
"name",
",",
"$",
"countryId",
",",
"$",
"provinceId",
",",
"$",
"zone",
")",
"{",
"return",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"'name=:name AND countryId=:cid AND provinceId=:pid AND... | Try to find out a city having unique name within zone.
@param string $name
@param integer $countryId
@param integer $provinceId
@param string $zone
@return City by name, country id, province id and zone | [
"Try",
"to",
"find",
"out",
"a",
"city",
"having",
"unique",
"name",
"within",
"zone",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/City.php#L338-L341 | train |
cmsgears/module-core | common/models/entities/City.php | City.isUniqueExist | public static function isUniqueExist( $name, $countryId, $provinceId ) {
$city = self::findUnique( $name, $countryId, $provinceId );
return isset( $city );
} | php | public static function isUniqueExist( $name, $countryId, $provinceId ) {
$city = self::findUnique( $name, $countryId, $provinceId );
return isset( $city );
} | [
"public",
"static",
"function",
"isUniqueExist",
"(",
"$",
"name",
",",
"$",
"countryId",
",",
"$",
"provinceId",
")",
"{",
"$",
"city",
"=",
"self",
"::",
"findUnique",
"(",
"$",
"name",
",",
"$",
"countryId",
",",
"$",
"provinceId",
")",
";",
"return... | Check whether a city already exist using given name within province.
@param string $name
@param integer $countryId
@param integer $provinceId
@return boolean | [
"Check",
"whether",
"a",
"city",
"already",
"exist",
"using",
"given",
"name",
"within",
"province",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/City.php#L351-L356 | train |
cmsgears/module-core | common/models/entities/City.php | City.isUniqueExistByZone | public static function isUniqueExistByZone( $name, $countryId, $provinceId, $zone ) {
$city = self::findUniqueByZone( $name, $countryId, $provinceId, $zone );
return isset( $city );
} | php | public static function isUniqueExistByZone( $name, $countryId, $provinceId, $zone ) {
$city = self::findUniqueByZone( $name, $countryId, $provinceId, $zone );
return isset( $city );
} | [
"public",
"static",
"function",
"isUniqueExistByZone",
"(",
"$",
"name",
",",
"$",
"countryId",
",",
"$",
"provinceId",
",",
"$",
"zone",
")",
"{",
"$",
"city",
"=",
"self",
"::",
"findUniqueByZone",
"(",
"$",
"name",
",",
"$",
"countryId",
",",
"$",
"... | Check whether a city already exist using given name within zone.
@param string $name
@param integer $countryId
@param integer $provinceId
@return boolean | [
"Check",
"whether",
"a",
"city",
"already",
"exist",
"using",
"given",
"name",
"within",
"zone",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/City.php#L366-L371 | train |
geekwright/RegDom | src/RegisteredDomain.php | RegisteredDomain.normalizeHost | protected function normalizeHost($url)
{
$host = (false!==strpos($url, '/')) ? parse_url($url, PHP_URL_HOST) : $url;
$parts = explode('.', $host);
$utf8Host = '';
foreach ($parts as $part) {
$utf8Host = $utf8Host . (($utf8Host === '') ? '' : '.') . $this->convertPunycode($part);
}
return mb_strtolower($utf8Host);
} | php | protected function normalizeHost($url)
{
$host = (false!==strpos($url, '/')) ? parse_url($url, PHP_URL_HOST) : $url;
$parts = explode('.', $host);
$utf8Host = '';
foreach ($parts as $part) {
$utf8Host = $utf8Host . (($utf8Host === '') ? '' : '.') . $this->convertPunycode($part);
}
return mb_strtolower($utf8Host);
} | [
"protected",
"function",
"normalizeHost",
"(",
"$",
"url",
")",
"{",
"$",
"host",
"=",
"(",
"false",
"!==",
"strpos",
"(",
"$",
"url",
",",
"'/'",
")",
")",
"?",
"parse_url",
"(",
"$",
"url",
",",
"PHP_URL_HOST",
")",
":",
"$",
"url",
";",
"$",
"... | Given a URL or bare host name, return a normalized host name, converting punycode to UTF-8
and converting to lower case
@param string $url URL or host name
@return string | [
"Given",
"a",
"URL",
"or",
"bare",
"host",
"name",
"return",
"a",
"normalized",
"host",
"name",
"converting",
"punycode",
"to",
"UTF",
"-",
"8",
"and",
"converting",
"to",
"lower",
"case"
] | f51eb343c526913f699d84c47596195a8a63ce09 | https://github.com/geekwright/RegDom/blob/f51eb343c526913f699d84c47596195a8a63ce09/src/RegisteredDomain.php#L41-L51 | train |
geekwright/RegDom | src/RegisteredDomain.php | RegisteredDomain.convertPunycode | protected function convertPunycode($part)
{
if (strpos($part, 'xn--')===0) {
if (function_exists('idn_to_utf8')) {
if (defined('INTL_IDNA_VARIANT_UTS46')) { // PHP 7.2
return idn_to_utf8($part, 0, INTL_IDNA_VARIANT_UTS46);
}
return idn_to_utf8($part);
}
return $this->decodePunycode($part);
}
return $part;
} | php | protected function convertPunycode($part)
{
if (strpos($part, 'xn--')===0) {
if (function_exists('idn_to_utf8')) {
if (defined('INTL_IDNA_VARIANT_UTS46')) { // PHP 7.2
return idn_to_utf8($part, 0, INTL_IDNA_VARIANT_UTS46);
}
return idn_to_utf8($part);
}
return $this->decodePunycode($part);
}
return $part;
} | [
"protected",
"function",
"convertPunycode",
"(",
"$",
"part",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"part",
",",
"'xn--'",
")",
"===",
"0",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'idn_to_utf8'",
")",
")",
"{",
"if",
"(",
"defined",
"(",
"'I... | Convert a punycode string to UTF-8 if needed
@param string $part host component
@return string host component as UTF-8 | [
"Convert",
"a",
"punycode",
"string",
"to",
"UTF",
"-",
"8",
"if",
"needed"
] | f51eb343c526913f699d84c47596195a8a63ce09 | https://github.com/geekwright/RegDom/blob/f51eb343c526913f699d84c47596195a8a63ce09/src/RegisteredDomain.php#L60-L72 | train |
geekwright/RegDom | src/RegisteredDomain.php | RegisteredDomain.getRegisteredDomain | public function getRegisteredDomain($host)
{
$this->tree = $this->psl->getTree();
$signingDomain = $this->normalizeHost($host);
$signingDomainParts = explode('.', $signingDomain);
$result = $this->findRegisteredDomain($signingDomainParts, $this->tree);
if (empty($result)) {
// this is an invalid domain name
return null;
}
// assure there is at least 1 TLD in the stripped signing domain
if (!strpos($result, '.')) {
$cnt = count($signingDomainParts);
if ($cnt == 1 || $signingDomainParts[$cnt-2] == '') {
return null;
}
return $signingDomainParts[$cnt-2] . '.' . $signingDomainParts[$cnt-1];
}
return $result;
} | php | public function getRegisteredDomain($host)
{
$this->tree = $this->psl->getTree();
$signingDomain = $this->normalizeHost($host);
$signingDomainParts = explode('.', $signingDomain);
$result = $this->findRegisteredDomain($signingDomainParts, $this->tree);
if (empty($result)) {
// this is an invalid domain name
return null;
}
// assure there is at least 1 TLD in the stripped signing domain
if (!strpos($result, '.')) {
$cnt = count($signingDomainParts);
if ($cnt == 1 || $signingDomainParts[$cnt-2] == '') {
return null;
}
return $signingDomainParts[$cnt-2] . '.' . $signingDomainParts[$cnt-1];
}
return $result;
} | [
"public",
"function",
"getRegisteredDomain",
"(",
"$",
"host",
")",
"{",
"$",
"this",
"->",
"tree",
"=",
"$",
"this",
"->",
"psl",
"->",
"getTree",
"(",
")",
";",
"$",
"signingDomain",
"=",
"$",
"this",
"->",
"normalizeHost",
"(",
"$",
"host",
")",
"... | Determine the registered domain portion of the supplied host string
@param string $host a host name or URL containing a host name
@return string|null shortest registrable domain portion of the supplied host or null if invalid | [
"Determine",
"the",
"registered",
"domain",
"portion",
"of",
"the",
"supplied",
"host",
"string"
] | f51eb343c526913f699d84c47596195a8a63ce09 | https://github.com/geekwright/RegDom/blob/f51eb343c526913f699d84c47596195a8a63ce09/src/RegisteredDomain.php#L168-L191 | train |
geekwright/RegDom | src/RegisteredDomain.php | RegisteredDomain.findRegisteredDomain | protected function findRegisteredDomain($remainingSigningDomainParts, &$treeNode)
{
$sub = array_pop($remainingSigningDomainParts);
$result = null;
if (isset($treeNode['!'])) {
return '';
} elseif (is_array($treeNode) && array_key_exists($sub, $treeNode)) {
$result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode[$sub]);
} elseif (is_array($treeNode) && array_key_exists('*', $treeNode)) {
$result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode['*']);
} else {
return $sub;
}
if ($result === '') {
return $sub;
} elseif (strlen($result)>0) {
return $result . '.' . $sub;
}
return null;
} | php | protected function findRegisteredDomain($remainingSigningDomainParts, &$treeNode)
{
$sub = array_pop($remainingSigningDomainParts);
$result = null;
if (isset($treeNode['!'])) {
return '';
} elseif (is_array($treeNode) && array_key_exists($sub, $treeNode)) {
$result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode[$sub]);
} elseif (is_array($treeNode) && array_key_exists('*', $treeNode)) {
$result = $this->findRegisteredDomain($remainingSigningDomainParts, $treeNode['*']);
} else {
return $sub;
}
if ($result === '') {
return $sub;
} elseif (strlen($result)>0) {
return $result . '.' . $sub;
}
return null;
} | [
"protected",
"function",
"findRegisteredDomain",
"(",
"$",
"remainingSigningDomainParts",
",",
"&",
"$",
"treeNode",
")",
"{",
"$",
"sub",
"=",
"array_pop",
"(",
"$",
"remainingSigningDomainParts",
")",
";",
"$",
"result",
"=",
"null",
";",
"if",
"(",
"isset",... | Recursive helper method to query the PSL tree
@param string[] $remainingSigningDomainParts parts of domain being queried
@param string[] $treeNode subset of tree array by reference
@return null|string | [
"Recursive",
"helper",
"method",
"to",
"query",
"the",
"PSL",
"tree"
] | f51eb343c526913f699d84c47596195a8a63ce09 | https://github.com/geekwright/RegDom/blob/f51eb343c526913f699d84c47596195a8a63ce09/src/RegisteredDomain.php#L201-L222 | train |
rodrigoiii/skeleton-core | src/classes/Console/Commands/MakeCommandCommand.php | MakeCommandCommand.makeTemplate | private function makeTemplate($command)
{
$file = __DIR__ . "/../templates/command.php.dist";
try {
if (!file_exists($file)) throw new \Exception("{$file} file is not exist.", 1);
$template = strtr(file_get_contents($file), [
'{{namespace}}' => get_app_namespace(),
'{{command}}' => $command,
'{{command_name}}' => strtolower($command)
]);
if (!file_exists(app_path("Commands")))
{
mkdir(app_path("Commands"), 0755, true);
}
$file_path = app_path("Commands/{$command}.php");
$file = fopen($file_path, "w");
fwrite($file, $template);
fclose($file);
return file_exists($file_path);
} catch (Exception $e) {
$output->writeln($e->getMessage());
}
return false;
} | php | private function makeTemplate($command)
{
$file = __DIR__ . "/../templates/command.php.dist";
try {
if (!file_exists($file)) throw new \Exception("{$file} file is not exist.", 1);
$template = strtr(file_get_contents($file), [
'{{namespace}}' => get_app_namespace(),
'{{command}}' => $command,
'{{command_name}}' => strtolower($command)
]);
if (!file_exists(app_path("Commands")))
{
mkdir(app_path("Commands"), 0755, true);
}
$file_path = app_path("Commands/{$command}.php");
$file = fopen($file_path, "w");
fwrite($file, $template);
fclose($file);
return file_exists($file_path);
} catch (Exception $e) {
$output->writeln($e->getMessage());
}
return false;
} | [
"private",
"function",
"makeTemplate",
"(",
"$",
"command",
")",
"{",
"$",
"file",
"=",
"__DIR__",
".",
"\"/../templates/command.php.dist\"",
";",
"try",
"{",
"if",
"(",
"!",
"file_exists",
"(",
"$",
"file",
")",
")",
"throw",
"new",
"\\",
"Exception",
"("... | Create the command template.
@depends handle
@param string $command
@return boolean | [
"Create",
"the",
"command",
"template",
"."
] | 5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0 | https://github.com/rodrigoiii/skeleton-core/blob/5dab0637b9cd0f55a64b1f5926d7ba6bb3f93df0/src/classes/Console/Commands/MakeCommandCommand.php#L63-L94 | train |
cmsgears/module-core | common/models/hierarchy/HierarchicalModel.php | HierarchicalModel.validateParentChain | public function validateParentChain( $attribute, $params ) {
if( !$this->hasErrors() ) {
if( isset( $this->parentId ) && $this->parentId > 0 && $this->parentId == $this->id ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_PARENT_CHAIN ) );
}
}
} | php | public function validateParentChain( $attribute, $params ) {
if( !$this->hasErrors() ) {
if( isset( $this->parentId ) && $this->parentId > 0 && $this->parentId == $this->id ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_PARENT_CHAIN ) );
}
}
} | [
"public",
"function",
"validateParentChain",
"(",
"$",
"attribute",
",",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasErrors",
"(",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"parentId",
")",
"&&",
"$",
"this",
"-... | Validates parent to ensure that the model cannot be parent of itself.
@param type $attribute
@param type $params
@return void | [
"Validates",
"parent",
"to",
"ensure",
"that",
"the",
"model",
"cannot",
"be",
"parent",
"of",
"itself",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/hierarchy/HierarchicalModel.php#L67-L76 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.getRandom | public function getRandom( $config = [] ) {
$offset = $config[ 'offset' ] ?? 0;
$limit = $config[ 'limit' ] ?? 10;
$conditions = $config[ 'conditions' ] ?? null;
// model class
$modelClass = static::$modelClass;
// query generation
$results = [];
$query = $modelClass::find();
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
// Randomise -----------
$query = $query->orderBy( 'RAND()' );
// Offset --------------
if( $offset > 0 ) {
$query->offset( $offset );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
$results = $query->all();
return $results;
} | php | public function getRandom( $config = [] ) {
$offset = $config[ 'offset' ] ?? 0;
$limit = $config[ 'limit' ] ?? 10;
$conditions = $config[ 'conditions' ] ?? null;
// model class
$modelClass = static::$modelClass;
// query generation
$results = [];
$query = $modelClass::find();
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
// Randomise -----------
$query = $query->orderBy( 'RAND()' );
// Offset --------------
if( $offset > 0 ) {
$query->offset( $offset );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
$results = $query->all();
return $results;
} | [
"public",
"function",
"getRandom",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"offset",
"=",
"$",
"config",
"[",
"'offset'",
"]",
"??",
"0",
";",
"$",
"limit",
"=",
"$",
"config",
"[",
"'limit'",
"]",
"??",
"10",
";",
"$",
"conditions",
"=... | A simple method to get random ids.
It's not efficient for tables having large number of rows.
TODO: We can make this method efficient by using random offset and limit instead of going for full table scan.
Avoid using count() to get total rows. Use Stats Table to get estimated count.
Notes: Using offset is much slower as compared to start index with limit. | [
"A",
"simple",
"method",
"to",
"get",
"random",
"ids",
".",
"It",
"s",
"not",
"efficient",
"for",
"tables",
"having",
"large",
"number",
"of",
"rows",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L220-L270 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.delete | public function delete( $model, $config = [] ) {
$hard = $config[ 'hard' ] ?? true;
$notify = $config[ 'notify' ] ?? true;
if( isset( $model ) ) {
// Permanent Delete
if( $hard ) {
return $model->delete();
}
// Soft Delete - Useful for models using status to mark model as deleted, but keep for historic purpose.
else {
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
// Approval Trait
return $this->softDeleteNotify( $model, $notify, $config );
}
else {
return $this->softDelete( $model );
}
}
}
return false;
} | php | public function delete( $model, $config = [] ) {
$hard = $config[ 'hard' ] ?? true;
$notify = $config[ 'notify' ] ?? true;
if( isset( $model ) ) {
// Permanent Delete
if( $hard ) {
return $model->delete();
}
// Soft Delete - Useful for models using status to mark model as deleted, but keep for historic purpose.
else {
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
// Approval Trait
return $this->softDeleteNotify( $model, $notify, $config );
}
else {
return $this->softDelete( $model );
}
}
}
return false;
} | [
"public",
"function",
"delete",
"(",
"$",
"model",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"hard",
"=",
"$",
"config",
"[",
"'hard'",
"]",
"??",
"true",
";",
"$",
"notify",
"=",
"$",
"config",
"[",
"'notify'",
"]",
"??",
"true",
";",
... | Delete the model by deleting related resources and mapper.
@param type $model
@param type $config
@return boolean | [
"Delete",
"the",
"model",
"by",
"deleting",
"related",
"resources",
"and",
"mapper",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L497-L527 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.applyBulkByTargetId | public function applyBulkByTargetId( $column, $action, $target, $config = [] ) {
foreach ( $target as $id ) {
$model = $this->getById( $id );
// Bulk Conditions
if( isset( $model ) ) {
$this->applyBulk( $model, $column, $action, $target, $config );
}
}
} | php | public function applyBulkByTargetId( $column, $action, $target, $config = [] ) {
foreach ( $target as $id ) {
$model = $this->getById( $id );
// Bulk Conditions
if( isset( $model ) ) {
$this->applyBulk( $model, $column, $action, $target, $config );
}
}
} | [
"public",
"function",
"applyBulkByTargetId",
"(",
"$",
"column",
",",
"$",
"action",
",",
"$",
"target",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"foreach",
"(",
"$",
"target",
"as",
"$",
"id",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
... | Default method for bulk actions.
@param string $column
@param string $action
@param string $target | [
"Default",
"method",
"for",
"bulk",
"actions",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L571-L583 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.notifyAdmin | public function notifyAdmin( $model, $config = [] ) {
$config[ 'admin' ] = true;
$config[ 'direct' ] = false;
$this->sendNotification( $model, $config );
} | php | public function notifyAdmin( $model, $config = [] ) {
$config[ 'admin' ] = true;
$config[ 'direct' ] = false;
$this->sendNotification( $model, $config );
} | [
"public",
"function",
"notifyAdmin",
"(",
"$",
"model",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"config",
"[",
"'admin'",
"]",
"=",
"true",
";",
"$",
"config",
"[",
"'direct'",
"]",
"=",
"false",
";",
"$",
"this",
"->",
"sendNotification",
... | Trigger Admin Notifications. The template settings will override.
@param \cmsgears\core\common\models\base\ActiveRecord $model
@param array $config - key elements are template(template slug), data(template data),
title(notification title), createdBy(creator id), parentId(parent model id), parentType,
link, admin(flag), adminLink and users(to notify) | [
"Trigger",
"Admin",
"Notifications",
".",
"The",
"template",
"settings",
"will",
"override",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L601-L607 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.sendNotification | protected function sendNotification( $model, $config = [] ) {
$templateData = $config[ 'data' ] ?? [];
$templateConfig = [];
$templateData = ArrayHelper::merge( [ 'model' => $model, 'service' => $this ], $templateData );
$templateConfig[ 'createdBy' ] = $config[ 'createdBy' ] ?? null;
$templateConfig[ 'parentId' ] = $model->id;
$templateConfig[ 'parentType' ] = self::$parentType;
$templateConfig[ 'link' ] = $config[ 'link' ] ?? null;
$templateConfig[ 'adminLink' ] = $config[ 'adminLink' ] ?? null;
$templateConfig[ 'title' ] = $config[ 'title' ] ?? $model->name ?? null;
$templateConfig[ 'users' ] = $config[ 'users' ] ?? [];
return Yii::$app->eventManager->triggerNotification( $config[ 'template' ], $templateData, $templateConfig );
} | php | protected function sendNotification( $model, $config = [] ) {
$templateData = $config[ 'data' ] ?? [];
$templateConfig = [];
$templateData = ArrayHelper::merge( [ 'model' => $model, 'service' => $this ], $templateData );
$templateConfig[ 'createdBy' ] = $config[ 'createdBy' ] ?? null;
$templateConfig[ 'parentId' ] = $model->id;
$templateConfig[ 'parentType' ] = self::$parentType;
$templateConfig[ 'link' ] = $config[ 'link' ] ?? null;
$templateConfig[ 'adminLink' ] = $config[ 'adminLink' ] ?? null;
$templateConfig[ 'title' ] = $config[ 'title' ] ?? $model->name ?? null;
$templateConfig[ 'users' ] = $config[ 'users' ] ?? [];
return Yii::$app->eventManager->triggerNotification( $config[ 'template' ], $templateData, $templateConfig );
} | [
"protected",
"function",
"sendNotification",
"(",
"$",
"model",
",",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"templateData",
"=",
"$",
"config",
"[",
"'data'",
"]",
"??",
"[",
"]",
";",
"$",
"templateConfig",
"=",
"[",
"]",
";",
"$",
"templateDa... | Prepare the notification data and configuration and trigger it using the active
event manager.
@param \cmsgears\core\common\models\base\ActiveRecord $model
@param array $config
@return type | [
"Prepare",
"the",
"notification",
"data",
"and",
"configuration",
"and",
"trigger",
"it",
"using",
"the",
"active",
"event",
"manager",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L651-L668 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.findPage | public static function findPage( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$sort = isset( $config[ 'sort' ] ) ? $config[ 'sort' ] : false;
// Default sort
if( !$sort ) {
$defaultSort = isset( $config[ 'defaultSort' ] ) ? $config[ 'defaultSort' ] : [ 'id' => SORT_DESC ];
$sort = new Sort([
'attributes' => [
'id' => [
'asc' => [ "$modelTable.id" => SORT_ASC ],
'desc' => [ "$modelTable.id" => SORT_DESC ],
'default' => SORT_DESC,
'label' => 'Id'
]
],
'defaultOrder' => $defaultSort
]);
$config[ 'sort' ] = $sort;
}
// Default conditions
$config[ 'conditions' ] = $config[ 'conditions' ] ?? [];
// Default query
if( !isset( $config[ 'query' ] ) ) {
$modelClass = static::$modelClass;
$hasOne = isset( $config[ 'hasOne' ] ) ? $config[ 'hasOne' ] : false;
if( $hasOne ) {
$config[ 'query' ] = $modelClass::queryWithHasOne();
}
}
// Filters
$config = static::applyPublicFilters( $config );
$config = static::applySiteFilters( $config );
// Default search column
if( !isset( $config[ 'search-col' ] ) ) {
$config[ 'search-col' ][] = "$modelTable.id";
}
return static::findDataProvider( $config );
} | php | public static function findPage( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$sort = isset( $config[ 'sort' ] ) ? $config[ 'sort' ] : false;
// Default sort
if( !$sort ) {
$defaultSort = isset( $config[ 'defaultSort' ] ) ? $config[ 'defaultSort' ] : [ 'id' => SORT_DESC ];
$sort = new Sort([
'attributes' => [
'id' => [
'asc' => [ "$modelTable.id" => SORT_ASC ],
'desc' => [ "$modelTable.id" => SORT_DESC ],
'default' => SORT_DESC,
'label' => 'Id'
]
],
'defaultOrder' => $defaultSort
]);
$config[ 'sort' ] = $sort;
}
// Default conditions
$config[ 'conditions' ] = $config[ 'conditions' ] ?? [];
// Default query
if( !isset( $config[ 'query' ] ) ) {
$modelClass = static::$modelClass;
$hasOne = isset( $config[ 'hasOne' ] ) ? $config[ 'hasOne' ] : false;
if( $hasOne ) {
$config[ 'query' ] = $modelClass::queryWithHasOne();
}
}
// Filters
$config = static::applyPublicFilters( $config );
$config = static::applySiteFilters( $config );
// Default search column
if( !isset( $config[ 'search-col' ] ) ) {
$config[ 'search-col' ][] = "$modelTable.id";
}
return static::findDataProvider( $config );
} | [
"public",
"static",
"function",
"findPage",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$",
"modelTable",
"=",
"$",
"modelClass",
"::",
"tableName",
"(",
")",
";",
"$",
"sort",
"=",
"i... | The method findPage provide data provider after generating appropriate query.
It uses find or queryWithHasOne as default method to generate base query. | [
"The",
"method",
"findPage",
"provide",
"data",
"provider",
"after",
"generating",
"appropriate",
"query",
".",
"It",
"uses",
"find",
"or",
"queryWithHasOne",
"as",
"default",
"method",
"to",
"generate",
"base",
"query",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L991-L1045 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.findPageForSearch | public static function findPageForSearch( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$parentType = $config[ 'parentType' ] ?? static::$parentType;
// Search in
$searchModel = $config[ 'searchModel' ] ?? true; // Search in model name
$searchCategory = $config[ 'searchCategory' ] ?? false; // Search in category name
$searchTag = $config[ 'searchTag' ] ?? false; // Search in tag name
// DB Tables
$mcategoryTable = CoreTables::TABLE_MODEL_CATEGORY;
$categoryTable = CoreTables::TABLE_CATEGORY;
$mtagTable = CoreTables::TABLE_MODEL_TAG;
$tagTable = CoreTables::TABLE_TAG;
// Sort
$sortParam = Yii::$app->request->get( 'sort' );
$sortParam = preg_replace( '/-/', '', $sortParam );
// Keywords
$searchParam = isset( $config[ 'search-param' ] ) ? $config[ 'search-param' ] : 'keywords';
$keywords = Yii::$app->request->getQueryParam( $searchParam );
// Search Query
$query = $config[ 'query' ] ?? $modelClass::find();
$hasOne = $config[ 'hasOne' ] ?? false;
// Use model joins
if( $hasOne ) {
$query = $modelClass::queryWithHasOne();
}
// Tag
if( $searchTag || isset( $config[ 'tag' ] ) || $sortParam === 'tag' ) {
$query->leftJoin( $mtagTable, "$modelTable.id=$mtagTable.parentId AND $mtagTable.parentType='$parentType' AND $mtagTable.active=TRUE" )
->leftJoin( $tagTable, "$mtagTable.modelId=$tagTable.id" );
}
if( isset( $config[ 'tag' ] ) ) {
$query->andWhere( "$tagTable.id=" . $config[ 'tag' ]->id );
}
// Category
if( $searchCategory || isset( $config[ 'category' ] ) || $sortParam === 'category' ) {
$query->leftJoin( $mcategoryTable, "$modelTable.id=$mcategoryTable.parentId AND $mcategoryTable.parentType='$parentType' AND $mcategoryTable.active=TRUE" )
->leftJoin( $categoryTable, "$mcategoryTable.modelId=$categoryTable.id" );
}
if( isset( $config[ 'category' ] ) ) {
$query->andWhere( "$categoryTable.id=" . $config[ 'category' ]->id );
}
// Search
if( isset( $keywords ) ) {
if( $searchModel ) {
$config[ 'search-col' ][] = "$modelTable.name";
}
if( $searchCategory ) {
$config[ 'search-col' ][] = "$categoryTable.name";
}
if( $searchTag ) {
$config[ 'search-col' ][] = "$tagTable.name";
}
}
// Group by model id
$query->groupBy( "$modelTable.id" );
$config[ 'query' ] = $query;
return static::findPage( $config );
} | php | public static function findPageForSearch( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
$parentType = $config[ 'parentType' ] ?? static::$parentType;
// Search in
$searchModel = $config[ 'searchModel' ] ?? true; // Search in model name
$searchCategory = $config[ 'searchCategory' ] ?? false; // Search in category name
$searchTag = $config[ 'searchTag' ] ?? false; // Search in tag name
// DB Tables
$mcategoryTable = CoreTables::TABLE_MODEL_CATEGORY;
$categoryTable = CoreTables::TABLE_CATEGORY;
$mtagTable = CoreTables::TABLE_MODEL_TAG;
$tagTable = CoreTables::TABLE_TAG;
// Sort
$sortParam = Yii::$app->request->get( 'sort' );
$sortParam = preg_replace( '/-/', '', $sortParam );
// Keywords
$searchParam = isset( $config[ 'search-param' ] ) ? $config[ 'search-param' ] : 'keywords';
$keywords = Yii::$app->request->getQueryParam( $searchParam );
// Search Query
$query = $config[ 'query' ] ?? $modelClass::find();
$hasOne = $config[ 'hasOne' ] ?? false;
// Use model joins
if( $hasOne ) {
$query = $modelClass::queryWithHasOne();
}
// Tag
if( $searchTag || isset( $config[ 'tag' ] ) || $sortParam === 'tag' ) {
$query->leftJoin( $mtagTable, "$modelTable.id=$mtagTable.parentId AND $mtagTable.parentType='$parentType' AND $mtagTable.active=TRUE" )
->leftJoin( $tagTable, "$mtagTable.modelId=$tagTable.id" );
}
if( isset( $config[ 'tag' ] ) ) {
$query->andWhere( "$tagTable.id=" . $config[ 'tag' ]->id );
}
// Category
if( $searchCategory || isset( $config[ 'category' ] ) || $sortParam === 'category' ) {
$query->leftJoin( $mcategoryTable, "$modelTable.id=$mcategoryTable.parentId AND $mcategoryTable.parentType='$parentType' AND $mcategoryTable.active=TRUE" )
->leftJoin( $categoryTable, "$mcategoryTable.modelId=$categoryTable.id" );
}
if( isset( $config[ 'category' ] ) ) {
$query->andWhere( "$categoryTable.id=" . $config[ 'category' ]->id );
}
// Search
if( isset( $keywords ) ) {
if( $searchModel ) {
$config[ 'search-col' ][] = "$modelTable.name";
}
if( $searchCategory ) {
$config[ 'search-col' ][] = "$categoryTable.name";
}
if( $searchTag ) {
$config[ 'search-col' ][] = "$tagTable.name";
}
}
// Group by model id
$query->groupBy( "$modelTable.id" );
$config[ 'query' ] = $query;
return static::findPage( $config );
} | [
"public",
"static",
"function",
"findPageForSearch",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$",
"modelTable",
"=",
"$",
"modelClass",
"::",
"tableName",
"(",
")",
";",
"$",
"parentTyp... | Generate search query using tag and category tables. The search will be done in model, category and tag names. | [
"Generate",
"search",
"query",
"using",
"tag",
"and",
"category",
"tables",
".",
"The",
"search",
"will",
"be",
"done",
"in",
"model",
"category",
"and",
"tag",
"names",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1050-L1135 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.searchModels | public static function searchModels( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// Filters
$config = static::applyPublicFilters( $config );
$config = static::applySiteFilters( $config );
// Generate Query
$query = $config[ 'query' ] ?? $modelClass::find();
$offset = $config[ 'offset' ] ?? 0;
$limit = $config[ 'limit' ] ?? self::PAGE_LIMIT;
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$sort = $config[ 'sort' ] ?? [ 'id' => SORT_DESC ]; // Show latest first
$public = $config[ 'public' ] ?? false;
// Result Columns
$columns = $config[ 'columns' ] ?? [];
// Array Result
$array = $config[ 'array' ] ?? false;
// Selective columns ---
if( count( $columns ) > 0 ) {
$query->select( $columns );
}
// Conditions ----------
if( isset( $conditions ) ) {
foreach( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach( $filters as $filter ) {
$query->andFilterWhere( $filter );
}
}
// Offset --------------
if( $offset > 0 ) {
$query->offset( $offset );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
// Sort -----------------
if( count( $sort ) > 0 ) {
$query->orderBy( $sort );
}
// Print to Debug -------
if( isset( $config[ 'pquery' ] ) && $config[ 'pquery' ] ) {
$command = $query->createCommand();
var_dump( $command );
}
// Models ---------------
if( $array ) {
$models = $query->asArray( $array )->all();
}
else {
$models = $query->all();
}
return $models;
} | php | public static function searchModels( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// Filters
$config = static::applyPublicFilters( $config );
$config = static::applySiteFilters( $config );
// Generate Query
$query = $config[ 'query' ] ?? $modelClass::find();
$offset = $config[ 'offset' ] ?? 0;
$limit = $config[ 'limit' ] ?? self::PAGE_LIMIT;
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$sort = $config[ 'sort' ] ?? [ 'id' => SORT_DESC ]; // Show latest first
$public = $config[ 'public' ] ?? false;
// Result Columns
$columns = $config[ 'columns' ] ?? [];
// Array Result
$array = $config[ 'array' ] ?? false;
// Selective columns ---
if( count( $columns ) > 0 ) {
$query->select( $columns );
}
// Conditions ----------
if( isset( $conditions ) ) {
foreach( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach( $filters as $filter ) {
$query->andFilterWhere( $filter );
}
}
// Offset --------------
if( $offset > 0 ) {
$query->offset( $offset );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
// Sort -----------------
if( count( $sort ) > 0 ) {
$query->orderBy( $sort );
}
// Print to Debug -------
if( isset( $config[ 'pquery' ] ) && $config[ 'pquery' ] ) {
$command = $query->createCommand();
var_dump( $command );
}
// Models ---------------
if( $array ) {
$models = $query->asArray( $array )->all();
}
else {
$models = $query->all();
}
return $models;
} | [
"public",
"static",
"function",
"searchModels",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$",
"modelTable",
"=",
"$",
"modelClass",
"::",
"tableName",
"(",
")",
";",
"// Filters",
"$",
... | Advanced findModels having more options to search. | [
"Advanced",
"findModels",
"having",
"more",
"options",
"to",
"search",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1161-L1270 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.generateList | public static function generateList( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// Query and Column
$query = new Query();
$column = $config[ 'column' ] ?? 'id';
// Conditions, Filters and Sorting
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$order = $config[ 'order' ] ?? null;
// Conditions ----------
$query->select( $column )->from( $modelTable );
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach ( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Sorting -------------
if( isset( $order ) ) {
$query->orderBy( $order );
}
// Quering -------------
// Get column
$query->column();
// Create command
$command = $query->createCommand();
// Execute the command
$list = $command->queryAll();
$resultList = [];
// Result --------------
foreach ( $list as $item ) {
$resultList[] = $item[ $column ];
}
return $resultList;
} | php | public static function generateList( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// Query and Column
$query = new Query();
$column = $config[ 'column' ] ?? 'id';
// Conditions, Filters and Sorting
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$order = $config[ 'order' ] ?? null;
// Conditions ----------
$query->select( $column )->from( $modelTable );
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach ( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Sorting -------------
if( isset( $order ) ) {
$query->orderBy( $order );
}
// Quering -------------
// Get column
$query->column();
// Create command
$command = $query->createCommand();
// Execute the command
$list = $command->queryAll();
$resultList = [];
// Result --------------
foreach ( $list as $item ) {
$resultList[] = $item[ $column ];
}
return $resultList;
} | [
"public",
"static",
"function",
"generateList",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$",
"modelTable",
"=",
"$",
"modelClass",
"::",
"tableName",
"(",
")",
";",
"// Query and Column",... | The method generateList returns an array of list for given column
@param array $config
@return array - array of values. | [
"The",
"method",
"generateList",
"returns",
"an",
"array",
"of",
"list",
"for",
"given",
"column"
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1308-L1387 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.generateNameValueList | public static function generateNameValueList( $config = [] ) {
$config = static::applySiteFilters( $config );
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// map columns
$nameColumn = $config[ 'nameColumn' ] ?? 'name';
$valueColumn = $config[ 'valueColumn' ] ?? 'value';
// column alias
$nameAlias = $config[ 'nameAlias' ] ?? 'name';
$valueAlias = $config[ 'valueAlias' ] ?? 'value';
// limit
$limit = $config[ 'limit' ] ?? 0;
// Query
$query = $config[ 'query' ] ?? new Query();
// Conditions, Filters and Sorting
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$order = $config[ 'order' ] ?? null;
// additional data
$prepend = $config[ 'prepend' ] ?? [];
$append = $config[ 'append' ] ?? [];
// Conditions ----------
$query->select( [ "$nameColumn as $nameAlias", "$valueColumn as $valueAlias" ] )
->from( $modelTable );
if( isset( $conditions ) ) {
foreach( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Sorting -------------
if( isset( $order ) ) {
$query->orderBy( $order );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
// Quering -------------
// Create command
$command = $query->createCommand();
// Execute the command
$arrayList = $command->queryAll();
// Result --------------
// Prepend given list
if( count( $prepend ) > 0 ) {
$arrayList = ArrayHelper::merge( $prepend, $arrayList );
}
// Append given list
if( count( $append ) > 0 ) {
$arrayList = ArrayHelper::merge( $arrayList, $append );
}
return $arrayList;
} | php | public static function generateNameValueList( $config = [] ) {
$config = static::applySiteFilters( $config );
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// map columns
$nameColumn = $config[ 'nameColumn' ] ?? 'name';
$valueColumn = $config[ 'valueColumn' ] ?? 'value';
// column alias
$nameAlias = $config[ 'nameAlias' ] ?? 'name';
$valueAlias = $config[ 'valueAlias' ] ?? 'value';
// limit
$limit = $config[ 'limit' ] ?? 0;
// Query
$query = $config[ 'query' ] ?? new Query();
// Conditions, Filters and Sorting
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
$order = $config[ 'order' ] ?? null;
// additional data
$prepend = $config[ 'prepend' ] ?? [];
$append = $config[ 'append' ] ?? [];
// Conditions ----------
$query->select( [ "$nameColumn as $nameAlias", "$valueColumn as $valueAlias" ] )
->from( $modelTable );
if( isset( $conditions ) ) {
foreach( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Sorting -------------
if( isset( $order ) ) {
$query->orderBy( $order );
}
// Limit ---------------
if( $limit > 0 ) {
$query->limit( $limit );
}
// Quering -------------
// Create command
$command = $query->createCommand();
// Execute the command
$arrayList = $command->queryAll();
// Result --------------
// Prepend given list
if( count( $prepend ) > 0 ) {
$arrayList = ArrayHelper::merge( $prepend, $arrayList );
}
// Append given list
if( count( $append ) > 0 ) {
$arrayList = ArrayHelper::merge( $arrayList, $append );
}
return $arrayList;
} | [
"public",
"static",
"function",
"generateNameValueList",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"config",
"=",
"static",
"::",
"applySiteFilters",
"(",
"$",
"config",
")",
";",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$... | The method generateNameValueList returns an array of associative arrays having name and value as keys for the defined columns.
@param array $config
@return array - associative array of arrays having name and value as keys. | [
"The",
"method",
"generateNameValueList",
"returns",
"an",
"array",
"of",
"associative",
"arrays",
"having",
"name",
"and",
"value",
"as",
"keys",
"for",
"the",
"defined",
"columns",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1394-L1500 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.generateMap | public static function generateMap( $config = [] ) {
$parentType = static::$parentType;
// column alias
$defaultValue = preg_replace( '/-/', ' ', $parentType );
$default = $config[ 'default' ] ?? false;
$defaultValue = $config[ 'defaultValue' ] ?? ucfirst( $defaultValue );
$nameAlias = $config[ 'nameAlias' ] ?? 'name';
$valueAlias = $config[ 'valueAlias' ] ?? 'value';
$arrayList = static::generateNameValueList( $config );
$map = $default ? [ '0' => "Choose $defaultValue" ] : [];
foreach( $arrayList as $item ) {
$map[ $item[ $nameAlias ] ] = $item[ $valueAlias ];
}
return $map;
} | php | public static function generateMap( $config = [] ) {
$parentType = static::$parentType;
// column alias
$defaultValue = preg_replace( '/-/', ' ', $parentType );
$default = $config[ 'default' ] ?? false;
$defaultValue = $config[ 'defaultValue' ] ?? ucfirst( $defaultValue );
$nameAlias = $config[ 'nameAlias' ] ?? 'name';
$valueAlias = $config[ 'valueAlias' ] ?? 'value';
$arrayList = static::generateNameValueList( $config );
$map = $default ? [ '0' => "Choose $defaultValue" ] : [];
foreach( $arrayList as $item ) {
$map[ $item[ $nameAlias ] ] = $item[ $valueAlias ];
}
return $map;
} | [
"public",
"static",
"function",
"generateMap",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"parentType",
"=",
"static",
"::",
"$",
"parentType",
";",
"// column alias",
"$",
"defaultValue",
"=",
"preg_replace",
"(",
"'/-/'",
",",
"' '",
",",
"$",
"... | The method findMap returns an associative array for the defined table and columns. It also apply the provided conditions.
@param array $config
@return array - associative array of arrays having name as key and value as value. | [
"The",
"method",
"findMap",
"returns",
"an",
"associative",
"array",
"for",
"the",
"defined",
"table",
"and",
"columns",
".",
"It",
"also",
"apply",
"the",
"provided",
"conditions",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1531-L1552 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.generateObjectMap | public static function generateObjectMap( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// map columns
$key = $config[ 'key' ] ?? 'id';
$value = static::$modelClass;
// query generation
$query = $config[ 'query' ] ?? $value::find();
$limit = $config[ 'limit' ] ?? self::PAGE_LIMIT;
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
// Conditions ----------
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach ( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Quering -------------
$objects = $query->all();
// Result --------------
$map = [];
foreach( $objects as $object ) {
$map[ $object->$key ] = $object;
}
return $map;
} | php | public static function generateObjectMap( $config = [] ) {
$modelClass = static::$modelClass;
$modelTable = $modelClass::tableName();
// map columns
$key = $config[ 'key' ] ?? 'id';
$value = static::$modelClass;
// query generation
$query = $config[ 'query' ] ?? $value::find();
$limit = $config[ 'limit' ] ?? self::PAGE_LIMIT;
$conditions = $config[ 'conditions' ] ?? null;
$filters = $config[ 'filters' ] ?? null;
// Conditions ----------
if( isset( $conditions ) ) {
foreach ( $conditions as $ckey => $condition ) {
if( is_numeric( $ckey ) ) {
$query->andWhere( $condition );
unset( $conditions[ $ckey ] );
}
}
$query->andWhere( $conditions );
}
$interfaces = class_implements( static::class );
if( isset( $interfaces[ 'cmsgears\core\common\services\interfaces\base\IApproval' ] ) ) {
$statusFilter = $modelClass::STATUS_TERMINATED;
$query->andWhere( "$modelTable.status<$statusFilter" );
}
// Filters -------------
if( isset( $filters ) ) {
foreach ( $filters as $filter ) {
$query = $query->andFilterWhere( $filter );
}
}
// Quering -------------
$objects = $query->all();
// Result --------------
$map = [];
foreach( $objects as $object ) {
$map[ $object->$key ] = $object;
}
return $map;
} | [
"public",
"static",
"function",
"generateObjectMap",
"(",
"$",
"config",
"=",
"[",
"]",
")",
"{",
"$",
"modelClass",
"=",
"static",
"::",
"$",
"modelClass",
";",
"$",
"modelTable",
"=",
"$",
"modelClass",
"::",
"tableName",
"(",
")",
";",
"// map columns",... | The method findObjectMap returns an associative array for the defined table and columns. It also apply the provided conditions.
@param array $config | [
"The",
"method",
"findObjectMap",
"returns",
"an",
"associative",
"array",
"for",
"the",
"defined",
"table",
"and",
"columns",
".",
"It",
"also",
"apply",
"the",
"provided",
"conditions",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1558-L1623 | train |
cmsgears/module-core | common/services/base/ActiveRecordService.php | ActiveRecordService.generateSearchQuery | public static function generateSearchQuery( $columns, $searchTerms ) {
$searchTerms = preg_split( '/,/', $searchTerms );
$searchQuery = "";
// Multiple columns
if( is_array( $columns ) ) {
foreach( $columns as $ckey => $column ) {
$query = null;
foreach( $searchTerms as $skey => $term ) {
if( $skey == 0 ) {
$query = " $column like '%$term%' ";
}
else {
$query .= " OR $column like '%$term%' ";
}
}
if( isset( $query ) ) {
if( $ckey == 0 ) {
$searchQuery = "( $query )";
}
else {
$searchQuery .= " OR ( $query )";
}
}
}
}
// Single column
else {
foreach( $searchTerms as $key => $value ) {
if( $key == 0 ) {
$searchQuery .= " $columns like '%$value%' ";
}
else {
$searchQuery .= " OR $columns like '%$value%' ";
}
}
}
return $searchQuery;
} | php | public static function generateSearchQuery( $columns, $searchTerms ) {
$searchTerms = preg_split( '/,/', $searchTerms );
$searchQuery = "";
// Multiple columns
if( is_array( $columns ) ) {
foreach( $columns as $ckey => $column ) {
$query = null;
foreach( $searchTerms as $skey => $term ) {
if( $skey == 0 ) {
$query = " $column like '%$term%' ";
}
else {
$query .= " OR $column like '%$term%' ";
}
}
if( isset( $query ) ) {
if( $ckey == 0 ) {
$searchQuery = "( $query )";
}
else {
$searchQuery .= " OR ( $query )";
}
}
}
}
// Single column
else {
foreach( $searchTerms as $key => $value ) {
if( $key == 0 ) {
$searchQuery .= " $columns like '%$value%' ";
}
else {
$searchQuery .= " OR $columns like '%$value%' ";
}
}
}
return $searchQuery;
} | [
"public",
"static",
"function",
"generateSearchQuery",
"(",
"$",
"columns",
",",
"$",
"searchTerms",
")",
"{",
"$",
"searchTerms",
"=",
"preg_split",
"(",
"'/,/'",
",",
"$",
"searchTerms",
")",
";",
"$",
"searchQuery",
"=",
"\"\"",
";",
"// Multiple columns",
... | It generate search query for specified columns by parsing the comma separated search terms | [
"It",
"generate",
"search",
"query",
"for",
"specified",
"columns",
"by",
"parsing",
"the",
"comma",
"separated",
"search",
"terms"
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/services/base/ActiveRecordService.php#L1630-L1684 | train |
mcaskill/charcoal-support | src/Admin/Mixin/AdminSearchableTrait.php | AdminSearchableTrait.generateAdminSearchable | protected function generateAdminSearchable()
{
$translator = $this->translator();
$languages = $translator->availableLocales();
$searchKeywords = [];
$searchableProperties = $this->metadata()->get('admin.search.properties');
foreach ($searchableProperties as $propIdent => $searchData) {
$property = $this->property($propIdent);
$objValue = $this[$propIdent];
if (empty($objValue)) {
continue;
}
if ($property instanceof ObjectProperty) {
if (empty($searchData['properties'])) {
continue;
}
$searchProps = $searchData['properties'];
$fillKeywords = function ($relObj) use (&$searchKeywords, $searchProps, $translator, $languages) {
foreach ($searchProps as $searchProp) {
foreach ($languages as $lang) {
$relValue = $relObj->get($searchProp);
$searchKeywords[$lang][] = $translator->translate($relValue, [], null, $lang);
}
}
};
$relObjType = $property->objType();
if ($property->multiple()) {
if (!count($objValue)) {
continue;
}
$relObjIds = implode($property->multipleSeparator(), $objValue);
$this->collectionLoader()
->setModel($relObjType)
->addFilter([
'condition' => sprintf('FIND_IN_SET(objTable.id, "%s")', $relObjIds),
])
->setCallback($fillKeywords)
->load();
} else {
$relObj = $this->modelFactory()->create($relObjType)->load($objValue);
$fillKeywords($relObj);
}
} else {
foreach ($languages as $lang) {
$objValue = $property->parseVal($objValue);
$searchKeywords[$lang][] = $translator->translate($objValue, [], null, $lang);
}
}
}
$this->setAdminSearchKeywords($searchKeywords);
} | php | protected function generateAdminSearchable()
{
$translator = $this->translator();
$languages = $translator->availableLocales();
$searchKeywords = [];
$searchableProperties = $this->metadata()->get('admin.search.properties');
foreach ($searchableProperties as $propIdent => $searchData) {
$property = $this->property($propIdent);
$objValue = $this[$propIdent];
if (empty($objValue)) {
continue;
}
if ($property instanceof ObjectProperty) {
if (empty($searchData['properties'])) {
continue;
}
$searchProps = $searchData['properties'];
$fillKeywords = function ($relObj) use (&$searchKeywords, $searchProps, $translator, $languages) {
foreach ($searchProps as $searchProp) {
foreach ($languages as $lang) {
$relValue = $relObj->get($searchProp);
$searchKeywords[$lang][] = $translator->translate($relValue, [], null, $lang);
}
}
};
$relObjType = $property->objType();
if ($property->multiple()) {
if (!count($objValue)) {
continue;
}
$relObjIds = implode($property->multipleSeparator(), $objValue);
$this->collectionLoader()
->setModel($relObjType)
->addFilter([
'condition' => sprintf('FIND_IN_SET(objTable.id, "%s")', $relObjIds),
])
->setCallback($fillKeywords)
->load();
} else {
$relObj = $this->modelFactory()->create($relObjType)->load($objValue);
$fillKeywords($relObj);
}
} else {
foreach ($languages as $lang) {
$objValue = $property->parseVal($objValue);
$searchKeywords[$lang][] = $translator->translate($objValue, [], null, $lang);
}
}
}
$this->setAdminSearchKeywords($searchKeywords);
} | [
"protected",
"function",
"generateAdminSearchable",
"(",
")",
"{",
"$",
"translator",
"=",
"$",
"this",
"->",
"translator",
"(",
")",
";",
"$",
"languages",
"=",
"$",
"translator",
"->",
"availableLocales",
"(",
")",
";",
"$",
"searchKeywords",
"=",
"[",
"... | Generate this object's search keywords for the Charcoal Admin.
@return void | [
"Generate",
"this",
"object",
"s",
"search",
"keywords",
"for",
"the",
"Charcoal",
"Admin",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Admin/Mixin/AdminSearchableTrait.php#L53-L112 | train |
plumephp/plume | src/Plume/Provider/ExceptionProvider.php | ExceptionProvider.error_function | public function error_function($errno, $errstr, $errfile, $errline, $errcontext){
$this->provider('log')->exception('error_function',
array('errno' => $errno,'errstr' => $errstr, 'errfile' => $errfile, 'errline' => $errline, 'errcontext' => $errcontext));
require $this->plume('plume.root.path').$this->plume('plume.templates.500');
die();
// return false;//如果函数返回 FALSE,标准错误处理处理程序将会继续调用。
} | php | public function error_function($errno, $errstr, $errfile, $errline, $errcontext){
$this->provider('log')->exception('error_function',
array('errno' => $errno,'errstr' => $errstr, 'errfile' => $errfile, 'errline' => $errline, 'errcontext' => $errcontext));
require $this->plume('plume.root.path').$this->plume('plume.templates.500');
die();
// return false;//如果函数返回 FALSE,标准错误处理处理程序将会继续调用。
} | [
"public",
"function",
"error_function",
"(",
"$",
"errno",
",",
"$",
"errstr",
",",
"$",
"errfile",
",",
"$",
"errline",
",",
"$",
"errcontext",
")",
"{",
"$",
"this",
"->",
"provider",
"(",
"'log'",
")",
"->",
"exception",
"(",
"'error_function'",
",",
... | 1=>'ERROR', 2=>'WARNING', 4=>'PARSE', 8=>'NOTICE' | [
"1",
"=",
">",
"ERROR",
"2",
"=",
">",
"WARNING",
"4",
"=",
">",
"PARSE",
"8",
"=",
">",
"NOTICE"
] | e30baf34729e01fca30e713fe59d285216218eca | https://github.com/plumephp/plume/blob/e30baf34729e01fca30e713fe59d285216218eca/src/Plume/Provider/ExceptionProvider.php#L21-L27 | train |
cmsgears/module-core | common/models/entities/User.php | User.validateSlugUpdate | public function validateSlugUpdate( $attribute, $params ) {
if( !$this->hasErrors() ) {
$existingUser = self::findBySlug( $this->slug );
if( isset( $existingUser ) && $this->id != $existingUser->id ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_SLUG_EXIST ) );
}
}
} | php | public function validateSlugUpdate( $attribute, $params ) {
if( !$this->hasErrors() ) {
$existingUser = self::findBySlug( $this->slug );
if( isset( $existingUser ) && $this->id != $existingUser->id ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_SLUG_EXIST ) );
}
}
} | [
"public",
"function",
"validateSlugUpdate",
"(",
"$",
"attribute",
",",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasErrors",
"(",
")",
")",
"{",
"$",
"existingUser",
"=",
"self",
"::",
"findBySlug",
"(",
"$",
"this",
"->",
"slug",
... | Validates user slug to ensure that only one user exist with the given slug.
@param type $attribute
@param type $params
@return void | [
"Validates",
"user",
"slug",
"to",
"ensure",
"that",
"only",
"one",
"user",
"exist",
"with",
"the",
"given",
"slug",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L476-L487 | train |
cmsgears/module-core | common/models/entities/User.php | User.validateMobileChange | public function validateMobileChange( $attribute, $params ) {
if( !$this->hasErrors() ) {
$properties = CoreProperties::getInstance();
$existingUser = self::findById( $this->id );
if( isset( $existingUser ) && $existingUser->mobile !== $this->mobile && !$properties->isChangeMobile() ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_CHANGE_USERNAME ) );
}
}
} | php | public function validateMobileChange( $attribute, $params ) {
if( !$this->hasErrors() ) {
$properties = CoreProperties::getInstance();
$existingUser = self::findById( $this->id );
if( isset( $existingUser ) && $existingUser->mobile !== $this->mobile && !$properties->isChangeMobile() ) {
$this->addError( $attribute, Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_CHANGE_USERNAME ) );
}
}
} | [
"public",
"function",
"validateMobileChange",
"(",
"$",
"attribute",
",",
"$",
"params",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"hasErrors",
"(",
")",
")",
"{",
"$",
"properties",
"=",
"CoreProperties",
"::",
"getInstance",
"(",
")",
";",
"$",
"e... | Validates mobile to ensure that it does not allow to change while changing user profile.
@param type $attribute
@param type $params
@return void | [
"Validates",
"mobile",
"to",
"ensure",
"that",
"it",
"does",
"not",
"allow",
"to",
"change",
"while",
"changing",
"user",
"profile",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L554-L566 | train |
cmsgears/module-core | common/models/entities/User.php | User.validatePassword | public function validatePassword( $password ) {
if( isset( $password ) && isset( $this->passwordHash ) ) {
return Yii::$app->getSecurity()->validatePassword( $password, $this->passwordHash );
}
return false;
} | php | public function validatePassword( $password ) {
if( isset( $password ) && isset( $this->passwordHash ) ) {
return Yii::$app->getSecurity()->validatePassword( $password, $this->passwordHash );
}
return false;
} | [
"public",
"function",
"validatePassword",
"(",
"$",
"password",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"password",
")",
"&&",
"isset",
"(",
"$",
"this",
"->",
"passwordHash",
")",
")",
"{",
"return",
"Yii",
"::",
"$",
"app",
"->",
"getSecurity",
"(",
... | Validates user password while login.
@param type $password
@return boolean | [
"Validates",
"user",
"password",
"while",
"login",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L574-L582 | train |
cmsgears/module-core | common/models/entities/User.php | User.getActiveSiteMember | public function getActiveSiteMember() {
$site = Yii::$app->core->site;
return $this->hasOne( SiteMember::class, [ "userId" => 'id' ] )->where( [ "siteId" => $site->id ] );
} | php | public function getActiveSiteMember() {
$site = Yii::$app->core->site;
return $this->hasOne( SiteMember::class, [ "userId" => 'id' ] )->where( [ "siteId" => $site->id ] );
} | [
"public",
"function",
"getActiveSiteMember",
"(",
")",
"{",
"$",
"site",
"=",
"Yii",
"::",
"$",
"app",
"->",
"core",
"->",
"site",
";",
"return",
"$",
"this",
"->",
"hasOne",
"(",
"SiteMember",
"::",
"class",
",",
"[",
"\"userId\"",
"=>",
"'id'",
"]",
... | Returns site member mapping of active site.
It's useful in multi-site environment to get the member of current site.
@return \cmsgears\core\common\models\mappers\SiteMember | [
"Returns",
"site",
"member",
"mapping",
"of",
"active",
"site",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L603-L608 | train |
cmsgears/module-core | common/models/entities/User.php | User.getRole | public function getRole() {
$roleTable = CoreTables::getTableName( CoreTables::TABLE_ROLE );
$siteTable = CoreTables::getTableName( CoreTables::TABLE_SITE );
$siteMemberTable = CoreTables::getTableName( CoreTables::TABLE_SITE_MEMBER );
// TODO: Check why it's not working without appending one() after recent Yii Upgrade
return Role::find()
->leftJoin( $siteMemberTable, "$siteMemberTable.roleId = $roleTable.id" )
->leftJoin( $siteTable, "$siteTable.id = $siteMemberTable.siteId" )
->where( "$siteMemberTable.userId=:id AND $siteTable.slug=:slug", [ ':id' => $this->id, ':slug' => Yii::$app->core->getSiteSlug() ] )
->one();
} | php | public function getRole() {
$roleTable = CoreTables::getTableName( CoreTables::TABLE_ROLE );
$siteTable = CoreTables::getTableName( CoreTables::TABLE_SITE );
$siteMemberTable = CoreTables::getTableName( CoreTables::TABLE_SITE_MEMBER );
// TODO: Check why it's not working without appending one() after recent Yii Upgrade
return Role::find()
->leftJoin( $siteMemberTable, "$siteMemberTable.roleId = $roleTable.id" )
->leftJoin( $siteTable, "$siteTable.id = $siteMemberTable.siteId" )
->where( "$siteMemberTable.userId=:id AND $siteTable.slug=:slug", [ ':id' => $this->id, ':slug' => Yii::$app->core->getSiteSlug() ] )
->one();
} | [
"public",
"function",
"getRole",
"(",
")",
"{",
"$",
"roleTable",
"=",
"CoreTables",
"::",
"getTableName",
"(",
"CoreTables",
"::",
"TABLE_ROLE",
")",
";",
"$",
"siteTable",
"=",
"CoreTables",
"::",
"getTableName",
"(",
"CoreTables",
"::",
"TABLE_SITE",
")",
... | Returns role assigned to user for active site.
@return Role Assigned to User. | [
"Returns",
"role",
"assigned",
"to",
"user",
"for",
"active",
"site",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L615-L627 | train |
cmsgears/module-core | common/models/entities/User.php | User.getFullName | public function getFullName() {
$name = $this->firstName;
if( !empty( $this->middleName ) ) {
$name = "$name $this->middleName";
}
if( !empty( $this->lastName ) ) {
$name = "$name $this->lastName";
}
return $name;
} | php | public function getFullName() {
$name = $this->firstName;
if( !empty( $this->middleName ) ) {
$name = "$name $this->middleName";
}
if( !empty( $this->lastName ) ) {
$name = "$name $this->lastName";
}
return $name;
} | [
"public",
"function",
"getFullName",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"firstName",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"this",
"->",
"middleName",
")",
")",
"{",
"$",
"name",
"=",
"\"$name $this->middleName\"",
";",
"}",
"if",
... | Returns full name of user using first name, middle name and last name.
@return string | [
"Returns",
"full",
"name",
"of",
"user",
"using",
"first",
"name",
"middle",
"name",
"and",
"last",
"name",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L681-L696 | train |
cmsgears/module-core | common/models/entities/User.php | User.getName | public function getName() {
$name = $this->getFullName();
if( empty( $name ) ) {
$name = $this->username;
if( empty( $name ) ) {
$name = preg_split( '/@/', $this->email );
$name = $name[ 0 ];
}
}
return $name;
} | php | public function getName() {
$name = $this->getFullName();
if( empty( $name ) ) {
$name = $this->username;
if( empty( $name ) ) {
$name = preg_split( '/@/', $this->email );
$name = $name[ 0 ];
}
}
return $name;
} | [
"public",
"function",
"getName",
"(",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getFullName",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"username",
";",
"if",
"(",
"empty",
"(... | Returns name of user using first name, middle name and last name.
It returns username or user id of email in case name is not set for the user.
@return string | [
"Returns",
"name",
"of",
"user",
"using",
"first",
"name",
"middle",
"name",
"and",
"last",
"name",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L710-L726 | train |
cmsgears/module-core | common/models/entities/User.php | User.isVerified | public function isVerified( $strict = true ) {
if( $strict ) {
return $this->status == self::STATUS_VERIFIED;
}
return $this->status >= self::STATUS_VERIFIED;
} | php | public function isVerified( $strict = true ) {
if( $strict ) {
return $this->status == self::STATUS_VERIFIED;
}
return $this->status >= self::STATUS_VERIFIED;
} | [
"public",
"function",
"isVerified",
"(",
"$",
"strict",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"strict",
")",
"{",
"return",
"$",
"this",
"->",
"status",
"==",
"self",
"::",
"STATUS_VERIFIED",
";",
"}",
"return",
"$",
"this",
"->",
"status",
">=",
"s... | Check whether user is verified.
@param boolean $strict
@return boolean | [
"Check",
"whether",
"user",
"is",
"verified",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L747-L755 | train |
cmsgears/module-core | common/models/entities/User.php | User.generateOtp | public function generateOtp() {
$this->otp = random_int( 100000, 999999 );
$valid = DateUtil::getDateTime();
$valid = strtotime( $valid ) + Yii::$app->core->getOtpValidity();
$this->otpValidTill = DateUtil::getDateTimeFromMillis( $valid );
return $this->otp;
} | php | public function generateOtp() {
$this->otp = random_int( 100000, 999999 );
$valid = DateUtil::getDateTime();
$valid = strtotime( $valid ) + Yii::$app->core->getOtpValidity();
$this->otpValidTill = DateUtil::getDateTimeFromMillis( $valid );
return $this->otp;
} | [
"public",
"function",
"generateOtp",
"(",
")",
"{",
"$",
"this",
"->",
"otp",
"=",
"random_int",
"(",
"100000",
",",
"999999",
")",
";",
"$",
"valid",
"=",
"DateUtil",
"::",
"getDateTime",
"(",
")",
";",
"$",
"valid",
"=",
"strtotime",
"(",
"$",
"val... | Generate and set 6 digit random OTP.
@return void | [
"Generate",
"and",
"set",
"6",
"digit",
"random",
"OTP",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L849-L859 | train |
cmsgears/module-core | common/models/entities/User.php | User.isOtpValid | public function isOtpValid( $otp ) {
$now = DateUtil::getDateTime();
return $this->otp == $otp && DateUtil::lessThan( $now, $this->otpValidTill );
} | php | public function isOtpValid( $otp ) {
$now = DateUtil::getDateTime();
return $this->otp == $otp && DateUtil::lessThan( $now, $this->otpValidTill );
} | [
"public",
"function",
"isOtpValid",
"(",
"$",
"otp",
")",
"{",
"$",
"now",
"=",
"DateUtil",
"::",
"getDateTime",
"(",
")",
";",
"return",
"$",
"this",
"->",
"otp",
"==",
"$",
"otp",
"&&",
"DateUtil",
"::",
"lessThan",
"(",
"$",
"now",
",",
"$",
"th... | Check whether OTP is valid.
@param integer $otp
@return boolean | [
"Check",
"whether",
"OTP",
"is",
"valid",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L877-L882 | train |
cmsgears/module-core | common/models/entities/User.php | User.loadPermissions | public function loadPermissions() {
$role = $this->role;
if( isset( $role ) ) {
$this->permissions = $role->getPermissionsSlugList();
}
else {
throw new ForbiddenHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NO_ACCESS ) );
}
} | php | public function loadPermissions() {
$role = $this->role;
if( isset( $role ) ) {
$this->permissions = $role->getPermissionsSlugList();
}
else {
throw new ForbiddenHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NO_ACCESS ) );
}
} | [
"public",
"function",
"loadPermissions",
"(",
")",
"{",
"$",
"role",
"=",
"$",
"this",
"->",
"role",
";",
"if",
"(",
"isset",
"(",
"$",
"role",
")",
")",
"{",
"$",
"this",
"->",
"permissions",
"=",
"$",
"role",
"->",
"getPermissionsSlugList",
"(",
")... | Load the permissions assigned to the user.
The loaded permissions will be queried for access to specific features.
@throws \yii\web\ForbiddenHttpException
@return void | [
"Load",
"the",
"permissions",
"assigned",
"to",
"the",
"user",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L902-L914 | train |
cmsgears/module-core | common/models/entities/User.php | User.isPermitted | public function isPermitted( $permission ) {
if( is_string( $permission ) ) {
return in_array( $permission, $this->permissions );
}
else {
$permitted = false;
foreach( $permission as $perm ) {
if( in_array( $perm, $this->permissions ) ) {
$permitted = true;
break;
}
}
return $permitted;
}
} | php | public function isPermitted( $permission ) {
if( is_string( $permission ) ) {
return in_array( $permission, $this->permissions );
}
else {
$permitted = false;
foreach( $permission as $perm ) {
if( in_array( $perm, $this->permissions ) ) {
$permitted = true;
break;
}
}
return $permitted;
}
} | [
"public",
"function",
"isPermitted",
"(",
"$",
"permission",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"permission",
")",
")",
"{",
"return",
"in_array",
"(",
"$",
"permission",
",",
"$",
"this",
"->",
"permissions",
")",
";",
"}",
"else",
"{",
"$",
... | Check whether given permission is assigned to the user.
@param string $permission Permission slug
@return boolean | [
"Check",
"whether",
"given",
"permission",
"is",
"assigned",
"to",
"the",
"user",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L922-L944 | train |
cmsgears/module-core | common/models/entities/User.php | User.findIdentity | public static function findIdentity( $id ) {
// Find valid User
$user = static::findById( $id );
// Load User Permissions
if( isset( $user ) ) {
if( Yii::$app->core->isRbac() ) {
$user->loadPermissions();
}
return $user;
}
throw new NotFoundHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | php | public static function findIdentity( $id ) {
// Find valid User
$user = static::findById( $id );
// Load User Permissions
if( isset( $user ) ) {
if( Yii::$app->core->isRbac() ) {
$user->loadPermissions();
}
return $user;
}
throw new NotFoundHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
} | [
"public",
"static",
"function",
"findIdentity",
"(",
"$",
"id",
")",
"{",
"// Find valid User",
"$",
"user",
"=",
"static",
"::",
"findById",
"(",
"$",
"id",
")",
";",
"// Load User Permissions",
"if",
"(",
"isset",
"(",
"$",
"user",
")",
")",
"{",
"if",... | Finds user identity using the given id and also loads the available permissions if
RBAC is enabled for the application.
@param integer $id
@throws \yii\web\NotFoundHttpException
@return User based on given id. | [
"Finds",
"user",
"identity",
"using",
"the",
"given",
"id",
"and",
"also",
"loads",
"the",
"available",
"permissions",
"if",
"RBAC",
"is",
"enabled",
"for",
"the",
"application",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L960-L977 | train |
cmsgears/module-core | common/models/entities/User.php | User.findIdentityByAccessToken | public static function findIdentityByAccessToken( $token, $type = null ) {
// TODO: Also check access token validity using apiValidDays config
if( Yii::$app->core->isApis() ) {
// Find valid User
$user = static::findByAccessToken( $token );
// Load User Permissions
if( isset( $user ) ) {
if( Yii::$app->core->isRbac() ) {
$user->loadPermissions();
}
return $user;
}
throw new NotFoundHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
}
throw new NotSupportedException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_APIS_DISABLED ) );
} | php | public static function findIdentityByAccessToken( $token, $type = null ) {
// TODO: Also check access token validity using apiValidDays config
if( Yii::$app->core->isApis() ) {
// Find valid User
$user = static::findByAccessToken( $token );
// Load User Permissions
if( isset( $user ) ) {
if( Yii::$app->core->isRbac() ) {
$user->loadPermissions();
}
return $user;
}
throw new NotFoundHttpException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_NOT_FOUND ) );
}
throw new NotSupportedException( Yii::$app->coreMessage->getMessage( CoreGlobal::ERROR_APIS_DISABLED ) );
} | [
"public",
"static",
"function",
"findIdentityByAccessToken",
"(",
"$",
"token",
",",
"$",
"type",
"=",
"null",
")",
"{",
"// TODO: Also check access token validity using apiValidDays config",
"if",
"(",
"Yii",
"::",
"$",
"app",
"->",
"core",
"->",
"isApis",
"(",
"... | Finds user identity using the given access token and also loads the available
permissions if RBAC is enabled for the application.
@param string $token
@param string $type
@throws \yii\web\NotFoundHttpException
@throws \yii\base\NotSupportedException
@return a valid user based on given token and type | [
"Finds",
"user",
"identity",
"using",
"the",
"given",
"access",
"token",
"and",
"also",
"loads",
"the",
"available",
"permissions",
"if",
"RBAC",
"is",
"enabled",
"for",
"the",
"application",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L989-L1013 | train |
cmsgears/module-core | common/models/entities/User.php | User.isExistByEmail | public static function isExistByEmail( $email ) {
$user = self::find()->where( 'email=:email', [ ':email' => $email ] )->one();
return isset( $user );
} | php | public static function isExistByEmail( $email ) {
$user = self::find()->where( 'email=:email', [ ':email' => $email ] )->one();
return isset( $user );
} | [
"public",
"static",
"function",
"isExistByEmail",
"(",
"$",
"email",
")",
"{",
"$",
"user",
"=",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"'email=:email'",
",",
"[",
"':email'",
"=>",
"$",
"email",
"]",
")",
"->",
"one",
"(",
")",
";",
"... | Check whether user exist for given email.
@param string $email
@return boolean | [
"Check",
"whether",
"user",
"exist",
"for",
"given",
"email",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L1131-L1136 | train |
cmsgears/module-core | common/models/entities/User.php | User.isExistByUsername | public static function isExistByUsername( $username ) {
$user = self::find()->where( 'username=:username', [ ':username' => $username ] )->one();
return isset( $user );
} | php | public static function isExistByUsername( $username ) {
$user = self::find()->where( 'username=:username', [ ':username' => $username ] )->one();
return isset( $user );
} | [
"public",
"static",
"function",
"isExistByUsername",
"(",
"$",
"username",
")",
"{",
"$",
"user",
"=",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"'username=:username'",
",",
"[",
"':username'",
"=>",
"$",
"username",
"]",
")",
"->",
"one",
"(",... | Check whether user exist for given username.
@param string $username
@return boolean | [
"Check",
"whether",
"user",
"exist",
"for",
"given",
"username",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L1155-L1160 | train |
cmsgears/module-core | common/models/entities/User.php | User.isExistBySlug | public static function isExistBySlug( $slug ) {
$user = self::find()->where( 'slug=:slug', [ ':slug' => $slug ] )->one();
return isset( $user );
} | php | public static function isExistBySlug( $slug ) {
$user = self::find()->where( 'slug=:slug', [ ':slug' => $slug ] )->one();
return isset( $user );
} | [
"public",
"static",
"function",
"isExistBySlug",
"(",
"$",
"slug",
")",
"{",
"$",
"user",
"=",
"self",
"::",
"find",
"(",
")",
"->",
"where",
"(",
"'slug=:slug'",
",",
"[",
"':slug'",
"=>",
"$",
"slug",
"]",
")",
"->",
"one",
"(",
")",
";",
"return... | Check whether user exist for given slug.
@param string $slug
@return boolean | [
"Check",
"whether",
"user",
"exist",
"for",
"given",
"slug",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/entities/User.php#L1179-L1184 | train |
cmsgears/module-core | common/models/resources/FormField.php | FormField.getFieldValue | public function getFieldValue() {
switch( $this->type ) {
case self::TYPE_TEXT:
case self::TYPE_TEXTAREA:
case self::TYPE_RADIO:
case self::TYPE_RADIO_GROUP:
case self::TYPE_SELECT:
case self::TYPE_RATING:
case self::TYPE_ICON:
case self::TYPE_CHECKBOX_GROUP: {
return $this->value;
}
case self::TYPE_PASSWORD: {
return null;
}
case self::TYPE_CHECKBOX:
case self::TYPE_TOGGLE: {
return Yii::$app->formatter->asBoolean( $this->value );
}
}
} | php | public function getFieldValue() {
switch( $this->type ) {
case self::TYPE_TEXT:
case self::TYPE_TEXTAREA:
case self::TYPE_RADIO:
case self::TYPE_RADIO_GROUP:
case self::TYPE_SELECT:
case self::TYPE_RATING:
case self::TYPE_ICON:
case self::TYPE_CHECKBOX_GROUP: {
return $this->value;
}
case self::TYPE_PASSWORD: {
return null;
}
case self::TYPE_CHECKBOX:
case self::TYPE_TOGGLE: {
return Yii::$app->formatter->asBoolean( $this->value );
}
}
} | [
"public",
"function",
"getFieldValue",
"(",
")",
"{",
"switch",
"(",
"$",
"this",
"->",
"type",
")",
"{",
"case",
"self",
"::",
"TYPE_TEXT",
":",
"case",
"self",
"::",
"TYPE_TEXTAREA",
":",
"case",
"self",
"::",
"TYPE_RADIO",
":",
"case",
"self",
"::",
... | Identify the field value type and return the value according to type.
@return mixed | [
"Identify",
"the",
"field",
"value",
"type",
"and",
"return",
"the",
"value",
"according",
"to",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/resources/FormField.php#L347-L372 | train |
cmsgears/module-core | common/models/resources/FormField.php | FormField.isExistByNameFormId | public static function isExistByNameFormId( $name, $formId ) {
$field = self::findByNameFormId( $name, $formId );
return isset( $field );
} | php | public static function isExistByNameFormId( $name, $formId ) {
$field = self::findByNameFormId( $name, $formId );
return isset( $field );
} | [
"public",
"static",
"function",
"isExistByNameFormId",
"(",
"$",
"name",
",",
"$",
"formId",
")",
"{",
"$",
"field",
"=",
"self",
"::",
"findByNameFormId",
"(",
"$",
"name",
",",
"$",
"formId",
")",
";",
"return",
"isset",
"(",
"$",
"field",
")",
";",
... | Check whether field exist for given name and form id.
@param string $name
@param integer $formId
@return boolean | [
"Check",
"whether",
"field",
"exist",
"for",
"given",
"name",
"and",
"form",
"id",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/resources/FormField.php#L450-L455 | train |
cmsgears/module-core | common/models/base/Meta.php | Meta.findByName | public static function findByName( $modelId, $name ) {
$query = self::queryByName( $modelId, $name );
return $query->all();
} | php | public static function findByName( $modelId, $name ) {
$query = self::queryByName( $modelId, $name );
return $query->all();
} | [
"public",
"static",
"function",
"findByName",
"(",
"$",
"modelId",
",",
"$",
"name",
")",
"{",
"$",
"query",
"=",
"self",
"::",
"queryByName",
"(",
"$",
"modelId",
",",
"$",
"name",
")",
";",
"return",
"$",
"query",
"->",
"all",
"(",
")",
";",
"}"
... | Return meta models by parent id and meta name.
@param integer $modelId Parent Id.
@param string $name
@return ModelMeta[] by parent id and meta name. | [
"Return",
"meta",
"models",
"by",
"parent",
"id",
"and",
"meta",
"name",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/base/Meta.php#L276-L281 | train |
cmsgears/module-core | common/models/base/Meta.php | Meta.findFirstByName | public static function findFirstByName( $modelId, $name ) {
$query = self::queryByName( $modelId, $name );
return $query->one();
} | php | public static function findFirstByName( $modelId, $name ) {
$query = self::queryByName( $modelId, $name );
return $query->one();
} | [
"public",
"static",
"function",
"findFirstByName",
"(",
"$",
"modelId",
",",
"$",
"name",
")",
"{",
"$",
"query",
"=",
"self",
"::",
"queryByName",
"(",
"$",
"modelId",
",",
"$",
"name",
")",
";",
"return",
"$",
"query",
"->",
"one",
"(",
")",
";",
... | Return first meta model by parent id and meta name.
@param integer $modelId Parent Id.
@param string $name
@return ModelMeta|array|null by parent id and meta name. | [
"Return",
"first",
"meta",
"model",
"by",
"parent",
"id",
"and",
"meta",
"name",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/base/Meta.php#L290-L295 | train |
cmsgears/module-core | common/models/base/Meta.php | Meta.findByNameType | public static function findByNameType( $modelId, $name, $type ) {
return self::queryByNameType( $modelId, $name, $type )->one();
} | php | public static function findByNameType( $modelId, $name, $type ) {
return self::queryByNameType( $modelId, $name, $type )->one();
} | [
"public",
"static",
"function",
"findByNameType",
"(",
"$",
"modelId",
",",
"$",
"name",
",",
"$",
"type",
")",
"{",
"return",
"self",
"::",
"queryByNameType",
"(",
"$",
"modelId",
",",
"$",
"name",
",",
"$",
"type",
")",
"->",
"one",
"(",
")",
";",
... | Return meta model by parent id, meta name and meta type.
@param integer $modelId Parent Id.
@param string $name
@param string $type
@return ModelMeta|array|null by parent id, meta name and meta type. | [
"Return",
"meta",
"model",
"by",
"parent",
"id",
"meta",
"name",
"and",
"meta",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/base/Meta.php#L317-L320 | train |
cmsgears/module-core | common/models/base/Meta.php | Meta.isExistByNameType | public static function isExistByNameType( $modelId, $name, $type ) {
$meta = self::findByNameType( $modelId, $type, $name );
return isset( $meta );
} | php | public static function isExistByNameType( $modelId, $name, $type ) {
$meta = self::findByNameType( $modelId, $type, $name );
return isset( $meta );
} | [
"public",
"static",
"function",
"isExistByNameType",
"(",
"$",
"modelId",
",",
"$",
"name",
",",
"$",
"type",
")",
"{",
"$",
"meta",
"=",
"self",
"::",
"findByNameType",
"(",
"$",
"modelId",
",",
"$",
"type",
",",
"$",
"name",
")",
";",
"return",
"is... | Check whether meta exist by parent id, meta name and meta type.
@param integer $modelId Parent Id.
@param string $name
@param string $type
@return boolean | [
"Check",
"whether",
"meta",
"exist",
"by",
"parent",
"id",
"meta",
"name",
"and",
"meta",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/base/Meta.php#L330-L335 | train |
cmsgears/module-core | common/models/base/Meta.php | Meta.updateByNameType | public static function updateByNameType( $modelId, $name, $type, $value ) {
$meta = self::findByNameType( $modelId, $name, $type );
if( isset( $meta ) ) {
$meta->value = $value;
return $meta->update();
}
return false;
} | php | public static function updateByNameType( $modelId, $name, $type, $value ) {
$meta = self::findByNameType( $modelId, $name, $type );
if( isset( $meta ) ) {
$meta->value = $value;
return $meta->update();
}
return false;
} | [
"public",
"static",
"function",
"updateByNameType",
"(",
"$",
"modelId",
",",
"$",
"name",
",",
"$",
"type",
",",
"$",
"value",
")",
"{",
"$",
"meta",
"=",
"self",
"::",
"findByNameType",
"(",
"$",
"modelId",
",",
"$",
"name",
",",
"$",
"type",
")",
... | Update the meta value for given parent id, name, type.
@param integer $modelId Parent Id.
@param string $name
@param string $type
@param type $value
@return int|false either 1 or false if meta not found or validation fails. | [
"Update",
"the",
"meta",
"value",
"for",
"given",
"parent",
"id",
"name",
"type",
"."
] | ce1b1f7afff2931847d71afa152c72355f374dc6 | https://github.com/cmsgears/module-core/blob/ce1b1f7afff2931847d71afa152c72355f374dc6/common/models/base/Meta.php#L350-L362 | train |
techdivision/import-product-variant-ee | src/Subjects/EeVariantSubject.php | EeVariantSubject.mapSkuToRowId | public function mapSkuToRowId($sku)
{
// query weather or not the SKU has been mapped
if (isset($this->skuRowIdMapping[$sku])) {
return $this->skuRowIdMapping[$sku];
}
// throw an exception if the SKU has not been mapped yet
throw new \Exception(sprintf('Found not mapped SKU %s', $sku));
} | php | public function mapSkuToRowId($sku)
{
// query weather or not the SKU has been mapped
if (isset($this->skuRowIdMapping[$sku])) {
return $this->skuRowIdMapping[$sku];
}
// throw an exception if the SKU has not been mapped yet
throw new \Exception(sprintf('Found not mapped SKU %s', $sku));
} | [
"public",
"function",
"mapSkuToRowId",
"(",
"$",
"sku",
")",
"{",
"// query weather or not the SKU has been mapped",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"skuRowIdMapping",
"[",
"$",
"sku",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"skuRowIdMappi... | Return the row ID for the passed SKU.
@param string $sku The SKU to return the row ID for
@return integer The mapped row ID
@throws \Exception Is thrown if the SKU is not mapped yet | [
"Return",
"the",
"row",
"ID",
"for",
"the",
"passed",
"SKU",
"."
] | 9421d30782ea45924f9cc86fe5d6169aadc9817f | https://github.com/techdivision/import-product-variant-ee/blob/9421d30782ea45924f9cc86fe5d6169aadc9817f/src/Subjects/EeVariantSubject.php#L76-L86 | train |
phPoirot/Std | src/CallableArgsResolver.php | CallableArgsResolver.makeReflectFromCallable | static function makeReflectFromCallable(callable $callable)
{
if ( $callable instanceof ipInvokableCallback )
$callable = $callable->getCallable();
if ( is_array($callable) )
// [className_orObject, 'method_name']
$reflection = new \ReflectionMethod($callable[0], $callable[1]);
if ( is_string($callable) ) {
if ( strpos($callable, '::') )
// 'classname::method'
$reflection = new \ReflectionMethod($callable);
else
// 'function_name'
$reflection = new \ReflectionFunction($callable);
}
if ( method_exists($callable, '__invoke') ) {
// Closure and Invokable
if ($callable instanceof \Closure)
$reflection = new \ReflectionFunction($callable);
else
$reflection = new \ReflectionMethod($callable, '__invoke');
}
if (! isset($reflection) )
throw new \ReflectionException;
return $reflection;
} | php | static function makeReflectFromCallable(callable $callable)
{
if ( $callable instanceof ipInvokableCallback )
$callable = $callable->getCallable();
if ( is_array($callable) )
// [className_orObject, 'method_name']
$reflection = new \ReflectionMethod($callable[0], $callable[1]);
if ( is_string($callable) ) {
if ( strpos($callable, '::') )
// 'classname::method'
$reflection = new \ReflectionMethod($callable);
else
// 'function_name'
$reflection = new \ReflectionFunction($callable);
}
if ( method_exists($callable, '__invoke') ) {
// Closure and Invokable
if ($callable instanceof \Closure)
$reflection = new \ReflectionFunction($callable);
else
$reflection = new \ReflectionMethod($callable, '__invoke');
}
if (! isset($reflection) )
throw new \ReflectionException;
return $reflection;
} | [
"static",
"function",
"makeReflectFromCallable",
"(",
"callable",
"$",
"callable",
")",
"{",
"if",
"(",
"$",
"callable",
"instanceof",
"ipInvokableCallback",
")",
"$",
"callable",
"=",
"$",
"callable",
"->",
"getCallable",
"(",
")",
";",
"if",
"(",
"is_array",... | Factory Reflection From Given Callable
$function
'function_name' | \closure
'classname::method'
[className_orObject, 'method_name']
@param $callable
@throws \ReflectionException
@return \ReflectionFunction|\ReflectionMethod | [
"Factory",
"Reflection",
"From",
"Given",
"Callable"
] | 67883b1b1dd2cea80fec3d98a199c403b8a23b4d | https://github.com/phPoirot/Std/blob/67883b1b1dd2cea80fec3d98a199c403b8a23b4d/src/CallableArgsResolver.php#L23-L53 | train |
phPoirot/Std | src/CallableArgsResolver.php | CallableArgsResolver.resolveCallableWithArgs | static function resolveCallableWithArgs(callable $callable, $parameters)
{
if ($parameters instanceof \Traversable)
$parameters = \Poirot\Std\cast($parameters)->toArray();
$reflection = self::makeReflectFromCallable($callable);
$matchedArguments = self::resolveArgsForReflection($reflection, $parameters);
if (!empty($parameters) && empty($matchedArguments))
// In Case That Fun Has No Any Argument.
// exp. func() { $args = func_get_args() ..
$matchedArguments = $parameters;
$callbackResolved = function() use ($callable, $matchedArguments) {
return call_user_func_array($callable, $matchedArguments);
};
return $callbackResolved;
} | php | static function resolveCallableWithArgs(callable $callable, $parameters)
{
if ($parameters instanceof \Traversable)
$parameters = \Poirot\Std\cast($parameters)->toArray();
$reflection = self::makeReflectFromCallable($callable);
$matchedArguments = self::resolveArgsForReflection($reflection, $parameters);
if (!empty($parameters) && empty($matchedArguments))
// In Case That Fun Has No Any Argument.
// exp. func() { $args = func_get_args() ..
$matchedArguments = $parameters;
$callbackResolved = function() use ($callable, $matchedArguments) {
return call_user_func_array($callable, $matchedArguments);
};
return $callbackResolved;
} | [
"static",
"function",
"resolveCallableWithArgs",
"(",
"callable",
"$",
"callable",
",",
"$",
"parameters",
")",
"{",
"if",
"(",
"$",
"parameters",
"instanceof",
"\\",
"Traversable",
")",
"$",
"parameters",
"=",
"\\",
"Poirot",
"\\",
"Std",
"\\",
"cast",
"(",... | Resolve Arguments Matched With Callable Arguments
@param callable $callable
@param array|\Traversable $parameters Params to match with function arguments
@return \Closure
@throws \InvalidArgumentException | [
"Resolve",
"Arguments",
"Matched",
"With",
"Callable",
"Arguments"
] | 67883b1b1dd2cea80fec3d98a199c403b8a23b4d | https://github.com/phPoirot/Std/blob/67883b1b1dd2cea80fec3d98a199c403b8a23b4d/src/CallableArgsResolver.php#L64-L83 | train |
mcaskill/charcoal-support | src/Cms/SectionAwareTrait.php | SectionAwareTrait.getSection | private function getSection()
{
$this->section = $this->modelFactory()->get($this->sectionClass());
return $this->section;
} | php | private function getSection()
{
$this->section = $this->modelFactory()->get($this->sectionClass());
return $this->section;
} | [
"private",
"function",
"getSection",
"(",
")",
"{",
"$",
"this",
"->",
"section",
"=",
"$",
"this",
"->",
"modelFactory",
"(",
")",
"->",
"get",
"(",
"$",
"this",
"->",
"sectionClass",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"section",
";",
... | Retrieve a prototype from the section model name.
@return SectionInterface | [
"Retrieve",
"a",
"prototype",
"from",
"the",
"section",
"model",
"name",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Cms/SectionAwareTrait.php#L69-L74 | train |
mcaskill/charcoal-support | src/Cms/SectionAwareTrait.php | SectionAwareTrait.createSection | private function createSection()
{
$this->section = $this->modelFactory()->create($this->sectionClass());
return $this->section;
} | php | private function createSection()
{
$this->section = $this->modelFactory()->create($this->sectionClass());
return $this->section;
} | [
"private",
"function",
"createSection",
"(",
")",
"{",
"$",
"this",
"->",
"section",
"=",
"$",
"this",
"->",
"modelFactory",
"(",
")",
"->",
"create",
"(",
"$",
"this",
"->",
"sectionClass",
"(",
")",
")",
";",
"return",
"$",
"this",
"->",
"section",
... | Create a new section object from the section model name.
@return SectionInterface | [
"Create",
"a",
"new",
"section",
"object",
"from",
"the",
"section",
"model",
"name",
"."
] | 2138a34463ca6865bf3a60635aa11381a9ae73c5 | https://github.com/mcaskill/charcoal-support/blob/2138a34463ca6865bf3a60635aa11381a9ae73c5/src/Cms/SectionAwareTrait.php#L81-L86 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.