repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_code_tokens
listlengths 15
672k
| func_documentation_string
stringlengths 1
47.2k
| func_documentation_tokens
listlengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|---|---|---|
baleen/cli
|
src/CommandBus/Config/StatusHandler.php
|
StatusHandler.splitDiff
|
protected function splitDiff(array $diff, callable $comparator, Version $head)
{
$beforeHead = [];
$afterHead = [];
foreach ($diff as $v) {
$result = $comparator($v, $head);
if ($result < 0) {
$beforeHead[] = $v;
} elseif ($result > 0) {
$afterHead[] = $v;
}
}
return [$beforeHead, $afterHead];
}
|
php
|
protected function splitDiff(array $diff, callable $comparator, Version $head)
{
$beforeHead = [];
$afterHead = [];
foreach ($diff as $v) {
$result = $comparator($v, $head);
if ($result < 0) {
$beforeHead[] = $v;
} elseif ($result > 0) {
$afterHead[] = $v;
}
}
return [$beforeHead, $afterHead];
}
|
[
"protected",
"function",
"splitDiff",
"(",
"array",
"$",
"diff",
",",
"callable",
"$",
"comparator",
",",
"Version",
"$",
"head",
")",
"{",
"$",
"beforeHead",
"=",
"[",
"]",
";",
"$",
"afterHead",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"diff",
"as",
"$",
"v",
")",
"{",
"$",
"result",
"=",
"$",
"comparator",
"(",
"$",
"v",
",",
"$",
"head",
")",
";",
"if",
"(",
"$",
"result",
"<",
"0",
")",
"{",
"$",
"beforeHead",
"[",
"]",
"=",
"$",
"v",
";",
"}",
"elseif",
"(",
"$",
"result",
">",
"0",
")",
"{",
"$",
"afterHead",
"[",
"]",
"=",
"$",
"v",
";",
"}",
"}",
"return",
"[",
"$",
"beforeHead",
",",
"$",
"afterHead",
"]",
";",
"}"
] |
Splits an array of Versions into two arrays and returns them. The first one contains all versions before the HEAD
(latest migrated) Version, and the second one contains all Versions after HEAD. Head is never included in either
of the arrays.
@param Version[] $diff The array of Versions that should be split.
@param callable $comparator The comparator used to sort Versions.
@param Version $head The HEAD version.
@return array
|
[
"Splits",
"an",
"array",
"of",
"Versions",
"into",
"two",
"arrays",
"and",
"returns",
"them",
".",
"The",
"first",
"one",
"contains",
"all",
"versions",
"before",
"the",
"HEAD",
"(",
"latest",
"migrated",
")",
"Version",
"and",
"the",
"second",
"one",
"contains",
"all",
"Versions",
"after",
"HEAD",
".",
"Head",
"is",
"never",
"included",
"in",
"either",
"of",
"the",
"arrays",
"."
] |
train
|
https://github.com/baleen/cli/blob/2ecbc7179c5800c9075fd93204ef25da375536ed/src/CommandBus/Config/StatusHandler.php#L191-L204
|
gdbots/pbjx-bundle-php
|
src/Command/DescribeSchedulerStorageCommand.php
|
DescribeSchedulerStorageCommand.execute
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Scheduler Storage Describer');
$details = $this->getPbjxServiceLocator()->getScheduler()->describeStorage();
$io->text($details);
$io->newLine();
}
|
php
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$io->title('Scheduler Storage Describer');
$details = $this->getPbjxServiceLocator()->getScheduler()->describeStorage();
$io->text($details);
$io->newLine();
}
|
[
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"io",
"=",
"new",
"SymfonyStyle",
"(",
"$",
"input",
",",
"$",
"output",
")",
";",
"$",
"io",
"->",
"title",
"(",
"'Scheduler Storage Describer'",
")",
";",
"$",
"details",
"=",
"$",
"this",
"->",
"getPbjxServiceLocator",
"(",
")",
"->",
"getScheduler",
"(",
")",
"->",
"describeStorage",
"(",
")",
";",
"$",
"io",
"->",
"text",
"(",
"$",
"details",
")",
";",
"$",
"io",
"->",
"newLine",
"(",
")",
";",
"}"
] |
@param InputInterface $input
@param OutputInterface $output
@return null
@throws \Exception
|
[
"@param",
"InputInterface",
"$input",
"@param",
"OutputInterface",
"$output"
] |
train
|
https://github.com/gdbots/pbjx-bundle-php/blob/f3c0088583879fc92f13247a0752634bd8696eac/src/Command/DescribeSchedulerStorageCommand.php#L50-L58
|
runcmf/runbb-ext-renderer
|
src/View.php
|
View.setStyle
|
public function setStyle($style)
{
$dir = ForumEnv::get('WEB_ROOT').'themes/'.$style.'/';
if (!is_dir($dir)) {
throw new RunBBException('The style '.$style.' doesn\'t exist');
}
if (is_file($dir . 'bootstrap.php')) {
$vars = include_once $dir . 'bootstrap.php';
// file exist but return nothing
if (!is_array($vars)) {
$vars = [];
}
foreach ($vars as $key => $assets) {
if ($key === 'jsraw' || !in_array($key, ['js', 'jshead', 'css'])) {
continue;
}
foreach ($assets as $asset) {
$params = ($key === 'css') ? ['type' => 'text/css', 'rel' => 'stylesheet'] : (
($key === 'js' || $key === 'jshead') ? ['type' => 'text/javascript'] : []
);
$this->addAsset($key, $asset, $params);
}
}
$this->set('jsraw', isset($vars['jsraw']) ? $vars['jsraw'] : '');
}
if (isset($vars['themeTemplates']) && $vars['themeTemplates'] == true) {
$templatesDir = ForumEnv::get('WEB_ROOT').'themes/'.$style.'/view';
} else {
$templatesDir = ForumEnv::get('FORUM_ROOT') . 'View/';
}
$this->set('style', (string) $style);
$this->addTemplatesDirectory($templatesDir);
}
|
php
|
public function setStyle($style)
{
$dir = ForumEnv::get('WEB_ROOT').'themes/'.$style.'/';
if (!is_dir($dir)) {
throw new RunBBException('The style '.$style.' doesn\'t exist');
}
if (is_file($dir . 'bootstrap.php')) {
$vars = include_once $dir . 'bootstrap.php';
// file exist but return nothing
if (!is_array($vars)) {
$vars = [];
}
foreach ($vars as $key => $assets) {
if ($key === 'jsraw' || !in_array($key, ['js', 'jshead', 'css'])) {
continue;
}
foreach ($assets as $asset) {
$params = ($key === 'css') ? ['type' => 'text/css', 'rel' => 'stylesheet'] : (
($key === 'js' || $key === 'jshead') ? ['type' => 'text/javascript'] : []
);
$this->addAsset($key, $asset, $params);
}
}
$this->set('jsraw', isset($vars['jsraw']) ? $vars['jsraw'] : '');
}
if (isset($vars['themeTemplates']) && $vars['themeTemplates'] == true) {
$templatesDir = ForumEnv::get('WEB_ROOT').'themes/'.$style.'/view';
} else {
$templatesDir = ForumEnv::get('FORUM_ROOT') . 'View/';
}
$this->set('style', (string) $style);
$this->addTemplatesDirectory($templatesDir);
}
|
[
"public",
"function",
"setStyle",
"(",
"$",
"style",
")",
"{",
"$",
"dir",
"=",
"ForumEnv",
"::",
"get",
"(",
"'WEB_ROOT'",
")",
".",
"'themes/'",
".",
"$",
"style",
".",
"'/'",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"dir",
")",
")",
"{",
"throw",
"new",
"RunBBException",
"(",
"'The style '",
".",
"$",
"style",
".",
"' doesn\\'t exist'",
")",
";",
"}",
"if",
"(",
"is_file",
"(",
"$",
"dir",
".",
"'bootstrap.php'",
")",
")",
"{",
"$",
"vars",
"=",
"include_once",
"$",
"dir",
".",
"'bootstrap.php'",
";",
"// file exist but return nothing",
"if",
"(",
"!",
"is_array",
"(",
"$",
"vars",
")",
")",
"{",
"$",
"vars",
"=",
"[",
"]",
";",
"}",
"foreach",
"(",
"$",
"vars",
"as",
"$",
"key",
"=>",
"$",
"assets",
")",
"{",
"if",
"(",
"$",
"key",
"===",
"'jsraw'",
"||",
"!",
"in_array",
"(",
"$",
"key",
",",
"[",
"'js'",
",",
"'jshead'",
",",
"'css'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"foreach",
"(",
"$",
"assets",
"as",
"$",
"asset",
")",
"{",
"$",
"params",
"=",
"(",
"$",
"key",
"===",
"'css'",
")",
"?",
"[",
"'type'",
"=>",
"'text/css'",
",",
"'rel'",
"=>",
"'stylesheet'",
"]",
":",
"(",
"(",
"$",
"key",
"===",
"'js'",
"||",
"$",
"key",
"===",
"'jshead'",
")",
"?",
"[",
"'type'",
"=>",
"'text/javascript'",
"]",
":",
"[",
"]",
")",
";",
"$",
"this",
"->",
"addAsset",
"(",
"$",
"key",
",",
"$",
"asset",
",",
"$",
"params",
")",
";",
"}",
"}",
"$",
"this",
"->",
"set",
"(",
"'jsraw'",
",",
"isset",
"(",
"$",
"vars",
"[",
"'jsraw'",
"]",
")",
"?",
"$",
"vars",
"[",
"'jsraw'",
"]",
":",
"''",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"vars",
"[",
"'themeTemplates'",
"]",
")",
"&&",
"$",
"vars",
"[",
"'themeTemplates'",
"]",
"==",
"true",
")",
"{",
"$",
"templatesDir",
"=",
"ForumEnv",
"::",
"get",
"(",
"'WEB_ROOT'",
")",
".",
"'themes/'",
".",
"$",
"style",
".",
"'/view'",
";",
"}",
"else",
"{",
"$",
"templatesDir",
"=",
"ForumEnv",
"::",
"get",
"(",
"'FORUM_ROOT'",
")",
".",
"'View/'",
";",
"}",
"$",
"this",
"->",
"set",
"(",
"'style'",
",",
"(",
"string",
")",
"$",
"style",
")",
";",
"$",
"this",
"->",
"addTemplatesDirectory",
"(",
"$",
"templatesDir",
")",
";",
"}"
] |
Initialise style, load assets for given style
@param $style
@throws RunBBException
|
[
"Initialise",
"style",
"load",
"assets",
"for",
"given",
"style"
] |
train
|
https://github.com/runcmf/runbb-ext-renderer/blob/df47ea8550f79c34676df7abb4112a5addaccea0/src/View.php#L55-L91
|
runcmf/runbb-ext-renderer
|
src/View.php
|
View.addMessage
|
public function addMessage($msg, $type = 'info')
{
if (Container::get('flash')) {
if (in_array($type, ['info', 'error', 'warning', 'success'])) {
Container::get('flash')->addMessage($type, (string) $msg);
}
}
}
|
php
|
public function addMessage($msg, $type = 'info')
{
if (Container::get('flash')) {
if (in_array($type, ['info', 'error', 'warning', 'success'])) {
Container::get('flash')->addMessage($type, (string) $msg);
}
}
}
|
[
"public",
"function",
"addMessage",
"(",
"$",
"msg",
",",
"$",
"type",
"=",
"'info'",
")",
"{",
"if",
"(",
"Container",
"::",
"get",
"(",
"'flash'",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"type",
",",
"[",
"'info'",
",",
"'error'",
",",
"'warning'",
",",
"'success'",
"]",
")",
")",
"{",
"Container",
"::",
"get",
"(",
"'flash'",
")",
"->",
"addMessage",
"(",
"$",
"type",
",",
"(",
"string",
")",
"$",
"msg",
")",
";",
"}",
"}",
"}"
] |
}
|
[
"}"
] |
train
|
https://github.com/runcmf/runbb-ext-renderer/blob/df47ea8550f79c34676df7abb4112a5addaccea0/src/View.php#L163-L170
|
runcmf/runbb-ext-renderer
|
src/View.php
|
View.parseName
|
protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '@' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new \RunBB\Exception\RunBBException(
sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)
);
}
$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
return array($namespace, $shortname);
}
return array($default, $name);
}
|
php
|
protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '@' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new \RunBB\Exception\RunBBException(
sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)
);
}
$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
return array($namespace, $shortname);
}
return array($default, $name);
}
|
[
"protected",
"function",
"parseName",
"(",
"$",
"name",
",",
"$",
"default",
"=",
"self",
"::",
"MAIN_NAMESPACE",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"name",
"[",
"0",
"]",
")",
"&&",
"'@'",
"==",
"$",
"name",
"[",
"0",
"]",
")",
"{",
"if",
"(",
"false",
"===",
"$",
"pos",
"=",
"strpos",
"(",
"$",
"name",
",",
"'/'",
")",
")",
"{",
"throw",
"new",
"\\",
"RunBB",
"\\",
"Exception",
"\\",
"RunBBException",
"(",
"sprintf",
"(",
"'Malformed namespaced template name \"%s\" (expecting \"@namespace/template_name\").'",
",",
"$",
"name",
")",
")",
";",
"}",
"$",
"namespace",
"=",
"substr",
"(",
"$",
"name",
",",
"1",
",",
"$",
"pos",
"-",
"1",
")",
";",
"$",
"shortname",
"=",
"substr",
"(",
"$",
"name",
",",
"$",
"pos",
"+",
"1",
")",
";",
"return",
"array",
"(",
"$",
"namespace",
",",
"$",
"shortname",
")",
";",
"}",
"return",
"array",
"(",
"$",
"default",
",",
"$",
"name",
")",
";",
"}"
] |
Twig function
@param $name
@param string $default
@return array
@throws \RunBB\Exception\RunBBException
|
[
"Twig",
"function"
] |
train
|
https://github.com/runcmf/runbb-ext-renderer/blob/df47ea8550f79c34676df7abb4112a5addaccea0/src/View.php#L349-L364
|
wizbii/pipeline
|
Runnable/DispatcherStore.php
|
DispatcherStore.dumpAction
|
public function dumpAction()
{
return $this->newActionMatcher()->thenExecute(function($action) {
echo "Action '" . $action->getName() . "' : " . var_export($action->getProperties(), true) . "\n";
});
}
|
php
|
public function dumpAction()
{
return $this->newActionMatcher()->thenExecute(function($action) {
echo "Action '" . $action->getName() . "' : " . var_export($action->getProperties(), true) . "\n";
});
}
|
[
"public",
"function",
"dumpAction",
"(",
")",
"{",
"return",
"$",
"this",
"->",
"newActionMatcher",
"(",
")",
"->",
"thenExecute",
"(",
"function",
"(",
"$",
"action",
")",
"{",
"echo",
"\"Action '\"",
".",
"$",
"action",
"->",
"getName",
"(",
")",
".",
"\"' : \"",
".",
"var_export",
"(",
"$",
"action",
"->",
"getProperties",
"(",
")",
",",
"true",
")",
".",
"\"\\n\"",
";",
"}",
")",
";",
"}"
] |
Used for debug purposes mainly
@return $this
|
[
"Used",
"for",
"debug",
"purposes",
"mainly"
] |
train
|
https://github.com/wizbii/pipeline/blob/8d22b976a53bb52abf0333b62b308ec7127cf414/Runnable/DispatcherStore.php#L162-L167
|
faustbrian/Laravel-Countries
|
src/Console/Commands/SeedTaxRates.php
|
SeedTaxRates.handle
|
public function handle()
{
$data = base_path('vendor/faustbrian/laravel-countries/data/taxrates.json');
$data = json_decode(file_get_contents($data), true);
foreach ($this->getModel()->all() as $country) {
$rate = 0;
if (array_key_exists($country['name']['common'], $data)) {
$rate = $data[$country['name']['common']];
}
$country->taxrate()->create([
'rate' => $rate,
'percentage' => $rate * 100,
]);
}
$this->getOutput()->writeln('<info>Seeded:</info> Countries > TaxRates');
}
|
php
|
public function handle()
{
$data = base_path('vendor/faustbrian/laravel-countries/data/taxrates.json');
$data = json_decode(file_get_contents($data), true);
foreach ($this->getModel()->all() as $country) {
$rate = 0;
if (array_key_exists($country['name']['common'], $data)) {
$rate = $data[$country['name']['common']];
}
$country->taxrate()->create([
'rate' => $rate,
'percentage' => $rate * 100,
]);
}
$this->getOutput()->writeln('<info>Seeded:</info> Countries > TaxRates');
}
|
[
"public",
"function",
"handle",
"(",
")",
"{",
"$",
"data",
"=",
"base_path",
"(",
"'vendor/faustbrian/laravel-countries/data/taxrates.json'",
")",
";",
"$",
"data",
"=",
"json_decode",
"(",
"file_get_contents",
"(",
"$",
"data",
")",
",",
"true",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"getModel",
"(",
")",
"->",
"all",
"(",
")",
"as",
"$",
"country",
")",
"{",
"$",
"rate",
"=",
"0",
";",
"if",
"(",
"array_key_exists",
"(",
"$",
"country",
"[",
"'name'",
"]",
"[",
"'common'",
"]",
",",
"$",
"data",
")",
")",
"{",
"$",
"rate",
"=",
"$",
"data",
"[",
"$",
"country",
"[",
"'name'",
"]",
"[",
"'common'",
"]",
"]",
";",
"}",
"$",
"country",
"->",
"taxrate",
"(",
")",
"->",
"create",
"(",
"[",
"'rate'",
"=>",
"$",
"rate",
",",
"'percentage'",
"=>",
"$",
"rate",
"*",
"100",
",",
"]",
")",
";",
"}",
"$",
"this",
"->",
"getOutput",
"(",
")",
"->",
"writeln",
"(",
"'<info>Seeded:</info> Countries > TaxRates'",
")",
";",
"}"
] |
Execute the console command.
@return mixed
|
[
"Execute",
"the",
"console",
"command",
"."
] |
train
|
https://github.com/faustbrian/Laravel-Countries/blob/3d72301acd37e7f351d9b991dba41807ab68362b/src/Console/Commands/SeedTaxRates.php#L40-L59
|
jan-dolata/crude-crud
|
src/Http/Controllers/FileController.php
|
FileController.upload
|
public function upload(FileRequest $request)
{
$crudeName = $request->input('crudeName');
$crude = CrudeInstance::get($crudeName);
$files = $request->file()['file'];
$id = $request->input('modelId');
$errors = [];
if ($crude instanceof \JanDolata\CrudeCRUD\Engine\Interfaces\WithValidationInterface) {
foreach($files as $key => $file) {
$rules = $crude->getValidationRules(['file']);
$mime = $file->getMimeType();
$fileTypeRules = 'file_'.collect(explode('/', $mime))->first();
empty($crude->getValidationRules([$fileTypeRules])[$fileTypeRules])
? $rules = $rules
: $rules['file'] = $rules['file'] . '|' . $crude->getValidationRules([$fileTypeRules])[$fileTypeRules];
$validator = Validator::make(['file' => $file], $rules);
if ($validator->fails()) {
unset($files[$key]);
$errors[] = $file->getClientOriginalName() . ': '. $validator->messages()->first();
}
}
}
$model = empty($files)
? $crude->getById($id)
: $crude->uploadFilesById($id, $files);
$response = ['success' => true, 'model' => $model];
if (!empty($errors)) {
$response = array_merge($response, ['errors' => join('<br/>', $errors)]);
$response['success'] = false;
}
return $response;
}
|
php
|
public function upload(FileRequest $request)
{
$crudeName = $request->input('crudeName');
$crude = CrudeInstance::get($crudeName);
$files = $request->file()['file'];
$id = $request->input('modelId');
$errors = [];
if ($crude instanceof \JanDolata\CrudeCRUD\Engine\Interfaces\WithValidationInterface) {
foreach($files as $key => $file) {
$rules = $crude->getValidationRules(['file']);
$mime = $file->getMimeType();
$fileTypeRules = 'file_'.collect(explode('/', $mime))->first();
empty($crude->getValidationRules([$fileTypeRules])[$fileTypeRules])
? $rules = $rules
: $rules['file'] = $rules['file'] . '|' . $crude->getValidationRules([$fileTypeRules])[$fileTypeRules];
$validator = Validator::make(['file' => $file], $rules);
if ($validator->fails()) {
unset($files[$key]);
$errors[] = $file->getClientOriginalName() . ': '. $validator->messages()->first();
}
}
}
$model = empty($files)
? $crude->getById($id)
: $crude->uploadFilesById($id, $files);
$response = ['success' => true, 'model' => $model];
if (!empty($errors)) {
$response = array_merge($response, ['errors' => join('<br/>', $errors)]);
$response['success'] = false;
}
return $response;
}
|
[
"public",
"function",
"upload",
"(",
"FileRequest",
"$",
"request",
")",
"{",
"$",
"crudeName",
"=",
"$",
"request",
"->",
"input",
"(",
"'crudeName'",
")",
";",
"$",
"crude",
"=",
"CrudeInstance",
"::",
"get",
"(",
"$",
"crudeName",
")",
";",
"$",
"files",
"=",
"$",
"request",
"->",
"file",
"(",
")",
"[",
"'file'",
"]",
";",
"$",
"id",
"=",
"$",
"request",
"->",
"input",
"(",
"'modelId'",
")",
";",
"$",
"errors",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"crude",
"instanceof",
"\\",
"JanDolata",
"\\",
"CrudeCRUD",
"\\",
"Engine",
"\\",
"Interfaces",
"\\",
"WithValidationInterface",
")",
"{",
"foreach",
"(",
"$",
"files",
"as",
"$",
"key",
"=>",
"$",
"file",
")",
"{",
"$",
"rules",
"=",
"$",
"crude",
"->",
"getValidationRules",
"(",
"[",
"'file'",
"]",
")",
";",
"$",
"mime",
"=",
"$",
"file",
"->",
"getMimeType",
"(",
")",
";",
"$",
"fileTypeRules",
"=",
"'file_'",
".",
"collect",
"(",
"explode",
"(",
"'/'",
",",
"$",
"mime",
")",
")",
"->",
"first",
"(",
")",
";",
"empty",
"(",
"$",
"crude",
"->",
"getValidationRules",
"(",
"[",
"$",
"fileTypeRules",
"]",
")",
"[",
"$",
"fileTypeRules",
"]",
")",
"?",
"$",
"rules",
"=",
"$",
"rules",
":",
"$",
"rules",
"[",
"'file'",
"]",
"=",
"$",
"rules",
"[",
"'file'",
"]",
".",
"'|'",
".",
"$",
"crude",
"->",
"getValidationRules",
"(",
"[",
"$",
"fileTypeRules",
"]",
")",
"[",
"$",
"fileTypeRules",
"]",
";",
"$",
"validator",
"=",
"Validator",
"::",
"make",
"(",
"[",
"'file'",
"=>",
"$",
"file",
"]",
",",
"$",
"rules",
")",
";",
"if",
"(",
"$",
"validator",
"->",
"fails",
"(",
")",
")",
"{",
"unset",
"(",
"$",
"files",
"[",
"$",
"key",
"]",
")",
";",
"$",
"errors",
"[",
"]",
"=",
"$",
"file",
"->",
"getClientOriginalName",
"(",
")",
".",
"': '",
".",
"$",
"validator",
"->",
"messages",
"(",
")",
"->",
"first",
"(",
")",
";",
"}",
"}",
"}",
"$",
"model",
"=",
"empty",
"(",
"$",
"files",
")",
"?",
"$",
"crude",
"->",
"getById",
"(",
"$",
"id",
")",
":",
"$",
"crude",
"->",
"uploadFilesById",
"(",
"$",
"id",
",",
"$",
"files",
")",
";",
"$",
"response",
"=",
"[",
"'success'",
"=>",
"true",
",",
"'model'",
"=>",
"$",
"model",
"]",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"errors",
")",
")",
"{",
"$",
"response",
"=",
"array_merge",
"(",
"$",
"response",
",",
"[",
"'errors'",
"=>",
"join",
"(",
"'<br/>'",
",",
"$",
"errors",
")",
"]",
")",
";",
"$",
"response",
"[",
"'success'",
"]",
"=",
"false",
";",
"}",
"return",
"$",
"response",
";",
"}"
] |
Handle files upload
file on model is a helper field
@author Wojciech Jurkowski <[email protected]>
|
[
"Handle",
"files",
"upload",
"file",
"on",
"model",
"is",
"a",
"helper",
"field"
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Http/Controllers/FileController.php#L22-L62
|
jan-dolata/crude-crud
|
src/Http/Controllers/FileController.php
|
FileController.delete
|
public function delete(FileRequest $request)
{
$crude = CrudeInstance::get($request->input('crudeName'));
$model = $crude->deleteFileByData($request->input('crudeModelId'), $request->input('file_log_id'));
return ['model' => $model];
}
|
php
|
public function delete(FileRequest $request)
{
$crude = CrudeInstance::get($request->input('crudeName'));
$model = $crude->deleteFileByData($request->input('crudeModelId'), $request->input('file_log_id'));
return ['model' => $model];
}
|
[
"public",
"function",
"delete",
"(",
"FileRequest",
"$",
"request",
")",
"{",
"$",
"crude",
"=",
"CrudeInstance",
"::",
"get",
"(",
"$",
"request",
"->",
"input",
"(",
"'crudeName'",
")",
")",
";",
"$",
"model",
"=",
"$",
"crude",
"->",
"deleteFileByData",
"(",
"$",
"request",
"->",
"input",
"(",
"'crudeModelId'",
")",
",",
"$",
"request",
"->",
"input",
"(",
"'file_log_id'",
")",
")",
";",
"return",
"[",
"'model'",
"=>",
"$",
"model",
"]",
";",
"}"
] |
delete file
@author Wojciech Jurkowski <[email protected]>
|
[
"delete",
"file"
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Http/Controllers/FileController.php#L68-L74
|
jan-dolata/crude-crud
|
src/Http/Controllers/FileController.php
|
FileController.download
|
public function download(Request $request)
{
$path = $request->input('path');
$name = $request->input('name');
$path = parse_url($path)['path'];
$file = storage_path('app' . $path);
return response()->download($file, $name);
}
|
php
|
public function download(Request $request)
{
$path = $request->input('path');
$name = $request->input('name');
$path = parse_url($path)['path'];
$file = storage_path('app' . $path);
return response()->download($file, $name);
}
|
[
"public",
"function",
"download",
"(",
"Request",
"$",
"request",
")",
"{",
"$",
"path",
"=",
"$",
"request",
"->",
"input",
"(",
"'path'",
")",
";",
"$",
"name",
"=",
"$",
"request",
"->",
"input",
"(",
"'name'",
")",
";",
"$",
"path",
"=",
"parse_url",
"(",
"$",
"path",
")",
"[",
"'path'",
"]",
";",
"$",
"file",
"=",
"storage_path",
"(",
"'app'",
".",
"$",
"path",
")",
";",
"return",
"response",
"(",
")",
"->",
"download",
"(",
"$",
"file",
",",
"$",
"name",
")",
";",
"}"
] |
Download file
|
[
"Download",
"file"
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Http/Controllers/FileController.php#L79-L87
|
jan-dolata/crude-crud
|
src/Http/Controllers/FileController.php
|
FileController.downloadAll
|
public function downloadAll($crudeName = null, $id = null)
{
if (! $crudeName || ! $id)
return redirect()->back();
$crude = CrudeInstance::get($crudeName);
if (! $crude)
return redirect()->back();
$model = $crude->getModel()->find($id);
if (! $model)
return redirect()->back();
$filesZip = CrudeZip::run($model);
if (! $filesZip)
return redirect()->back();
return response()->download($filesZip, $crudeName . '-' . $id . '.zip')->deleteFileAfterSend(true);
}
|
php
|
public function downloadAll($crudeName = null, $id = null)
{
if (! $crudeName || ! $id)
return redirect()->back();
$crude = CrudeInstance::get($crudeName);
if (! $crude)
return redirect()->back();
$model = $crude->getModel()->find($id);
if (! $model)
return redirect()->back();
$filesZip = CrudeZip::run($model);
if (! $filesZip)
return redirect()->back();
return response()->download($filesZip, $crudeName . '-' . $id . '.zip')->deleteFileAfterSend(true);
}
|
[
"public",
"function",
"downloadAll",
"(",
"$",
"crudeName",
"=",
"null",
",",
"$",
"id",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"crudeName",
"||",
"!",
"$",
"id",
")",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"$",
"crude",
"=",
"CrudeInstance",
"::",
"get",
"(",
"$",
"crudeName",
")",
";",
"if",
"(",
"!",
"$",
"crude",
")",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"$",
"model",
"=",
"$",
"crude",
"->",
"getModel",
"(",
")",
"->",
"find",
"(",
"$",
"id",
")",
";",
"if",
"(",
"!",
"$",
"model",
")",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"$",
"filesZip",
"=",
"CrudeZip",
"::",
"run",
"(",
"$",
"model",
")",
";",
"if",
"(",
"!",
"$",
"filesZip",
")",
"return",
"redirect",
"(",
")",
"->",
"back",
"(",
")",
";",
"return",
"response",
"(",
")",
"->",
"download",
"(",
"$",
"filesZip",
",",
"$",
"crudeName",
".",
"'-'",
".",
"$",
"id",
".",
"'.zip'",
")",
"->",
"deleteFileAfterSend",
"(",
"true",
")",
";",
"}"
] |
Download all files for model
|
[
"Download",
"all",
"files",
"for",
"model"
] |
train
|
https://github.com/jan-dolata/crude-crud/blob/9129ea08278835cf5cecfd46a90369226ae6bdd7/src/Http/Controllers/FileController.php#L92-L110
|
Wonail/wocenter
|
helpers/DateTimeHelper.php
|
DateTimeHelper.getTimeUnitList
|
public static function getTimeUnitList()
{
return [
self::HOUR => Yii::t('wocenter/app', 'Hour'),
self::MINUTE => Yii::t('wocenter/app', 'Minute'),
self::SECOND => Yii::t('wocenter/app', 'Second'),
self::YEAR => Yii::t('wocenter/app', 'Year'),
self::MONTH => Yii::t('wocenter/app', 'Month'),
self::DAY => Yii::t('wocenter/app', 'Day'),
self::WEEK => Yii::t('wocenter/app', 'Week'),
];
}
|
php
|
public static function getTimeUnitList()
{
return [
self::HOUR => Yii::t('wocenter/app', 'Hour'),
self::MINUTE => Yii::t('wocenter/app', 'Minute'),
self::SECOND => Yii::t('wocenter/app', 'Second'),
self::YEAR => Yii::t('wocenter/app', 'Year'),
self::MONTH => Yii::t('wocenter/app', 'Month'),
self::DAY => Yii::t('wocenter/app', 'Day'),
self::WEEK => Yii::t('wocenter/app', 'Week'),
];
}
|
[
"public",
"static",
"function",
"getTimeUnitList",
"(",
")",
"{",
"return",
"[",
"self",
"::",
"HOUR",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Hour'",
")",
",",
"self",
"::",
"MINUTE",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Minute'",
")",
",",
"self",
"::",
"SECOND",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Second'",
")",
",",
"self",
"::",
"YEAR",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Year'",
")",
",",
"self",
"::",
"MONTH",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Month'",
")",
",",
"self",
"::",
"DAY",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Day'",
")",
",",
"self",
"::",
"WEEK",
"=>",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Week'",
")",
",",
"]",
";",
"}"
] |
获取时间单位列表
@return array
|
[
"获取时间单位列表"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/helpers/DateTimeHelper.php#L31-L42
|
Wonail/wocenter
|
helpers/DateTimeHelper.php
|
DateTimeHelper.timeFormat
|
public static function timeFormat($timestamp = null, $format = 'Y-m-d H:i:s')
{
if ($timestamp === null) {
$timestamp = time();
} elseif (empty($timestamp)) {
return null;
} else {
$timestamp = intval($timestamp);
}
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
}
return date($format, $timestamp);
}
|
php
|
public static function timeFormat($timestamp = null, $format = 'Y-m-d H:i:s')
{
if ($timestamp === null) {
$timestamp = time();
} elseif (empty($timestamp)) {
return null;
} else {
$timestamp = intval($timestamp);
}
if (strncmp($format, 'php:', 4) === 0) {
$format = substr($format, 4);
}
return date($format, $timestamp);
}
|
[
"public",
"static",
"function",
"timeFormat",
"(",
"$",
"timestamp",
"=",
"null",
",",
"$",
"format",
"=",
"'Y-m-d H:i:s'",
")",
"{",
"if",
"(",
"$",
"timestamp",
"===",
"null",
")",
"{",
"$",
"timestamp",
"=",
"time",
"(",
")",
";",
"}",
"elseif",
"(",
"empty",
"(",
"$",
"timestamp",
")",
")",
"{",
"return",
"null",
";",
"}",
"else",
"{",
"$",
"timestamp",
"=",
"intval",
"(",
"$",
"timestamp",
")",
";",
"}",
"if",
"(",
"strncmp",
"(",
"$",
"format",
",",
"'php:'",
",",
"4",
")",
"===",
"0",
")",
"{",
"$",
"format",
"=",
"substr",
"(",
"$",
"format",
",",
"4",
")",
";",
"}",
"return",
"date",
"(",
"$",
"format",
",",
"$",
"timestamp",
")",
";",
"}"
] |
标准化格式时间戳
@param integer $timestamp 需要格式化的日期时间
@param string $format 时间格式,默认为 Y-m-d H:i:s
@return string|null 完整的时间显示
|
[
"标准化格式时间戳"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/helpers/DateTimeHelper.php#L64-L78
|
Wonail/wocenter
|
helpers/DateTimeHelper.php
|
DateTimeHelper.timeFriendly
|
public static function timeFriendly($timestamp = null)
{
if ($timestamp == null) {
return 'N/A';
}
// 获取当前时间戳
$currentTime = time();
// 获取当天0点时间戳
$todayZero = strtotime('today');
// 获取昨天时间戳
$yesterday = strtotime('-1 day', $todayZero);
// 获取前天时间戳
$beforeYesterday = strtotime('-1 day', $yesterday);
// 获取明天0点时间戳
$tomorrow = strtotime('+1 day', $todayZero);
// 获取后天0点时间戳
$afterTomorrow = strtotime('+1 day', $tomorrow);
// 获取一天的时间戳
$oneDayTimestamp = 3600 * 24;
//当年时间戳
$yearDiff = $currentTime - strtotime("-1 year");
// 时间差
$timeDiff = $currentTime - $timestamp;
switch (true) {
case $timestamp >= $afterTomorrow && $timestamp < $afterTomorrow + $oneDayTimestamp :
return Yii::t('wocenter/app', 'The day after tomorrow {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $tomorrow && $timestamp < $afterTomorrow :
return Yii::t('wocenter/app', 'Tomorrow {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $todayZero && $timestamp < $tomorrow :
if ($timeDiff < (3600 * 8)) {
return Yii::$app->getFormatter()->asRelativeTime($timestamp);
} else {
return Yii::t('wocenter/app', 'Today {time}', ['time' => date('H:i', $timestamp)]);
}
case $timestamp >= $yesterday && $timestamp < $todayZero :
return Yii::t('wocenter/app', 'Yesterday {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $beforeYesterday && $timestamp < $yesterday :
return Yii::t('wocenter/app', 'The day before yesterday {time}', ['time' => date('H:i', $timestamp)]);
default :
if ($timeDiff > $yearDiff) {
return date('Y-m-d H:i', $timestamp);
} else {
return date('m-d H:i', $timestamp);
}
}
}
|
php
|
public static function timeFriendly($timestamp = null)
{
if ($timestamp == null) {
return 'N/A';
}
// 获取当前时间戳
$currentTime = time();
// 获取当天0点时间戳
$todayZero = strtotime('today');
// 获取昨天时间戳
$yesterday = strtotime('-1 day', $todayZero);
// 获取前天时间戳
$beforeYesterday = strtotime('-1 day', $yesterday);
// 获取明天0点时间戳
$tomorrow = strtotime('+1 day', $todayZero);
// 获取后天0点时间戳
$afterTomorrow = strtotime('+1 day', $tomorrow);
// 获取一天的时间戳
$oneDayTimestamp = 3600 * 24;
//当年时间戳
$yearDiff = $currentTime - strtotime("-1 year");
// 时间差
$timeDiff = $currentTime - $timestamp;
switch (true) {
case $timestamp >= $afterTomorrow && $timestamp < $afterTomorrow + $oneDayTimestamp :
return Yii::t('wocenter/app', 'The day after tomorrow {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $tomorrow && $timestamp < $afterTomorrow :
return Yii::t('wocenter/app', 'Tomorrow {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $todayZero && $timestamp < $tomorrow :
if ($timeDiff < (3600 * 8)) {
return Yii::$app->getFormatter()->asRelativeTime($timestamp);
} else {
return Yii::t('wocenter/app', 'Today {time}', ['time' => date('H:i', $timestamp)]);
}
case $timestamp >= $yesterday && $timestamp < $todayZero :
return Yii::t('wocenter/app', 'Yesterday {time}', ['time' => date('H:i', $timestamp)]);
case $timestamp >= $beforeYesterday && $timestamp < $yesterday :
return Yii::t('wocenter/app', 'The day before yesterday {time}', ['time' => date('H:i', $timestamp)]);
default :
if ($timeDiff > $yearDiff) {
return date('Y-m-d H:i', $timestamp);
} else {
return date('m-d H:i', $timestamp);
}
}
}
|
[
"public",
"static",
"function",
"timeFriendly",
"(",
"$",
"timestamp",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"timestamp",
"==",
"null",
")",
"{",
"return",
"'N/A'",
";",
"}",
"// 获取当前时间戳",
"$",
"currentTime",
"=",
"time",
"(",
")",
";",
"// 获取当天0点时间戳",
"$",
"todayZero",
"=",
"strtotime",
"(",
"'today'",
")",
";",
"// 获取昨天时间戳",
"$",
"yesterday",
"=",
"strtotime",
"(",
"'-1 day'",
",",
"$",
"todayZero",
")",
";",
"// 获取前天时间戳",
"$",
"beforeYesterday",
"=",
"strtotime",
"(",
"'-1 day'",
",",
"$",
"yesterday",
")",
";",
"// 获取明天0点时间戳",
"$",
"tomorrow",
"=",
"strtotime",
"(",
"'+1 day'",
",",
"$",
"todayZero",
")",
";",
"// 获取后天0点时间戳",
"$",
"afterTomorrow",
"=",
"strtotime",
"(",
"'+1 day'",
",",
"$",
"tomorrow",
")",
";",
"// 获取一天的时间戳",
"$",
"oneDayTimestamp",
"=",
"3600",
"*",
"24",
";",
"//当年时间戳",
"$",
"yearDiff",
"=",
"$",
"currentTime",
"-",
"strtotime",
"(",
"\"-1 year\"",
")",
";",
"// 时间差",
"$",
"timeDiff",
"=",
"$",
"currentTime",
"-",
"$",
"timestamp",
";",
"switch",
"(",
"true",
")",
"{",
"case",
"$",
"timestamp",
">=",
"$",
"afterTomorrow",
"&&",
"$",
"timestamp",
"<",
"$",
"afterTomorrow",
"+",
"$",
"oneDayTimestamp",
":",
"return",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'The day after tomorrow {time}'",
",",
"[",
"'time'",
"=>",
"date",
"(",
"'H:i'",
",",
"$",
"timestamp",
")",
"]",
")",
";",
"case",
"$",
"timestamp",
">=",
"$",
"tomorrow",
"&&",
"$",
"timestamp",
"<",
"$",
"afterTomorrow",
":",
"return",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Tomorrow {time}'",
",",
"[",
"'time'",
"=>",
"date",
"(",
"'H:i'",
",",
"$",
"timestamp",
")",
"]",
")",
";",
"case",
"$",
"timestamp",
">=",
"$",
"todayZero",
"&&",
"$",
"timestamp",
"<",
"$",
"tomorrow",
":",
"if",
"(",
"$",
"timeDiff",
"<",
"(",
"3600",
"*",
"8",
")",
")",
"{",
"return",
"Yii",
"::",
"$",
"app",
"->",
"getFormatter",
"(",
")",
"->",
"asRelativeTime",
"(",
"$",
"timestamp",
")",
";",
"}",
"else",
"{",
"return",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Today {time}'",
",",
"[",
"'time'",
"=>",
"date",
"(",
"'H:i'",
",",
"$",
"timestamp",
")",
"]",
")",
";",
"}",
"case",
"$",
"timestamp",
">=",
"$",
"yesterday",
"&&",
"$",
"timestamp",
"<",
"$",
"todayZero",
":",
"return",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'Yesterday {time}'",
",",
"[",
"'time'",
"=>",
"date",
"(",
"'H:i'",
",",
"$",
"timestamp",
")",
"]",
")",
";",
"case",
"$",
"timestamp",
">=",
"$",
"beforeYesterday",
"&&",
"$",
"timestamp",
"<",
"$",
"yesterday",
":",
"return",
"Yii",
"::",
"t",
"(",
"'wocenter/app'",
",",
"'The day before yesterday {time}'",
",",
"[",
"'time'",
"=>",
"date",
"(",
"'H:i'",
",",
"$",
"timestamp",
")",
"]",
")",
";",
"default",
":",
"if",
"(",
"$",
"timeDiff",
">",
"$",
"yearDiff",
")",
"{",
"return",
"date",
"(",
"'Y-m-d H:i'",
",",
"$",
"timestamp",
")",
";",
"}",
"else",
"{",
"return",
"date",
"(",
"'m-d H:i'",
",",
"$",
"timestamp",
")",
";",
"}",
"}",
"}"
] |
格式化为友好时间格式
@param integer $timestamp 时间戳
@return string 友好时间格式
|
[
"格式化为友好时间格式"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/helpers/DateTimeHelper.php#L87-L142
|
Wonail/wocenter
|
helpers/DateTimeHelper.php
|
DateTimeHelper.getTimeAgo
|
public static function getTimeAgo($timestamp = 1, $type = self::SECOND, $time = null)
{
if (empty($time)) {
$time = time();
}
switch ($type) {
case self::HOUR:
$result = $time - $timestamp * 60 * 60;
break;
case self::MINUTE:
$result = $time - $timestamp * 60;
break;
case self::SECOND:
$result = $time - $timestamp;
break;
case self::YEAR:
$result = strtotime('-' . $timestamp . ' year', $time);
break;
case self::MONTH:
$result = strtotime('-' . $timestamp . ' month', $time);
break;
case self::DAY:
$result = strtotime('-' . $timestamp . ' day', $time);
break;
case self::WEEK:
$result = strtotime('-' . ($timestamp * 7) . ' day', $time);
break;
default:
$result = $time - $timestamp;
}
return $result;
}
|
php
|
public static function getTimeAgo($timestamp = 1, $type = self::SECOND, $time = null)
{
if (empty($time)) {
$time = time();
}
switch ($type) {
case self::HOUR:
$result = $time - $timestamp * 60 * 60;
break;
case self::MINUTE:
$result = $time - $timestamp * 60;
break;
case self::SECOND:
$result = $time - $timestamp;
break;
case self::YEAR:
$result = strtotime('-' . $timestamp . ' year', $time);
break;
case self::MONTH:
$result = strtotime('-' . $timestamp . ' month', $time);
break;
case self::DAY:
$result = strtotime('-' . $timestamp . ' day', $time);
break;
case self::WEEK:
$result = strtotime('-' . ($timestamp * 7) . ' day', $time);
break;
default:
$result = $time - $timestamp;
}
return $result;
}
|
[
"public",
"static",
"function",
"getTimeAgo",
"(",
"$",
"timestamp",
"=",
"1",
",",
"$",
"type",
"=",
"self",
"::",
"SECOND",
",",
"$",
"time",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"time",
")",
")",
"{",
"$",
"time",
"=",
"time",
"(",
")",
";",
"}",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"self",
"::",
"HOUR",
":",
"$",
"result",
"=",
"$",
"time",
"-",
"$",
"timestamp",
"*",
"60",
"*",
"60",
";",
"break",
";",
"case",
"self",
"::",
"MINUTE",
":",
"$",
"result",
"=",
"$",
"time",
"-",
"$",
"timestamp",
"*",
"60",
";",
"break",
";",
"case",
"self",
"::",
"SECOND",
":",
"$",
"result",
"=",
"$",
"time",
"-",
"$",
"timestamp",
";",
"break",
";",
"case",
"self",
"::",
"YEAR",
":",
"$",
"result",
"=",
"strtotime",
"(",
"'-'",
".",
"$",
"timestamp",
".",
"' year'",
",",
"$",
"time",
")",
";",
"break",
";",
"case",
"self",
"::",
"MONTH",
":",
"$",
"result",
"=",
"strtotime",
"(",
"'-'",
".",
"$",
"timestamp",
".",
"' month'",
",",
"$",
"time",
")",
";",
"break",
";",
"case",
"self",
"::",
"DAY",
":",
"$",
"result",
"=",
"strtotime",
"(",
"'-'",
".",
"$",
"timestamp",
".",
"' day'",
",",
"$",
"time",
")",
";",
"break",
";",
"case",
"self",
"::",
"WEEK",
":",
"$",
"result",
"=",
"strtotime",
"(",
"'-'",
".",
"(",
"$",
"timestamp",
"*",
"7",
")",
".",
"' day'",
",",
"$",
"time",
")",
";",
"break",
";",
"default",
":",
"$",
"result",
"=",
"$",
"time",
"-",
"$",
"timestamp",
";",
"}",
"return",
"$",
"result",
";",
"}"
] |
根据时间单位,比较两个时间差。即$timestamp距离$time(默认为当前时间)已过多久
@param integer $timestamp 需要比较的时间
@param int|string $type 需要比较的时间单位,默认为秒, [时,分,秒,年,月,日,周];
@param null|integer $time 被比较的时间,默认为当前时间
@return int 两个时间差
|
[
"根据时间单位,比较两个时间差。即$timestamp距离$time",
"(",
"默认为当前时间",
")",
"已过多久"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/helpers/DateTimeHelper.php#L153-L185
|
Wonail/wocenter
|
helpers/DateTimeHelper.php
|
DateTimeHelper.parseFormat
|
public static function parseFormat($format, $type)
{
if (strncmp($format, 'php:', 4) === 0) {
return substr($format, 4);
} elseif ($format != '') {
return FormatConverter::convertDateIcuToPhp($format, $type);
} else {
throw new InvalidConfigException("Error parsing '{$type}' format.");
}
}
|
php
|
public static function parseFormat($format, $type)
{
if (strncmp($format, 'php:', 4) === 0) {
return substr($format, 4);
} elseif ($format != '') {
return FormatConverter::convertDateIcuToPhp($format, $type);
} else {
throw new InvalidConfigException("Error parsing '{$type}' format.");
}
}
|
[
"public",
"static",
"function",
"parseFormat",
"(",
"$",
"format",
",",
"$",
"type",
")",
"{",
"if",
"(",
"strncmp",
"(",
"$",
"format",
",",
"'php:'",
",",
"4",
")",
"===",
"0",
")",
"{",
"return",
"substr",
"(",
"$",
"format",
",",
"4",
")",
";",
"}",
"elseif",
"(",
"$",
"format",
"!=",
"''",
")",
"{",
"return",
"FormatConverter",
"::",
"convertDateIcuToPhp",
"(",
"$",
"format",
",",
"$",
"type",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"Error parsing '{$type}' format.\"",
")",
";",
"}",
"}"
] |
解析并返回PHP DateTime能够理解的时间日期格式
@param string $format ICU或php类型的时间日期格式
配置示例:
```php
'MM/dd/yyyy' // ICU格式
'php:m/d/Y' // PHP格式
```
@param string $type 时间日期类型,可选值有: `date`, `time`, `datetime`
@return string
@throws InvalidConfigException
|
[
"解析并返回PHP",
"DateTime能够理解的时间日期格式"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/helpers/DateTimeHelper.php#L245-L254
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.getNamespace
|
public function getNamespace()
{
if (!isset($this->namespace)) {
$reflectionClass = new \ReflectionClass($this->name);
$this->namespace = $reflectionClass->getNamespaceName();
}
return $this->namespace;
}
|
php
|
public function getNamespace()
{
if (!isset($this->namespace)) {
$reflectionClass = new \ReflectionClass($this->name);
$this->namespace = $reflectionClass->getNamespaceName();
}
return $this->namespace;
}
|
[
"public",
"function",
"getNamespace",
"(",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"namespace",
")",
")",
"{",
"$",
"reflectionClass",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
"->",
"name",
")",
";",
"$",
"this",
"->",
"namespace",
"=",
"$",
"reflectionClass",
"->",
"getNamespaceName",
"(",
")",
";",
"}",
"return",
"$",
"this",
"->",
"namespace",
";",
"}"
] |
Get namespace of the class
|
[
"Get",
"namespace",
"of",
"the",
"class"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L103-L110
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.getPropertyInfo
|
public function getPropertyInfo($prop)
{
if (!$this->loaded) {
$this->load();
}
if (isset($this->propertiesInfos[$prop])) {
return $this->propertiesInfos[$prop];
}
return false;
}
|
php
|
public function getPropertyInfo($prop)
{
if (!$this->loaded) {
$this->load();
}
if (isset($this->propertiesInfos[$prop])) {
return $this->propertiesInfos[$prop];
}
return false;
}
|
[
"public",
"function",
"getPropertyInfo",
"(",
"$",
"prop",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"prop",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"prop",
"]",
";",
"}",
"return",
"false",
";",
"}"
] |
Get property information
@param string $prop Name of the property
@return PropertyInfo
|
[
"Get",
"property",
"information"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L146-L157
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.getPropertyInfoForField
|
public function getPropertyInfoForField($field)
{
if (!$this->loaded) {
$this->load();
}
foreach ($this->propertiesInfos as $name => $infos) {
if ($infos->getField() == $field) {
return $infos;
}
}
return false;
}
|
php
|
public function getPropertyInfoForField($field)
{
if (!$this->loaded) {
$this->load();
}
foreach ($this->propertiesInfos as $name => $infos) {
if ($infos->getField() == $field) {
return $infos;
}
}
return false;
}
|
[
"public",
"function",
"getPropertyInfoForField",
"(",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"propertiesInfos",
"as",
"$",
"name",
"=>",
"$",
"infos",
")",
"{",
"if",
"(",
"$",
"infos",
"->",
"getField",
"(",
")",
"==",
"$",
"field",
")",
"{",
"return",
"$",
"infos",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Get property info corresponding to a field
@param string $field Field
@return PropertyInfo
|
[
"Get",
"property",
"info",
"corresponding",
"to",
"a",
"field"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L179-L192
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.getPropertyForField
|
public function getPropertyForField($field)
{
if (!$this->loaded) {
$this->load();
}
foreach ($this->propertiesInfos as $name => $infos) {
if ($infos->getField() == $field) {
return new \ReflectionProperty($this->name, $name);
}
}
return false;
}
|
php
|
public function getPropertyForField($field)
{
if (!$this->loaded) {
$this->load();
}
foreach ($this->propertiesInfos as $name => $infos) {
if ($infos->getField() == $field) {
return new \ReflectionProperty($this->name, $name);
}
}
return false;
}
|
[
"public",
"function",
"getPropertyForField",
"(",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"this",
"->",
"propertiesInfos",
"as",
"$",
"name",
"=>",
"$",
"infos",
")",
"{",
"if",
"(",
"$",
"infos",
"->",
"getField",
"(",
")",
"==",
"$",
"field",
")",
"{",
"return",
"new",
"\\",
"ReflectionProperty",
"(",
"$",
"this",
"->",
"name",
",",
"$",
"name",
")",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Get ReflectionProperty for a field
@param string $field Field
@return \ReflectionProperty
|
[
"Get",
"ReflectionProperty",
"for",
"a",
"field"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L200-L213
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.setCollection
|
public function setCollection($collection)
{
if (!$this->loaded) {
$this->load();
}
$this->collectionInfo->setCollection($collection);
return $this;
}
|
php
|
public function setCollection($collection)
{
if (!$this->loaded) {
$this->load();
}
$this->collectionInfo->setCollection($collection);
return $this;
}
|
[
"public",
"function",
"setCollection",
"(",
"$",
"collection",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"loaded",
")",
"{",
"$",
"this",
"->",
"load",
"(",
")",
";",
"}",
"$",
"this",
"->",
"collectionInfo",
"->",
"setCollection",
"(",
"$",
"collection",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
Set the collection
@param string $collection Name of the collection
@return ClassMetadata
|
[
"Set",
"the",
"collection"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L249-L257
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.load
|
private function load()
{
$reflectionClass = new \ReflectionClass($this->name);
$this->collectionInfo = new CollectionInfo();
foreach ($this->reader->getClassAnnotations($reflectionClass) as $annotation) {
$this->processClassAnnotation($annotation);
}
$properties = $reflectionClass->getProperties();
foreach ($properties as $property) {
foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
if (!isset($this->propertiesInfos[$property->getName()])) {
$this->propertiesInfos[$property->getName()] = new PropertyInfo();
}
$this->processPropertiesAnnotation($property->getName(), $annotation);
}
}
$this->eventManager = new EventManager();
if ($this->hasEvent) {
$methods = $reflectionClass->getMethods();
foreach ($methods as $method) {
$annotations = $this->reader->getMethodAnnotations($method);
if (!empty($annotations)) {
foreach ($annotations as $annotation) {
if (in_array('JPC\MongoDB\ODM\Annotations\Event\Event', class_implements($annotation))) {
$this->eventManager->add($annotation, $method->getName());
}
}
}
}
}
$this->loaded = true;
}
|
php
|
private function load()
{
$reflectionClass = new \ReflectionClass($this->name);
$this->collectionInfo = new CollectionInfo();
foreach ($this->reader->getClassAnnotations($reflectionClass) as $annotation) {
$this->processClassAnnotation($annotation);
}
$properties = $reflectionClass->getProperties();
foreach ($properties as $property) {
foreach ($this->reader->getPropertyAnnotations($property) as $annotation) {
if (!isset($this->propertiesInfos[$property->getName()])) {
$this->propertiesInfos[$property->getName()] = new PropertyInfo();
}
$this->processPropertiesAnnotation($property->getName(), $annotation);
}
}
$this->eventManager = new EventManager();
if ($this->hasEvent) {
$methods = $reflectionClass->getMethods();
foreach ($methods as $method) {
$annotations = $this->reader->getMethodAnnotations($method);
if (!empty($annotations)) {
foreach ($annotations as $annotation) {
if (in_array('JPC\MongoDB\ODM\Annotations\Event\Event', class_implements($annotation))) {
$this->eventManager->add($annotation, $method->getName());
}
}
}
}
}
$this->loaded = true;
}
|
[
"private",
"function",
"load",
"(",
")",
"{",
"$",
"reflectionClass",
"=",
"new",
"\\",
"ReflectionClass",
"(",
"$",
"this",
"->",
"name",
")",
";",
"$",
"this",
"->",
"collectionInfo",
"=",
"new",
"CollectionInfo",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"reader",
"->",
"getClassAnnotations",
"(",
"$",
"reflectionClass",
")",
"as",
"$",
"annotation",
")",
"{",
"$",
"this",
"->",
"processClassAnnotation",
"(",
"$",
"annotation",
")",
";",
"}",
"$",
"properties",
"=",
"$",
"reflectionClass",
"->",
"getProperties",
"(",
")",
";",
"foreach",
"(",
"$",
"properties",
"as",
"$",
"property",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"reader",
"->",
"getPropertyAnnotations",
"(",
"$",
"property",
")",
"as",
"$",
"annotation",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"property",
"->",
"getName",
"(",
")",
"]",
")",
")",
"{",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"property",
"->",
"getName",
"(",
")",
"]",
"=",
"new",
"PropertyInfo",
"(",
")",
";",
"}",
"$",
"this",
"->",
"processPropertiesAnnotation",
"(",
"$",
"property",
"->",
"getName",
"(",
")",
",",
"$",
"annotation",
")",
";",
"}",
"}",
"$",
"this",
"->",
"eventManager",
"=",
"new",
"EventManager",
"(",
")",
";",
"if",
"(",
"$",
"this",
"->",
"hasEvent",
")",
"{",
"$",
"methods",
"=",
"$",
"reflectionClass",
"->",
"getMethods",
"(",
")",
";",
"foreach",
"(",
"$",
"methods",
"as",
"$",
"method",
")",
"{",
"$",
"annotations",
"=",
"$",
"this",
"->",
"reader",
"->",
"getMethodAnnotations",
"(",
"$",
"method",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"annotations",
")",
")",
"{",
"foreach",
"(",
"$",
"annotations",
"as",
"$",
"annotation",
")",
"{",
"if",
"(",
"in_array",
"(",
"'JPC\\MongoDB\\ODM\\Annotations\\Event\\Event'",
",",
"class_implements",
"(",
"$",
"annotation",
")",
")",
")",
"{",
"$",
"this",
"->",
"eventManager",
"->",
"add",
"(",
"$",
"annotation",
",",
"$",
"method",
"->",
"getName",
"(",
")",
")",
";",
"}",
"}",
"}",
"}",
"}",
"$",
"this",
"->",
"loaded",
"=",
"true",
";",
"}"
] |
Load all metadata
@return void
|
[
"Load",
"all",
"metadata"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L316-L352
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.processClassAnnotation
|
private function processClassAnnotation($annotation)
{
$class = get_class($annotation);
switch ($class) {
case "JPC\MongoDB\ODM\Annotations\Mapping\Document":
$this->collectionInfo->setCollection($annotation->collectionName);
if (null !== ($rep = $annotation->repositoryClass)) {
$this->collectionInfo->setRepository($annotation->repositoryClass);
} else {
if (class_exists($this->getName() . 'Repository')) {
$this->collectionInfo->setRepository($this->getName() . 'Repository');
} else {
$this->collectionInfo->setRepository("JPC\MongoDB\ODM\Repository");
}
}
if (null !== ($rep = $annotation->hydratorClass)) {
$this->collectionInfo->setHydrator($annotation->hydratorClass);
} else {
$this->collectionInfo->setHydrator("JPC\MongoDB\ODM\Hydrator");
}
$this->checkCollectionCreationOptions($annotation);
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Document":
$this->collectionInfo->setBucketName($annotation->bucketName);
$this->collectionInfo->setCollection($annotation->bucketName . ".files");
if (null !== ($rep = $annotation->repositoryClass)) {
$this->collectionInfo->setRepository($annotation->repositoryClass);
} else {
$this->collectionInfo->setRepository("JPC\MongoDB\ODM\GridFS\Repository");
}
if (null !== ($rep = $annotation->hydratorClass)) {
$this->collectionInfo->setHydrator($annotation->hydratorClass);
} else {
$this->collectionInfo->setHydrator("JPC\MongoDB\ODM\GridFS\Hydrator");
}
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Option":
$this->processOptionAnnotation($annotation);
break;
case "JPC\MongoDB\ODM\Annotations\Event\HasLifecycleCallbacks":
$this->hasEvent = true;
break;
}
}
|
php
|
private function processClassAnnotation($annotation)
{
$class = get_class($annotation);
switch ($class) {
case "JPC\MongoDB\ODM\Annotations\Mapping\Document":
$this->collectionInfo->setCollection($annotation->collectionName);
if (null !== ($rep = $annotation->repositoryClass)) {
$this->collectionInfo->setRepository($annotation->repositoryClass);
} else {
if (class_exists($this->getName() . 'Repository')) {
$this->collectionInfo->setRepository($this->getName() . 'Repository');
} else {
$this->collectionInfo->setRepository("JPC\MongoDB\ODM\Repository");
}
}
if (null !== ($rep = $annotation->hydratorClass)) {
$this->collectionInfo->setHydrator($annotation->hydratorClass);
} else {
$this->collectionInfo->setHydrator("JPC\MongoDB\ODM\Hydrator");
}
$this->checkCollectionCreationOptions($annotation);
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Document":
$this->collectionInfo->setBucketName($annotation->bucketName);
$this->collectionInfo->setCollection($annotation->bucketName . ".files");
if (null !== ($rep = $annotation->repositoryClass)) {
$this->collectionInfo->setRepository($annotation->repositoryClass);
} else {
$this->collectionInfo->setRepository("JPC\MongoDB\ODM\GridFS\Repository");
}
if (null !== ($rep = $annotation->hydratorClass)) {
$this->collectionInfo->setHydrator($annotation->hydratorClass);
} else {
$this->collectionInfo->setHydrator("JPC\MongoDB\ODM\GridFS\Hydrator");
}
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Option":
$this->processOptionAnnotation($annotation);
break;
case "JPC\MongoDB\ODM\Annotations\Event\HasLifecycleCallbacks":
$this->hasEvent = true;
break;
}
}
|
[
"private",
"function",
"processClassAnnotation",
"(",
"$",
"annotation",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"annotation",
")",
";",
"switch",
"(",
"$",
"class",
")",
"{",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\Document\"",
":",
"$",
"this",
"->",
"collectionInfo",
"->",
"setCollection",
"(",
"$",
"annotation",
"->",
"collectionName",
")",
";",
"if",
"(",
"null",
"!==",
"(",
"$",
"rep",
"=",
"$",
"annotation",
"->",
"repositoryClass",
")",
")",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setRepository",
"(",
"$",
"annotation",
"->",
"repositoryClass",
")",
";",
"}",
"else",
"{",
"if",
"(",
"class_exists",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"'Repository'",
")",
")",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setRepository",
"(",
"$",
"this",
"->",
"getName",
"(",
")",
".",
"'Repository'",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setRepository",
"(",
"\"JPC\\MongoDB\\ODM\\Repository\"",
")",
";",
"}",
"}",
"if",
"(",
"null",
"!==",
"(",
"$",
"rep",
"=",
"$",
"annotation",
"->",
"hydratorClass",
")",
")",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setHydrator",
"(",
"$",
"annotation",
"->",
"hydratorClass",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setHydrator",
"(",
"\"JPC\\MongoDB\\ODM\\Hydrator\"",
")",
";",
"}",
"$",
"this",
"->",
"checkCollectionCreationOptions",
"(",
"$",
"annotation",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Document\"",
":",
"$",
"this",
"->",
"collectionInfo",
"->",
"setBucketName",
"(",
"$",
"annotation",
"->",
"bucketName",
")",
";",
"$",
"this",
"->",
"collectionInfo",
"->",
"setCollection",
"(",
"$",
"annotation",
"->",
"bucketName",
".",
"\".files\"",
")",
";",
"if",
"(",
"null",
"!==",
"(",
"$",
"rep",
"=",
"$",
"annotation",
"->",
"repositoryClass",
")",
")",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setRepository",
"(",
"$",
"annotation",
"->",
"repositoryClass",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setRepository",
"(",
"\"JPC\\MongoDB\\ODM\\GridFS\\Repository\"",
")",
";",
"}",
"if",
"(",
"null",
"!==",
"(",
"$",
"rep",
"=",
"$",
"annotation",
"->",
"hydratorClass",
")",
")",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setHydrator",
"(",
"$",
"annotation",
"->",
"hydratorClass",
")",
";",
"}",
"else",
"{",
"$",
"this",
"->",
"collectionInfo",
"->",
"setHydrator",
"(",
"\"JPC\\MongoDB\\ODM\\GridFS\\Hydrator\"",
")",
";",
"}",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\Option\"",
":",
"$",
"this",
"->",
"processOptionAnnotation",
"(",
"$",
"annotation",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Event\\HasLifecycleCallbacks\"",
":",
"$",
"this",
"->",
"hasEvent",
"=",
"true",
";",
"break",
";",
"}",
"}"
] |
Process class annotation to extract infos
@param Annotation $annotation Annotation to process
@return void
|
[
"Process",
"class",
"annotation",
"to",
"extract",
"infos"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L360-L408
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.processOptionAnnotation
|
private function processOptionAnnotation(\JPC\MongoDB\ODM\Annotations\Mapping\Option $annotation)
{
$options = [];
if (isset($annotation->writeConcern)) {
$options["writeConcern"] = $annotation->writeConcern->getWriteConcern();
}
if (isset($annotation->readConcern)) {
$options["readConcern"] = $annotation->readConcern->getReadConcern();
}
if (isset($annotation->readPreference)) {
$options["readPreference"] = $annotation->readPreference->getReadPreference();
}
if (isset($annotation->typeMap)) {
$options["typeMap"] = $annotation->typeMap;
}
$this->collectionInfo->setOptions($options);
}
|
php
|
private function processOptionAnnotation(\JPC\MongoDB\ODM\Annotations\Mapping\Option $annotation)
{
$options = [];
if (isset($annotation->writeConcern)) {
$options["writeConcern"] = $annotation->writeConcern->getWriteConcern();
}
if (isset($annotation->readConcern)) {
$options["readConcern"] = $annotation->readConcern->getReadConcern();
}
if (isset($annotation->readPreference)) {
$options["readPreference"] = $annotation->readPreference->getReadPreference();
}
if (isset($annotation->typeMap)) {
$options["typeMap"] = $annotation->typeMap;
}
$this->collectionInfo->setOptions($options);
}
|
[
"private",
"function",
"processOptionAnnotation",
"(",
"\\",
"JPC",
"\\",
"MongoDB",
"\\",
"ODM",
"\\",
"Annotations",
"\\",
"Mapping",
"\\",
"Option",
"$",
"annotation",
")",
"{",
"$",
"options",
"=",
"[",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"writeConcern",
")",
")",
"{",
"$",
"options",
"[",
"\"writeConcern\"",
"]",
"=",
"$",
"annotation",
"->",
"writeConcern",
"->",
"getWriteConcern",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"readConcern",
")",
")",
"{",
"$",
"options",
"[",
"\"readConcern\"",
"]",
"=",
"$",
"annotation",
"->",
"readConcern",
"->",
"getReadConcern",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"readPreference",
")",
")",
"{",
"$",
"options",
"[",
"\"readPreference\"",
"]",
"=",
"$",
"annotation",
"->",
"readPreference",
"->",
"getReadPreference",
"(",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"annotation",
"->",
"typeMap",
")",
")",
"{",
"$",
"options",
"[",
"\"typeMap\"",
"]",
"=",
"$",
"annotation",
"->",
"typeMap",
";",
"}",
"$",
"this",
"->",
"collectionInfo",
"->",
"setOptions",
"(",
"$",
"options",
")",
";",
"}"
] |
Process option annotation
@param \JPC\MongoDB\ODM\Annotations\Mapping\Option $annotation Annotation to process
@return void
|
[
"Process",
"option",
"annotation"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L416-L436
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.processPropertiesAnnotation
|
private function processPropertiesAnnotation($name, $annotation)
{
$class = get_class($annotation);
switch ($class) {
case "JPC\MongoDB\ODM\Annotations\Mapping\Id":
$this->propertiesInfos[$name]->setField("_id");
$this->idGenerator = $annotation->generator;
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Field":
$this->propertiesInfos[$name]->setField($annotation->name);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\EmbeddedDocument":
$this->propertiesInfos[$name]->setEmbedded(true);
$this->propertiesInfos[$name]->setEmbeddedClass($annotation->document);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\MultiEmbeddedDocument":
$this->propertiesInfos[$name]->setMultiEmbedded(true);
$this->propertiesInfos[$name]->setEmbeddedClass($annotation->document);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Id":
$this->propertiesInfos[$name]->setField("_id");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Stream":
$this->propertiesInfos[$name]->setField("stream");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Filename":
$this->propertiesInfos[$name]->setField("filename");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Aliases":
$this->propertiesInfos[$name]->setField("aliases");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\ChunkSize":
$this->propertiesInfos[$name]->setField("chunkSize");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\UploadDate":
$this->propertiesInfos[$name]->setField("uploadDate");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Length":
$this->propertiesInfos[$name]->setField("length");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\ContentType":
$this->propertiesInfos[$name]->setField("contentType");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Md5":
$this->propertiesInfos[$name]->setField("md5");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Metadata":
$this->propertiesInfos[$name]->setMetadata(true);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\RefersOne":
$referenceInfo = new ReferenceInfo();
$referenceInfo->setDocument($annotation->document)->setCollection($annotation->collection);
$this->propertiesInfos[$name]->setReferenceInfo($referenceInfo);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\RefersMany":
$referenceInfo = new ReferenceInfo();
$referenceInfo->setIsMultiple(true)->setDocument($annotation->document)->setCollection($annotation->collection);
$this->propertiesInfos[$name]->setReferenceInfo($referenceInfo);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorField":
$this->propertiesInfos[$name]->setDiscriminatorField($annotation->field);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorMap":
$this->propertiesInfos[$name]->setDiscriminatorMap($annotation->map);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorMethod":
$this->propertiesInfos[$name]->setDiscriminatorMethod($annotation->method);
break;
}
}
|
php
|
private function processPropertiesAnnotation($name, $annotation)
{
$class = get_class($annotation);
switch ($class) {
case "JPC\MongoDB\ODM\Annotations\Mapping\Id":
$this->propertiesInfos[$name]->setField("_id");
$this->idGenerator = $annotation->generator;
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Field":
$this->propertiesInfos[$name]->setField($annotation->name);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\EmbeddedDocument":
$this->propertiesInfos[$name]->setEmbedded(true);
$this->propertiesInfos[$name]->setEmbeddedClass($annotation->document);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\MultiEmbeddedDocument":
$this->propertiesInfos[$name]->setMultiEmbedded(true);
$this->propertiesInfos[$name]->setEmbeddedClass($annotation->document);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\Id":
$this->propertiesInfos[$name]->setField("_id");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Stream":
$this->propertiesInfos[$name]->setField("stream");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Filename":
$this->propertiesInfos[$name]->setField("filename");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Aliases":
$this->propertiesInfos[$name]->setField("aliases");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\ChunkSize":
$this->propertiesInfos[$name]->setField("chunkSize");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\UploadDate":
$this->propertiesInfos[$name]->setField("uploadDate");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Length":
$this->propertiesInfos[$name]->setField("length");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\ContentType":
$this->propertiesInfos[$name]->setField("contentType");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Md5":
$this->propertiesInfos[$name]->setField("md5");
break;
case "JPC\MongoDB\ODM\GridFS\Annotations\Mapping\Metadata":
$this->propertiesInfos[$name]->setMetadata(true);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\RefersOne":
$referenceInfo = new ReferenceInfo();
$referenceInfo->setDocument($annotation->document)->setCollection($annotation->collection);
$this->propertiesInfos[$name]->setReferenceInfo($referenceInfo);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\RefersMany":
$referenceInfo = new ReferenceInfo();
$referenceInfo->setIsMultiple(true)->setDocument($annotation->document)->setCollection($annotation->collection);
$this->propertiesInfos[$name]->setReferenceInfo($referenceInfo);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorField":
$this->propertiesInfos[$name]->setDiscriminatorField($annotation->field);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorMap":
$this->propertiesInfos[$name]->setDiscriminatorMap($annotation->map);
break;
case "JPC\MongoDB\ODM\Annotations\Mapping\DiscriminatorMethod":
$this->propertiesInfos[$name]->setDiscriminatorMethod($annotation->method);
break;
}
}
|
[
"private",
"function",
"processPropertiesAnnotation",
"(",
"$",
"name",
",",
"$",
"annotation",
")",
"{",
"$",
"class",
"=",
"get_class",
"(",
"$",
"annotation",
")",
";",
"switch",
"(",
"$",
"class",
")",
"{",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\Id\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"_id\"",
")",
";",
"$",
"this",
"->",
"idGenerator",
"=",
"$",
"annotation",
"->",
"generator",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\Field\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"$",
"annotation",
"->",
"name",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\EmbeddedDocument\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setEmbedded",
"(",
"true",
")",
";",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setEmbeddedClass",
"(",
"$",
"annotation",
"->",
"document",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\MultiEmbeddedDocument\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setMultiEmbedded",
"(",
"true",
")",
";",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setEmbeddedClass",
"(",
"$",
"annotation",
"->",
"document",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\Id\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"_id\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Stream\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"stream\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Filename\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"filename\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Aliases\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"aliases\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\ChunkSize\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"chunkSize\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\UploadDate\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"uploadDate\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Length\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"length\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\ContentType\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"contentType\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Md5\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setField",
"(",
"\"md5\"",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\GridFS\\Annotations\\Mapping\\Metadata\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setMetadata",
"(",
"true",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\RefersOne\"",
":",
"$",
"referenceInfo",
"=",
"new",
"ReferenceInfo",
"(",
")",
";",
"$",
"referenceInfo",
"->",
"setDocument",
"(",
"$",
"annotation",
"->",
"document",
")",
"->",
"setCollection",
"(",
"$",
"annotation",
"->",
"collection",
")",
";",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setReferenceInfo",
"(",
"$",
"referenceInfo",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\RefersMany\"",
":",
"$",
"referenceInfo",
"=",
"new",
"ReferenceInfo",
"(",
")",
";",
"$",
"referenceInfo",
"->",
"setIsMultiple",
"(",
"true",
")",
"->",
"setDocument",
"(",
"$",
"annotation",
"->",
"document",
")",
"->",
"setCollection",
"(",
"$",
"annotation",
"->",
"collection",
")",
";",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setReferenceInfo",
"(",
"$",
"referenceInfo",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\DiscriminatorField\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setDiscriminatorField",
"(",
"$",
"annotation",
"->",
"field",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\DiscriminatorMap\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setDiscriminatorMap",
"(",
"$",
"annotation",
"->",
"map",
")",
";",
"break",
";",
"case",
"\"JPC\\MongoDB\\ODM\\Annotations\\Mapping\\DiscriminatorMethod\"",
":",
"$",
"this",
"->",
"propertiesInfos",
"[",
"$",
"name",
"]",
"->",
"setDiscriminatorMethod",
"(",
"$",
"annotation",
"->",
"method",
")",
";",
"break",
";",
"}",
"}"
] |
Process property annotation
@param string $name Name of the property
@param Annotation $annotation Annotation to process
@return void
|
[
"Process",
"property",
"annotation"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L445-L514
|
JoffreyPoreeCoding/MongoDB-ODM
|
src/Tools/ClassMetadata/ClassMetadata.php
|
ClassMetadata.checkCollectionCreationOptions
|
private function checkCollectionCreationOptions(\JPC\MongoDB\ODM\Annotations\Mapping\Document $annotation)
{
$options = [];
if ($annotation->capped) {
$options["capped"] = true;
$options["size"] = $annotation->size;
if ($annotation->max != false) {
$options["max"] = $annotation->max;
}
}
$this->collectionInfo->setCreationOptions($options);
}
|
php
|
private function checkCollectionCreationOptions(\JPC\MongoDB\ODM\Annotations\Mapping\Document $annotation)
{
$options = [];
if ($annotation->capped) {
$options["capped"] = true;
$options["size"] = $annotation->size;
if ($annotation->max != false) {
$options["max"] = $annotation->max;
}
}
$this->collectionInfo->setCreationOptions($options);
}
|
[
"private",
"function",
"checkCollectionCreationOptions",
"(",
"\\",
"JPC",
"\\",
"MongoDB",
"\\",
"ODM",
"\\",
"Annotations",
"\\",
"Mapping",
"\\",
"Document",
"$",
"annotation",
")",
"{",
"$",
"options",
"=",
"[",
"]",
";",
"if",
"(",
"$",
"annotation",
"->",
"capped",
")",
"{",
"$",
"options",
"[",
"\"capped\"",
"]",
"=",
"true",
";",
"$",
"options",
"[",
"\"size\"",
"]",
"=",
"$",
"annotation",
"->",
"size",
";",
"if",
"(",
"$",
"annotation",
"->",
"max",
"!=",
"false",
")",
"{",
"$",
"options",
"[",
"\"max\"",
"]",
"=",
"$",
"annotation",
"->",
"max",
";",
"}",
"}",
"$",
"this",
"->",
"collectionInfo",
"->",
"setCreationOptions",
"(",
"$",
"options",
")",
";",
"}"
] |
Check and set collection creation options
@param \JPC\MongoDB\ODM\Annotations\Mapping\Document $annotation Annotation to process
@return void
|
[
"Check",
"and",
"set",
"collection",
"creation",
"options"
] |
train
|
https://github.com/JoffreyPoreeCoding/MongoDB-ODM/blob/56fd7ab28c22f276573a89d56bb93c8d74ad7f74/src/Tools/ClassMetadata/ClassMetadata.php#L522-L535
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.convertToShiftJISableInAnswerWithoutKatakana
|
protected function convertToShiftJISableInAnswerWithoutKatakana(string $str): string
{
return preg_replace_callback(
'/(?:ゎー|(?<no_replace_a>(?<sokuon_or_n>[んっ])ー*)ー|(?<no_replace_b>(?<previous>[ぁ-を])ー*)ーー)$/u',
function (array $matches): string {
if ($matches[0] === 'ゎー') {
$end = 'ゎあ';
} elseif ($matches['sokuon_or_n']) {
$end = $matches['no_replace_a'] . $matches['sokuon_or_n'];
} else {
$end = $matches['no_replace_b'] . self::VOWEL_CORRESPONDENCE_TABLE[$matches['previous']] . 'ー';
}
return $end;
},
str_replace(
['~', 'ゐ', 'ゑ', 'ヴぁ', 'ヴぃ', 'ヴぇ', 'ヴぉ', 'ヴ', 'ヵ', 'ヶ'],
['ー', 'い', 'え', 'ば' , 'び' , 'べ' , 'ぼ' , 'ぶ', 'か', 'け'],
$this->convertToShiftJISableInAnswer($str)
)
);
}
|
php
|
protected function convertToShiftJISableInAnswerWithoutKatakana(string $str): string
{
return preg_replace_callback(
'/(?:ゎー|(?<no_replace_a>(?<sokuon_or_n>[んっ])ー*)ー|(?<no_replace_b>(?<previous>[ぁ-を])ー*)ーー)$/u',
function (array $matches): string {
if ($matches[0] === 'ゎー') {
$end = 'ゎあ';
} elseif ($matches['sokuon_or_n']) {
$end = $matches['no_replace_a'] . $matches['sokuon_or_n'];
} else {
$end = $matches['no_replace_b'] . self::VOWEL_CORRESPONDENCE_TABLE[$matches['previous']] . 'ー';
}
return $end;
},
str_replace(
['~', 'ゐ', 'ゑ', 'ヴぁ', 'ヴぃ', 'ヴぇ', 'ヴぉ', 'ヴ', 'ヵ', 'ヶ'],
['ー', 'い', 'え', 'ば' , 'び' , 'べ' , 'ぼ' , 'ぶ', 'か', 'け'],
$this->convertToShiftJISableInAnswer($str)
)
);
}
|
[
"protected",
"function",
"convertToShiftJISableInAnswerWithoutKatakana",
"(",
"string",
"$",
"str",
")",
":",
"string",
"{",
"return",
"preg_replace_callback",
"(",
"'/(?:ゎー|(?<no_replace_a>(?<sokuon_or_n>[んっ])ー*)ー|(?<no_replace_b>(?<previous>[ぁ-を])ー*)ーー)$/u',",
"",
"function",
"(",
"array",
"$",
"matches",
")",
":",
"string",
"{",
"if",
"(",
"$",
"matches",
"[",
"0",
"]",
"===",
"'ゎー') {",
"",
"",
"$",
"end",
"=",
"'ゎあ';",
"",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'sokuon_or_n'",
"]",
")",
"{",
"$",
"end",
"=",
"$",
"matches",
"[",
"'no_replace_a'",
"]",
".",
"$",
"matches",
"[",
"'sokuon_or_n'",
"]",
";",
"}",
"else",
"{",
"$",
"end",
"=",
"$",
"matches",
"[",
"'no_replace_b'",
"]",
".",
"self",
"::",
"VOWEL_CORRESPONDENCE_TABLE",
"[",
"$",
"matches",
"[",
"'previous'",
"]",
"]",
".",
"'ー';",
"",
"}",
"return",
"$",
"end",
";",
"}",
",",
"str_replace",
"(",
"[",
"'~', ",
"'",
"', 'ゑ",
"'",
" 'ヴぁ'",
",",
"'ヴぃ', 'ヴ",
"ぇ",
", 'ヴぉ', ",
"'",
"', 'ヵ', ",
"'",
"'],",
"",
"",
"",
"",
"",
"",
"",
"",
"[",
"'ー', ",
"'",
"', 'え",
"'",
" 'ば' ",
" ",
" 'び' ",
" ",
"べ' ,",
"ぼ",
" , '",
",",
"'か', ",
"'",
",",
"",
"",
"",
"",
"",
"",
"$",
"this",
"->",
"convertToShiftJISableInAnswer",
"(",
"$",
"str",
")",
")",
")",
";",
"}"
] |
解答内のShift_JISに存在しないひらがな、カタカナなどを、Shift_JISに直列化可能なひらがなに置き換えます。
また、「ゐ」「ゑ」は「い」「え」に置き換えます。波ダッシュ「〜」は長音符「ー」に置換します。
末尾の「んー」「ゎー」「ーー」についても処理します。
@param string $str
@return string
|
[
"解答内のShift_JISに存在しないひらがな、カタカナなどを、Shift_JISに直列化可能なひらがなに置き換えます。",
"また、「ゐ」「ゑ」は「い」「え」に置き換えます。波ダッシュ「〜」は長音符「ー」に置換します。",
"末尾の「んー」「ゎー」「ーー」についても処理します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L53-L73
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.serializeWordAsShiritori
|
protected function serializeWordAsShiritori(array $word): string
{
if (!isset($word['type'][0]) || $word['type'][0] !== 'selection') {
$answers = preg_filter(
'/^[ぁ-わを][ぁ-わをんー]*$/u',
'$0',
$this->getAnswers($word, [$this, 'convertToShiftJISableInAnswerWithoutKatakana'])
);
if ($answers) {
array_unshift(
$answers,
str_replace([',', "\n"], [',', ' '], $this->convertToShiftJISable($word['text'][0]))
);
if (isset($word['weight'][0])) {
$answers[] = round(1 / $word['weight'][0]);
}
if (isset($word['description'][0])) {
$answers[] = '@' . str_replace(
[',', "\n"],
[',', ' '],
$this->convertToShiftJISable($word['description'][0]['lml'])
);
}
$output = implode(',', $answers) . "\r\n";
}
}
if (!isset($output)) {
$output = '';
$this->logUnserializableError('Inteligenceω しりとり', $word);
}
return $output;
}
|
php
|
protected function serializeWordAsShiritori(array $word): string
{
if (!isset($word['type'][0]) || $word['type'][0] !== 'selection') {
$answers = preg_filter(
'/^[ぁ-わを][ぁ-わをんー]*$/u',
'$0',
$this->getAnswers($word, [$this, 'convertToShiftJISableInAnswerWithoutKatakana'])
);
if ($answers) {
array_unshift(
$answers,
str_replace([',', "\n"], [',', ' '], $this->convertToShiftJISable($word['text'][0]))
);
if (isset($word['weight'][0])) {
$answers[] = round(1 / $word['weight'][0]);
}
if (isset($word['description'][0])) {
$answers[] = '@' . str_replace(
[',', "\n"],
[',', ' '],
$this->convertToShiftJISable($word['description'][0]['lml'])
);
}
$output = implode(',', $answers) . "\r\n";
}
}
if (!isset($output)) {
$output = '';
$this->logUnserializableError('Inteligenceω しりとり', $word);
}
return $output;
}
|
[
"protected",
"function",
"serializeWordAsShiritori",
"(",
"array",
"$",
"word",
")",
":",
"string",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
")",
"||",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
"!==",
"'selection'",
")",
"{",
"$",
"answers",
"=",
"preg_filter",
"(",
"'/^[ぁ-わを][ぁ-わをんー]*$/u',",
"",
"'$0'",
",",
"$",
"this",
"->",
"getAnswers",
"(",
"$",
"word",
",",
"[",
"$",
"this",
",",
"'convertToShiftJISableInAnswerWithoutKatakana'",
"]",
")",
")",
";",
"if",
"(",
"$",
"answers",
")",
"{",
"array_unshift",
"(",
"$",
"answers",
",",
"str_replace",
"(",
"[",
"','",
",",
"\"\\n\"",
"]",
",",
"[",
"',', ",
"'",
"'],",
" ",
"$",
"h",
"is->",
"co",
"nvertToShiftJISable($",
"w",
"o",
"rd['",
"t",
"ext'][",
"0",
"]",
")",
")",
"",
"",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'weight'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"answers",
"[",
"]",
"=",
"round",
"(",
"1",
"/",
"$",
"word",
"[",
"'weight'",
"]",
"[",
"0",
"]",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'description'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"answers",
"[",
"]",
"=",
"'@'",
".",
"str_replace",
"(",
"[",
"','",
",",
"\"\\n\"",
"]",
",",
"[",
"',', ",
"'",
"'],",
"",
"",
"$",
"this",
"->",
"convertToShiftJISable",
"(",
"$",
"word",
"[",
"'description'",
"]",
"[",
"0",
"]",
"[",
"'lml'",
"]",
")",
")",
";",
"}",
"$",
"output",
"=",
"implode",
"(",
"','",
",",
"$",
"answers",
")",
".",
"\"\\r\\n\"",
";",
"}",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"output",
")",
")",
"{",
"$",
"output",
"=",
"''",
";",
"$",
"this",
"->",
"logUnserializableError",
"(",
"'Inteligenceω しりとり', $word);",
"",
"",
"",
"",
"",
"}",
"return",
"$",
"output",
";",
"}"
] |
一つのお題を表す配列をしりとり形式で直列化します。
@param (string|string[]|float)[][] $word
@return string 末尾に改行 (CRLF) を含みます。直列化できないお題だった場合は空文字列を返します。
|
[
"一つのお題を表す配列をしりとり形式で直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L80-L112
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.serializeQuizField
|
protected function serializeQuizField(string $field): string
{
return str_replace(['\\', ',', '=', "\n"], ['\\\\', ',', '=', '\\n'], $this->convertToShiftJISable($field));
}
|
php
|
protected function serializeQuizField(string $field): string
{
return str_replace(['\\', ',', '=', "\n"], ['\\\\', ',', '=', '\\n'], $this->convertToShiftJISable($field));
}
|
[
"protected",
"function",
"serializeQuizField",
"(",
"string",
"$",
"field",
")",
":",
"string",
"{",
"return",
"str_replace",
"(",
"[",
"'\\\\'",
",",
"','",
",",
"'='",
",",
"\"\\n\"",
"]",
",",
"[",
"'\\\\\\\\'",
",",
"',', ",
"'",
"', '\\",
"\\",
"'], $",
"t",
"h",
"s",
"->co",
"nv",
"ertToShiftJISable($fi",
"e",
"l",
"d));",
"",
"",
"",
"}"
] |
クイズ形式における、カンマ区切りの一つのフィールドを直列化します。
@param string $field
|
[
"クイズ形式における、カンマ区切りの一つのフィールドを直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L118-L121
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.serializeQuestionLine
|
protected function serializeQuestionLine(array $word, string $directoryName, array $filenames): string
{
$line = ['Q'];
if (isset($word['image'][0])) {
$line[] = 2;
$fileLocation = $word['image'][0];
} elseif (isset($word['audio'][0])) {
$line[] = 1;
$fileLocation = $word['audio'][0];
} else {
$line[] = 0;
}
$line[] = isset($word['question'][0]) ? $this->serializeQuizField($word['question'][0]) : '';
if (isset($fileLocation)) {
$line[] = str_replace(',', '%2C', in_array($fileLocation, $filenames)
? (is_string($this->textFileOnly)
? sprintf($this->textFileOnly, $fileLocation)
: "./$directoryName/$fileLocation")
: $fileLocation);
}
if (isset($word['specifics'][0])) {
$specifics = new URLSearchParams($word['specifics'][0]);
if ($specifics->has('start')) {
$line[] = 'start=' . round($specifics->get('start') * InteligenceoParser::SECONDS_TO_MILISECONDS);
}
if ($specifics->has('repeat')) {
$line[] = 'repeat=' . $specifics->get('repeat');
}
if ($specifics->has('length')) {
$line[] = 'length=' . round($specifics->get('length') * InteligenceoParser::SECONDS_TO_MILISECONDS);
}
if ($specifics->has('speed')) {
$line[] = 'speed=' . round($specifics->get('speed') * InteligenceoParser::DECIMAL_TO_PERCENT);
}
if ($specifics->has('magnification')) {
$magnification = round($specifics->get('magnification'));
if ($magnification > 0) {
$line[] = "zoom_start=$magnification";
if ($specifics->has('last-magnification')) {
$lastMagnification = round($specifics->get('last-magnification'));
if ($lastMagnification > 0) {
$line[] = "zoom_end=$lastMagnification";
}
}
}
}
if ($specifics->has('pixelization')) {
$line[] = 'mozaic=1';
}
if ($specifics->has('score')) {
$line[] = 'score=' . $specifics->get('score');
if ($specifics->has('last-score')) {
$line[] = 'finalscore=' . $specifics->get('last-score');
}
}
}
return implode(',', $line) . "\r\n";
}
|
php
|
protected function serializeQuestionLine(array $word, string $directoryName, array $filenames): string
{
$line = ['Q'];
if (isset($word['image'][0])) {
$line[] = 2;
$fileLocation = $word['image'][0];
} elseif (isset($word['audio'][0])) {
$line[] = 1;
$fileLocation = $word['audio'][0];
} else {
$line[] = 0;
}
$line[] = isset($word['question'][0]) ? $this->serializeQuizField($word['question'][0]) : '';
if (isset($fileLocation)) {
$line[] = str_replace(',', '%2C', in_array($fileLocation, $filenames)
? (is_string($this->textFileOnly)
? sprintf($this->textFileOnly, $fileLocation)
: "./$directoryName/$fileLocation")
: $fileLocation);
}
if (isset($word['specifics'][0])) {
$specifics = new URLSearchParams($word['specifics'][0]);
if ($specifics->has('start')) {
$line[] = 'start=' . round($specifics->get('start') * InteligenceoParser::SECONDS_TO_MILISECONDS);
}
if ($specifics->has('repeat')) {
$line[] = 'repeat=' . $specifics->get('repeat');
}
if ($specifics->has('length')) {
$line[] = 'length=' . round($specifics->get('length') * InteligenceoParser::SECONDS_TO_MILISECONDS);
}
if ($specifics->has('speed')) {
$line[] = 'speed=' . round($specifics->get('speed') * InteligenceoParser::DECIMAL_TO_PERCENT);
}
if ($specifics->has('magnification')) {
$magnification = round($specifics->get('magnification'));
if ($magnification > 0) {
$line[] = "zoom_start=$magnification";
if ($specifics->has('last-magnification')) {
$lastMagnification = round($specifics->get('last-magnification'));
if ($lastMagnification > 0) {
$line[] = "zoom_end=$lastMagnification";
}
}
}
}
if ($specifics->has('pixelization')) {
$line[] = 'mozaic=1';
}
if ($specifics->has('score')) {
$line[] = 'score=' . $specifics->get('score');
if ($specifics->has('last-score')) {
$line[] = 'finalscore=' . $specifics->get('last-score');
}
}
}
return implode(',', $line) . "\r\n";
}
|
[
"protected",
"function",
"serializeQuestionLine",
"(",
"array",
"$",
"word",
",",
"string",
"$",
"directoryName",
",",
"array",
"$",
"filenames",
")",
":",
"string",
"{",
"$",
"line",
"=",
"[",
"'Q'",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'image'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"2",
";",
"$",
"fileLocation",
"=",
"$",
"word",
"[",
"'image'",
"]",
"[",
"0",
"]",
";",
"}",
"elseif",
"(",
"isset",
"(",
"$",
"word",
"[",
"'audio'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"1",
";",
"$",
"fileLocation",
"=",
"$",
"word",
"[",
"'audio'",
"]",
"[",
"0",
"]",
";",
"}",
"else",
"{",
"$",
"line",
"[",
"]",
"=",
"0",
";",
"}",
"$",
"line",
"[",
"]",
"=",
"isset",
"(",
"$",
"word",
"[",
"'question'",
"]",
"[",
"0",
"]",
")",
"?",
"$",
"this",
"->",
"serializeQuizField",
"(",
"$",
"word",
"[",
"'question'",
"]",
"[",
"0",
"]",
")",
":",
"''",
";",
"if",
"(",
"isset",
"(",
"$",
"fileLocation",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"str_replace",
"(",
"','",
",",
"'%2C'",
",",
"in_array",
"(",
"$",
"fileLocation",
",",
"$",
"filenames",
")",
"?",
"(",
"is_string",
"(",
"$",
"this",
"->",
"textFileOnly",
")",
"?",
"sprintf",
"(",
"$",
"this",
"->",
"textFileOnly",
",",
"$",
"fileLocation",
")",
":",
"\"./$directoryName/$fileLocation\"",
")",
":",
"$",
"fileLocation",
")",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'specifics'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"specifics",
"=",
"new",
"URLSearchParams",
"(",
"$",
"word",
"[",
"'specifics'",
"]",
"[",
"0",
"]",
")",
";",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'start'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'start='",
".",
"round",
"(",
"$",
"specifics",
"->",
"get",
"(",
"'start'",
")",
"*",
"InteligenceoParser",
"::",
"SECONDS_TO_MILISECONDS",
")",
";",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'repeat'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'repeat='",
".",
"$",
"specifics",
"->",
"get",
"(",
"'repeat'",
")",
";",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'length'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'length='",
".",
"round",
"(",
"$",
"specifics",
"->",
"get",
"(",
"'length'",
")",
"*",
"InteligenceoParser",
"::",
"SECONDS_TO_MILISECONDS",
")",
";",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'speed'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'speed='",
".",
"round",
"(",
"$",
"specifics",
"->",
"get",
"(",
"'speed'",
")",
"*",
"InteligenceoParser",
"::",
"DECIMAL_TO_PERCENT",
")",
";",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'magnification'",
")",
")",
"{",
"$",
"magnification",
"=",
"round",
"(",
"$",
"specifics",
"->",
"get",
"(",
"'magnification'",
")",
")",
";",
"if",
"(",
"$",
"magnification",
">",
"0",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"\"zoom_start=$magnification\"",
";",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'last-magnification'",
")",
")",
"{",
"$",
"lastMagnification",
"=",
"round",
"(",
"$",
"specifics",
"->",
"get",
"(",
"'last-magnification'",
")",
")",
";",
"if",
"(",
"$",
"lastMagnification",
">",
"0",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"\"zoom_end=$lastMagnification\"",
";",
"}",
"}",
"}",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'pixelization'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'mozaic=1'",
";",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'score'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'score='",
".",
"$",
"specifics",
"->",
"get",
"(",
"'score'",
")",
";",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'last-score'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'finalscore='",
".",
"$",
"specifics",
"->",
"get",
"(",
"'last-score'",
")",
";",
"}",
"}",
"}",
"return",
"implode",
"(",
"','",
",",
"$",
"line",
")",
".",
"\"\\r\\n\"",
";",
"}"
] |
一つのお題を表す配列から問題行に直列化します。
@param (string|string[]|float)[][] $word
@param string $directoryName
@param string[] $filenames
@return string 末尾に改行 (CRLF) を含みます。
|
[
"一つのお題を表す配列から問題行に直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L130-L192
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.serializeAnswerLine
|
protected function serializeAnswerLine(array $word): string
{
$line = ['A'];
$specifics = new URLSearchParams($word['specifics'][0] ?? '');
if (isset($word['option'][0])) {
if (isset($word['type'][0]) && $word['type'][0] === 'selection' && empty($word['answer'])) {
$line[] = 2;
} elseif ($specifics->has('require-all-right')) {
$line[] = 3;
} else {
$line[] = 1;
}
$answers = isset($word['answer'][0]) ? $word['answer'] : $word['text'];
foreach ($word['option'] as $i => $option) {
$line[] = $this->serializeQuizField($option);
if ($line[1] === 2) {
$line[] = $i + 1;
} elseif (in_array($option, $answers)) {
$line[] = '\\seikai';
}
}
if ($specifics->has('no-random')) {
$line[] = '\\norandom';
}
} else {
$line[] = 0;
$answers = $this->getAnswers($word, [$this, 'convertToShiftJISableInAnswerWithKatakana']);
if (!$answers) {
$this->logUnserializableError('Inteligenceω クイズ', $word);
return '';
}
$bonuses = $specifics->getAll('bonus');
foreach ($answers as $i => $answer) {
$line[] = $answer;
if (!empty($bonuses[$i])) {
$line[] = "\\bonus=$bonuses[$i]";
}
}
}
$explain[] = $word['text'][0];
if (isset($word['description'][0])) {
$explain[] = $word['description'][0]['lml'];
}
$line[] = '\\explain=' . $this->serializeQuizField(implode("\n\n", $explain));
return implode(',', $line) . "\r\n";
}
|
php
|
protected function serializeAnswerLine(array $word): string
{
$line = ['A'];
$specifics = new URLSearchParams($word['specifics'][0] ?? '');
if (isset($word['option'][0])) {
if (isset($word['type'][0]) && $word['type'][0] === 'selection' && empty($word['answer'])) {
$line[] = 2;
} elseif ($specifics->has('require-all-right')) {
$line[] = 3;
} else {
$line[] = 1;
}
$answers = isset($word['answer'][0]) ? $word['answer'] : $word['text'];
foreach ($word['option'] as $i => $option) {
$line[] = $this->serializeQuizField($option);
if ($line[1] === 2) {
$line[] = $i + 1;
} elseif (in_array($option, $answers)) {
$line[] = '\\seikai';
}
}
if ($specifics->has('no-random')) {
$line[] = '\\norandom';
}
} else {
$line[] = 0;
$answers = $this->getAnswers($word, [$this, 'convertToShiftJISableInAnswerWithKatakana']);
if (!$answers) {
$this->logUnserializableError('Inteligenceω クイズ', $word);
return '';
}
$bonuses = $specifics->getAll('bonus');
foreach ($answers as $i => $answer) {
$line[] = $answer;
if (!empty($bonuses[$i])) {
$line[] = "\\bonus=$bonuses[$i]";
}
}
}
$explain[] = $word['text'][0];
if (isset($word['description'][0])) {
$explain[] = $word['description'][0]['lml'];
}
$line[] = '\\explain=' . $this->serializeQuizField(implode("\n\n", $explain));
return implode(',', $line) . "\r\n";
}
|
[
"protected",
"function",
"serializeAnswerLine",
"(",
"array",
"$",
"word",
")",
":",
"string",
"{",
"$",
"line",
"=",
"[",
"'A'",
"]",
";",
"$",
"specifics",
"=",
"new",
"URLSearchParams",
"(",
"$",
"word",
"[",
"'specifics'",
"]",
"[",
"0",
"]",
"??",
"''",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'option'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
")",
"&&",
"$",
"word",
"[",
"'type'",
"]",
"[",
"0",
"]",
"===",
"'selection'",
"&&",
"empty",
"(",
"$",
"word",
"[",
"'answer'",
"]",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"2",
";",
"}",
"elseif",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'require-all-right'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"3",
";",
"}",
"else",
"{",
"$",
"line",
"[",
"]",
"=",
"1",
";",
"}",
"$",
"answers",
"=",
"isset",
"(",
"$",
"word",
"[",
"'answer'",
"]",
"[",
"0",
"]",
")",
"?",
"$",
"word",
"[",
"'answer'",
"]",
":",
"$",
"word",
"[",
"'text'",
"]",
";",
"foreach",
"(",
"$",
"word",
"[",
"'option'",
"]",
"as",
"$",
"i",
"=>",
"$",
"option",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"$",
"this",
"->",
"serializeQuizField",
"(",
"$",
"option",
")",
";",
"if",
"(",
"$",
"line",
"[",
"1",
"]",
"===",
"2",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"$",
"i",
"+",
"1",
";",
"}",
"elseif",
"(",
"in_array",
"(",
"$",
"option",
",",
"$",
"answers",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'\\\\seikai'",
";",
"}",
"}",
"if",
"(",
"$",
"specifics",
"->",
"has",
"(",
"'no-random'",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"'\\\\norandom'",
";",
"}",
"}",
"else",
"{",
"$",
"line",
"[",
"]",
"=",
"0",
";",
"$",
"answers",
"=",
"$",
"this",
"->",
"getAnswers",
"(",
"$",
"word",
",",
"[",
"$",
"this",
",",
"'convertToShiftJISableInAnswerWithKatakana'",
"]",
")",
";",
"if",
"(",
"!",
"$",
"answers",
")",
"{",
"$",
"this",
"->",
"logUnserializableError",
"(",
"'Inteligenceω クイズ', $word",
")",
"",
"",
"",
"",
"return",
"''",
";",
"}",
"$",
"bonuses",
"=",
"$",
"specifics",
"->",
"getAll",
"(",
"'bonus'",
")",
";",
"foreach",
"(",
"$",
"answers",
"as",
"$",
"i",
"=>",
"$",
"answer",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"$",
"answer",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"bonuses",
"[",
"$",
"i",
"]",
")",
")",
"{",
"$",
"line",
"[",
"]",
"=",
"\"\\\\bonus=$bonuses[$i]\"",
";",
"}",
"}",
"}",
"$",
"explain",
"[",
"]",
"=",
"$",
"word",
"[",
"'text'",
"]",
"[",
"0",
"]",
";",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'description'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"explain",
"[",
"]",
"=",
"$",
"word",
"[",
"'description'",
"]",
"[",
"0",
"]",
"[",
"'lml'",
"]",
";",
"}",
"$",
"line",
"[",
"]",
"=",
"'\\\\explain='",
".",
"$",
"this",
"->",
"serializeQuizField",
"(",
"implode",
"(",
"\"\\n\\n\"",
",",
"$",
"explain",
")",
")",
";",
"return",
"implode",
"(",
"','",
",",
"$",
"line",
")",
".",
"\"\\r\\n\"",
";",
"}"
] |
一つのお題を表す配列から解答行に直列化します。
@param (string|string[]|float)[][] $word
@return string 末尾に改行 (CRLF) を含みます。
|
[
"一つのお題を表す配列から解答行に直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L213-L266
|
esperecyan/dictionary-php
|
src/serializer/InteligenceoSerializer.php
|
InteligenceoSerializer.serializeWordAsQuiz
|
protected function serializeWordAsQuiz(array $word, string $directoryName, array $filenames): string
{
if (isset($word['question'][0])
|| isset($word['image'][0]) || isset($word['audio'][0]) || isset($word['option'][0])) {
$answerLine = $this->serializeAnswerLine($word);
if ($answerLine !== '') {
$output = $this->serializeQuestionLine($word, $directoryName, $filenames) . $answerLine;
}
}
return $output ?? '';
}
|
php
|
protected function serializeWordAsQuiz(array $word, string $directoryName, array $filenames): string
{
if (isset($word['question'][0])
|| isset($word['image'][0]) || isset($word['audio'][0]) || isset($word['option'][0])) {
$answerLine = $this->serializeAnswerLine($word);
if ($answerLine !== '') {
$output = $this->serializeQuestionLine($word, $directoryName, $filenames) . $answerLine;
}
}
return $output ?? '';
}
|
[
"protected",
"function",
"serializeWordAsQuiz",
"(",
"array",
"$",
"word",
",",
"string",
"$",
"directoryName",
",",
"array",
"$",
"filenames",
")",
":",
"string",
"{",
"if",
"(",
"isset",
"(",
"$",
"word",
"[",
"'question'",
"]",
"[",
"0",
"]",
")",
"||",
"isset",
"(",
"$",
"word",
"[",
"'image'",
"]",
"[",
"0",
"]",
")",
"||",
"isset",
"(",
"$",
"word",
"[",
"'audio'",
"]",
"[",
"0",
"]",
")",
"||",
"isset",
"(",
"$",
"word",
"[",
"'option'",
"]",
"[",
"0",
"]",
")",
")",
"{",
"$",
"answerLine",
"=",
"$",
"this",
"->",
"serializeAnswerLine",
"(",
"$",
"word",
")",
";",
"if",
"(",
"$",
"answerLine",
"!==",
"''",
")",
"{",
"$",
"output",
"=",
"$",
"this",
"->",
"serializeQuestionLine",
"(",
"$",
"word",
",",
"$",
"directoryName",
",",
"$",
"filenames",
")",
".",
"$",
"answerLine",
";",
"}",
"}",
"return",
"$",
"output",
"??",
"''",
";",
"}"
] |
一つのお題を表す配列をクイズ形式で直列化します。
@param (string|string[]|float)[][] $word
@param string $directoryName
@param string[] $filenames
@return string 末尾に改行 (CRLF) を含みます。直列化できないお題だった場合は空文字列を返します。
|
[
"一つのお題を表す配列をクイズ形式で直列化します。"
] |
train
|
https://github.com/esperecyan/dictionary-php/blob/14fad08fb43006995c763094e8e7ed0dc0e26676/src/serializer/InteligenceoSerializer.php#L275-L285
|
Nayjest/Tree
|
src/Utils.php
|
Utils.buildTree
|
public static function buildTree(array $config, array $plainItems, $flags = TreeBuilder::NORMALIZE_CONFIG)
{
return self::getDefaultTreeBuilder()->build($config, $plainItems, $flags);
}
|
php
|
public static function buildTree(array $config, array $plainItems, $flags = TreeBuilder::NORMALIZE_CONFIG)
{
return self::getDefaultTreeBuilder()->build($config, $plainItems, $flags);
}
|
[
"public",
"static",
"function",
"buildTree",
"(",
"array",
"$",
"config",
",",
"array",
"$",
"plainItems",
",",
"$",
"flags",
"=",
"TreeBuilder",
"::",
"NORMALIZE_CONFIG",
")",
"{",
"return",
"self",
"::",
"getDefaultTreeBuilder",
"(",
")",
"->",
"build",
"(",
"$",
"config",
",",
"$",
"plainItems",
",",
"$",
"flags",
")",
";",
"}"
] |
Builds tree from plain nodes based on configuration.
@param array $config multidimensional array that represents tree structure
@param NodeInterface[] $plainItems nodes that must be organized to tree
@param int $flags specifies tree building options, default: TreeBuilder::NORMALIZE_CONFIG; see TreeBuilder constants
@return NodeInterface[] items organized to tree structure; array keys are not preserved
|
[
"Builds",
"tree",
"from",
"plain",
"nodes",
"based",
"on",
"configuration",
"."
] |
train
|
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/Utils.php#L32-L35
|
Nayjest/Tree
|
src/Utils.php
|
Utils.applyCallback
|
public static function applyCallback(callable $callback, NodeInterface $root, $targetClass = ChildNodeInterface::class)
{
$processed = [];
$f = function (ChildNodeInterface $targetNode) use ($callback, $targetClass, &$f, &$processed) {
if (in_array($targetNode, $processed, true)) {
return;
}
$nodes = $targetNode instanceof ParentNodeInterface
? $targetNode->getChildrenRecursive()->toArray()
: [];
$nodes[] = $targetNode;
/** @var NodeInterface $node */
foreach ($nodes as $node) {
$node instanceof $targetClass && call_user_func($callback, $node);
$node instanceof ParentNodeInterface && $node->children()->onItemAdd($f);
$processed[] = $node;
}
};
$f($root);
}
|
php
|
public static function applyCallback(callable $callback, NodeInterface $root, $targetClass = ChildNodeInterface::class)
{
$processed = [];
$f = function (ChildNodeInterface $targetNode) use ($callback, $targetClass, &$f, &$processed) {
if (in_array($targetNode, $processed, true)) {
return;
}
$nodes = $targetNode instanceof ParentNodeInterface
? $targetNode->getChildrenRecursive()->toArray()
: [];
$nodes[] = $targetNode;
/** @var NodeInterface $node */
foreach ($nodes as $node) {
$node instanceof $targetClass && call_user_func($callback, $node);
$node instanceof ParentNodeInterface && $node->children()->onItemAdd($f);
$processed[] = $node;
}
};
$f($root);
}
|
[
"public",
"static",
"function",
"applyCallback",
"(",
"callable",
"$",
"callback",
",",
"NodeInterface",
"$",
"root",
",",
"$",
"targetClass",
"=",
"ChildNodeInterface",
"::",
"class",
")",
"{",
"$",
"processed",
"=",
"[",
"]",
";",
"$",
"f",
"=",
"function",
"(",
"ChildNodeInterface",
"$",
"targetNode",
")",
"use",
"(",
"$",
"callback",
",",
"$",
"targetClass",
",",
"&",
"$",
"f",
",",
"&",
"$",
"processed",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"targetNode",
",",
"$",
"processed",
",",
"true",
")",
")",
"{",
"return",
";",
"}",
"$",
"nodes",
"=",
"$",
"targetNode",
"instanceof",
"ParentNodeInterface",
"?",
"$",
"targetNode",
"->",
"getChildrenRecursive",
"(",
")",
"->",
"toArray",
"(",
")",
":",
"[",
"]",
";",
"$",
"nodes",
"[",
"]",
"=",
"$",
"targetNode",
";",
"/** @var NodeInterface $node */",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"node",
"instanceof",
"$",
"targetClass",
"&&",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"node",
")",
";",
"$",
"node",
"instanceof",
"ParentNodeInterface",
"&&",
"$",
"node",
"->",
"children",
"(",
")",
"->",
"onItemAdd",
"(",
"$",
"f",
")",
";",
"$",
"processed",
"[",
"]",
"=",
"$",
"node",
";",
"}",
"}",
";",
"$",
"f",
"(",
"$",
"root",
")",
";",
"}"
] |
Applies callback to root node, if it's existing and further descendant nodes directly after adding to tree.
@param callable $callback function to apply
@param NodeInterface $root root node
@param string $targetClass callback will be applied only to nodes that are instances of $targetClass or inherited classes
|
[
"Applies",
"callback",
"to",
"root",
"node",
"if",
"it",
"s",
"existing",
"and",
"further",
"descendant",
"nodes",
"directly",
"after",
"adding",
"to",
"tree",
"."
] |
train
|
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/Utils.php#L44-L64
|
shawnsandy/ui-pages
|
src/Controllers/MarkdownController.php
|
MarkdownController.show
|
public function show($posts, Request $request)
{
$file = $posts;
$markdown = $this->pagekit->markdown($file);
$view = "page::missing-page";
if ($request->has('page')) :
$markdown = $this->pagekit->markdown($request->page, $posts);
endif;
if (!empty($markdown)) :
$view = 'page::markdown.show';
endif;
return view($view, compact('markdown'));
}
|
php
|
public function show($posts, Request $request)
{
$file = $posts;
$markdown = $this->pagekit->markdown($file);
$view = "page::missing-page";
if ($request->has('page')) :
$markdown = $this->pagekit->markdown($request->page, $posts);
endif;
if (!empty($markdown)) :
$view = 'page::markdown.show';
endif;
return view($view, compact('markdown'));
}
|
[
"public",
"function",
"show",
"(",
"$",
"posts",
",",
"Request",
"$",
"request",
")",
"{",
"$",
"file",
"=",
"$",
"posts",
";",
"$",
"markdown",
"=",
"$",
"this",
"->",
"pagekit",
"->",
"markdown",
"(",
"$",
"file",
")",
";",
"$",
"view",
"=",
"\"page::missing-page\"",
";",
"if",
"(",
"$",
"request",
"->",
"has",
"(",
"'page'",
")",
")",
":",
"$",
"markdown",
"=",
"$",
"this",
"->",
"pagekit",
"->",
"markdown",
"(",
"$",
"request",
"->",
"page",
",",
"$",
"posts",
")",
";",
"endif",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"markdown",
")",
")",
":",
"$",
"view",
"=",
"'page::markdown.show'",
";",
"endif",
";",
"return",
"view",
"(",
"$",
"view",
",",
"compact",
"(",
"'markdown'",
")",
")",
";",
"}"
] |
Show a specific page params
@param $posts
@param Request $request
@return string
|
[
"Show",
"a",
"specific",
"page",
"params"
] |
train
|
https://github.com/shawnsandy/ui-pages/blob/11584c12fa3e2b9a5c513f4ec9e2eaf78c206ca8/src/Controllers/MarkdownController.php#L51-L69
|
gregorybesson/PlaygroundCore
|
src/Service/Cron.php
|
Cron.getCronjobs
|
public function getCronjobs()
{
if (!$this->cronjobs) {
$cronjobs = array();
$results = $this->serviceLocator
->get('Application')
->getEventManager()
->trigger(__FUNCTION__, $this, array(
'cronjobs' => $cronjobs
));
if ($results) {
foreach ($results as $key => $cron) {
foreach ($cron as $id => $conf) {
$cronjobs[$id] = $conf;
}
}
}
$this->setCronjobs($cronjobs);
}
return $this->cronjobs;
}
|
php
|
public function getCronjobs()
{
if (!$this->cronjobs) {
$cronjobs = array();
$results = $this->serviceLocator
->get('Application')
->getEventManager()
->trigger(__FUNCTION__, $this, array(
'cronjobs' => $cronjobs
));
if ($results) {
foreach ($results as $key => $cron) {
foreach ($cron as $id => $conf) {
$cronjobs[$id] = $conf;
}
}
}
$this->setCronjobs($cronjobs);
}
return $this->cronjobs;
}
|
[
"public",
"function",
"getCronjobs",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"cronjobs",
")",
"{",
"$",
"cronjobs",
"=",
"array",
"(",
")",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"serviceLocator",
"->",
"get",
"(",
"'Application'",
")",
"->",
"getEventManager",
"(",
")",
"->",
"trigger",
"(",
"__FUNCTION__",
",",
"$",
"this",
",",
"array",
"(",
"'cronjobs'",
"=>",
"$",
"cronjobs",
")",
")",
";",
"if",
"(",
"$",
"results",
")",
"{",
"foreach",
"(",
"$",
"results",
"as",
"$",
"key",
"=>",
"$",
"cron",
")",
"{",
"foreach",
"(",
"$",
"cron",
"as",
"$",
"id",
"=>",
"$",
"conf",
")",
"{",
"$",
"cronjobs",
"[",
"$",
"id",
"]",
"=",
"$",
"conf",
";",
"}",
"}",
"}",
"$",
"this",
"->",
"setCronjobs",
"(",
"$",
"cronjobs",
")",
";",
"}",
"return",
"$",
"this",
"->",
"cronjobs",
";",
"}"
] |
trigger an event and fetch crons
Return array
|
[
"trigger",
"an",
"event",
"and",
"fetch",
"crons",
"Return",
"array"
] |
train
|
https://github.com/gregorybesson/PlaygroundCore/blob/f8dfa4c7660b54354933b3c28c0cf35304a649df/src/Service/Cron.php#L117-L141
|
gregorybesson/PlaygroundCore
|
src/Service/Cron.php
|
Cron.schedule
|
public function schedule()
{
$em = $this->getEm();
$pending = $this->getPending();
$exists = array();
foreach ($pending as $job) {
$identifier = $job->getCode();
$identifier .= $job->getScheduleTime()->getTimeStamp();
$exists[$identifier] = true;
}
$scheduleAhead = $this->getScheduleAhead() * 60;
$cronRegistry = $this->getCronjobs();
foreach ($cronRegistry as $code => $item) {
$now = time();
$timeAhead = $now + $scheduleAhead;
for ($time = $now; $time < $timeAhead; $time += 60) {
$scheduleTime = new \DateTime();
$scheduleTime->setTimestamp($time);
$scheduleTime->setTime(
$scheduleTime->format('H'),
$scheduleTime->format('i')
);
$scheduleTimestamp = $scheduleTime->getTimestamp();
$identifier = $code . $scheduleTimestamp;
if (isset($exists[$identifier])) {
//already scheduled
continue;
}
$job = new Entity\Cronjob;
if ($this->matchTime(
$scheduleTimestamp,
$item['frequency']
)) {
$job
->setCode($code)
->setStatus(Mapper\Cronjob::STATUS_PENDING)
->setCreateTime(new \DateTime)
->setScheduleTime($scheduleTime);
$em->persist($job);
$exists[$identifier] = true;
}
}
}
$em->flush();
return $this;
}
|
php
|
public function schedule()
{
$em = $this->getEm();
$pending = $this->getPending();
$exists = array();
foreach ($pending as $job) {
$identifier = $job->getCode();
$identifier .= $job->getScheduleTime()->getTimeStamp();
$exists[$identifier] = true;
}
$scheduleAhead = $this->getScheduleAhead() * 60;
$cronRegistry = $this->getCronjobs();
foreach ($cronRegistry as $code => $item) {
$now = time();
$timeAhead = $now + $scheduleAhead;
for ($time = $now; $time < $timeAhead; $time += 60) {
$scheduleTime = new \DateTime();
$scheduleTime->setTimestamp($time);
$scheduleTime->setTime(
$scheduleTime->format('H'),
$scheduleTime->format('i')
);
$scheduleTimestamp = $scheduleTime->getTimestamp();
$identifier = $code . $scheduleTimestamp;
if (isset($exists[$identifier])) {
//already scheduled
continue;
}
$job = new Entity\Cronjob;
if ($this->matchTime(
$scheduleTimestamp,
$item['frequency']
)) {
$job
->setCode($code)
->setStatus(Mapper\Cronjob::STATUS_PENDING)
->setCreateTime(new \DateTime)
->setScheduleTime($scheduleTime);
$em->persist($job);
$exists[$identifier] = true;
}
}
}
$em->flush();
return $this;
}
|
[
"public",
"function",
"schedule",
"(",
")",
"{",
"$",
"em",
"=",
"$",
"this",
"->",
"getEm",
"(",
")",
";",
"$",
"pending",
"=",
"$",
"this",
"->",
"getPending",
"(",
")",
";",
"$",
"exists",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"pending",
"as",
"$",
"job",
")",
"{",
"$",
"identifier",
"=",
"$",
"job",
"->",
"getCode",
"(",
")",
";",
"$",
"identifier",
".=",
"$",
"job",
"->",
"getScheduleTime",
"(",
")",
"->",
"getTimeStamp",
"(",
")",
";",
"$",
"exists",
"[",
"$",
"identifier",
"]",
"=",
"true",
";",
"}",
"$",
"scheduleAhead",
"=",
"$",
"this",
"->",
"getScheduleAhead",
"(",
")",
"*",
"60",
";",
"$",
"cronRegistry",
"=",
"$",
"this",
"->",
"getCronjobs",
"(",
")",
";",
"foreach",
"(",
"$",
"cronRegistry",
"as",
"$",
"code",
"=>",
"$",
"item",
")",
"{",
"$",
"now",
"=",
"time",
"(",
")",
";",
"$",
"timeAhead",
"=",
"$",
"now",
"+",
"$",
"scheduleAhead",
";",
"for",
"(",
"$",
"time",
"=",
"$",
"now",
";",
"$",
"time",
"<",
"$",
"timeAhead",
";",
"$",
"time",
"+=",
"60",
")",
"{",
"$",
"scheduleTime",
"=",
"new",
"\\",
"DateTime",
"(",
")",
";",
"$",
"scheduleTime",
"->",
"setTimestamp",
"(",
"$",
"time",
")",
";",
"$",
"scheduleTime",
"->",
"setTime",
"(",
"$",
"scheduleTime",
"->",
"format",
"(",
"'H'",
")",
",",
"$",
"scheduleTime",
"->",
"format",
"(",
"'i'",
")",
")",
";",
"$",
"scheduleTimestamp",
"=",
"$",
"scheduleTime",
"->",
"getTimestamp",
"(",
")",
";",
"$",
"identifier",
"=",
"$",
"code",
".",
"$",
"scheduleTimestamp",
";",
"if",
"(",
"isset",
"(",
"$",
"exists",
"[",
"$",
"identifier",
"]",
")",
")",
"{",
"//already scheduled",
"continue",
";",
"}",
"$",
"job",
"=",
"new",
"Entity",
"\\",
"Cronjob",
";",
"if",
"(",
"$",
"this",
"->",
"matchTime",
"(",
"$",
"scheduleTimestamp",
",",
"$",
"item",
"[",
"'frequency'",
"]",
")",
")",
"{",
"$",
"job",
"->",
"setCode",
"(",
"$",
"code",
")",
"->",
"setStatus",
"(",
"Mapper",
"\\",
"Cronjob",
"::",
"STATUS_PENDING",
")",
"->",
"setCreateTime",
"(",
"new",
"\\",
"DateTime",
")",
"->",
"setScheduleTime",
"(",
"$",
"scheduleTime",
")",
";",
"$",
"em",
"->",
"persist",
"(",
"$",
"job",
")",
";",
"$",
"exists",
"[",
"$",
"identifier",
"]",
"=",
"true",
";",
"}",
"}",
"}",
"$",
"em",
"->",
"flush",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
schedule cron jobs
@return self
|
[
"schedule",
"cron",
"jobs"
] |
train
|
https://github.com/gregorybesson/PlaygroundCore/blob/f8dfa4c7660b54354933b3c28c0cf35304a649df/src/Service/Cron.php#L251-L304
|
gregorybesson/PlaygroundCore
|
src/Service/Cron.php
|
Cron.register
|
public static function register(
$code,
$frequency,
$callback,
array $args = array()
) {
Registry::register($code, $frequency, $callback, $args);
}
|
php
|
public static function register(
$code,
$frequency,
$callback,
array $args = array()
) {
Registry::register($code, $frequency, $callback, $args);
}
|
[
"public",
"static",
"function",
"register",
"(",
"$",
"code",
",",
"$",
"frequency",
",",
"$",
"callback",
",",
"array",
"$",
"args",
"=",
"array",
"(",
")",
")",
"{",
"Registry",
"::",
"register",
"(",
"$",
"code",
",",
"$",
"frequency",
",",
"$",
"callback",
",",
"$",
"args",
")",
";",
"}"
] |
wrapper function
@see Registry::register()
|
[
"wrapper",
"function"
] |
train
|
https://github.com/gregorybesson/PlaygroundCore/blob/f8dfa4c7660b54354933b3c28c0cf35304a649df/src/Service/Cron.php#L382-L389
|
nkt/flame
|
src/QueryBuilder/Part/JoinPart.php
|
JoinPart.join
|
public function join($table, $on, $joinField = null, $type = 'INNER')
{
$grammar = $this->getGrammar();
$join = $type . ' JOIN ' . $grammar->buildId($table) . ' ON ';
if ($joinField !== null) {
$join .= $grammar->buildId($on) . ' = ' . $grammar->buildId($joinField);
} elseif ($on instanceof \Closure) {
$expr = new Expression($this->getGrammar());
call_user_func($on, $expr);
$join .= $expr;
} else {
$join .= $on;
}
$this->joins[] = $join;
return $this;
}
|
php
|
public function join($table, $on, $joinField = null, $type = 'INNER')
{
$grammar = $this->getGrammar();
$join = $type . ' JOIN ' . $grammar->buildId($table) . ' ON ';
if ($joinField !== null) {
$join .= $grammar->buildId($on) . ' = ' . $grammar->buildId($joinField);
} elseif ($on instanceof \Closure) {
$expr = new Expression($this->getGrammar());
call_user_func($on, $expr);
$join .= $expr;
} else {
$join .= $on;
}
$this->joins[] = $join;
return $this;
}
|
[
"public",
"function",
"join",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
"=",
"null",
",",
"$",
"type",
"=",
"'INNER'",
")",
"{",
"$",
"grammar",
"=",
"$",
"this",
"->",
"getGrammar",
"(",
")",
";",
"$",
"join",
"=",
"$",
"type",
".",
"' JOIN '",
".",
"$",
"grammar",
"->",
"buildId",
"(",
"$",
"table",
")",
".",
"' ON '",
";",
"if",
"(",
"$",
"joinField",
"!==",
"null",
")",
"{",
"$",
"join",
".=",
"$",
"grammar",
"->",
"buildId",
"(",
"$",
"on",
")",
".",
"' = '",
".",
"$",
"grammar",
"->",
"buildId",
"(",
"$",
"joinField",
")",
";",
"}",
"elseif",
"(",
"$",
"on",
"instanceof",
"\\",
"Closure",
")",
"{",
"$",
"expr",
"=",
"new",
"Expression",
"(",
"$",
"this",
"->",
"getGrammar",
"(",
")",
")",
";",
"call_user_func",
"(",
"$",
"on",
",",
"$",
"expr",
")",
";",
"$",
"join",
".=",
"$",
"expr",
";",
"}",
"else",
"{",
"$",
"join",
".=",
"$",
"on",
";",
"}",
"$",
"this",
"->",
"joins",
"[",
"]",
"=",
"$",
"join",
";",
"return",
"$",
"this",
";",
"}"
] |
@param string $table
@param Expression|callable|string $on
@param string|null $joinField
@param string $type
@return static
|
[
"@param",
"string",
"$table",
"@param",
"Expression|callable|string",
"$on",
"@param",
"string|null",
"$joinField",
"@param",
"string",
"$type"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/Part/JoinPart.php#L26-L42
|
nkt/flame
|
src/QueryBuilder/Part/JoinPart.php
|
JoinPart.leftJoin
|
public function leftJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'LEFT');
}
|
php
|
public function leftJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'LEFT');
}
|
[
"public",
"function",
"leftJoin",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"join",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
",",
"'LEFT'",
")",
";",
"}"
] |
@param string $table
@param Expression|callable|string $on
@param string|null $joinField
@return static
|
[
"@param",
"string",
"$table",
"@param",
"Expression|callable|string",
"$on",
"@param",
"string|null",
"$joinField"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/Part/JoinPart.php#L51-L54
|
nkt/flame
|
src/QueryBuilder/Part/JoinPart.php
|
JoinPart.rightJoin
|
public function rightJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'RIGHT');
}
|
php
|
public function rightJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'RIGHT');
}
|
[
"public",
"function",
"rightJoin",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"join",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
",",
"'RIGHT'",
")",
";",
"}"
] |
@param string $table
@param Expression|callable|string $on
@param string|null $joinField
@return static
|
[
"@param",
"string",
"$table",
"@param",
"Expression|callable|string",
"$on",
"@param",
"string|null",
"$joinField"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/Part/JoinPart.php#L63-L66
|
nkt/flame
|
src/QueryBuilder/Part/JoinPart.php
|
JoinPart.fullJoin
|
public function fullJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'FULL');
}
|
php
|
public function fullJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'FULL');
}
|
[
"public",
"function",
"fullJoin",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"join",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
",",
"'FULL'",
")",
";",
"}"
] |
@param string $table
@param Expression|callable|string $on
@param string|null $joinField
@return static
|
[
"@param",
"string",
"$table",
"@param",
"Expression|callable|string",
"$on",
"@param",
"string|null",
"$joinField"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/Part/JoinPart.php#L75-L78
|
nkt/flame
|
src/QueryBuilder/Part/JoinPart.php
|
JoinPart.crossJoin
|
public function crossJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'CROSS');
}
|
php
|
public function crossJoin($table, $on, $joinField = null)
{
return $this->join($table, $on, $joinField, 'CROSS');
}
|
[
"public",
"function",
"crossJoin",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
"=",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"join",
"(",
"$",
"table",
",",
"$",
"on",
",",
"$",
"joinField",
",",
"'CROSS'",
")",
";",
"}"
] |
@param string $table
@param Expression|callable|string $on
@param string|null $joinField
@return static
|
[
"@param",
"string",
"$table",
"@param",
"Expression|callable|string",
"$on",
"@param",
"string|null",
"$joinField"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/QueryBuilder/Part/JoinPart.php#L87-L90
|
zhaoyang1214/phalcon-framwork-plugins
|
src/DbProfiler.php
|
DbProfiler.beforeQuery
|
public function beforeQuery(Event $event, $connection)
{
$this->profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes());
}
|
php
|
public function beforeQuery(Event $event, $connection)
{
$this->profiler->startProfile($connection->getSQLStatement(), $connection->getSqlVariables(), $connection->getSQLBindTypes());
}
|
[
"public",
"function",
"beforeQuery",
"(",
"Event",
"$",
"event",
",",
"$",
"connection",
")",
"{",
"$",
"this",
"->",
"profiler",
"->",
"startProfile",
"(",
"$",
"connection",
"->",
"getSQLStatement",
"(",
")",
",",
"$",
"connection",
"->",
"getSqlVariables",
"(",
")",
",",
"$",
"connection",
"->",
"getSQLBindTypes",
"(",
")",
")",
";",
"}"
] |
执行sql语句前执行
@param Event $event
事件
@param $connection 数据库连接
|
[
"执行sql语句前执行"
] |
train
|
https://github.com/zhaoyang1214/phalcon-framwork-plugins/blob/fe2e25e6d01fb7315e37ee32fdeaed6c88c382c1/src/DbProfiler.php#L20-L23
|
zhaoyang1214/phalcon-framwork-plugins
|
src/DbProfiler.php
|
DbProfiler.afterQuery
|
public function afterQuery(Event $event, $connection)
{
$profiler = $this->profiler;
$profiler->stopProfile();
$profile = $profiler->getLastProfile();
$sql = $profile->getSQLStatement();
$params = $profile->getSqlVariables();
$params = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$executeTime = $profile->getTotalElapsedSeconds();
$profiler->reset();
$this->di->getLogger()->info("[$sql] [$params] [$executeTime]");
}
|
php
|
public function afterQuery(Event $event, $connection)
{
$profiler = $this->profiler;
$profiler->stopProfile();
$profile = $profiler->getLastProfile();
$sql = $profile->getSQLStatement();
$params = $profile->getSqlVariables();
$params = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$executeTime = $profile->getTotalElapsedSeconds();
$profiler->reset();
$this->di->getLogger()->info("[$sql] [$params] [$executeTime]");
}
|
[
"public",
"function",
"afterQuery",
"(",
"Event",
"$",
"event",
",",
"$",
"connection",
")",
"{",
"$",
"profiler",
"=",
"$",
"this",
"->",
"profiler",
";",
"$",
"profiler",
"->",
"stopProfile",
"(",
")",
";",
"$",
"profile",
"=",
"$",
"profiler",
"->",
"getLastProfile",
"(",
")",
";",
"$",
"sql",
"=",
"$",
"profile",
"->",
"getSQLStatement",
"(",
")",
";",
"$",
"params",
"=",
"$",
"profile",
"->",
"getSqlVariables",
"(",
")",
";",
"$",
"params",
"=",
"json_encode",
"(",
"$",
"params",
",",
"JSON_UNESCAPED_UNICODE",
"|",
"JSON_UNESCAPED_SLASHES",
")",
";",
"$",
"executeTime",
"=",
"$",
"profile",
"->",
"getTotalElapsedSeconds",
"(",
")",
";",
"$",
"profiler",
"->",
"reset",
"(",
")",
";",
"$",
"this",
"->",
"di",
"->",
"getLogger",
"(",
")",
"->",
"info",
"(",
"\"[$sql] [$params] [$executeTime]\"",
")",
";",
"}"
] |
执行sql语句前执行
@param Event $event
事件
@param $connection 数据库连接
|
[
"执行sql语句前执行"
] |
train
|
https://github.com/zhaoyang1214/phalcon-framwork-plugins/blob/fe2e25e6d01fb7315e37ee32fdeaed6c88c382c1/src/DbProfiler.php#L32-L43
|
dengyongbin/loopeer-lib
|
src/Services/pingpp_sdk/Pingpp/ApiRequestor.php
|
Pingpp_ApiRequestor.handleApiError
|
public function handleApiError($rbody, $rcode, $resp)
{
if (!is_object($resp) || !isset($resp->error)) {
$msg = "Invalid response object from API: $rbody "
."(HTTP response code was $rcode)";
throw new Pingpp_ApiError($msg, $rcode, $rbody, $resp);
}
$error = $resp->error;
$msg = isset($error->message) ? $error->message : null;
$param = isset($error->param) ? $error->param : null;
$code = isset($error->code) ? $error->code : null;
switch ($rcode) {
case 400:
if ($code == 'rate_limit') {
throw new Pingpp_RateLimitError(
$msg, $param, $rcode, $rbody, $resp
);
}
case 404:
throw new Pingpp_InvalidRequestError(
$msg, $param, $rcode, $rbody, $resp
);
case 401:
throw new Pingpp_AuthenticationError($msg, $rcode, $rbody, $resp);
default:
throw new Pingpp_ApiError($msg, $rcode, $rbody, $resp);
}
}
|
php
|
public function handleApiError($rbody, $rcode, $resp)
{
if (!is_object($resp) || !isset($resp->error)) {
$msg = "Invalid response object from API: $rbody "
."(HTTP response code was $rcode)";
throw new Pingpp_ApiError($msg, $rcode, $rbody, $resp);
}
$error = $resp->error;
$msg = isset($error->message) ? $error->message : null;
$param = isset($error->param) ? $error->param : null;
$code = isset($error->code) ? $error->code : null;
switch ($rcode) {
case 400:
if ($code == 'rate_limit') {
throw new Pingpp_RateLimitError(
$msg, $param, $rcode, $rbody, $resp
);
}
case 404:
throw new Pingpp_InvalidRequestError(
$msg, $param, $rcode, $rbody, $resp
);
case 401:
throw new Pingpp_AuthenticationError($msg, $rcode, $rbody, $resp);
default:
throw new Pingpp_ApiError($msg, $rcode, $rbody, $resp);
}
}
|
[
"public",
"function",
"handleApiError",
"(",
"$",
"rbody",
",",
"$",
"rcode",
",",
"$",
"resp",
")",
"{",
"if",
"(",
"!",
"is_object",
"(",
"$",
"resp",
")",
"||",
"!",
"isset",
"(",
"$",
"resp",
"->",
"error",
")",
")",
"{",
"$",
"msg",
"=",
"\"Invalid response object from API: $rbody \"",
".",
"\"(HTTP response code was $rcode)\"",
";",
"throw",
"new",
"Pingpp_ApiError",
"(",
"$",
"msg",
",",
"$",
"rcode",
",",
"$",
"rbody",
",",
"$",
"resp",
")",
";",
"}",
"$",
"error",
"=",
"$",
"resp",
"->",
"error",
";",
"$",
"msg",
"=",
"isset",
"(",
"$",
"error",
"->",
"message",
")",
"?",
"$",
"error",
"->",
"message",
":",
"null",
";",
"$",
"param",
"=",
"isset",
"(",
"$",
"error",
"->",
"param",
")",
"?",
"$",
"error",
"->",
"param",
":",
"null",
";",
"$",
"code",
"=",
"isset",
"(",
"$",
"error",
"->",
"code",
")",
"?",
"$",
"error",
"->",
"code",
":",
"null",
";",
"switch",
"(",
"$",
"rcode",
")",
"{",
"case",
"400",
":",
"if",
"(",
"$",
"code",
"==",
"'rate_limit'",
")",
"{",
"throw",
"new",
"Pingpp_RateLimitError",
"(",
"$",
"msg",
",",
"$",
"param",
",",
"$",
"rcode",
",",
"$",
"rbody",
",",
"$",
"resp",
")",
";",
"}",
"case",
"404",
":",
"throw",
"new",
"Pingpp_InvalidRequestError",
"(",
"$",
"msg",
",",
"$",
"param",
",",
"$",
"rcode",
",",
"$",
"rbody",
",",
"$",
"resp",
")",
";",
"case",
"401",
":",
"throw",
"new",
"Pingpp_AuthenticationError",
"(",
"$",
"msg",
",",
"$",
"rcode",
",",
"$",
"rbody",
",",
"$",
"resp",
")",
";",
"default",
":",
"throw",
"new",
"Pingpp_ApiError",
"(",
"$",
"msg",
",",
"$",
"rcode",
",",
"$",
"rbody",
",",
"$",
"resp",
")",
";",
"}",
"}"
] |
@param string $rbody A JSON string.
@param int $rcode
@param array $resp
@throws Pingpp_InvalidRequestError if the error is caused by the user.
@throws Pingpp_AuthenticationError if the error is caused by a lack of
permissions.
@throws Pingpp_ApiError otherwise.
|
[
"@param",
"string",
"$rbody",
"A",
"JSON",
"string",
".",
"@param",
"int",
"$rcode",
"@param",
"array",
"$resp"
] |
train
|
https://github.com/dengyongbin/loopeer-lib/blob/4609338f6a48666ca96ee380509a5b5cb066808f/src/Services/pingpp_sdk/Pingpp/ApiRequestor.php#L129-L158
|
Nayjest/Tree
|
src/Utils/TreeBuilder.php
|
TreeBuilder.build
|
public function build(array $config, array $plainItems, $flags = self::NORMALIZE_CONFIG)
{
$flags = $flags | $this->defaultFlags;
// preprocess config if needed
if ($flags & self::NORMALIZE_CONFIG) {
$config = $this->normalizeConfig($config);
}
$currentLevelItems = [];
foreach ($config as $key => $itemConfig) {
// check that item specified in $config exists.
if (!array_key_exists($key, $plainItems)) {
if ($flags & self::ALLOW_ABSENT_ITEMS) {
continue;
}
throw new NodeNotFoundException(
'Error building tree: '
."Can't find item by '$key' key that's used in tree configuration."
);
}
/* @var NodeInterface $item */
$currentLevelItems[] = $item = $plainItems[$key];
// attach children
$itemChildren = $this->build(
$itemConfig,
$plainItems,
// config must be already normalized, so remove self::NORMALIZE_CONFIG flag on recursive call
$flags ^ self::NORMALIZE_CONFIG
);
if (count($itemChildren) === 0) {
continue;
}
if (!$item->isWritable()) {
throw new ReadonlyNodeModifyException(
'Error building tree: '
."Can't attach children to '$key' node that is'nt writable."
);
}
$method = $flags & self::RESET_CHILDREN ? 'setChildren' : 'addChildren';
$item->{$method}($itemChildren);
}
return $currentLevelItems;
}
|
php
|
public function build(array $config, array $plainItems, $flags = self::NORMALIZE_CONFIG)
{
$flags = $flags | $this->defaultFlags;
// preprocess config if needed
if ($flags & self::NORMALIZE_CONFIG) {
$config = $this->normalizeConfig($config);
}
$currentLevelItems = [];
foreach ($config as $key => $itemConfig) {
// check that item specified in $config exists.
if (!array_key_exists($key, $plainItems)) {
if ($flags & self::ALLOW_ABSENT_ITEMS) {
continue;
}
throw new NodeNotFoundException(
'Error building tree: '
."Can't find item by '$key' key that's used in tree configuration."
);
}
/* @var NodeInterface $item */
$currentLevelItems[] = $item = $plainItems[$key];
// attach children
$itemChildren = $this->build(
$itemConfig,
$plainItems,
// config must be already normalized, so remove self::NORMALIZE_CONFIG flag on recursive call
$flags ^ self::NORMALIZE_CONFIG
);
if (count($itemChildren) === 0) {
continue;
}
if (!$item->isWritable()) {
throw new ReadonlyNodeModifyException(
'Error building tree: '
."Can't attach children to '$key' node that is'nt writable."
);
}
$method = $flags & self::RESET_CHILDREN ? 'setChildren' : 'addChildren';
$item->{$method}($itemChildren);
}
return $currentLevelItems;
}
|
[
"public",
"function",
"build",
"(",
"array",
"$",
"config",
",",
"array",
"$",
"plainItems",
",",
"$",
"flags",
"=",
"self",
"::",
"NORMALIZE_CONFIG",
")",
"{",
"$",
"flags",
"=",
"$",
"flags",
"|",
"$",
"this",
"->",
"defaultFlags",
";",
"// preprocess config if needed",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"NORMALIZE_CONFIG",
")",
"{",
"$",
"config",
"=",
"$",
"this",
"->",
"normalizeConfig",
"(",
"$",
"config",
")",
";",
"}",
"$",
"currentLevelItems",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"config",
"as",
"$",
"key",
"=>",
"$",
"itemConfig",
")",
"{",
"// check that item specified in $config exists.",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"key",
",",
"$",
"plainItems",
")",
")",
"{",
"if",
"(",
"$",
"flags",
"&",
"self",
"::",
"ALLOW_ABSENT_ITEMS",
")",
"{",
"continue",
";",
"}",
"throw",
"new",
"NodeNotFoundException",
"(",
"'Error building tree: '",
".",
"\"Can't find item by '$key' key that's used in tree configuration.\"",
")",
";",
"}",
"/* @var NodeInterface $item */",
"$",
"currentLevelItems",
"[",
"]",
"=",
"$",
"item",
"=",
"$",
"plainItems",
"[",
"$",
"key",
"]",
";",
"// attach children",
"$",
"itemChildren",
"=",
"$",
"this",
"->",
"build",
"(",
"$",
"itemConfig",
",",
"$",
"plainItems",
",",
"// config must be already normalized, so remove self::NORMALIZE_CONFIG flag on recursive call",
"$",
"flags",
"^",
"self",
"::",
"NORMALIZE_CONFIG",
")",
";",
"if",
"(",
"count",
"(",
"$",
"itemChildren",
")",
"===",
"0",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"$",
"item",
"->",
"isWritable",
"(",
")",
")",
"{",
"throw",
"new",
"ReadonlyNodeModifyException",
"(",
"'Error building tree: '",
".",
"\"Can't attach children to '$key' node that is'nt writable.\"",
")",
";",
"}",
"$",
"method",
"=",
"$",
"flags",
"&",
"self",
"::",
"RESET_CHILDREN",
"?",
"'setChildren'",
":",
"'addChildren'",
";",
"$",
"item",
"->",
"{",
"$",
"method",
"}",
"(",
"$",
"itemChildren",
")",
";",
"}",
"return",
"$",
"currentLevelItems",
";",
"}"
] |
Builds tree from plain nodes based on configuration.
@param array $config multidimensional array that represents tree structure
@param NodeInterface[] $plainItems nodes that must be organized to tree
@param int $flags specifies tree building options, default: TreeBuilder::NORMALIZE_CONFIG; see TreeBuilder constants
@return NodeInterface[] items organized to tree structure; array keys are not preserved
|
[
"Builds",
"tree",
"from",
"plain",
"nodes",
"based",
"on",
"configuration",
"."
] |
train
|
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/Utils/TreeBuilder.php#L42-L86
|
Nayjest/Tree
|
src/Utils/TreeBuilder.php
|
TreeBuilder.normalizeConfig
|
protected function normalizeConfig(array $config)
{
$final = [];
foreach ($config as $key => $value) {
if (is_array($value)) {
$final[$key] = $this->normalizeConfig($value);
} else {
$final[$value] = [];
}
}
return $final;
}
|
php
|
protected function normalizeConfig(array $config)
{
$final = [];
foreach ($config as $key => $value) {
if (is_array($value)) {
$final[$key] = $this->normalizeConfig($value);
} else {
$final[$value] = [];
}
}
return $final;
}
|
[
"protected",
"function",
"normalizeConfig",
"(",
"array",
"$",
"config",
")",
"{",
"$",
"final",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"config",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"final",
"[",
"$",
"key",
"]",
"=",
"$",
"this",
"->",
"normalizeConfig",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"final",
"[",
"$",
"value",
"]",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"$",
"final",
";",
"}"
] |
Transforms array in form [1,2 => [3]] to [1=>[], 2=>[3=>[]]].
@param array $config
@return array
|
[
"Transforms",
"array",
"in",
"form",
"[",
"1",
"2",
"=",
">",
"[",
"3",
"]]",
"to",
"[",
"1",
"=",
">",
"[]",
"2",
"=",
">",
"[",
"3",
"=",
">",
"[]",
"]]",
"."
] |
train
|
https://github.com/Nayjest/Tree/blob/e73da75f939e207b1c25065e9466c28300e7113c/src/Utils/TreeBuilder.php#L95-L107
|
fuelphp/display
|
src/Presenter.php
|
Presenter.setView
|
public function setView($view)
{
$this->view = $view;
// construct the view if needed
if ( ! $this->view instanceof View)
{
$this->view = $this->viewManager->forge($this->view);
}
}
|
php
|
public function setView($view)
{
$this->view = $view;
// construct the view if needed
if ( ! $this->view instanceof View)
{
$this->view = $this->viewManager->forge($this->view);
}
}
|
[
"public",
"function",
"setView",
"(",
"$",
"view",
")",
"{",
"$",
"this",
"->",
"view",
"=",
"$",
"view",
";",
"// construct the view if needed",
"if",
"(",
"!",
"$",
"this",
"->",
"view",
"instanceof",
"View",
")",
"{",
"$",
"this",
"->",
"view",
"=",
"$",
"this",
"->",
"viewManager",
"->",
"forge",
"(",
"$",
"this",
"->",
"view",
")",
";",
"}",
"}"
] |
Sets a new View (object)
@param string|View $view
|
[
"Sets",
"a",
"new",
"View",
"(",
"object",
")"
] |
train
|
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/Presenter.php#L84-L93
|
fuelphp/display
|
src/Presenter.php
|
Presenter.render
|
public function render(array $data = [])
{
// run the methods
$this->before();
if (method_exists($this, $this->method))
{
$this->{$this->method}();
}
$this->after();
// transfer the presenter data to the view
$this->view->merge($this);
// set autofilter on view
$this->view->autoFilter($this->autoFilter);
// render the view
return $this->view->render($data);
}
|
php
|
public function render(array $data = [])
{
// run the methods
$this->before();
if (method_exists($this, $this->method))
{
$this->{$this->method}();
}
$this->after();
// transfer the presenter data to the view
$this->view->merge($this);
// set autofilter on view
$this->view->autoFilter($this->autoFilter);
// render the view
return $this->view->render($data);
}
|
[
"public",
"function",
"render",
"(",
"array",
"$",
"data",
"=",
"[",
"]",
")",
"{",
"// run the methods",
"$",
"this",
"->",
"before",
"(",
")",
";",
"if",
"(",
"method_exists",
"(",
"$",
"this",
",",
"$",
"this",
"->",
"method",
")",
")",
"{",
"$",
"this",
"->",
"{",
"$",
"this",
"->",
"method",
"}",
"(",
")",
";",
"}",
"$",
"this",
"->",
"after",
"(",
")",
";",
"// transfer the presenter data to the view",
"$",
"this",
"->",
"view",
"->",
"merge",
"(",
"$",
"this",
")",
";",
"// set autofilter on view",
"$",
"this",
"->",
"view",
"->",
"autoFilter",
"(",
"$",
"this",
"->",
"autoFilter",
")",
";",
"// render the view",
"return",
"$",
"this",
"->",
"view",
"->",
"render",
"(",
"$",
"data",
")",
";",
"}"
] |
Renders the view
@param array $data additional view data
@return string
|
[
"Renders",
"the",
"view"
] |
train
|
https://github.com/fuelphp/display/blob/d9a3eddbf80f0fd81beb40d9f4507600ac6611a4/src/Presenter.php#L102-L122
|
blast-project/CoreBundle
|
src/Command/GenerateTranslationsCommand.php
|
GenerateTranslationsCommand.execute
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundle = $input->getArgument('bundle');
$fs = new Filesystem();
$finder = new Finder();
$crawler = new Crawler();
$path = $this->getContainer()->get('kernel')->locateResource('@' . $bundle);
$transPath = $path . 'Resources/translations/';
if (!$fs->exists($transPath)) {
try {
$fs->mkdir($transPath);
} catch (IOExceptionInterface $e) {
echo sprintf('An error occurred while creating your directory at %s', $e->getPath());
}
}
foreach ($finder->files()->in($transPath) as $file) {
$translations = [];
$crawler->addXmlContent(file_get_contents($file->getPathName()));
$crawler = $crawler->filter('trans-unit');
foreach ($crawler as $transUnit) {
$source = $transUnit
->getElementsByTagName('source')
->item(0)
->nodeValue
;
$source = str_replace("'", "''", $source);
$target = $transUnit
->getElementsByTagName('target')
->item(0)
->nodeValue
;
$target = str_replace("'", "''", $target);
$translations[$source] = $target;
}
$ymlGenerator = new ArrayToYamlGenerator($file, __DIR__ . '/../Resources/skeleton');
$ymlGenerator->generate($translations, 'Messages.yml.twig');
}
return 0;
}
|
php
|
protected function execute(InputInterface $input, OutputInterface $output)
{
$bundle = $input->getArgument('bundle');
$fs = new Filesystem();
$finder = new Finder();
$crawler = new Crawler();
$path = $this->getContainer()->get('kernel')->locateResource('@' . $bundle);
$transPath = $path . 'Resources/translations/';
if (!$fs->exists($transPath)) {
try {
$fs->mkdir($transPath);
} catch (IOExceptionInterface $e) {
echo sprintf('An error occurred while creating your directory at %s', $e->getPath());
}
}
foreach ($finder->files()->in($transPath) as $file) {
$translations = [];
$crawler->addXmlContent(file_get_contents($file->getPathName()));
$crawler = $crawler->filter('trans-unit');
foreach ($crawler as $transUnit) {
$source = $transUnit
->getElementsByTagName('source')
->item(0)
->nodeValue
;
$source = str_replace("'", "''", $source);
$target = $transUnit
->getElementsByTagName('target')
->item(0)
->nodeValue
;
$target = str_replace("'", "''", $target);
$translations[$source] = $target;
}
$ymlGenerator = new ArrayToYamlGenerator($file, __DIR__ . '/../Resources/skeleton');
$ymlGenerator->generate($translations, 'Messages.yml.twig');
}
return 0;
}
|
[
"protected",
"function",
"execute",
"(",
"InputInterface",
"$",
"input",
",",
"OutputInterface",
"$",
"output",
")",
"{",
"$",
"bundle",
"=",
"$",
"input",
"->",
"getArgument",
"(",
"'bundle'",
")",
";",
"$",
"fs",
"=",
"new",
"Filesystem",
"(",
")",
";",
"$",
"finder",
"=",
"new",
"Finder",
"(",
")",
";",
"$",
"crawler",
"=",
"new",
"Crawler",
"(",
")",
";",
"$",
"path",
"=",
"$",
"this",
"->",
"getContainer",
"(",
")",
"->",
"get",
"(",
"'kernel'",
")",
"->",
"locateResource",
"(",
"'@'",
".",
"$",
"bundle",
")",
";",
"$",
"transPath",
"=",
"$",
"path",
".",
"'Resources/translations/'",
";",
"if",
"(",
"!",
"$",
"fs",
"->",
"exists",
"(",
"$",
"transPath",
")",
")",
"{",
"try",
"{",
"$",
"fs",
"->",
"mkdir",
"(",
"$",
"transPath",
")",
";",
"}",
"catch",
"(",
"IOExceptionInterface",
"$",
"e",
")",
"{",
"echo",
"sprintf",
"(",
"'An error occurred while creating your directory at %s'",
",",
"$",
"e",
"->",
"getPath",
"(",
")",
")",
";",
"}",
"}",
"foreach",
"(",
"$",
"finder",
"->",
"files",
"(",
")",
"->",
"in",
"(",
"$",
"transPath",
")",
"as",
"$",
"file",
")",
"{",
"$",
"translations",
"=",
"[",
"]",
";",
"$",
"crawler",
"->",
"addXmlContent",
"(",
"file_get_contents",
"(",
"$",
"file",
"->",
"getPathName",
"(",
")",
")",
")",
";",
"$",
"crawler",
"=",
"$",
"crawler",
"->",
"filter",
"(",
"'trans-unit'",
")",
";",
"foreach",
"(",
"$",
"crawler",
"as",
"$",
"transUnit",
")",
"{",
"$",
"source",
"=",
"$",
"transUnit",
"->",
"getElementsByTagName",
"(",
"'source'",
")",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
";",
"$",
"source",
"=",
"str_replace",
"(",
"\"'\"",
",",
"\"''\"",
",",
"$",
"source",
")",
";",
"$",
"target",
"=",
"$",
"transUnit",
"->",
"getElementsByTagName",
"(",
"'target'",
")",
"->",
"item",
"(",
"0",
")",
"->",
"nodeValue",
";",
"$",
"target",
"=",
"str_replace",
"(",
"\"'\"",
",",
"\"''\"",
",",
"$",
"target",
")",
";",
"$",
"translations",
"[",
"$",
"source",
"]",
"=",
"$",
"target",
";",
"}",
"$",
"ymlGenerator",
"=",
"new",
"ArrayToYamlGenerator",
"(",
"$",
"file",
",",
"__DIR__",
".",
"'/../Resources/skeleton'",
")",
";",
"$",
"ymlGenerator",
"->",
"generate",
"(",
"$",
"translations",
",",
"'Messages.yml.twig'",
")",
";",
"}",
"return",
"0",
";",
"}"
] |
{@inheritdoc}
|
[
"{"
] |
train
|
https://github.com/blast-project/CoreBundle/blob/7a0832758ca14e5bc5d65515532c1220df3930ae/src/Command/GenerateTranslationsCommand.php#L52-L99
|
huasituo/hstcms
|
src/Libraries/HstcmsSms.php
|
HstcmsSms.sendMobileMessage
|
public function sendMobileMessage($mobile, $type, $param = [], $uid = 0)
{
if (!$this->plat) {
return hst_message(hst_lang('hstcms::manage.sms.plat.choose.error'));
}
$this->type = CommonSmsModel::getType($type);
if (!$this->type) {
return hst_message(hst_lang('hstcms::manage.sms.plat.choose.error'));
}
$code = CommonSmsCodeModel::_buildCode();
$content = $this->_buildContent($code, $type);
$number = $this->checkTodayNum($mobile, $type);
if (hst_message_verify($number)) {
return $number;
}
$param['code'] = $code;
$param['product'] = hst_config('sms', 'product');
$result = $this->plat->sendMobileMessage($mobile, $content, $param);
if (hst_message_verify($result)) {
return $result;
}
$results = CommonSmsCodeModel::addInfo($mobile, $type, $code, $number);
if($results) {
CommonSmsModel::addInfo($mobile, $type, $code, $content, json_encode($param), (int)$result['res']['type'], $result['res']['requestid'], $uid);
}
return true;
}
|
php
|
public function sendMobileMessage($mobile, $type, $param = [], $uid = 0)
{
if (!$this->plat) {
return hst_message(hst_lang('hstcms::manage.sms.plat.choose.error'));
}
$this->type = CommonSmsModel::getType($type);
if (!$this->type) {
return hst_message(hst_lang('hstcms::manage.sms.plat.choose.error'));
}
$code = CommonSmsCodeModel::_buildCode();
$content = $this->_buildContent($code, $type);
$number = $this->checkTodayNum($mobile, $type);
if (hst_message_verify($number)) {
return $number;
}
$param['code'] = $code;
$param['product'] = hst_config('sms', 'product');
$result = $this->plat->sendMobileMessage($mobile, $content, $param);
if (hst_message_verify($result)) {
return $result;
}
$results = CommonSmsCodeModel::addInfo($mobile, $type, $code, $number);
if($results) {
CommonSmsModel::addInfo($mobile, $type, $code, $content, json_encode($param), (int)$result['res']['type'], $result['res']['requestid'], $uid);
}
return true;
}
|
[
"public",
"function",
"sendMobileMessage",
"(",
"$",
"mobile",
",",
"$",
"type",
",",
"$",
"param",
"=",
"[",
"]",
",",
"$",
"uid",
"=",
"0",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"plat",
")",
"{",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::manage.sms.plat.choose.error'",
")",
")",
";",
"}",
"$",
"this",
"->",
"type",
"=",
"CommonSmsModel",
"::",
"getType",
"(",
"$",
"type",
")",
";",
"if",
"(",
"!",
"$",
"this",
"->",
"type",
")",
"{",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::manage.sms.plat.choose.error'",
")",
")",
";",
"}",
"$",
"code",
"=",
"CommonSmsCodeModel",
"::",
"_buildCode",
"(",
")",
";",
"$",
"content",
"=",
"$",
"this",
"->",
"_buildContent",
"(",
"$",
"code",
",",
"$",
"type",
")",
";",
"$",
"number",
"=",
"$",
"this",
"->",
"checkTodayNum",
"(",
"$",
"mobile",
",",
"$",
"type",
")",
";",
"if",
"(",
"hst_message_verify",
"(",
"$",
"number",
")",
")",
"{",
"return",
"$",
"number",
";",
"}",
"$",
"param",
"[",
"'code'",
"]",
"=",
"$",
"code",
";",
"$",
"param",
"[",
"'product'",
"]",
"=",
"hst_config",
"(",
"'sms'",
",",
"'product'",
")",
";",
"$",
"result",
"=",
"$",
"this",
"->",
"plat",
"->",
"sendMobileMessage",
"(",
"$",
"mobile",
",",
"$",
"content",
",",
"$",
"param",
")",
";",
"if",
"(",
"hst_message_verify",
"(",
"$",
"result",
")",
")",
"{",
"return",
"$",
"result",
";",
"}",
"$",
"results",
"=",
"CommonSmsCodeModel",
"::",
"addInfo",
"(",
"$",
"mobile",
",",
"$",
"type",
",",
"$",
"code",
",",
"$",
"number",
")",
";",
"if",
"(",
"$",
"results",
")",
"{",
"CommonSmsModel",
"::",
"addInfo",
"(",
"$",
"mobile",
",",
"$",
"type",
",",
"$",
"code",
",",
"$",
"content",
",",
"json_encode",
"(",
"$",
"param",
")",
",",
"(",
"int",
")",
"$",
"result",
"[",
"'res'",
"]",
"[",
"'type'",
"]",
",",
"$",
"result",
"[",
"'res'",
"]",
"[",
"'requestid'",
"]",
",",
"$",
"uid",
")",
";",
"}",
"return",
"true",
";",
"}"
] |
发送短信
@return bool
|
[
"发送短信"
] |
train
|
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsSms.php#L51-L77
|
huasituo/hstcms
|
src/Libraries/HstcmsSms.php
|
HstcmsSms.checkVerify
|
public function checkVerify($mobile, $inputCode, $type = 'register')
{
if (!$mobile || !$inputCode) return hst_message(hst_lang('hstcms::public.mobile.code.mobile.empty'));
$info = CommonSmsCodeModel::where('type', $type)->where('mobile', $mobile)->first();
if (!$info) return hst_message(hst_lang('hstcms::public.mobile.code.error'));
if ($info['expired_time'] < hst_time()) return hst_message(hst_lang('hstcms::public.mobile.code.expired_time.error'));
if ($inputCode !== $info['code']) return hst_message(hst_lang('hstcms::public.mobile.code.error'));
return true;
}
|
php
|
public function checkVerify($mobile, $inputCode, $type = 'register')
{
if (!$mobile || !$inputCode) return hst_message(hst_lang('hstcms::public.mobile.code.mobile.empty'));
$info = CommonSmsCodeModel::where('type', $type)->where('mobile', $mobile)->first();
if (!$info) return hst_message(hst_lang('hstcms::public.mobile.code.error'));
if ($info['expired_time'] < hst_time()) return hst_message(hst_lang('hstcms::public.mobile.code.expired_time.error'));
if ($inputCode !== $info['code']) return hst_message(hst_lang('hstcms::public.mobile.code.error'));
return true;
}
|
[
"public",
"function",
"checkVerify",
"(",
"$",
"mobile",
",",
"$",
"inputCode",
",",
"$",
"type",
"=",
"'register'",
")",
"{",
"if",
"(",
"!",
"$",
"mobile",
"||",
"!",
"$",
"inputCode",
")",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::public.mobile.code.mobile.empty'",
")",
")",
";",
"$",
"info",
"=",
"CommonSmsCodeModel",
"::",
"where",
"(",
"'type'",
",",
"$",
"type",
")",
"->",
"where",
"(",
"'mobile'",
",",
"$",
"mobile",
")",
"->",
"first",
"(",
")",
";",
"if",
"(",
"!",
"$",
"info",
")",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::public.mobile.code.error'",
")",
")",
";",
"if",
"(",
"$",
"info",
"[",
"'expired_time'",
"]",
"<",
"hst_time",
"(",
")",
")",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::public.mobile.code.expired_time.error'",
")",
")",
";",
"if",
"(",
"$",
"inputCode",
"!==",
"$",
"info",
"[",
"'code'",
"]",
")",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::public.mobile.code.error'",
")",
")",
";",
"return",
"true",
";",
"}"
] |
验证验证码
|
[
"验证验证码"
] |
train
|
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsSms.php#L83-L91
|
huasituo/hstcms
|
src/Libraries/HstcmsSms.php
|
HstcmsSms.checkTodayNum
|
public function checkTodayNum($mobile, $type = 'register')
{
$info = CommonSmsCodeModel::where('type', $type)->where('mobile', $mobile)->first();
$number = 1;
$tdtime = hst_getTdtime();
if ($info)
{
$number = $info['number'];
if ($info['create_time'] < $tdtime + 86400 && $info['create_time'] > $tdtime) {
$number++;
} else {
$number = 1;
}
}
if ($number > $this->type['num']) {
return hst_message(hst_lang('hstcms::public.mobile.code.send.num.error'));
}
return $number;
}
|
php
|
public function checkTodayNum($mobile, $type = 'register')
{
$info = CommonSmsCodeModel::where('type', $type)->where('mobile', $mobile)->first();
$number = 1;
$tdtime = hst_getTdtime();
if ($info)
{
$number = $info['number'];
if ($info['create_time'] < $tdtime + 86400 && $info['create_time'] > $tdtime) {
$number++;
} else {
$number = 1;
}
}
if ($number > $this->type['num']) {
return hst_message(hst_lang('hstcms::public.mobile.code.send.num.error'));
}
return $number;
}
|
[
"public",
"function",
"checkTodayNum",
"(",
"$",
"mobile",
",",
"$",
"type",
"=",
"'register'",
")",
"{",
"$",
"info",
"=",
"CommonSmsCodeModel",
"::",
"where",
"(",
"'type'",
",",
"$",
"type",
")",
"->",
"where",
"(",
"'mobile'",
",",
"$",
"mobile",
")",
"->",
"first",
"(",
")",
";",
"$",
"number",
"=",
"1",
";",
"$",
"tdtime",
"=",
"hst_getTdtime",
"(",
")",
";",
"if",
"(",
"$",
"info",
")",
"{",
"$",
"number",
"=",
"$",
"info",
"[",
"'number'",
"]",
";",
"if",
"(",
"$",
"info",
"[",
"'create_time'",
"]",
"<",
"$",
"tdtime",
"+",
"86400",
"&&",
"$",
"info",
"[",
"'create_time'",
"]",
">",
"$",
"tdtime",
")",
"{",
"$",
"number",
"++",
";",
"}",
"else",
"{",
"$",
"number",
"=",
"1",
";",
"}",
"}",
"if",
"(",
"$",
"number",
">",
"$",
"this",
"->",
"type",
"[",
"'num'",
"]",
")",
"{",
"return",
"hst_message",
"(",
"hst_lang",
"(",
"'hstcms::public.mobile.code.send.num.error'",
")",
")",
";",
"}",
"return",
"$",
"number",
";",
"}"
] |
检查发送次数
|
[
"检查发送次数"
] |
train
|
https://github.com/huasituo/hstcms/blob/12819979289e58ce38e3e92540aeeb16e205e525/src/Libraries/HstcmsSms.php#L97-L115
|
FrenchFrogs/framework
|
src/Form/Element/Date.php
|
Date.getDisplayValue
|
public function getDisplayValue()
{
$value = parent::getValue();
if (!empty($value)) {
try {
$date = substr($value, 0, strlen(date($this->getFormatStore())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatStore(), $date);
} catch (\InvalidArgumentException $e) {
throw $e;
} finally {
$value = $value instanceof \Carbon\Carbon ? $value->format($this->getFormatDisplay()) : '';
}
}
return $value;
}
|
php
|
public function getDisplayValue()
{
$value = parent::getValue();
if (!empty($value)) {
try {
$date = substr($value, 0, strlen(date($this->getFormatStore())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatStore(), $date);
} catch (\InvalidArgumentException $e) {
throw $e;
} finally {
$value = $value instanceof \Carbon\Carbon ? $value->format($this->getFormatDisplay()) : '';
}
}
return $value;
}
|
[
"public",
"function",
"getDisplayValue",
"(",
")",
"{",
"$",
"value",
"=",
"parent",
"::",
"getValue",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"try",
"{",
"$",
"date",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"strlen",
"(",
"date",
"(",
"$",
"this",
"->",
"getFormatStore",
"(",
")",
")",
")",
")",
";",
"$",
"value",
"=",
"\\",
"Carbon",
"\\",
"Carbon",
"::",
"createFromFormat",
"(",
"$",
"this",
"->",
"getFormatStore",
"(",
")",
",",
"$",
"date",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"finally",
"{",
"$",
"value",
"=",
"$",
"value",
"instanceof",
"\\",
"Carbon",
"\\",
"Carbon",
"?",
"$",
"value",
"->",
"format",
"(",
"$",
"this",
"->",
"getFormatDisplay",
"(",
")",
")",
":",
"''",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] |
Overload getvalue
@return mixed|string|static
|
[
"Overload",
"getvalue"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Form/Element/Date.php#L91-L108
|
FrenchFrogs/framework
|
src/Form/Element/Date.php
|
Date.getFilteredValue
|
public function getFilteredValue()
{
$value = parent::getFilteredValue();
if (!empty($value)) {
try {
$date = substr($value, 0, strlen(date($this->getFormatDisplay())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatDisplay(), $date);
} catch (\InvalidArgumentException $e) {
try {
$date = substr($value, 0, strlen(date($this->getFormatStore())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatStore(), $date);
} catch (\InvalidArgumentException $e) {
throw $e;
}
} finally {
$value = $value instanceof \Carbon\Carbon ? $value->format($this->getFormatStore()) : '';
}
}
return $value;
}
|
php
|
public function getFilteredValue()
{
$value = parent::getFilteredValue();
if (!empty($value)) {
try {
$date = substr($value, 0, strlen(date($this->getFormatDisplay())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatDisplay(), $date);
} catch (\InvalidArgumentException $e) {
try {
$date = substr($value, 0, strlen(date($this->getFormatStore())));
$value = \Carbon\Carbon::createFromFormat($this->getFormatStore(), $date);
} catch (\InvalidArgumentException $e) {
throw $e;
}
} finally {
$value = $value instanceof \Carbon\Carbon ? $value->format($this->getFormatStore()) : '';
}
}
return $value;
}
|
[
"public",
"function",
"getFilteredValue",
"(",
")",
"{",
"$",
"value",
"=",
"parent",
"::",
"getFilteredValue",
"(",
")",
";",
"if",
"(",
"!",
"empty",
"(",
"$",
"value",
")",
")",
"{",
"try",
"{",
"$",
"date",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"strlen",
"(",
"date",
"(",
"$",
"this",
"->",
"getFormatDisplay",
"(",
")",
")",
")",
")",
";",
"$",
"value",
"=",
"\\",
"Carbon",
"\\",
"Carbon",
"::",
"createFromFormat",
"(",
"$",
"this",
"->",
"getFormatDisplay",
"(",
")",
",",
"$",
"date",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"try",
"{",
"$",
"date",
"=",
"substr",
"(",
"$",
"value",
",",
"0",
",",
"strlen",
"(",
"date",
"(",
"$",
"this",
"->",
"getFormatStore",
"(",
")",
")",
")",
")",
";",
"$",
"value",
"=",
"\\",
"Carbon",
"\\",
"Carbon",
"::",
"createFromFormat",
"(",
"$",
"this",
"->",
"getFormatStore",
"(",
")",
",",
"$",
"date",
")",
";",
"}",
"catch",
"(",
"\\",
"InvalidArgumentException",
"$",
"e",
")",
"{",
"throw",
"$",
"e",
";",
"}",
"}",
"finally",
"{",
"$",
"value",
"=",
"$",
"value",
"instanceof",
"\\",
"Carbon",
"\\",
"Carbon",
"?",
"$",
"value",
"->",
"format",
"(",
"$",
"this",
"->",
"getFormatStore",
"(",
")",
")",
":",
"''",
";",
"}",
"}",
"return",
"$",
"value",
";",
"}"
] |
overload
@return mixed|string|static
|
[
"overload"
] |
train
|
https://github.com/FrenchFrogs/framework/blob/a4838c698a5600437e87dac6d35ba8ebe32c4395/src/Form/Element/Date.php#L116-L139
|
stubbles/stubbles-webapp-core
|
src/main/php/routing/Redirect.php
|
Redirect.resolve
|
public function resolve(Request $request, Response $response, UriPath $uriPath)
{
if ($this->target instanceof HttpUri) {
$targetUri = $this->target;
} else {
$targetUri = $request->uri()->withPath($this->target);
}
$response->redirect($targetUri, $this->statusCode);
}
|
php
|
public function resolve(Request $request, Response $response, UriPath $uriPath)
{
if ($this->target instanceof HttpUri) {
$targetUri = $this->target;
} else {
$targetUri = $request->uri()->withPath($this->target);
}
$response->redirect($targetUri, $this->statusCode);
}
|
[
"public",
"function",
"resolve",
"(",
"Request",
"$",
"request",
",",
"Response",
"$",
"response",
",",
"UriPath",
"$",
"uriPath",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"target",
"instanceof",
"HttpUri",
")",
"{",
"$",
"targetUri",
"=",
"$",
"this",
"->",
"target",
";",
"}",
"else",
"{",
"$",
"targetUri",
"=",
"$",
"request",
"->",
"uri",
"(",
")",
"->",
"withPath",
"(",
"$",
"this",
"->",
"target",
")",
";",
"}",
"$",
"response",
"->",
"redirect",
"(",
"$",
"targetUri",
",",
"$",
"this",
"->",
"statusCode",
")",
";",
"}"
] |
resolves the request and returns resource data
@param \stubbles\webapp\Request $request current request
@param \stubbles\webapp\Response $response response to send
@param \stubbles\webapp\UriPath $uriPath information about called uri path
|
[
"resolves",
"the",
"request",
"and",
"returns",
"resource",
"data"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/routing/Redirect.php#L70-L79
|
h1g/proxmox
|
src/h1g/Proxmox/ProxmoxServiceProvider.php
|
ProxmoxServiceProvider.register
|
public function register()
{
$this->app['proxmox'] = $this->app->share(function($app)
{
$proxmoxConfig = $app['config'];
$proxmoxCredetianls = $proxmoxConfig->get('proxmox.server', array());
return new \ProxmoxVE\Proxmox($proxmoxCredetianls);
});
}
|
php
|
public function register()
{
$this->app['proxmox'] = $this->app->share(function($app)
{
$proxmoxConfig = $app['config'];
$proxmoxCredetianls = $proxmoxConfig->get('proxmox.server', array());
return new \ProxmoxVE\Proxmox($proxmoxCredetianls);
});
}
|
[
"public",
"function",
"register",
"(",
")",
"{",
"$",
"this",
"->",
"app",
"[",
"'proxmox'",
"]",
"=",
"$",
"this",
"->",
"app",
"->",
"share",
"(",
"function",
"(",
"$",
"app",
")",
"{",
"$",
"proxmoxConfig",
"=",
"$",
"app",
"[",
"'config'",
"]",
";",
"$",
"proxmoxCredetianls",
"=",
"$",
"proxmoxConfig",
"->",
"get",
"(",
"'proxmox.server'",
",",
"array",
"(",
")",
")",
";",
"return",
"new",
"\\",
"ProxmoxVE",
"\\",
"Proxmox",
"(",
"$",
"proxmoxCredetianls",
")",
";",
"}",
")",
";",
"}"
] |
Register the service provider.
@return void
|
[
"Register",
"the",
"service",
"provider",
"."
] |
train
|
https://github.com/h1g/proxmox/blob/25539b5490315cfce8d48128b23cdc43825e3eb4/src/h1g/Proxmox/ProxmoxServiceProvider.php#L31-L41
|
weavephp/weave
|
src/Resolve/Resolve.php
|
Resolve.shift
|
public function shift($values)
{
if (!is_array($values)) {
if (!is_string($values)) {
// Handle callables being passed in.
return [];
}
// Handle a string being passed in
$components = explode('|', $values);
if (count($components) < 2) {
return [];
} elseif (count($components) === 2) {
return [$components[1]];
} else {
array_shift($components);
$lastItem = array_pop($components);
$components = array_map(
function ($value) {
return $value . '|';
},
$components
);
$components[] = $lastItem;
return $components;
}
} else {
$shiftedArray = $values;
array_shift($shiftedArray);
return $shiftedArray;
}
}
|
php
|
public function shift($values)
{
if (!is_array($values)) {
if (!is_string($values)) {
// Handle callables being passed in.
return [];
}
// Handle a string being passed in
$components = explode('|', $values);
if (count($components) < 2) {
return [];
} elseif (count($components) === 2) {
return [$components[1]];
} else {
array_shift($components);
$lastItem = array_pop($components);
$components = array_map(
function ($value) {
return $value . '|';
},
$components
);
$components[] = $lastItem;
return $components;
}
} else {
$shiftedArray = $values;
array_shift($shiftedArray);
return $shiftedArray;
}
}
|
[
"public",
"function",
"shift",
"(",
"$",
"values",
")",
"{",
"if",
"(",
"!",
"is_array",
"(",
"$",
"values",
")",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"values",
")",
")",
"{",
"// Handle callables being passed in.",
"return",
"[",
"]",
";",
"}",
"// Handle a string being passed in",
"$",
"components",
"=",
"explode",
"(",
"'|'",
",",
"$",
"values",
")",
";",
"if",
"(",
"count",
"(",
"$",
"components",
")",
"<",
"2",
")",
"{",
"return",
"[",
"]",
";",
"}",
"elseif",
"(",
"count",
"(",
"$",
"components",
")",
"===",
"2",
")",
"{",
"return",
"[",
"$",
"components",
"[",
"1",
"]",
"]",
";",
"}",
"else",
"{",
"array_shift",
"(",
"$",
"components",
")",
";",
"$",
"lastItem",
"=",
"array_pop",
"(",
"$",
"components",
")",
";",
"$",
"components",
"=",
"array_map",
"(",
"function",
"(",
"$",
"value",
")",
"{",
"return",
"$",
"value",
".",
"'|'",
";",
"}",
",",
"$",
"components",
")",
";",
"$",
"components",
"[",
"]",
"=",
"$",
"lastItem",
";",
"return",
"$",
"components",
";",
"}",
"}",
"else",
"{",
"$",
"shiftedArray",
"=",
"$",
"values",
";",
"array_shift",
"(",
"$",
"shiftedArray",
")",
";",
"return",
"$",
"shiftedArray",
";",
"}",
"}"
] |
Return the array of remaining dispatch steps with the first step removed (shifted).
A dispatch array can contain multiple middleware pipe names separated by a '|' char
which can be progressively consumed by Dispatch middlewares. This method removes a
single dispatch pipeline step, returning the remaining array.
If a string is passed into the array, attempt to split on the '|' char and return
an array of the remaining steps.
If something else is passed in then return an empty array.
@param array|string|callable $values The dispatch steps.
@return array The array of remaining dispatch steps.
|
[
"Return",
"the",
"array",
"of",
"remaining",
"dispatch",
"steps",
"with",
"the",
"first",
"step",
"removed",
"(",
"shifted",
")",
"."
] |
train
|
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Resolve/Resolve.php#L47-L78
|
weavephp/weave
|
src/Resolve/Resolve.php
|
Resolve.resolve
|
public function resolve($value, &$resolutionType)
{
if (is_array($value)) {
$value = $value[0];
}
if (is_string($value)) {
if (strpos($value, '|') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_PIPELINE;
return $this->resolveMiddlewarePipeline($value);
} elseif (strpos($value, '::') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_STATIC;
return $this->resolveStatic($value);
} elseif (strpos($value, '->') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_INSTANCE;
return $this->resolveInstanceMethod($value);
} else {
$resolutionType = ResolveAdaptorInterface::TYPE_INVOKE;
return $this->resolveInvokable($value);
}
} else {
$resolutionType = ResolveAdaptorInterface::TYPE_ORIGINAL;
return $value;
}
}
|
php
|
public function resolve($value, &$resolutionType)
{
if (is_array($value)) {
$value = $value[0];
}
if (is_string($value)) {
if (strpos($value, '|') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_PIPELINE;
return $this->resolveMiddlewarePipeline($value);
} elseif (strpos($value, '::') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_STATIC;
return $this->resolveStatic($value);
} elseif (strpos($value, '->') !== false) {
$resolutionType = ResolveAdaptorInterface::TYPE_INSTANCE;
return $this->resolveInstanceMethod($value);
} else {
$resolutionType = ResolveAdaptorInterface::TYPE_INVOKE;
return $this->resolveInvokable($value);
}
} else {
$resolutionType = ResolveAdaptorInterface::TYPE_ORIGINAL;
return $value;
}
}
|
[
"public",
"function",
"resolve",
"(",
"$",
"value",
",",
"&",
"$",
"resolutionType",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"$",
"value",
"=",
"$",
"value",
"[",
"0",
"]",
";",
"}",
"if",
"(",
"is_string",
"(",
"$",
"value",
")",
")",
"{",
"if",
"(",
"strpos",
"(",
"$",
"value",
",",
"'|'",
")",
"!==",
"false",
")",
"{",
"$",
"resolutionType",
"=",
"ResolveAdaptorInterface",
"::",
"TYPE_PIPELINE",
";",
"return",
"$",
"this",
"->",
"resolveMiddlewarePipeline",
"(",
"$",
"value",
")",
";",
"}",
"elseif",
"(",
"strpos",
"(",
"$",
"value",
",",
"'::'",
")",
"!==",
"false",
")",
"{",
"$",
"resolutionType",
"=",
"ResolveAdaptorInterface",
"::",
"TYPE_STATIC",
";",
"return",
"$",
"this",
"->",
"resolveStatic",
"(",
"$",
"value",
")",
";",
"}",
"elseif",
"(",
"strpos",
"(",
"$",
"value",
",",
"'->'",
")",
"!==",
"false",
")",
"{",
"$",
"resolutionType",
"=",
"ResolveAdaptorInterface",
"::",
"TYPE_INSTANCE",
";",
"return",
"$",
"this",
"->",
"resolveInstanceMethod",
"(",
"$",
"value",
")",
";",
"}",
"else",
"{",
"$",
"resolutionType",
"=",
"ResolveAdaptorInterface",
"::",
"TYPE_INVOKE",
";",
"return",
"$",
"this",
"->",
"resolveInvokable",
"(",
"$",
"value",
")",
";",
"}",
"}",
"else",
"{",
"$",
"resolutionType",
"=",
"ResolveAdaptorInterface",
"::",
"TYPE_ORIGINAL",
";",
"return",
"$",
"value",
";",
"}",
"}"
] |
Attempt to convert a provided value into a callable.
If the value is an array, the rest of the rules apply to the first item.
If the value isn't a string it is simply returned.
If the string value contains '|' treat it as a pipeline name.
If the string value contains '::' treat it as a static method call.
If the string value contains '->' treat it as an instance method call.
Otherwise, attempt to treat it as an invokable.
@param string|callable|array $value The value to resolve.
@param string $resolutionType Set to the type of resolution identified.
@return callable Usually some form of callable.
|
[
"Attempt",
"to",
"convert",
"a",
"provided",
"value",
"into",
"a",
"callable",
"."
] |
train
|
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Resolve/Resolve.php#L95-L118
|
weavephp/weave
|
src/Resolve/Resolve.php
|
Resolve.resolveMiddlewarePipeline
|
protected function resolveMiddlewarePipeline($value)
{
$value = strstr($value, '|', true);
$instantiator = $this->instantiator;
$middleware = $instantiator(\Weave\Middleware\Middleware::class);
return function (Request $request, $response = null) use ($middleware, $value) {
return $middleware->chain($value, $request, $response);
};
}
|
php
|
protected function resolveMiddlewarePipeline($value)
{
$value = strstr($value, '|', true);
$instantiator = $this->instantiator;
$middleware = $instantiator(\Weave\Middleware\Middleware::class);
return function (Request $request, $response = null) use ($middleware, $value) {
return $middleware->chain($value, $request, $response);
};
}
|
[
"protected",
"function",
"resolveMiddlewarePipeline",
"(",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"strstr",
"(",
"$",
"value",
",",
"'|'",
",",
"true",
")",
";",
"$",
"instantiator",
"=",
"$",
"this",
"->",
"instantiator",
";",
"$",
"middleware",
"=",
"$",
"instantiator",
"(",
"\\",
"Weave",
"\\",
"Middleware",
"\\",
"Middleware",
"::",
"class",
")",
";",
"return",
"function",
"(",
"Request",
"$",
"request",
",",
"$",
"response",
"=",
"null",
")",
"use",
"(",
"$",
"middleware",
",",
"$",
"value",
")",
"{",
"return",
"$",
"middleware",
"->",
"chain",
"(",
"$",
"value",
",",
"$",
"request",
",",
"$",
"response",
")",
";",
"}",
";",
"}"
] |
Resolve the provided value to a named middleware chain.
@param string $value The name of the middleware chain plus optional chained dispatch.
@return callable A callable that executes the middleware chain.
|
[
"Resolve",
"the",
"provided",
"value",
"to",
"a",
"named",
"middleware",
"chain",
"."
] |
train
|
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Resolve/Resolve.php#L127-L135
|
weavephp/weave
|
src/Resolve/Resolve.php
|
Resolve.resolveInstanceMethod
|
protected function resolveInstanceMethod($value)
{
$callable = explode('->', $value);
$instantiator = $this->instantiator;
$callable[0] = $instantiator($callable[0]);
return function (...$params) use ($callable) {
return call_user_func_array($callable, $params);
};
}
|
php
|
protected function resolveInstanceMethod($value)
{
$callable = explode('->', $value);
$instantiator = $this->instantiator;
$callable[0] = $instantiator($callable[0]);
return function (...$params) use ($callable) {
return call_user_func_array($callable, $params);
};
}
|
[
"protected",
"function",
"resolveInstanceMethod",
"(",
"$",
"value",
")",
"{",
"$",
"callable",
"=",
"explode",
"(",
"'->'",
",",
"$",
"value",
")",
";",
"$",
"instantiator",
"=",
"$",
"this",
"->",
"instantiator",
";",
"$",
"callable",
"[",
"0",
"]",
"=",
"$",
"instantiator",
"(",
"$",
"callable",
"[",
"0",
"]",
")",
";",
"return",
"function",
"(",
"...",
"$",
"params",
")",
"use",
"(",
"$",
"callable",
")",
"{",
"return",
"call_user_func_array",
"(",
"$",
"callable",
",",
"$",
"params",
")",
";",
"}",
";",
"}"
] |
Resolve the provided value to an instancelass method call.
@param string $value The class and method definition string.
@return callable A callable that executes the instance method.
|
[
"Resolve",
"the",
"provided",
"value",
"to",
"an",
"instancelass",
"method",
"call",
"."
] |
train
|
https://github.com/weavephp/weave/blob/44183a5bcb9e3ed3754cc76aa9e0724d718caeec/src/Resolve/Resolve.php#L158-L166
|
RinkAttendant6/JsonI18n
|
src/DateFormat.php
|
DateFormat.addResource
|
public function addResource(string $file): void
{
$contents = file_get_contents($file);
if ($contents === false) {
throw new \RuntimeException("Error reading file at $file.");
}
$this->processData(json_decode($contents, true));
}
|
php
|
public function addResource(string $file): void
{
$contents = file_get_contents($file);
if ($contents === false) {
throw new \RuntimeException("Error reading file at $file.");
}
$this->processData(json_decode($contents, true));
}
|
[
"public",
"function",
"addResource",
"(",
"string",
"$",
"file",
")",
":",
"void",
"{",
"$",
"contents",
"=",
"file_get_contents",
"(",
"$",
"file",
")",
";",
"if",
"(",
"$",
"contents",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Error reading file at $file.\"",
")",
";",
"}",
"$",
"this",
"->",
"processData",
"(",
"json_decode",
"(",
"$",
"contents",
",",
"true",
")",
")",
";",
"}"
] |
Adds a resource
@param string $file The resource to add
|
[
"Adds",
"a",
"resource"
] |
train
|
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/DateFormat.php#L42-L51
|
RinkAttendant6/JsonI18n
|
src/DateFormat.php
|
DateFormat.processData
|
private function processData(array $data): void
{
foreach ($data['formatters'] as $locale => $f) {
if (!isset($this->formatters[$locale])) {
$this->formatters[$locale] = array();
}
foreach ($f as $formatter => $d) {
$calendar = \IntlDateFormatter::GREGORIAN;
if (isset($d['calendar']) && $d['calendar'] === 'traditional') {
$calendar = \IntlDateFormatter::TRADITIONAL;
}
$this->formatters[$locale][$formatter] = new \IntlDateFormatter($locale, null, null, null, $calendar, $d['pattern']);
}
}
}
|
php
|
private function processData(array $data): void
{
foreach ($data['formatters'] as $locale => $f) {
if (!isset($this->formatters[$locale])) {
$this->formatters[$locale] = array();
}
foreach ($f as $formatter => $d) {
$calendar = \IntlDateFormatter::GREGORIAN;
if (isset($d['calendar']) && $d['calendar'] === 'traditional') {
$calendar = \IntlDateFormatter::TRADITIONAL;
}
$this->formatters[$locale][$formatter] = new \IntlDateFormatter($locale, null, null, null, $calendar, $d['pattern']);
}
}
}
|
[
"private",
"function",
"processData",
"(",
"array",
"$",
"data",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"data",
"[",
"'formatters'",
"]",
"as",
"$",
"locale",
"=>",
"$",
"f",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"=",
"array",
"(",
")",
";",
"}",
"foreach",
"(",
"$",
"f",
"as",
"$",
"formatter",
"=>",
"$",
"d",
")",
"{",
"$",
"calendar",
"=",
"\\",
"IntlDateFormatter",
"::",
"GREGORIAN",
";",
"if",
"(",
"isset",
"(",
"$",
"d",
"[",
"'calendar'",
"]",
")",
"&&",
"$",
"d",
"[",
"'calendar'",
"]",
"===",
"'traditional'",
")",
"{",
"$",
"calendar",
"=",
"\\",
"IntlDateFormatter",
"::",
"TRADITIONAL",
";",
"}",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"[",
"$",
"formatter",
"]",
"=",
"new",
"\\",
"IntlDateFormatter",
"(",
"$",
"locale",
",",
"null",
",",
"null",
",",
"null",
",",
"$",
"calendar",
",",
"$",
"d",
"[",
"'pattern'",
"]",
")",
";",
"}",
"}",
"}"
] |
Processes the resource file data
@param array $data The data from the resource file
|
[
"Processes",
"the",
"resource",
"file",
"data"
] |
train
|
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/DateFormat.php#L57-L73
|
RinkAttendant6/JsonI18n
|
src/DateFormat.php
|
DateFormat.format
|
public function format($datetime, string $formatter, ?string $locale = null): string
{
if ($locale === null) {
$locale = $this->locale;
}
if (!($datetime instanceof \DateTime)) {
$datetime = new \DateTime($datetime);
}
if (!isset($this->formatters[$locale])) {
throw new \InvalidArgumentException('Locale data not found.');
}
if (!isset($this->formatters[$locale][$formatter])) {
throw new \InvalidArgumentException('Formatter not found for specified locale.');
}
return $this->formatters[$locale][$formatter]->format($datetime->getTimestamp());
}
|
php
|
public function format($datetime, string $formatter, ?string $locale = null): string
{
if ($locale === null) {
$locale = $this->locale;
}
if (!($datetime instanceof \DateTime)) {
$datetime = new \DateTime($datetime);
}
if (!isset($this->formatters[$locale])) {
throw new \InvalidArgumentException('Locale data not found.');
}
if (!isset($this->formatters[$locale][$formatter])) {
throw new \InvalidArgumentException('Formatter not found for specified locale.');
}
return $this->formatters[$locale][$formatter]->format($datetime->getTimestamp());
}
|
[
"public",
"function",
"format",
"(",
"$",
"datetime",
",",
"string",
"$",
"formatter",
",",
"?",
"string",
"$",
"locale",
"=",
"null",
")",
":",
"string",
"{",
"if",
"(",
"$",
"locale",
"===",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"this",
"->",
"locale",
";",
"}",
"if",
"(",
"!",
"(",
"$",
"datetime",
"instanceof",
"\\",
"DateTime",
")",
")",
"{",
"$",
"datetime",
"=",
"new",
"\\",
"DateTime",
"(",
"$",
"datetime",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Locale data not found.'",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"[",
"$",
"formatter",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Formatter not found for specified locale.'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"[",
"$",
"formatter",
"]",
"->",
"format",
"(",
"$",
"datetime",
"->",
"getTimestamp",
"(",
")",
")",
";",
"}"
] |
Formats a date/time
@param \DateTime|string $datetime The date/time to format. If a string is passed, it will be used to create a DateTime object.
@param string $formatter The name of the formatter pattern to use
@param string $locale The locale for format in. Defaults to default locale.
@return string The formatted date
@throws \InvalidArgumentException If the locale or formatter name is invalid.
|
[
"Formats",
"a",
"date",
"/",
"time"
] |
train
|
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/DateFormat.php#L83-L102
|
RinkAttendant6/JsonI18n
|
src/DateFormat.php
|
DateFormat.getFormatter
|
public function getFormatter(string $formatter, ?string $locale = null): \IntlDateFormatter
{
if ($locale === null) {
$locale = $this->locale;
}
if (!isset($this->formatters[$locale])) {
throw new \InvalidArgumentException('Locale data not found.');
}
if (!isset($this->formatters[$locale][$formatter])) {
throw new \InvalidArgumentException('Formatter not found for specified locale.');
}
return $this->formatters[$locale][$formatter];
}
|
php
|
public function getFormatter(string $formatter, ?string $locale = null): \IntlDateFormatter
{
if ($locale === null) {
$locale = $this->locale;
}
if (!isset($this->formatters[$locale])) {
throw new \InvalidArgumentException('Locale data not found.');
}
if (!isset($this->formatters[$locale][$formatter])) {
throw new \InvalidArgumentException('Formatter not found for specified locale.');
}
return $this->formatters[$locale][$formatter];
}
|
[
"public",
"function",
"getFormatter",
"(",
"string",
"$",
"formatter",
",",
"?",
"string",
"$",
"locale",
"=",
"null",
")",
":",
"\\",
"IntlDateFormatter",
"{",
"if",
"(",
"$",
"locale",
"===",
"null",
")",
"{",
"$",
"locale",
"=",
"$",
"this",
"->",
"locale",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Locale data not found.'",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"[",
"$",
"formatter",
"]",
")",
")",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"'Formatter not found for specified locale.'",
")",
";",
"}",
"return",
"$",
"this",
"->",
"formatters",
"[",
"$",
"locale",
"]",
"[",
"$",
"formatter",
"]",
";",
"}"
] |
Returns a IntlDateFormatter object
@param string $formatter The name of the formatter pattern
@param string $locale The locale. Defaults to default locale.
@return \IntlDateFormatter The formatter object
@throws \InvalidArgumentException If the locale or formatter name is invalid.
|
[
"Returns",
"a",
"IntlDateFormatter",
"object"
] |
train
|
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/DateFormat.php#L111-L126
|
RinkAttendant6/JsonI18n
|
src/DateFormat.php
|
DateFormat.debug
|
public function debug(): void
{
foreach ($this->formatters as $locale => $formats) {
echo "\n# $locale\n";
foreach ($formats as $name => $format) {
echo "## $name\n";
echo "Locale: " . $format->getLocale(\Locale::VALID_LOCALE) . "\n" .
"DateType: " . $format->getDateType() . "\n" .
"TimeType: " . $format->getTimeType() . "\n" .
"Calendar: " . $format->getCalendar() . "\n" .
"Pattern: " . $format->getPattern() . "\n\n";
}
}
}
|
php
|
public function debug(): void
{
foreach ($this->formatters as $locale => $formats) {
echo "\n# $locale\n";
foreach ($formats as $name => $format) {
echo "## $name\n";
echo "Locale: " . $format->getLocale(\Locale::VALID_LOCALE) . "\n" .
"DateType: " . $format->getDateType() . "\n" .
"TimeType: " . $format->getTimeType() . "\n" .
"Calendar: " . $format->getCalendar() . "\n" .
"Pattern: " . $format->getPattern() . "\n\n";
}
}
}
|
[
"public",
"function",
"debug",
"(",
")",
":",
"void",
"{",
"foreach",
"(",
"$",
"this",
"->",
"formatters",
"as",
"$",
"locale",
"=>",
"$",
"formats",
")",
"{",
"echo",
"\"\\n# $locale\\n\"",
";",
"foreach",
"(",
"$",
"formats",
"as",
"$",
"name",
"=>",
"$",
"format",
")",
"{",
"echo",
"\"## $name\\n\"",
";",
"echo",
"\"Locale: \"",
".",
"$",
"format",
"->",
"getLocale",
"(",
"\\",
"Locale",
"::",
"VALID_LOCALE",
")",
".",
"\"\\n\"",
".",
"\"DateType: \"",
".",
"$",
"format",
"->",
"getDateType",
"(",
")",
".",
"\"\\n\"",
".",
"\"TimeType: \"",
".",
"$",
"format",
"->",
"getTimeType",
"(",
")",
".",
"\"\\n\"",
".",
"\"Calendar: \"",
".",
"$",
"format",
"->",
"getCalendar",
"(",
")",
".",
"\"\\n\"",
".",
"\"Pattern: \"",
".",
"$",
"format",
"->",
"getPattern",
"(",
")",
".",
"\"\\n\\n\"",
";",
"}",
"}",
"}"
] |
Debug function
@codeCoverageIgnore
|
[
"Debug",
"function"
] |
train
|
https://github.com/RinkAttendant6/JsonI18n/blob/882cbd43d273f771a384eb09d205d327033aaae3/src/DateFormat.php#L132-L145
|
markdegrootnl/omnipay-ideal
|
src/Message/AbstractRequest.php
|
AbstractRequest.validate
|
public function validate()
{
foreach (func_get_args() as $key) {
$value = $this->parameters->get($key);
if (empty($value) && $value !== '0' && $value !== false) {
throw new InvalidRequestException("The $key parameter is required");
}
}
}
|
php
|
public function validate()
{
foreach (func_get_args() as $key) {
$value = $this->parameters->get($key);
if (empty($value) && $value !== '0' && $value !== false) {
throw new InvalidRequestException("The $key parameter is required");
}
}
}
|
[
"public",
"function",
"validate",
"(",
")",
"{",
"foreach",
"(",
"func_get_args",
"(",
")",
"as",
"$",
"key",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"parameters",
"->",
"get",
"(",
"$",
"key",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"value",
")",
"&&",
"$",
"value",
"!==",
"'0'",
"&&",
"$",
"value",
"!==",
"false",
")",
"{",
"throw",
"new",
"InvalidRequestException",
"(",
"\"The $key parameter is required\"",
")",
";",
"}",
"}",
"}"
] |
/*
This function overwrites the \Omnipay\Common\Message\AbstractRequest::validate() function
to fix: https://github.com/thephpleague/omnipay-common/issues/13
and can be removed once the issue is fixed upstream.
|
[
"/",
"*",
"This",
"function",
"overwrites",
"the",
"\\",
"Omnipay",
"\\",
"Common",
"\\",
"Message",
"\\",
"AbstractRequest",
"::",
"validate",
"()",
"function",
"to",
"fix",
":",
"https",
":",
"//",
"github",
".",
"com",
"/",
"thephpleague",
"/",
"omnipay",
"-",
"common",
"/",
"issues",
"/",
"13",
"and",
"can",
"be",
"removed",
"once",
"the",
"issue",
"is",
"fixed",
"upstream",
"."
] |
train
|
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L118-L126
|
markdegrootnl/omnipay-ideal
|
src/Message/AbstractRequest.php
|
AbstractRequest.signXML
|
public function signXML($data)
{
$xml = new DOMDocument;
$xml->preserveWhiteSpace = false;
$xml->loadXML($data);
$sig = new DOMDocument;
$sig->preserveWhiteSpace = false;
$sig->loadXML(
'<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue/>
</Reference>
</SignedInfo>
<SignatureValue/>
<KeyInfo><KeyName/></KeyInfo>
</Signature>'
);
$sig = $xml->importNode($sig->documentElement, true);
$xml->documentElement->appendChild($sig);
// calculate digest
$xpath = $this->getXPath($xml);
$digestValue = $xpath->query('ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue')->item(0);
$digestValue->nodeValue = $this->generateDigest($xml);
// calculate signature
$signedInfo = $xpath->query('ds:Signature/ds:SignedInfo')->item(0);
$signatureValue = $xpath->query('ds:Signature/ds:SignatureValue')->item(0);
$signatureValue->nodeValue = $this->generateSignature($signedInfo);
// add key reference
$keyName = $xpath->query('ds:Signature/ds:KeyInfo/ds:KeyName')->item(0);
$keyName->nodeValue = $this->getPublicKeyDigest();
return $xml->saveXML();
}
|
php
|
public function signXML($data)
{
$xml = new DOMDocument;
$xml->preserveWhiteSpace = false;
$xml->loadXML($data);
$sig = new DOMDocument;
$sig->preserveWhiteSpace = false;
$sig->loadXML(
'<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
<Reference URI="">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
<DigestValue/>
</Reference>
</SignedInfo>
<SignatureValue/>
<KeyInfo><KeyName/></KeyInfo>
</Signature>'
);
$sig = $xml->importNode($sig->documentElement, true);
$xml->documentElement->appendChild($sig);
// calculate digest
$xpath = $this->getXPath($xml);
$digestValue = $xpath->query('ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue')->item(0);
$digestValue->nodeValue = $this->generateDigest($xml);
// calculate signature
$signedInfo = $xpath->query('ds:Signature/ds:SignedInfo')->item(0);
$signatureValue = $xpath->query('ds:Signature/ds:SignatureValue')->item(0);
$signatureValue->nodeValue = $this->generateSignature($signedInfo);
// add key reference
$keyName = $xpath->query('ds:Signature/ds:KeyInfo/ds:KeyName')->item(0);
$keyName->nodeValue = $this->getPublicKeyDigest();
return $xml->saveXML();
}
|
[
"public",
"function",
"signXML",
"(",
"$",
"data",
")",
"{",
"$",
"xml",
"=",
"new",
"DOMDocument",
";",
"$",
"xml",
"->",
"preserveWhiteSpace",
"=",
"false",
";",
"$",
"xml",
"->",
"loadXML",
"(",
"$",
"data",
")",
";",
"$",
"sig",
"=",
"new",
"DOMDocument",
";",
"$",
"sig",
"->",
"preserveWhiteSpace",
"=",
"false",
";",
"$",
"sig",
"->",
"loadXML",
"(",
"'<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\">\n <SignedInfo>\n <CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\n <SignatureMethod Algorithm=\"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256\"/>\n <Reference URI=\"\">\n <Transforms>\n <Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"/>\n </Transforms>\n <DigestMethod Algorithm=\"http://www.w3.org/2001/04/xmlenc#sha256\"/>\n <DigestValue/>\n </Reference>\n </SignedInfo>\n <SignatureValue/>\n <KeyInfo><KeyName/></KeyInfo>\n </Signature>'",
")",
";",
"$",
"sig",
"=",
"$",
"xml",
"->",
"importNode",
"(",
"$",
"sig",
"->",
"documentElement",
",",
"true",
")",
";",
"$",
"xml",
"->",
"documentElement",
"->",
"appendChild",
"(",
"$",
"sig",
")",
";",
"// calculate digest",
"$",
"xpath",
"=",
"$",
"this",
"->",
"getXPath",
"(",
"$",
"xml",
")",
";",
"$",
"digestValue",
"=",
"$",
"xpath",
"->",
"query",
"(",
"'ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue'",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"digestValue",
"->",
"nodeValue",
"=",
"$",
"this",
"->",
"generateDigest",
"(",
"$",
"xml",
")",
";",
"// calculate signature",
"$",
"signedInfo",
"=",
"$",
"xpath",
"->",
"query",
"(",
"'ds:Signature/ds:SignedInfo'",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"signatureValue",
"=",
"$",
"xpath",
"->",
"query",
"(",
"'ds:Signature/ds:SignatureValue'",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"signatureValue",
"->",
"nodeValue",
"=",
"$",
"this",
"->",
"generateSignature",
"(",
"$",
"signedInfo",
")",
";",
"// add key reference",
"$",
"keyName",
"=",
"$",
"xpath",
"->",
"query",
"(",
"'ds:Signature/ds:KeyInfo/ds:KeyName'",
")",
"->",
"item",
"(",
"0",
")",
";",
"$",
"keyName",
"->",
"nodeValue",
"=",
"$",
"this",
"->",
"getPublicKeyDigest",
"(",
")",
";",
"return",
"$",
"xml",
"->",
"saveXML",
"(",
")",
";",
"}"
] |
Sign an XML request
@param string
@return string
|
[
"Sign",
"an",
"XML",
"request"
] |
train
|
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L134-L178
|
markdegrootnl/omnipay-ideal
|
src/Message/AbstractRequest.php
|
AbstractRequest.generateDigest
|
public function generateDigest(DOMDocument $xml)
{
$xml = $xml->cloneNode(true);
// strip Signature
foreach ($this->getXPath($xml)->query('ds:Signature') as $node) {
$node->parentNode->removeChild($node);
}
$message = $this->c14n($xml);
return base64_encode(hash('sha256', $message, true));
}
|
php
|
public function generateDigest(DOMDocument $xml)
{
$xml = $xml->cloneNode(true);
// strip Signature
foreach ($this->getXPath($xml)->query('ds:Signature') as $node) {
$node->parentNode->removeChild($node);
}
$message = $this->c14n($xml);
return base64_encode(hash('sha256', $message, true));
}
|
[
"public",
"function",
"generateDigest",
"(",
"DOMDocument",
"$",
"xml",
")",
"{",
"$",
"xml",
"=",
"$",
"xml",
"->",
"cloneNode",
"(",
"true",
")",
";",
"// strip Signature",
"foreach",
"(",
"$",
"this",
"->",
"getXPath",
"(",
"$",
"xml",
")",
"->",
"query",
"(",
"'ds:Signature'",
")",
"as",
"$",
"node",
")",
"{",
"$",
"node",
"->",
"parentNode",
"->",
"removeChild",
"(",
"$",
"node",
")",
";",
"}",
"$",
"message",
"=",
"$",
"this",
"->",
"c14n",
"(",
"$",
"xml",
")",
";",
"return",
"base64_encode",
"(",
"hash",
"(",
"'sha256'",
",",
"$",
"message",
",",
"true",
")",
")",
";",
"}"
] |
Generate sha256 digest of xml
@param DOMNode
@return string
|
[
"Generate",
"sha256",
"digest",
"of",
"xml"
] |
train
|
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L186-L198
|
markdegrootnl/omnipay-ideal
|
src/Message/AbstractRequest.php
|
AbstractRequest.generateSignature
|
public function generateSignature(DOMNode $xml)
{
$message = $this->c14n($xml);
$key = openssl_get_privatekey('file://'.$this->getPrivateKeyPath(), $this->getPrivateKeyPassphrase());
if ($key && openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) {
openssl_free_key($key);
return base64_encode($signature);
}
$error = 'Invalid private key.';
while ($msg = openssl_error_string()) {
$error .= ' '.$msg;
}
throw new InvalidRequestException($error);
}
|
php
|
public function generateSignature(DOMNode $xml)
{
$message = $this->c14n($xml);
$key = openssl_get_privatekey('file://'.$this->getPrivateKeyPath(), $this->getPrivateKeyPassphrase());
if ($key && openssl_sign($message, $signature, $key, OPENSSL_ALGO_SHA256)) {
openssl_free_key($key);
return base64_encode($signature);
}
$error = 'Invalid private key.';
while ($msg = openssl_error_string()) {
$error .= ' '.$msg;
}
throw new InvalidRequestException($error);
}
|
[
"public",
"function",
"generateSignature",
"(",
"DOMNode",
"$",
"xml",
")",
"{",
"$",
"message",
"=",
"$",
"this",
"->",
"c14n",
"(",
"$",
"xml",
")",
";",
"$",
"key",
"=",
"openssl_get_privatekey",
"(",
"'file://'",
".",
"$",
"this",
"->",
"getPrivateKeyPath",
"(",
")",
",",
"$",
"this",
"->",
"getPrivateKeyPassphrase",
"(",
")",
")",
";",
"if",
"(",
"$",
"key",
"&&",
"openssl_sign",
"(",
"$",
"message",
",",
"$",
"signature",
",",
"$",
"key",
",",
"OPENSSL_ALGO_SHA256",
")",
")",
"{",
"openssl_free_key",
"(",
"$",
"key",
")",
";",
"return",
"base64_encode",
"(",
"$",
"signature",
")",
";",
"}",
"$",
"error",
"=",
"'Invalid private key.'",
";",
"while",
"(",
"$",
"msg",
"=",
"openssl_error_string",
"(",
")",
")",
"{",
"$",
"error",
".=",
"' '",
".",
"$",
"msg",
";",
"}",
"throw",
"new",
"InvalidRequestException",
"(",
"$",
"error",
")",
";",
"}"
] |
Generate RSA signature of SignedInfo element
@param DOMNode
@return string
|
[
"Generate",
"RSA",
"signature",
"of",
"SignedInfo",
"element"
] |
train
|
https://github.com/markdegrootnl/omnipay-ideal/blob/565e942c2d22dd160ce6101cc5743f131af54660/src/Message/AbstractRequest.php#L206-L223
|
prooph/link-app-core
|
src/Service/AbstractQueryController.php
|
AbstractQueryController.getProcessingTypesForClient
|
protected function getProcessingTypesForClient(array $processingTypes = null)
{
if (is_null($processingTypes)) {
$processingTypes = $this->systemConfig->getAllAvailableProcessingTypes();
}
return array_map(function($processingTypeClass) { return $this->prepareProcessingType($processingTypeClass); }, $processingTypes);
}
|
php
|
protected function getProcessingTypesForClient(array $processingTypes = null)
{
if (is_null($processingTypes)) {
$processingTypes = $this->systemConfig->getAllAvailableProcessingTypes();
}
return array_map(function($processingTypeClass) { return $this->prepareProcessingType($processingTypeClass); }, $processingTypes);
}
|
[
"protected",
"function",
"getProcessingTypesForClient",
"(",
"array",
"$",
"processingTypes",
"=",
"null",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"processingTypes",
")",
")",
"{",
"$",
"processingTypes",
"=",
"$",
"this",
"->",
"systemConfig",
"->",
"getAllAvailableProcessingTypes",
"(",
")",
";",
"}",
"return",
"array_map",
"(",
"function",
"(",
"$",
"processingTypeClass",
")",
"{",
"return",
"$",
"this",
"->",
"prepareProcessingType",
"(",
"$",
"processingTypeClass",
")",
";",
"}",
",",
"$",
"processingTypes",
")",
";",
"}"
] |
Loads available DataTypes from system config and converts some to cient format
If optional data type array is passed as argument, this is used instead of all available types
@param array|null $processingTypes
@return array
|
[
"Loads",
"available",
"DataTypes",
"from",
"system",
"config",
"and",
"converts",
"some",
"to",
"cient",
"format"
] |
train
|
https://github.com/prooph/link-app-core/blob/835a5945dfa7be7b2cebfa6e84e757ecfd783357/src/Service/AbstractQueryController.php#L49-L56
|
Wonail/wocenter
|
libs/Tree.php
|
Tree.getParentIds
|
public static function getParentIds($modelClass, $pk = 0, $pkField = 'id', $parentField = 'parent_id', $rootId = 0)
{
$model = '';
if ($isObj = ($modelClass instanceof ActiveRecord)) {
$model = $modelClass;
if (!isset($model->$pkField)) {
throw new InvalidConfigException("The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists");
}
$pk = $model->$pkField;
} elseif (!class_exists($modelClass)) {
throw new InvalidConfigException("The model class: `{$modelClass}` does not exists");
}
if (empty($pk)) {
$method = __METHOD__ . '()';
throw new NotFoundHttpException("{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}");
}
if (!$isObj) {
$model = $modelClass::findOne([$pkField => $pk]);
}
if (!isset($model->$parentField)) {
throw new InvalidConfigException("The `{$parentField}` property of model class: `{$modelClass::className()}` does not exists");
}
$_parentIds = [];
while ($model !== null) {
if ($model->$parentField !== $rootId) {
array_unshift($_parentIds, $model->$parentField);
$model = $modelClass::findOne([$pkField => $model->$parentField]);
} else {
$model = null;
}
}
return $_parentIds;
}
|
php
|
public static function getParentIds($modelClass, $pk = 0, $pkField = 'id', $parentField = 'parent_id', $rootId = 0)
{
$model = '';
if ($isObj = ($modelClass instanceof ActiveRecord)) {
$model = $modelClass;
if (!isset($model->$pkField)) {
throw new InvalidConfigException("The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists");
}
$pk = $model->$pkField;
} elseif (!class_exists($modelClass)) {
throw new InvalidConfigException("The model class: `{$modelClass}` does not exists");
}
if (empty($pk)) {
$method = __METHOD__ . '()';
throw new NotFoundHttpException("{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}");
}
if (!$isObj) {
$model = $modelClass::findOne([$pkField => $pk]);
}
if (!isset($model->$parentField)) {
throw new InvalidConfigException("The `{$parentField}` property of model class: `{$modelClass::className()}` does not exists");
}
$_parentIds = [];
while ($model !== null) {
if ($model->$parentField !== $rootId) {
array_unshift($_parentIds, $model->$parentField);
$model = $modelClass::findOne([$pkField => $model->$parentField]);
} else {
$model = null;
}
}
return $_parentIds;
}
|
[
"public",
"static",
"function",
"getParentIds",
"(",
"$",
"modelClass",
",",
"$",
"pk",
"=",
"0",
",",
"$",
"pkField",
"=",
"'id'",
",",
"$",
"parentField",
"=",
"'parent_id'",
",",
"$",
"rootId",
"=",
"0",
")",
"{",
"$",
"model",
"=",
"''",
";",
"if",
"(",
"$",
"isObj",
"=",
"(",
"$",
"modelClass",
"instanceof",
"ActiveRecord",
")",
")",
"{",
"$",
"model",
"=",
"$",
"modelClass",
";",
"if",
"(",
"!",
"isset",
"(",
"$",
"model",
"->",
"$",
"pkField",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists\"",
")",
";",
"}",
"$",
"pk",
"=",
"$",
"model",
"->",
"$",
"pkField",
";",
"}",
"elseif",
"(",
"!",
"class_exists",
"(",
"$",
"modelClass",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"The model class: `{$modelClass}` does not exists\"",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"pk",
")",
")",
"{",
"$",
"method",
"=",
"__METHOD__",
".",
"'()'",
";",
"throw",
"new",
"NotFoundHttpException",
"(",
"\"{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}\");",
"",
"",
"}",
"if",
"(",
"!",
"$",
"isObj",
")",
"{",
"$",
"model",
"=",
"$",
"modelClass",
"::",
"findOne",
"(",
"[",
"$",
"pkField",
"=>",
"$",
"pk",
"]",
")",
";",
"}",
"if",
"(",
"!",
"isset",
"(",
"$",
"model",
"->",
"$",
"parentField",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"The `{$parentField}` property of model class: `{$modelClass::className()}` does not exists\"",
")",
";",
"}",
"$",
"_parentIds",
"=",
"[",
"]",
";",
"while",
"(",
"$",
"model",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"model",
"->",
"$",
"parentField",
"!==",
"$",
"rootId",
")",
"{",
"array_unshift",
"(",
"$",
"_parentIds",
",",
"$",
"model",
"->",
"$",
"parentField",
")",
";",
"$",
"model",
"=",
"$",
"modelClass",
"::",
"findOne",
"(",
"[",
"$",
"pkField",
"=>",
"$",
"model",
"->",
"$",
"parentField",
"]",
")",
";",
"}",
"else",
"{",
"$",
"model",
"=",
"null",
";",
"}",
"}",
"return",
"$",
"_parentIds",
";",
"}"
] |
获取指定模型指定主键的所有父级ID数据
@param ActiveRecord|string $modelClass 模型对象或模型命名空间
@param integer $pk 待查询的主键值,仅在`$modelClass`为字符串时生效,否则会自动从`$modelClass`对象处获取
@param string $pkField 主键字段
@param string $parentField 父级字段
@param integer $rootId 顶级ID,默认为`0`,返回的父级ID数据获取到此顶级ID后则停止获取
@return array
@throws InvalidConfigException
@throws NotFoundHttpException
|
[
"获取指定模型指定主键的所有父级ID数据"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/libs/Tree.php#L30-L65
|
Wonail/wocenter
|
libs/Tree.php
|
Tree.getChildrenIds
|
public static function getChildrenIds($modelClass, $pk = 0, $pkField = 'id', $parentField = 'parent_id')
{
if ($modelClass instanceof ActiveRecord) {
if (!isset($modelClass->$pkField)) {
throw new InvalidConfigException("The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists");
}
$pk = $modelClass->$pkField;
} elseif (!class_exists($modelClass)) {
throw new InvalidConfigException("The model class: `{$modelClass}` does not exists");
}
if (empty($pk)) {
$method = __METHOD__ . '()';
throw new NotFoundHttpException("{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}");
}
$_childrenIds = [];
$children = $modelClass::findAll([$parentField => $pk]);
while (count($children) > 0) {
$first = array_shift($children);
$_childrenIds[] = $first->$pkField;
$next = $modelClass::findAll([$parentField => $first->$pkField]);
if (count($next) > 0) {
$children = array_merge($children, $next);
}
}
return $_childrenIds;
}
|
php
|
public static function getChildrenIds($modelClass, $pk = 0, $pkField = 'id', $parentField = 'parent_id')
{
if ($modelClass instanceof ActiveRecord) {
if (!isset($modelClass->$pkField)) {
throw new InvalidConfigException("The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists");
}
$pk = $modelClass->$pkField;
} elseif (!class_exists($modelClass)) {
throw new InvalidConfigException("The model class: `{$modelClass}` does not exists");
}
if (empty($pk)) {
$method = __METHOD__ . '()';
throw new NotFoundHttpException("{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}");
}
$_childrenIds = [];
$children = $modelClass::findAll([$parentField => $pk]);
while (count($children) > 0) {
$first = array_shift($children);
$_childrenIds[] = $first->$pkField;
$next = $modelClass::findAll([$parentField => $first->$pkField]);
if (count($next) > 0) {
$children = array_merge($children, $next);
}
}
return $_childrenIds;
}
|
[
"public",
"static",
"function",
"getChildrenIds",
"(",
"$",
"modelClass",
",",
"$",
"pk",
"=",
"0",
",",
"$",
"pkField",
"=",
"'id'",
",",
"$",
"parentField",
"=",
"'parent_id'",
")",
"{",
"if",
"(",
"$",
"modelClass",
"instanceof",
"ActiveRecord",
")",
"{",
"if",
"(",
"!",
"isset",
"(",
"$",
"modelClass",
"->",
"$",
"pkField",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"The `{$pkField}` property of model class: `{$modelClass::className()}` does not exists\"",
")",
";",
"}",
"$",
"pk",
"=",
"$",
"modelClass",
"->",
"$",
"pkField",
";",
"}",
"elseif",
"(",
"!",
"class_exists",
"(",
"$",
"modelClass",
")",
")",
"{",
"throw",
"new",
"InvalidConfigException",
"(",
"\"The model class: `{$modelClass}` does not exists\"",
")",
";",
"}",
"if",
"(",
"empty",
"(",
"$",
"pk",
")",
")",
"{",
"$",
"method",
"=",
"__METHOD__",
".",
"'()'",
";",
"throw",
"new",
"NotFoundHttpException",
"(",
"\"{$modelClass::className()}()必须先通过`{$pkField}`主键获取相关数据后才能执行操作:{$method}\");",
"",
"",
"}",
"$",
"_childrenIds",
"=",
"[",
"]",
";",
"$",
"children",
"=",
"$",
"modelClass",
"::",
"findAll",
"(",
"[",
"$",
"parentField",
"=>",
"$",
"pk",
"]",
")",
";",
"while",
"(",
"count",
"(",
"$",
"children",
")",
">",
"0",
")",
"{",
"$",
"first",
"=",
"array_shift",
"(",
"$",
"children",
")",
";",
"$",
"_childrenIds",
"[",
"]",
"=",
"$",
"first",
"->",
"$",
"pkField",
";",
"$",
"next",
"=",
"$",
"modelClass",
"::",
"findAll",
"(",
"[",
"$",
"parentField",
"=>",
"$",
"first",
"->",
"$",
"pkField",
"]",
")",
";",
"if",
"(",
"count",
"(",
"$",
"next",
")",
">",
"0",
")",
"{",
"$",
"children",
"=",
"array_merge",
"(",
"$",
"children",
",",
"$",
"next",
")",
";",
"}",
"}",
"return",
"$",
"_childrenIds",
";",
"}"
] |
获取指定模型指定主键的所有子类ID数据
@param ActiveRecord|string $modelClass 模型对象或模型命名空间
@param integer $pk 待查询的主键值,仅在`$modelClass`为字符串时生效,否则会自动从`$modelClass`对象处获取
@param string $pkField 主键字段
@param string $parentField 父级字段
@return array
@throws InvalidConfigException
@throws NotFoundHttpException
|
[
"获取指定模型指定主键的所有子类ID数据"
] |
train
|
https://github.com/Wonail/wocenter/blob/186c15aad008d32fbf5ad75256cf01581dccf9e6/libs/Tree.php#L79-L107
|
crossjoin/Css
|
src/Crossjoin/Css/Reader/ReaderAbstract.php
|
ReaderAbstract.getPreparedCssContent
|
protected function getPreparedCssContent()
{
if ($this->preparedContent === null) {
$this->preparedContent = Placeholder::replaceStringsAndComments($this->getCssContent());
// Move comments from the end of the line to the beginning to make it easier to
// detect, to which rule they belong to
$this->preparedContent = preg_replace(
'/^([^\r\n]+)(_COMMENT_[a-f0-9]{32}_)([\r\n\t\f]+)/m',
"\\2\n\\1\\3",
$this->preparedContent
);
// Remove white space characters before comments
$this->preparedContent = preg_replace(
'/^([ \t\f]*)(_COMMENT_[a-f0-9]{32}_)/m',
"\\2\n",
$this->preparedContent
);
// Very important: Split long lines, because parsing long lines (char by char) costs a lot performance
// (several thousand percent...).
$this->preparedContent = str_replace(["{", "}", ";"], ["{\n", "}\n", ";\n"], $this->preparedContent);
}
return $this->preparedContent;
}
|
php
|
protected function getPreparedCssContent()
{
if ($this->preparedContent === null) {
$this->preparedContent = Placeholder::replaceStringsAndComments($this->getCssContent());
// Move comments from the end of the line to the beginning to make it easier to
// detect, to which rule they belong to
$this->preparedContent = preg_replace(
'/^([^\r\n]+)(_COMMENT_[a-f0-9]{32}_)([\r\n\t\f]+)/m',
"\\2\n\\1\\3",
$this->preparedContent
);
// Remove white space characters before comments
$this->preparedContent = preg_replace(
'/^([ \t\f]*)(_COMMENT_[a-f0-9]{32}_)/m',
"\\2\n",
$this->preparedContent
);
// Very important: Split long lines, because parsing long lines (char by char) costs a lot performance
// (several thousand percent...).
$this->preparedContent = str_replace(["{", "}", ";"], ["{\n", "}\n", ";\n"], $this->preparedContent);
}
return $this->preparedContent;
}
|
[
"protected",
"function",
"getPreparedCssContent",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"preparedContent",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"preparedContent",
"=",
"Placeholder",
"::",
"replaceStringsAndComments",
"(",
"$",
"this",
"->",
"getCssContent",
"(",
")",
")",
";",
"// Move comments from the end of the line to the beginning to make it easier to",
"// detect, to which rule they belong to",
"$",
"this",
"->",
"preparedContent",
"=",
"preg_replace",
"(",
"'/^([^\\r\\n]+)(_COMMENT_[a-f0-9]{32}_)([\\r\\n\\t\\f]+)/m'",
",",
"\"\\\\2\\n\\\\1\\\\3\"",
",",
"$",
"this",
"->",
"preparedContent",
")",
";",
"// Remove white space characters before comments",
"$",
"this",
"->",
"preparedContent",
"=",
"preg_replace",
"(",
"'/^([ \\t\\f]*)(_COMMENT_[a-f0-9]{32}_)/m'",
",",
"\"\\\\2\\n\"",
",",
"$",
"this",
"->",
"preparedContent",
")",
";",
"// Very important: Split long lines, because parsing long lines (char by char) costs a lot performance",
"// (several thousand percent...).",
"$",
"this",
"->",
"preparedContent",
"=",
"str_replace",
"(",
"[",
"\"{\"",
",",
"\"}\"",
",",
"\";\"",
"]",
",",
"[",
"\"{\\n\"",
",",
"\"}\\n\"",
",",
"\";\\n\"",
"]",
",",
"$",
"this",
"->",
"preparedContent",
")",
";",
"}",
"return",
"$",
"this",
"->",
"preparedContent",
";",
"}"
] |
Gets a prepared version of the CSS content for parsing.
@return string
|
[
"Gets",
"a",
"prepared",
"version",
"of",
"the",
"CSS",
"content",
"for",
"parsing",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L72-L98
|
crossjoin/Css
|
src/Crossjoin/Css/Reader/ReaderAbstract.php
|
ReaderAbstract.getCssResource
|
protected function getCssResource()
{
$handle = fopen("php://memory", "rw");
fputs($handle, $this->getPreparedCssContent());
rewind($handle);
return $handle;
}
|
php
|
protected function getCssResource()
{
$handle = fopen("php://memory", "rw");
fputs($handle, $this->getPreparedCssContent());
rewind($handle);
return $handle;
}
|
[
"protected",
"function",
"getCssResource",
"(",
")",
"{",
"$",
"handle",
"=",
"fopen",
"(",
"\"php://memory\"",
",",
"\"rw\"",
")",
";",
"fputs",
"(",
"$",
"handle",
",",
"$",
"this",
"->",
"getPreparedCssContent",
"(",
")",
")",
";",
"rewind",
"(",
"$",
"handle",
")",
";",
"return",
"$",
"handle",
";",
"}"
] |
Gets the CSS content as resource.
@return resource
|
[
"Gets",
"the",
"CSS",
"content",
"as",
"resource",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L105-L112
|
crossjoin/Css
|
src/Crossjoin/Css/Reader/ReaderAbstract.php
|
ReaderAbstract.setProtocolEncoding
|
protected function setProtocolEncoding($encoding)
{
if (is_string($encoding)) {
if (in_array($encoding, mb_list_encodings())) {
$this->protocolEncoding = $encoding;
} else {
throw new \InvalidArgumentException(
"Invalid value '" . $encoding . "' for argument 'encoding' given. Encoding not supported."
);
}
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($encoding). "' for argument 'encoding' given."
);
}
return $this;
}
|
php
|
protected function setProtocolEncoding($encoding)
{
if (is_string($encoding)) {
if (in_array($encoding, mb_list_encodings())) {
$this->protocolEncoding = $encoding;
} else {
throw new \InvalidArgumentException(
"Invalid value '" . $encoding . "' for argument 'encoding' given. Encoding not supported."
);
}
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($encoding). "' for argument 'encoding' given."
);
}
return $this;
}
|
[
"protected",
"function",
"setProtocolEncoding",
"(",
"$",
"encoding",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"encoding",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"encoding",
",",
"mb_list_encodings",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"protocolEncoding",
"=",
"$",
"encoding",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid value '\"",
".",
"$",
"encoding",
".",
"\"' for argument 'encoding' given. Encoding not supported.\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid type '\"",
".",
"gettype",
"(",
"$",
"encoding",
")",
".",
"\"' for argument 'encoding' given.\"",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Set the encoding of the CSS file, as defined in HTTP (Content-Type header) or equivalent protocol,
when the CSS was loaded from an external source. This is used as a fall back value to determine
the charset of the CSS file.
@param string $encoding
@return $this
|
[
"Set",
"the",
"encoding",
"of",
"the",
"CSS",
"file",
"as",
"defined",
"in",
"HTTP",
"(",
"Content",
"-",
"Type",
"header",
")",
"or",
"equivalent",
"protocol",
"when",
"the",
"CSS",
"was",
"loaded",
"from",
"an",
"external",
"source",
".",
"This",
"is",
"used",
"as",
"a",
"fall",
"back",
"value",
"to",
"determine",
"the",
"charset",
"of",
"the",
"CSS",
"file",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L145-L162
|
crossjoin/Css
|
src/Crossjoin/Css/Reader/ReaderAbstract.php
|
ReaderAbstract.setEnvironmentEncoding
|
public function setEnvironmentEncoding($encoding)
{
if (is_string($encoding)) {
if (in_array($encoding, mb_list_encodings())) {
$this->environmentEncoding = $encoding;
} else {
throw new \InvalidArgumentException(
"Invalid value '" . $encoding . "' for argument 'encoding' given. Encoding not supported."
);
}
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($encoding). "' for argument 'encoding' given."
);
}
return $this;
}
|
php
|
public function setEnvironmentEncoding($encoding)
{
if (is_string($encoding)) {
if (in_array($encoding, mb_list_encodings())) {
$this->environmentEncoding = $encoding;
} else {
throw new \InvalidArgumentException(
"Invalid value '" . $encoding . "' for argument 'encoding' given. Encoding not supported."
);
}
} else {
throw new \InvalidArgumentException(
"Invalid type '" . gettype($encoding). "' for argument 'encoding' given."
);
}
return $this;
}
|
[
"public",
"function",
"setEnvironmentEncoding",
"(",
"$",
"encoding",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"encoding",
")",
")",
"{",
"if",
"(",
"in_array",
"(",
"$",
"encoding",
",",
"mb_list_encodings",
"(",
")",
")",
")",
"{",
"$",
"this",
"->",
"environmentEncoding",
"=",
"$",
"encoding",
";",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid value '\"",
".",
"$",
"encoding",
".",
"\"' for argument 'encoding' given. Encoding not supported.\"",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid type '\"",
".",
"gettype",
"(",
"$",
"encoding",
")",
".",
"\"' for argument 'encoding' given.\"",
")",
";",
"}",
"return",
"$",
"this",
";",
"}"
] |
Sets the environment encoding of the referencing (!) document, e.g. if defined in a link tag of an HTML page.
This is used as a fall back value to determine the charset of the CSS file.
@param string $encoding
@return $this
|
[
"Sets",
"the",
"environment",
"encoding",
"of",
"the",
"referencing",
"(",
"!",
")",
"document",
"e",
".",
"g",
".",
"if",
"defined",
"in",
"a",
"link",
"tag",
"of",
"an",
"HTML",
"page",
".",
"This",
"is",
"used",
"as",
"a",
"fall",
"back",
"value",
"to",
"determine",
"the",
"charset",
"of",
"the",
"CSS",
"file",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L183-L200
|
crossjoin/Css
|
src/Crossjoin/Css/Reader/ReaderAbstract.php
|
ReaderAbstract.parseCss
|
protected function parseCss()
{
// Init variables
$this->styleSheet = new StyleSheet();
$cssContent = "";
// Prepare CSS content to allow easy parsing;
// temporarily replace all strings.
$blockCount = 0;
$ruleCount = 0;
$ruleBlock = 0;
$inBrackets = false;
$charsetIgnored = true;
$charsetReplaced = false;
if (($handle = $this->getCssResource()) !== false) {
// Determine charset in the correct order, defined in
// http://www.w3.org/TR/css-syntax-3/#input-byte-stream
$charset = null;
$fileContainsBom = false;
if (($firstLine = fgets($handle)) === false) {
$firstLine = "";
}
// Check for a BOM and use it, if it exists. "The decode algorithm gives precedence to a byte order mark
// (BOM), and only uses the fallback when none is found."
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (strlen($firstLine) >= 3 && strncmp($firstLine, $bom, 3) === 0) {
$charset = "UTF-8";
$fileContainsBom = true;
} else {
// Fallback 1: The encoding defined in HTTP or equivalent protocol
$charset = $this->getProtocolEncoding();
// Fallback 2: The charset as defined in the CSS file
if ($charset === null) {
if (preg_match('/^@charset\s+(["\'])([-a-zA-Z0-9_]+)\g{1}/i', $firstLine, $matches)) {
$charset = $matches[2];
$charsetIgnored = false;
// Auto-correction of the defined charset.
//"If the return value was utf-16be or utf-16le, use utf-8 as the fallback encoding".
if (in_array(strtoupper($charset), ["UTF-16BE", "UTF-16LE"])) {
$charset = "UTF-8";
$charsetReplaced = true;
}
}
}
// Fallback 3: The environment encoding of the referencing document
if ($charset === null) {
$charset = $this->getEnvironmentEncoding();
}
// Fallback 4: Default to UTF-8
if ($charset === null) {
$charset = "UTF-8";
}
}
$this->setCharset($charset);
// Set position back to the beginning (but skip BOMs)
fseek($handle, ($fileContainsBom?3:0));
while (($css = fgets($handle)) !== false) {
// Required check to avoid errors when the encoding of the
// file doesn't match the set/detected charset.
if (mb_check_encoding($css, $charset) === false) {
throw new \RuntimeException("Invalid '$charset' encoding in CSS file.");
}
if (preg_match('/[^\x00-\x7f]/', $css)) {
$isAscii = false;
$strLen = mb_strlen($css, $charset);
} else {
$isAscii = true;
$strLen = strlen($css);
}
for ($i = 0, $j = $strLen; $i < $j; $i++) {
if ($isAscii === true) {
$char = $css[$i];
} else {
$char = mb_substr($css, $i, 1, $charset);
}
if ($char === "{") {
$blockCount++;
$cssContent .= "\n_BLOCKSTART_" . $blockCount . "_\n";
if ($ruleCount > $ruleBlock) {
$ruleBlock++;
}
} else if ($char === "}") {
$cssContent .= "\n_BLOCKEND_" . $blockCount . "_\n";
$blockCount--;
if ($blockCount < $ruleCount) {
if ($ruleCount > 0) {
$cssContent .= "\n_RULEEND_" . $ruleCount . "_\n";
$ruleCount--;
}
}
if ($ruleCount > 0) {
$ruleBlock--;
}
} elseif ($char === ";") {
$cssContent .= $char;
if ($ruleCount > 0 && $ruleBlock === 0) {
$cssContent .= "\n_RULEEND_1_\n";
$ruleCount--;
}
} else {
// Start new at-rule, but only if we are not in brackets, which still can occur, although we
// replaced all strings, e.g. in this case: "background: url(/images/[email protected])".
if ($char === "@" && $inBrackets === false) {
if ($ruleCount > 0 && $blockCount === 0) {
$errorCss = Placeholder::replaceCommentPlaceholders(
Placeholder::replaceStringPlaceholders($css)
);
throw new \RuntimeException("Parse error near '$errorCss'.");
}
$ruleCount++;
$cssContent .= "\n_RULESTART_" . $ruleCount . "_\n";
// Replace all white-space characters within rule definitions by normal space to get
// one line only
} elseif ($ruleCount >= $blockCount && in_array($char, ["\r", "\n", "\t", "\f"])) {
$char = " ";
} elseif ($char === "(") {
$inBrackets = true;
} elseif ($char === ")") {
$inBrackets = false;
}
$cssContent .= $char;
}
}
}
// Auto-correction as required by CSS specs
while ($blockCount > 0) {
$cssContent .= "\n_BLOCKEND_" . $blockCount . "_\n";
$blockCount--;
}
while ($ruleCount > 0) {
$cssContent .= "\n_RULEEND_" . $ruleCount . "_\n";
$ruleCount--;
}
}
// Prettify...
$cssContent = preg_replace('/;/', ";\n", $cssContent);
$cssContent = preg_replace('/[\t\f]+/', "", $cssContent);
$cssContent = preg_replace('/[ ]+/', " ", $cssContent);
$cssContent = preg_replace('/(\n)[ ]|[ ](\n)/', "\\1\\2", $cssContent);
$cssContent = preg_replace('/(?<!_)[ \t\n\r\f]*(:)[ \t\n\r\f]*/', "\\1", $cssContent);
$cssContent = preg_replace('/([\r\n])+/', "\\1", $cssContent);
$cssContent = preg_replace('/^\n|\n$/', "", $cssContent);
$cssContent = preg_replace('/^(_COMMENT_[a-f0-9]{32}_)([^\r\n]+)/m', "\\1\n\\2", $cssContent);
// Parse
$lines = explode("\n", $cssContent);
$ruleCount = 0;
$blockCount = 0;
$lastRuleContainers = [$this->styleSheet];
$lastRuleSet = null;
// Prepare vendor prefix regular expression
$vendorPrefixRegExp = RuleAbstract::getVendorPrefixRegExp("/");
$comment = null;
$atRuleCharsetAllowed = true;
$atRuleImportAllowed = true;
$atRuleNamespaceAllowed = true;
foreach ($lines as $line) {
if (preg_match(
'/^(?J)(?:_(?P<type>RULESTART|RULEEND|BLOCKSTART|BLOCKEND)_\d+_|_(?P<type>COMMENT)_[a-f0-9]{32}_)/',
$line,
$matches
)) {
if ($matches['type'] === 'RULESTART') {
$ruleCount++;
} elseif ($matches['type'] === 'RULEEND') {
$ruleCount--;
if ($ruleCount === $blockCount) {
// Current rule finished
}
} elseif ($matches['type'] === 'BLOCKSTART') {
$blockCount++;
} elseif ($matches['type'] === 'BLOCKEND') {
$blockCount--;
if ($blockCount === $ruleCount) {
if ($comment !== null) {
/** @var AtRuleAbstract $lastRuleSet */
$lastRuleSet->addComment($comment);
$comment = null;
}
// Current rule set finished
$lastRuleSet = null;
} else {
if ($comment !== null) {
/** @var AtRuleAbstract[] $lastRuleContainers */
$lastRuleContainers[$ruleCount]->addComment($comment);
$comment = null;
}
}
} elseif ($matches['type'] === 'COMMENT') {
$comment = rtrim($line);
}
} else {
if ($blockCount < $ruleCount) {
// New rule opened
if (preg_match(
'/^@(' . $vendorPrefixRegExp . ')?([a-zA-Z_]{1}(?:[-a-zA-Z0-9_]*|[^[:ascii:]*]))/i',
trim($line),
$matches
)) {
$identifier = mb_strtolower($matches[2], $this->getCharset());
switch($identifier) {
case "charset":
$atRule = new CharsetRule($line, $this->styleSheet);
break;
case "import":
$atRule = new ImportRule($line, $this->styleSheet);
break;
case "namespace":
$atRule = new NamespaceRule($line, $this->styleSheet);
break;
case "media":
$atRule = new MediaRule($line, $this->styleSheet);
break;
case "supports":
$atRule = new SupportsRule($line, $this->styleSheet);
break;
case "document":
$atRule = new DocumentRule($line, $this->styleSheet);
break;
case "font-face":
$atRule = new FontFaceRule($line, $this->styleSheet);
break;
case "page":
$atRule = new PageRule($line, $this->styleSheet);
break;
case "keyframes":
$atRule = new KeyframesRule($line, $this->styleSheet);
break;
default:
throw new \InvalidArgumentException("Unknown at rule identifier '$identifier'.");
}
// Add vendor prefix
if ($matches[1] !== "") {
$vendorPrefix = mb_strtolower($matches[1], $this->getCharset());
$atRule->setVendorPrefix($vendorPrefix);
}
} else {
throw new \InvalidArgumentException("Invalid rule format in '$line'.");
}
// IMPORTANT:
// - The @charset rule must be the first element in the style sheet and not be preceded by any
// character.
// - Any @import rules must precede all other types of rules, except @charset rules (and other
// @import rules).
// - Any @namespace rules must follow all @charset and @import rules (and other @namespace rules)
// and precede all other non-ignored at-rules and style rules in a style-sheet.
if ($atRule instanceof CharsetRule) {
if ($atRuleCharsetAllowed === false) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the
// style sheet. E.g. @charset must be the first content of the file, @import must be first
// or follow @charset or @import, and @namespace can only follow to @charset, @import or
// @namespace.
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @charset rule, because at wrong position in style sheet."
);
} elseif ($charsetIgnored === true) {
// As defined by CSS specs, the charset rule has been ignored, due to charset information
// from other sources (e.g. BOMs in the file or defined protocol encoding).
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @charset rule, because charset got from other source with higher priority."
);
$atRuleCharsetAllowed = false;
} elseif ($charsetReplaced === true) {
// As defined by CSS specs, the charset defined by the charset rule has been replaced with
// "UTF-8", because an UTF-16* charset has been used.
$atRule->setIsValid(false);
$atRule->addValidationError(
"Replaced charset in @charset rule with 'UTF-8', because defined charset is invalid."
);
$atRuleCharsetAllowed = false;
} else {
$atRuleCharsetAllowed = false;
}
} elseif ($atRule instanceof ImportRule) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style
// sheet. E.g. @charset must be the first content of the file, @import must be first or follow
// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.
if ($atRuleImportAllowed === false) {
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @import rule, because at wrong position in style sheet."
);
}
$atRuleCharsetAllowed = false;
} elseif ($atRule instanceof NamespaceRule) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style
// sheet. E.g. @charset must be the first content of the file, @import must be first or follow
// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.
if ($atRuleNamespaceAllowed === false) {
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @namespace rule, because at wrong position in style sheet."
);
}
$atRuleCharsetAllowed = false;
$atRuleImportAllowed = false;
} else {
$atRuleCharsetAllowed = false;
$atRuleImportAllowed = false;
$atRuleNamespaceAllowed = false;
}
$lastRuleContainers[$ruleCount-1]->addRule($atRule);
if ($atRule instanceof AtRuleConditionalAbstract) {
$lastRuleContainers[$ruleCount] = $atRule;
} elseif ($atRule instanceof KeyframesRule) {
$lastRuleContainers[$ruleCount] = $atRule;
} elseif ($atRule instanceof FontFaceRule) {
$lastRuleContainers[$ruleCount] = $atRule;
$lastRuleSet = $atRule;
} elseif ($atRule instanceof PageRule) {
$lastRuleContainers[$ruleCount] = $atRule;
$lastRuleSet = $atRule;
}
// Not all at-rules contain other rule, e.g. in @page rules the rules are mixed with the
// at-rule, so they directly contain declarations - this is filtered by checking for the
// HasRulesInterface here.
} elseif ($blockCount === $ruleCount && $lastRuleContainers[$ruleCount] instanceof HasRulesInterface) {
// New rule set opened
if ($lastRuleContainers[$ruleCount] instanceof KeyframesRule) {
$ruleSet = new KeyframesRuleSet($line, $this->styleSheet);
} else {
$ruleSet = new StyleRuleSet($line, $this->styleSheet);
}
if ($comment !== null) {
$ruleSet->addComment($comment);
$comment = null;
}
$lastRuleContainers[$ruleCount]->addRule($ruleSet);
$lastRuleSet = $ruleSet;
$atRuleCharsetAllowed = false;
} elseif ($blockCount >= $ruleCount) {
// New declaration
if ($lastRuleSet !== null) {
$line = preg_replace('/[\s;]+$/', '', $line);
$invalidDeclaration = false;
if (strpos($line, ":") === false) {
$property = $line;
$value = "";
$invalidDeclaration = true;
} else {
list($property, $value) = explode(":", $line, 2);
}
$declaration = null;
if ($lastRuleContainers[$ruleCount] instanceof StyleSheet) {
$declaration = new StyleDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof AtRuleConditionalAbstract) {
$declaration = new StyleDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof KeyframesRule) {
$declaration = new KeyframesDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof FontFaceRule) {
$declaration = new FontFaceDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof PageRule) {
$declaration = new PageDeclaration($property, $value, $this->styleSheet);
}
if ($declaration !== null) {
if ($comment !== null) {
$declaration->addComment($comment);
$comment = null;
}
if ($invalidDeclaration === true) {
$declaration->setIsValid(false);
$declaration->addValidationError("Parse error. Invalid declaration at '$line'.");
}
$lastRuleSet->addDeclaration($declaration);
}
}
$atRuleCharsetAllowed = false;
}
}
}
}
|
php
|
protected function parseCss()
{
// Init variables
$this->styleSheet = new StyleSheet();
$cssContent = "";
// Prepare CSS content to allow easy parsing;
// temporarily replace all strings.
$blockCount = 0;
$ruleCount = 0;
$ruleBlock = 0;
$inBrackets = false;
$charsetIgnored = true;
$charsetReplaced = false;
if (($handle = $this->getCssResource()) !== false) {
// Determine charset in the correct order, defined in
// http://www.w3.org/TR/css-syntax-3/#input-byte-stream
$charset = null;
$fileContainsBom = false;
if (($firstLine = fgets($handle)) === false) {
$firstLine = "";
}
// Check for a BOM and use it, if it exists. "The decode algorithm gives precedence to a byte order mark
// (BOM), and only uses the fallback when none is found."
$bom = pack("CCC", 0xef, 0xbb, 0xbf);
if (strlen($firstLine) >= 3 && strncmp($firstLine, $bom, 3) === 0) {
$charset = "UTF-8";
$fileContainsBom = true;
} else {
// Fallback 1: The encoding defined in HTTP or equivalent protocol
$charset = $this->getProtocolEncoding();
// Fallback 2: The charset as defined in the CSS file
if ($charset === null) {
if (preg_match('/^@charset\s+(["\'])([-a-zA-Z0-9_]+)\g{1}/i', $firstLine, $matches)) {
$charset = $matches[2];
$charsetIgnored = false;
// Auto-correction of the defined charset.
//"If the return value was utf-16be or utf-16le, use utf-8 as the fallback encoding".
if (in_array(strtoupper($charset), ["UTF-16BE", "UTF-16LE"])) {
$charset = "UTF-8";
$charsetReplaced = true;
}
}
}
// Fallback 3: The environment encoding of the referencing document
if ($charset === null) {
$charset = $this->getEnvironmentEncoding();
}
// Fallback 4: Default to UTF-8
if ($charset === null) {
$charset = "UTF-8";
}
}
$this->setCharset($charset);
// Set position back to the beginning (but skip BOMs)
fseek($handle, ($fileContainsBom?3:0));
while (($css = fgets($handle)) !== false) {
// Required check to avoid errors when the encoding of the
// file doesn't match the set/detected charset.
if (mb_check_encoding($css, $charset) === false) {
throw new \RuntimeException("Invalid '$charset' encoding in CSS file.");
}
if (preg_match('/[^\x00-\x7f]/', $css)) {
$isAscii = false;
$strLen = mb_strlen($css, $charset);
} else {
$isAscii = true;
$strLen = strlen($css);
}
for ($i = 0, $j = $strLen; $i < $j; $i++) {
if ($isAscii === true) {
$char = $css[$i];
} else {
$char = mb_substr($css, $i, 1, $charset);
}
if ($char === "{") {
$blockCount++;
$cssContent .= "\n_BLOCKSTART_" . $blockCount . "_\n";
if ($ruleCount > $ruleBlock) {
$ruleBlock++;
}
} else if ($char === "}") {
$cssContent .= "\n_BLOCKEND_" . $blockCount . "_\n";
$blockCount--;
if ($blockCount < $ruleCount) {
if ($ruleCount > 0) {
$cssContent .= "\n_RULEEND_" . $ruleCount . "_\n";
$ruleCount--;
}
}
if ($ruleCount > 0) {
$ruleBlock--;
}
} elseif ($char === ";") {
$cssContent .= $char;
if ($ruleCount > 0 && $ruleBlock === 0) {
$cssContent .= "\n_RULEEND_1_\n";
$ruleCount--;
}
} else {
// Start new at-rule, but only if we are not in brackets, which still can occur, although we
// replaced all strings, e.g. in this case: "background: url(/images/[email protected])".
if ($char === "@" && $inBrackets === false) {
if ($ruleCount > 0 && $blockCount === 0) {
$errorCss = Placeholder::replaceCommentPlaceholders(
Placeholder::replaceStringPlaceholders($css)
);
throw new \RuntimeException("Parse error near '$errorCss'.");
}
$ruleCount++;
$cssContent .= "\n_RULESTART_" . $ruleCount . "_\n";
// Replace all white-space characters within rule definitions by normal space to get
// one line only
} elseif ($ruleCount >= $blockCount && in_array($char, ["\r", "\n", "\t", "\f"])) {
$char = " ";
} elseif ($char === "(") {
$inBrackets = true;
} elseif ($char === ")") {
$inBrackets = false;
}
$cssContent .= $char;
}
}
}
// Auto-correction as required by CSS specs
while ($blockCount > 0) {
$cssContent .= "\n_BLOCKEND_" . $blockCount . "_\n";
$blockCount--;
}
while ($ruleCount > 0) {
$cssContent .= "\n_RULEEND_" . $ruleCount . "_\n";
$ruleCount--;
}
}
// Prettify...
$cssContent = preg_replace('/;/', ";\n", $cssContent);
$cssContent = preg_replace('/[\t\f]+/', "", $cssContent);
$cssContent = preg_replace('/[ ]+/', " ", $cssContent);
$cssContent = preg_replace('/(\n)[ ]|[ ](\n)/', "\\1\\2", $cssContent);
$cssContent = preg_replace('/(?<!_)[ \t\n\r\f]*(:)[ \t\n\r\f]*/', "\\1", $cssContent);
$cssContent = preg_replace('/([\r\n])+/', "\\1", $cssContent);
$cssContent = preg_replace('/^\n|\n$/', "", $cssContent);
$cssContent = preg_replace('/^(_COMMENT_[a-f0-9]{32}_)([^\r\n]+)/m', "\\1\n\\2", $cssContent);
// Parse
$lines = explode("\n", $cssContent);
$ruleCount = 0;
$blockCount = 0;
$lastRuleContainers = [$this->styleSheet];
$lastRuleSet = null;
// Prepare vendor prefix regular expression
$vendorPrefixRegExp = RuleAbstract::getVendorPrefixRegExp("/");
$comment = null;
$atRuleCharsetAllowed = true;
$atRuleImportAllowed = true;
$atRuleNamespaceAllowed = true;
foreach ($lines as $line) {
if (preg_match(
'/^(?J)(?:_(?P<type>RULESTART|RULEEND|BLOCKSTART|BLOCKEND)_\d+_|_(?P<type>COMMENT)_[a-f0-9]{32}_)/',
$line,
$matches
)) {
if ($matches['type'] === 'RULESTART') {
$ruleCount++;
} elseif ($matches['type'] === 'RULEEND') {
$ruleCount--;
if ($ruleCount === $blockCount) {
// Current rule finished
}
} elseif ($matches['type'] === 'BLOCKSTART') {
$blockCount++;
} elseif ($matches['type'] === 'BLOCKEND') {
$blockCount--;
if ($blockCount === $ruleCount) {
if ($comment !== null) {
/** @var AtRuleAbstract $lastRuleSet */
$lastRuleSet->addComment($comment);
$comment = null;
}
// Current rule set finished
$lastRuleSet = null;
} else {
if ($comment !== null) {
/** @var AtRuleAbstract[] $lastRuleContainers */
$lastRuleContainers[$ruleCount]->addComment($comment);
$comment = null;
}
}
} elseif ($matches['type'] === 'COMMENT') {
$comment = rtrim($line);
}
} else {
if ($blockCount < $ruleCount) {
// New rule opened
if (preg_match(
'/^@(' . $vendorPrefixRegExp . ')?([a-zA-Z_]{1}(?:[-a-zA-Z0-9_]*|[^[:ascii:]*]))/i',
trim($line),
$matches
)) {
$identifier = mb_strtolower($matches[2], $this->getCharset());
switch($identifier) {
case "charset":
$atRule = new CharsetRule($line, $this->styleSheet);
break;
case "import":
$atRule = new ImportRule($line, $this->styleSheet);
break;
case "namespace":
$atRule = new NamespaceRule($line, $this->styleSheet);
break;
case "media":
$atRule = new MediaRule($line, $this->styleSheet);
break;
case "supports":
$atRule = new SupportsRule($line, $this->styleSheet);
break;
case "document":
$atRule = new DocumentRule($line, $this->styleSheet);
break;
case "font-face":
$atRule = new FontFaceRule($line, $this->styleSheet);
break;
case "page":
$atRule = new PageRule($line, $this->styleSheet);
break;
case "keyframes":
$atRule = new KeyframesRule($line, $this->styleSheet);
break;
default:
throw new \InvalidArgumentException("Unknown at rule identifier '$identifier'.");
}
// Add vendor prefix
if ($matches[1] !== "") {
$vendorPrefix = mb_strtolower($matches[1], $this->getCharset());
$atRule->setVendorPrefix($vendorPrefix);
}
} else {
throw new \InvalidArgumentException("Invalid rule format in '$line'.");
}
// IMPORTANT:
// - The @charset rule must be the first element in the style sheet and not be preceded by any
// character.
// - Any @import rules must precede all other types of rules, except @charset rules (and other
// @import rules).
// - Any @namespace rules must follow all @charset and @import rules (and other @namespace rules)
// and precede all other non-ignored at-rules and style rules in a style-sheet.
if ($atRule instanceof CharsetRule) {
if ($atRuleCharsetAllowed === false) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the
// style sheet. E.g. @charset must be the first content of the file, @import must be first
// or follow @charset or @import, and @namespace can only follow to @charset, @import or
// @namespace.
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @charset rule, because at wrong position in style sheet."
);
} elseif ($charsetIgnored === true) {
// As defined by CSS specs, the charset rule has been ignored, due to charset information
// from other sources (e.g. BOMs in the file or defined protocol encoding).
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @charset rule, because charset got from other source with higher priority."
);
$atRuleCharsetAllowed = false;
} elseif ($charsetReplaced === true) {
// As defined by CSS specs, the charset defined by the charset rule has been replaced with
// "UTF-8", because an UTF-16* charset has been used.
$atRule->setIsValid(false);
$atRule->addValidationError(
"Replaced charset in @charset rule with 'UTF-8', because defined charset is invalid."
);
$atRuleCharsetAllowed = false;
} else {
$atRuleCharsetAllowed = false;
}
} elseif ($atRule instanceof ImportRule) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style
// sheet. E.g. @charset must be the first content of the file, @import must be first or follow
// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.
if ($atRuleImportAllowed === false) {
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @import rule, because at wrong position in style sheet."
);
}
$atRuleCharsetAllowed = false;
} elseif ($atRule instanceof NamespaceRule) {
// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style
// sheet. E.g. @charset must be the first content of the file, @import must be first or follow
// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.
if ($atRuleNamespaceAllowed === false) {
$atRule->setIsValid(false);
$atRule->addValidationError(
"Ignored @namespace rule, because at wrong position in style sheet."
);
}
$atRuleCharsetAllowed = false;
$atRuleImportAllowed = false;
} else {
$atRuleCharsetAllowed = false;
$atRuleImportAllowed = false;
$atRuleNamespaceAllowed = false;
}
$lastRuleContainers[$ruleCount-1]->addRule($atRule);
if ($atRule instanceof AtRuleConditionalAbstract) {
$lastRuleContainers[$ruleCount] = $atRule;
} elseif ($atRule instanceof KeyframesRule) {
$lastRuleContainers[$ruleCount] = $atRule;
} elseif ($atRule instanceof FontFaceRule) {
$lastRuleContainers[$ruleCount] = $atRule;
$lastRuleSet = $atRule;
} elseif ($atRule instanceof PageRule) {
$lastRuleContainers[$ruleCount] = $atRule;
$lastRuleSet = $atRule;
}
// Not all at-rules contain other rule, e.g. in @page rules the rules are mixed with the
// at-rule, so they directly contain declarations - this is filtered by checking for the
// HasRulesInterface here.
} elseif ($blockCount === $ruleCount && $lastRuleContainers[$ruleCount] instanceof HasRulesInterface) {
// New rule set opened
if ($lastRuleContainers[$ruleCount] instanceof KeyframesRule) {
$ruleSet = new KeyframesRuleSet($line, $this->styleSheet);
} else {
$ruleSet = new StyleRuleSet($line, $this->styleSheet);
}
if ($comment !== null) {
$ruleSet->addComment($comment);
$comment = null;
}
$lastRuleContainers[$ruleCount]->addRule($ruleSet);
$lastRuleSet = $ruleSet;
$atRuleCharsetAllowed = false;
} elseif ($blockCount >= $ruleCount) {
// New declaration
if ($lastRuleSet !== null) {
$line = preg_replace('/[\s;]+$/', '', $line);
$invalidDeclaration = false;
if (strpos($line, ":") === false) {
$property = $line;
$value = "";
$invalidDeclaration = true;
} else {
list($property, $value) = explode(":", $line, 2);
}
$declaration = null;
if ($lastRuleContainers[$ruleCount] instanceof StyleSheet) {
$declaration = new StyleDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof AtRuleConditionalAbstract) {
$declaration = new StyleDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof KeyframesRule) {
$declaration = new KeyframesDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof FontFaceRule) {
$declaration = new FontFaceDeclaration($property, $value, $this->styleSheet);
} elseif ($lastRuleContainers[$ruleCount] instanceof PageRule) {
$declaration = new PageDeclaration($property, $value, $this->styleSheet);
}
if ($declaration !== null) {
if ($comment !== null) {
$declaration->addComment($comment);
$comment = null;
}
if ($invalidDeclaration === true) {
$declaration->setIsValid(false);
$declaration->addValidationError("Parse error. Invalid declaration at '$line'.");
}
$lastRuleSet->addDeclaration($declaration);
}
}
$atRuleCharsetAllowed = false;
}
}
}
}
|
[
"protected",
"function",
"parseCss",
"(",
")",
"{",
"// Init variables",
"$",
"this",
"->",
"styleSheet",
"=",
"new",
"StyleSheet",
"(",
")",
";",
"$",
"cssContent",
"=",
"\"\"",
";",
"// Prepare CSS content to allow easy parsing;",
"// temporarily replace all strings.",
"$",
"blockCount",
"=",
"0",
";",
"$",
"ruleCount",
"=",
"0",
";",
"$",
"ruleBlock",
"=",
"0",
";",
"$",
"inBrackets",
"=",
"false",
";",
"$",
"charsetIgnored",
"=",
"true",
";",
"$",
"charsetReplaced",
"=",
"false",
";",
"if",
"(",
"(",
"$",
"handle",
"=",
"$",
"this",
"->",
"getCssResource",
"(",
")",
")",
"!==",
"false",
")",
"{",
"// Determine charset in the correct order, defined in",
"// http://www.w3.org/TR/css-syntax-3/#input-byte-stream",
"$",
"charset",
"=",
"null",
";",
"$",
"fileContainsBom",
"=",
"false",
";",
"if",
"(",
"(",
"$",
"firstLine",
"=",
"fgets",
"(",
"$",
"handle",
")",
")",
"===",
"false",
")",
"{",
"$",
"firstLine",
"=",
"\"\"",
";",
"}",
"// Check for a BOM and use it, if it exists. \"The decode algorithm gives precedence to a byte order mark",
"// (BOM), and only uses the fallback when none is found.\"",
"$",
"bom",
"=",
"pack",
"(",
"\"CCC\"",
",",
"0xef",
",",
"0xbb",
",",
"0xbf",
")",
";",
"if",
"(",
"strlen",
"(",
"$",
"firstLine",
")",
">=",
"3",
"&&",
"strncmp",
"(",
"$",
"firstLine",
",",
"$",
"bom",
",",
"3",
")",
"===",
"0",
")",
"{",
"$",
"charset",
"=",
"\"UTF-8\"",
";",
"$",
"fileContainsBom",
"=",
"true",
";",
"}",
"else",
"{",
"// Fallback 1: The encoding defined in HTTP or equivalent protocol",
"$",
"charset",
"=",
"$",
"this",
"->",
"getProtocolEncoding",
"(",
")",
";",
"// Fallback 2: The charset as defined in the CSS file",
"if",
"(",
"$",
"charset",
"===",
"null",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^@charset\\s+([\"\\'])([-a-zA-Z0-9_]+)\\g{1}/i'",
",",
"$",
"firstLine",
",",
"$",
"matches",
")",
")",
"{",
"$",
"charset",
"=",
"$",
"matches",
"[",
"2",
"]",
";",
"$",
"charsetIgnored",
"=",
"false",
";",
"// Auto-correction of the defined charset.",
"//\"If the return value was utf-16be or utf-16le, use utf-8 as the fallback encoding\".",
"if",
"(",
"in_array",
"(",
"strtoupper",
"(",
"$",
"charset",
")",
",",
"[",
"\"UTF-16BE\"",
",",
"\"UTF-16LE\"",
"]",
")",
")",
"{",
"$",
"charset",
"=",
"\"UTF-8\"",
";",
"$",
"charsetReplaced",
"=",
"true",
";",
"}",
"}",
"}",
"// Fallback 3: The environment encoding of the referencing document",
"if",
"(",
"$",
"charset",
"===",
"null",
")",
"{",
"$",
"charset",
"=",
"$",
"this",
"->",
"getEnvironmentEncoding",
"(",
")",
";",
"}",
"// Fallback 4: Default to UTF-8",
"if",
"(",
"$",
"charset",
"===",
"null",
")",
"{",
"$",
"charset",
"=",
"\"UTF-8\"",
";",
"}",
"}",
"$",
"this",
"->",
"setCharset",
"(",
"$",
"charset",
")",
";",
"// Set position back to the beginning (but skip BOMs)",
"fseek",
"(",
"$",
"handle",
",",
"(",
"$",
"fileContainsBom",
"?",
"3",
":",
"0",
")",
")",
";",
"while",
"(",
"(",
"$",
"css",
"=",
"fgets",
"(",
"$",
"handle",
")",
")",
"!==",
"false",
")",
"{",
"// Required check to avoid errors when the encoding of the",
"// file doesn't match the set/detected charset.",
"if",
"(",
"mb_check_encoding",
"(",
"$",
"css",
",",
"$",
"charset",
")",
"===",
"false",
")",
"{",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Invalid '$charset' encoding in CSS file.\"",
")",
";",
"}",
"if",
"(",
"preg_match",
"(",
"'/[^\\x00-\\x7f]/'",
",",
"$",
"css",
")",
")",
"{",
"$",
"isAscii",
"=",
"false",
";",
"$",
"strLen",
"=",
"mb_strlen",
"(",
"$",
"css",
",",
"$",
"charset",
")",
";",
"}",
"else",
"{",
"$",
"isAscii",
"=",
"true",
";",
"$",
"strLen",
"=",
"strlen",
"(",
"$",
"css",
")",
";",
"}",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"j",
"=",
"$",
"strLen",
";",
"$",
"i",
"<",
"$",
"j",
";",
"$",
"i",
"++",
")",
"{",
"if",
"(",
"$",
"isAscii",
"===",
"true",
")",
"{",
"$",
"char",
"=",
"$",
"css",
"[",
"$",
"i",
"]",
";",
"}",
"else",
"{",
"$",
"char",
"=",
"mb_substr",
"(",
"$",
"css",
",",
"$",
"i",
",",
"1",
",",
"$",
"charset",
")",
";",
"}",
"if",
"(",
"$",
"char",
"===",
"\"{\"",
")",
"{",
"$",
"blockCount",
"++",
";",
"$",
"cssContent",
".=",
"\"\\n_BLOCKSTART_\"",
".",
"$",
"blockCount",
".",
"\"_\\n\"",
";",
"if",
"(",
"$",
"ruleCount",
">",
"$",
"ruleBlock",
")",
"{",
"$",
"ruleBlock",
"++",
";",
"}",
"}",
"else",
"if",
"(",
"$",
"char",
"===",
"\"}\"",
")",
"{",
"$",
"cssContent",
".=",
"\"\\n_BLOCKEND_\"",
".",
"$",
"blockCount",
".",
"\"_\\n\"",
";",
"$",
"blockCount",
"--",
";",
"if",
"(",
"$",
"blockCount",
"<",
"$",
"ruleCount",
")",
"{",
"if",
"(",
"$",
"ruleCount",
">",
"0",
")",
"{",
"$",
"cssContent",
".=",
"\"\\n_RULEEND_\"",
".",
"$",
"ruleCount",
".",
"\"_\\n\"",
";",
"$",
"ruleCount",
"--",
";",
"}",
"}",
"if",
"(",
"$",
"ruleCount",
">",
"0",
")",
"{",
"$",
"ruleBlock",
"--",
";",
"}",
"}",
"elseif",
"(",
"$",
"char",
"===",
"\";\"",
")",
"{",
"$",
"cssContent",
".=",
"$",
"char",
";",
"if",
"(",
"$",
"ruleCount",
">",
"0",
"&&",
"$",
"ruleBlock",
"===",
"0",
")",
"{",
"$",
"cssContent",
".=",
"\"\\n_RULEEND_1_\\n\"",
";",
"$",
"ruleCount",
"--",
";",
"}",
"}",
"else",
"{",
"// Start new at-rule, but only if we are not in brackets, which still can occur, although we",
"// replaced all strings, e.g. in this case: \"background: url(/images/[email protected])\".",
"if",
"(",
"$",
"char",
"===",
"\"@\"",
"&&",
"$",
"inBrackets",
"===",
"false",
")",
"{",
"if",
"(",
"$",
"ruleCount",
">",
"0",
"&&",
"$",
"blockCount",
"===",
"0",
")",
"{",
"$",
"errorCss",
"=",
"Placeholder",
"::",
"replaceCommentPlaceholders",
"(",
"Placeholder",
"::",
"replaceStringPlaceholders",
"(",
"$",
"css",
")",
")",
";",
"throw",
"new",
"\\",
"RuntimeException",
"(",
"\"Parse error near '$errorCss'.\"",
")",
";",
"}",
"$",
"ruleCount",
"++",
";",
"$",
"cssContent",
".=",
"\"\\n_RULESTART_\"",
".",
"$",
"ruleCount",
".",
"\"_\\n\"",
";",
"// Replace all white-space characters within rule definitions by normal space to get",
"// one line only",
"}",
"elseif",
"(",
"$",
"ruleCount",
">=",
"$",
"blockCount",
"&&",
"in_array",
"(",
"$",
"char",
",",
"[",
"\"\\r\"",
",",
"\"\\n\"",
",",
"\"\\t\"",
",",
"\"\\f\"",
"]",
")",
")",
"{",
"$",
"char",
"=",
"\" \"",
";",
"}",
"elseif",
"(",
"$",
"char",
"===",
"\"(\"",
")",
"{",
"$",
"inBrackets",
"=",
"true",
";",
"}",
"elseif",
"(",
"$",
"char",
"===",
"\")\"",
")",
"{",
"$",
"inBrackets",
"=",
"false",
";",
"}",
"$",
"cssContent",
".=",
"$",
"char",
";",
"}",
"}",
"}",
"// Auto-correction as required by CSS specs",
"while",
"(",
"$",
"blockCount",
">",
"0",
")",
"{",
"$",
"cssContent",
".=",
"\"\\n_BLOCKEND_\"",
".",
"$",
"blockCount",
".",
"\"_\\n\"",
";",
"$",
"blockCount",
"--",
";",
"}",
"while",
"(",
"$",
"ruleCount",
">",
"0",
")",
"{",
"$",
"cssContent",
".=",
"\"\\n_RULEEND_\"",
".",
"$",
"ruleCount",
".",
"\"_\\n\"",
";",
"$",
"ruleCount",
"--",
";",
"}",
"}",
"// Prettify...",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/;/'",
",",
"\";\\n\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/[\\t\\f]+/'",
",",
"\"\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/[ ]+/'",
",",
"\" \"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/(\\n)[ ]|[ ](\\n)/'",
",",
"\"\\\\1\\\\2\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/(?<!_)[ \\t\\n\\r\\f]*(:)[ \\t\\n\\r\\f]*/'",
",",
"\"\\\\1\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/([\\r\\n])+/'",
",",
"\"\\\\1\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/^\\n|\\n$/'",
",",
"\"\"",
",",
"$",
"cssContent",
")",
";",
"$",
"cssContent",
"=",
"preg_replace",
"(",
"'/^(_COMMENT_[a-f0-9]{32}_)([^\\r\\n]+)/m'",
",",
"\"\\\\1\\n\\\\2\"",
",",
"$",
"cssContent",
")",
";",
"// Parse",
"$",
"lines",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"cssContent",
")",
";",
"$",
"ruleCount",
"=",
"0",
";",
"$",
"blockCount",
"=",
"0",
";",
"$",
"lastRuleContainers",
"=",
"[",
"$",
"this",
"->",
"styleSheet",
"]",
";",
"$",
"lastRuleSet",
"=",
"null",
";",
"// Prepare vendor prefix regular expression",
"$",
"vendorPrefixRegExp",
"=",
"RuleAbstract",
"::",
"getVendorPrefixRegExp",
"(",
"\"/\"",
")",
";",
"$",
"comment",
"=",
"null",
";",
"$",
"atRuleCharsetAllowed",
"=",
"true",
";",
"$",
"atRuleImportAllowed",
"=",
"true",
";",
"$",
"atRuleNamespaceAllowed",
"=",
"true",
";",
"foreach",
"(",
"$",
"lines",
"as",
"$",
"line",
")",
"{",
"if",
"(",
"preg_match",
"(",
"'/^(?J)(?:_(?P<type>RULESTART|RULEEND|BLOCKSTART|BLOCKEND)_\\d+_|_(?P<type>COMMENT)_[a-f0-9]{32}_)/'",
",",
"$",
"line",
",",
"$",
"matches",
")",
")",
"{",
"if",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"===",
"'RULESTART'",
")",
"{",
"$",
"ruleCount",
"++",
";",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"===",
"'RULEEND'",
")",
"{",
"$",
"ruleCount",
"--",
";",
"if",
"(",
"$",
"ruleCount",
"===",
"$",
"blockCount",
")",
"{",
"// Current rule finished",
"}",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"===",
"'BLOCKSTART'",
")",
"{",
"$",
"blockCount",
"++",
";",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"===",
"'BLOCKEND'",
")",
"{",
"$",
"blockCount",
"--",
";",
"if",
"(",
"$",
"blockCount",
"===",
"$",
"ruleCount",
")",
"{",
"if",
"(",
"$",
"comment",
"!==",
"null",
")",
"{",
"/** @var AtRuleAbstract $lastRuleSet */",
"$",
"lastRuleSet",
"->",
"addComment",
"(",
"$",
"comment",
")",
";",
"$",
"comment",
"=",
"null",
";",
"}",
"// Current rule set finished",
"$",
"lastRuleSet",
"=",
"null",
";",
"}",
"else",
"{",
"if",
"(",
"$",
"comment",
"!==",
"null",
")",
"{",
"/** @var AtRuleAbstract[] $lastRuleContainers */",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"->",
"addComment",
"(",
"$",
"comment",
")",
";",
"$",
"comment",
"=",
"null",
";",
"}",
"}",
"}",
"elseif",
"(",
"$",
"matches",
"[",
"'type'",
"]",
"===",
"'COMMENT'",
")",
"{",
"$",
"comment",
"=",
"rtrim",
"(",
"$",
"line",
")",
";",
"}",
"}",
"else",
"{",
"if",
"(",
"$",
"blockCount",
"<",
"$",
"ruleCount",
")",
"{",
"// New rule opened",
"if",
"(",
"preg_match",
"(",
"'/^@('",
".",
"$",
"vendorPrefixRegExp",
".",
"')?([a-zA-Z_]{1}(?:[-a-zA-Z0-9_]*|[^[:ascii:]*]))/i'",
",",
"trim",
"(",
"$",
"line",
")",
",",
"$",
"matches",
")",
")",
"{",
"$",
"identifier",
"=",
"mb_strtolower",
"(",
"$",
"matches",
"[",
"2",
"]",
",",
"$",
"this",
"->",
"getCharset",
"(",
")",
")",
";",
"switch",
"(",
"$",
"identifier",
")",
"{",
"case",
"\"charset\"",
":",
"$",
"atRule",
"=",
"new",
"CharsetRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"import\"",
":",
"$",
"atRule",
"=",
"new",
"ImportRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"namespace\"",
":",
"$",
"atRule",
"=",
"new",
"NamespaceRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"media\"",
":",
"$",
"atRule",
"=",
"new",
"MediaRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"supports\"",
":",
"$",
"atRule",
"=",
"new",
"SupportsRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"document\"",
":",
"$",
"atRule",
"=",
"new",
"DocumentRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"font-face\"",
":",
"$",
"atRule",
"=",
"new",
"FontFaceRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"page\"",
":",
"$",
"atRule",
"=",
"new",
"PageRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"case",
"\"keyframes\"",
":",
"$",
"atRule",
"=",
"new",
"KeyframesRule",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"break",
";",
"default",
":",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Unknown at rule identifier '$identifier'.\"",
")",
";",
"}",
"// Add vendor prefix",
"if",
"(",
"$",
"matches",
"[",
"1",
"]",
"!==",
"\"\"",
")",
"{",
"$",
"vendorPrefix",
"=",
"mb_strtolower",
"(",
"$",
"matches",
"[",
"1",
"]",
",",
"$",
"this",
"->",
"getCharset",
"(",
")",
")",
";",
"$",
"atRule",
"->",
"setVendorPrefix",
"(",
"$",
"vendorPrefix",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"\\",
"InvalidArgumentException",
"(",
"\"Invalid rule format in '$line'.\"",
")",
";",
"}",
"// IMPORTANT:",
"// - The @charset rule must be the first element in the style sheet and not be preceded by any",
"// character.",
"// - Any @import rules must precede all other types of rules, except @charset rules (and other",
"// @import rules).",
"// - Any @namespace rules must follow all @charset and @import rules (and other @namespace rules)",
"// and precede all other non-ignored at-rules and style rules in a style-sheet.",
"if",
"(",
"$",
"atRule",
"instanceof",
"CharsetRule",
")",
"{",
"if",
"(",
"$",
"atRuleCharsetAllowed",
"===",
"false",
")",
"{",
"// As defined by CSS specs, the rule has been ignored, du to an invalid position in the",
"// style sheet. E.g. @charset must be the first content of the file, @import must be first",
"// or follow @charset or @import, and @namespace can only follow to @charset, @import or",
"// @namespace.",
"$",
"atRule",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"atRule",
"->",
"addValidationError",
"(",
"\"Ignored @charset rule, because at wrong position in style sheet.\"",
")",
";",
"}",
"elseif",
"(",
"$",
"charsetIgnored",
"===",
"true",
")",
"{",
"// As defined by CSS specs, the charset rule has been ignored, due to charset information",
"// from other sources (e.g. BOMs in the file or defined protocol encoding).",
"$",
"atRule",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"atRule",
"->",
"addValidationError",
"(",
"\"Ignored @charset rule, because charset got from other source with higher priority.\"",
")",
";",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"charsetReplaced",
"===",
"true",
")",
"{",
"// As defined by CSS specs, the charset defined by the charset rule has been replaced with",
"// \"UTF-8\", because an UTF-16* charset has been used.",
"$",
"atRule",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"atRule",
"->",
"addValidationError",
"(",
"\"Replaced charset in @charset rule with 'UTF-8', because defined charset is invalid.\"",
")",
";",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"else",
"{",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"}",
"elseif",
"(",
"$",
"atRule",
"instanceof",
"ImportRule",
")",
"{",
"// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style",
"// sheet. E.g. @charset must be the first content of the file, @import must be first or follow",
"// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.",
"if",
"(",
"$",
"atRuleImportAllowed",
"===",
"false",
")",
"{",
"$",
"atRule",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"atRule",
"->",
"addValidationError",
"(",
"\"Ignored @import rule, because at wrong position in style sheet.\"",
")",
";",
"}",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"atRule",
"instanceof",
"NamespaceRule",
")",
"{",
"// As defined by CSS specs, the rule has been ignored, du to an invalid position in the style",
"// sheet. E.g. @charset must be the first content of the file, @import must be first or follow",
"// @charset or @import, and @namespace can only follow to @charset, @import or @namespace.",
"if",
"(",
"$",
"atRuleNamespaceAllowed",
"===",
"false",
")",
"{",
"$",
"atRule",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"atRule",
"->",
"addValidationError",
"(",
"\"Ignored @namespace rule, because at wrong position in style sheet.\"",
")",
";",
"}",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"$",
"atRuleImportAllowed",
"=",
"false",
";",
"}",
"else",
"{",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"$",
"atRuleImportAllowed",
"=",
"false",
";",
"$",
"atRuleNamespaceAllowed",
"=",
"false",
";",
"}",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"-",
"1",
"]",
"->",
"addRule",
"(",
"$",
"atRule",
")",
";",
"if",
"(",
"$",
"atRule",
"instanceof",
"AtRuleConditionalAbstract",
")",
"{",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"=",
"$",
"atRule",
";",
"}",
"elseif",
"(",
"$",
"atRule",
"instanceof",
"KeyframesRule",
")",
"{",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"=",
"$",
"atRule",
";",
"}",
"elseif",
"(",
"$",
"atRule",
"instanceof",
"FontFaceRule",
")",
"{",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"=",
"$",
"atRule",
";",
"$",
"lastRuleSet",
"=",
"$",
"atRule",
";",
"}",
"elseif",
"(",
"$",
"atRule",
"instanceof",
"PageRule",
")",
"{",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"=",
"$",
"atRule",
";",
"$",
"lastRuleSet",
"=",
"$",
"atRule",
";",
"}",
"// Not all at-rules contain other rule, e.g. in @page rules the rules are mixed with the",
"// at-rule, so they directly contain declarations - this is filtered by checking for the",
"// HasRulesInterface here.",
"}",
"elseif",
"(",
"$",
"blockCount",
"===",
"$",
"ruleCount",
"&&",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"HasRulesInterface",
")",
"{",
"// New rule set opened",
"if",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"KeyframesRule",
")",
"{",
"$",
"ruleSet",
"=",
"new",
"KeyframesRuleSet",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"else",
"{",
"$",
"ruleSet",
"=",
"new",
"StyleRuleSet",
"(",
"$",
"line",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"if",
"(",
"$",
"comment",
"!==",
"null",
")",
"{",
"$",
"ruleSet",
"->",
"addComment",
"(",
"$",
"comment",
")",
";",
"$",
"comment",
"=",
"null",
";",
"}",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"->",
"addRule",
"(",
"$",
"ruleSet",
")",
";",
"$",
"lastRuleSet",
"=",
"$",
"ruleSet",
";",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"elseif",
"(",
"$",
"blockCount",
">=",
"$",
"ruleCount",
")",
"{",
"// New declaration",
"if",
"(",
"$",
"lastRuleSet",
"!==",
"null",
")",
"{",
"$",
"line",
"=",
"preg_replace",
"(",
"'/[\\s;]+$/'",
",",
"''",
",",
"$",
"line",
")",
";",
"$",
"invalidDeclaration",
"=",
"false",
";",
"if",
"(",
"strpos",
"(",
"$",
"line",
",",
"\":\"",
")",
"===",
"false",
")",
"{",
"$",
"property",
"=",
"$",
"line",
";",
"$",
"value",
"=",
"\"\"",
";",
"$",
"invalidDeclaration",
"=",
"true",
";",
"}",
"else",
"{",
"list",
"(",
"$",
"property",
",",
"$",
"value",
")",
"=",
"explode",
"(",
"\":\"",
",",
"$",
"line",
",",
"2",
")",
";",
"}",
"$",
"declaration",
"=",
"null",
";",
"if",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"StyleSheet",
")",
"{",
"$",
"declaration",
"=",
"new",
"StyleDeclaration",
"(",
"$",
"property",
",",
"$",
"value",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"elseif",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"AtRuleConditionalAbstract",
")",
"{",
"$",
"declaration",
"=",
"new",
"StyleDeclaration",
"(",
"$",
"property",
",",
"$",
"value",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"elseif",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"KeyframesRule",
")",
"{",
"$",
"declaration",
"=",
"new",
"KeyframesDeclaration",
"(",
"$",
"property",
",",
"$",
"value",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"elseif",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"FontFaceRule",
")",
"{",
"$",
"declaration",
"=",
"new",
"FontFaceDeclaration",
"(",
"$",
"property",
",",
"$",
"value",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"elseif",
"(",
"$",
"lastRuleContainers",
"[",
"$",
"ruleCount",
"]",
"instanceof",
"PageRule",
")",
"{",
"$",
"declaration",
"=",
"new",
"PageDeclaration",
"(",
"$",
"property",
",",
"$",
"value",
",",
"$",
"this",
"->",
"styleSheet",
")",
";",
"}",
"if",
"(",
"$",
"declaration",
"!==",
"null",
")",
"{",
"if",
"(",
"$",
"comment",
"!==",
"null",
")",
"{",
"$",
"declaration",
"->",
"addComment",
"(",
"$",
"comment",
")",
";",
"$",
"comment",
"=",
"null",
";",
"}",
"if",
"(",
"$",
"invalidDeclaration",
"===",
"true",
")",
"{",
"$",
"declaration",
"->",
"setIsValid",
"(",
"false",
")",
";",
"$",
"declaration",
"->",
"addValidationError",
"(",
"\"Parse error. Invalid declaration at '$line'.\"",
")",
";",
"}",
"$",
"lastRuleSet",
"->",
"addDeclaration",
"(",
"$",
"declaration",
")",
";",
"}",
"}",
"$",
"atRuleCharsetAllowed",
"=",
"false",
";",
"}",
"}",
"}",
"}"
] |
Parses the CSS source content.
|
[
"Parses",
"the",
"CSS",
"source",
"content",
"."
] |
train
|
https://github.com/crossjoin/Css/blob/7b50ca94c4bdad60d01cfa327f00b7a600d6f9f3/src/Crossjoin/Css/Reader/ReaderAbstract.php#L216-L614
|
nkt/flame
|
src/Statement.php
|
Statement.execute
|
public function execute($parameters = null)
{
if ($parameters !== null) {
$parameters = array_intersect_key($parameters, $this->types);
foreach ($this->placeholders as $i => $name) {
$value = & $parameters[$name];
if ($value === null) {
$this->bindValue($i + 1, null, Connection::PARAM_NULL);
} else {
$type = & $this->types[$name];
if ($type === Connection::PARAM_INT) {
$value = (int)$value;
} elseif ($type === Connection::PARAM_DATE_TIME) {
$value = $this->grammar->buildDateTime($value);
$type = Connection::PARAM_STR;
} elseif ($type === Connection::PARAM_TIME) {
$value = $this->grammar->buildTime($value);
$type = Connection::PARAM_STR;
}
$this->bindValue($i + 1, $value, $type);
}
}
}
parent::execute();
return $this;
}
|
php
|
public function execute($parameters = null)
{
if ($parameters !== null) {
$parameters = array_intersect_key($parameters, $this->types);
foreach ($this->placeholders as $i => $name) {
$value = & $parameters[$name];
if ($value === null) {
$this->bindValue($i + 1, null, Connection::PARAM_NULL);
} else {
$type = & $this->types[$name];
if ($type === Connection::PARAM_INT) {
$value = (int)$value;
} elseif ($type === Connection::PARAM_DATE_TIME) {
$value = $this->grammar->buildDateTime($value);
$type = Connection::PARAM_STR;
} elseif ($type === Connection::PARAM_TIME) {
$value = $this->grammar->buildTime($value);
$type = Connection::PARAM_STR;
}
$this->bindValue($i + 1, $value, $type);
}
}
}
parent::execute();
return $this;
}
|
[
"public",
"function",
"execute",
"(",
"$",
"parameters",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"parameters",
"!==",
"null",
")",
"{",
"$",
"parameters",
"=",
"array_intersect_key",
"(",
"$",
"parameters",
",",
"$",
"this",
"->",
"types",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"placeholders",
"as",
"$",
"i",
"=>",
"$",
"name",
")",
"{",
"$",
"value",
"=",
"&",
"$",
"parameters",
"[",
"$",
"name",
"]",
";",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"bindValue",
"(",
"$",
"i",
"+",
"1",
",",
"null",
",",
"Connection",
"::",
"PARAM_NULL",
")",
";",
"}",
"else",
"{",
"$",
"type",
"=",
"&",
"$",
"this",
"->",
"types",
"[",
"$",
"name",
"]",
";",
"if",
"(",
"$",
"type",
"===",
"Connection",
"::",
"PARAM_INT",
")",
"{",
"$",
"value",
"=",
"(",
"int",
")",
"$",
"value",
";",
"}",
"elseif",
"(",
"$",
"type",
"===",
"Connection",
"::",
"PARAM_DATE_TIME",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"grammar",
"->",
"buildDateTime",
"(",
"$",
"value",
")",
";",
"$",
"type",
"=",
"Connection",
"::",
"PARAM_STR",
";",
"}",
"elseif",
"(",
"$",
"type",
"===",
"Connection",
"::",
"PARAM_TIME",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"grammar",
"->",
"buildTime",
"(",
"$",
"value",
")",
";",
"$",
"type",
"=",
"Connection",
"::",
"PARAM_STR",
";",
"}",
"$",
"this",
"->",
"bindValue",
"(",
"$",
"i",
"+",
"1",
",",
"$",
"value",
",",
"$",
"type",
")",
";",
"}",
"}",
"}",
"parent",
"::",
"execute",
"(",
")",
";",
"return",
"$",
"this",
";",
"}"
] |
@param array $parameters
@return static
@throws Exception
|
[
"@param",
"array",
"$parameters"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/Statement.php#L38-L64
|
nkt/flame
|
src/Statement.php
|
Statement.fetchCallback
|
public function fetchCallback(callable $callback, $mode = null)
{
$results = [];
while (false !== $row = $this->fetch($mode)) {
$results[] = call_user_func($callback, $row);
}
return $results;
}
|
php
|
public function fetchCallback(callable $callback, $mode = null)
{
$results = [];
while (false !== $row = $this->fetch($mode)) {
$results[] = call_user_func($callback, $row);
}
return $results;
}
|
[
"public",
"function",
"fetchCallback",
"(",
"callable",
"$",
"callback",
",",
"$",
"mode",
"=",
"null",
")",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"while",
"(",
"false",
"!==",
"$",
"row",
"=",
"$",
"this",
"->",
"fetch",
"(",
"$",
"mode",
")",
")",
"{",
"$",
"results",
"[",
"]",
"=",
"call_user_func",
"(",
"$",
"callback",
",",
"$",
"row",
")",
";",
"}",
"return",
"$",
"results",
";",
"}"
] |
@param callable $callback
@param int $mode
@return array
|
[
"@param",
"callable",
"$callback",
"@param",
"int",
"$mode"
] |
train
|
https://github.com/nkt/flame/blob/16f9f172db5a8a618b628429e0986eacb089d217/src/Statement.php#L83-L91
|
comodojo/dispatcher.framework
|
src/Comodojo/Dispatcher/Router/Route.php
|
Route.serialize
|
public function serialize() {
return serialize( (object) [
'classname' => $this->classname,
'type' => $this->type,
'service' => $this->service,
'parameters' => $this->parameters,
'request' => $this->request,
'query' => $this->query
]);
}
|
php
|
public function serialize() {
return serialize( (object) [
'classname' => $this->classname,
'type' => $this->type,
'service' => $this->service,
'parameters' => $this->parameters,
'request' => $this->request,
'query' => $this->query
]);
}
|
[
"public",
"function",
"serialize",
"(",
")",
"{",
"return",
"serialize",
"(",
"(",
"object",
")",
"[",
"'classname'",
"=>",
"$",
"this",
"->",
"classname",
",",
"'type'",
"=>",
"$",
"this",
"->",
"type",
",",
"'service'",
"=>",
"$",
"this",
"->",
"service",
",",
"'parameters'",
"=>",
"$",
"this",
"->",
"parameters",
",",
"'request'",
"=>",
"$",
"this",
"->",
"request",
",",
"'query'",
"=>",
"$",
"this",
"->",
"query",
"]",
")",
";",
"}"
] |
Return the serialized data
@return string
|
[
"Return",
"the",
"serialized",
"data"
] |
train
|
https://github.com/comodojo/dispatcher.framework/blob/5093297dcb7441a8d8f79cbb2429c93232e16d1c/src/Comodojo/Dispatcher/Router/Route.php#L387-L398
|
comodojo/dispatcher.framework
|
src/Comodojo/Dispatcher/Router/Route.php
|
Route.unserialize
|
public function unserialize($data) {
$parts = unserialize($data);
$this->classname = $parts->classname;
$this->type = $parts->type;
$this->service = $parts->service;
$this->parameters = $parts->parameters;
$this->request = $parts->request;
$this->query = $parts->query;
}
|
php
|
public function unserialize($data) {
$parts = unserialize($data);
$this->classname = $parts->classname;
$this->type = $parts->type;
$this->service = $parts->service;
$this->parameters = $parts->parameters;
$this->request = $parts->request;
$this->query = $parts->query;
}
|
[
"public",
"function",
"unserialize",
"(",
"$",
"data",
")",
"{",
"$",
"parts",
"=",
"unserialize",
"(",
"$",
"data",
")",
";",
"$",
"this",
"->",
"classname",
"=",
"$",
"parts",
"->",
"classname",
";",
"$",
"this",
"->",
"type",
"=",
"$",
"parts",
"->",
"type",
";",
"$",
"this",
"->",
"service",
"=",
"$",
"parts",
"->",
"service",
";",
"$",
"this",
"->",
"parameters",
"=",
"$",
"parts",
"->",
"parameters",
";",
"$",
"this",
"->",
"request",
"=",
"$",
"parts",
"->",
"request",
";",
"$",
"this",
"->",
"query",
"=",
"$",
"parts",
"->",
"query",
";",
"}"
] |
Return the unserialized object
@param string $data Serialized data
|
[
"Return",
"the",
"unserialized",
"object"
] |
train
|
https://github.com/comodojo/dispatcher.framework/blob/5093297dcb7441a8d8f79cbb2429c93232e16d1c/src/Comodojo/Dispatcher/Router/Route.php#L406-L417
|
jpuck/color-mixer
|
src/CanonicalNames.php
|
CanonicalNames.hex
|
public static function hex(string $name = null)
{
if ( empty($name) ) {
return static::$hexmap;
}
return static::$hexmap[$name] ?? false;
}
|
php
|
public static function hex(string $name = null)
{
if ( empty($name) ) {
return static::$hexmap;
}
return static::$hexmap[$name] ?? false;
}
|
[
"public",
"static",
"function",
"hex",
"(",
"string",
"$",
"name",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
")",
"{",
"return",
"static",
"::",
"$",
"hexmap",
";",
"}",
"return",
"static",
"::",
"$",
"hexmap",
"[",
"$",
"name",
"]",
"??",
"false",
";",
"}"
] |
Returns the hexadecimal CSS color given the canonical name.
@param string Optional canonical color name.
@return mixed Default returns array of all canonical keys and hex values.
Given a name, returns string hexadecimal color or false if color
does not exist.
|
[
"Returns",
"the",
"hexadecimal",
"CSS",
"color",
"given",
"the",
"canonical",
"name",
"."
] |
train
|
https://github.com/jpuck/color-mixer/blob/cea01c3082a921a35e00ae0a287c795d9fd73ada/src/CanonicalNames.php#L165-L172
|
constant-null/backstubber
|
src/FileGenerator.php
|
FileGenerator.set
|
public function set($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $innerName => $innerValue) {
$this->replace($innerName, $this->formatValue($innerValue));
}
} else {
$this->replace($name, $this->formatValue($value));
}
// return is for chaining
return $this;
}
|
php
|
public function set($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $innerName => $innerValue) {
$this->replace($innerName, $this->formatValue($innerValue));
}
} else {
$this->replace($name, $this->formatValue($value));
}
// return is for chaining
return $this;
}
|
[
"public",
"function",
"set",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"foreach",
"(",
"$",
"name",
"as",
"$",
"innerName",
"=>",
"$",
"innerValue",
")",
"{",
"$",
"this",
"->",
"replace",
"(",
"$",
"innerName",
",",
"$",
"this",
"->",
"formatValue",
"(",
"$",
"innerValue",
")",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"replace",
"(",
"$",
"name",
",",
"$",
"this",
"->",
"formatValue",
"(",
"$",
"value",
")",
")",
";",
"}",
"// return is for chaining",
"return",
"$",
"this",
";",
"}"
] |
Add variable(s) to replacement list
it will automatically format scalar types and arrays,
so they text representation will be inserted
@param $name array|string
@param $value null|string|array
@return $this
|
[
"Add",
"variable",
"(",
"s",
")",
"to",
"replacement",
"list",
"it",
"will",
"automatically",
"format",
"scalar",
"types",
"and",
"arrays",
"so",
"they",
"text",
"representation",
"will",
"be",
"inserted"
] |
train
|
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L57-L69
|
constant-null/backstubber
|
src/FileGenerator.php
|
FileGenerator.setRaw
|
public function setRaw($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $innerName => $innerValue) {
$this->replace($innerName, $innerValue);
}
} else {
$this->replace($name, $value);
}
// return is for chaining
return $this;
}
|
php
|
public function setRaw($name, $value = null)
{
if (is_array($name)) {
foreach ($name as $innerName => $innerValue) {
$this->replace($innerName, $innerValue);
}
} else {
$this->replace($name, $value);
}
// return is for chaining
return $this;
}
|
[
"public",
"function",
"setRaw",
"(",
"$",
"name",
",",
"$",
"value",
"=",
"null",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"foreach",
"(",
"$",
"name",
"as",
"$",
"innerName",
"=>",
"$",
"innerValue",
")",
"{",
"$",
"this",
"->",
"replace",
"(",
"$",
"innerName",
",",
"$",
"innerValue",
")",
";",
"}",
"}",
"else",
"{",
"$",
"this",
"->",
"replace",
"(",
"$",
"name",
",",
"$",
"value",
")",
";",
"}",
"// return is for chaining",
"return",
"$",
"this",
";",
"}"
] |
Add variable(s) to replacement list, without any formatting.
May be usefull when inserting class/variable/trait names, control structures, etc.
@param $name array|string
@param $value null|array|string
@return $this
|
[
"Add",
"variable",
"(",
"s",
")",
"to",
"replacement",
"list",
"without",
"any",
"formatting",
".",
"May",
"be",
"usefull",
"when",
"inserting",
"class",
"/",
"variable",
"/",
"trait",
"names",
"control",
"structures",
"etc",
"."
] |
train
|
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L79-L91
|
constant-null/backstubber
|
src/FileGenerator.php
|
FileGenerator.generate
|
public function generate($outputPath)
{
// do content replacement
$this->process();
// check if directory exist, if not create it
$baseDir = dirname($outputPath);
if (!is_dir($baseDir)) {
mkdir($baseDir, 700, true);
}
return (bool)file_put_contents($outputPath, $this->getContent());
}
|
php
|
public function generate($outputPath)
{
// do content replacement
$this->process();
// check if directory exist, if not create it
$baseDir = dirname($outputPath);
if (!is_dir($baseDir)) {
mkdir($baseDir, 700, true);
}
return (bool)file_put_contents($outputPath, $this->getContent());
}
|
[
"public",
"function",
"generate",
"(",
"$",
"outputPath",
")",
"{",
"// do content replacement",
"$",
"this",
"->",
"process",
"(",
")",
";",
"// check if directory exist, if not create it",
"$",
"baseDir",
"=",
"dirname",
"(",
"$",
"outputPath",
")",
";",
"if",
"(",
"!",
"is_dir",
"(",
"$",
"baseDir",
")",
")",
"{",
"mkdir",
"(",
"$",
"baseDir",
",",
"700",
",",
"true",
")",
";",
"}",
"return",
"(",
"bool",
")",
"file_put_contents",
"(",
"$",
"outputPath",
",",
"$",
"this",
"->",
"getContent",
"(",
")",
")",
";",
"}"
] |
save generated file to path
returns true if file was successfully created false otherwise
@param $outputPath string
@return bool
|
[
"save",
"generated",
"file",
"to",
"path",
"returns",
"true",
"if",
"file",
"was",
"successfully",
"created",
"false",
"otherwise"
] |
train
|
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L100-L112
|
constant-null/backstubber
|
src/FileGenerator.php
|
FileGenerator.formatValue
|
protected function formatValue($value)
{
if (is_array($value)) {
return Formatter::formatArray($value);
}
return Formatter::formatScalar($value);
}
|
php
|
protected function formatValue($value)
{
if (is_array($value)) {
return Formatter::formatArray($value);
}
return Formatter::formatScalar($value);
}
|
[
"protected",
"function",
"formatValue",
"(",
"$",
"value",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"value",
")",
")",
"{",
"return",
"Formatter",
"::",
"formatArray",
"(",
"$",
"value",
")",
";",
"}",
"return",
"Formatter",
"::",
"formatScalar",
"(",
"$",
"value",
")",
";",
"}"
] |
Format a value before processing.
@param array|string $value
@return array|string
|
[
"Format",
"a",
"value",
"before",
"processing",
"."
] |
train
|
https://github.com/constant-null/backstubber/blob/1e7ee66091bae4e6b709642467609a8566dae479/src/FileGenerator.php#L120-L127
|
stubbles/stubbles-webapp-core
|
src/main/php/UriPath.php
|
UriPath.hasArgument
|
public function hasArgument(string $name): bool
{
$this->parsePathArguments();
return isset($this->arguments[$name]);
}
|
php
|
public function hasArgument(string $name): bool
{
$this->parsePathArguments();
return isset($this->arguments[$name]);
}
|
[
"public",
"function",
"hasArgument",
"(",
"string",
"$",
"name",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"parsePathArguments",
"(",
")",
";",
"return",
"isset",
"(",
"$",
"this",
"->",
"arguments",
"[",
"$",
"name",
"]",
")",
";",
"}"
] |
checks if path contains argument with given name
@param string $name
@return bool
|
[
"checks",
"if",
"path",
"contains",
"argument",
"with",
"given",
"name"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L99-L103
|
stubbles/stubbles-webapp-core
|
src/main/php/UriPath.php
|
UriPath.readArgument
|
public function readArgument(string $name): ValueReader
{
$this->parsePathArguments();
if (isset($this->arguments[$name])) {
return ValueReader::forValue($this->arguments[$name]);
}
return ValueReader::forValue(null);
}
|
php
|
public function readArgument(string $name): ValueReader
{
$this->parsePathArguments();
if (isset($this->arguments[$name])) {
return ValueReader::forValue($this->arguments[$name]);
}
return ValueReader::forValue(null);
}
|
[
"public",
"function",
"readArgument",
"(",
"string",
"$",
"name",
")",
":",
"ValueReader",
"{",
"$",
"this",
"->",
"parsePathArguments",
"(",
")",
";",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"arguments",
"[",
"$",
"name",
"]",
")",
")",
"{",
"return",
"ValueReader",
"::",
"forValue",
"(",
"$",
"this",
"->",
"arguments",
"[",
"$",
"name",
"]",
")",
";",
"}",
"return",
"ValueReader",
"::",
"forValue",
"(",
"null",
")",
";",
"}"
] |
returns argument with given name or default if not set
@param string $name
@return \stubbles\input\ValueReader
@since 3.3.0
|
[
"returns",
"argument",
"with",
"given",
"name",
"or",
"default",
"if",
"not",
"set"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L112-L120
|
stubbles/stubbles-webapp-core
|
src/main/php/UriPath.php
|
UriPath.parsePathArguments
|
private function parsePathArguments()
{
if (null !== $this->arguments) {
return;
}
$arguments = [];
preg_match('/^' . self::pattern($this->configuredPath) . '/', $this->calledPath, $arguments);
array_shift($arguments);
$names = [];
$this->arguments = [];
preg_match_all('/[{][^}]*[}]/', str_replace('/', '\/', $this->configuredPath), $names);
foreach ($names[0] as $key => $name) {
if (isset($arguments[$key])) {
$this->arguments[str_replace(['{', '}'], '', $name)] = $arguments[$key];
}
}
}
|
php
|
private function parsePathArguments()
{
if (null !== $this->arguments) {
return;
}
$arguments = [];
preg_match('/^' . self::pattern($this->configuredPath) . '/', $this->calledPath, $arguments);
array_shift($arguments);
$names = [];
$this->arguments = [];
preg_match_all('/[{][^}]*[}]/', str_replace('/', '\/', $this->configuredPath), $names);
foreach ($names[0] as $key => $name) {
if (isset($arguments[$key])) {
$this->arguments[str_replace(['{', '}'], '', $name)] = $arguments[$key];
}
}
}
|
[
"private",
"function",
"parsePathArguments",
"(",
")",
"{",
"if",
"(",
"null",
"!==",
"$",
"this",
"->",
"arguments",
")",
"{",
"return",
";",
"}",
"$",
"arguments",
"=",
"[",
"]",
";",
"preg_match",
"(",
"'/^'",
".",
"self",
"::",
"pattern",
"(",
"$",
"this",
"->",
"configuredPath",
")",
".",
"'/'",
",",
"$",
"this",
"->",
"calledPath",
",",
"$",
"arguments",
")",
";",
"array_shift",
"(",
"$",
"arguments",
")",
";",
"$",
"names",
"=",
"[",
"]",
";",
"$",
"this",
"->",
"arguments",
"=",
"[",
"]",
";",
"preg_match_all",
"(",
"'/[{][^}]*[}]/'",
",",
"str_replace",
"(",
"'/'",
",",
"'\\/'",
",",
"$",
"this",
"->",
"configuredPath",
")",
",",
"$",
"names",
")",
";",
"foreach",
"(",
"$",
"names",
"[",
"0",
"]",
"as",
"$",
"key",
"=>",
"$",
"name",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"arguments",
"[",
"$",
"key",
"]",
")",
")",
"{",
"$",
"this",
"->",
"arguments",
"[",
"str_replace",
"(",
"[",
"'{'",
",",
"'}'",
"]",
",",
"''",
",",
"$",
"name",
")",
"]",
"=",
"$",
"arguments",
"[",
"$",
"key",
"]",
";",
"}",
"}",
"}"
] |
parses path arguments from called path
|
[
"parses",
"path",
"arguments",
"from",
"called",
"path"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L125-L142
|
stubbles/stubbles-webapp-core
|
src/main/php/UriPath.php
|
UriPath.remaining
|
public function remaining(string $default = null)
{
$matches = [];
preg_match('/(' . self::pattern($this->configuredPath) . ')([^?]*)?/', $this->calledPath, $matches);
$last = count($matches) - 1;
if (2 > $last) {
return $default;
}
if (isset($matches[$last]) && !empty($matches[$last])) {
return $matches[$last];
}
return $default;
}
|
php
|
public function remaining(string $default = null)
{
$matches = [];
preg_match('/(' . self::pattern($this->configuredPath) . ')([^?]*)?/', $this->calledPath, $matches);
$last = count($matches) - 1;
if (2 > $last) {
return $default;
}
if (isset($matches[$last]) && !empty($matches[$last])) {
return $matches[$last];
}
return $default;
}
|
[
"public",
"function",
"remaining",
"(",
"string",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"matches",
"=",
"[",
"]",
";",
"preg_match",
"(",
"'/('",
".",
"self",
"::",
"pattern",
"(",
"$",
"this",
"->",
"configuredPath",
")",
".",
"')([^?]*)?/'",
",",
"$",
"this",
"->",
"calledPath",
",",
"$",
"matches",
")",
";",
"$",
"last",
"=",
"count",
"(",
"$",
"matches",
")",
"-",
"1",
";",
"if",
"(",
"2",
">",
"$",
"last",
")",
"{",
"return",
"$",
"default",
";",
"}",
"if",
"(",
"isset",
"(",
"$",
"matches",
"[",
"$",
"last",
"]",
")",
"&&",
"!",
"empty",
"(",
"$",
"matches",
"[",
"$",
"last",
"]",
")",
")",
"{",
"return",
"$",
"matches",
"[",
"$",
"last",
"]",
";",
"}",
"return",
"$",
"default",
";",
"}"
] |
returns remaining path that was not matched by original path
@param string $default
@return string
|
[
"returns",
"remaining",
"path",
"that",
"was",
"not",
"matched",
"by",
"original",
"path"
] |
train
|
https://github.com/stubbles/stubbles-webapp-core/blob/7705f129011a81d5cc3c76b4b150fab3dadac6a3/src/main/php/UriPath.php#L150-L164
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getTemplate
|
public function getTemplate($entityType)
{
$params = [
'fields' => 'attributes.title',
'limit' => 1,
];
$definition = $this->search('EntityType', ['title' => $entityType], $params);
return array_fill_keys(array_merge(['_id'], array_column($definition[0]['attributes'], 'title')), null);
}
|
php
|
public function getTemplate($entityType)
{
$params = [
'fields' => 'attributes.title',
'limit' => 1,
];
$definition = $this->search('EntityType', ['title' => $entityType], $params);
return array_fill_keys(array_merge(['_id'], array_column($definition[0]['attributes'], 'title')), null);
}
|
[
"public",
"function",
"getTemplate",
"(",
"$",
"entityType",
")",
"{",
"$",
"params",
"=",
"[",
"'fields'",
"=>",
"'attributes.title'",
",",
"'limit'",
"=>",
"1",
",",
"]",
";",
"$",
"definition",
"=",
"$",
"this",
"->",
"search",
"(",
"'EntityType'",
",",
"[",
"'title'",
"=>",
"$",
"entityType",
"]",
",",
"$",
"params",
")",
";",
"return",
"array_fill_keys",
"(",
"array_merge",
"(",
"[",
"'_id'",
"]",
",",
"array_column",
"(",
"$",
"definition",
"[",
"0",
"]",
"[",
"'attributes'",
"]",
",",
"'title'",
")",
")",
",",
"null",
")",
";",
"}"
] |
Returns an array that has all the fields according to the definition in Communibase.
@param string $entityType
@return array
@throws Exception
|
[
"Returns",
"an",
"array",
"that",
"has",
"all",
"the",
"fields",
"according",
"to",
"the",
"definition",
"in",
"Communibase",
"."
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L88-L97
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getById
|
public function getById($entityType, $id, array $params = [], $version = null)
{
if (empty($id)) {
throw new Exception('Id is empty');
}
if (!static::isIdValid($id)) {
throw new Exception('Id is invalid, please use a correctly formatted id');
}
return ($version === null)
? $this->doGet($entityType . '.json/crud/' . $id, $params)
: $this->doGet($entityType . '.json/history/' . $id . '/' . $version, $params);
}
|
php
|
public function getById($entityType, $id, array $params = [], $version = null)
{
if (empty($id)) {
throw new Exception('Id is empty');
}
if (!static::isIdValid($id)) {
throw new Exception('Id is invalid, please use a correctly formatted id');
}
return ($version === null)
? $this->doGet($entityType . '.json/crud/' . $id, $params)
: $this->doGet($entityType . '.json/history/' . $id . '/' . $version, $params);
}
|
[
"public",
"function",
"getById",
"(",
"$",
"entityType",
",",
"$",
"id",
",",
"array",
"$",
"params",
"=",
"[",
"]",
",",
"$",
"version",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Id is empty'",
")",
";",
"}",
"if",
"(",
"!",
"static",
"::",
"isIdValid",
"(",
"$",
"id",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Id is invalid, please use a correctly formatted id'",
")",
";",
"}",
"return",
"(",
"$",
"version",
"===",
"null",
")",
"?",
"$",
"this",
"->",
"doGet",
"(",
"$",
"entityType",
".",
"'.json/crud/'",
".",
"$",
"id",
",",
"$",
"params",
")",
":",
"$",
"this",
"->",
"doGet",
"(",
"$",
"entityType",
".",
"'.json/history/'",
".",
"$",
"id",
".",
"'/'",
".",
"$",
"version",
",",
"$",
"params",
")",
";",
"}"
] |
Get a single Entity by its id
@param string $entityType
@param string $id
@param array $params (optional)
@param string|null $version
@return array entity
@throws Exception
|
[
"Get",
"a",
"single",
"Entity",
"by",
"its",
"id"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L111-L124
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getByRef
|
public function getByRef(array $ref, array $parentEntity = [])
{
$document = $parentEntity;
if (strpos($ref['rootDocumentEntityType'], 'parent') === false) {
if (empty($document['_id']) || $document['_id'] !== $ref['rootDocumentId']) {
$document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']);
}
if (count($document) === 0) {
throw new Exception('Invalid document reference (document cannot be found by Id)');
}
}
$container = $document;
foreach ($ref['path'] as $pathInDocument) {
if (!array_key_exists($pathInDocument['field'], $container)) {
throw new Exception('Could not find the path in document');
}
$container = $container[$pathInDocument['field']];
if (empty($pathInDocument['objectId'])) {
continue;
}
if (!is_array($container)) {
throw new Exception('Invalid value for path in document');
}
$result = array_filter($container, function ($item) use ($pathInDocument) {
return $item['_id'] === $pathInDocument['objectId'];
});
if (count($result) === 0) {
throw new Exception('Empty result of reference');
}
$container = reset($result);
}
return $container;
}
|
php
|
public function getByRef(array $ref, array $parentEntity = [])
{
$document = $parentEntity;
if (strpos($ref['rootDocumentEntityType'], 'parent') === false) {
if (empty($document['_id']) || $document['_id'] !== $ref['rootDocumentId']) {
$document = $this->getById($ref['rootDocumentEntityType'], $ref['rootDocumentId']);
}
if (count($document) === 0) {
throw new Exception('Invalid document reference (document cannot be found by Id)');
}
}
$container = $document;
foreach ($ref['path'] as $pathInDocument) {
if (!array_key_exists($pathInDocument['field'], $container)) {
throw new Exception('Could not find the path in document');
}
$container = $container[$pathInDocument['field']];
if (empty($pathInDocument['objectId'])) {
continue;
}
if (!is_array($container)) {
throw new Exception('Invalid value for path in document');
}
$result = array_filter($container, function ($item) use ($pathInDocument) {
return $item['_id'] === $pathInDocument['objectId'];
});
if (count($result) === 0) {
throw new Exception('Empty result of reference');
}
$container = reset($result);
}
return $container;
}
|
[
"public",
"function",
"getByRef",
"(",
"array",
"$",
"ref",
",",
"array",
"$",
"parentEntity",
"=",
"[",
"]",
")",
"{",
"$",
"document",
"=",
"$",
"parentEntity",
";",
"if",
"(",
"strpos",
"(",
"$",
"ref",
"[",
"'rootDocumentEntityType'",
"]",
",",
"'parent'",
")",
"===",
"false",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"document",
"[",
"'_id'",
"]",
")",
"||",
"$",
"document",
"[",
"'_id'",
"]",
"!==",
"$",
"ref",
"[",
"'rootDocumentId'",
"]",
")",
"{",
"$",
"document",
"=",
"$",
"this",
"->",
"getById",
"(",
"$",
"ref",
"[",
"'rootDocumentEntityType'",
"]",
",",
"$",
"ref",
"[",
"'rootDocumentId'",
"]",
")",
";",
"}",
"if",
"(",
"count",
"(",
"$",
"document",
")",
"===",
"0",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Invalid document reference (document cannot be found by Id)'",
")",
";",
"}",
"}",
"$",
"container",
"=",
"$",
"document",
";",
"foreach",
"(",
"$",
"ref",
"[",
"'path'",
"]",
"as",
"$",
"pathInDocument",
")",
"{",
"if",
"(",
"!",
"array_key_exists",
"(",
"$",
"pathInDocument",
"[",
"'field'",
"]",
",",
"$",
"container",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Could not find the path in document'",
")",
";",
"}",
"$",
"container",
"=",
"$",
"container",
"[",
"$",
"pathInDocument",
"[",
"'field'",
"]",
"]",
";",
"if",
"(",
"empty",
"(",
"$",
"pathInDocument",
"[",
"'objectId'",
"]",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"!",
"is_array",
"(",
"$",
"container",
")",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Invalid value for path in document'",
")",
";",
"}",
"$",
"result",
"=",
"array_filter",
"(",
"$",
"container",
",",
"function",
"(",
"$",
"item",
")",
"use",
"(",
"$",
"pathInDocument",
")",
"{",
"return",
"$",
"item",
"[",
"'_id'",
"]",
"===",
"$",
"pathInDocument",
"[",
"'objectId'",
"]",
";",
"}",
")",
";",
"if",
"(",
"count",
"(",
"$",
"result",
")",
"===",
"0",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Empty result of reference'",
")",
";",
"}",
"$",
"container",
"=",
"reset",
"(",
"$",
"result",
")",
";",
"}",
"return",
"$",
"container",
";",
"}"
] |
Get a single Entity by a ref-string
@todo if the ref is a parent.parent.parent the code would need further improvement.
@param array $ref
@param array $parentEntity (optional)
@return array the referred Entity data
@throws Exception
|
[
"Get",
"a",
"single",
"Entity",
"by",
"a",
"ref",
"-",
"string"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L138-L173
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getByIds
|
public function getByIds($entityType, array $ids, array $params = [])
{
$validIds = array_values(array_unique(array_filter($ids, [__CLASS__, 'isIdValid'])));
if (count($validIds) === 0) {
return [];
}
$doSortByIds = empty($params['sort']);
$results = $this->search($entityType, ['_id' => ['$in' => $validIds]], $params);
if (!$doSortByIds) {
return $results;
}
$flipped = array_flip($validIds);
foreach ($results as $result) {
$flipped[$result['_id']] = $result;
}
return array_filter(array_values($flipped), function ($result) {
return is_array($result) && count($result) > 0;
});
}
|
php
|
public function getByIds($entityType, array $ids, array $params = [])
{
$validIds = array_values(array_unique(array_filter($ids, [__CLASS__, 'isIdValid'])));
if (count($validIds) === 0) {
return [];
}
$doSortByIds = empty($params['sort']);
$results = $this->search($entityType, ['_id' => ['$in' => $validIds]], $params);
if (!$doSortByIds) {
return $results;
}
$flipped = array_flip($validIds);
foreach ($results as $result) {
$flipped[$result['_id']] = $result;
}
return array_filter(array_values($flipped), function ($result) {
return is_array($result) && count($result) > 0;
});
}
|
[
"public",
"function",
"getByIds",
"(",
"$",
"entityType",
",",
"array",
"$",
"ids",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"validIds",
"=",
"array_values",
"(",
"array_unique",
"(",
"array_filter",
"(",
"$",
"ids",
",",
"[",
"__CLASS__",
",",
"'isIdValid'",
"]",
")",
")",
")",
";",
"if",
"(",
"count",
"(",
"$",
"validIds",
")",
"===",
"0",
")",
"{",
"return",
"[",
"]",
";",
"}",
"$",
"doSortByIds",
"=",
"empty",
"(",
"$",
"params",
"[",
"'sort'",
"]",
")",
";",
"$",
"results",
"=",
"$",
"this",
"->",
"search",
"(",
"$",
"entityType",
",",
"[",
"'_id'",
"=>",
"[",
"'$in'",
"=>",
"$",
"validIds",
"]",
"]",
",",
"$",
"params",
")",
";",
"if",
"(",
"!",
"$",
"doSortByIds",
")",
"{",
"return",
"$",
"results",
";",
"}",
"$",
"flipped",
"=",
"array_flip",
"(",
"$",
"validIds",
")",
";",
"foreach",
"(",
"$",
"results",
"as",
"$",
"result",
")",
"{",
"$",
"flipped",
"[",
"$",
"result",
"[",
"'_id'",
"]",
"]",
"=",
"$",
"result",
";",
"}",
"return",
"array_filter",
"(",
"array_values",
"(",
"$",
"flipped",
")",
",",
"function",
"(",
"$",
"result",
")",
"{",
"return",
"is_array",
"(",
"$",
"result",
")",
"&&",
"count",
"(",
"$",
"result",
")",
">",
"0",
";",
"}",
")",
";",
"}"
] |
Get an array of entities by their ids
@param string $entityType
@param array $ids
@param array $params (optional)
@return array entities
@throws Exception
|
[
"Get",
"an",
"array",
"of",
"entities",
"by",
"their",
"ids"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L186-L208
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getIds
|
public function getIds($entityType, array $selector = [], array $params = [])
{
$params['fields'] = '_id';
return array_column($this->search($entityType, $selector, $params), '_id');
}
|
php
|
public function getIds($entityType, array $selector = [], array $params = [])
{
$params['fields'] = '_id';
return array_column($this->search($entityType, $selector, $params), '_id');
}
|
[
"public",
"function",
"getIds",
"(",
"$",
"entityType",
",",
"array",
"$",
"selector",
"=",
"[",
"]",
",",
"array",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"[",
"'fields'",
"]",
"=",
"'_id'",
";",
"return",
"array_column",
"(",
"$",
"this",
"->",
"search",
"(",
"$",
"entityType",
",",
"$",
"selector",
",",
"$",
"params",
")",
",",
"'_id'",
")",
";",
"}"
] |
Get result entityIds of a certain search
@param string $entityType
@param array $selector (optional)
@param array $params (optional)
@return array
@throws Exception
|
[
"Get",
"result",
"entityIds",
"of",
"a",
"certain",
"search"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L236-L241
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.getId
|
public function getId($entityType, array $selector = [])
{
$params = ['limit' => 1];
$ids = (array)$this->getIds($entityType, $selector, $params);
return array_shift($ids);
}
|
php
|
public function getId($entityType, array $selector = [])
{
$params = ['limit' => 1];
$ids = (array)$this->getIds($entityType, $selector, $params);
return array_shift($ids);
}
|
[
"public",
"function",
"getId",
"(",
"$",
"entityType",
",",
"array",
"$",
"selector",
"=",
"[",
"]",
")",
"{",
"$",
"params",
"=",
"[",
"'limit'",
"=>",
"1",
"]",
";",
"$",
"ids",
"=",
"(",
"array",
")",
"$",
"this",
"->",
"getIds",
"(",
"$",
"entityType",
",",
"$",
"selector",
",",
"$",
"params",
")",
";",
"return",
"array_shift",
"(",
"$",
"ids",
")",
";",
"}"
] |
Get the id of an entity based on a search
@param string $entityType i.e. Person
@param array $selector (optional) i.e. ['firstName' => 'Henk']
@return array resultData
@throws Exception
|
[
"Get",
"the",
"id",
"of",
"an",
"entity",
"based",
"on",
"a",
"search"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L253-L259
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.update
|
public function update($entityType, array $properties)
{
if (empty($properties['_id'])) {
return $this->doPost($entityType . '.json/crud/', [], $properties);
}
return $this->doPut($entityType . '.json/crud/' . $properties['_id'], [], $properties);
}
|
php
|
public function update($entityType, array $properties)
{
if (empty($properties['_id'])) {
return $this->doPost($entityType . '.json/crud/', [], $properties);
}
return $this->doPut($entityType . '.json/crud/' . $properties['_id'], [], $properties);
}
|
[
"public",
"function",
"update",
"(",
"$",
"entityType",
",",
"array",
"$",
"properties",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"properties",
"[",
"'_id'",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"doPost",
"(",
"$",
"entityType",
".",
"'.json/crud/'",
",",
"[",
"]",
",",
"$",
"properties",
")",
";",
"}",
"return",
"$",
"this",
"->",
"doPut",
"(",
"$",
"entityType",
".",
"'.json/crud/'",
".",
"$",
"properties",
"[",
"'_id'",
"]",
",",
"[",
"]",
",",
"$",
"properties",
")",
";",
"}"
] |
This will save an entity in Communibase. When a _id-field is found, this entity will be updated
NOTE: When updating, depending on the Entity, you may need to include all fields.
@param string $entityType
@param array $properties - the to-be-saved entity data
@return array resultData
@throws Exception
|
[
"This",
"will",
"save",
"an",
"entity",
"in",
"Communibase",
".",
"When",
"a",
"_id",
"-",
"field",
"is",
"found",
"this",
"entity",
"will",
"be",
"updated"
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L336-L342
|
kingsquare/communibase-connector-php
|
src/Communibase/Connector.php
|
Connector.finalize
|
public function finalize($entityType, $id)
{
if ($entityType !== 'Invoice') {
throw new Exception('Cannot call finalize on ' . $entityType);
}
return $this->doPost($entityType . '.json/finalize/' . $id);
}
|
php
|
public function finalize($entityType, $id)
{
if ($entityType !== 'Invoice') {
throw new Exception('Cannot call finalize on ' . $entityType);
}
return $this->doPost($entityType . '.json/finalize/' . $id);
}
|
[
"public",
"function",
"finalize",
"(",
"$",
"entityType",
",",
"$",
"id",
")",
"{",
"if",
"(",
"$",
"entityType",
"!==",
"'Invoice'",
")",
"{",
"throw",
"new",
"Exception",
"(",
"'Cannot call finalize on '",
".",
"$",
"entityType",
")",
";",
"}",
"return",
"$",
"this",
"->",
"doPost",
"(",
"$",
"entityType",
".",
"'.json/finalize/'",
".",
"$",
"id",
")",
";",
"}"
] |
Finalize an invoice by adding an invoiceNumber to it.
Besides, invoice items will receive a 'generalLedgerAccountNumber'.
This number will be unique and sequential within the 'daybook' of the invoice.
NOTE: this is Invoice specific
@param string $entityType
@param string $id
@return array
@throws Exception
|
[
"Finalize",
"an",
"invoice",
"by",
"adding",
"an",
"invoiceNumber",
"to",
"it",
".",
"Besides",
"invoice",
"items",
"will",
"receive",
"a",
"generalLedgerAccountNumber",
".",
"This",
"number",
"will",
"be",
"unique",
"and",
"sequential",
"within",
"the",
"daybook",
"of",
"the",
"invoice",
"."
] |
train
|
https://github.com/kingsquare/communibase-connector-php/blob/f1f9699e1a8acf066fab308f1e86cb8b5548e2db/src/Communibase/Connector.php#L358-L365
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.