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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
mapbender/fom | src/FOM/CoreBundle/Doctrine/DoctrineHelper.php | DoctrineHelper.checkAndCreateTableByEntityName | public static function checkAndCreateTableByEntityName(ContainerInterface $container, $className, $force = false)
{
/** @var Registry $doctrine */
/** @var Connection $connection */
/** @var ClassMetadata $classMetadata */
$doctrine = $container->get('doctrine');
$manager = $doctrine->getManager();
$schemaTool = new SchemaTool($doctrine->getManager());
$connection = $doctrine->getConnection();
$schemaManager = $connection->getSchemaManager();
$classMetadata = $manager->getClassMetadata($className);
if ($force || !$schemaManager->tablesExist($classMetadata->getTableName())) {
if ($schemaManager instanceof SqliteSchemaManager) {
$columns = array();
$identifiers = $classMetadata->getIdentifierColumnNames();
foreach ($classMetadata->getFieldNames() as $fieldName) {
$fieldMapping = $classMetadata->getFieldMapping($fieldName);
$columnSql = $fieldMapping["fieldName"];
switch ($fieldMapping["type"]) {
case 'integer':
$columnSql .= " INTEGER ";
break;
case 'real':
case 'double':
case 'float':
$columnSql .= " REAL ";
break;
case 'datetime':
case 'date':
case 'boolean':
$columnSql .= " INTEGER ";
break;
case 'blob':
case 'file':
$columnSql .= " BLOB ";
break;
default:
$columnSql .= " TEXT ";
}
// PRIMARY KEY
in_array($fieldName, $identifiers) && $columnSql .= "PRIMARY KEY ";
$columnSql .= $fieldMapping["nullable"] ? "NULL " : "NOT NULL ";
$columns[] = $columnSql;
}
$sql = 'CREATE TABLE IF NOT EXISTS ' . $classMetadata->getTableName() . '( ' . implode(",\n", $columns) . ')';
$statement = $connection->query($sql);
} else {
$schemaTool->updateSchema(array($classMetadata), true);
}
}
} | php | public static function checkAndCreateTableByEntityName(ContainerInterface $container, $className, $force = false)
{
/** @var Registry $doctrine */
/** @var Connection $connection */
/** @var ClassMetadata $classMetadata */
$doctrine = $container->get('doctrine');
$manager = $doctrine->getManager();
$schemaTool = new SchemaTool($doctrine->getManager());
$connection = $doctrine->getConnection();
$schemaManager = $connection->getSchemaManager();
$classMetadata = $manager->getClassMetadata($className);
if ($force || !$schemaManager->tablesExist($classMetadata->getTableName())) {
if ($schemaManager instanceof SqliteSchemaManager) {
$columns = array();
$identifiers = $classMetadata->getIdentifierColumnNames();
foreach ($classMetadata->getFieldNames() as $fieldName) {
$fieldMapping = $classMetadata->getFieldMapping($fieldName);
$columnSql = $fieldMapping["fieldName"];
switch ($fieldMapping["type"]) {
case 'integer':
$columnSql .= " INTEGER ";
break;
case 'real':
case 'double':
case 'float':
$columnSql .= " REAL ";
break;
case 'datetime':
case 'date':
case 'boolean':
$columnSql .= " INTEGER ";
break;
case 'blob':
case 'file':
$columnSql .= " BLOB ";
break;
default:
$columnSql .= " TEXT ";
}
// PRIMARY KEY
in_array($fieldName, $identifiers) && $columnSql .= "PRIMARY KEY ";
$columnSql .= $fieldMapping["nullable"] ? "NULL " : "NOT NULL ";
$columns[] = $columnSql;
}
$sql = 'CREATE TABLE IF NOT EXISTS ' . $classMetadata->getTableName() . '( ' . implode(",\n", $columns) . ')';
$statement = $connection->query($sql);
} else {
$schemaTool->updateSchema(array($classMetadata), true);
}
}
} | [
"public",
"static",
"function",
"checkAndCreateTableByEntityName",
"(",
"ContainerInterface",
"$",
"container",
",",
"$",
"className",
",",
"$",
"force",
"=",
"false",
")",
"{",
"/** @var Registry $doctrine */",
"/** @var Connection $connection */",
"/** @var ClassMetadata $c... | Check and create table if not exists
@param ContainerInterface $container ContainerInterface Container
@param $className String Name of the ORM class
@param bool $force bool Force update table | [
"Check",
"and",
"create",
"table",
"if",
"not",
"exists"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/CoreBundle/Doctrine/DoctrineHelper.php#L25-L83 | train |
xdan/jodit-connector-application | src/Application.php | Application.actionFiles | public function actionFiles() {
$sources = [];
$currentSource = $this->getSource();
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $currentSource !== $source && $this->request->path !== './') {
continue;
}
if ($this->accessControl->isAllow($this->getUserRole(), $this->action, $source->getPath())) {
$sources[$key] = $this->read($source);
}
}
return [
'sources' => $sources
];
} | php | public function actionFiles() {
$sources = [];
$currentSource = $this->getSource();
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $currentSource !== $source && $this->request->path !== './') {
continue;
}
if ($this->accessControl->isAllow($this->getUserRole(), $this->action, $source->getPath())) {
$sources[$key] = $this->read($source);
}
}
return [
'sources' => $sources
];
} | [
"public",
"function",
"actionFiles",
"(",
")",
"{",
"$",
"sources",
"=",
"[",
"]",
";",
"$",
"currentSource",
"=",
"$",
"this",
"->",
"getSource",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"config",
"->",
"sources",
"as",
"$",
"key",
"=>",
... | Load all files from folder ore source or sources | [
"Load",
"all",
"files",
"from",
"folder",
"ore",
"source",
"or",
"sources"
] | a1f8ebf2d605665fb25e737d60a62ea410358c62 | https://github.com/xdan/jodit-connector-application/blob/a1f8ebf2d605665fb25e737d60a62ea410358c62/src/Application.php#L17-L37 | train |
xdan/jodit-connector-application | src/Application.php | Application.actionFolders | public function actionFolders() {
$sources = [];
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$path = $source->getPath();
try {
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);
} catch (\Exception $e) {
continue;
}
$sourceData = (object)[
'baseurl' => $source->baseurl,
'path' => str_replace(realpath($source->getRoot()) . Consts::DS, '', $path),
'folders' => [],
];
$sourceData->folders[] = $path == $source->getRoot() ? '.' : '..';
$dir = opendir($path);
while ($file = readdir($dir)) {
if (
$file != '.' &&
$file != '..' &&
is_dir($path . $file) and
(
!$this->config->createThumb ||
$file !== $this->config->thumbFolderName
) and
!in_array($file, $this->config->excludeDirectoryNames)
) {
$sourceData->folders[] = $file;
}
}
$sources[$key] = $sourceData;
}
return [
'sources' => $sources
];
} | php | public function actionFolders() {
$sources = [];
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$path = $source->getPath();
try {
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $path);
} catch (\Exception $e) {
continue;
}
$sourceData = (object)[
'baseurl' => $source->baseurl,
'path' => str_replace(realpath($source->getRoot()) . Consts::DS, '', $path),
'folders' => [],
];
$sourceData->folders[] = $path == $source->getRoot() ? '.' : '..';
$dir = opendir($path);
while ($file = readdir($dir)) {
if (
$file != '.' &&
$file != '..' &&
is_dir($path . $file) and
(
!$this->config->createThumb ||
$file !== $this->config->thumbFolderName
) and
!in_array($file, $this->config->excludeDirectoryNames)
) {
$sourceData->folders[] = $file;
}
}
$sources[$key] = $sourceData;
}
return [
'sources' => $sources
];
} | [
"public",
"function",
"actionFolders",
"(",
")",
"{",
"$",
"sources",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"config",
"->",
"sources",
"as",
"$",
"key",
"=>",
"$",
"source",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"request",
"->",
... | Load all folders from folder ore source or sources | [
"Load",
"all",
"folders",
"from",
"folder",
"ore",
"source",
"or",
"sources"
] | a1f8ebf2d605665fb25e737d60a62ea410358c62 | https://github.com/xdan/jodit-connector-application/blob/a1f8ebf2d605665fb25e737d60a62ea410358c62/src/Application.php#L42-L87 | train |
xdan/jodit-connector-application | src/Application.php | Application.actionFileUploadRemote | public function actionFileUploadRemote() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need url parameter', Consts::ERROR_CODE_BAD_REQUEST);
}
$result = parse_url($url);
if (!isset($result['host']) || !isset($result['path'])) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$filename = Helper::makeSafe(basename($result['path']));
if (!$filename) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$source = $this->config->getCompatibleSource($this->request->source);
Helper::downloadRemoteFile($url, $source->getRoot() . $filename);
$file = new File($source->getRoot() . $filename);
try {
if (!$file->isGoodFile($source)) {
throw new \Exception('Bad file', Consts::ERROR_CODE_FORBIDDEN);
}
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), $file->getExtension());
} catch (\Exception $e) {
$file->remove();
throw $e;
}
return [
'newfilename' => $file->getName(),
'baseurl' => $source->baseurl,
];
} | php | public function actionFileUploadRemote() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need url parameter', Consts::ERROR_CODE_BAD_REQUEST);
}
$result = parse_url($url);
if (!isset($result['host']) || !isset($result['path'])) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$filename = Helper::makeSafe(basename($result['path']));
if (!$filename) {
throw new \Exception('Not valid URL', Consts::ERROR_CODE_BAD_REQUEST);
}
$source = $this->config->getCompatibleSource($this->request->source);
Helper::downloadRemoteFile($url, $source->getRoot() . $filename);
$file = new File($source->getRoot() . $filename);
try {
if (!$file->isGoodFile($source)) {
throw new \Exception('Bad file', Consts::ERROR_CODE_FORBIDDEN);
}
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $source->getRoot(), $file->getExtension());
} catch (\Exception $e) {
$file->remove();
throw $e;
}
return [
'newfilename' => $file->getName(),
'baseurl' => $source->baseurl,
];
} | [
"public",
"function",
"actionFileUploadRemote",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"request",
"->",
"url",
";",
"if",
"(",
"!",
"$",
"url",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Need url parameter'",
",",
"Consts",
"::",
"... | Load remote image by URL to self host
@throws \Exception | [
"Load",
"remote",
"image",
"by",
"URL",
"to",
"self",
"host"
] | a1f8ebf2d605665fb25e737d60a62ea410358c62 | https://github.com/xdan/jodit-connector-application/blob/a1f8ebf2d605665fb25e737d60a62ea410358c62/src/Application.php#L93-L133 | train |
xdan/jodit-connector-application | src/Application.php | Application.movePath | private function movePath() {
$source = $this->getSource();
$destinationPath = $source->getPath();
$sourcePath = $source->getPath($this->request->from);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $destinationPath);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $sourcePath);
if ($sourcePath) {
if ($destinationPath) {
if (is_file($sourcePath) or is_dir($sourcePath)) {
rename($sourcePath, $destinationPath . basename($sourcePath));
} else {
throw new \Exception('Not file', Consts::ERROR_CODE_NOT_EXISTS);
}
} else {
throw new \Exception('Need destination path', Consts::ERROR_CODE_BAD_REQUEST);
}
} else {
throw new \Exception('Need source path', Consts::ERROR_CODE_BAD_REQUEST);
}
} | php | private function movePath() {
$source = $this->getSource();
$destinationPath = $source->getPath();
$sourcePath = $source->getPath($this->request->from);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $destinationPath);
$this->accessControl->checkPermission($this->getUserRole(), $this->action, $sourcePath);
if ($sourcePath) {
if ($destinationPath) {
if (is_file($sourcePath) or is_dir($sourcePath)) {
rename($sourcePath, $destinationPath . basename($sourcePath));
} else {
throw new \Exception('Not file', Consts::ERROR_CODE_NOT_EXISTS);
}
} else {
throw new \Exception('Need destination path', Consts::ERROR_CODE_BAD_REQUEST);
}
} else {
throw new \Exception('Need source path', Consts::ERROR_CODE_BAD_REQUEST);
}
} | [
"private",
"function",
"movePath",
"(",
")",
"{",
"$",
"source",
"=",
"$",
"this",
"->",
"getSource",
"(",
")",
";",
"$",
"destinationPath",
"=",
"$",
"source",
"->",
"getPath",
"(",
")",
";",
"$",
"sourcePath",
"=",
"$",
"source",
"->",
"getPath",
"... | Move file or directory to another folder
@throws \Exception | [
"Move",
"file",
"or",
"directory",
"to",
"another",
"folder"
] | a1f8ebf2d605665fb25e737d60a62ea410358c62 | https://github.com/xdan/jodit-connector-application/blob/a1f8ebf2d605665fb25e737d60a62ea410358c62/src/Application.php#L279-L300 | train |
xdan/jodit-connector-application | src/Application.php | Application.actionGetLocalFileByUrl | public function actionGetLocalFileByUrl() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need full url', Consts::ERROR_CODE_BAD_REQUEST);
}
$parts = parse_url($url);
if (empty($parts['path'])) {
throw new \Exception('Empty url', Consts::ERROR_CODE_BAD_REQUEST);
}
$found = false;
$path = '';
$root = '';
$key = 0;
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$base = parse_url($source->baseurl);
$path = preg_replace('#^(/)?' . $base['path'] . '#', '', $parts['path']);
$root = $source->getPath();
if (file_exists($root . $path) && is_file($root . $path)) {
$file = new File($root . $path);
if ($file->isGoodFile($source)) {
$found = true;
break;
}
}
}
if (!$found) {
throw new \Exception('File does not exist or is above the root of the connector', Consts::ERROR_CODE_FAILED);
}
return [
'path' => str_replace($root, '', dirname($root . $path) . Consts::DS),
'name' => basename($path),
'source' => $key
];
} | php | public function actionGetLocalFileByUrl() {
$url = $this->request->url;
if (!$url) {
throw new \Exception('Need full url', Consts::ERROR_CODE_BAD_REQUEST);
}
$parts = parse_url($url);
if (empty($parts['path'])) {
throw new \Exception('Empty url', Consts::ERROR_CODE_BAD_REQUEST);
}
$found = false;
$path = '';
$root = '';
$key = 0;
foreach ($this->config->sources as $key => $source) {
if ($this->request->source && $this->request->source !== 'default' && $key !== $this->request->source && $this->request->path !== './') {
continue;
}
$base = parse_url($source->baseurl);
$path = preg_replace('#^(/)?' . $base['path'] . '#', '', $parts['path']);
$root = $source->getPath();
if (file_exists($root . $path) && is_file($root . $path)) {
$file = new File($root . $path);
if ($file->isGoodFile($source)) {
$found = true;
break;
}
}
}
if (!$found) {
throw new \Exception('File does not exist or is above the root of the connector', Consts::ERROR_CODE_FAILED);
}
return [
'path' => str_replace($root, '', dirname($root . $path) . Consts::DS),
'name' => basename($path),
'source' => $key
];
} | [
"public",
"function",
"actionGetLocalFileByUrl",
"(",
")",
"{",
"$",
"url",
"=",
"$",
"this",
"->",
"request",
"->",
"url",
";",
"if",
"(",
"!",
"$",
"url",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Need full url'",
",",
"Consts",
"::",
"ERRO... | Get filepath by URL for local files
@metod actionGetFileByURL | [
"Get",
"filepath",
"by",
"URL",
"for",
"local",
"files"
] | a1f8ebf2d605665fb25e737d60a62ea410358c62 | https://github.com/xdan/jodit-connector-application/blob/a1f8ebf2d605665fb25e737d60a62ea410358c62/src/Application.php#L378-L426 | train |
manaphp/framework | Model.php | Model.getSource | public function getSource($context = null)
{
$class = static::class;
return Text::underscore(($pos = strrpos($class, '\\')) === false ? $class : substr($class, $pos + 1));
} | php | public function getSource($context = null)
{
$class = static::class;
return Text::underscore(($pos = strrpos($class, '\\')) === false ? $class : substr($class, $pos + 1));
} | [
"public",
"function",
"getSource",
"(",
"$",
"context",
"=",
"null",
")",
"{",
"$",
"class",
"=",
"static",
"::",
"class",
";",
"return",
"Text",
"::",
"underscore",
"(",
"(",
"$",
"pos",
"=",
"strrpos",
"(",
"$",
"class",
",",
"'\\\\'",
")",
")",
... | Returns table name mapped in the model
@param mixed $context
@return string | [
"Returns",
"table",
"name",
"mapped",
"in",
"the",
"model"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L117-L121 | train |
manaphp/framework | Model.php | Model.last | public static function last($filters = null, $fields = null)
{
$model = new static();
if (is_string($primaryKey = $model->getPrimaryKey())) {
$options['order'] = [$primaryKey => SORT_DESC];
} else {
throw new BadMethodCallException('infer `:class` order condition for last failed:', ['class' => static::class]);
}
$rs = static::query(null, $model)->select($fields)->where($filters)->limit(1)->fetch();
return isset($rs[0]) ? $rs[0] : null;
} | php | public static function last($filters = null, $fields = null)
{
$model = new static();
if (is_string($primaryKey = $model->getPrimaryKey())) {
$options['order'] = [$primaryKey => SORT_DESC];
} else {
throw new BadMethodCallException('infer `:class` order condition for last failed:', ['class' => static::class]);
}
$rs = static::query(null, $model)->select($fields)->where($filters)->limit(1)->fetch();
return isset($rs[0]) ? $rs[0] : null;
} | [
"public",
"static",
"function",
"last",
"(",
"$",
"filters",
"=",
"null",
",",
"$",
"fields",
"=",
"null",
")",
"{",
"$",
"model",
"=",
"new",
"static",
"(",
")",
";",
"if",
"(",
"is_string",
"(",
"$",
"primaryKey",
"=",
"$",
"model",
"->",
"getPri... | Allows to query the last record that match the specified conditions
@param array $filters =static::sample()
@param array $fields =static::sample()
@return static|null | [
"Allows",
"to",
"query",
"the",
"last",
"record",
"that",
"match",
"the",
"specified",
"conditions"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L364-L376 | train |
manaphp/framework | Model.php | Model.avg | public static function avg($field, $filters = null)
{
return (float)static::query()->where($filters)->avg($field);
} | php | public static function avg($field, $filters = null)
{
return (float)static::query()->where($filters)->avg($field);
} | [
"public",
"static",
"function",
"avg",
"(",
"$",
"field",
",",
"$",
"filters",
"=",
"null",
")",
"{",
"return",
"(",
"float",
")",
"static",
"::",
"query",
"(",
")",
"->",
"where",
"(",
"$",
"filters",
")",
"->",
"avg",
"(",
"$",
"field",
")",
";... | Allows to calculate the average value on a column matching the specified conditions
@param string $field =array_keys(static::sample())[$i]
@param array $filters =static::sample()
@return float|null | [
"Allows",
"to",
"calculate",
"the",
"average",
"value",
"on",
"a",
"column",
"matching",
"the",
"specified",
"conditions"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L550-L553 | train |
manaphp/framework | Model.php | Model.assign | public function assign($data, $whiteList = null)
{
if ($whiteList === null) {
$whiteList = $this->getSafeFields();
}
if ($whiteList === null) {
throw new PreconditionException(['`:model` model do not define accessible fields.', 'model' => static::class]);
}
foreach ($whiteList ?: $this->getFields() as $field) {
if (isset($data[$field])) {
$value = $data[$field];
$this->{$field} = is_string($value) ? trim($value) : $value;
}
}
return $this;
} | php | public function assign($data, $whiteList = null)
{
if ($whiteList === null) {
$whiteList = $this->getSafeFields();
}
if ($whiteList === null) {
throw new PreconditionException(['`:model` model do not define accessible fields.', 'model' => static::class]);
}
foreach ($whiteList ?: $this->getFields() as $field) {
if (isset($data[$field])) {
$value = $data[$field];
$this->{$field} = is_string($value) ? trim($value) : $value;
}
}
return $this;
} | [
"public",
"function",
"assign",
"(",
"$",
"data",
",",
"$",
"whiteList",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"whiteList",
"===",
"null",
")",
"{",
"$",
"whiteList",
"=",
"$",
"this",
"->",
"getSafeFields",
"(",
")",
";",
"}",
"if",
"(",
"$",
"... | Assigns values to a model from an array
@param array $data
@param array $whiteList =static::sample()
@return static | [
"Assigns",
"values",
"to",
"a",
"model",
"from",
"an",
"array"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L563-L581 | train |
manaphp/framework | Model.php | Model.delete | public function delete()
{
$this->eventsManager->fireEvent('model:beforeDelete', $this);
static::query(null, $this)->where($this->_getPrimaryKeyValuePairs())->delete();
$this->eventsManager->fireEvent('model:afterDelete', $this);
return $this;
} | php | public function delete()
{
$this->eventsManager->fireEvent('model:beforeDelete', $this);
static::query(null, $this)->where($this->_getPrimaryKeyValuePairs())->delete();
$this->eventsManager->fireEvent('model:afterDelete', $this);
return $this;
} | [
"public",
"function",
"delete",
"(",
")",
"{",
"$",
"this",
"->",
"eventsManager",
"->",
"fireEvent",
"(",
"'model:beforeDelete'",
",",
"$",
"this",
")",
";",
"static",
"::",
"query",
"(",
"null",
",",
"$",
"this",
")",
"->",
"where",
"(",
"$",
"this",... | Deletes a model instance. Returning true on success or false otherwise.
@return static | [
"Deletes",
"a",
"model",
"instance",
".",
"Returning",
"true",
"on",
"success",
"or",
"false",
"otherwise",
"."
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L763-L772 | train |
manaphp/framework | Model.php | Model.toArray | public function toArray()
{
$data = [];
foreach (get_object_vars($this) as $field => $value) {
if ($field[0] === '_') {
continue;
}
if (is_object($value)) {
if ($value instanceof self) {
$value = $value->toArray();
} else {
continue;
}
} elseif (is_array($value) && ($first = current($value)) && $first instanceof self) {
foreach ($value as $k => $v) {
$value[$k] = $v->toArray();
}
}
if ($value !== null) {
$data[$field] = $value;
}
}
return $data;
} | php | public function toArray()
{
$data = [];
foreach (get_object_vars($this) as $field => $value) {
if ($field[0] === '_') {
continue;
}
if (is_object($value)) {
if ($value instanceof self) {
$value = $value->toArray();
} else {
continue;
}
} elseif (is_array($value) && ($first = current($value)) && $first instanceof self) {
foreach ($value as $k => $v) {
$value[$k] = $v->toArray();
}
}
if ($value !== null) {
$data[$field] = $value;
}
}
return $data;
} | [
"public",
"function",
"toArray",
"(",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"get_object_vars",
"(",
"$",
"this",
")",
"as",
"$",
"field",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"field",
"[",
"0",
"]",
"===",
"'_'",
"... | Returns the instance as an array representation
@return array | [
"Returns",
"the",
"instance",
"as",
"an",
"array",
"representation"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L836-L863 | train |
manaphp/framework | Model.php | Model.getChangedFields | public function getChangedFields()
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
$changed = [];
foreach ($this->getFields() as $field) {
if (isset($this->_snapshot[$field])) {
if ($this->{$field} !== $this->_snapshot[$field]) {
$changed[] = $field;
}
} elseif ($this->$field !== null) {
$changed[] = $field;
}
}
return $changed;
} | php | public function getChangedFields()
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
$changed = [];
foreach ($this->getFields() as $field) {
if (isset($this->_snapshot[$field])) {
if ($this->{$field} !== $this->_snapshot[$field]) {
$changed[] = $field;
}
} elseif ($this->$field !== null) {
$changed[] = $field;
}
}
return $changed;
} | [
"public",
"function",
"getChangedFields",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_snapshot",
"===",
"false",
")",
"{",
"throw",
"new",
"PreconditionException",
"(",
"[",
"'getChangedFields failed: `:model` instance is snapshot disabled'",
",",
"'model'",
"=>",
... | Returns a list of changed values
@return array | [
"Returns",
"a",
"list",
"of",
"changed",
"values"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L894-L913 | train |
manaphp/framework | Model.php | Model.hasChanged | public function hasChanged($fields)
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
/** @noinspection ForeachSourceInspection */
foreach ((array)$fields as $field) {
if (!isset($this->_snapshot[$field]) || $this->{$field} !== $this->_snapshot[$field]) {
return true;
}
}
return false;
} | php | public function hasChanged($fields)
{
if ($this->_snapshot === false) {
throw new PreconditionException(['getChangedFields failed: `:model` instance is snapshot disabled', 'model' => static::class]);
}
/** @noinspection ForeachSourceInspection */
foreach ((array)$fields as $field) {
if (!isset($this->_snapshot[$field]) || $this->{$field} !== $this->_snapshot[$field]) {
return true;
}
}
return false;
} | [
"public",
"function",
"hasChanged",
"(",
"$",
"fields",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"_snapshot",
"===",
"false",
")",
"{",
"throw",
"new",
"PreconditionException",
"(",
"[",
"'getChangedFields failed: `:model` instance is snapshot disabled'",
",",
"'mode... | Check if a specific attribute has changed
This only works if the model is keeping data snapshots
@param string|array $fields
@return bool | [
"Check",
"if",
"a",
"specific",
"attribute",
"has",
"changed",
"This",
"only",
"works",
"if",
"the",
"model",
"is",
"keeping",
"data",
"snapshots"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Model.php#L923-L937 | train |
Erdiko/users | src/models/User.php | User.hasRole | public function hasRole($role = "general")
{
$roleModel = new \erdiko\users\models\Role;
$roleEntity = $roleModel->findByName($role);
if (empty($roleEntity)) {
throw new \Exception("Error, role {$role} not found.");
}
$result = $this->_user->getRole() == $roleEntity->getId();
return $result;
} | php | public function hasRole($role = "general")
{
$roleModel = new \erdiko\users\models\Role;
$roleEntity = $roleModel->findByName($role);
if (empty($roleEntity)) {
throw new \Exception("Error, role {$role} not found.");
}
$result = $this->_user->getRole() == $roleEntity->getId();
return $result;
} | [
"public",
"function",
"hasRole",
"(",
"$",
"role",
"=",
"\"general\"",
")",
"{",
"$",
"roleModel",
"=",
"new",
"\\",
"erdiko",
"\\",
"users",
"\\",
"models",
"\\",
"Role",
";",
"$",
"roleEntity",
"=",
"$",
"roleModel",
"->",
"findByName",
"(",
"$",
"ro... | hasRole
returns true if current user has requested role
@param string
@return bool | [
"hasRole",
"returns",
"true",
"if",
"current",
"user",
"has",
"requested",
"role"
] | a063e0c61ceccdbfeaf7750e92bac8c3565c39a9 | https://github.com/Erdiko/users/blob/a063e0c61ceccdbfeaf7750e92bac8c3565c39a9/src/models/User.php#L275-L285 | train |
Erdiko/users | src/models/User.php | User.save | public function save($data=array())
{
if (empty($data)) {
throw new \Exception( "User data is missing" );
}
$data = (object) $data;
if ((!isset($data->email) || empty($data->email))) {
throw new \Exception( "Email is required" );
}
if ((!isset($data->password) || empty($data->password)) && !isset($data->id)) {
throw new \Exception( "Password is required" );
}
$new = false;
if (isset($data->id)) {
$entity = $this->getById($data->id);
} else {
$entity = new entity();
$new = true;
}
if (isset($data->name)) {
$entity->setName($data->name);
}
if (isset($data->email)) {
$entity->setEmail($data->email);
}
if (isset($data->password)) {
$entity->setPassword($this->getSalted($data->password));
} elseif (isset($data->new_password)){
$entity->setPassword($this->getSalted($data->new_password));
}
if (empty($data->role)) {
$data->role = $this->_getDefaultRole();
}
$entity->setRole($data->role);
if (isset($data->gateway_customer_id)) {
$entity->setGatewayCustomerId($data->gateway_customer_id);
}
if ($new) {
$this->_em->persist($entity);
} else {
$this->_em->merge($entity);
}
// Save the entity
try {
$eventType = $new ? Log::EVENT_CREATE : Log::EVENT_UPDATE;
if(isset($data->new_password)){
$eventType = Log::EVENT_PASSWORD;
unset($data->new_password);
}
unset($data->password);
$this->createUserEventLog($eventType, $data);
$this->_em->flush();
$this->setEntity($entity);
return $entity->getId();
} catch ( \Doctrine\DBAL\Exception\UniqueConstraintViolationException $e ) {
// \Erdiko::log(\Psr\Log\LogLevel::INFO, 'UniqueConstraintViolationException caught: '.$e->getMessage());
throw new \Exception( "Can not create user with duplicate email" );
}
return null;
} | php | public function save($data=array())
{
if (empty($data)) {
throw new \Exception( "User data is missing" );
}
$data = (object) $data;
if ((!isset($data->email) || empty($data->email))) {
throw new \Exception( "Email is required" );
}
if ((!isset($data->password) || empty($data->password)) && !isset($data->id)) {
throw new \Exception( "Password is required" );
}
$new = false;
if (isset($data->id)) {
$entity = $this->getById($data->id);
} else {
$entity = new entity();
$new = true;
}
if (isset($data->name)) {
$entity->setName($data->name);
}
if (isset($data->email)) {
$entity->setEmail($data->email);
}
if (isset($data->password)) {
$entity->setPassword($this->getSalted($data->password));
} elseif (isset($data->new_password)){
$entity->setPassword($this->getSalted($data->new_password));
}
if (empty($data->role)) {
$data->role = $this->_getDefaultRole();
}
$entity->setRole($data->role);
if (isset($data->gateway_customer_id)) {
$entity->setGatewayCustomerId($data->gateway_customer_id);
}
if ($new) {
$this->_em->persist($entity);
} else {
$this->_em->merge($entity);
}
// Save the entity
try {
$eventType = $new ? Log::EVENT_CREATE : Log::EVENT_UPDATE;
if(isset($data->new_password)){
$eventType = Log::EVENT_PASSWORD;
unset($data->new_password);
}
unset($data->password);
$this->createUserEventLog($eventType, $data);
$this->_em->flush();
$this->setEntity($entity);
return $entity->getId();
} catch ( \Doctrine\DBAL\Exception\UniqueConstraintViolationException $e ) {
// \Erdiko::log(\Psr\Log\LogLevel::INFO, 'UniqueConstraintViolationException caught: '.$e->getMessage());
throw new \Exception( "Can not create user with duplicate email" );
}
return null;
} | [
"public",
"function",
"save",
"(",
"$",
"data",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"data",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"\"User data is missing\"",
")",
";",
"}",
"$",
"data",
"=",
"(",
"object... | Update or create a new user
@param $data
@return int
@throws \Exception | [
"Update",
"or",
"create",
"a",
"new",
"user"
] | a063e0c61ceccdbfeaf7750e92bac8c3565c39a9 | https://github.com/Erdiko/users/blob/a063e0c61ceccdbfeaf7750e92bac8c3565c39a9/src/models/User.php#L413-L481 | train |
manaphp/framework | Db/Model.php | Model.create | public function create()
{
$autoIncrementField = $this->getAutoIncrementField();
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = $this->getNextAutoIncrementId();
}
$fields = $this->getFields();
foreach ($this->getAutoFilledData(self::OP_CREATE) as $field => $value) {
/** @noinspection NotOptimalIfConditionsInspection */
if (!in_array($field, $fields, true) || $this->$field !== null) {
continue;
}
$this->$field = $value;
}
$this->validate($fields);
$this->eventsManager->fireEvent('model:beforeSave', $this);
$this->eventsManager->fireEvent('model:beforeCreate', $this);
$fieldValues = [];
$defaultValueFields = [];
foreach ($fields as $field) {
if ($this->$field !== null) {
$fieldValues[$field] = $this->$field;
} elseif ($field !== $autoIncrementField) {
$defaultValueFields[] = $field;
}
}
foreach ($this->getJsonFields() as $field) {
if (is_array($this->$field)) {
$fieldValues[$field] = json_encode($this->$field, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* @var \ManaPHP\DbInterface $connection
*/
$connection = $this->_di->getShared($this->getDb($this));
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = (int)$connection->insert($this->getSource($this), $fieldValues, true);
} else {
$connection->insert($this->getSource($this), $fieldValues);
}
if ($defaultValueFields) {
if ($r = static::query(null, $this)->select($defaultValueFields)->where($this->_getPrimaryKeyValuePairs())->fetch(true)) {
foreach ($r[0] as $field => $value) {
$this->$field = $value;
}
}
}
$this->_snapshot = $this->toArray();
$this->eventsManager->fireEvent('model:afterCreate', $this);
$this->eventsManager->fireEvent('model:afterSave', $this);
return $this;
} | php | public function create()
{
$autoIncrementField = $this->getAutoIncrementField();
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = $this->getNextAutoIncrementId();
}
$fields = $this->getFields();
foreach ($this->getAutoFilledData(self::OP_CREATE) as $field => $value) {
/** @noinspection NotOptimalIfConditionsInspection */
if (!in_array($field, $fields, true) || $this->$field !== null) {
continue;
}
$this->$field = $value;
}
$this->validate($fields);
$this->eventsManager->fireEvent('model:beforeSave', $this);
$this->eventsManager->fireEvent('model:beforeCreate', $this);
$fieldValues = [];
$defaultValueFields = [];
foreach ($fields as $field) {
if ($this->$field !== null) {
$fieldValues[$field] = $this->$field;
} elseif ($field !== $autoIncrementField) {
$defaultValueFields[] = $field;
}
}
foreach ($this->getJsonFields() as $field) {
if (is_array($this->$field)) {
$fieldValues[$field] = json_encode($this->$field, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
/**
* @var \ManaPHP\DbInterface $connection
*/
$connection = $this->_di->getShared($this->getDb($this));
if ($autoIncrementField && $this->$autoIncrementField === null) {
$this->$autoIncrementField = (int)$connection->insert($this->getSource($this), $fieldValues, true);
} else {
$connection->insert($this->getSource($this), $fieldValues);
}
if ($defaultValueFields) {
if ($r = static::query(null, $this)->select($defaultValueFields)->where($this->_getPrimaryKeyValuePairs())->fetch(true)) {
foreach ($r[0] as $field => $value) {
$this->$field = $value;
}
}
}
$this->_snapshot = $this->toArray();
$this->eventsManager->fireEvent('model:afterCreate', $this);
$this->eventsManager->fireEvent('model:afterSave', $this);
return $this;
} | [
"public",
"function",
"create",
"(",
")",
"{",
"$",
"autoIncrementField",
"=",
"$",
"this",
"->",
"getAutoIncrementField",
"(",
")",
";",
"if",
"(",
"$",
"autoIncrementField",
"&&",
"$",
"this",
"->",
"$",
"autoIncrementField",
"===",
"null",
")",
"{",
"$"... | Inserts a model instance. If the instance already exists in the persistence it will throw an exception
@return static | [
"Inserts",
"a",
"model",
"instance",
".",
"If",
"the",
"instance",
"already",
"exists",
"in",
"the",
"persistence",
"it",
"will",
"throw",
"an",
"exception"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Db/Model.php#L146-L208 | train |
Erdiko/users | src/controllers/UserAjax.php | UserAjax.checkAuth | protected function checkAuth()
{
try {
// get the JWT from the headers
list($jwt) = sscanf($_SERVER["HTTP_AUTHORIZATION"], 'Bearer %s');
// init the jwt auth class
$authenticator = new JWTAuthenticator(new User());
// get the application secret key
$config = \Erdiko::getConfig();
$secretKey = $config["site"]["secret_key"];
// collect login params
$params = array(
'secret_key' => $secretKey,
'jwt' => $jwt
);
$user = $authenticator->verify($params, 'jwt_auth');
//TODO check the user's permissions via Resource & Authorization
// no exceptions? welp, this is a valid request
return true;
} catch (\Exception $e) {
return true;
}
} | php | protected function checkAuth()
{
try {
// get the JWT from the headers
list($jwt) = sscanf($_SERVER["HTTP_AUTHORIZATION"], 'Bearer %s');
// init the jwt auth class
$authenticator = new JWTAuthenticator(new User());
// get the application secret key
$config = \Erdiko::getConfig();
$secretKey = $config["site"]["secret_key"];
// collect login params
$params = array(
'secret_key' => $secretKey,
'jwt' => $jwt
);
$user = $authenticator->verify($params, 'jwt_auth');
//TODO check the user's permissions via Resource & Authorization
// no exceptions? welp, this is a valid request
return true;
} catch (\Exception $e) {
return true;
}
} | [
"protected",
"function",
"checkAuth",
"(",
")",
"{",
"try",
"{",
"// get the JWT from the headers",
"list",
"(",
"$",
"jwt",
")",
"=",
"sscanf",
"(",
"$",
"_SERVER",
"[",
"\"HTTP_AUTHORIZATION\"",
"]",
",",
"'Bearer %s'",
")",
";",
"// init the jwt auth class",
... | It always returns true because login is not a must in this section, but we still want to create authenticator
instance if there's a logged in user to restrict some actions.
@return bool | [
"It",
"always",
"returns",
"true",
"because",
"login",
"is",
"not",
"a",
"must",
"in",
"this",
"section",
"but",
"we",
"still",
"want",
"to",
"create",
"authenticator",
"instance",
"if",
"there",
"s",
"a",
"logged",
"in",
"user",
"to",
"restrict",
"some",
... | a063e0c61ceccdbfeaf7750e92bac8c3565c39a9 | https://github.com/Erdiko/users/blob/a063e0c61ceccdbfeaf7750e92bac8c3565c39a9/src/controllers/UserAjax.php#L32-L61 | train |
fezfez/codeGenerator | src/CrudGenerator/Context/EngineDataForQuestion.php | EngineDataForQuestion.setShutdownWithoutResponse | public function setShutdownWithoutResponse($value, $customeExceptionMessage = null)
{
$this->shutdownWithoutResponse = $value;
$this->customeExceptionMessage = $customeExceptionMessage;
return $this;
} | php | public function setShutdownWithoutResponse($value, $customeExceptionMessage = null)
{
$this->shutdownWithoutResponse = $value;
$this->customeExceptionMessage = $customeExceptionMessage;
return $this;
} | [
"public",
"function",
"setShutdownWithoutResponse",
"(",
"$",
"value",
",",
"$",
"customeExceptionMessage",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"shutdownWithoutResponse",
"=",
"$",
"value",
";",
"$",
"this",
"->",
"customeExceptionMessage",
"=",
"$",
"cust... | If no response provided, Exception of type
CrudGenerator\Generators\ResponseExpectedException
will be throw
@param boolean $value
@param string $customeExceptionMessage
@return \CrudGenerator\Context\EngineDataForQuestion | [
"If",
"no",
"response",
"provided",
"Exception",
"of",
"type",
"CrudGenerator",
"\\",
"Generators",
"\\",
"ResponseExpectedException",
"will",
"be",
"throw"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Context/EngineDataForQuestion.php#L75-L81 | train |
wodby/wodby-sdk-php | SwaggerClient-php/lib/Client/TaskApi.php | TaskApi.getTaskRequest | protected function getTaskRequest($id)
{
// verify the required parameter 'id' is set
if ($id === null) {
throw new \InvalidArgumentException(
'Missing the required parameter $id when calling getTask'
);
}
$resourcePath = '/tasks/{id}';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// path params
if ($id !== null) {
$resourcePath = str_replace(
'{' . 'id' . '}',
ObjectSerializer::toPathValue($id),
$resourcePath
);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
// this endpoint requires API key authentication
$apiKey = $this->config->getApiKeyWithPrefix('X-API-KEY');
if ($apiKey !== null) {
$headers['X-API-KEY'] = $apiKey;
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
} | php | protected function getTaskRequest($id)
{
// verify the required parameter 'id' is set
if ($id === null) {
throw new \InvalidArgumentException(
'Missing the required parameter $id when calling getTask'
);
}
$resourcePath = '/tasks/{id}';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
// path params
if ($id !== null) {
$resourcePath = str_replace(
'{' . 'id' . '}',
ObjectSerializer::toPathValue($id),
$resourcePath
);
}
// body params
$_tempBody = null;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json']
);
}
// for model (json/xml)
if (isset($_tempBody)) {
// $_tempBody is the method argument, if present
$httpBody = $_tempBody;
// \stdClass has no __toString(), so we should encode it manually
if ($httpBody instanceof \stdClass && $headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($httpBody);
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValue
];
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
// this endpoint requires API key authentication
$apiKey = $this->config->getApiKeyWithPrefix('X-API-KEY');
if ($apiKey !== null) {
$headers['X-API-KEY'] = $apiKey;
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'GET',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
} | [
"protected",
"function",
"getTaskRequest",
"(",
"$",
"id",
")",
"{",
"// verify the required parameter 'id' is set",
"if",
"(",
"$",
"id",
"===",
"null",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Missing the required parameter $id when calling get... | Create request for operation 'getTask'
@param string $id Task ID (required)
@throws \InvalidArgumentException
@return \GuzzleHttp\Psr7\Request | [
"Create",
"request",
"for",
"operation",
"getTask"
] | affe52fcf7392c6f40ed275f34f85eb13095d5ff | https://github.com/wodby/wodby-sdk-php/blob/affe52fcf7392c6f40ed275f34f85eb13095d5ff/SwaggerClient-php/lib/Client/TaskApi.php#L253-L346 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController.nodeAction | public function nodeAction()
{
//wyłączenie layout
FrontController::getInstance()->getView()->setLayoutDisabled();
//id węzła rodzica
$this->view->parentId = ($this->parentId > 0) ? $this->parentId : null;
//pobranie drzewiastej struktury stron CMS
$this->view->categoryTree = (new \Cms\Model\CategoryModel)->getCategoryTree($this->view->parentId);
} | php | public function nodeAction()
{
//wyłączenie layout
FrontController::getInstance()->getView()->setLayoutDisabled();
//id węzła rodzica
$this->view->parentId = ($this->parentId > 0) ? $this->parentId : null;
//pobranie drzewiastej struktury stron CMS
$this->view->categoryTree = (new \Cms\Model\CategoryModel)->getCategoryTree($this->view->parentId);
} | [
"public",
"function",
"nodeAction",
"(",
")",
"{",
"//wyłączenie layout",
"FrontController",
"::",
"getInstance",
"(",
")",
"->",
"getView",
"(",
")",
"->",
"setLayoutDisabled",
"(",
")",
";",
"//id węzła rodzica",
"$",
"this",
"->",
"view",
"->",
"parentId",
... | Renderowanie fragmentu drzewa stron na podstawie parentId | [
"Renderowanie",
"fragmentu",
"drzewa",
"stron",
"na",
"podstawie",
"parentId"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L114-L122 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController.createAction | public function createAction()
{
$this->getResponse()->setTypeJson();
$cat = new \Cms\Orm\CmsCategoryRecord();
$cat->name = $this->getPost()->name;
$cat->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$cat->order = $this->getPost()->order;
$cat->active = false;
$cat->status = \Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE;
if ($cat->save()) {
$icon = '';
$disabled = false;
//ikona nieaktywnego wezla gdy nieaktywny
if (!$cat->active) {
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-inactive.png';
}
//sprawdzenie uprawnień do węzła
$acl = (new \CmsAdmin\Model\CategoryAclModel)->getAcl();
if (!$acl->isAllowed(\App\Registry::$auth->getRoles(), $cat->id)) {
$disabled = true;
//ikona zablokowanego wezla gdy brak uprawnien
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-disabled.png';
}
return json_encode([
'status' => true,
'id' => $cat->id,
'icon' => $icon,
'disabled' => $disabled,
'message' => $this->view->_('controller.category.create.message')
]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.create.error')]);
} | php | public function createAction()
{
$this->getResponse()->setTypeJson();
$cat = new \Cms\Orm\CmsCategoryRecord();
$cat->name = $this->getPost()->name;
$cat->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$cat->order = $this->getPost()->order;
$cat->active = false;
$cat->status = \Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE;
if ($cat->save()) {
$icon = '';
$disabled = false;
//ikona nieaktywnego wezla gdy nieaktywny
if (!$cat->active) {
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-inactive.png';
}
//sprawdzenie uprawnień do węzła
$acl = (new \CmsAdmin\Model\CategoryAclModel)->getAcl();
if (!$acl->isAllowed(\App\Registry::$auth->getRoles(), $cat->id)) {
$disabled = true;
//ikona zablokowanego wezla gdy brak uprawnien
$icon = $this->view->baseUrl . '/resource/cmsAdmin/images/folder-disabled.png';
}
return json_encode([
'status' => true,
'id' => $cat->id,
'icon' => $icon,
'disabled' => $disabled,
'message' => $this->view->_('controller.category.create.message')
]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.create.error')]);
} | [
"public",
"function",
"createAction",
"(",
")",
"{",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setTypeJson",
"(",
")",
";",
"$",
"cat",
"=",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsCategoryRecord",
"(",
")",
";",
"$",
"cat",
"->",
"name",... | Tworzenie nowej strony | [
"Tworzenie",
"nowej",
"strony"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L127-L159 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController.renameAction | public function renameAction()
{
$this->getResponse()->setTypeJson();
if (null !== $cat = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
$name = trim($this->getPost()->name);
if (mb_strlen($name) < 2 || mb_strlen($name) > 64) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.validator')]);
}
$cat->name = $name;
if ($cat->save()) {
return json_encode(['status' => true, 'id' => $cat->id, 'name' => $name, 'message' => $this->view->_('controller.category.rename.message')]);
}
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.error')]);
} | php | public function renameAction()
{
$this->getResponse()->setTypeJson();
if (null !== $cat = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
$name = trim($this->getPost()->name);
if (mb_strlen($name) < 2 || mb_strlen($name) > 64) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.validator')]);
}
$cat->name = $name;
if ($cat->save()) {
return json_encode(['status' => true, 'id' => $cat->id, 'name' => $name, 'message' => $this->view->_('controller.category.rename.message')]);
}
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.rename.error')]);
} | [
"public",
"function",
"renameAction",
"(",
")",
"{",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setTypeJson",
"(",
")",
";",
"if",
"(",
"null",
"!==",
"$",
"cat",
"=",
"(",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsCategoryQuery",
")",
"->",... | Zmiana nazwy strony | [
"Zmiana",
"nazwy",
"strony"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L164-L178 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController.moveAction | public function moveAction()
{
$this->getResponse()->setTypeJson();
//brak kategorii
if (null === $masterCategory = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error.missing')]);
}
//domyślnie nie ma drafta - alias
$draft = $masterCategory;
//zmiana parenta tworzy draft
if ($this->getPost()->parentId != $masterCategory->parentId) {
//tworzenie draftu
$draft = (new \Cms\Model\CategoryDraft($masterCategory))->createAndGetDraftForUser(\App\Registry::$auth->getId(), true);
}
//zapis kolejności
$draft->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$draft->order = $this->getPost()->order;
//próba zapisu
return ($draft->save() && $draft->commitVersion()) ? json_encode(['status' => true, 'id' => $masterCategory->id, 'message' => $this->view->_('controller.category.move.message')]) : json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error')]);
} | php | public function moveAction()
{
$this->getResponse()->setTypeJson();
//brak kategorii
if (null === $masterCategory = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error.missing')]);
}
//domyślnie nie ma drafta - alias
$draft = $masterCategory;
//zmiana parenta tworzy draft
if ($this->getPost()->parentId != $masterCategory->parentId) {
//tworzenie draftu
$draft = (new \Cms\Model\CategoryDraft($masterCategory))->createAndGetDraftForUser(\App\Registry::$auth->getId(), true);
}
//zapis kolejności
$draft->parentId = ($this->getPost()->parentId > 0) ? $this->getPost()->parentId : null;
$draft->order = $this->getPost()->order;
//próba zapisu
return ($draft->save() && $draft->commitVersion()) ? json_encode(['status' => true, 'id' => $masterCategory->id, 'message' => $this->view->_('controller.category.move.message')]) : json_encode(['status' => false, 'error' => $this->view->_('controller.category.move.error')]);
} | [
"public",
"function",
"moveAction",
"(",
")",
"{",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setTypeJson",
"(",
")",
";",
"//brak kategorii",
"if",
"(",
"null",
"===",
"$",
"masterCategory",
"=",
"(",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"Cm... | Przenoszenie strony w drzewie | [
"Przenoszenie",
"strony",
"w",
"drzewie"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L183-L202 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController.copyAction | public function copyAction()
{
$this->getResponse()->setTypeJson();
if (null === $category = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => 'Strona nie istnieje']);
}
//model do kopiowania kategorii
$copyModel = new \Cms\Model\CategoryCopy($category);
//kopiowanie z transakcją
if ($copyModel->copyWithTransaction()) {
return json_encode(['status' => true, 'id' => $copyModel->getCopyRecord()->id, 'message' => $this->view->_('controller.category.copy.message')]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.copy.error')]);
} | php | public function copyAction()
{
$this->getResponse()->setTypeJson();
if (null === $category = (new \Cms\Orm\CmsCategoryQuery)->findPk($this->getPost()->id)) {
return json_encode(['status' => false, 'error' => 'Strona nie istnieje']);
}
//model do kopiowania kategorii
$copyModel = new \Cms\Model\CategoryCopy($category);
//kopiowanie z transakcją
if ($copyModel->copyWithTransaction()) {
return json_encode(['status' => true, 'id' => $copyModel->getCopyRecord()->id, 'message' => $this->view->_('controller.category.copy.message')]);
}
return json_encode(['status' => false, 'error' => $this->view->_('controller.category.copy.error')]);
} | [
"public",
"function",
"copyAction",
"(",
")",
"{",
"$",
"this",
"->",
"getResponse",
"(",
")",
"->",
"setTypeJson",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"category",
"=",
"(",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsCategoryQuery",
")",
"-... | Kopiowanie strony - kategorii | [
"Kopiowanie",
"strony",
"-",
"kategorii"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L228-L241 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController._isCategoryDuplicate | private function _isCategoryDuplicate($originalId)
{
$category = (new \Cms\Orm\CmsCategoryQuery)->findPk($originalId);
//znaleziono kategorię o tym samym uri
return (null !== (new \Cms\Orm\CmsCategoryQuery)
->whereId()->notEquals($category->id)
->andFieldRedirectUri()->equals(null)
->andFieldStatus()->equals(\Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE)
->andQuery((new \Cms\Orm\CmsCategoryQuery)->searchByUri($category->uri))
->findFirst()) && !$category->redirectUri && !$category->customUri;
} | php | private function _isCategoryDuplicate($originalId)
{
$category = (new \Cms\Orm\CmsCategoryQuery)->findPk($originalId);
//znaleziono kategorię o tym samym uri
return (null !== (new \Cms\Orm\CmsCategoryQuery)
->whereId()->notEquals($category->id)
->andFieldRedirectUri()->equals(null)
->andFieldStatus()->equals(\Cms\Orm\CmsCategoryRecord::STATUS_ACTIVE)
->andQuery((new \Cms\Orm\CmsCategoryQuery)->searchByUri($category->uri))
->findFirst()) && !$category->redirectUri && !$category->customUri;
} | [
"private",
"function",
"_isCategoryDuplicate",
"(",
"$",
"originalId",
")",
"{",
"$",
"category",
"=",
"(",
"new",
"\\",
"Cms",
"\\",
"Orm",
"\\",
"CmsCategoryQuery",
")",
"->",
"findPk",
"(",
"$",
"originalId",
")",
";",
"//znaleziono kategorię o tym samym uri"... | Sprawdzanie czy kategoria ma duplikat
@param integer $originalId
@return boolean | [
"Sprawdzanie",
"czy",
"kategoria",
"ma",
"duplikat"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L248-L258 | train |
milejko/mmi-cms | src/CmsAdmin/CategoryController.php | CategoryController._setReferrer | private function _setReferrer($referer, $id)
{
//brak referera lub referer kieruje na stronę edycji
if (!$referer || strpos($referer, self::EDIT_MVC_PARAMS)) {
return;
}
if (strpos($referer, 'cms-content-preview')) {
return;
}
$space = new \Mmi\Session\SessionSpace(self::SESSION_SPACE_PREFIX . $id);
$space->referer = $referer;
} | php | private function _setReferrer($referer, $id)
{
//brak referera lub referer kieruje na stronę edycji
if (!$referer || strpos($referer, self::EDIT_MVC_PARAMS)) {
return;
}
if (strpos($referer, 'cms-content-preview')) {
return;
}
$space = new \Mmi\Session\SessionSpace(self::SESSION_SPACE_PREFIX . $id);
$space->referer = $referer;
} | [
"private",
"function",
"_setReferrer",
"(",
"$",
"referer",
",",
"$",
"id",
")",
"{",
"//brak referera lub referer kieruje na stronę edycji",
"if",
"(",
"!",
"$",
"referer",
"||",
"strpos",
"(",
"$",
"referer",
",",
"self",
"::",
"EDIT_MVC_PARAMS",
")",
")",
"... | Ustawianie referer'a do sesji
@param string $referer | [
"Ustawianie",
"referer",
"a",
"do",
"sesji"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/CategoryController.php#L318-L329 | train |
claroline/MessageBundle | Repository/UserMessageRepository.php | UserMessageRepository.findSent | public function findSent(User $user, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = false
AND um.isSent = true
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
return $executeQuery ? $query->getResult() : $query;
} | php | public function findSent(User $user, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = false
AND um.isSent = true
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
return $executeQuery ? $query->getResult() : $query;
} | [
"public",
"function",
"findSent",
"(",
"User",
"$",
"user",
",",
"$",
"executeQuery",
"=",
"true",
")",
"{",
"$",
"dql",
"=",
"\"\n SELECT um, m, u\n FROM Claroline\\MessageBundle\\Entity\\UserMessage um\n JOIN um.user u\n JOIN um.message... | Finds UserMessage marked as sent by a user.
@param User $user
@param boolean $executeQuery
@return array[UserMessage]|Query | [
"Finds",
"UserMessage",
"marked",
"as",
"sent",
"by",
"a",
"user",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/UserMessageRepository.php#L28-L43 | train |
claroline/MessageBundle | Repository/UserMessageRepository.php | UserMessageRepository.findReceivedByObjectOrSender | public function findReceivedByObjectOrSender(
User $receiver,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$receiver->getId()}
AND um.isRemoved = false
AND um.isSent = false
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | public function findReceivedByObjectOrSender(
User $receiver,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$receiver->getId()}
AND um.isRemoved = false
AND um.isSent = false
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | [
"public",
"function",
"findReceivedByObjectOrSender",
"(",
"User",
"$",
"receiver",
",",
"$",
"objectOrSenderUsernameSearch",
",",
"$",
"executeQuery",
"=",
"true",
")",
"{",
"$",
"dql",
"=",
"\"\n SELECT um, m, u\n FROM Claroline\\MessageBundle\\Entity\... | Finds UserMessage received by a user, filtered by a search
on the object or on the username of the sender.
@param User $receiver
@param string $objectOrSenderUsernameSearch
@param boolean $executeQuery
@return array[UserMessage]|Query | [
"Finds",
"UserMessage",
"received",
"by",
"a",
"user",
"filtered",
"by",
"a",
"search",
"on",
"the",
"object",
"or",
"on",
"the",
"username",
"of",
"the",
"sender",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/UserMessageRepository.php#L104-L129 | train |
claroline/MessageBundle | Repository/UserMessageRepository.php | UserMessageRepository.findSentByObject | public function findSentByObject(User $sender, $objectSearch, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$sender->getId()}
AND um.isRemoved = false
AND um.isSent = true
AND UPPER(m.object) LIKE :search
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | public function findSentByObject(User $sender, $objectSearch, $executeQuery = true)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$sender->getId()}
AND um.isRemoved = false
AND um.isSent = true
AND UPPER(m.object) LIKE :search
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | [
"public",
"function",
"findSentByObject",
"(",
"User",
"$",
"sender",
",",
"$",
"objectSearch",
",",
"$",
"executeQuery",
"=",
"true",
")",
"{",
"$",
"dql",
"=",
"\"\n SELECT um, m, u\n FROM Claroline\\MessageBundle\\Entity\\UserMessage um\n J... | Finds UserMessage sent by a user, filtered by a search on the object.
@param User $sender
@param string $objectSearch
@param boolean $executeQuery
@return array[UserMessage]|Query | [
"Finds",
"UserMessage",
"sent",
"by",
"a",
"user",
"filtered",
"by",
"a",
"search",
"on",
"the",
"object",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/UserMessageRepository.php#L140-L158 | train |
claroline/MessageBundle | Repository/UserMessageRepository.php | UserMessageRepository.findRemovedByObjectOrSender | public function findRemovedByObjectOrSender(
User $user,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = true
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
GROUP BY m
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | php | public function findRemovedByObjectOrSender(
User $user,
$objectOrSenderUsernameSearch,
$executeQuery = true
)
{
$dql = "
SELECT um, m, u
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE u.id = {$user->getId()}
AND um.isRemoved = true
AND (
UPPER(m.object) LIKE :search
OR UPPER(m.senderUsername) LIKE :search
)
GROUP BY m
ORDER BY m.date DESC
";
$query = $this->_em->createQuery($dql);
$searchParameter = '%' . strtoupper($objectOrSenderUsernameSearch) . '%';
$query->setParameter('search', $searchParameter);
return $executeQuery ? $query->getResult() : $query;
} | [
"public",
"function",
"findRemovedByObjectOrSender",
"(",
"User",
"$",
"user",
",",
"$",
"objectOrSenderUsernameSearch",
",",
"$",
"executeQuery",
"=",
"true",
")",
"{",
"$",
"dql",
"=",
"\"\n SELECT um, m, u\n FROM Claroline\\MessageBundle\\Entity\\User... | Finds UserMessage removed by a user, filtered by a search
on the object or on the username of the sender.
@param User $user
@param string $objectOrSenderUsernameSearch
@param boolean $executeQuery
@return array[UserMessage]|Query | [
"Finds",
"UserMessage",
"removed",
"by",
"a",
"user",
"filtered",
"by",
"a",
"search",
"on",
"the",
"object",
"or",
"on",
"the",
"username",
"of",
"the",
"sender",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/UserMessageRepository.php#L170-L195 | train |
claroline/MessageBundle | Repository/UserMessageRepository.php | UserMessageRepository.findByMessages | public function findByMessages(User $user, array $messages)
{
$messageIds = array();
foreach ($messages as $message) {
$messageIds[] = $message->getId();
}
$dql = '
SELECT um
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE m.id IN (:messageIds)
AND u.id = :userId
ORDER BY m.date DESC
';
$query = $this->_em->createQuery($dql);
$query->setParameter('messageIds', $messageIds);
$query->setParameter('userId', $user->getId());
return $query->getResult();
} | php | public function findByMessages(User $user, array $messages)
{
$messageIds = array();
foreach ($messages as $message) {
$messageIds[] = $message->getId();
}
$dql = '
SELECT um
FROM Claroline\MessageBundle\Entity\UserMessage um
JOIN um.user u
JOIN um.message m
WHERE m.id IN (:messageIds)
AND u.id = :userId
ORDER BY m.date DESC
';
$query = $this->_em->createQuery($dql);
$query->setParameter('messageIds', $messageIds);
$query->setParameter('userId', $user->getId());
return $query->getResult();
} | [
"public",
"function",
"findByMessages",
"(",
"User",
"$",
"user",
",",
"array",
"$",
"messages",
")",
"{",
"$",
"messageIds",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"messages",
"as",
"$",
"message",
")",
"{",
"$",
"messageIds",
"[",
"]",
"... | Finds UserMessage received or sent by a user, filtered by specific messages.
@param User $user
@param array[Message] $messages
@return array[UserMessage] | [
"Finds",
"UserMessage",
"received",
"or",
"sent",
"by",
"a",
"user",
"filtered",
"by",
"specific",
"messages",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/UserMessageRepository.php#L205-L227 | train |
milejko/mmi-cms | src/Cms/Model/Stat.php | Stat.getUniqueObjects | public static function getUniqueObjects()
{
$all = (new Orm\CmsStatDateQuery)
->whereHour()->equals(null)
->andFieldDay()->equals(null)
->andFieldMonth()->equals(null)
->andFieldObjectId()->equals(null)
->orderAscObject()
->find();
$objects = [];
foreach ($all as $object) {
if (!isset($objects[$object->object])) {
$objects[$object->object] = $object->object;
}
}
return $objects;
} | php | public static function getUniqueObjects()
{
$all = (new Orm\CmsStatDateQuery)
->whereHour()->equals(null)
->andFieldDay()->equals(null)
->andFieldMonth()->equals(null)
->andFieldObjectId()->equals(null)
->orderAscObject()
->find();
$objects = [];
foreach ($all as $object) {
if (!isset($objects[$object->object])) {
$objects[$object->object] = $object->object;
}
}
return $objects;
} | [
"public",
"static",
"function",
"getUniqueObjects",
"(",
")",
"{",
"$",
"all",
"=",
"(",
"new",
"Orm",
"\\",
"CmsStatDateQuery",
")",
"->",
"whereHour",
"(",
")",
"->",
"equals",
"(",
"null",
")",
"->",
"andFieldDay",
"(",
")",
"->",
"equals",
"(",
"nu... | Pobiera unikalne obiekty
@return array | [
"Pobiera",
"unikalne",
"obiekty"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Model/Stat.php#L118-L134 | train |
milejko/mmi-cms | src/Cms/Model/Stat.php | Stat.getRows | public static function getRows($object, $objectId, $year = null, $month = null, $day = null, $hour = null)
{
//nowa quera filtrująca po obiekcie i ID
$q = (new Orm\CmsStatDateQuery)
->whereObject()->equals($object)
->andFieldObjectId()->equals($objectId);
//wiązanie roku
self::_bindParam($q, 'year', $year);
//wiązanie miesiąca
self::_bindParam($q, 'month', $month);
//wiązanie dnia
self::_bindParam($q, 'day', $day);
//wiązanie godziny
self::_bindParam($q, 'hour', $hour);
//sortowanie i zwrot
return $q->orderAsc('day')
->orderAsc('month')
->orderAsc('year')
->orderAsc('hour')
->find();
} | php | public static function getRows($object, $objectId, $year = null, $month = null, $day = null, $hour = null)
{
//nowa quera filtrująca po obiekcie i ID
$q = (new Orm\CmsStatDateQuery)
->whereObject()->equals($object)
->andFieldObjectId()->equals($objectId);
//wiązanie roku
self::_bindParam($q, 'year', $year);
//wiązanie miesiąca
self::_bindParam($q, 'month', $month);
//wiązanie dnia
self::_bindParam($q, 'day', $day);
//wiązanie godziny
self::_bindParam($q, 'hour', $hour);
//sortowanie i zwrot
return $q->orderAsc('day')
->orderAsc('month')
->orderAsc('year')
->orderAsc('hour')
->find();
} | [
"public",
"static",
"function",
"getRows",
"(",
"$",
"object",
",",
"$",
"objectId",
",",
"$",
"year",
"=",
"null",
",",
"$",
"month",
"=",
"null",
",",
"$",
"day",
"=",
"null",
",",
"$",
"hour",
"=",
"null",
")",
"{",
"//nowa quera filtrująca po obiek... | Pobranie wierszy z DB
@param string $object
@param integer $objectId
@param integer $year
@param integer $month
@param integer $day
@param integer $hour
@return \Mmi\Orm\RecordCollection | [
"Pobranie",
"wierszy",
"z",
"DB"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Model/Stat.php#L285-L306 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Service/Auth/ApiKeyAuthenticationHandler.php | ApiKeyAuthenticationHandler.buildKey | private function buildKey($userObject)
{
$key = $this->classMetadata->getPropertyValue($userObject, ClassMetadata::API_KEY_PROPERTY);
if (empty($key)) {
$this->classMetadata->modifyProperty(
$userObject,
$this->keyFactory->getKey(),
ClassMetadata::API_KEY_PROPERTY
);
}
} | php | private function buildKey($userObject)
{
$key = $this->classMetadata->getPropertyValue($userObject, ClassMetadata::API_KEY_PROPERTY);
if (empty($key)) {
$this->classMetadata->modifyProperty(
$userObject,
$this->keyFactory->getKey(),
ClassMetadata::API_KEY_PROPERTY
);
}
} | [
"private",
"function",
"buildKey",
"(",
"$",
"userObject",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"classMetadata",
"->",
"getPropertyValue",
"(",
"$",
"userObject",
",",
"ClassMetadata",
"::",
"API_KEY_PROPERTY",
")",
";",
"if",
"(",
"empty",
"(",
"... | Simple helper which builds the API key and stores it in the user.
@param object $userObject | [
"Simple",
"helper",
"which",
"builds",
"the",
"API",
"key",
"and",
"stores",
"it",
"in",
"the",
"user",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Service/Auth/ApiKeyAuthenticationHandler.php#L203-L214 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Service/Auth/ApiKeyAuthenticationHandler.php | ApiKeyAuthenticationHandler.resolveObject | private function resolveObject($loginProperty, array $credentials)
{
return $this->om->getRepository($this->modelName)->findOneBy([
$loginProperty => $credentials[$loginProperty],
]);
} | php | private function resolveObject($loginProperty, array $credentials)
{
return $this->om->getRepository($this->modelName)->findOneBy([
$loginProperty => $credentials[$loginProperty],
]);
} | [
"private",
"function",
"resolveObject",
"(",
"$",
"loginProperty",
",",
"array",
"$",
"credentials",
")",
"{",
"return",
"$",
"this",
"->",
"om",
"->",
"getRepository",
"(",
"$",
"this",
"->",
"modelName",
")",
"->",
"findOneBy",
"(",
"[",
"$",
"loginPrope... | Simple helper which searches the ObjectManager by the given login parameter.
@param string $loginProperty
@param array $credentials
@return object | [
"Simple",
"helper",
"which",
"searches",
"the",
"ObjectManager",
"by",
"the",
"given",
"login",
"parameter",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Service/Auth/ApiKeyAuthenticationHandler.php#L224-L229 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Service/Auth/ApiKeyAuthenticationHandler.php | ApiKeyAuthenticationHandler.validateCredentials | private function validateCredentials($object, $password)
{
return !(
null === $object
|| !$this->passwordHasher->compareWith($object->getPassword(), $password)
);
} | php | private function validateCredentials($object, $password)
{
return !(
null === $object
|| !$this->passwordHasher->compareWith($object->getPassword(), $password)
);
} | [
"private",
"function",
"validateCredentials",
"(",
"$",
"object",
",",
"$",
"password",
")",
"{",
"return",
"!",
"(",
"null",
"===",
"$",
"object",
"||",
"!",
"$",
"this",
"->",
"passwordHasher",
"->",
"compareWith",
"(",
"$",
"object",
"->",
"getPassword"... | Validates the existance of the object and ensures that a valid password is given.
@param object $object
@param string $password
@return bool | [
"Validates",
"the",
"existance",
"of",
"the",
"object",
"and",
"ensures",
"that",
"a",
"valid",
"password",
"is",
"given",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Service/Auth/ApiKeyAuthenticationHandler.php#L239-L245 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Service/Auth/ApiKeyAuthenticationHandler.php | ApiKeyAuthenticationHandler.buildEventObject | private function buildEventObject($user, $purgeJob = false)
{
$event = new OnLogoutEvent($user);
if ($purgeJob) {
$event->markAsPurgeJob();
}
return $event;
} | php | private function buildEventObject($user, $purgeJob = false)
{
$event = new OnLogoutEvent($user);
if ($purgeJob) {
$event->markAsPurgeJob();
}
return $event;
} | [
"private",
"function",
"buildEventObject",
"(",
"$",
"user",
",",
"$",
"purgeJob",
"=",
"false",
")",
"{",
"$",
"event",
"=",
"new",
"OnLogoutEvent",
"(",
"$",
"user",
")",
";",
"if",
"(",
"$",
"purgeJob",
")",
"{",
"$",
"event",
"->",
"markAsPurgeJob"... | Builds the `OnLogoutEvent`.
@param object $user
@param bool $purgeJob
@return OnLogoutEvent | [
"Builds",
"the",
"OnLogoutEvent",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Service/Auth/ApiKeyAuthenticationHandler.php#L255-L263 | train |
mapbender/fom | src/FOM/UserBundle/Entity/UserLogEntry.php | UserLogEntry.fill | private function fill(array $args)
{
$properties = array_keys(get_object_vars($this));
foreach ($args as $key => $value) {
if (in_array($key, $properties)) {
$this->{$key} = $value;
}
}
} | php | private function fill(array $args)
{
$properties = array_keys(get_object_vars($this));
foreach ($args as $key => $value) {
if (in_array($key, $properties)) {
$this->{$key} = $value;
}
}
} | [
"private",
"function",
"fill",
"(",
"array",
"$",
"args",
")",
"{",
"$",
"properties",
"=",
"array_keys",
"(",
"get_object_vars",
"(",
"$",
"this",
")",
")",
";",
"foreach",
"(",
"$",
"args",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(... | Fill the object
@param array $args | [
"Fill",
"the",
"object"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Entity/UserLogEntry.php#L85-L93 | train |
milejko/mmi-cms | src/Cms/Orm/CmsCategoryRecord.php | CmsCategoryRecord.getUrl | public function getUrl($https = null)
{
//pobranie linku z widoku
return \Mmi\App\FrontController::getInstance()->getView()->url(['module' => 'cms', 'controller' => 'category', 'action' => 'dispatch', 'uri' => $this->customUri ? $this->customUri : $this->uri], true, $https);
} | php | public function getUrl($https = null)
{
//pobranie linku z widoku
return \Mmi\App\FrontController::getInstance()->getView()->url(['module' => 'cms', 'controller' => 'category', 'action' => 'dispatch', 'uri' => $this->customUri ? $this->customUri : $this->uri], true, $https);
} | [
"public",
"function",
"getUrl",
"(",
"$",
"https",
"=",
"null",
")",
"{",
"//pobranie linku z widoku",
"return",
"\\",
"Mmi",
"\\",
"App",
"\\",
"FrontController",
"::",
"getInstance",
"(",
")",
"->",
"getView",
"(",
")",
"->",
"url",
"(",
"[",
"'module'",... | Pobiera url kategorii
@param boolean $https true - tak, false - nie, null - bez zmiany protokołu
@return string | [
"Pobiera",
"url",
"kategorii"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsCategoryRecord.php#L352-L356 | train |
milejko/mmi-cms | src/Cms/Orm/CmsCategoryRecord.php | CmsCategoryRecord.getParentRecord | public function getParentRecord()
{
//brak parenta
if (!$this->parentId) {
return;
}
//próba pobrania rodzica z cache
if (null === $parent = \App\Registry::$cache->load($cacheKey = 'category-' . $this->parentId)) {
//pobieranie rodzica
\App\Registry::$cache->save($parent = (new \Cms\Orm\CmsCategoryQuery)
->withType()
->findPk($this->parentId), $cacheKey, 0);
}
//zwrot rodzica
return $parent;
} | php | public function getParentRecord()
{
//brak parenta
if (!$this->parentId) {
return;
}
//próba pobrania rodzica z cache
if (null === $parent = \App\Registry::$cache->load($cacheKey = 'category-' . $this->parentId)) {
//pobieranie rodzica
\App\Registry::$cache->save($parent = (new \Cms\Orm\CmsCategoryQuery)
->withType()
->findPk($this->parentId), $cacheKey, 0);
}
//zwrot rodzica
return $parent;
} | [
"public",
"function",
"getParentRecord",
"(",
")",
"{",
"//brak parenta",
"if",
"(",
"!",
"$",
"this",
"->",
"parentId",
")",
"{",
"return",
";",
"}",
"//próba pobrania rodzica z cache",
"if",
"(",
"null",
"===",
"$",
"parent",
"=",
"\\",
"App",
"\\",
"Reg... | Pobiera rekord rodzica
@return \Cms\Orm\CmsCategoryRecord | [
"Pobiera",
"rekord",
"rodzica"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsCategoryRecord.php#L393-L408 | train |
milejko/mmi-cms | src/Cms/Orm/CmsCategoryRecord.php | CmsCategoryRecord._getChildren | protected function _getChildren($parentId, $activeOnly = false)
{
//inicjalizacja zapytania
$query = (new CmsCategoryQuery)
->whereParentId()->equals($parentId)
->joinLeft('cms_category_type')->on('cms_category_type_id')
->orderAscOrder()
->orderAscId();
//tylko aktywne
if ($activeOnly) {
$query->whereStatus()->equals(self::STATUS_ACTIVE);
}
//zwrot w postaci tablicy rekordów
return $query->find()->toObjectArray();
} | php | protected function _getChildren($parentId, $activeOnly = false)
{
//inicjalizacja zapytania
$query = (new CmsCategoryQuery)
->whereParentId()->equals($parentId)
->joinLeft('cms_category_type')->on('cms_category_type_id')
->orderAscOrder()
->orderAscId();
//tylko aktywne
if ($activeOnly) {
$query->whereStatus()->equals(self::STATUS_ACTIVE);
}
//zwrot w postaci tablicy rekordów
return $query->find()->toObjectArray();
} | [
"protected",
"function",
"_getChildren",
"(",
"$",
"parentId",
",",
"$",
"activeOnly",
"=",
"false",
")",
"{",
"//inicjalizacja zapytania",
"$",
"query",
"=",
"(",
"new",
"CmsCategoryQuery",
")",
"->",
"whereParentId",
"(",
")",
"->",
"equals",
"(",
"$",
"pa... | Zwraca dzieci danego rodzica
@param integer $parentId id rodzica
@param boolean $activeOnly tylko aktywne
@return \Cms\Orm\CmsCategoryRecord[] | [
"Zwraca",
"dzieci",
"danego",
"rodzica"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsCategoryRecord.php#L503-L517 | train |
milejko/mmi-cms | src/Cms/Orm/CmsCategoryRecord.php | CmsCategoryRecord._sortChildren | protected function _sortChildren()
{
$i = 0;
//pobranie dzieci swojego rodzica
foreach ($this->_getChildren($this->parentId, true) as $categoryRecord) {
//ten rekord musi pozostać w niezmienionej pozycji (był sortowany)
if ($categoryRecord->id == $this->id) {
continue;
}
//ten sam order wskakuje za rekord
if ($this->order == $i) {
$i++;
}
//obliczanie nowej kolejności
$categoryRecord->order = $i++;
//blokada dalszego sortowania i zapis
$categoryRecord
->setOption('block-ordering', true)
->save();
}
} | php | protected function _sortChildren()
{
$i = 0;
//pobranie dzieci swojego rodzica
foreach ($this->_getChildren($this->parentId, true) as $categoryRecord) {
//ten rekord musi pozostać w niezmienionej pozycji (był sortowany)
if ($categoryRecord->id == $this->id) {
continue;
}
//ten sam order wskakuje za rekord
if ($this->order == $i) {
$i++;
}
//obliczanie nowej kolejności
$categoryRecord->order = $i++;
//blokada dalszego sortowania i zapis
$categoryRecord
->setOption('block-ordering', true)
->save();
}
} | [
"protected",
"function",
"_sortChildren",
"(",
")",
"{",
"$",
"i",
"=",
"0",
";",
"//pobranie dzieci swojego rodzica",
"foreach",
"(",
"$",
"this",
"->",
"_getChildren",
"(",
"$",
"this",
"->",
"parentId",
",",
"true",
")",
"as",
"$",
"categoryRecord",
")",
... | Sortuje dzieci wybranego rodzica
@param integer $order wstawiona kolejność | [
"Sortuje",
"dzieci",
"wybranego",
"rodzica"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsCategoryRecord.php#L539-L559 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Command/SessionCleanupCommand.php | SessionCleanupCommand.searchUsers | private function searchUsers()
{
$criteria = Criteria::create()
->where(Criteria::expr()->lte(
$this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY),
new \DateTime($this->dateTimeRule))
)
->andWhere(
Criteria::expr()->neq(
$this->classMetadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY),
null
)
);
return $this->getUsersByCriteria($criteria);
} | php | private function searchUsers()
{
$criteria = Criteria::create()
->where(Criteria::expr()->lte(
$this->classMetadata->getPropertyName(ClassMetadata::LAST_ACTION_PROPERTY),
new \DateTime($this->dateTimeRule))
)
->andWhere(
Criteria::expr()->neq(
$this->classMetadata->getPropertyName(ClassMetadata::API_KEY_PROPERTY),
null
)
);
return $this->getUsersByCriteria($criteria);
} | [
"private",
"function",
"searchUsers",
"(",
")",
"{",
"$",
"criteria",
"=",
"Criteria",
"::",
"create",
"(",
")",
"->",
"where",
"(",
"Criteria",
"::",
"expr",
"(",
")",
"->",
"lte",
"(",
"$",
"this",
"->",
"classMetadata",
"->",
"getPropertyName",
"(",
... | Search query for users with outdated api keys.
@return object[] | [
"Search",
"query",
"for",
"users",
"with",
"outdated",
"api",
"keys",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Command/SessionCleanupCommand.php#L146-L161 | train |
Ma27/Ma27ApiKeyAuthenticationBundle | Command/SessionCleanupCommand.php | SessionCleanupCommand.getUsersByCriteria | private function getUsersByCriteria(Criteria $criteria)
{
$repository = $this->om->getRepository($this->modelName);
if ($repository instanceof Selectable) {
$filteredUsers = $repository->matching($criteria);
} else {
$allUsers = new ArrayCollection($repository->findAll());
$filteredUsers = $allUsers->matching($criteria);
}
return $filteredUsers->toArray();
} | php | private function getUsersByCriteria(Criteria $criteria)
{
$repository = $this->om->getRepository($this->modelName);
if ($repository instanceof Selectable) {
$filteredUsers = $repository->matching($criteria);
} else {
$allUsers = new ArrayCollection($repository->findAll());
$filteredUsers = $allUsers->matching($criteria);
}
return $filteredUsers->toArray();
} | [
"private",
"function",
"getUsersByCriteria",
"(",
"Criteria",
"$",
"criteria",
")",
"{",
"$",
"repository",
"=",
"$",
"this",
"->",
"om",
"->",
"getRepository",
"(",
"$",
"this",
"->",
"modelName",
")",
";",
"if",
"(",
"$",
"repository",
"instanceof",
"Sel... | Simple utility to query users by a given criteria.
As there's no unified query language defined in doctrine/common, the criteria tool of doctrine/collections
should help. The ORM and Mongo-ODM support the `Selectable` API which means that they can build native
DB queries for their database based on a criteria object. The other official implementations PHPCR and CouchDB-ODM
don't support that, so they have to be evaluated manually.
@param Criteria $criteria
@return object[] | [
"Simple",
"utility",
"to",
"query",
"users",
"by",
"a",
"given",
"criteria",
"."
] | 3f1e2ea6eacefac0db41b2ad964c8ef262f0e408 | https://github.com/Ma27/Ma27ApiKeyAuthenticationBundle/blob/3f1e2ea6eacefac0db41b2ad964c8ef262f0e408/Command/SessionCleanupCommand.php#L186-L198 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._extractBytes | private static function _extractBytes($byteString, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($byteString, $start, $length, '8bit');
}
return substr($byteString, $start, $length);
} | php | private static function _extractBytes($byteString, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($byteString, $start, $length, '8bit');
}
return substr($byteString, $start, $length);
} | [
"private",
"static",
"function",
"_extractBytes",
"(",
"$",
"byteString",
",",
"$",
"start",
",",
"$",
"length",
")",
"{",
"if",
"(",
"function_exists",
"(",
"'mb_substr'",
")",
")",
"{",
"return",
"mb_substr",
"(",
"$",
"byteString",
",",
"$",
"start",
... | Returns the bytes of the given string specified by the start and length
parameters.
@param string $byteString The string from which to extract the bytes.
@param int $start Start position.
@param int $length Number of bytes to extract.
@return string Subset of bytes from given string. | [
"Returns",
"the",
"bytes",
"of",
"the",
"given",
"string",
"specified",
"by",
"the",
"start",
"and",
"length",
"parameters",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L217-L222 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._intStrToByteStr | private static function _intStrToByteStr($intStr) {
// Check if given value is a positive integer (string).
if (!preg_match('/[0-9]+/', (string) $intStr)) {
$msg = 'Argument 1 must be a non-negative integer or a string representing a non-negative integer.';
throw new InvalidArgumentException($msg, self::E_NO_NON_NEGATIVE_INT);
}
$byteStr = '';
// If possible, use integer type for conversion.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
// Convert integer to byte-string.
while ($int > 0) {
$byteStr = chr($int & 255) . $byteStr;
$int >>= 8;
}
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
// Convert integer to byte-string.
while ((int) $intStr > 0) {
$byteStr = chr(bcmod($intStr, '256')) . $byteStr;
$intStr = bcdiv($intStr, '256', 0);
}
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
if ($byteStr == '')
$byteStr = chr(0);
return $byteStr;
} | php | private static function _intStrToByteStr($intStr) {
// Check if given value is a positive integer (string).
if (!preg_match('/[0-9]+/', (string) $intStr)) {
$msg = 'Argument 1 must be a non-negative integer or a string representing a non-negative integer.';
throw new InvalidArgumentException($msg, self::E_NO_NON_NEGATIVE_INT);
}
$byteStr = '';
// If possible, use integer type for conversion.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
// Convert integer to byte-string.
while ($int > 0) {
$byteStr = chr($int & 255) . $byteStr;
$int >>= 8;
}
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
// Convert integer to byte-string.
while ((int) $intStr > 0) {
$byteStr = chr(bcmod($intStr, '256')) . $byteStr;
$intStr = bcdiv($intStr, '256', 0);
}
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
if ($byteStr == '')
$byteStr = chr(0);
return $byteStr;
} | [
"private",
"static",
"function",
"_intStrToByteStr",
"(",
"$",
"intStr",
")",
"{",
"// Check if given value is a positive integer (string).",
"if",
"(",
"!",
"preg_match",
"(",
"'/[0-9]+/'",
",",
"(",
"string",
")",
"$",
"intStr",
")",
")",
"{",
"$",
"msg",
"=",... | Converts an integer into a byte-string.
Stores the bits representing the given non-negative integer in the
smallest sufficient number of bytes, padding the left side with zeros.
Uses PHP's BC Math library if the given integer string is too large to be
processed with PHP's internal string type.
Example: $intStr = 16706 => chr(16706 >> 8 & 255) . chr(16706 & 255) =
'AB'
@param mixed $intStr Non-negative integer or string representing a
non-negative integer.
@return string Byte-string containing the bits representing the given
integer.
@throws InvalidArgumentException
@throws RuntimeException | [
"Converts",
"an",
"integer",
"into",
"a",
"byte",
"-",
"string",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L242-L273 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._byteStrToIntStr | private static function _byteStrToIntStr($byteStr) {
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Check if byte count is not 0.
if ($byteCount == 0) {
$msg = 'Empty byte-string cannot be convertet to integer.';
throw new InvalidArgumentException($msg, self::E_EMPTY_BYTESTRING);
}
// Try to use PHP's internal integer type.
if ($byteCount <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $byteCount; $i++) {
$int <<= 8;
$int |= ord($byteStr[$i]);
}
if ($int >= 0)
return $int;
}
// If we did not already return here, either the byte-string has more
// characters (bytes) than PHP_INT_SIZE, or the conversion resulted in a
// negative integer. In both cases, we need to use PHP's BC Math library and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $byteCount; $i++) {
$intStr = bcmul($intStr, '256', 0);
$intStr = bcadd($intStr, (string) ord($byteStr[$i]), 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | php | private static function _byteStrToIntStr($byteStr) {
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Check if byte count is not 0.
if ($byteCount == 0) {
$msg = 'Empty byte-string cannot be convertet to integer.';
throw new InvalidArgumentException($msg, self::E_EMPTY_BYTESTRING);
}
// Try to use PHP's internal integer type.
if ($byteCount <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $byteCount; $i++) {
$int <<= 8;
$int |= ord($byteStr[$i]);
}
if ($int >= 0)
return $int;
}
// If we did not already return here, either the byte-string has more
// characters (bytes) than PHP_INT_SIZE, or the conversion resulted in a
// negative integer. In both cases, we need to use PHP's BC Math library and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $byteCount; $i++) {
$intStr = bcmul($intStr, '256', 0);
$intStr = bcadd($intStr, (string) ord($byteStr[$i]), 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | [
"private",
"static",
"function",
"_byteStrToIntStr",
"(",
"$",
"byteStr",
")",
"{",
"// Get byte count.",
"$",
"byteCount",
"=",
"self",
"::",
"_byteCount",
"(",
"$",
"byteStr",
")",
";",
"// Check if byte count is not 0.",
"if",
"(",
"$",
"byteCount",
"==",
"0"... | Converts a byte-string into a non-negative integer.
Uses PHP's BC Math library if the integer represented by the given bytes
is too big to be stored in PHP's internal integer type. In this case a
string containing the integer is returned, otherwise a native integer.
Example: $byteStr = 'AB' => ord($byteStr[0]) << 8 | ord($byteStr[1]) =
16706
@param string $byteStr Byte-string whose binary content shall be
converted to an integer.
@return mixed Non-negative integer or string representing a non-negative
integer.
@throws InvalidArgumentException
@throws RuntimeException | [
"Converts",
"a",
"byte",
"-",
"string",
"into",
"a",
"non",
"-",
"negative",
"integer",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L292-L327 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._intStrModulus | private static function _intStrModulus($intStr, $divisor) {
// If possible, use integer type for calculation.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
return $int % $divisor;
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
return bcmod($intStr, (string) $divisor);
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
} | php | private static function _intStrModulus($intStr, $divisor) {
// If possible, use integer type for calculation.
$int = (int) $intStr;
if ((string) $int == (string) $intStr) {
// Use of integer type is possible.
return $int % $divisor;
} else {
// Cannot use integer type, use BC Math library.
if (extension_loaded('bcmath')) {
return bcmod($intStr, (string) $divisor);
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
}
} | [
"private",
"static",
"function",
"_intStrModulus",
"(",
"$",
"intStr",
",",
"$",
"divisor",
")",
"{",
"// If possible, use integer type for calculation.",
"$",
"int",
"=",
"(",
"int",
")",
"$",
"intStr",
";",
"if",
"(",
"(",
"string",
")",
"$",
"int",
"==",
... | Calculates dividend modulus divisor.
Uses PHP's BC Math library if the dividend is too big to be processed
with PHP's internal integer type.
@param mixed $intStr Dividend as integer or as string representing an
integer.
@param int $divisor Divisor.
@return mixed Remainder as integer or as string representing an integer.
@throws RuntimeException | [
"Calculates",
"dividend",
"modulus",
"divisor",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L341-L355 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._encodeByteStr | private static function _encodeByteStr($byteStr, $alphabet, $pad) {
// Check if argument is a string.
if (!is_string($byteStr)) {
$msg = 'Supplied argument 1 is not a string.';
throw new InvalidArgumentException($msg, self::E_NO_STRING);
}
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Make byte count divisible by 5.
$remainder = $byteCount % 5;
$fillbyteCount = ($remainder) ? 5 - $remainder : 0;
if ($fillbyteCount > 0)
$byteStr .= str_repeat(chr(0), $fillbyteCount);
// Iterate over blocks of 5 bytes and build encoded string.
$encodedStr = '';
for ($i = 0; $i < ($byteCount + $fillbyteCount); $i = $i + 5) {
// Convert chars to bytes.
$byte1 = ord($byteStr[$i]);
$byte2 = ord($byteStr[$i + 1]);
$byte3 = ord($byteStr[$i + 2]);
$byte4 = ord($byteStr[$i + 3]);
$byte5 = ord($byteStr[$i + 4]);
// Read first 5 bit group.
$bitGroup = $byte1 >> 3;
$encodedStr .= $alphabet[$bitGroup];
// Read second 5 bit group.
$bitGroup = ($byte1 & ~(31 << 3)) << 2 | $byte2 >> 6;
$encodedStr .= $alphabet[$bitGroup];
// Read third 5 bit group.
$bitGroup = $byte2 >> 1 & ~(3 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read fourth 5 bit group.
$bitGroup = ($byte2 & 1) << 4 | $byte3 >> 4;
$encodedStr .= $alphabet[$bitGroup];
// Read fifth 5 bit group.
$bitGroup = ($byte3 & ~(15 << 4)) << 1 | $byte4 >> 7;
$encodedStr .= $alphabet[$bitGroup];
// Read sixth 5 bit group.
$bitGroup = $byte4 >> 2 & ~(1 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read seventh 5 bit group.
$bitGroup = ($byte4 & ~(63 << 2)) << 3 | $byte5 >> 5;
$encodedStr .= $alphabet[$bitGroup];
// Read eighth 5 bit group.
$bitGroup = $byte5 & ~(7 << 5);
$encodedStr .= $alphabet[$bitGroup];
}
// Replace fillbit characters at the end of the encoded string.
$encodedStrLen = ($byteCount + $fillbyteCount) * 8 / 5;
$fillbitCharCount = (int) ($fillbyteCount * 8 / 5);
$encodedStr = substr($encodedStr, 0, $encodedStrLen - $fillbitCharCount);
if ($pad)
$encodedStr .= str_repeat($alphabet[32], $fillbitCharCount);
// Return encoded string.
return $encodedStr;
} | php | private static function _encodeByteStr($byteStr, $alphabet, $pad) {
// Check if argument is a string.
if (!is_string($byteStr)) {
$msg = 'Supplied argument 1 is not a string.';
throw new InvalidArgumentException($msg, self::E_NO_STRING);
}
// Get byte count.
$byteCount = self::_byteCount($byteStr);
// Make byte count divisible by 5.
$remainder = $byteCount % 5;
$fillbyteCount = ($remainder) ? 5 - $remainder : 0;
if ($fillbyteCount > 0)
$byteStr .= str_repeat(chr(0), $fillbyteCount);
// Iterate over blocks of 5 bytes and build encoded string.
$encodedStr = '';
for ($i = 0; $i < ($byteCount + $fillbyteCount); $i = $i + 5) {
// Convert chars to bytes.
$byte1 = ord($byteStr[$i]);
$byte2 = ord($byteStr[$i + 1]);
$byte3 = ord($byteStr[$i + 2]);
$byte4 = ord($byteStr[$i + 3]);
$byte5 = ord($byteStr[$i + 4]);
// Read first 5 bit group.
$bitGroup = $byte1 >> 3;
$encodedStr .= $alphabet[$bitGroup];
// Read second 5 bit group.
$bitGroup = ($byte1 & ~(31 << 3)) << 2 | $byte2 >> 6;
$encodedStr .= $alphabet[$bitGroup];
// Read third 5 bit group.
$bitGroup = $byte2 >> 1 & ~(3 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read fourth 5 bit group.
$bitGroup = ($byte2 & 1) << 4 | $byte3 >> 4;
$encodedStr .= $alphabet[$bitGroup];
// Read fifth 5 bit group.
$bitGroup = ($byte3 & ~(15 << 4)) << 1 | $byte4 >> 7;
$encodedStr .= $alphabet[$bitGroup];
// Read sixth 5 bit group.
$bitGroup = $byte4 >> 2 & ~(1 << 5);
$encodedStr .= $alphabet[$bitGroup];
// Read seventh 5 bit group.
$bitGroup = ($byte4 & ~(63 << 2)) << 3 | $byte5 >> 5;
$encodedStr .= $alphabet[$bitGroup];
// Read eighth 5 bit group.
$bitGroup = $byte5 & ~(7 << 5);
$encodedStr .= $alphabet[$bitGroup];
}
// Replace fillbit characters at the end of the encoded string.
$encodedStrLen = ($byteCount + $fillbyteCount) * 8 / 5;
$fillbitCharCount = (int) ($fillbyteCount * 8 / 5);
$encodedStr = substr($encodedStr, 0, $encodedStrLen - $fillbitCharCount);
if ($pad)
$encodedStr .= str_repeat($alphabet[32], $fillbitCharCount);
// Return encoded string.
return $encodedStr;
} | [
"private",
"static",
"function",
"_encodeByteStr",
"(",
"$",
"byteStr",
",",
"$",
"alphabet",
",",
"$",
"pad",
")",
"{",
"// Check if argument is a string.",
"if",
"(",
"!",
"is_string",
"(",
"$",
"byteStr",
")",
")",
"{",
"$",
"msg",
"=",
"'Supplied argumen... | Base 32 encodes the given byte-string using the given alphabet.
@param string $byteStr String containing the bytes to be encoded.
@param string $alphabet The alphabet to be used for encoding.
@param bool $pad If true, the encoded string is padded using the padding
character specified in the given alphabet to have a length which
is evenly divisible by 8.
@return string The encoded string.
@throws InvalidArgumentException | [
"Base",
"32",
"encodes",
"the",
"given",
"byte",
"-",
"string",
"using",
"the",
"given",
"alphabet",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L529-L589 | train |
skleeschulte/php-base32 | src/Base32.php | Base32.decodeToByteStr | public static function decodeToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[A-Z2-7]*([A-Z2-7]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_commonFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | php | public static function decodeToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[A-Z2-7]*([A-Z2-7]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_commonFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | [
"public",
"static",
"function",
"decodeToByteStr",
"(",
"$",
"encodedStr",
",",
"$",
"allowOmittedPadding",
"=",
"false",
")",
"{",
"// Check input string.",
"$",
"pattern",
"=",
"'/[A-Z2-7]*([A-Z2-7]={0,6})?/'",
";",
"self",
"::",
"_checkEncodedString",
"(",
"$",
"... | Decodes a RFC 4646 base32 encoded string to a byte-string.
Expects an encoded string according to the base 32 encoding described in
RFC 4648 p. 8f (http://tools.ietf.org/html/rfc4648#page-8). Throws an
exception if the encoded string is malformed.
@param string $encodedStr The encoded string.
@param bool $allowOmittedPadding If true, missing padding characters at
the end of the encoded string will not lead to an exception.
Defaults to false.
@return string The decoded byte-string. | [
"Decodes",
"a",
"RFC",
"4646",
"base32",
"encoded",
"string",
"to",
"a",
"byte",
"-",
"string",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L687-L700 | train |
skleeschulte/php-base32 | src/Base32.php | Base32.decodeHexToByteStr | public static function decodeHexToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[0-9A-V]*([0-9A-V]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_hexFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | php | public static function decodeHexToByteStr($encodedStr, $allowOmittedPadding = false) {
// Check input string.
$pattern = '/[0-9A-V]*([0-9A-V]={0,6})?/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, self::$_hexFlippedAlphabet, '=', $allowOmittedPadding);
// Return byte-string.
return $byteStr;
} | [
"public",
"static",
"function",
"decodeHexToByteStr",
"(",
"$",
"encodedStr",
",",
"$",
"allowOmittedPadding",
"=",
"false",
")",
"{",
"// Check input string.",
"$",
"pattern",
"=",
"'/[0-9A-V]*([0-9A-V]={0,6})?/'",
";",
"self",
"::",
"_checkEncodedString",
"(",
"$",
... | Decodes a RFC 4646 base32 extended hex encoded string to a byte-string.
Expects an encoded string according to the base 32 extended hex encoding
described in RFC 4648 p. 10 (http://tools.ietf.org/html/rfc4648#page-10).
Throws an exception if the encoded string is malformed.
@param string $encodedStr The encoded string.
@param bool $allowOmittedPadding If true, missing padding characters at
the end of the encoded string will not lead to an exception.
Defaults to false.
@return string The decoded byte-string. | [
"Decodes",
"a",
"RFC",
"4646",
"base32",
"extended",
"hex",
"encoded",
"string",
"to",
"a",
"byte",
"-",
"string",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L738-L751 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._decodeCrockford | private static function _decodeCrockford($to, $encodedStr, $hasCheckSymbol = false) {
// Check input string.
if ($hasCheckSymbol) {
$pattern = '/[0-9A-TV-Z-]*[0-9A-Z*~$=]-*/i';
} else {
$pattern = '/[0-9A-TV-Z-]*/i';
}
self::_checkEncodedString($encodedStr, $pattern);
// Remove hyphens from encoded string.
$encodedStr = str_replace('-', '', $encodedStr);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// If the last character is a valid Crockford check symbol, remove it from
// the encoded string.
if ($hasCheckSymbol) {
$checkSymbol = $encodedStr[$encodedStrLen - 1];
$encodedStr = self::_extractBytes($encodedStr, 0, $encodedStrLen - 1);
$encodedStrLen--;
}
// Compose Crockford decoding mapping.
$mapping = self::$_crockfordFlippedAlphabet + self::$_crockfordAdditionalCharMapping + array('_' => 0);
// Get decoded content.
if ($to == 'byteStr') {
$decoded = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
} elseif ($to == 'intStr') {
$decoded = self::_crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping);
}
// If check symbol is present, check if decoded string is correct.
if ($hasCheckSymbol) {
if ($to == 'byteStr') {
$intStr = self::_byteStrToIntStr($decoded);
} elseif ($to == 'intStr') {
$intStr = $decoded;
}
$modulus = (int) self::_intStrModulus($intStr, 37);
if ($modulus != $mapping[$checkSymbol]) {
throw new UnexpectedValueException('Check symbol does not match data.', self::E_CHECKSYMBOL_DOES_NOT_MATCH_DATA);
}
}
// Return byte-string.
return $decoded;
} | php | private static function _decodeCrockford($to, $encodedStr, $hasCheckSymbol = false) {
// Check input string.
if ($hasCheckSymbol) {
$pattern = '/[0-9A-TV-Z-]*[0-9A-Z*~$=]-*/i';
} else {
$pattern = '/[0-9A-TV-Z-]*/i';
}
self::_checkEncodedString($encodedStr, $pattern);
// Remove hyphens from encoded string.
$encodedStr = str_replace('-', '', $encodedStr);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// If the last character is a valid Crockford check symbol, remove it from
// the encoded string.
if ($hasCheckSymbol) {
$checkSymbol = $encodedStr[$encodedStrLen - 1];
$encodedStr = self::_extractBytes($encodedStr, 0, $encodedStrLen - 1);
$encodedStrLen--;
}
// Compose Crockford decoding mapping.
$mapping = self::$_crockfordFlippedAlphabet + self::$_crockfordAdditionalCharMapping + array('_' => 0);
// Get decoded content.
if ($to == 'byteStr') {
$decoded = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
} elseif ($to == 'intStr') {
$decoded = self::_crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping);
}
// If check symbol is present, check if decoded string is correct.
if ($hasCheckSymbol) {
if ($to == 'byteStr') {
$intStr = self::_byteStrToIntStr($decoded);
} elseif ($to == 'intStr') {
$intStr = $decoded;
}
$modulus = (int) self::_intStrModulus($intStr, 37);
if ($modulus != $mapping[$checkSymbol]) {
throw new UnexpectedValueException('Check symbol does not match data.', self::E_CHECKSYMBOL_DOES_NOT_MATCH_DATA);
}
}
// Return byte-string.
return $decoded;
} | [
"private",
"static",
"function",
"_decodeCrockford",
"(",
"$",
"to",
",",
"$",
"encodedStr",
",",
"$",
"hasCheckSymbol",
"=",
"false",
")",
"{",
"// Check input string.",
"if",
"(",
"$",
"hasCheckSymbol",
")",
"{",
"$",
"pattern",
"=",
"'/[0-9A-TV-Z-]*[0-9A-Z*~$... | Decodes a Crockford base32 encoded string.
Expects an encoded string according to the base 32 encoding exposed by
Douglas Crockford (http://www.crockford.com/wrmg/base32.html). Throws an
exception if the encoded string is malformed.
If a check symbol is provided and does not match the decoded data, an
exception is thrown.
@param string $to String to specify whether to decode to an integer
('intStr') or to a byte-string ('byteStr').
@param string $encodedStr The encoded string.
@param bool $hasCheckSymbol If true, the last character of the encoded
string is regarded as check symbol.
@return mixed A byte-string (for $to = 'byteStr') or a non-negative
integer or a string representing a non-negative integer (for $to
= 'intStr').
@throws UnexpectedValueException | [
"Decodes",
"a",
"Crockford",
"base32",
"encoded",
"string",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L796-L844 | train |
skleeschulte/php-base32 | src/Base32.php | Base32.decodeZookoToByteStr | public static function decodeZookoToByteStr($encodedStr) {
// Check input string.
$pattern = '/[a-km-uw-z13-9]*/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Add padding character to mapping.
$mapping = self::$_zookoFlippedAlphabet + array('_' => 0);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
// Return byte-string.
return $byteStr;
} | php | public static function decodeZookoToByteStr($encodedStr) {
// Check input string.
$pattern = '/[a-km-uw-z13-9]*/';
self::_checkEncodedString($encodedStr, $pattern);
// Get length (byte count) of encoded string.
$encodedStrLen = self::_byteCount($encodedStr);
// Add padding character to mapping.
$mapping = self::$_zookoFlippedAlphabet + array('_' => 0);
// Get decoded byte-string.
$byteStr = self::_decodeToByteStr($encodedStr, $encodedStrLen, $mapping, '_', true);
// Return byte-string.
return $byteStr;
} | [
"public",
"static",
"function",
"decodeZookoToByteStr",
"(",
"$",
"encodedStr",
")",
"{",
"// Check input string.",
"$",
"pattern",
"=",
"'/[a-km-uw-z13-9]*/'",
";",
"self",
"::",
"_checkEncodedString",
"(",
"$",
"encodedStr",
",",
"$",
"pattern",
")",
";",
"// Ge... | Decodes a Zooko encoded string to a byte-string.
Expects an encoded string according to the base 32 encoding exposed by
Zooko O'Whielacronx
(http://philzimmermann.com/docs/human-oriented-base-32-encoding.txt).
Throws an exception if the encoded string is malformed.
This implementation will always decode full bytes (analog to the base 32
encoding described in RFC 4648), which is one possible proceeding
mentioned in the referred document.
@param string $encodedStr The encoded string.
@return string The decoded byte-string. | [
"Decodes",
"a",
"Zooko",
"encoded",
"string",
"to",
"a",
"byte",
"-",
"string",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L910-L926 | train |
skleeschulte/php-base32 | src/Base32.php | Base32._crockfordDecodeToIntStr | private static function _crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping) {
// Try to use PHP's internal integer type.
if (($encodedStrLen * 5 / 8) <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $encodedStrLen; $i++) {
$int <<= 5;
$int |= $mapping[$encodedStr[$i]];
}
if ($int >= 0)
return $int;
}
// If we did not already return here, PHP's internal integer type can not
// hold the encoded value. Now we use PHP's BC Math library instead and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $encodedStrLen; $i++) {
$intStr = bcmul($intStr, '32', 0);
$intStr = bcadd($intStr, (string) $mapping[$encodedStr[$i]], 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | php | private static function _crockfordDecodeToIntStr($encodedStr, $encodedStrLen, $mapping) {
// Try to use PHP's internal integer type.
if (($encodedStrLen * 5 / 8) <= PHP_INT_SIZE) {
$int = 0;
for ($i = 0; $i < $encodedStrLen; $i++) {
$int <<= 5;
$int |= $mapping[$encodedStr[$i]];
}
if ($int >= 0)
return $int;
}
// If we did not already return here, PHP's internal integer type can not
// hold the encoded value. Now we use PHP's BC Math library instead and
// return the integer as string.
if (extension_loaded('bcmath')) {
$intStr = '0';
for ($i = 0; $i < $encodedStrLen; $i++) {
$intStr = bcmul($intStr, '32', 0);
$intStr = bcadd($intStr, (string) $mapping[$encodedStr[$i]], 0);
}
return $intStr;
} else {
throw new RuntimeException('BC Math functions are not available.', self::E_NO_BCMATH);
}
} | [
"private",
"static",
"function",
"_crockfordDecodeToIntStr",
"(",
"$",
"encodedStr",
",",
"$",
"encodedStrLen",
",",
"$",
"mapping",
")",
"{",
"// Try to use PHP's internal integer type.",
"if",
"(",
"(",
"$",
"encodedStrLen",
"*",
"5",
"/",
"8",
")",
"<=",
"PHP... | Decodes the given base32 encoded string using the given character
mapping to an integer.
Expects the given encoded string to be padding free!
Uses PHP's BC Math library if the integer represented by the given bytes
is too big to be stored in PHP's internal integer type. In this case a
string containing the integer is returned, otherwise a native integer.
@param string $encodedStr The encoded string.
@param int $encodedStrLen Length of the encoded string.
@param array $mapping Associative array mapping the characters in the
encoded string to the values they represent.
@return mixed A non-negative integer or a string representing a
non-negative integer.
@throws RuntimeException | [
"Decodes",
"the",
"given",
"base32",
"encoded",
"string",
"using",
"the",
"given",
"character",
"mapping",
"to",
"an",
"integer",
"."
] | 62a274b148d16f1aafb88967e2ba6209fcea9203 | https://github.com/skleeschulte/php-base32/blob/62a274b148d16f1aafb88967e2ba6209fcea9203/src/Base32.php#L1050-L1075 | train |
paypayue/paypay-soap | src/WebhookHandler.php | WebhookHandler.eachPayment | public function eachPayment($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException("Argument must be callable");
}
foreach ($this->payments as $payment) {
call_user_func_array($callback, array($payment));
}
} | php | public function eachPayment($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException("Argument must be callable");
}
foreach ($this->payments as $payment) {
call_user_func_array($callback, array($payment));
}
} | [
"public",
"function",
"eachPayment",
"(",
"$",
"callback",
")",
"{",
"if",
"(",
"!",
"is_callable",
"(",
"$",
"callback",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Argument must be callable\"",
")",
";",
"}",
"foreach",
"(",
"$... | Loop the payments with a custom callback
@param callable $callback A function to be called on each payment | [
"Loop",
"the",
"payments",
"with",
"a",
"custom",
"callback"
] | ab01d5c041bbf1032fa5725abef5a6b19af746e4 | https://github.com/paypayue/paypay-soap/blob/ab01d5c041bbf1032fa5725abef5a6b19af746e4/src/WebhookHandler.php#L61-L69 | train |
paypayue/paypay-soap | src/WebhookHandler.php | WebhookHandler.isValidHookHash | private function isValidHookHash($privateKey)
{
$confirmationHash = hash('sha256', $privateKey.$this->hookAction.$this->hookDate);
return ($this->hookHash === $confirmationHash);
} | php | private function isValidHookHash($privateKey)
{
$confirmationHash = hash('sha256', $privateKey.$this->hookAction.$this->hookDate);
return ($this->hookHash === $confirmationHash);
} | [
"private",
"function",
"isValidHookHash",
"(",
"$",
"privateKey",
")",
"{",
"$",
"confirmationHash",
"=",
"hash",
"(",
"'sha256'",
",",
"$",
"privateKey",
".",
"$",
"this",
"->",
"hookAction",
".",
"$",
"this",
"->",
"hookDate",
")",
";",
"return",
"(",
... | Validates the request hash using the client private key
@param string $privateKey
@return boolean | [
"Validates",
"the",
"request",
"hash",
"using",
"the",
"client",
"private",
"key"
] | ab01d5c041bbf1032fa5725abef5a6b19af746e4 | https://github.com/paypayue/paypay-soap/blob/ab01d5c041bbf1032fa5725abef5a6b19af746e4/src/WebhookHandler.php#L76-L81 | train |
fezfez/codeGenerator | src/CrudGenerator/Service/CliFactory.php | CliFactory.getInstance | public static function getInstance(OutputInterface $output, InputInterface $input)
{
$questionHelper = new QuestionHelper();
$application = new Application('Code Generator Command Line Interface', 'Alpha');
$application->getHelperSet()->set(new FormatterHelper(), 'formatter');
$application->getHelperSet()->set($questionHelper, 'question');
$context = new CliContext(
$questionHelper,
$output,
$input,
CreateCommandFactory::getInstance($application)
);
$mainBackbone = MainBackboneFactory::getInstance($context);
$mainBackbone->run();
return $application;
} | php | public static function getInstance(OutputInterface $output, InputInterface $input)
{
$questionHelper = new QuestionHelper();
$application = new Application('Code Generator Command Line Interface', 'Alpha');
$application->getHelperSet()->set(new FormatterHelper(), 'formatter');
$application->getHelperSet()->set($questionHelper, 'question');
$context = new CliContext(
$questionHelper,
$output,
$input,
CreateCommandFactory::getInstance($application)
);
$mainBackbone = MainBackboneFactory::getInstance($context);
$mainBackbone->run();
return $application;
} | [
"public",
"static",
"function",
"getInstance",
"(",
"OutputInterface",
"$",
"output",
",",
"InputInterface",
"$",
"input",
")",
"{",
"$",
"questionHelper",
"=",
"new",
"QuestionHelper",
"(",
")",
";",
"$",
"application",
"=",
"new",
"Application",
"(",
"'Code ... | Create CLI instance
@param OutputInterface $output
@param InputInterface $input
@return \Symfony\Component\Console\Application | [
"Create",
"CLI",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Service/CliFactory.php#L35-L54 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getMethods | protected function getMethods()
{
if ($this->option('plain')) {
return [];
}
$methods = ['all', 'find', 'create', 'update', 'delete'];
if (($only = $this->option('only')) && $only != '') {
$methods = array_flip(array_only(array_flip($methods), $this->getArray($only)));
}
if (($except = $this->option('except')) && $except != '') {
$methods = array_flip(array_except(array_flip($methods), $this->getArray($except)));
}
return $methods;
} | php | protected function getMethods()
{
if ($this->option('plain')) {
return [];
}
$methods = ['all', 'find', 'create', 'update', 'delete'];
if (($only = $this->option('only')) && $only != '') {
$methods = array_flip(array_only(array_flip($methods), $this->getArray($only)));
}
if (($except = $this->option('except')) && $except != '') {
$methods = array_flip(array_except(array_flip($methods), $this->getArray($except)));
}
return $methods;
} | [
"protected",
"function",
"getMethods",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"option",
"(",
"'plain'",
")",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"methods",
"=",
"[",
"'all'",
",",
"'find'",
",",
"'create'",
",",
"'update'",
",",
"'de... | Get the methods to implement.
@return array | [
"Get",
"the",
"methods",
"to",
"implement",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L193-L210 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getArray | protected function getArray($values)
{
$values = explode(',', $values);
array_walk($values, function (&$value) {
$value = trim($value);
});
return $values;
} | php | protected function getArray($values)
{
$values = explode(',', $values);
array_walk($values, function (&$value) {
$value = trim($value);
});
return $values;
} | [
"protected",
"function",
"getArray",
"(",
"$",
"values",
")",
"{",
"$",
"values",
"=",
"explode",
"(",
"','",
",",
"$",
"values",
")",
";",
"array_walk",
"(",
"$",
"values",
",",
"function",
"(",
"&",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"tri... | Get an array of the given values.
@param string $values
@return array | [
"Get",
"an",
"array",
"of",
"the",
"given",
"values",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L218-L227 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.compileFileName | protected function compileFileName($className)
{
if (!$className) {
return false;
}
$className = str_replace($this->getAppNamespace(), '', $className);
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
return $className . '.php';
} | php | protected function compileFileName($className)
{
if (!$className) {
return false;
}
$className = str_replace($this->getAppNamespace(), '', $className);
$className = str_replace('\\', DIRECTORY_SEPARATOR, $className);
return $className . '.php';
} | [
"protected",
"function",
"compileFileName",
"(",
"$",
"className",
")",
"{",
"if",
"(",
"!",
"$",
"className",
")",
"{",
"return",
"false",
";",
"}",
"$",
"className",
"=",
"str_replace",
"(",
"$",
"this",
"->",
"getAppNamespace",
"(",
")",
",",
"''",
... | Get a compiled file name for the given full class name.
@param string|bool $className
@return string|bool | [
"Get",
"a",
"compiled",
"file",
"name",
"for",
"the",
"given",
"full",
"class",
"name",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L235-L245 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getContractName | protected function getContractName()
{
if (!$this->input->getOption('contract')) {
return false;
}
$className = $this->getClassName();
return $this->getContractNamespace() . '\\' . $className;
} | php | protected function getContractName()
{
if (!$this->input->getOption('contract')) {
return false;
}
$className = $this->getClassName();
return $this->getContractNamespace() . '\\' . $className;
} | [
"protected",
"function",
"getContractName",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'contract'",
")",
")",
"{",
"return",
"false",
";",
"}",
"$",
"className",
"=",
"$",
"this",
"->",
"getClassName",
"(",
")",... | Get the contract interface name.
@return string|bool | [
"Get",
"the",
"contract",
"interface",
"name",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L265-L274 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getRepositoryName | protected function getRepositoryName()
{
$prefix = $this->getClassNamePrefix();
$name = $this->getClassName();
if ($this->input->getOption('contract')) {
$name = $prefix . $name;
}
return $this->getNamespace() . '\\' . $name;
} | php | protected function getRepositoryName()
{
$prefix = $this->getClassNamePrefix();
$name = $this->getClassName();
if ($this->input->getOption('contract')) {
$name = $prefix . $name;
}
return $this->getNamespace() . '\\' . $name;
} | [
"protected",
"function",
"getRepositoryName",
"(",
")",
"{",
"$",
"prefix",
"=",
"$",
"this",
"->",
"getClassNamePrefix",
"(",
")",
";",
"$",
"name",
"=",
"$",
"this",
"->",
"getClassName",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"input",
"->",
... | Get the repository name.
@return string | [
"Get",
"the",
"repository",
"name",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L281-L291 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getClassNamePrefix | protected function getClassNamePrefix()
{
$prefix = $this->input->getOption('prefix');
if (empty($prefix)) {
$prefix = $this->classNamePrefix;
}
return $prefix;
} | php | protected function getClassNamePrefix()
{
$prefix = $this->input->getOption('prefix');
if (empty($prefix)) {
$prefix = $this->classNamePrefix;
}
return $prefix;
} | [
"protected",
"function",
"getClassNamePrefix",
"(",
")",
"{",
"$",
"prefix",
"=",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'prefix'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"prefix",
")",
")",
"{",
"$",
"prefix",
"=",
"$",
"this",
"->",
... | Get class name prefix.
@return string | [
"Get",
"class",
"name",
"prefix",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L314-L323 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getClassNameSuffix | protected function getClassNameSuffix()
{
$suffix = $this->input->getOption('suffix');
if (empty($suffix)) {
$suffix = $this->classNameSuffix;
}
return $suffix;
} | php | protected function getClassNameSuffix()
{
$suffix = $this->input->getOption('suffix');
if (empty($suffix)) {
$suffix = $this->classNameSuffix;
}
return $suffix;
} | [
"protected",
"function",
"getClassNameSuffix",
"(",
")",
"{",
"$",
"suffix",
"=",
"$",
"this",
"->",
"input",
"->",
"getOption",
"(",
"'suffix'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"suffix",
")",
")",
"{",
"$",
"suffix",
"=",
"$",
"this",
"->",
... | Get class name suffix.
@return string | [
"Get",
"class",
"name",
"suffix",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L330-L339 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getModelReflection | protected function getModelReflection()
{
$modelClassName = str_replace('/', '\\', $this->input->getArgument('model'));
try {
$reflection = new ReflectionClass($this->getAppNamespace() . $modelClassName);
} catch (\ReflectionException $e) {
$reflection = new ReflectionClass($modelClassName);
}
if (!$reflection->isSubclassOf(Model::class) || !$reflection->isInstantiable()) {
throw new NotAnInstanceOfException(sprintf('The model must be an instance of [%s]', Model::class));
}
return $reflection;
} | php | protected function getModelReflection()
{
$modelClassName = str_replace('/', '\\', $this->input->getArgument('model'));
try {
$reflection = new ReflectionClass($this->getAppNamespace() . $modelClassName);
} catch (\ReflectionException $e) {
$reflection = new ReflectionClass($modelClassName);
}
if (!$reflection->isSubclassOf(Model::class) || !$reflection->isInstantiable()) {
throw new NotAnInstanceOfException(sprintf('The model must be an instance of [%s]', Model::class));
}
return $reflection;
} | [
"protected",
"function",
"getModelReflection",
"(",
")",
"{",
"$",
"modelClassName",
"=",
"str_replace",
"(",
"'/'",
",",
"'\\\\'",
",",
"$",
"this",
"->",
"input",
"->",
"getArgument",
"(",
"'model'",
")",
")",
";",
"try",
"{",
"$",
"reflection",
"=",
"... | Get the model class name.
@return ReflectionClass
@throws \VTalbot\RepositoryGenerator\Exceptions\NotAnInstanceOfException | [
"Get",
"the",
"model",
"class",
"name",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L347-L362 | train |
vtalbot/repository-generator | src/Console/RepositoryMakeCommand.php | RepositoryMakeCommand.getNamespace | protected function getNamespace($namespace = null)
{
if (!is_null($namespace)) {
$parts = explode('\\', $namespace);
array_pop($parts);
return join('\\', $parts);
}
return $this->getAppNamespace() . $this->namespace;
} | php | protected function getNamespace($namespace = null)
{
if (!is_null($namespace)) {
$parts = explode('\\', $namespace);
array_pop($parts);
return join('\\', $parts);
}
return $this->getAppNamespace() . $this->namespace;
} | [
"protected",
"function",
"getNamespace",
"(",
"$",
"namespace",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"namespace",
")",
")",
"{",
"$",
"parts",
"=",
"explode",
"(",
"'\\\\'",
",",
"$",
"namespace",
")",
";",
"array_pop",
"(",
"$... | Get the namespace of the repositories classes.
@return string | [
"Get",
"the",
"namespace",
"of",
"the",
"repositories",
"classes",
"."
] | e74924552bd322c3b6f93087a049896d960843e3 | https://github.com/vtalbot/repository-generator/blob/e74924552bd322c3b6f93087a049896d960843e3/src/Console/RepositoryMakeCommand.php#L379-L390 | train |
mapbender/fom | src/FOM/UserBundle/Form/EventListener/UserSubscriber.php | UserSubscriber.submit | public function submit(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if ($this->currentUser !== null && $this->currentUser !== $user && $event->getForm()->has('activated')) {
$activated = $event->getForm()->get('activated')->getData();
if ($activated && $user->getRegistrationToken()) {
$user->setRegistrationToken(null);
} elseif (!$activated && !$user->getRegistrationToken()) {
$user->setRegistrationToken(hash("sha1",rand()));
}
}
} | php | public function submit(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if ($this->currentUser !== null && $this->currentUser !== $user && $event->getForm()->has('activated')) {
$activated = $event->getForm()->get('activated')->getData();
if ($activated && $user->getRegistrationToken()) {
$user->setRegistrationToken(null);
} elseif (!$activated && !$user->getRegistrationToken()) {
$user->setRegistrationToken(hash("sha1",rand()));
}
}
} | [
"public",
"function",
"submit",
"(",
"FormEvent",
"$",
"event",
")",
"{",
"$",
"user",
"=",
"$",
"event",
"->",
"getData",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"user",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"currentU... | Checkt form fields by SUBMIT FormEvent
@param FormEvent $event | [
"Checkt",
"form",
"fields",
"by",
"SUBMIT",
"FormEvent"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Form/EventListener/UserSubscriber.php#L56-L70 | train |
mapbender/fom | src/FOM/UserBundle/Form/EventListener/UserSubscriber.php | UserSubscriber.preSetData | public function preSetData(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if($this->currentUser !== null && $this->currentUser !== $user) {
$event->getForm()->add($this->factory->createNamed('activated', 'checkbox', null, array(
'data' => $user->getRegistrationToken() ? false : true,
'auto_initialize' => false,
'label' => 'Activated',
'required' => false,
'mapped' => false)));
}
} | php | public function preSetData(FormEvent $event)
{
$user = $event->getData();
if (null === $user) {
return;
}
if($this->currentUser !== null && $this->currentUser !== $user) {
$event->getForm()->add($this->factory->createNamed('activated', 'checkbox', null, array(
'data' => $user->getRegistrationToken() ? false : true,
'auto_initialize' => false,
'label' => 'Activated',
'required' => false,
'mapped' => false)));
}
} | [
"public",
"function",
"preSetData",
"(",
"FormEvent",
"$",
"event",
")",
"{",
"$",
"user",
"=",
"$",
"event",
"->",
"getData",
"(",
")",
";",
"if",
"(",
"null",
"===",
"$",
"user",
")",
"{",
"return",
";",
"}",
"if",
"(",
"$",
"this",
"->",
"curr... | Checkt form fields by PRE_SET_DATA FormEvent
@param FormEvent $event | [
"Checkt",
"form",
"fields",
"by",
"PRE_SET_DATA",
"FormEvent"
] | 6dea943121f3c3f9b1b4b14dc2a8e8640a120675 | https://github.com/mapbender/fom/blob/6dea943121f3c3f9b1b4b14dc2a8e8640a120675/src/FOM/UserBundle/Form/EventListener/UserSubscriber.php#L77-L91 | train |
AXN-Informatique/laravel-glide | src/ServerManager.php | ServerManager.server | public function server($name = null)
{
if (empty($name)) {
$name = $this->getDefaultServerName();
}
if (!isset($this->servers[$name])) {
$this->servers[$name] = $this->makeServer($name);
}
return $this->servers[$name];
} | php | public function server($name = null)
{
if (empty($name)) {
$name = $this->getDefaultServerName();
}
if (!isset($this->servers[$name])) {
$this->servers[$name] = $this->makeServer($name);
}
return $this->servers[$name];
} | [
"public",
"function",
"server",
"(",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"$",
"name",
"=",
"$",
"this",
"->",
"getDefaultServerName",
"(",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"t... | Get a server instance.
@param string|null $name
@return GlideServer | [
"Get",
"a",
"server",
"instance",
"."
] | 85fbf70dcc87c8aeda25411b86f26a1f5f55b2c2 | https://github.com/AXN-Informatique/laravel-glide/blob/85fbf70dcc87c8aeda25411b86f26a1f5f55b2c2/src/ServerManager.php#L40-L51 | train |
AXN-Informatique/laravel-glide | src/ServerManager.php | ServerManager.makeServer | protected function makeServer($name)
{
$config = $this->getConfig($name);
if (empty($config)) {
throw new \InvalidArgumentException("Unable to instantiate Glide server because you provide en empty configuration, \"{$name}\" is probably a wrong server name.");
}
if (array_key_exists($config['source'], $this->app['config']['filesystems']['disks'])) {
$config['source'] = $this->app['filesystem']->disk($config['source'])->getDriver();
}
if (array_key_exists($config['cache'], $this->app['config']['filesystems']['disks'])) {
$config['cache'] = $this->app['filesystem']->disk($config['cache'])->getDriver();
}
if (isset($config['watermarks']) && array_key_exists($config['watermarks'], $this->app['config']['filesystems']['disks'])) {
$config['watermarks'] = $this->app['filesystem']->disk($config['watermarks'])->getDriver();
}
return new GlideServer($this->app, $config);
} | php | protected function makeServer($name)
{
$config = $this->getConfig($name);
if (empty($config)) {
throw new \InvalidArgumentException("Unable to instantiate Glide server because you provide en empty configuration, \"{$name}\" is probably a wrong server name.");
}
if (array_key_exists($config['source'], $this->app['config']['filesystems']['disks'])) {
$config['source'] = $this->app['filesystem']->disk($config['source'])->getDriver();
}
if (array_key_exists($config['cache'], $this->app['config']['filesystems']['disks'])) {
$config['cache'] = $this->app['filesystem']->disk($config['cache'])->getDriver();
}
if (isset($config['watermarks']) && array_key_exists($config['watermarks'], $this->app['config']['filesystems']['disks'])) {
$config['watermarks'] = $this->app['filesystem']->disk($config['watermarks'])->getDriver();
}
return new GlideServer($this->app, $config);
} | [
"protected",
"function",
"makeServer",
"(",
"$",
"name",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"$",
"name",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"config",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
... | Make the server instance.
@param string $name
@return GlideServer | [
"Make",
"the",
"server",
"instance",
"."
] | 85fbf70dcc87c8aeda25411b86f26a1f5f55b2c2 | https://github.com/AXN-Informatique/laravel-glide/blob/85fbf70dcc87c8aeda25411b86f26a1f5f55b2c2/src/ServerManager.php#L59-L80 | train |
manaphp/framework | Cli/Controllers/HelpController.php | HelpController.listCommand | public function listCommand()
{
$this->console->writeLn('manaphp commands:', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob(__DIR__ . '/*Controller.php') as $file) {
$plainName = basename($file, '.php');
if (in_array($plainName, ['BashCompletionController', 'HelpController'], true)) {
continue;
}
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands(__NAMESPACE__ . "\\" . $plainName);
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width) . ' ' . $description);
}
}
if ($this->alias->has('@cli')) {
$this->console->writeLn('application commands: ', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob($this->alias->resolve('@cli/*Controller.php')) as $file) {
$plainName = basename($file, '.php');
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands($this->alias->resolveNS("@ns.cli\\$plainName"));
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width + 1) . ' ' . $description);
}
}
}
return 0;
} | php | public function listCommand()
{
$this->console->writeLn('manaphp commands:', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob(__DIR__ . '/*Controller.php') as $file) {
$plainName = basename($file, '.php');
if (in_array($plainName, ['BashCompletionController', 'HelpController'], true)) {
continue;
}
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands(__NAMESPACE__ . "\\" . $plainName);
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width) . ' ' . $description);
}
}
if ($this->alias->has('@cli')) {
$this->console->writeLn('application commands: ', Console::FC_GREEN | Console::AT_BOLD);
foreach (glob($this->alias->resolve('@cli/*Controller.php')) as $file) {
$plainName = basename($file, '.php');
$this->console->writeLn(' - ' . $this->console->colorize(Text::underscore(basename($plainName, 'Controller')), Console::FC_YELLOW));
$commands = $this->_getCommands($this->alias->resolveNS("@ns.cli\\$plainName"));
$width = max(max(array_map('strlen', array_keys($commands))), 18);
foreach ($commands as $command => $description) {
$this->console->writeLn(' ' . $this->console->colorize($command, Console::FC_CYAN, $width + 1) . ' ' . $description);
}
}
}
return 0;
} | [
"public",
"function",
"listCommand",
"(",
")",
"{",
"$",
"this",
"->",
"console",
"->",
"writeLn",
"(",
"'manaphp commands:'",
",",
"Console",
"::",
"FC_GREEN",
"|",
"Console",
"::",
"AT_BOLD",
")",
";",
"foreach",
"(",
"glob",
"(",
"__DIR__",
".",
"'/*Con... | list all commands
@return int | [
"list",
"all",
"commands"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/HelpController.php#L20-L54 | train |
fezfez/codeGenerator | src/CrudGenerator/Backbone/CreateSourceBackboneFactory.php | CreateSourceBackboneFactory.getInstance | public static function getInstance(ContextInterface $context)
{
return new CreateSourceBackbone(
MetadataSourceQuestionFactory::getInstance($context),
MetaDataConfigDAOFactory::getInstance($context),
$context
);
} | php | public static function getInstance(ContextInterface $context)
{
return new CreateSourceBackbone(
MetadataSourceQuestionFactory::getInstance($context),
MetaDataConfigDAOFactory::getInstance($context),
$context
);
} | [
"public",
"static",
"function",
"getInstance",
"(",
"ContextInterface",
"$",
"context",
")",
"{",
"return",
"new",
"CreateSourceBackbone",
"(",
"MetadataSourceQuestionFactory",
"::",
"getInstance",
"(",
"$",
"context",
")",
",",
"MetaDataConfigDAOFactory",
"::",
"getI... | Create CreateSourceBackbone instance
@param ContextInterface $context
@return \CrudGenerator\Backbone\CreateSourceBackbone | [
"Create",
"CreateSourceBackbone",
"instance"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Backbone/CreateSourceBackboneFactory.php#L24-L31 | train |
manaphp/framework | Cli/Controllers/TaskController.php | TaskController.listCommand | public function listCommand()
{
$this->console->writeLn('tasks list:');
$tasks = [];
$tasksDir = $this->alias->resolve('@app/Tasks');
if (is_dir($tasksDir)) {
foreach (glob("$tasksDir/*Task.php") as $file) {
$task = basename($file, 'Task.php');
$tasks[] = ['name' => Text::underscore($task), 'desc' => $this->_getTaskDescription($task)];
}
}
$width = max(array_map(static function ($v) {
return strlen($v['name']);
}, $tasks)) + 3;
foreach ($tasks as $task) {
$this->console->writeLn([' :1 :2', $this->console->colorize($task['name'], Console::FC_MAGENTA, $width), $task['desc']]);
}
} | php | public function listCommand()
{
$this->console->writeLn('tasks list:');
$tasks = [];
$tasksDir = $this->alias->resolve('@app/Tasks');
if (is_dir($tasksDir)) {
foreach (glob("$tasksDir/*Task.php") as $file) {
$task = basename($file, 'Task.php');
$tasks[] = ['name' => Text::underscore($task), 'desc' => $this->_getTaskDescription($task)];
}
}
$width = max(array_map(static function ($v) {
return strlen($v['name']);
}, $tasks)) + 3;
foreach ($tasks as $task) {
$this->console->writeLn([' :1 :2', $this->console->colorize($task['name'], Console::FC_MAGENTA, $width), $task['desc']]);
}
} | [
"public",
"function",
"listCommand",
"(",
")",
"{",
"$",
"this",
"->",
"console",
"->",
"writeLn",
"(",
"'tasks list:'",
")",
";",
"$",
"tasks",
"=",
"[",
"]",
";",
"$",
"tasksDir",
"=",
"$",
"this",
"->",
"alias",
"->",
"resolve",
"(",
"'@app/Tasks'",... | list all tasks | [
"list",
"all",
"tasks"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/TaskController.php#L20-L38 | train |
webfactory/symfony-application-tests | src/Webfactory/Util/VendorResources.php | VendorResources.isVendorClass | public static function isVendorClass($classNameOrObject)
{
$className = (is_object($classNameOrObject)) ? get_class($classNameOrObject) : $classNameOrObject;
if (!class_exists($className)) {
$message = '"' . $className . '" is not the name of a loadable class.';
throw new \InvalidArgumentException($message);
}
$reflection = new \ReflectionClass($className);
if ($reflection->isInternal()) {
return false;
}
return static::isVendorFile($reflection->getFileName());
} | php | public static function isVendorClass($classNameOrObject)
{
$className = (is_object($classNameOrObject)) ? get_class($classNameOrObject) : $classNameOrObject;
if (!class_exists($className)) {
$message = '"' . $className . '" is not the name of a loadable class.';
throw new \InvalidArgumentException($message);
}
$reflection = new \ReflectionClass($className);
if ($reflection->isInternal()) {
return false;
}
return static::isVendorFile($reflection->getFileName());
} | [
"public",
"static",
"function",
"isVendorClass",
"(",
"$",
"classNameOrObject",
")",
"{",
"$",
"className",
"=",
"(",
"is_object",
"(",
"$",
"classNameOrObject",
")",
")",
"?",
"get_class",
"(",
"$",
"classNameOrObject",
")",
":",
"$",
"classNameOrObject",
";"... | Checks if the given class is located in the vendor directory.
For convenience, it is also possible to pass an object whose
class is then checked.
@param string|object $classNameOrObject
@return boolean
@throws \InvalidArgumentException If no valid class name or object is passed. | [
"Checks",
"if",
"the",
"given",
"class",
"is",
"located",
"in",
"the",
"vendor",
"directory",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Util/VendorResources.php#L28-L40 | train |
webfactory/symfony-application-tests | src/Webfactory/Util/VendorResources.php | VendorResources.isVendorFile | public static function isVendorFile($pathOrFileObject)
{
$path = ($pathOrFileObject instanceof \SplFileInfo) ? $pathOrFileObject->getPathname() : $pathOrFileObject;
if (!file_exists($path)) {
$message = '"' . $path . '" does not reference a file or directory.';
throw new \InvalidArgumentException($message);
}
// The file path must start with the vendor directory.
return strpos($path, static::getVendorDirectory()) === 0;
} | php | public static function isVendorFile($pathOrFileObject)
{
$path = ($pathOrFileObject instanceof \SplFileInfo) ? $pathOrFileObject->getPathname() : $pathOrFileObject;
if (!file_exists($path)) {
$message = '"' . $path . '" does not reference a file or directory.';
throw new \InvalidArgumentException($message);
}
// The file path must start with the vendor directory.
return strpos($path, static::getVendorDirectory()) === 0;
} | [
"public",
"static",
"function",
"isVendorFile",
"(",
"$",
"pathOrFileObject",
")",
"{",
"$",
"path",
"=",
"(",
"$",
"pathOrFileObject",
"instanceof",
"\\",
"SplFileInfo",
")",
"?",
"$",
"pathOrFileObject",
"->",
"getPathname",
"(",
")",
":",
"$",
"pathOrFileOb... | Checks if the given file is located in the vendor directory.
@param string|\SplFileInfo $pathOrFileObject
@return boolean
@throws \InvalidArgumentException If no valid file path is provided. | [
"Checks",
"if",
"the",
"given",
"file",
"is",
"located",
"in",
"the",
"vendor",
"directory",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Util/VendorResources.php#L49-L58 | train |
paypayue/paypay-soap | src/Structure/PaymentMethodCode.php | PaymentMethodCode.code | public static function code($constant)
{
$ref = new \ReflectionClass('\PayPay\Structure\PaymentMethodCode');
$constants = $ref->getConstants();
if (!isset($constants[$constant])) {
throw new \InvalidArgumentException("Invalid payment method code constant " . $constant);
}
return $ref->getConstant($constant);
} | php | public static function code($constant)
{
$ref = new \ReflectionClass('\PayPay\Structure\PaymentMethodCode');
$constants = $ref->getConstants();
if (!isset($constants[$constant])) {
throw new \InvalidArgumentException("Invalid payment method code constant " . $constant);
}
return $ref->getConstant($constant);
} | [
"public",
"static",
"function",
"code",
"(",
"$",
"constant",
")",
"{",
"$",
"ref",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"'\\PayPay\\Structure\\PaymentMethodCode'",
")",
";",
"$",
"constants",
"=",
"$",
"ref",
"->",
"getConstants",
"(",
")",
";",
"if",
... | Helper method to get a code using the class constant name.
@param string $constant The Payment Method Code constant
@return string The defined constant | [
"Helper",
"method",
"to",
"get",
"a",
"code",
"using",
"the",
"class",
"constant",
"name",
"."
] | ab01d5c041bbf1032fa5725abef5a6b19af746e4 | https://github.com/paypayue/paypay-soap/blob/ab01d5c041bbf1032fa5725abef5a6b19af746e4/src/Structure/PaymentMethodCode.php#L16-L25 | train |
manaphp/framework | Dom/CssToXPath.php | CssToXPath._transform | protected function _transform($path_src)
{
$path = (string)$path_src;
if (strpos($path, ',') !== false) {
$paths = explode(',', $path);
$expressions = [];
foreach ($paths as $path) {
$xpath = $this->transform(trim($path));
if (is_string($xpath)) {
$expressions[] = $xpath;
} elseif (is_array($xpath)) {
/** @noinspection SlowArrayOperationsInLoopInspection */
$expressions = array_merge($expressions, $xpath);
}
}
return implode('|', $expressions);
}
$paths = ['//'];
$path = preg_replace('|\s+>\s+|', '>', $path);
$segments = preg_split('/\s+/', $path);
foreach ($segments as $key => $segment) {
$pathSegment = static::_tokenize($segment);
if (0 === $key) {
if (0 === strpos($pathSegment, '[contains(')) {
$paths[0] .= '*' . ltrim($pathSegment, '*');
} else {
$paths[0] .= $pathSegment;
}
continue;
}
if (0 === strpos($pathSegment, '[contains(')) {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//*' . ltrim($pathSegment, '*');
$paths[] = $xpath . $pathSegment;
}
} else {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//' . $pathSegment;
}
}
}
if (1 === count($paths)) {
return $paths[0];
}
return implode('|', $paths);
} | php | protected function _transform($path_src)
{
$path = (string)$path_src;
if (strpos($path, ',') !== false) {
$paths = explode(',', $path);
$expressions = [];
foreach ($paths as $path) {
$xpath = $this->transform(trim($path));
if (is_string($xpath)) {
$expressions[] = $xpath;
} elseif (is_array($xpath)) {
/** @noinspection SlowArrayOperationsInLoopInspection */
$expressions = array_merge($expressions, $xpath);
}
}
return implode('|', $expressions);
}
$paths = ['//'];
$path = preg_replace('|\s+>\s+|', '>', $path);
$segments = preg_split('/\s+/', $path);
foreach ($segments as $key => $segment) {
$pathSegment = static::_tokenize($segment);
if (0 === $key) {
if (0 === strpos($pathSegment, '[contains(')) {
$paths[0] .= '*' . ltrim($pathSegment, '*');
} else {
$paths[0] .= $pathSegment;
}
continue;
}
if (0 === strpos($pathSegment, '[contains(')) {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//*' . ltrim($pathSegment, '*');
$paths[] = $xpath . $pathSegment;
}
} else {
foreach ($paths as $pathKey => $xpath) {
$paths[$pathKey] .= '//' . $pathSegment;
}
}
}
if (1 === count($paths)) {
return $paths[0];
}
return implode('|', $paths);
} | [
"protected",
"function",
"_transform",
"(",
"$",
"path_src",
")",
"{",
"$",
"path",
"=",
"(",
"string",
")",
"$",
"path_src",
";",
"if",
"(",
"strpos",
"(",
"$",
"path",
",",
"','",
")",
"!==",
"false",
")",
"{",
"$",
"paths",
"=",
"explode",
"(",
... | Transform CSS expression to XPath
@param string $path_src
@return string | [
"Transform",
"CSS",
"expression",
"to",
"XPath"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Dom/CssToXPath.php#L56-L104 | train |
manaphp/framework | Dom/CssToXPath.php | CssToXPath._tokenize | protected static function _tokenize($expression_src)
{
// Child selectors
$expression = str_replace('>', '/', $expression_src);
// IDs
$expression = preg_replace('|#([a-z][a-z0-9_-]*)|i', "[@id='$1']", $expression);
$expression = preg_replace('|(?<![a-z0-9_-])(\[@id=)|i', '*$1', $expression);
// arbitrary attribute strict equality
$expression = preg_replace_callback(
'|\[@?([a-z0-9_-]*)([~\*\^\$\|\!])?=([^\[]+)\]|i',
static function ($matches) {
$attr = strtolower($matches[1]);
$type = $matches[2];
$val = trim($matches[3], "'\" \t");
$field = ($attr === '' ? 'text()' : '@' . $attr);
$items = [];
foreach (explode(strpos($val, '|') !== false ? '|' : '&', $val) as $word) {
if ($type === '') {
$items[] = "$field='$word'";
} elseif ($type === '~') {
$items[] = "contains(concat(' ', normalize-space($field), ' '), ' $word ')";
} elseif ($type === '|') {
$item = "$field='$word' or starts-with($field,'$word-')";
$items[] = $word === $val ? $item : "($item)";
} elseif ($type === '!') {
$item = "not($field) or $field!='$word'";
$items[] = $word === $val ? $item : "($item)";
} else {
$items[] = ['*' => 'contains', '^' => 'starts-with', '$' => 'ends-with'][$type] . "($field, '$word')";
}
}
return '[' . implode(strpos($val, '|') !== false ? ' or ' : ' and ', $items) . ']';
},
$expression
);
//attribute contains specified content
$expression = preg_replace_callback(
'|\[(!?)([a-z][a-z0-9_-\|&]*)\]|i',
static function ($matches) {
$val = $matches[2];
$op = strpos($val, '|') !== false ? '|' : '&';
$items = [];
foreach (explode($op, $val) as $word) {
$items[] = '@' . $word;
}
$r = '[' . implode($op === '|' ? ' or ' : ' and ', $items) . ']';
return $matches[1] === '!' ? "not($r)" : $r;
},
$expression
);
// Classes
if (false === strpos($expression, '[@')) {
$expression = preg_replace(
'|\.([a-z][a-z0-9_-]*)|i',
"[contains(concat(' ', normalize-space(@class), ' '), ' \$1 ')]",
$expression
);
}
/** ZF-9764 -- remove double asterisk */
$expression = str_replace('**', '*', $expression);
return $expression;
} | php | protected static function _tokenize($expression_src)
{
// Child selectors
$expression = str_replace('>', '/', $expression_src);
// IDs
$expression = preg_replace('|#([a-z][a-z0-9_-]*)|i', "[@id='$1']", $expression);
$expression = preg_replace('|(?<![a-z0-9_-])(\[@id=)|i', '*$1', $expression);
// arbitrary attribute strict equality
$expression = preg_replace_callback(
'|\[@?([a-z0-9_-]*)([~\*\^\$\|\!])?=([^\[]+)\]|i',
static function ($matches) {
$attr = strtolower($matches[1]);
$type = $matches[2];
$val = trim($matches[3], "'\" \t");
$field = ($attr === '' ? 'text()' : '@' . $attr);
$items = [];
foreach (explode(strpos($val, '|') !== false ? '|' : '&', $val) as $word) {
if ($type === '') {
$items[] = "$field='$word'";
} elseif ($type === '~') {
$items[] = "contains(concat(' ', normalize-space($field), ' '), ' $word ')";
} elseif ($type === '|') {
$item = "$field='$word' or starts-with($field,'$word-')";
$items[] = $word === $val ? $item : "($item)";
} elseif ($type === '!') {
$item = "not($field) or $field!='$word'";
$items[] = $word === $val ? $item : "($item)";
} else {
$items[] = ['*' => 'contains', '^' => 'starts-with', '$' => 'ends-with'][$type] . "($field, '$word')";
}
}
return '[' . implode(strpos($val, '|') !== false ? ' or ' : ' and ', $items) . ']';
},
$expression
);
//attribute contains specified content
$expression = preg_replace_callback(
'|\[(!?)([a-z][a-z0-9_-\|&]*)\]|i',
static function ($matches) {
$val = $matches[2];
$op = strpos($val, '|') !== false ? '|' : '&';
$items = [];
foreach (explode($op, $val) as $word) {
$items[] = '@' . $word;
}
$r = '[' . implode($op === '|' ? ' or ' : ' and ', $items) . ']';
return $matches[1] === '!' ? "not($r)" : $r;
},
$expression
);
// Classes
if (false === strpos($expression, '[@')) {
$expression = preg_replace(
'|\.([a-z][a-z0-9_-]*)|i',
"[contains(concat(' ', normalize-space(@class), ' '), ' \$1 ')]",
$expression
);
}
/** ZF-9764 -- remove double asterisk */
$expression = str_replace('**', '*', $expression);
return $expression;
} | [
"protected",
"static",
"function",
"_tokenize",
"(",
"$",
"expression_src",
")",
"{",
"// Child selectors",
"$",
"expression",
"=",
"str_replace",
"(",
"'>'",
",",
"'/'",
",",
"$",
"expression_src",
")",
";",
"// IDs",
"$",
"expression",
"=",
"preg_replace",
"... | Tokenize CSS expressions to XPath
@param string $expression_src
@return string | [
"Tokenize",
"CSS",
"expressions",
"to",
"XPath"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Dom/CssToXPath.php#L113-L183 | train |
jbouzekri/ConfigKnpMenuBundle | Provider/ConfigurationMenuProvider.php | ConfigurationMenuProvider.sortItems | protected function sortItems(&$items)
{
$this->safeUaSortItems($items, function ($item1, $item2) {
if (empty($item1['order']) || empty($item2['order']) || $item1['order'] == $item2['order']) {
return 0;
}
return ($item1['order'] < $item2['order']) ? -1 : 1;
});
} | php | protected function sortItems(&$items)
{
$this->safeUaSortItems($items, function ($item1, $item2) {
if (empty($item1['order']) || empty($item2['order']) || $item1['order'] == $item2['order']) {
return 0;
}
return ($item1['order'] < $item2['order']) ? -1 : 1;
});
} | [
"protected",
"function",
"sortItems",
"(",
"&",
"$",
"items",
")",
"{",
"$",
"this",
"->",
"safeUaSortItems",
"(",
"$",
"items",
",",
"function",
"(",
"$",
"item1",
",",
"$",
"item2",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"item1",
"[",
"'order'",
... | Sort items according to the order key value
@param array $items an array of items | [
"Sort",
"items",
"according",
"to",
"the",
"order",
"key",
"value"
] | d5a6154de04f3f7342f68496cad02a1b4a3846b9 | https://github.com/jbouzekri/ConfigKnpMenuBundle/blob/d5a6154de04f3f7342f68496cad02a1b4a3846b9/Provider/ConfigurationMenuProvider.php#L176-L185 | train |
jbouzekri/ConfigKnpMenuBundle | Provider/ConfigurationMenuProvider.php | ConfigurationMenuProvider.isGranted | protected function isGranted(array $configuration)
{
// If no role configuration. Grant rights.
if (!isset($configuration['roles'])) {
return true;
}
// If no configuration. Grant rights.
if (!is_array($configuration['roles'])) {
return true;
}
// Check if one of the role is granted
foreach ($configuration['roles'] as $role) {
if ($this->authorizationChecker->isGranted($role)) {
return true;
}
}
// Else return false
return false;
} | php | protected function isGranted(array $configuration)
{
// If no role configuration. Grant rights.
if (!isset($configuration['roles'])) {
return true;
}
// If no configuration. Grant rights.
if (!is_array($configuration['roles'])) {
return true;
}
// Check if one of the role is granted
foreach ($configuration['roles'] as $role) {
if ($this->authorizationChecker->isGranted($role)) {
return true;
}
}
// Else return false
return false;
} | [
"protected",
"function",
"isGranted",
"(",
"array",
"$",
"configuration",
")",
"{",
"// If no role configuration. Grant rights.",
"if",
"(",
"!",
"isset",
"(",
"$",
"configuration",
"[",
"'roles'",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"// If no config... | Check if security context grant rights on menu item
@param array $configuration
@return boolean | [
"Check",
"if",
"security",
"context",
"grant",
"rights",
"on",
"menu",
"item"
] | d5a6154de04f3f7342f68496cad02a1b4a3846b9 | https://github.com/jbouzekri/ConfigKnpMenuBundle/blob/d5a6154de04f3f7342f68496cad02a1b4a3846b9/Provider/ConfigurationMenuProvider.php#L244-L265 | train |
tamagokun/pomander | lib/Pomander/RemoteShell.php | RemoteShell.process | protected function process()
{
$output = "";
$offset = 0;
$this->shell->_initShell();
while( true ) {
$temp = $this->shell->_get_channel_packet(SSH2::CHANNEL_EXEC);
switch( true ) {
case $temp === true:
case $temp === false:
return $output;
default:
$output .= $temp;
if( $this->handle_data(substr($output, $offset)) ) {
$offset = strlen($output);
}
}
}
} | php | protected function process()
{
$output = "";
$offset = 0;
$this->shell->_initShell();
while( true ) {
$temp = $this->shell->_get_channel_packet(SSH2::CHANNEL_EXEC);
switch( true ) {
case $temp === true:
case $temp === false:
return $output;
default:
$output .= $temp;
if( $this->handle_data(substr($output, $offset)) ) {
$offset = strlen($output);
}
}
}
} | [
"protected",
"function",
"process",
"(",
")",
"{",
"$",
"output",
"=",
"\"\"",
";",
"$",
"offset",
"=",
"0",
";",
"$",
"this",
"->",
"shell",
"->",
"_initShell",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"$",
"temp",
"=",
"$",
"this",
"->",
... | Process remote command execution
@return string | [
"Process",
"remote",
"command",
"execution"
] | 1240911c38750c13cb54e590e9a63caec246c491 | https://github.com/tamagokun/pomander/blob/1240911c38750c13cb54e590e9a63caec246c491/lib/Pomander/RemoteShell.php#L70-L88 | train |
manaphp/framework | Cli/Controllers/KeyController.php | KeyController.generateCommand | public function generateCommand($length = 32, $lowercase = 0)
{
$key = $this->random->getBase($length);
$this->console->writeLn($lowercase ? strtolower($key) : $key);
} | php | public function generateCommand($length = 32, $lowercase = 0)
{
$key = $this->random->getBase($length);
$this->console->writeLn($lowercase ? strtolower($key) : $key);
} | [
"public",
"function",
"generateCommand",
"(",
"$",
"length",
"=",
"32",
",",
"$",
"lowercase",
"=",
"0",
")",
"{",
"$",
"key",
"=",
"$",
"this",
"->",
"random",
"->",
"getBase",
"(",
"$",
"length",
")",
";",
"$",
"this",
"->",
"console",
"->",
"wri... | generate random key
@param int $length length of key(default is 32 characters)
@param int $lowercase | [
"generate",
"random",
"key"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/KeyController.php#L15-L19 | train |
milejko/mmi-cms | src/CmsAdmin/Grid/Grid.php | Grid.addColumn | public final function addColumn(Column\ColumnAbstract $column)
{
//dodawanie Columnu (nazwa unikalna)
return $this->_columns[$column->getName()] = $column->setGrid($this);
} | php | public final function addColumn(Column\ColumnAbstract $column)
{
//dodawanie Columnu (nazwa unikalna)
return $this->_columns[$column->getName()] = $column->setGrid($this);
} | [
"public",
"final",
"function",
"addColumn",
"(",
"Column",
"\\",
"ColumnAbstract",
"$",
"column",
")",
"{",
"//dodawanie Columnu (nazwa unikalna)",
"return",
"$",
"this",
"->",
"_columns",
"[",
"$",
"column",
"->",
"getName",
"(",
")",
"]",
"=",
"$",
"column",... | Dodaje Column grida
@param \CmsAdmin\Grid\Column\ColumnAbstract $column
@return Column\ColumnAbstract | [
"Dodaje",
"Column",
"grida"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Grid/Grid.php#L69-L73 | train |
claroline/MessageBundle | Repository/MessageRepository.php | MessageRepository.countUnread | public function countUnread(User $user)
{
return $this->createQueryBuilder('m')
->select('count(m)')
->join('m.userMessages', 'um')
->where('m.user != :sender')
->orWhere('m.user IS NULL')
->andWhere('um.user = :user')
->andWhere('um.isRead = 0')
->andWhere('um.isRemoved = 0')
->setParameter(':user', $user)
->setParameter(':sender', $user)
->getQuery()
->getSingleScalarResult();
} | php | public function countUnread(User $user)
{
return $this->createQueryBuilder('m')
->select('count(m)')
->join('m.userMessages', 'um')
->where('m.user != :sender')
->orWhere('m.user IS NULL')
->andWhere('um.user = :user')
->andWhere('um.isRead = 0')
->andWhere('um.isRemoved = 0')
->setParameter(':user', $user)
->setParameter(':sender', $user)
->getQuery()
->getSingleScalarResult();
} | [
"public",
"function",
"countUnread",
"(",
"User",
"$",
"user",
")",
"{",
"return",
"$",
"this",
"->",
"createQueryBuilder",
"(",
"'m'",
")",
"->",
"select",
"(",
"'count(m)'",
")",
"->",
"join",
"(",
"'m.userMessages'",
",",
"'um'",
")",
"->",
"where",
"... | Counts the number of unread messages of a user.
@param User $user
@return integer | [
"Counts",
"the",
"number",
"of",
"unread",
"messages",
"of",
"a",
"user",
"."
] | 705f999780875ef5b657f9cc07b87f8d11e855d5 | https://github.com/claroline/MessageBundle/blob/705f999780875ef5b657f9cc07b87f8d11e855d5/Repository/MessageRepository.php#L56-L70 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileQuery.php | CmsFileQuery.imagesByObject | public static function imagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie
return self::byObject($object, $objectId)
->whereClass()->equals('image');
} | php | public static function imagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie
return self::byObject($object, $objectId)
->whereClass()->equals('image');
} | [
"public",
"static",
"function",
"imagesByObject",
"(",
"$",
"object",
"=",
"null",
",",
"$",
"objectId",
"=",
"null",
")",
"{",
"//zapytanie po obiekcie",
"return",
"self",
"::",
"byObject",
"(",
"$",
"object",
",",
"$",
"objectId",
")",
"->",
"whereClass",
... | Zapytanie o obrazy po obiektach i id
@param string $object
@param string $objectId
@return CmsFileQuery | [
"Zapytanie",
"o",
"obrazy",
"po",
"obiektach",
"i",
"id"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileQuery.php#L165-L170 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileQuery.php | CmsFileQuery.stickyByObject | public static function stickyByObject($object = null, $objectId = null, $class = null)
{
//zapytanie po obiekcie
$q = self::byObject($object, $objectId)
->whereSticky()->equals(1);
//dodawanie klasy jeśli wyspecyfikowana
if (null !== $class) {
$q->andFieldClass()->equals($class);
}
return $q;
} | php | public static function stickyByObject($object = null, $objectId = null, $class = null)
{
//zapytanie po obiekcie
$q = self::byObject($object, $objectId)
->whereSticky()->equals(1);
//dodawanie klasy jeśli wyspecyfikowana
if (null !== $class) {
$q->andFieldClass()->equals($class);
}
return $q;
} | [
"public",
"static",
"function",
"stickyByObject",
"(",
"$",
"object",
"=",
"null",
",",
"$",
"objectId",
"=",
"null",
",",
"$",
"class",
"=",
"null",
")",
"{",
"//zapytanie po obiekcie",
"$",
"q",
"=",
"self",
"::",
"byObject",
"(",
"$",
"object",
",",
... | Przyklejone po obiekcie i id
@param string $object
@param string $objectId
@param string $class klasa
@return CmsFileQuery | [
"Przyklejone",
"po",
"obiekcie",
"i",
"id"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileQuery.php#L179-L189 | train |
milejko/mmi-cms | src/Cms/Orm/CmsFileQuery.php | CmsFileQuery.notImagesByObject | public static function notImagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie i id
return self::byObject($object, $objectId)
->whereClass()->notEquals('image');
} | php | public static function notImagesByObject($object = null, $objectId = null)
{
//zapytanie po obiekcie i id
return self::byObject($object, $objectId)
->whereClass()->notEquals('image');
} | [
"public",
"static",
"function",
"notImagesByObject",
"(",
"$",
"object",
"=",
"null",
",",
"$",
"objectId",
"=",
"null",
")",
"{",
"//zapytanie po obiekcie i id",
"return",
"self",
"::",
"byObject",
"(",
"$",
"object",
",",
"$",
"objectId",
")",
"->",
"where... | Nie obrazy po obiekcie i id
@param string $object
@param string $objectId
@return CmsFileQuery | [
"Nie",
"obrazy",
"po",
"obiekcie",
"i",
"id"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/Cms/Orm/CmsFileQuery.php#L197-L202 | train |
ARCANEDEV/Hasher | src/HashManager.php | HashManager.option | public function option($option = null)
{
if ( ! is_null($option)) {
$this->option = $option;
$this->buildDrivers();
}
return $this;
} | php | public function option($option = null)
{
if ( ! is_null($option)) {
$this->option = $option;
$this->buildDrivers();
}
return $this;
} | [
"public",
"function",
"option",
"(",
"$",
"option",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"is_null",
"(",
"$",
"option",
")",
")",
"{",
"$",
"this",
"->",
"option",
"=",
"$",
"option",
";",
"$",
"this",
"->",
"buildDrivers",
"(",
")",
";",
"}",
... | Set the hasher option.
@param string $option
@return \Arcanedev\Hasher\HashManager | [
"Set",
"the",
"hasher",
"option",
"."
] | 03971434fb3ac89c95ba8459b083eb0ed81da8b6 | https://github.com/ARCANEDEV/Hasher/blob/03971434fb3ac89c95ba8459b083eb0ed81da8b6/src/HashManager.php#L76-L84 | train |
ARCANEDEV/Hasher | src/HashManager.php | HashManager.buildDrivers | private function buildDrivers()
{
$drivers = $this->getHasherConfig('drivers', []);
foreach ($drivers as $name => $driver) {
$this->buildDriver($name, $driver);
}
} | php | private function buildDrivers()
{
$drivers = $this->getHasherConfig('drivers', []);
foreach ($drivers as $name => $driver) {
$this->buildDriver($name, $driver);
}
} | [
"private",
"function",
"buildDrivers",
"(",
")",
"{",
"$",
"drivers",
"=",
"$",
"this",
"->",
"getHasherConfig",
"(",
"'drivers'",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"$",
"drivers",
"as",
"$",
"name",
"=>",
"$",
"driver",
")",
"{",
"$",
"this",... | Build all hash drivers. | [
"Build",
"all",
"hash",
"drivers",
"."
] | 03971434fb3ac89c95ba8459b083eb0ed81da8b6 | https://github.com/ARCANEDEV/Hasher/blob/03971434fb3ac89c95ba8459b083eb0ed81da8b6/src/HashManager.php#L119-L126 | train |
ARCANEDEV/Hasher | src/HashManager.php | HashManager.buildDriver | private function buildDriver($name, array $driver)
{
return $this->drivers[$name] = new $driver['driver'](
Arr::get($driver, 'options.'.$this->getDefaultOption(), [])
);
} | php | private function buildDriver($name, array $driver)
{
return $this->drivers[$name] = new $driver['driver'](
Arr::get($driver, 'options.'.$this->getDefaultOption(), [])
);
} | [
"private",
"function",
"buildDriver",
"(",
"$",
"name",
",",
"array",
"$",
"driver",
")",
"{",
"return",
"$",
"this",
"->",
"drivers",
"[",
"$",
"name",
"]",
"=",
"new",
"$",
"driver",
"[",
"'driver'",
"]",
"(",
"Arr",
"::",
"get",
"(",
"$",
"drive... | Build the driver.
@param string $name
@param array $driver
@return \Arcanedev\Hasher\Contracts\HashDriver | [
"Build",
"the",
"driver",
"."
] | 03971434fb3ac89c95ba8459b083eb0ed81da8b6 | https://github.com/ARCANEDEV/Hasher/blob/03971434fb3ac89c95ba8459b083eb0ed81da8b6/src/HashManager.php#L136-L141 | train |
manaphp/framework | Cli/Controllers/FrameworkController.php | FrameworkController.minifyCommand | public function minifyCommand()
{
$ManaPHPSrcDir = $this->alias->get('@manaphp');
$ManaPHPDstDir = $ManaPHPSrcDir . '_' . date('ymd');
$totalClassLines = 0;
$totalInterfaceLines = 0;
$totalLines = 0;
$fileLines = [];
$sourceFiles = $this->_getSourceFiles($ManaPHPSrcDir);
foreach ($sourceFiles as $file) {
$dstFile = str_replace($ManaPHPSrcDir, $ManaPHPDstDir, $file);
$content = $this->_minify($this->filesystem->fileGet($file));
$lineCount = substr_count($content, strpos($content, "\r") !== false ? "\r" : "\n");
if (strpos($file, 'Interface.php')) {
$totalInterfaceLines += $lineCount;
$totalLines += $lineCount;
} else {
$totalClassLines += $lineCount;
$totalLines += $lineCount;
}
$this->console->writeLn($content);
$this->filesystem->filePut($dstFile, $content);
$fileLines[$file] = $lineCount;
}
asort($fileLines);
$i = 1;
$this->console->writeLn('------------------------------------------------------');
foreach ($fileLines as $file => $line) {
$this->console->writeLn(sprintf('%3d %3d %.3f', $i++, $line, $line / $totalLines * 100) . ' ' . substr($file, strpos($file, 'ManaPHP')));
}
$this->console->writeLn('------------------------------------------------------');
$this->console->writeLn('total lines: ' . $totalLines);
$this->console->writeLn('class lines: ' . $totalClassLines);
$this->console->writeLn('interface lines: ' . $totalInterfaceLines);
return 0;
} | php | public function minifyCommand()
{
$ManaPHPSrcDir = $this->alias->get('@manaphp');
$ManaPHPDstDir = $ManaPHPSrcDir . '_' . date('ymd');
$totalClassLines = 0;
$totalInterfaceLines = 0;
$totalLines = 0;
$fileLines = [];
$sourceFiles = $this->_getSourceFiles($ManaPHPSrcDir);
foreach ($sourceFiles as $file) {
$dstFile = str_replace($ManaPHPSrcDir, $ManaPHPDstDir, $file);
$content = $this->_minify($this->filesystem->fileGet($file));
$lineCount = substr_count($content, strpos($content, "\r") !== false ? "\r" : "\n");
if (strpos($file, 'Interface.php')) {
$totalInterfaceLines += $lineCount;
$totalLines += $lineCount;
} else {
$totalClassLines += $lineCount;
$totalLines += $lineCount;
}
$this->console->writeLn($content);
$this->filesystem->filePut($dstFile, $content);
$fileLines[$file] = $lineCount;
}
asort($fileLines);
$i = 1;
$this->console->writeLn('------------------------------------------------------');
foreach ($fileLines as $file => $line) {
$this->console->writeLn(sprintf('%3d %3d %.3f', $i++, $line, $line / $totalLines * 100) . ' ' . substr($file, strpos($file, 'ManaPHP')));
}
$this->console->writeLn('------------------------------------------------------');
$this->console->writeLn('total lines: ' . $totalLines);
$this->console->writeLn('class lines: ' . $totalClassLines);
$this->console->writeLn('interface lines: ' . $totalInterfaceLines);
return 0;
} | [
"public",
"function",
"minifyCommand",
"(",
")",
"{",
"$",
"ManaPHPSrcDir",
"=",
"$",
"this",
"->",
"alias",
"->",
"get",
"(",
"'@manaphp'",
")",
";",
"$",
"ManaPHPDstDir",
"=",
"$",
"ManaPHPSrcDir",
".",
"'_'",
".",
"date",
"(",
"'ymd'",
")",
";",
"$"... | minify framework source code
@return int | [
"minify",
"framework",
"source",
"code"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/FrameworkController.php#L154-L197 | train |
manaphp/framework | Cli/Controllers/FrameworkController.php | FrameworkController.genJsonCommand | public function genJsonCommand($source)
{
$classNames = [];
/** @noinspection ForeachSourceInspection */
/** @noinspection PhpIncludeInspection */
foreach (require $source as $className) {
if (preg_match('#^ManaPHP\\\\.*$#', $className)) {
$classNames[] = $className;
}
}
$output = __DIR__ . '/manaphp_lite.json';
if ($this->filesystem->fileExists($output)) {
$data = json_encode($this->filesystem->fileGet($output));
} else {
$data = [
'output' => '@root/manaphp.lite'
];
}
$data['classes'] = $classNames;
$this->filesystem->filePut($output, json_encode($data, JSON_PRETTY_PRINT));
$this->console->writeLn(json_encode($classNames, JSON_PRETTY_PRINT));
} | php | public function genJsonCommand($source)
{
$classNames = [];
/** @noinspection ForeachSourceInspection */
/** @noinspection PhpIncludeInspection */
foreach (require $source as $className) {
if (preg_match('#^ManaPHP\\\\.*$#', $className)) {
$classNames[] = $className;
}
}
$output = __DIR__ . '/manaphp_lite.json';
if ($this->filesystem->fileExists($output)) {
$data = json_encode($this->filesystem->fileGet($output));
} else {
$data = [
'output' => '@root/manaphp.lite'
];
}
$data['classes'] = $classNames;
$this->filesystem->filePut($output, json_encode($data, JSON_PRETTY_PRINT));
$this->console->writeLn(json_encode($classNames, JSON_PRETTY_PRINT));
} | [
"public",
"function",
"genJsonCommand",
"(",
"$",
"source",
")",
"{",
"$",
"classNames",
"=",
"[",
"]",
";",
"/** @noinspection ForeachSourceInspection */",
"/** @noinspection PhpIncludeInspection */",
"foreach",
"(",
"require",
"$",
"source",
"as",
"$",
"className",
... | generate manaphp_lite.json file
@param string $source | [
"generate",
"manaphp_lite",
".",
"json",
"file"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Cli/Controllers/FrameworkController.php#L204-L228 | train |
webfactory/symfony-application-tests | src/Webfactory/Util/TaggedServiceIterator.php | TaggedServiceIterator.getIterator | public function getIterator()
{
$tagsById = $this->container->findTaggedServiceIds($this->tag);
$taggedServices = array();
foreach ($tagsById as $id => $tagDefinitions) {
/* @var $id string */
/* @var $tagDefinitions array(array(string=>string)) */
foreach ($tagDefinitions as $tagDefinition) {
/* @var $tagDefinition array(string=>string) */
$taggedServices[] = new TaggedService($id, $tagDefinition);
}
}
return new \ArrayIterator($taggedServices);
} | php | public function getIterator()
{
$tagsById = $this->container->findTaggedServiceIds($this->tag);
$taggedServices = array();
foreach ($tagsById as $id => $tagDefinitions) {
/* @var $id string */
/* @var $tagDefinitions array(array(string=>string)) */
foreach ($tagDefinitions as $tagDefinition) {
/* @var $tagDefinition array(string=>string) */
$taggedServices[] = new TaggedService($id, $tagDefinition);
}
}
return new \ArrayIterator($taggedServices);
} | [
"public",
"function",
"getIterator",
"(",
")",
"{",
"$",
"tagsById",
"=",
"$",
"this",
"->",
"container",
"->",
"findTaggedServiceIds",
"(",
"$",
"this",
"->",
"tag",
")",
";",
"$",
"taggedServices",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"t... | Returns the iterator.
@return \Traversable
@link http://php.net/manual/en/iteratoraggregate.getiterator.php | [
"Returns",
"the",
"iterator",
"."
] | 971c0d45c46dc20323535940fc0d1cc7eafaf553 | https://github.com/webfactory/symfony-application-tests/blob/971c0d45c46dc20323535940fc0d1cc7eafaf553/src/Webfactory/Util/TaggedServiceIterator.php#L44-L57 | train |
milejko/mmi-cms | src/CmsAdmin/Grid/Column/OperationColumn.php | OperationColumn.addCustomButton | public function addCustomButton($iconName, array $params = [], $hashTarget = '')
{
$customButtons = is_array($this->getOption('customButtons')) ? $this->getOption('customButtons') : [];
$customButtons[] = ['iconName' => $iconName, 'params' => $params, 'hashTarget' => $hashTarget];
return $this->setOption('customButtons', $customButtons);
} | php | public function addCustomButton($iconName, array $params = [], $hashTarget = '')
{
$customButtons = is_array($this->getOption('customButtons')) ? $this->getOption('customButtons') : [];
$customButtons[] = ['iconName' => $iconName, 'params' => $params, 'hashTarget' => $hashTarget];
return $this->setOption('customButtons', $customButtons);
} | [
"public",
"function",
"addCustomButton",
"(",
"$",
"iconName",
",",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"hashTarget",
"=",
"''",
")",
"{",
"$",
"customButtons",
"=",
"is_array",
"(",
"$",
"this",
"->",
"getOption",
"(",
"'customButtons'",
")... | Dodaje dowolny button
@param string $iconName
@param array $params parametry
@param string $hashTarget
@return OperationColumn | [
"Dodaje",
"dowolny",
"button"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Grid/Column/OperationColumn.php#L100-L105 | train |
fezfez/codeGenerator | src/CrudGenerator/Metadata/DataObject/MetaDataColumn.php | MetaDataColumn.getName | public function getName($ucfirst = false)
{
$value = $this->camelCase($this->name);
if (true === $ucfirst) {
return ucfirst($value);
} else {
return $value;
}
} | php | public function getName($ucfirst = false)
{
$value = $this->camelCase($this->name);
if (true === $ucfirst) {
return ucfirst($value);
} else {
return $value;
}
} | [
"public",
"function",
"getName",
"(",
"$",
"ucfirst",
"=",
"false",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"camelCase",
"(",
"$",
"this",
"->",
"name",
")",
";",
"if",
"(",
"true",
"===",
"$",
"ucfirst",
")",
"{",
"return",
"ucfirst",
"(",... | Get Column name
@return string | [
"Get",
"Column",
"name"
] | 559f22bcc525c3157ecb17fe96818dd7b7ee58c2 | https://github.com/fezfez/codeGenerator/blob/559f22bcc525c3157ecb17fe96818dd7b7ee58c2/src/CrudGenerator/Metadata/DataObject/MetaDataColumn.php#L107-L115 | train |
manaphp/framework | Http/Request.php | Request.getFiles | public function getFiles($onlySuccessful = true)
{
$context = $this->_context;
$files = [];
/** @var $_FILES array */
foreach ($context->_FILES as $key => $file) {
if (is_int($file['error'])) {
if (!$onlySuccessful || $file['error'] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size'],
];
$files[] = new File($key, $fileInfo);
}
} else {
$countFiles = count($file['error']);
/** @noinspection ForeachInvariantsInspection */
for ($i = 0; $i < $countFiles; $i++) {
if (!$onlySuccessful || $file['error'][$i] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i],
'size' => $file['size'][$i],
];
$files[] = new File($key, $fileInfo);
}
}
}
}
return $files;
} | php | public function getFiles($onlySuccessful = true)
{
$context = $this->_context;
$files = [];
/** @var $_FILES array */
foreach ($context->_FILES as $key => $file) {
if (is_int($file['error'])) {
if (!$onlySuccessful || $file['error'] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size'],
];
$files[] = new File($key, $fileInfo);
}
} else {
$countFiles = count($file['error']);
/** @noinspection ForeachInvariantsInspection */
for ($i = 0; $i < $countFiles; $i++) {
if (!$onlySuccessful || $file['error'][$i] === UPLOAD_ERR_OK) {
$fileInfo = [
'name' => $file['name'][$i],
'type' => $file['type'][$i],
'tmp_name' => $file['tmp_name'][$i],
'error' => $file['error'][$i],
'size' => $file['size'][$i],
];
$files[] = new File($key, $fileInfo);
}
}
}
}
return $files;
} | [
"public",
"function",
"getFiles",
"(",
"$",
"onlySuccessful",
"=",
"true",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"$",
"files",
"=",
"[",
"]",
";",
"/** @var $_FILES array */",
"foreach",
"(",
"$",
"context",
"->",
"_FILES",
"... | Gets attached files as \ManaPHP\Http\Request\File instances
@param bool $onlySuccessful
@return \ManaPHP\Http\Request\File[] | [
"Gets",
"attached",
"files",
"as",
"\\",
"ManaPHP",
"\\",
"Http",
"\\",
"Request",
"\\",
"File",
"instances"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Http/Request.php#L400-L438 | train |
milejko/mmi-cms | src/CmsAdmin/Form/Contact.php | Contact.beforeSave | public function beforeSave()
{
$this->getRecord()->active = 0;
$this->getRecord()->cmsAuthIdReply = \App\Registry::$auth->getId();
return true;
} | php | public function beforeSave()
{
$this->getRecord()->active = 0;
$this->getRecord()->cmsAuthIdReply = \App\Registry::$auth->getId();
return true;
} | [
"public",
"function",
"beforeSave",
"(",
")",
"{",
"$",
"this",
"->",
"getRecord",
"(",
")",
"->",
"active",
"=",
"0",
";",
"$",
"this",
"->",
"getRecord",
"(",
")",
"->",
"cmsAuthIdReply",
"=",
"\\",
"App",
"\\",
"Registry",
"::",
"$",
"auth",
"->",... | Ustawienie opcji przed zapisem
@return boolean | [
"Ustawienie",
"opcji",
"przed",
"zapisem"
] | 95483b08f25136b8d6bcf787ec4ecc3e8bdffb38 | https://github.com/milejko/mmi-cms/blob/95483b08f25136b8d6bcf787ec4ecc3e8bdffb38/src/CmsAdmin/Form/Contact.php#L62-L67 | train |
manaphp/framework | Http/Session.php | Session.destroy | public function destroy($session_id = null)
{
if ($session_id) {
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id]);
$this->do_destroy($session_id);
} else {
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id, 'context' => $context]);
$context->started = false;
$context->is_dirty = false;
$context->session_id = null;
$context->_SESSION = null;
$this->do_destroy($context->session_id);
$params = $this->_cookie_params;
$this->cookies->delete($this->_name, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
} | php | public function destroy($session_id = null)
{
if ($session_id) {
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id]);
$this->do_destroy($session_id);
} else {
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
$this->eventsManager->fireEvent('session:destroy', $this, ['session_id' => $session_id, 'context' => $context]);
$context->started = false;
$context->is_dirty = false;
$context->session_id = null;
$context->_SESSION = null;
$this->do_destroy($context->session_id);
$params = $this->_cookie_params;
$this->cookies->delete($this->_name, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
}
} | [
"public",
"function",
"destroy",
"(",
"$",
"session_id",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"session_id",
")",
"{",
"$",
"this",
"->",
"eventsManager",
"->",
"fireEvent",
"(",
"'session:destroy'",
",",
"$",
"this",
",",
"[",
"'session_id'",
"=>",
"$"... | Destroys the active session or assigned session
@param string $session_id
@return void | [
"Destroys",
"the",
"active",
"session",
"or",
"assigned",
"session"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Http/Session.php#L190-L214 | train |
manaphp/framework | Http/Session.php | Session.get | public function get($name = null, $default = null)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
if ($name === null) {
return $context->_SESSION;
} elseif (isset($context->_SESSION[$name])) {
return $context->_SESSION[$name];
} else {
return $default;
}
} | php | public function get($name = null, $default = null)
{
$context = $this->_context;
if (!$context->started) {
$this->_start();
}
if ($name === null) {
return $context->_SESSION;
} elseif (isset($context->_SESSION[$name])) {
return $context->_SESSION[$name];
} else {
return $default;
}
} | [
"public",
"function",
"get",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"context",
"=",
"$",
"this",
"->",
"_context",
";",
"if",
"(",
"!",
"$",
"context",
"->",
"started",
")",
"{",
"$",
"this",
"->",
"_start... | Gets a session variable from an application context
@param string $name
@param mixed $default
@return mixed | [
"Gets",
"a",
"session",
"variable",
"from",
"an",
"application",
"context"
] | b9a15c7f8f5d4770cacbea43f26914765bfcb248 | https://github.com/manaphp/framework/blob/b9a15c7f8f5d4770cacbea43f26914765bfcb248/Http/Session.php#L345-L360 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.