repo stringlengths 6 63 | path stringlengths 5 140 | func_name stringlengths 3 151 | original_string stringlengths 84 13k | language stringclasses 1
value | code stringlengths 84 13k | code_tokens list | docstring stringlengths 3 47.2k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 91 247 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
dereuromark/cakephp-tools | src/Model/Behavior/JsonableBehavior.php | JsonableBehavior._decode | public function _decode($val) {
if (!is_string($val)) {
return $val;
}
$decoded = json_decode($val, $this->_config['decodeParams']['assoc'], $this->_config['decodeParams']['depth'], $this->_config['decodeParams']['options']);
if ($decoded === false) {
return false;
}
if ($this->_config['decodeParams']['assoc']) {
$decoded = (array)$decoded;
}
if ($this->_config['output'] === 'param') {
$decoded = $this->_toParam($decoded);
} elseif ($this->_config['output'] === 'list') {
$decoded = $this->_toList($decoded);
}
return $decoded;
} | php | public function _decode($val) {
if (!is_string($val)) {
return $val;
}
$decoded = json_decode($val, $this->_config['decodeParams']['assoc'], $this->_config['decodeParams']['depth'], $this->_config['decodeParams']['options']);
if ($decoded === false) {
return false;
}
if ($this->_config['decodeParams']['assoc']) {
$decoded = (array)$decoded;
}
if ($this->_config['output'] === 'param') {
$decoded = $this->_toParam($decoded);
} elseif ($this->_config['output'] === 'list') {
$decoded = $this->_toList($decoded);
}
return $decoded;
} | [
"public",
"function",
"_decode",
"(",
"$",
"val",
")",
"{",
"if",
"(",
"!",
"is_string",
"(",
"$",
"val",
")",
")",
"{",
"return",
"$",
"val",
";",
"}",
"$",
"decoded",
"=",
"json_decode",
"(",
"$",
"val",
",",
"$",
"this",
"->",
"_config",
"[",
... | Fields are absolutely necessary to function properly!
@param array|null $val
@return array|null|false | [
"Fields",
"are",
"absolutely",
"necessary",
"to",
"function",
"properly!"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/JsonableBehavior.php#L217-L236 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaRobots | public function metaRobots($type = null) {
if ($type === null && ($meta = Configure::read('Config.robots')) !== null) {
$type = $meta;
}
$content = [];
if ($type === 'public') {
//$this->privatePage = false;
$content['robots'] = ['index', 'follow', 'noarchive'];
} else {
//$this->privatePage = true;
$content['robots'] = ['noindex', 'nofollow', 'noarchive'];
}
$return = '<meta name="robots" content="' . implode(',', $content['robots']) . '" />';
return $return;
} | php | public function metaRobots($type = null) {
if ($type === null && ($meta = Configure::read('Config.robots')) !== null) {
$type = $meta;
}
$content = [];
if ($type === 'public') {
//$this->privatePage = false;
$content['robots'] = ['index', 'follow', 'noarchive'];
} else {
//$this->privatePage = true;
$content['robots'] = ['noindex', 'nofollow', 'noarchive'];
}
$return = '<meta name="robots" content="' . implode(',', $content['robots']) . '" />';
return $return;
} | [
"public",
"function",
"metaRobots",
"(",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"type",
"===",
"null",
"&&",
"(",
"$",
"meta",
"=",
"Configure",
"::",
"read",
"(",
"'Config.robots'",
")",
")",
"!==",
"null",
")",
"{",
"$",
"type",
"=",... | Convenience method for clean ROBOTS allowance
@param string|null $type - private/public
@return string HTML | [
"Convenience",
"method",
"for",
"clean",
"ROBOTS",
"allowance"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L71-L86 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaName | public function metaName($name = null, $content = null) {
if (empty($name) || empty($content)) {
return '';
}
$content = (array)$content;
$return = '<meta name="' . $name . '" content="' . implode(', ', $content) . '" />';
return $return;
} | php | public function metaName($name = null, $content = null) {
if (empty($name) || empty($content)) {
return '';
}
$content = (array)$content;
$return = '<meta name="' . $name . '" content="' . implode(', ', $content) . '" />';
return $return;
} | [
"public",
"function",
"metaName",
"(",
"$",
"name",
"=",
"null",
",",
"$",
"content",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"name",
")",
"||",
"empty",
"(",
"$",
"content",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"content",
... | Convenience method for clean meta name tags
@param string|null $name Author, date, generator, revisit-after, language
@param string|array|null $content If array, it will be separated by commas
@return string HTML Markup | [
"Convenience",
"method",
"for",
"clean",
"meta",
"name",
"tags"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L95-L103 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaDescription | public function metaDescription($content, $language = null, $options = []) {
if (!empty($language)) {
$options['lang'] = mb_strtolower($language);
} elseif ($language !== false) {
$options['lang'] = Configure::read('Config.locale');
}
return $this->Html->meta('description', $content, $options);
} | php | public function metaDescription($content, $language = null, $options = []) {
if (!empty($language)) {
$options['lang'] = mb_strtolower($language);
} elseif ($language !== false) {
$options['lang'] = Configure::read('Config.locale');
}
return $this->Html->meta('description', $content, $options);
} | [
"public",
"function",
"metaDescription",
"(",
"$",
"content",
",",
"$",
"language",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"language",
")",
")",
"{",
"$",
"options",
"[",
"'lang'",
"]",
"=",
... | Convenience method for meta description
@param string $content
@param string|null $language (iso2: de, en-us, ...)
@param array $options Additional options
@return string HTML Markup | [
"Convenience",
"method",
"for",
"meta",
"description"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L113-L120 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaKeywords | public function metaKeywords($keywords = null, $language = null, $escape = true) {
if ($keywords === null) {
$keywords = Configure::read('Config.keywords');
}
if (is_array($keywords)) {
$keywords = implode(', ', $keywords);
}
if ($escape) {
$keywords = h($keywords);
}
$options = [];
if (!empty($language)) {
$options['lang'] = mb_strtolower($language);
} elseif ($language !== false) {
$options['lang'] = Configure::read('Config.locale');
}
return $this->Html->meta('keywords', $keywords, $options);
} | php | public function metaKeywords($keywords = null, $language = null, $escape = true) {
if ($keywords === null) {
$keywords = Configure::read('Config.keywords');
}
if (is_array($keywords)) {
$keywords = implode(', ', $keywords);
}
if ($escape) {
$keywords = h($keywords);
}
$options = [];
if (!empty($language)) {
$options['lang'] = mb_strtolower($language);
} elseif ($language !== false) {
$options['lang'] = Configure::read('Config.locale');
}
return $this->Html->meta('keywords', $keywords, $options);
} | [
"public",
"function",
"metaKeywords",
"(",
"$",
"keywords",
"=",
"null",
",",
"$",
"language",
"=",
"null",
",",
"$",
"escape",
"=",
"true",
")",
"{",
"if",
"(",
"$",
"keywords",
"===",
"null",
")",
"{",
"$",
"keywords",
"=",
"Configure",
"::",
"read... | Convenience method to output meta keywords
@param string|array|null $keywords
@param string|null $language (iso2: de, en-us, ...)
@param bool $escape
@return string HTML Markup | [
"Convenience",
"method",
"to",
"output",
"meta",
"keywords"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L130-L147 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaCanonical | public function metaCanonical($url = null, $full = false) {
$canonical = $this->Url->build($url, $full);
$options = ['rel' => 'canonical', 'link' => $canonical];
return $this->Html->meta($options);
} | php | public function metaCanonical($url = null, $full = false) {
$canonical = $this->Url->build($url, $full);
$options = ['rel' => 'canonical', 'link' => $canonical];
return $this->Html->meta($options);
} | [
"public",
"function",
"metaCanonical",
"(",
"$",
"url",
"=",
"null",
",",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"canonical",
"=",
"$",
"this",
"->",
"Url",
"->",
"build",
"(",
"$",
"url",
",",
"$",
"full",
")",
";",
"$",
"options",
"=",
"[",
... | Convenience function for "canonical" SEO links
@param string|array|null $url
@param bool $full
@return string HTML Markup | [
"Convenience",
"function",
"for",
"canonical",
"SEO",
"links"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L156-L160 | train |
dereuromark/cakephp-tools | src/View/Helper/CommonHelper.php | CommonHelper.metaAlternate | public function metaAlternate($url, $lang, $full = false) {
//$canonical = $this->Url->build($url, $full);
$url = $this->Url->build($url, $full);
//return $this->Html->meta('canonical', $canonical, array('rel'=>'canonical', 'type'=>null, 'title'=>null));
$lang = (array)$lang;
$res = [];
foreach ($lang as $language => $countries) {
if (is_numeric($language)) {
$language = '';
} else {
$language .= '-';
}
$countries = (array)$countries;
foreach ($countries as $country) {
$l = $language . $country;
$options = ['rel' => 'alternate', 'hreflang' => $l, 'link' => $url];
$res[] = $this->Html->meta($options) . PHP_EOL;
}
}
return implode('', $res);
} | php | public function metaAlternate($url, $lang, $full = false) {
//$canonical = $this->Url->build($url, $full);
$url = $this->Url->build($url, $full);
//return $this->Html->meta('canonical', $canonical, array('rel'=>'canonical', 'type'=>null, 'title'=>null));
$lang = (array)$lang;
$res = [];
foreach ($lang as $language => $countries) {
if (is_numeric($language)) {
$language = '';
} else {
$language .= '-';
}
$countries = (array)$countries;
foreach ($countries as $country) {
$l = $language . $country;
$options = ['rel' => 'alternate', 'hreflang' => $l, 'link' => $url];
$res[] = $this->Html->meta($options) . PHP_EOL;
}
}
return implode('', $res);
} | [
"public",
"function",
"metaAlternate",
"(",
"$",
"url",
",",
"$",
"lang",
",",
"$",
"full",
"=",
"false",
")",
"{",
"//$canonical = $this->Url->build($url, $full);",
"$",
"url",
"=",
"$",
"this",
"->",
"Url",
"->",
"build",
"(",
"$",
"url",
",",
"$",
"fu... | Convenience method for "alternate" SEO links
@param string|array $url
@param string|array $lang (lang(iso2) or array of langs)
lang: language (in ISO 6391-1 format) + optionally the region (in ISO 3166-1 Alpha 2 format)
- de
- de-ch
etc
@param bool $full
@return string HTML Markup | [
"Convenience",
"method",
"for",
"alternate",
"SEO",
"links"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/CommonHelper.php#L174-L194 | train |
dereuromark/cakephp-tools | src/Model/Behavior/PasswordableBehavior.php | PasswordableBehavior.beforeSave | public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
$formField = $this->_config['formField'];
$field = $this->_config['field'];
$PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
if ($entity->get($formField) !== null) {
$entity->set($field, $PasswordHasher->hash($entity->get($formField)));
if (!$entity->get($field)) {
throw new RuntimeException('Empty field');
}
$entity->unsetProperty($formField);
//$entity->set($formField, null);
if ($this->_config['confirm']) {
$formFieldRepeat = $this->_config['formFieldRepeat'];
$entity->unsetProperty($formFieldRepeat);
}
if ($this->_config['current']) {
$formFieldCurrent = $this->_config['formFieldCurrent'];
$entity->unsetProperty($formFieldCurrent);
}
} else {
// To help mitigate timing-based user enumeration attacks.
$PasswordHasher->hash('');
}
} | php | public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) {
$formField = $this->_config['formField'];
$field = $this->_config['field'];
$PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
if ($entity->get($formField) !== null) {
$entity->set($field, $PasswordHasher->hash($entity->get($formField)));
if (!$entity->get($field)) {
throw new RuntimeException('Empty field');
}
$entity->unsetProperty($formField);
//$entity->set($formField, null);
if ($this->_config['confirm']) {
$formFieldRepeat = $this->_config['formFieldRepeat'];
$entity->unsetProperty($formFieldRepeat);
}
if ($this->_config['current']) {
$formFieldCurrent = $this->_config['formFieldCurrent'];
$entity->unsetProperty($formFieldCurrent);
}
} else {
// To help mitigate timing-based user enumeration attacks.
$PasswordHasher->hash('');
}
} | [
"public",
"function",
"beforeSave",
"(",
"Event",
"$",
"event",
",",
"EntityInterface",
"$",
"entity",
",",
"ArrayObject",
"$",
"options",
")",
"{",
"$",
"formField",
"=",
"$",
"this",
"->",
"_config",
"[",
"'formField'",
"]",
";",
"$",
"field",
"=",
"$"... | Hashing the password and whitelisting
@param \Cake\Event\Event $event
@param \Cake\Datasource\EntityInterface $entity
@param \ArrayObject $options
@throws \RuntimeException
@return void | [
"Hashing",
"the",
"password",
"and",
"whitelisting"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/PasswordableBehavior.php#L314-L342 | train |
dereuromark/cakephp-tools | src/View/Helper/TypographyHelper.php | TypographyHelper.nl2brExceptPre | public function nl2brExceptPre($str) {
$ex = explode('pre>', $str);
$ct = count($ex);
$newstr = '';
for ($i = 0; $i < $ct; $i++) {
if (($i % 2) == 0) {
$newstr .= nl2br($ex[$i]);
} else {
$newstr .= $ex[$i];
}
if ($ct - 1 != $i) {
$newstr .= 'pre>';
}
}
return $newstr;
} | php | public function nl2brExceptPre($str) {
$ex = explode('pre>', $str);
$ct = count($ex);
$newstr = '';
for ($i = 0; $i < $ct; $i++) {
if (($i % 2) == 0) {
$newstr .= nl2br($ex[$i]);
} else {
$newstr .= $ex[$i];
}
if ($ct - 1 != $i) {
$newstr .= 'pre>';
}
}
return $newstr;
} | [
"public",
"function",
"nl2brExceptPre",
"(",
"$",
"str",
")",
"{",
"$",
"ex",
"=",
"explode",
"(",
"'pre>'",
",",
"$",
"str",
")",
";",
"$",
"ct",
"=",
"count",
"(",
"$",
"ex",
")",
";",
"$",
"newstr",
"=",
"''",
";",
"for",
"(",
"$",
"i",
"=... | Convert newlines to HTML line breaks except within PRE tags
@param string $str
@return string | [
"Convert",
"newlines",
"to",
"HTML",
"line",
"breaks",
"except",
"within",
"PRE",
"tags"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TypographyHelper.php#L360-L378 | train |
dereuromark/cakephp-tools | src/View/Helper/QrCodeHelper.php | QrCodeHelper.image | public function image($text, array $options = []) {
return $this->Html->image($this->uri($text), $options);
} | php | public function image($text, array $options = []) {
return $this->Html->image($this->uri($text), $options);
} | [
"public",
"function",
"image",
"(",
"$",
"text",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"return",
"$",
"this",
"->",
"Html",
"->",
"image",
"(",
"$",
"this",
"->",
"uri",
"(",
"$",
"text",
")",
",",
"$",
"options",
")",
";",
"}"... | Main barcode display function
Note: set size or level manually prior to calling this method
@param string $text Text (utf8 encoded)
@param array $options Options
@return string HTML | [
"Main",
"barcode",
"display",
"function"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/QrCodeHelper.php#L96-L98 | train |
dereuromark/cakephp-tools | src/View/Helper/QrCodeHelper.php | QrCodeHelper.formatText | public function formatText($text, $type = null) {
switch ($type) {
case 'text':
break;
case 'url':
$text = $this->Url->build($text, true);
break;
case 'sms':
$text = 'smsto:' . implode(':', (array)$text);
break;
case 'tel':
$text = 'tel:' . $text;
break;
case 'email':
$text = 'mailto:' . $text;
break;
case 'geo':
$text = 'geo:' . implode(',', (array)$text); #like 77.1,11.8
break;
case 'market':
$text = 'market://search?q=pname:' . $text;
}
return $text;
} | php | public function formatText($text, $type = null) {
switch ($type) {
case 'text':
break;
case 'url':
$text = $this->Url->build($text, true);
break;
case 'sms':
$text = 'smsto:' . implode(':', (array)$text);
break;
case 'tel':
$text = 'tel:' . $text;
break;
case 'email':
$text = 'mailto:' . $text;
break;
case 'geo':
$text = 'geo:' . implode(',', (array)$text); #like 77.1,11.8
break;
case 'market':
$text = 'market://search?q=pname:' . $text;
}
return $text;
} | [
"public",
"function",
"formatText",
"(",
"$",
"text",
",",
"$",
"type",
"=",
"null",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'text'",
":",
"break",
";",
"case",
"'url'",
":",
"$",
"text",
"=",
"$",
"this",
"->",
"Url",
"->",
"bui... | Format a text in a specific format
- url, sms, tel, email, market, geo
@param string|array $text
@param string|null $type
@return string formattedText | [
"Format",
"a",
"text",
"in",
"a",
"specific",
"format",
"-",
"url",
"sms",
"tel",
"email",
"market",
"geo"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/QrCodeHelper.php#L134-L157 | train |
dereuromark/cakephp-tools | src/Controller/Component/MobileComponent.php | MobileComponent._init | protected function _init() {
$mobileOverwrite = $this->Controller->getRequest()->getQuery('mobile');
if ($mobileOverwrite !== null) {
if ($mobileOverwrite === '-1') {
$this->Controller->getRequest()->getSession()->delete('User.mobile');
} else {
$wantsMobile = (bool)$mobileOverwrite;
$this->Controller->getRequest()->getSession()->write('User.mobile', (int)$wantsMobile);
}
}
$this->isMobile();
if (!$this->_config['auto']) {
return;
}
$this->setMobile();
} | php | protected function _init() {
$mobileOverwrite = $this->Controller->getRequest()->getQuery('mobile');
if ($mobileOverwrite !== null) {
if ($mobileOverwrite === '-1') {
$this->Controller->getRequest()->getSession()->delete('User.mobile');
} else {
$wantsMobile = (bool)$mobileOverwrite;
$this->Controller->getRequest()->getSession()->write('User.mobile', (int)$wantsMobile);
}
}
$this->isMobile();
if (!$this->_config['auto']) {
return;
}
$this->setMobile();
} | [
"protected",
"function",
"_init",
"(",
")",
"{",
"$",
"mobileOverwrite",
"=",
"$",
"this",
"->",
"Controller",
"->",
"getRequest",
"(",
")",
"->",
"getQuery",
"(",
"'mobile'",
")",
";",
"if",
"(",
"$",
"mobileOverwrite",
"!==",
"null",
")",
"{",
"if",
... | Main auto-detection logic including session based storage to avoid
multiple lookups.
Uses "mobile" query string to overwrite the auto-detection.
-1 clears the fixation
1 forces mobile
0 forces no-mobile
@return void | [
"Main",
"auto",
"-",
"detection",
"logic",
"including",
"session",
"based",
"storage",
"to",
"avoid",
"multiple",
"lookups",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/MobileComponent.php#L97-L114 | train |
dereuromark/cakephp-tools | src/Controller/Component/MobileComponent.php | MobileComponent.setMobile | public function setMobile() {
if ($this->isMobile === null) {
$this->isMobile();
}
$forceMobile = $this->Controller->getRequest()->getSession()->read('User.mobile');
if ($forceMobile !== null && !$forceMobile) {
$this->setMobile = false;
} elseif ($forceMobile !== null && $forceMobile || $this->isMobile()) {
$this->setMobile = true;
} else {
$this->setMobile = false;
}
//$urlParams = Router::getParams(true);
$urlParams = [];
if (!isset($urlParams['pass'])) {
$urlParams['pass'] = [];
}
$urlParams = array_merge($urlParams, $urlParams['pass']);
unset($urlParams['pass']);
if (isset($urlParams['prefix'])) {
unset($urlParams['prefix']);
}
if ($this->setMobile) {
$urlParams['?']['mobile'] = 0;
$url = Router::url($urlParams);
$this->Controller->set('desktopUrl', $url);
} else {
$urlParams['?']['mobile'] = 1;
$url = Router::url($urlParams);
$this->Controller->set('mobileUrl', $url);
}
Configure::write('User.setMobile', (int)$this->setMobile);
if (!$this->setMobile) {
return;
}
$this->Controller->viewBuilder()->setClassName('Theme');
$this->Controller->viewBuilder()->setTheme('Mobile');
} | php | public function setMobile() {
if ($this->isMobile === null) {
$this->isMobile();
}
$forceMobile = $this->Controller->getRequest()->getSession()->read('User.mobile');
if ($forceMobile !== null && !$forceMobile) {
$this->setMobile = false;
} elseif ($forceMobile !== null && $forceMobile || $this->isMobile()) {
$this->setMobile = true;
} else {
$this->setMobile = false;
}
//$urlParams = Router::getParams(true);
$urlParams = [];
if (!isset($urlParams['pass'])) {
$urlParams['pass'] = [];
}
$urlParams = array_merge($urlParams, $urlParams['pass']);
unset($urlParams['pass']);
if (isset($urlParams['prefix'])) {
unset($urlParams['prefix']);
}
if ($this->setMobile) {
$urlParams['?']['mobile'] = 0;
$url = Router::url($urlParams);
$this->Controller->set('desktopUrl', $url);
} else {
$urlParams['?']['mobile'] = 1;
$url = Router::url($urlParams);
$this->Controller->set('mobileUrl', $url);
}
Configure::write('User.setMobile', (int)$this->setMobile);
if (!$this->setMobile) {
return;
}
$this->Controller->viewBuilder()->setClassName('Theme');
$this->Controller->viewBuilder()->setTheme('Mobile');
} | [
"public",
"function",
"setMobile",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isMobile",
"===",
"null",
")",
"{",
"$",
"this",
"->",
"isMobile",
"(",
")",
";",
"}",
"$",
"forceMobile",
"=",
"$",
"this",
"->",
"Controller",
"->",
"getRequest",
"(",... | Sets mobile views as `Mobile` theme.
Only needs to be called if auto is set to false.
Then you probably want to call this from your AppController::beforeRender().
@return void | [
"Sets",
"mobile",
"views",
"as",
"Mobile",
"theme",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/MobileComponent.php#L124-L167 | train |
dereuromark/cakephp-tools | src/Controller/Component/MobileComponent.php | MobileComponent.isMobile | public function isMobile() {
if ($this->isMobile !== null) {
return $this->isMobile;
}
$this->isMobile = Configure::read('User.isMobile');
if ($this->isMobile !== null) {
return $this->isMobile;
}
$this->isMobile = (bool)$this->detect();
Configure::write('User.isMobile', (int)$this->isMobile);
return $this->isMobile;
} | php | public function isMobile() {
if ($this->isMobile !== null) {
return $this->isMobile;
}
$this->isMobile = Configure::read('User.isMobile');
if ($this->isMobile !== null) {
return $this->isMobile;
}
$this->isMobile = (bool)$this->detect();
Configure::write('User.isMobile', (int)$this->isMobile);
return $this->isMobile;
} | [
"public",
"function",
"isMobile",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isMobile",
"!==",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"isMobile",
";",
"}",
"$",
"this",
"->",
"isMobile",
"=",
"Configure",
"::",
"read",
"(",
"'User.isMobile'"... | Determines if we need to so serve mobile views based on session preference
and browser headers.
@return bool Success | [
"Determines",
"if",
"we",
"need",
"to",
"so",
"serve",
"mobile",
"views",
"based",
"on",
"session",
"preference",
"and",
"browser",
"headers",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/MobileComponent.php#L175-L188 | train |
dereuromark/cakephp-tools | src/Controller/Component/MobileComponent.php | MobileComponent.detect | public function detect() {
// Deprecated - the vendor libs are far more accurate and up to date
if (!$this->_config['engine']) {
if (isset($this->Controller->RequestHandler)) {
return $this->Controller->getRequest()->is('mobile') || $this->Controller->RequestHandler->accepts('wap');
}
return $this->Controller->getRequest()->is('mobile');
}
if (is_callable($this->_config['engine'])) {
return call_user_func($this->_config['engine']);
}
throw new RuntimeException(sprintf('Engine %s not available', $this->_config['engine']));
} | php | public function detect() {
// Deprecated - the vendor libs are far more accurate and up to date
if (!$this->_config['engine']) {
if (isset($this->Controller->RequestHandler)) {
return $this->Controller->getRequest()->is('mobile') || $this->Controller->RequestHandler->accepts('wap');
}
return $this->Controller->getRequest()->is('mobile');
}
if (is_callable($this->_config['engine'])) {
return call_user_func($this->_config['engine']);
}
throw new RuntimeException(sprintf('Engine %s not available', $this->_config['engine']));
} | [
"public",
"function",
"detect",
"(",
")",
"{",
"// Deprecated - the vendor libs are far more accurate and up to date",
"if",
"(",
"!",
"$",
"this",
"->",
"_config",
"[",
"'engine'",
"]",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"Controller",
"->",
... | Detects if the current request is from a mobile device.
Note that the cake internal way might soon be deprecated:
https://github.com/cakephp/cakephp/issues/2546
@return bool Success
@throws \RuntimeException | [
"Detects",
"if",
"the",
"current",
"request",
"is",
"from",
"a",
"mobile",
"device",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/MobileComponent.php#L199-L211 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.neighbors | public function neighbors(array $neighbors, $field, array $options = []) {
$name = 'Record'; // Translation further down!
if (!empty($options['name'])) {
$name = ucfirst($options['name']);
}
$prevSlug = $nextSlug = null;
if (!empty($options['slug'])) {
if (!empty($neighbors['prev'])) {
$prevSlug = $this->slug($neighbors['prev'][$field]);
}
if (!empty($neighbors['next'])) {
$nextSlug = $this->slug($neighbors['next'][$field]);
}
}
$titleField = $field;
if (!empty($options['titleField'])) {
$titleField = $options['titleField'];
}
if (!isset($options['escape']) || $options['escape'] === false) {
$titleField = h($titleField);
}
$ret = '<div class="next-prev-navi nextPrevNavi">';
if (!empty($neighbors['prev'])) {
$url = [$neighbors['prev']['id'], $prevSlug];
if (!empty($options['url'])) {
$url += $options['url'];
}
$ret .= $this->Html->link(
$this->icon('prev') . ' ' . __d('tools', 'prev' . $name),
$url,
['escape' => false, 'title' => $neighbors['prev'][$titleField]]
);
} else {
$ret .= $this->icon('prev');
}
$ret .= ' ';
if (!empty($neighbors['next'])) {
$url = [$neighbors['next']['id'], $nextSlug];
if (!empty($options['url'])) {
$url += $options['url'];
}
$ret .= $this->Html->link(
$this->icon('next') . ' ' . __d('tools', 'next' . $name),
$url,
['escape' => false, 'title' => $neighbors['next'][$titleField]]
);
} else {
$ret .= $this->icon('next') . ' ' . __d('tools', 'next' . $name);
}
$ret .= '</div>';
return $ret;
} | php | public function neighbors(array $neighbors, $field, array $options = []) {
$name = 'Record'; // Translation further down!
if (!empty($options['name'])) {
$name = ucfirst($options['name']);
}
$prevSlug = $nextSlug = null;
if (!empty($options['slug'])) {
if (!empty($neighbors['prev'])) {
$prevSlug = $this->slug($neighbors['prev'][$field]);
}
if (!empty($neighbors['next'])) {
$nextSlug = $this->slug($neighbors['next'][$field]);
}
}
$titleField = $field;
if (!empty($options['titleField'])) {
$titleField = $options['titleField'];
}
if (!isset($options['escape']) || $options['escape'] === false) {
$titleField = h($titleField);
}
$ret = '<div class="next-prev-navi nextPrevNavi">';
if (!empty($neighbors['prev'])) {
$url = [$neighbors['prev']['id'], $prevSlug];
if (!empty($options['url'])) {
$url += $options['url'];
}
$ret .= $this->Html->link(
$this->icon('prev') . ' ' . __d('tools', 'prev' . $name),
$url,
['escape' => false, 'title' => $neighbors['prev'][$titleField]]
);
} else {
$ret .= $this->icon('prev');
}
$ret .= ' ';
if (!empty($neighbors['next'])) {
$url = [$neighbors['next']['id'], $nextSlug];
if (!empty($options['url'])) {
$url += $options['url'];
}
$ret .= $this->Html->link(
$this->icon('next') . ' ' . __d('tools', 'next' . $name),
$url,
['escape' => false, 'title' => $neighbors['next'][$titleField]]
);
} else {
$ret .= $this->icon('next') . ' ' . __d('tools', 'next' . $name);
}
$ret .= '</div>';
return $ret;
} | [
"public",
"function",
"neighbors",
"(",
"array",
"$",
"neighbors",
",",
"$",
"field",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"name",
"=",
"'Record'",
";",
"// Translation further down!",
"if",
"(",
"!",
"empty",
"(",
"$",
"options",
... | Display neighbor quicklinks
@param array $neighbors (containing prev and next)
@param string $field : just field or Model.field syntax
@param array $options :
- name: title name: next{Record} (if none is provided, "record" is used - not translated!)
- slug: true/false (defaults to false)
- titleField: field or Model.field
@return string | [
"Display",
"neighbor",
"quicklinks"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L112-L170 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.genderIcon | public function genderIcon($value) {
$value = (int)$value;
if ($value == static::GENDER_FEMALE) {
$icon = $this->icon('female');
} elseif ($value == static::GENDER_MALE) {
$icon = $this->icon('male');
} else {
$icon = $this->icon('genderless', [], ['title' => __d('tools', 'Unknown')]);
}
return $icon;
} | php | public function genderIcon($value) {
$value = (int)$value;
if ($value == static::GENDER_FEMALE) {
$icon = $this->icon('female');
} elseif ($value == static::GENDER_MALE) {
$icon = $this->icon('male');
} else {
$icon = $this->icon('genderless', [], ['title' => __d('tools', 'Unknown')]);
}
return $icon;
} | [
"public",
"function",
"genderIcon",
"(",
"$",
"value",
")",
"{",
"$",
"value",
"=",
"(",
"int",
")",
"$",
"value",
";",
"if",
"(",
"$",
"value",
"==",
"static",
"::",
"GENDER_FEMALE",
")",
"{",
"$",
"icon",
"=",
"$",
"this",
"->",
"icon",
"(",
"'... | Displays gender icon
@param mixed $value
@return string | [
"Displays",
"gender",
"icon"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L181-L191 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.icon | public function icon($icon, array $options = [], array $attributes = []) {
if (!$icon) {
return '';
}
$defaults = [
'translate' => true,
];
$options += $defaults;
$type = $icon;
if ($this->getConfig('autoPrefix') && empty($options['iconNamespace'])) {
$namespace = $this->detectNamespace($icon);
if ($namespace) {
$options['iconNamespace'] = $namespace;
$options['autoPrefix'] = false;
$icon = substr($icon, strlen($namespace) + 1);
}
}
if (!isset($attributes['title'])) {
if (isset($options['title'])) {
$attributes['title'] = $options['title'];
} else {
$attributes['title'] = Inflector::humanize($icon);
}
}
return $this->_fontIcon($type, $options, $attributes);
} | php | public function icon($icon, array $options = [], array $attributes = []) {
if (!$icon) {
return '';
}
$defaults = [
'translate' => true,
];
$options += $defaults;
$type = $icon;
if ($this->getConfig('autoPrefix') && empty($options['iconNamespace'])) {
$namespace = $this->detectNamespace($icon);
if ($namespace) {
$options['iconNamespace'] = $namespace;
$options['autoPrefix'] = false;
$icon = substr($icon, strlen($namespace) + 1);
}
}
if (!isset($attributes['title'])) {
if (isset($options['title'])) {
$attributes['title'] = $options['title'];
} else {
$attributes['title'] = Inflector::humanize($icon);
}
}
return $this->_fontIcon($type, $options, $attributes);
} | [
"public",
"function",
"icon",
"(",
"$",
"icon",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"icon",
")",
"{",
"return",
"''",
";",
"}",
"$",
"defaults",
"=",
"[",
... | Icons using the default namespace or an already prefixed one.
@param string $icon (constant or filename)
@param array $options :
- translate, title, ...
@param array $attributes :
- class, ...
@return string | [
"Icons",
"using",
"the",
"default",
"namespace",
"or",
"an",
"already",
"prefixed",
"one",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L249-L278 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper._customIcon | protected function _customIcon($icon, array $options = [], array $attributes = []) {
$translate = isset($options['translate']) ? $options['translate'] : true;
$type = pathinfo($icon, PATHINFO_FILENAME);
$title = ucfirst($type);
$alt = $this->slug($title);
if ($translate !== false) {
$title = __($title);
$alt = __($alt);
}
$alt = '[' . $alt . ']';
$defaults = ['title' => $title, 'alt' => $alt, 'class' => 'icon'];
$options = $attributes + $options;
$options += $defaults;
if (substr($icon, 0, 1) !== '/') {
$icon = 'icons/' . $icon;
}
return $this->Html->image($icon, $options);
} | php | protected function _customIcon($icon, array $options = [], array $attributes = []) {
$translate = isset($options['translate']) ? $options['translate'] : true;
$type = pathinfo($icon, PATHINFO_FILENAME);
$title = ucfirst($type);
$alt = $this->slug($title);
if ($translate !== false) {
$title = __($title);
$alt = __($alt);
}
$alt = '[' . $alt . ']';
$defaults = ['title' => $title, 'alt' => $alt, 'class' => 'icon'];
$options = $attributes + $options;
$options += $defaults;
if (substr($icon, 0, 1) !== '/') {
$icon = 'icons/' . $icon;
}
return $this->Html->image($icon, $options);
} | [
"protected",
"function",
"_customIcon",
"(",
"$",
"icon",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"$",
"translate",
"=",
"isset",
"(",
"$",
"options",
"[",
"'translate'",
"]",
")",
"?",
... | Deprecated img icons, font icons should be used instead, but sometimes
we still need a custom img icon.
@param string $icon (constant or filename)
@param array $options :
- translate, title, ...
@param array $attributes :
- class, ...
@return string | [
"Deprecated",
"img",
"icons",
"font",
"icons",
"should",
"be",
"used",
"instead",
"but",
"sometimes",
"we",
"still",
"need",
"a",
"custom",
"img",
"icon",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L322-L342 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper._fontIcon | protected function _fontIcon($type, $options, $attributes) {
$iconClass = $type;
$options += $this->_config;
if ($options['autoPrefix'] && $options['iconNamespace']) {
$iconClass = $options['iconNamespace'] . '-' . $iconClass;
}
if ($options['iconNamespace']) {
$iconClass = $options['iconNamespace'] . ' ' . $iconClass;
}
if (isset($this->_config['fontIcons'][$type])) {
$iconClass = $this->_config['fontIcons'][$type];
}
$defaults = [
'class' => 'icon icon-' . $type . ' ' . $iconClass,
'escape' => true,
];
$options += $defaults;
if (!isset($attributes['title'])) {
$attributes['title'] = ucfirst($type);
if (!isset($options['translate']) || $options['translate'] !== false) {
$attributes['title'] = __($attributes['title']);
}
}
$attributes += [
'data-placement' => 'bottom',
'data-toggle' => 'tooltip'
];
$formatOptions = $attributes + [
'escape' => $options['escape'],
];
$options['attributes'] = $this->template->formatAttributes($formatOptions);
return $this->template->format('icon', $options);
} | php | protected function _fontIcon($type, $options, $attributes) {
$iconClass = $type;
$options += $this->_config;
if ($options['autoPrefix'] && $options['iconNamespace']) {
$iconClass = $options['iconNamespace'] . '-' . $iconClass;
}
if ($options['iconNamespace']) {
$iconClass = $options['iconNamespace'] . ' ' . $iconClass;
}
if (isset($this->_config['fontIcons'][$type])) {
$iconClass = $this->_config['fontIcons'][$type];
}
$defaults = [
'class' => 'icon icon-' . $type . ' ' . $iconClass,
'escape' => true,
];
$options += $defaults;
if (!isset($attributes['title'])) {
$attributes['title'] = ucfirst($type);
if (!isset($options['translate']) || $options['translate'] !== false) {
$attributes['title'] = __($attributes['title']);
}
}
$attributes += [
'data-placement' => 'bottom',
'data-toggle' => 'tooltip'
];
$formatOptions = $attributes + [
'escape' => $options['escape'],
];
$options['attributes'] = $this->template->formatAttributes($formatOptions);
return $this->template->format('icon', $options);
} | [
"protected",
"function",
"_fontIcon",
"(",
"$",
"type",
",",
"$",
"options",
",",
"$",
"attributes",
")",
"{",
"$",
"iconClass",
"=",
"$",
"type",
";",
"$",
"options",
"+=",
"$",
"this",
"->",
"_config",
";",
"if",
"(",
"$",
"options",
"[",
"'autoPre... | Renders a font icon.
@param string $type
@param array $options
@param array $attributes
@return string | [
"Renders",
"a",
"font",
"icon",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L352-L390 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.disabledLink | public function disabledLink($text, array $options = []) {
$defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
$options += $defaults;
return $this->Html->tag('span', $text, $options);
} | php | public function disabledLink($text, array $options = []) {
$defaults = ['class' => 'disabledLink', 'title' => __d('tools', 'notAvailable')];
$options += $defaults;
return $this->Html->tag('span', $text, $options);
} | [
"public",
"function",
"disabledLink",
"(",
"$",
"text",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'class'",
"=>",
"'disabledLink'",
",",
"'title'",
"=>",
"__d",
"(",
"'tools'",
",",
"'notAvailable'",
")",
"]",
"... | Display a disabled link tag
@param string $text
@param array $options
@return string | [
"Display",
"a",
"disabled",
"link",
"tag"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L468-L473 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.warning | public function warning($value, $ok = false) {
if (!$ok) {
return $this->ok($value, false);
}
return $value;
} | php | public function warning($value, $ok = false) {
if (!$ok) {
return $this->ok($value, false);
}
return $value;
} | [
"public",
"function",
"warning",
"(",
"$",
"value",
",",
"$",
"ok",
"=",
"false",
")",
"{",
"if",
"(",
"!",
"$",
"ok",
")",
"{",
"return",
"$",
"this",
"->",
"ok",
"(",
"$",
"value",
",",
"false",
")",
";",
"}",
"return",
"$",
"value",
";",
"... | Returns red colored if not ok
@param string $value
@param mixed $ok Boolish value
@return string Value in HTML tags | [
"Returns",
"red",
"colored",
"if",
"not",
"ok"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L540-L545 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.ok | public function ok($content, $ok = false, array $attributes = []) {
if ($ok) {
$type = 'yes';
$color = 'green';
} else {
$type = 'no';
$color = 'red';
}
$options = [
'type' => $type,
'color' => $color
];
$options['content'] = $content;
$options['attributes'] = $this->template->formatAttributes($attributes);
return $this->template->format('ok', $options);
} | php | public function ok($content, $ok = false, array $attributes = []) {
if ($ok) {
$type = 'yes';
$color = 'green';
} else {
$type = 'no';
$color = 'red';
}
$options = [
'type' => $type,
'color' => $color
];
$options['content'] = $content;
$options['attributes'] = $this->template->formatAttributes($attributes);
return $this->template->format('ok', $options);
} | [
"public",
"function",
"ok",
"(",
"$",
"content",
",",
"$",
"ok",
"=",
"false",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"ok",
")",
"{",
"$",
"type",
"=",
"'yes'",
";",
"$",
"color",
"=",
"'green'",
";",
"}",
"... | Returns green on ok, red otherwise
@todo Remove inline css and make classes better: green=>ok red=>not-ok
Maybe use templating
@param mixed $content Output
@param bool $ok Boolish value
@param array $attributes
@return string Value nicely formatted/colored | [
"Returns",
"green",
"on",
"ok",
"red",
"otherwise"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L558-L574 | train |
dereuromark/cakephp-tools | src/View/Helper/FormatHelper.php | FormatHelper.array2table | public function array2table(array $array, array $options = [], array $attributes = []) {
$defaults = [
'null' => ' ',
'recursive' => false,
'heading' => true,
'escape' => true
];
$options += $defaults;
// Sanity check
if (empty($array)) {
return '';
}
if (!isset($array[0]) || !is_array($array[0])) {
$array = [$array];
}
$attributes += [
'class' => 'table'
];
$attributes = $this->template->formatAttributes($attributes);
// Start the table
$table = "<table$attributes>\n";
if ($options['heading']) {
// The header
$table .= "\t<tr>";
// Take the keys from the first row as the headings
foreach (array_keys($array[0]) as $heading) {
$table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
}
$table .= "</tr>\n";
}
// The body
foreach ($array as $row) {
$table .= "\t<tr>";
foreach ($row as $cell) {
$table .= '<td>';
// Cast objects
if (is_object($cell)) {
$cell = (array)$cell;
}
if ($options['recursive'] && is_array($cell) && !empty($cell)) {
// Recursive mode
$table .= "\n" . static::array2table($cell, $options) . "\n";
} else {
$table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h(
$cell
) : $cell) : $options['null'];
}
$table .= '</td>';
}
$table .= "</tr>\n";
}
$table .= '</table>';
return $table;
} | php | public function array2table(array $array, array $options = [], array $attributes = []) {
$defaults = [
'null' => ' ',
'recursive' => false,
'heading' => true,
'escape' => true
];
$options += $defaults;
// Sanity check
if (empty($array)) {
return '';
}
if (!isset($array[0]) || !is_array($array[0])) {
$array = [$array];
}
$attributes += [
'class' => 'table'
];
$attributes = $this->template->formatAttributes($attributes);
// Start the table
$table = "<table$attributes>\n";
if ($options['heading']) {
// The header
$table .= "\t<tr>";
// Take the keys from the first row as the headings
foreach (array_keys($array[0]) as $heading) {
$table .= '<th>' . ($options['escape'] ? h($heading) : $heading) . '</th>';
}
$table .= "</tr>\n";
}
// The body
foreach ($array as $row) {
$table .= "\t<tr>";
foreach ($row as $cell) {
$table .= '<td>';
// Cast objects
if (is_object($cell)) {
$cell = (array)$cell;
}
if ($options['recursive'] && is_array($cell) && !empty($cell)) {
// Recursive mode
$table .= "\n" . static::array2table($cell, $options) . "\n";
} else {
$table .= (!is_array($cell) && strlen($cell) > 0) ? ($options['escape'] ? h(
$cell
) : $cell) : $options['null'];
}
$table .= '</td>';
}
$table .= "</tr>\n";
}
$table .= '</table>';
return $table;
} | [
"public",
"function",
"array2table",
"(",
"array",
"$",
"array",
",",
"array",
"$",
"options",
"=",
"[",
"]",
",",
"array",
"$",
"attributes",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'null'",
"=>",
"' '",
",",
"'recursive'",
"=>",
"... | Translate a result array into a HTML table
@todo Move to Text Helper etc.
Options:
- recursive: Recursively generate tables for multi-dimensional arrays
- heading: Display the first as heading row (th)
- escape: Defaults to true
- null: Null value
@author Aidan Lister <aidan@php.net>
@version 1.3.2
@link http://aidanlister.com/2004/04/converting-arrays-to-human-readable-tables/
@param array $array The result (numericaly keyed, associative inner) array.
@param array $options
@param array $attributes For the table
@return string | [
"Translate",
"a",
"result",
"array",
"into",
"a",
"HTML",
"table"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormatHelper.php#L642-L707 | train |
dereuromark/cakephp-tools | src/Mailer/Mailer.php | Mailer.fixateLocale | protected function fixateLocale() {
$this->locale = I18n::getLocale();
$primaryLocale = $this->getPrimaryLocale();
if ($primaryLocale && $primaryLocale !== $this->locale) {
I18n::setLocale($primaryLocale);
}
} | php | protected function fixateLocale() {
$this->locale = I18n::getLocale();
$primaryLocale = $this->getPrimaryLocale();
if ($primaryLocale && $primaryLocale !== $this->locale) {
I18n::setLocale($primaryLocale);
}
} | [
"protected",
"function",
"fixateLocale",
"(",
")",
"{",
"$",
"this",
"->",
"locale",
"=",
"I18n",
"::",
"getLocale",
"(",
")",
";",
"$",
"primaryLocale",
"=",
"$",
"this",
"->",
"getPrimaryLocale",
"(",
")",
";",
"if",
"(",
"$",
"primaryLocale",
"&&",
... | Switch to primary locale if applicable.
@return void | [
"Switch",
"to",
"primary",
"locale",
"if",
"applicable",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Mailer/Mailer.php#L37-L44 | train |
dereuromark/cakephp-tools | src/Mailer/Mailer.php | Mailer.restoreLocale | protected function restoreLocale() {
$primaryLocale = $this->getPrimaryLocale();
if ($primaryLocale && $primaryLocale !== $this->locale) {
I18n::setLocale($this->locale);
}
} | php | protected function restoreLocale() {
$primaryLocale = $this->getPrimaryLocale();
if ($primaryLocale && $primaryLocale !== $this->locale) {
I18n::setLocale($this->locale);
}
} | [
"protected",
"function",
"restoreLocale",
"(",
")",
"{",
"$",
"primaryLocale",
"=",
"$",
"this",
"->",
"getPrimaryLocale",
"(",
")",
";",
"if",
"(",
"$",
"primaryLocale",
"&&",
"$",
"primaryLocale",
"!==",
"$",
"this",
"->",
"locale",
")",
"{",
"I18n",
"... | Restore to current locale if applicable.
@return void | [
"Restore",
"to",
"current",
"locale",
"if",
"applicable",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Mailer/Mailer.php#L51-L56 | train |
dereuromark/cakephp-tools | src/Mailer/Mailer.php | Mailer.getPrimaryLocale | protected function getPrimaryLocale() {
$primaryLanguage = Configure::read('Config.defaultLanguage');
if (Configure::read('Config.defaultLocale')) {
return Configure::read('Config.defaultLocale');
}
$primaryLocale = Configure::read('Config.allowedLanguages.' . $primaryLanguage . '.locale');
return $primaryLocale;
} | php | protected function getPrimaryLocale() {
$primaryLanguage = Configure::read('Config.defaultLanguage');
if (Configure::read('Config.defaultLocale')) {
return Configure::read('Config.defaultLocale');
}
$primaryLocale = Configure::read('Config.allowedLanguages.' . $primaryLanguage . '.locale');
return $primaryLocale;
} | [
"protected",
"function",
"getPrimaryLocale",
"(",
")",
"{",
"$",
"primaryLanguage",
"=",
"Configure",
"::",
"read",
"(",
"'Config.defaultLanguage'",
")",
";",
"if",
"(",
"Configure",
"::",
"read",
"(",
"'Config.defaultLocale'",
")",
")",
"{",
"return",
"Configur... | Returns the configured default locale.
Can be based on the primary language and the allowed languages (whitelist).
@return string | [
"Returns",
"the",
"configured",
"default",
"locale",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Mailer/Mailer.php#L65-L73 | train |
dereuromark/cakephp-tools | src/View/Helper/FormHelper.php | FormHelper.create | public function create($model = null, array $options = []) {
$defaults = ['novalidate' => $this->_defaultConfig['novalidate']];
$options += $defaults;
return parent::create($model, $options);
} | php | public function create($model = null, array $options = []) {
$defaults = ['novalidate' => $this->_defaultConfig['novalidate']];
$options += $defaults;
return parent::create($model, $options);
} | [
"public",
"function",
"create",
"(",
"$",
"model",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'novalidate'",
"=>",
"$",
"this",
"->",
"_defaultConfig",
"[",
"'novalidate'",
"]",
"]",
";",
"$",
"opt... | Overwrite to allow FormConfig Configure settings to be applied.
@param mixed $model The context for which the form is being defined. Can
be an ORM entity, ORM resultset, or an array of meta data. You can use false or null
to make a model-less form.
@param array $options An array of html attributes and options.
@return string An formatted opening FORM tag. | [
"Overwrite",
"to",
"allow",
"FormConfig",
"Configure",
"settings",
"to",
"be",
"applied",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/FormHelper.php#L49-L53 | train |
dereuromark/cakephp-tools | src/Model/Behavior/SluggedBehavior.php | SluggedBehavior.needsSlugUpdate | public function needsSlugUpdate(EntityInterface $entity, $deep = false) {
foreach ((array)$this->_config['label'] as $label) {
if ($entity->isDirty($label)) {
return true;
}
}
if ($deep) {
$copy = clone $entity;
$this->slug($copy, ['overwrite' => true]);
return $copy->get($this->_config['field']) !== $entity->get($this->_config['field']);
}
return false;
} | php | public function needsSlugUpdate(EntityInterface $entity, $deep = false) {
foreach ((array)$this->_config['label'] as $label) {
if ($entity->isDirty($label)) {
return true;
}
}
if ($deep) {
$copy = clone $entity;
$this->slug($copy, ['overwrite' => true]);
return $copy->get($this->_config['field']) !== $entity->get($this->_config['field']);
}
return false;
} | [
"public",
"function",
"needsSlugUpdate",
"(",
"EntityInterface",
"$",
"entity",
",",
"$",
"deep",
"=",
"false",
")",
"{",
"foreach",
"(",
"(",
"array",
")",
"$",
"this",
"->",
"_config",
"[",
"'label'",
"]",
"as",
"$",
"label",
")",
"{",
"if",
"(",
"... | Method to find out if the current slug needs updating.
The deep option is useful if you cannot rely on dirty() because
of maybe some not in sync slugs anymore (saving the same title again,
but the slug is completely different, for example).
@param \Cake\Datasource\EntityInterface $entity
@param bool $deep If true it will generate a new slug and compare it to the currently stored one.
@return bool | [
"Method",
"to",
"find",
"out",
"if",
"the",
"current",
"slug",
"needs",
"updating",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/SluggedBehavior.php#L240-L252 | train |
dereuromark/cakephp-tools | src/Model/Behavior/SluggedBehavior.php | SluggedBehavior.resetSlugs | public function resetSlugs($params = []) {
if (!$this->_table->hasField($this->_config['field'])) {
throw new RuntimeException('Table does not have field ' . $this->_config['field']);
}
$defaults = [
'page' => 1,
'limit' => 100,
'fields' => array_merge([$this->_table->getPrimaryKey()], $this->_config['label']),
'order' => $this->_table->getDisplayField() . ' ASC',
'conditions' => $this->_config['scope'],
'overwrite' => true,
];
$params = array_merge($defaults, $params);
$conditions = $params['conditions'];
$count = $this->_table->find('all', compact('conditions'))->count();
$max = ini_get('max_execution_time');
if ($max) {
set_time_limit(max($max, $count / 100));
}
$this->setConfig($params, null, false);
while (($records = $this->_table->find('all', $params)->toArray())) {
/** @var \Cake\ORM\Entity $record */
foreach ($records as $record) {
$record->isNew(true);
$fields = array_merge([$this->_table->getPrimaryKey(), $this->_config['field']], $this->_config['label']);
$options = [
'validate' => true,
'fields' => $fields,
];
if (!$this->_table->save($record, $options)) {
throw new RuntimeException(print_r($record->getErrors(), true));
}
}
$params['page']++;
}
return true;
} | php | public function resetSlugs($params = []) {
if (!$this->_table->hasField($this->_config['field'])) {
throw new RuntimeException('Table does not have field ' . $this->_config['field']);
}
$defaults = [
'page' => 1,
'limit' => 100,
'fields' => array_merge([$this->_table->getPrimaryKey()], $this->_config['label']),
'order' => $this->_table->getDisplayField() . ' ASC',
'conditions' => $this->_config['scope'],
'overwrite' => true,
];
$params = array_merge($defaults, $params);
$conditions = $params['conditions'];
$count = $this->_table->find('all', compact('conditions'))->count();
$max = ini_get('max_execution_time');
if ($max) {
set_time_limit(max($max, $count / 100));
}
$this->setConfig($params, null, false);
while (($records = $this->_table->find('all', $params)->toArray())) {
/** @var \Cake\ORM\Entity $record */
foreach ($records as $record) {
$record->isNew(true);
$fields = array_merge([$this->_table->getPrimaryKey(), $this->_config['field']], $this->_config['label']);
$options = [
'validate' => true,
'fields' => $fields,
];
if (!$this->_table->save($record, $options)) {
throw new RuntimeException(print_r($record->getErrors(), true));
}
}
$params['page']++;
}
return true;
} | [
"public",
"function",
"resetSlugs",
"(",
"$",
"params",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"_table",
"->",
"hasField",
"(",
"$",
"this",
"->",
"_config",
"[",
"'field'",
"]",
")",
")",
"{",
"throw",
"new",
"RuntimeException",... | ResetSlugs method.
Regenerate all slugs. On large dbs this can take more than 30 seconds - a time
limit is set to allow a minimum 100 updates per second as a preventative measure.
Note that you should use the Reset behavior if you need additional functionality such
as callbacks or timeouts.
@param array $params
@return bool Success
@throws \RuntimeException | [
"ResetSlugs",
"method",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/SluggedBehavior.php#L373-L412 | train |
dereuromark/cakephp-tools | src/Model/Behavior/SluggedBehavior.php | SluggedBehavior._multiSlug | protected function _multiSlug(EntityInterface $entity) {
$label = $this->getConfig('label');
$field = current($label);
$fields = (array)$entity->get($field);
$locale = [];
foreach ($fields as $locale => $_) {
$res = null;
foreach ($label as $field) {
$res = $entity->get($field);
if (is_array($entity->get($field))) {
$res = $this->generateSlug($field[$locale], $entity);
}
}
$locale[$locale] = $res;
}
$entity->set($this->getConfig('slugField'), $locale);
} | php | protected function _multiSlug(EntityInterface $entity) {
$label = $this->getConfig('label');
$field = current($label);
$fields = (array)$entity->get($field);
$locale = [];
foreach ($fields as $locale => $_) {
$res = null;
foreach ($label as $field) {
$res = $entity->get($field);
if (is_array($entity->get($field))) {
$res = $this->generateSlug($field[$locale], $entity);
}
}
$locale[$locale] = $res;
}
$entity->set($this->getConfig('slugField'), $locale);
} | [
"protected",
"function",
"_multiSlug",
"(",
"EntityInterface",
"$",
"entity",
")",
"{",
"$",
"label",
"=",
"$",
"this",
"->",
"getConfig",
"(",
"'label'",
")",
";",
"$",
"field",
"=",
"current",
"(",
"$",
"label",
")",
";",
"$",
"fields",
"=",
"(",
"... | Multi slug method
Handle both slug and label fields using the translate behavior, and being edited
in multiple locales at once
//FIXME
@param \Cake\Datasource\EntityInterface $entity
@return void | [
"Multi",
"slug",
"method"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/SluggedBehavior.php#L425-L443 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table.getNextAutoIncrement | public function getNextAutoIncrement() {
$query = "SHOW TABLE STATUS WHERE name = '" . $this->getTable() . "'";
$statement = $this->_connection->execute($query);
$result = $statement->fetch();
if (!isset($result[10])) {
return false;
}
return (int)$result[10];
} | php | public function getNextAutoIncrement() {
$query = "SHOW TABLE STATUS WHERE name = '" . $this->getTable() . "'";
$statement = $this->_connection->execute($query);
$result = $statement->fetch();
if (!isset($result[10])) {
return false;
}
return (int)$result[10];
} | [
"public",
"function",
"getNextAutoIncrement",
"(",
")",
"{",
"$",
"query",
"=",
"\"SHOW TABLE STATUS WHERE name = '\"",
".",
"$",
"this",
"->",
"getTable",
"(",
")",
".",
"\"'\"",
";",
"$",
"statement",
"=",
"$",
"this",
"->",
"_connection",
"->",
"execute",
... | Return the next auto increment id from the current table
UUIDs will return false
@return int|bool next auto increment value or False on failure | [
"Return",
"the",
"next",
"auto",
"increment",
"id",
"from",
"the",
"current",
"table",
"UUIDs",
"will",
"return",
"false"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L83-L91 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table.getRelatedInUse | public function getRelatedInUse($tableName, $groupField = null, $type = 'all', $options = []) {
if ($groupField === null) {
$groupField = $this->belongsTo[$tableName]['foreignKey'];
}
$defaults = [
'contain' => [$tableName],
'group' => $groupField,
'order' => isset($this->$tableName->order) ? $this->$tableName->order : [$tableName . '.' . $this->$tableName->getDisplayField() => 'ASC'],
];
if ($type === 'list') {
$defaults['fields'] = [$tableName . '.' . $this->$tableName->getPrimaryKey(), $tableName . '.' . $this->$tableName->getDisplayField()];
$defaults['keyField'] = $tableName . '.' . $this->$tableName->getPrimaryKey();
$defaults['valueField'] = $tableName . '.' . $this->$tableName->getDisplayField();
}
$options += $defaults;
return $this->find($type, $options);
} | php | public function getRelatedInUse($tableName, $groupField = null, $type = 'all', $options = []) {
if ($groupField === null) {
$groupField = $this->belongsTo[$tableName]['foreignKey'];
}
$defaults = [
'contain' => [$tableName],
'group' => $groupField,
'order' => isset($this->$tableName->order) ? $this->$tableName->order : [$tableName . '.' . $this->$tableName->getDisplayField() => 'ASC'],
];
if ($type === 'list') {
$defaults['fields'] = [$tableName . '.' . $this->$tableName->getPrimaryKey(), $tableName . '.' . $this->$tableName->getDisplayField()];
$defaults['keyField'] = $tableName . '.' . $this->$tableName->getPrimaryKey();
$defaults['valueField'] = $tableName . '.' . $this->$tableName->getDisplayField();
}
$options += $defaults;
return $this->find($type, $options);
} | [
"public",
"function",
"getRelatedInUse",
"(",
"$",
"tableName",
",",
"$",
"groupField",
"=",
"null",
",",
"$",
"type",
"=",
"'all'",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"$",
"groupField",
"===",
"null",
")",
"{",
"$",
"groupField... | Get all related entries that have been used so far
@deprecated Must be refactored.
@param string $tableName The related model
@param string|null $groupField Field to group by
@param string $type Find type
@param array $options
@return \Cake\ORM\Query | [
"Get",
"all",
"related",
"entries",
"that",
"have",
"been",
"used",
"so",
"far"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L116-L133 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table.getFieldInUse | public function getFieldInUse($groupField, $type = 'all', array $options = []) {
$defaults = [
'group' => $groupField,
'order' => [$this->getDisplayField() => 'ASC'],
];
if ($type === 'list') {
$defaults['fields'] = ['' . $this->getPrimaryKey(), '' . $this->getDisplayField()];
}
$options += $defaults;
return $this->find($type, $options);
} | php | public function getFieldInUse($groupField, $type = 'all', array $options = []) {
$defaults = [
'group' => $groupField,
'order' => [$this->getDisplayField() => 'ASC'],
];
if ($type === 'list') {
$defaults['fields'] = ['' . $this->getPrimaryKey(), '' . $this->getDisplayField()];
}
$options += $defaults;
return $this->find($type, $options);
} | [
"public",
"function",
"getFieldInUse",
"(",
"$",
"groupField",
",",
"$",
"type",
"=",
"'all'",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaults",
"=",
"[",
"'group'",
"=>",
"$",
"groupField",
",",
"'order'",
"=>",
"[",
"$",
"this... | Get all fields that have been used so far
@param string $groupField Field to group by
@param string $type Find type
@param array $options
@return \Cake\ORM\Query | [
"Get",
"all",
"fields",
"that",
"have",
"been",
"used",
"so",
"far"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L143-L153 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table._autoCompleteUrl | protected function _autoCompleteUrl($url) {
if (mb_strpos($url, '/') === 0) {
$url = Router::url($url, true);
} elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
$url = 'http://' . $url;
}
return $url;
} | php | protected function _autoCompleteUrl($url) {
if (mb_strpos($url, '/') === 0) {
$url = Router::url($url, true);
} elseif (mb_strpos($url, '://') === false && mb_strpos($url, 'www.') === 0) {
$url = 'http://' . $url;
}
return $url;
} | [
"protected",
"function",
"_autoCompleteUrl",
"(",
"$",
"url",
")",
"{",
"if",
"(",
"mb_strpos",
"(",
"$",
"url",
",",
"'/'",
")",
"===",
"0",
")",
"{",
"$",
"url",
"=",
"Router",
"::",
"url",
"(",
"$",
"url",
",",
"true",
")",
";",
"}",
"elseif",... | Prepend protocol if missing
@param string $url
@return string URL | [
"Prepend",
"protocol",
"if",
"missing"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L240-L247 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table._validUrl | protected function _validUrl($url) {
$headers = Utility::getHeaderFromUrl($url);
if ($headers === false) {
return false;
}
$headers = implode("\n", $headers);
$protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
if (!preg_match('#^' . $protocol . '/.*?\s+[(200|301|302)]+\s#i', $headers)) {
return false;
}
if (preg_match('#^' . $protocol . '/.*?\s+[(404|999)]+\s#i', $headers)) {
return false;
}
return true;
} | php | protected function _validUrl($url) {
$headers = Utility::getHeaderFromUrl($url);
if ($headers === false) {
return false;
}
$headers = implode("\n", $headers);
$protocol = mb_strpos($url, 'https://') === 0 ? 'HTTP' : 'HTTP';
if (!preg_match('#^' . $protocol . '/.*?\s+[(200|301|302)]+\s#i', $headers)) {
return false;
}
if (preg_match('#^' . $protocol . '/.*?\s+[(404|999)]+\s#i', $headers)) {
return false;
}
return true;
} | [
"protected",
"function",
"_validUrl",
"(",
"$",
"url",
")",
"{",
"$",
"headers",
"=",
"Utility",
"::",
"getHeaderFromUrl",
"(",
"$",
"url",
")",
";",
"if",
"(",
"$",
"headers",
"===",
"false",
")",
"{",
"return",
"false",
";",
"}",
"$",
"headers",
"=... | Checks if a url is valid
@param string $url
@return bool Success | [
"Checks",
"if",
"a",
"url",
"is",
"valid"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L255-L269 | train |
dereuromark/cakephp-tools | src/Model/Table/Table.php | Table.validateTime | public function validateTime($value, $options = [], array $context = []) {
if (!$value) {
return false;
}
$dateTime = explode(' ', $value, 2);
$value = array_pop($dateTime);
if (Validation::time($value)) {
// after/before?
if (!empty($options['after']) && isset($context['data'][$options['after']])) {
if ($context['data'][$options['after']] >= $value) {
return false;
}
}
if (!empty($options['before']) && isset($context['data'][$options['before']])) {
if ($context['data'][$options['before']] <= $value) {
return false;
}
}
return true;
}
return false;
} | php | public function validateTime($value, $options = [], array $context = []) {
if (!$value) {
return false;
}
$dateTime = explode(' ', $value, 2);
$value = array_pop($dateTime);
if (Validation::time($value)) {
// after/before?
if (!empty($options['after']) && isset($context['data'][$options['after']])) {
if ($context['data'][$options['after']] >= $value) {
return false;
}
}
if (!empty($options['before']) && isset($context['data'][$options['before']])) {
if ($context['data'][$options['before']] <= $value) {
return false;
}
}
return true;
}
return false;
} | [
"public",
"function",
"validateTime",
"(",
"$",
"value",
",",
"$",
"options",
"=",
"[",
"]",
",",
"array",
"$",
"context",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"value",
")",
"{",
"return",
"false",
";",
"}",
"$",
"dateTime",
"=",
"explod... | Validation of Time fields
@param mixed $value
@param array $options
- timeFormat (defaults to 'hms')
- allowEmpty
- after/before (fieldName to validate against)
- min/max (defaults to >= 1 - at least 1 minute apart)
@param array $context
@return bool Success | [
"Validation",
"of",
"Time",
"fields"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/Table.php#L434-L456 | train |
dereuromark/cakephp-tools | src/Utility/Random.php | Random.date | public static function date($min = null, $max = null, $formatReturn = null) {
if ($min === null && $max === null) {
$res = time();
} elseif ($min > 0 && $max === null) {
$res = $min;
} elseif ($min > 0 && $max > 0) {
$res = static::int($min, $max);
} else {
$res = time();
}
$res = 0;
$formatReturnAs = FORMAT_DB_DATETIME;
if ($formatReturn !== null) {
if ($formatReturn === false) {
return $res;
}
$formatReturnAs = $formatReturn;
}
return date($formatReturnAs);
} | php | public static function date($min = null, $max = null, $formatReturn = null) {
if ($min === null && $max === null) {
$res = time();
} elseif ($min > 0 && $max === null) {
$res = $min;
} elseif ($min > 0 && $max > 0) {
$res = static::int($min, $max);
} else {
$res = time();
}
$res = 0;
$formatReturnAs = FORMAT_DB_DATETIME;
if ($formatReturn !== null) {
if ($formatReturn === false) {
return $res;
}
$formatReturnAs = $formatReturn;
}
return date($formatReturnAs);
} | [
"public",
"static",
"function",
"date",
"(",
"$",
"min",
"=",
"null",
",",
"$",
"max",
"=",
"null",
",",
"$",
"formatReturn",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"min",
"===",
"null",
"&&",
"$",
"max",
"===",
"null",
")",
"{",
"$",
"res",
"=... | 1950-01-01 - 2050-12-31
@param int|null $min
@param int|null $max
@param bool|null $formatReturn
@return int|null|string | [
"1950",
"-",
"01",
"-",
"01",
"-",
"2050",
"-",
"12",
"-",
"31"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Random.php#L64-L84 | train |
dereuromark/cakephp-tools | src/Utility/Random.php | Random.dob | public static function dob($min = 18, $max = 100) {
$dobYear = (int)date('Y') - (static::int($min, $max));
$dobMonth = static::int(1, 12);
if ($dobMonth == 2) {
// leap year?
if ($dobYear % 4 || $dobYear % 400) {
$maxDays = 29;
} else {
$maxDays = 28;
}
} elseif (in_array($dobMonth, [4, 6, 9, 11])) {
$maxDays = 30;
} else {
$maxDays = 31;
}
$dobDay = static::int(1, $maxDays);
$dob = sprintf('%4d-%02d-%02d', $dobYear, $dobMonth, $dobDay);
return $dob;
} | php | public static function dob($min = 18, $max = 100) {
$dobYear = (int)date('Y') - (static::int($min, $max));
$dobMonth = static::int(1, 12);
if ($dobMonth == 2) {
// leap year?
if ($dobYear % 4 || $dobYear % 400) {
$maxDays = 29;
} else {
$maxDays = 28;
}
} elseif (in_array($dobMonth, [4, 6, 9, 11])) {
$maxDays = 30;
} else {
$maxDays = 31;
}
$dobDay = static::int(1, $maxDays);
$dob = sprintf('%4d-%02d-%02d', $dobYear, $dobMonth, $dobDay);
return $dob;
} | [
"public",
"static",
"function",
"dob",
"(",
"$",
"min",
"=",
"18",
",",
"$",
"max",
"=",
"100",
")",
"{",
"$",
"dobYear",
"=",
"(",
"int",
")",
"date",
"(",
"'Y'",
")",
"-",
"(",
"static",
"::",
"int",
"(",
"$",
"min",
",",
"$",
"max",
")",
... | Returns a date of birth within the specified age range
@param int $min minimum age in years
@param int $max maximum age in years
@return string Dob a db (ISO) format datetime string | [
"Returns",
"a",
"date",
"of",
"birth",
"within",
"the",
"specified",
"age",
"range"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Random.php#L115-L137 | train |
dereuromark/cakephp-tools | src/Utility/Random.php | Random.pronounceablePwd | public static function pronounceablePwd($length = 10) {
srand((double)microtime() * 1000000);
$password = '';
$vowels = ['a', 'e', 'i', 'o', 'u'];
$cons = ['b', 'c', 'd', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'tr',
'cr', 'br', 'fr', 'th', 'dr', 'ch', 'ph', 'wr', 'st', 'sp', 'sw', 'pr', 'sl', 'cl'];
for ($i = 0; $i < $length; $i++) {
$password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)];
}
return substr($password, 0, $length);
} | php | public static function pronounceablePwd($length = 10) {
srand((double)microtime() * 1000000);
$password = '';
$vowels = ['a', 'e', 'i', 'o', 'u'];
$cons = ['b', 'c', 'd', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'u', 'v', 'w', 'tr',
'cr', 'br', 'fr', 'th', 'dr', 'ch', 'ph', 'wr', 'st', 'sp', 'sw', 'pr', 'sl', 'cl'];
for ($i = 0; $i < $length; $i++) {
$password .= $cons[mt_rand(0, 31)] . $vowels[mt_rand(0, 4)];
}
return substr($password, 0, $length);
} | [
"public",
"static",
"function",
"pronounceablePwd",
"(",
"$",
"length",
"=",
"10",
")",
"{",
"srand",
"(",
"(",
"double",
")",
"microtime",
"(",
")",
"*",
"1000000",
")",
";",
"$",
"password",
"=",
"''",
";",
"$",
"vowels",
"=",
"[",
"'a'",
",",
"'... | Generates a password
@param int $length Password length
@return string
@link https://github.com/CakeDC/users/blob/master/models/user.php#L498 | [
"Generates",
"a",
"password"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Random.php#L146-L156 | train |
dereuromark/cakephp-tools | src/Utility/Random.php | Random.pwd | public static function pwd($length, $chars = null) {
if ($chars === null) {
$chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
}
$i = 0;
$password = '';
$max = strlen($chars) - 1;
while ($i < $length) {
$password .= $chars[mt_rand(0, $max)];
$i++;
}
return $password;
} | php | public static function pwd($length, $chars = null) {
if ($chars === null) {
$chars = '234567890abcdefghijkmnopqrstuvwxyz'; // ABCDEFGHIJKLMNOPQRSTUVWXYZ
}
$i = 0;
$password = '';
$max = strlen($chars) - 1;
while ($i < $length) {
$password .= $chars[mt_rand(0, $max)];
$i++;
}
return $password;
} | [
"public",
"static",
"function",
"pwd",
"(",
"$",
"length",
",",
"$",
"chars",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"chars",
"===",
"null",
")",
"{",
"$",
"chars",
"=",
"'234567890abcdefghijkmnopqrstuvwxyz'",
";",
"// ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"}",
"$",
... | Generates random passwords.
@param int $length (necessary!)
@param string|null $chars
@return string Password | [
"Generates",
"random",
"passwords",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Random.php#L165-L178 | train |
dereuromark/cakephp-tools | src/Utility/Mime.php | Mime.mimeTypes | public function mimeTypes($coreHasPrecedence = false) {
if ($coreHasPrecedence) {
return $this->_mimeTypes += $this->_mimeTypesExt;
}
return $this->_mimeTypesExt += $this->_mimeTypes;
} | php | public function mimeTypes($coreHasPrecedence = false) {
if ($coreHasPrecedence) {
return $this->_mimeTypes += $this->_mimeTypesExt;
}
return $this->_mimeTypesExt += $this->_mimeTypes;
} | [
"public",
"function",
"mimeTypes",
"(",
"$",
"coreHasPrecedence",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"coreHasPrecedence",
")",
"{",
"return",
"$",
"this",
"->",
"_mimeTypes",
"+=",
"$",
"this",
"->",
"_mimeTypesExt",
";",
"}",
"return",
"$",
"this",
... | Get all mime types that are supported right now
@param bool $coreHasPrecedence
@return array | [
"Get",
"all",
"mime",
"types",
"that",
"are",
"supported",
"right",
"now"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Mime.php#L715-L720 | train |
dereuromark/cakephp-tools | src/Utility/Mime.php | Mime.getEncoding | public static function getEncoding($file = null, $default = 'utf-8') {
if (!function_exists('finfo_open')) {
return $default;
}
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
$encoding = finfo_file($finfo, $file);
finfo_close($finfo);
if ($encoding !== false) {
return $encoding;
}
return $default;
} | php | public static function getEncoding($file = null, $default = 'utf-8') {
if (!function_exists('finfo_open')) {
return $default;
}
$finfo = finfo_open(FILEINFO_MIME_ENCODING);
$encoding = finfo_file($finfo, $file);
finfo_close($finfo);
if ($encoding !== false) {
return $encoding;
}
return $default;
} | [
"public",
"static",
"function",
"getEncoding",
"(",
"$",
"file",
"=",
"null",
",",
"$",
"default",
"=",
"'utf-8'",
")",
"{",
"if",
"(",
"!",
"function_exists",
"(",
"'finfo_open'",
")",
")",
"{",
"return",
"$",
"default",
";",
"}",
"$",
"finfo",
"=",
... | Get encoding.
@param string|null $file
@param string $default
@return string | [
"Get",
"encoding",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Mime.php#L841-L852 | train |
dereuromark/cakephp-tools | src/Utility/Mime.php | Mime._getExtension | protected static function _getExtension($file) {
$pieces = explode('.', $file);
$ext = strtolower(array_pop($pieces));
return $ext;
} | php | protected static function _getExtension($file) {
$pieces = explode('.', $file);
$ext = strtolower(array_pop($pieces));
return $ext;
} | [
"protected",
"static",
"function",
"_getExtension",
"(",
"$",
"file",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"'.'",
",",
"$",
"file",
")",
";",
"$",
"ext",
"=",
"strtolower",
"(",
"array_pop",
"(",
"$",
"pieces",
")",
")",
";",
"return",
"$",
... | Gets the file extention from a string
@param string $file The full file name
@return string The file extension | [
"Gets",
"the",
"file",
"extention",
"from",
"a",
"string"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Mime.php#L860-L864 | train |
dereuromark/cakephp-tools | src/Controller/Component/CommonComponent.php | CommonComponent.getSafeRedirectUrl | public function getSafeRedirectUrl($default, $data = null, $key = 'redirect') {
$redirectUrl = $data ?: ($this->Controller->getRequest()->getData($key) ?: $this->Controller->getRequest()->getQuery($key));
if ($redirectUrl && (mb_substr($redirectUrl, 0, 1) !== '/' || mb_substr($redirectUrl, 0, 2) === '//')) {
$redirectUrl = null;
}
return $redirectUrl ?: $default;
} | php | public function getSafeRedirectUrl($default, $data = null, $key = 'redirect') {
$redirectUrl = $data ?: ($this->Controller->getRequest()->getData($key) ?: $this->Controller->getRequest()->getQuery($key));
if ($redirectUrl && (mb_substr($redirectUrl, 0, 1) !== '/' || mb_substr($redirectUrl, 0, 2) === '//')) {
$redirectUrl = null;
}
return $redirectUrl ?: $default;
} | [
"public",
"function",
"getSafeRedirectUrl",
"(",
"$",
"default",
",",
"$",
"data",
"=",
"null",
",",
"$",
"key",
"=",
"'redirect'",
")",
"{",
"$",
"redirectUrl",
"=",
"$",
"data",
"?",
":",
"(",
"$",
"this",
"->",
"Controller",
"->",
"getRequest",
"(",... | Returns internal redirect only, otherwise falls back to default.
Lookup order:
- POST data
- query string
- provided default
@param string|array $default
@param string|array|null $data
@param string $key
@return string|array | [
"Returns",
"internal",
"redirect",
"only",
"otherwise",
"falls",
"back",
"to",
"default",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/CommonComponent.php#L73-L80 | train |
dereuromark/cakephp-tools | src/Controller/Component/CommonComponent.php | CommonComponent.listActions | public function listActions() {
$parentClassMethods = get_class_methods(get_parent_class($this->Controller));
$subClassMethods = get_class_methods($this->Controller);
$classMethods = array_diff($subClassMethods, $parentClassMethods);
foreach ($classMethods as $key => $classMethod) {
if (mb_substr($classMethod, 0, 1) === '_') {
unset($classMethods[$key]);
}
}
return $classMethods;
} | php | public function listActions() {
$parentClassMethods = get_class_methods(get_parent_class($this->Controller));
$subClassMethods = get_class_methods($this->Controller);
$classMethods = array_diff($subClassMethods, $parentClassMethods);
foreach ($classMethods as $key => $classMethod) {
if (mb_substr($classMethod, 0, 1) === '_') {
unset($classMethods[$key]);
}
}
return $classMethods;
} | [
"public",
"function",
"listActions",
"(",
")",
"{",
"$",
"parentClassMethods",
"=",
"get_class_methods",
"(",
"get_parent_class",
"(",
"$",
"this",
"->",
"Controller",
")",
")",
";",
"$",
"subClassMethods",
"=",
"get_class_methods",
"(",
"$",
"this",
"->",
"Co... | List all direct actions of a controller
@return array Actions | [
"List",
"all",
"direct",
"actions",
"of",
"a",
"controller"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/CommonComponent.php#L87-L97 | train |
dereuromark/cakephp-tools | src/Controller/Component/CommonComponent.php | CommonComponent.getPassedParam | public function getPassedParam($var, $default = null) {
$passed = $this->Controller->getRequest()->getParam('pass');
return isset($passed[$var]) ? $passed[$var] : $default;
} | php | public function getPassedParam($var, $default = null) {
$passed = $this->Controller->getRequest()->getParam('pass');
return isset($passed[$var]) ? $passed[$var] : $default;
} | [
"public",
"function",
"getPassedParam",
"(",
"$",
"var",
",",
"$",
"default",
"=",
"null",
")",
"{",
"$",
"passed",
"=",
"$",
"this",
"->",
"Controller",
"->",
"getRequest",
"(",
")",
"->",
"getParam",
"(",
"'pass'",
")",
";",
"return",
"isset",
"(",
... | Used to get the value of a passed param.
@param mixed $var
@param mixed $default
@return mixed | [
"Used",
"to",
"get",
"the",
"value",
"of",
"a",
"passed",
"param",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/CommonComponent.php#L154-L158 | train |
dereuromark/cakephp-tools | src/Controller/Component/CommonComponent.php | CommonComponent.defaultUrlParams | public static function defaultUrlParams() {
$defaults = ['plugin' => false];
$prefixes = (array)Configure::read('Routing.prefixes');
foreach ($prefixes as $prefix) {
$defaults[$prefix] = false;
}
return $defaults;
} | php | public static function defaultUrlParams() {
$defaults = ['plugin' => false];
$prefixes = (array)Configure::read('Routing.prefixes');
foreach ($prefixes as $prefix) {
$defaults[$prefix] = false;
}
return $defaults;
} | [
"public",
"static",
"function",
"defaultUrlParams",
"(",
")",
"{",
"$",
"defaults",
"=",
"[",
"'plugin'",
"=>",
"false",
"]",
";",
"$",
"prefixes",
"=",
"(",
"array",
")",
"Configure",
"::",
"read",
"(",
"'Routing.prefixes'",
")",
";",
"foreach",
"(",
"$... | Returns defaultUrlParams including configured prefixes.
@return array URL params | [
"Returns",
"defaultUrlParams",
"including",
"configured",
"prefixes",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/CommonComponent.php#L165-L172 | train |
dereuromark/cakephp-tools | src/Controller/Component/CommonComponent.php | CommonComponent.autoRedirect | public function autoRedirect($whereTo, $allowSelf = false, $status = 302) {
if ($allowSelf || $this->Controller->referer(null, true) !== $this->Controller->getRequest()->getRequestTarget()) {
return $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
}
return $this->Controller->redirect($whereTo, $status);
} | php | public function autoRedirect($whereTo, $allowSelf = false, $status = 302) {
if ($allowSelf || $this->Controller->referer(null, true) !== $this->Controller->getRequest()->getRequestTarget()) {
return $this->Controller->redirect($this->Controller->referer($whereTo, true), $status);
}
return $this->Controller->redirect($whereTo, $status);
} | [
"public",
"function",
"autoRedirect",
"(",
"$",
"whereTo",
",",
"$",
"allowSelf",
"=",
"false",
",",
"$",
"status",
"=",
"302",
")",
"{",
"if",
"(",
"$",
"allowSelf",
"||",
"$",
"this",
"->",
"Controller",
"->",
"referer",
"(",
"null",
",",
"true",
"... | Smart Referer Redirect - will try to use an existing referer first
otherwise it will use the default url
@param mixed $whereTo URL
@param bool $allowSelf if redirect to the same controller/action (url) is allowed
@param int $status
@return \Cake\Http\Response | [
"Smart",
"Referer",
"Redirect",
"-",
"will",
"try",
"to",
"use",
"an",
"existing",
"referer",
"first",
"otherwise",
"it",
"will",
"use",
"the",
"default",
"url"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/Component/CommonComponent.php#L208-L213 | train |
dereuromark/cakephp-tools | src/Shell/InflectShell.php | InflectShell._getMethod | protected function _getMethod() {
$validCharacters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'q'];
$validCommands = array_merge($validCharacters, $this->validCommands);
$command = null;
while (empty($command)) {
$this->out('Please type the number or name of the inflection method you would like to use');
$this->hr();
$this->out('[1] Pluralize');
$this->out('[2] Singularize');
$this->out('[3] Camelize');
$this->out('[4] Underscore');
$this->out('[5] Humanize');
$this->out('[6] Tableize');
$this->out('[7] Classify');
$this->out('[8] Variable');
$this->out('[9] Dasherize');
$this->out('[10] Slug');
$this->out('[q] Quit');
$temp = $this->in('What command would you like to perform?', null, 'q');
if (in_array(strtolower($temp), $validCommands)) {
$command = strtolower($temp);
} else {
$this->out('Try again.');
}
}
switch ($command) {
case '1':
case 'pluralize':
return 'pluralize';
case '2':
case 'singularize':
return 'singularize';
case '3':
case 'camelize':
return 'camelize';
case '4':
case 'underscore':
return 'underscore';
case '5':
case 'humanize':
return 'humanize';
case '6':
case 'tableize':
return 'tableize';
case '7':
case 'classify':
return 'classify';
case '8':
case 'variable':
return 'variable';
case '9':
case 'dasherize':
return 'dasherize';
case '10':
case 'slug':
return 'slug';
case 'q':
case 'quit':
default:
$this->out('Exit');
$this->_stop();
return null;
}
} | php | protected function _getMethod() {
$validCharacters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'q'];
$validCommands = array_merge($validCharacters, $this->validCommands);
$command = null;
while (empty($command)) {
$this->out('Please type the number or name of the inflection method you would like to use');
$this->hr();
$this->out('[1] Pluralize');
$this->out('[2] Singularize');
$this->out('[3] Camelize');
$this->out('[4] Underscore');
$this->out('[5] Humanize');
$this->out('[6] Tableize');
$this->out('[7] Classify');
$this->out('[8] Variable');
$this->out('[9] Dasherize');
$this->out('[10] Slug');
$this->out('[q] Quit');
$temp = $this->in('What command would you like to perform?', null, 'q');
if (in_array(strtolower($temp), $validCommands)) {
$command = strtolower($temp);
} else {
$this->out('Try again.');
}
}
switch ($command) {
case '1':
case 'pluralize':
return 'pluralize';
case '2':
case 'singularize':
return 'singularize';
case '3':
case 'camelize':
return 'camelize';
case '4':
case 'underscore':
return 'underscore';
case '5':
case 'humanize':
return 'humanize';
case '6':
case 'tableize':
return 'tableize';
case '7':
case 'classify':
return 'classify';
case '8':
case 'variable':
return 'variable';
case '9':
case 'dasherize':
return 'dasherize';
case '10':
case 'slug':
return 'slug';
case 'q':
case 'quit':
default:
$this->out('Exit');
$this->_stop();
return null;
}
} | [
"protected",
"function",
"_getMethod",
"(",
")",
"{",
"$",
"validCharacters",
"=",
"[",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'6'",
",",
"'7'",
",",
"'8'",
",",
"'9'",
",",
"'10'",
",",
"'q'",
"]",
";",
"$",
"validCommands",
... | Requests a valid inflection method
@return string|null | [
"Requests",
"a",
"valid",
"inflection",
"method"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Shell/InflectShell.php#L71-L136 | train |
dereuromark/cakephp-tools | src/Shell/InflectShell.php | InflectShell._getWords | protected function _getWords() {
$words = null;
while (empty($words)) {
$temp = $this->in('What word(s) would you like to inflect?');
if (!empty($temp)) {
$words = $temp;
} else {
$this->out('Try again.');
}
}
return $words;
} | php | protected function _getWords() {
$words = null;
while (empty($words)) {
$temp = $this->in('What word(s) would you like to inflect?');
if (!empty($temp)) {
$words = $temp;
} else {
$this->out('Try again.');
}
}
return $words;
} | [
"protected",
"function",
"_getWords",
"(",
")",
"{",
"$",
"words",
"=",
"null",
";",
"while",
"(",
"empty",
"(",
"$",
"words",
")",
")",
"{",
"$",
"temp",
"=",
"$",
"this",
"->",
"in",
"(",
"'What word(s) would you like to inflect?'",
")",
";",
"if",
"... | Requests words to inflect
@return string|null | [
"Requests",
"words",
"to",
"inflect"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Shell/InflectShell.php#L143-L154 | train |
dereuromark/cakephp-tools | src/Shell/InflectShell.php | InflectShell._inflect | protected function _inflect($function, $words) {
$this->out($words);
if ($function === 'all') {
foreach ($this->validMethods as $method) {
$functionName = $this->_getMessage($method);
$this->out("{$functionName}: " . Inflector::$method($words));
}
} else {
$functionName = $this->_getMessage($function);
$this->out("{$functionName}: " . Inflector::$function($words));
}
} | php | protected function _inflect($function, $words) {
$this->out($words);
if ($function === 'all') {
foreach ($this->validMethods as $method) {
$functionName = $this->_getMessage($method);
$this->out("{$functionName}: " . Inflector::$method($words));
}
} else {
$functionName = $this->_getMessage($function);
$this->out("{$functionName}: " . Inflector::$function($words));
}
} | [
"protected",
"function",
"_inflect",
"(",
"$",
"function",
",",
"$",
"words",
")",
"{",
"$",
"this",
"->",
"out",
"(",
"$",
"words",
")",
";",
"if",
"(",
"$",
"function",
"===",
"'all'",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"validMethods",
... | Inflects a set of words based upon the inflection set in the arguments
@param string $function
@param string $words
@return void | [
"Inflects",
"a",
"set",
"of",
"words",
"based",
"upon",
"the",
"inflection",
"set",
"in",
"the",
"arguments"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Shell/InflectShell.php#L192-L203 | train |
dereuromark/cakephp-tools | src/Shell/InflectShell.php | InflectShell.help | public function help() {
$this->out('Inflector Shell');
$this->out('');
$this->out('This shell uses the Inflector class to inflect any word(s) you wish');
$this->hr();
$this->out('Usage: cake inflect');
$this->out(' cake inflect methodName');
$this->out(' cake inflect methodName word');
$this->out(' cake inflect methodName words to inflect');
$this->out('');
} | php | public function help() {
$this->out('Inflector Shell');
$this->out('');
$this->out('This shell uses the Inflector class to inflect any word(s) you wish');
$this->hr();
$this->out('Usage: cake inflect');
$this->out(' cake inflect methodName');
$this->out(' cake inflect methodName word');
$this->out(' cake inflect methodName words to inflect');
$this->out('');
} | [
"public",
"function",
"help",
"(",
")",
"{",
"$",
"this",
"->",
"out",
"(",
"'Inflector Shell'",
")",
";",
"$",
"this",
"->",
"out",
"(",
"''",
")",
";",
"$",
"this",
"->",
"out",
"(",
"'This shell uses the Inflector class to inflect any word(s) you wish'",
")... | Displays help contents
@return void | [
"Displays",
"help",
"contents"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Shell/InflectShell.php#L232-L242 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.readWithPattern | public function readWithPattern($text, $pattern) {
$pieces = explode("\n", $text);
$result = [];
foreach ($pieces as $piece) {
$result[] = sscanf(trim($piece, "\r\n"), $pattern);
}
return $result;
} | php | public function readWithPattern($text, $pattern) {
$pieces = explode("\n", $text);
$result = [];
foreach ($pieces as $piece) {
$result[] = sscanf(trim($piece, "\r\n"), $pattern);
}
return $result;
} | [
"public",
"function",
"readWithPattern",
"(",
"$",
"text",
",",
"$",
"pattern",
")",
"{",
"$",
"pieces",
"=",
"explode",
"(",
"\"\\n\"",
",",
"$",
"text",
")",
";",
"$",
"result",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"pieces",
"as",
"$",
"piece... | Read with a specific pattern.
E.g.: '%s,%s,%s'
@param string $text
@param string $pattern
@return array | [
"Read",
"with",
"a",
"specific",
"pattern",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L99-L106 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.numberOfWords | public static function numberOfWords($text) {
$count = 0;
$words = explode(' ', $text);
foreach ($words as $word) {
$word = trim($word);
if (!empty($word)) {
$count++;
}
}
return $count;
} | php | public static function numberOfWords($text) {
$count = 0;
$words = explode(' ', $text);
foreach ($words as $word) {
$word = trim($word);
if (!empty($word)) {
$count++;
}
}
return $count;
} | [
"public",
"static",
"function",
"numberOfWords",
"(",
"$",
"text",
")",
"{",
"$",
"count",
"=",
"0",
";",
"$",
"words",
"=",
"explode",
"(",
"' '",
",",
"$",
"text",
")",
";",
"foreach",
"(",
"$",
"words",
"as",
"$",
"word",
")",
"{",
"$",
"word"... | Count words in a text.
//TODO use str_word_count() instead!!!
@param string $text
@return int | [
"Count",
"words",
"in",
"a",
"text",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L116-L126 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.numberOfChars | public static function numberOfChars($text, array $options = []) {
$text = str_replace(["\r", "\n", "\t", ' '], '', $text);
$count = mb_strlen($text);
return $count;
} | php | public static function numberOfChars($text, array $options = []) {
$text = str_replace(["\r", "\n", "\t", ' '], '', $text);
$count = mb_strlen($text);
return $count;
} | [
"public",
"static",
"function",
"numberOfChars",
"(",
"$",
"text",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"text",
"=",
"str_replace",
"(",
"[",
"\"\\r\"",
",",
"\"\\n\"",
",",
"\"\\t\"",
",",
"' '",
"]",
",",
"''",
",",
"$",
"t... | Count chars in a text.
Options:
- 'whitespace': If whitespace should be counted, as well, defaults to false
@param string $text
@param array $options
@return int | [
"Count",
"chars",
"in",
"a",
"text",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L138-L142 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.explodeTags | public function explodeTags($tags) {
// This regexp allows the following types of user input:
// this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
preg_match_all($regexp, $tags, $matches);
$typedTags = array_unique($matches[1]);
$tags = [];
foreach ($typedTags as $tag) {
// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
if ($tag) {
$tags[] = $tag;
}
}
return $tags;
} | php | public function explodeTags($tags) {
// This regexp allows the following types of user input:
// this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
$regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
preg_match_all($regexp, $tags, $matches);
$typedTags = array_unique($matches[1]);
$tags = [];
foreach ($typedTags as $tag) {
// If a user has escaped a term (to demonstrate that it is a group,
// or includes a comma or quote character), we remove the escape
// formatting so to save the term into the database as the user intends.
$tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
if ($tag) {
$tags[] = $tag;
}
}
return $tags;
} | [
"public",
"function",
"explodeTags",
"(",
"$",
"tags",
")",
"{",
"// This regexp allows the following types of user input:",
"// this, \"somecompany, llc\", \"and \"\"this\"\" w,o.rks\", foo bar",
"$",
"regexp",
"=",
"'%(?:^|,\\ *)(\"(?>[^\"]*)(?>\"\"[^\"]* )*\"|(?: [^\",]*))%x'",
";",
... | Explode a string of given tags into an array.
@param string $tags
@return array | [
"Explode",
"a",
"string",
"of",
"given",
"tags",
"into",
"an",
"array",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L212-L231 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.implodeTags | public function implodeTags(array $tags) {
$encodedTags = [];
foreach ($tags as $tag) {
// Commas and quotes in tag names are special cases, so encode them.
if (strpos($tag, ',') !== false || strpos($tag, '"') !== false) {
$tag = '"' . str_replace('"', '""', $tag) . '"';
}
$encodedTags[] = $tag;
}
return implode(', ', $encodedTags);
} | php | public function implodeTags(array $tags) {
$encodedTags = [];
foreach ($tags as $tag) {
// Commas and quotes in tag names are special cases, so encode them.
if (strpos($tag, ',') !== false || strpos($tag, '"') !== false) {
$tag = '"' . str_replace('"', '""', $tag) . '"';
}
$encodedTags[] = $tag;
}
return implode(', ', $encodedTags);
} | [
"public",
"function",
"implodeTags",
"(",
"array",
"$",
"tags",
")",
"{",
"$",
"encodedTags",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"tags",
"as",
"$",
"tag",
")",
"{",
"// Commas and quotes in tag names are special cases, so encode them.",
"if",
"(",
"strpos"... | Implode an array of tags into a string.
@param array $tags
@return string | [
"Implode",
"an",
"array",
"of",
"tags",
"into",
"a",
"string",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L239-L250 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.asciiToEntities | public function asciiToEntities($str) {
$count = 1;
$out = '';
$temp = [];
for ($i = 0, $s = strlen($str); $i < $s; $i++) {
$ordinal = ord($str[$i]);
if ($ordinal < 128) {
/*
If the $temp array has a value but we have moved on, then it seems only
fair that we output that entity and restart $temp before continuing. -Paul
*/
if (count($temp) == 1) {
$out .= '&#' . array_shift($temp) . ';';
$count = 1;
}
$out .= $str[$i];
} else {
if (count($temp) == 0) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count) {
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] %
64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$out .= '&#' . $number . ';';
$count = 1;
$temp = [];
}
}
}
return $out;
} | php | public function asciiToEntities($str) {
$count = 1;
$out = '';
$temp = [];
for ($i = 0, $s = strlen($str); $i < $s; $i++) {
$ordinal = ord($str[$i]);
if ($ordinal < 128) {
/*
If the $temp array has a value but we have moved on, then it seems only
fair that we output that entity and restart $temp before continuing. -Paul
*/
if (count($temp) == 1) {
$out .= '&#' . array_shift($temp) . ';';
$count = 1;
}
$out .= $str[$i];
} else {
if (count($temp) == 0) {
$count = ($ordinal < 224) ? 2 : 3;
}
$temp[] = $ordinal;
if (count($temp) == $count) {
$number = ($count == 3) ? (($temp['0'] % 16) * 4096) + (($temp['1'] % 64) * 64) + ($temp['2'] %
64) : (($temp['0'] % 32) * 64) + ($temp['1'] % 64);
$out .= '&#' . $number . ';';
$count = 1;
$temp = [];
}
}
}
return $out;
} | [
"public",
"function",
"asciiToEntities",
"(",
"$",
"str",
")",
"{",
"$",
"count",
"=",
"1",
";",
"$",
"out",
"=",
"''",
";",
"$",
"temp",
"=",
"[",
"]",
";",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
"s",
"=",
"strlen",
"(",
"$",
"str",
")"... | High ASCII to Entities
Converts High ascii text and MS Word special characters to character entities
@param string $str
@return string | [
"High",
"ASCII",
"to",
"Entities"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L356-L393 | train |
dereuromark/cakephp-tools | src/Utility/Text.php | Text.entitiesToAscii | public function entitiesToAscii($str, $all = true) {
if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) {
for ($i = 0, $s = count($matches['0']); $i < $s; $i++) {
$digits = $matches['1'][$i];
$out = '';
if ($digits < 128) {
$out .= chr($digits);
} elseif ($digits < 2048) {
$out .= chr(192 + (($digits - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
} else {
$out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
$out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
}
$str = str_replace($matches['0'][$i], $out, $str);
}
}
if ($all) {
$str = str_replace(['&', '<', '>', '"', ''', '-'],
['&', '<', '>', '"', "'", '-'], $str);
}
return $str;
} | php | public function entitiesToAscii($str, $all = true) {
if (preg_match_all('/\&#(\d+)\;/', $str, $matches)) {
for ($i = 0, $s = count($matches['0']); $i < $s; $i++) {
$digits = $matches['1'][$i];
$out = '';
if ($digits < 128) {
$out .= chr($digits);
} elseif ($digits < 2048) {
$out .= chr(192 + (($digits - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
} else {
$out .= chr(224 + (($digits - ($digits % 4096)) / 4096));
$out .= chr(128 + ((($digits % 4096) - ($digits % 64)) / 64));
$out .= chr(128 + ($digits % 64));
}
$str = str_replace($matches['0'][$i], $out, $str);
}
}
if ($all) {
$str = str_replace(['&', '<', '>', '"', ''', '-'],
['&', '<', '>', '"', "'", '-'], $str);
}
return $str;
} | [
"public",
"function",
"entitiesToAscii",
"(",
"$",
"str",
",",
"$",
"all",
"=",
"true",
")",
"{",
"if",
"(",
"preg_match_all",
"(",
"'/\\&#(\\d+)\\;/'",
",",
"$",
"str",
",",
"$",
"matches",
")",
")",
"{",
"for",
"(",
"$",
"i",
"=",
"0",
",",
"$",
... | Entities to ASCII
Converts character entities back to ASCII
@param string $str
@param bool $all
@return string | [
"Entities",
"to",
"ASCII"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Text.php#L404-L432 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.hasDaylightSavingTime | public function hasDaylightSavingTime($timezone = null) {
$timezone = $this->safeCreateDateTimeZone($timezone);
// a date outside of DST
$offset = $timezone->getOffset(new CakeTime('@' . mktime(0, 0, 0, 2, 1, date('Y'))));
$offset = $offset / HOUR;
// a date inside of DST
$offset2 = $timezone->getOffset(new CakeTime('@' . mktime(0, 0, 0, 8, 1, date('Y'))));
$offset2 = $offset2 / HOUR;
return abs($offset2 - $offset) > 0;
} | php | public function hasDaylightSavingTime($timezone = null) {
$timezone = $this->safeCreateDateTimeZone($timezone);
// a date outside of DST
$offset = $timezone->getOffset(new CakeTime('@' . mktime(0, 0, 0, 2, 1, date('Y'))));
$offset = $offset / HOUR;
// a date inside of DST
$offset2 = $timezone->getOffset(new CakeTime('@' . mktime(0, 0, 0, 8, 1, date('Y'))));
$offset2 = $offset2 / HOUR;
return abs($offset2 - $offset) > 0;
} | [
"public",
"function",
"hasDaylightSavingTime",
"(",
"$",
"timezone",
"=",
"null",
")",
"{",
"$",
"timezone",
"=",
"$",
"this",
"->",
"safeCreateDateTimeZone",
"(",
"$",
"timezone",
")",
";",
"// a date outside of DST",
"$",
"offset",
"=",
"$",
"timezone",
"->"... | Detect if a timezone has a DST
@param string|\DateTimeZone|null $timezone User's timezone string or DateTimeZone object
@return bool | [
"Detect",
"if",
"a",
"timezone",
"has",
"a",
"DST"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L55-L66 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.difference | public static function difference($startTime, $endTime = null, array $options = []) {
if (!is_int($startTime)) {
$startTime = strtotime($startTime);
}
if (!is_int($endTime)) {
$endTime = strtotime($endTime);
}
//@FIXME: make it work for > month
return abs($endTime - $startTime);
} | php | public static function difference($startTime, $endTime = null, array $options = []) {
if (!is_int($startTime)) {
$startTime = strtotime($startTime);
}
if (!is_int($endTime)) {
$endTime = strtotime($endTime);
}
//@FIXME: make it work for > month
return abs($endTime - $startTime);
} | [
"public",
"static",
"function",
"difference",
"(",
"$",
"startTime",
",",
"$",
"endTime",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"is_int",
"(",
"$",
"startTime",
")",
")",
"{",
"$",
"startTime",
"=",
"st... | Calculate the difference between two dates
TODO: deprecate in favor of DateTime::diff() etc which will be more precise
should only be used for < month (due to the different month lenghts it gets fuzzy)
@param mixed $startTime (db format or timestamp)
@param mixed|null $endTime (db format or timestamp)
@param array $options
@return int The distance in seconds | [
"Calculate",
"the",
"difference",
"between",
"two",
"dates"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L80-L89 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.age | public static function age($start, $end = null) {
if (empty($start) && empty($end) || $start == $end) {
return 0;
}
if (is_int($start)) {
$start = date(FORMAT_DB_DATE, $start);
}
if (is_int($end)) {
$end = date(FORMAT_DB_DATE, $end);
}
$startDate = $start;
if (!is_object($start)) {
$startDate = new CakeTime($start);
}
$endDate = $end;
if (!is_object($end)) {
$endDate = new CakeTime($end);
}
if ($startDate > $endDate) {
return -1;
}
$oDateInterval = $endDate->diff($startDate);
return $oDateInterval->y;
} | php | public static function age($start, $end = null) {
if (empty($start) && empty($end) || $start == $end) {
return 0;
}
if (is_int($start)) {
$start = date(FORMAT_DB_DATE, $start);
}
if (is_int($end)) {
$end = date(FORMAT_DB_DATE, $end);
}
$startDate = $start;
if (!is_object($start)) {
$startDate = new CakeTime($start);
}
$endDate = $end;
if (!is_object($end)) {
$endDate = new CakeTime($end);
}
if ($startDate > $endDate) {
return -1;
}
$oDateInterval = $endDate->diff($startDate);
return $oDateInterval->y;
} | [
"public",
"static",
"function",
"age",
"(",
"$",
"start",
",",
"$",
"end",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"start",
")",
"&&",
"empty",
"(",
"$",
"end",
")",
"||",
"$",
"start",
"==",
"$",
"end",
")",
"{",
"return",
"0",
... | Calculates the age using start and optional end date.
Both dates default to current date. Note that start needs
to be before end for a valid result.
@param int|string $start Start date (if empty, use today)
@param int|string|null $end End date (if empty, use today)
@return int Age (0 if both timestamps are equal or empty, -1 on invalid dates) | [
"Calculates",
"the",
"age",
"using",
"start",
"and",
"optional",
"end",
"date",
".",
"Both",
"dates",
"default",
"to",
"current",
"date",
".",
"Note",
"that",
"start",
"needs",
"to",
"be",
"before",
"end",
"for",
"a",
"valid",
"result",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L100-L127 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.cWeekBeginning | public static function cWeekBeginning($year, $cWeek = 0) {
if ($cWeek <= 1 || $cWeek > static::cWeeks($year)) {
$first = mktime(0, 0, 0, 1, 1, $year);
$wtag = (int)date('w', $first);
if ($wtag <= 4) {
/* Thursday or less: back to Monday */
$firstmonday = mktime(0, 0, 0, 1, 1 - ($wtag - 1), $year);
} elseif ($wtag != 1) {
/* Back to Monday */
$firstmonday = mktime(0, 0, 0, 1, 1 + (7 - $wtag + 1), $year);
} else {
$firstmonday = $first;
}
return $firstmonday;
}
$monday = strtotime($year . 'W' . static::pad($cWeek) . '1');
return $monday;
} | php | public static function cWeekBeginning($year, $cWeek = 0) {
if ($cWeek <= 1 || $cWeek > static::cWeeks($year)) {
$first = mktime(0, 0, 0, 1, 1, $year);
$wtag = (int)date('w', $first);
if ($wtag <= 4) {
/* Thursday or less: back to Monday */
$firstmonday = mktime(0, 0, 0, 1, 1 - ($wtag - 1), $year);
} elseif ($wtag != 1) {
/* Back to Monday */
$firstmonday = mktime(0, 0, 0, 1, 1 + (7 - $wtag + 1), $year);
} else {
$firstmonday = $first;
}
return $firstmonday;
}
$monday = strtotime($year . 'W' . static::pad($cWeek) . '1');
return $monday;
} | [
"public",
"static",
"function",
"cWeekBeginning",
"(",
"$",
"year",
",",
"$",
"cWeek",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"cWeek",
"<=",
"1",
"||",
"$",
"cWeek",
">",
"static",
"::",
"cWeeks",
"(",
"$",
"year",
")",
")",
"{",
"$",
"first",
"=",
... | Calculate the beginning of a calender week
if no calendar week is given get the beginning of the first week of the year
@param int $year (format xxxx)
@param int $cWeek (optional, defaults to first, range 1...52/53)
@return int Timestamp | [
"Calculate",
"the",
"beginning",
"of",
"a",
"calender",
"week",
"if",
"no",
"calendar",
"week",
"is",
"given",
"get",
"the",
"beginning",
"of",
"the",
"first",
"week",
"of",
"the",
"year"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L262-L280 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.cWeekEnding | public static function cWeekEnding($year, $cWeek = 0) {
if ($cWeek < 1 || $cWeek >= static::cWeeks($year)) {
return static::cWeekBeginning($year + 1) - 1;
}
return static::cWeekBeginning($year, $cWeek + 1) - 1;
} | php | public static function cWeekEnding($year, $cWeek = 0) {
if ($cWeek < 1 || $cWeek >= static::cWeeks($year)) {
return static::cWeekBeginning($year + 1) - 1;
}
return static::cWeekBeginning($year, $cWeek + 1) - 1;
} | [
"public",
"static",
"function",
"cWeekEnding",
"(",
"$",
"year",
",",
"$",
"cWeek",
"=",
"0",
")",
"{",
"if",
"(",
"$",
"cWeek",
"<",
"1",
"||",
"$",
"cWeek",
">=",
"static",
"::",
"cWeeks",
"(",
"$",
"year",
")",
")",
"{",
"return",
"static",
":... | Calculate the ending of a calenderweek
if no cweek is given get the ending of the last week of the year
@param int $year (format xxxx)
@param int $cWeek (optional, defaults to last, range 1...52/53)
@return int Timestamp | [
"Calculate",
"the",
"ending",
"of",
"a",
"calenderweek",
"if",
"no",
"cweek",
"is",
"given",
"get",
"the",
"ending",
"of",
"the",
"last",
"week",
"of",
"the",
"year"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L290-L295 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.cWeeks | public static function cWeeks($year = null) {
if ($year === null) {
$year = date('Y');
}
return (int)date('W', mktime(23, 59, 59, 12, 28, $year));
} | php | public static function cWeeks($year = null) {
if ($year === null) {
$year = date('Y');
}
return (int)date('W', mktime(23, 59, 59, 12, 28, $year));
} | [
"public",
"static",
"function",
"cWeeks",
"(",
"$",
"year",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"year",
"===",
"null",
")",
"{",
"$",
"year",
"=",
"date",
"(",
"'Y'",
")",
";",
"}",
"return",
"(",
"int",
")",
"date",
"(",
"'W'",
",",
"mktime... | Calculate the amount of calender weeks in a year
@param int|null $year (format xxxx, defaults to current year)
@return int Amount of weeks - 52 or 53 | [
"Calculate",
"the",
"amount",
"of",
"calender",
"weeks",
"in",
"a",
"year"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L303-L308 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time._strftime | protected static function _strftime($format, $date) {
$format = strftime($format, $date);
$encoding = Configure::read('App.encoding');
if (!empty($encoding) && $encoding === 'UTF-8') {
$valid = mb_check_encoding($format, $encoding);
if (!$valid) {
$format = utf8_encode($format);
}
}
return $format;
} | php | protected static function _strftime($format, $date) {
$format = strftime($format, $date);
$encoding = Configure::read('App.encoding');
if (!empty($encoding) && $encoding === 'UTF-8') {
$valid = mb_check_encoding($format, $encoding);
if (!$valid) {
$format = utf8_encode($format);
}
}
return $format;
} | [
"protected",
"static",
"function",
"_strftime",
"(",
"$",
"format",
",",
"$",
"date",
")",
"{",
"$",
"format",
"=",
"strftime",
"(",
"$",
"format",
",",
"$",
"date",
")",
";",
"$",
"encoding",
"=",
"Configure",
"::",
"read",
"(",
"'App.encoding'",
")",... | Multibyte wrapper for strftime.
Handles utf8_encoding the result of strftime when necessary.
@param string $format Format string.
@param int $date Timestamp to format.
@return string formatted string with correct encoding. | [
"Multibyte",
"wrapper",
"for",
"strftime",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L448-L459 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.convertDate | public static function convertDate($oldDateString, $newDateFormatString, $timezone = null) {
$Date = new CakeTime($oldDateString, $timezone);
return $Date->format($newDateFormatString);
} | php | public static function convertDate($oldDateString, $newDateFormatString, $timezone = null) {
$Date = new CakeTime($oldDateString, $timezone);
return $Date->format($newDateFormatString);
} | [
"public",
"static",
"function",
"convertDate",
"(",
"$",
"oldDateString",
",",
"$",
"newDateFormatString",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"$",
"Date",
"=",
"new",
"CakeTime",
"(",
"$",
"oldDateString",
",",
"$",
"timezone",
")",
";",
"return"... | Convenience method to convert a given date
@deprecated
@param string $oldDateString
@param string $newDateFormatString
@param int|null $timezone User's timezone
@return string Formatted date | [
"Convenience",
"method",
"to",
"convert",
"a",
"given",
"date"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L939-L942 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.isNotTodayAndInTheFuture | public static function isNotTodayAndInTheFuture($dateString, $timezone = null) {
$date = new CakeTime($dateString, $timezone);
$date = $date->format('U');
return date(FORMAT_DB_DATE, $date) > date(FORMAT_DB_DATE, time());
} | php | public static function isNotTodayAndInTheFuture($dateString, $timezone = null) {
$date = new CakeTime($dateString, $timezone);
$date = $date->format('U');
return date(FORMAT_DB_DATE, $date) > date(FORMAT_DB_DATE, time());
} | [
"public",
"static",
"function",
"isNotTodayAndInTheFuture",
"(",
"$",
"dateString",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"$",
"date",
"=",
"new",
"CakeTime",
"(",
"$",
"dateString",
",",
"$",
"timezone",
")",
";",
"$",
"date",
"=",
"$",
"date",
... | Returns true if given datetime string is not today AND is in the future.
@param string $dateString Datetime string or Unix timestamp
@param int|null $timezone User's timezone
@return bool True if datetime is not today AND is in the future | [
"Returns",
"true",
"if",
"given",
"datetime",
"string",
"is",
"not",
"today",
"AND",
"is",
"in",
"the",
"future",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L971-L975 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.isInTheFuture | public static function isInTheFuture($dateString, $timezone = null) {
$date = new CakeTime($dateString, $timezone);
$date = $date->format('U');
return date(FORMAT_DB_DATETIME, $date) > date(FORMAT_DB_DATETIME, time());
} | php | public static function isInTheFuture($dateString, $timezone = null) {
$date = new CakeTime($dateString, $timezone);
$date = $date->format('U');
return date(FORMAT_DB_DATETIME, $date) > date(FORMAT_DB_DATETIME, time());
} | [
"public",
"static",
"function",
"isInTheFuture",
"(",
"$",
"dateString",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"$",
"date",
"=",
"new",
"CakeTime",
"(",
"$",
"dateString",
",",
"$",
"timezone",
")",
";",
"$",
"date",
"=",
"$",
"date",
"->",
"f... | Returns true if given datetime string is not now AND is in the future.
@param string $dateString Datetime string or Unix timestamp
@param int|null $timezone User's timezone
@return bool True if datetime is not today AND is in the future | [
"Returns",
"true",
"if",
"given",
"datetime",
"string",
"is",
"not",
"now",
"AND",
"is",
"in",
"the",
"future",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L984-L988 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.daysAsSql | public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
$begin = new CakeTime($begin, $timezone);
$begin = $begin->format('U');
$end = new CakeTime($end, $timezone);
$end = $end->format('U');
$begin = date('Y-m-d', $begin) . ' 00:00:00';
$end = date('Y-m-d', $end) . ' 23:59:59';
return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
} | php | public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
$begin = new CakeTime($begin, $timezone);
$begin = $begin->format('U');
$end = new CakeTime($end, $timezone);
$end = $end->format('U');
$begin = date('Y-m-d', $begin) . ' 00:00:00';
$end = date('Y-m-d', $end) . ' 23:59:59';
return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
} | [
"public",
"static",
"function",
"daysAsSql",
"(",
"$",
"begin",
",",
"$",
"end",
",",
"$",
"fieldName",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"$",
"begin",
"=",
"new",
"CakeTime",
"(",
"$",
"begin",
",",
"$",
"timezone",
")",
";",
"$",
"begi... | Returns a partial SQL string to search for all records between two dates.
@param int|string|\DateTime $begin UNIX timestamp, strtotime() valid string or DateTime object
@param int|string|\DateTime $end UNIX timestamp, strtotime() valid string or DateTime object
@param string $fieldName Name of database field to compare with
@param string|\DateTimeZone|null $timezone Timezone string or DateTimeZone object
@return string Partial SQL string. | [
"Returns",
"a",
"partial",
"SQL",
"string",
"to",
"search",
"for",
"all",
"records",
"between",
"two",
"dates",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L1098-L1107 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.dayAsSql | public static function dayAsSql($dateString, $fieldName, $timezone = null) {
return static::daysAsSql($dateString, $dateString, $fieldName, $timezone);
} | php | public static function dayAsSql($dateString, $fieldName, $timezone = null) {
return static::daysAsSql($dateString, $dateString, $fieldName, $timezone);
} | [
"public",
"static",
"function",
"dayAsSql",
"(",
"$",
"dateString",
",",
"$",
"fieldName",
",",
"$",
"timezone",
"=",
"null",
")",
"{",
"return",
"static",
"::",
"daysAsSql",
"(",
"$",
"dateString",
",",
"$",
"dateString",
",",
"$",
"fieldName",
",",
"$"... | Returns a partial SQL string to search for all records between two times
occurring on the same day.
@param int|string|\DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
@param string $fieldName Name of database field to compare with
@param string|\DateTimeZone|null $timezone Timezone string or DateTimeZone object
@return string Partial SQL string. | [
"Returns",
"a",
"partial",
"SQL",
"string",
"to",
"search",
"for",
"all",
"records",
"between",
"two",
"times",
"occurring",
"on",
"the",
"same",
"day",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L1118-L1120 | train |
dereuromark/cakephp-tools | src/Utility/Time.php | Time.parseLocalDate | public static function parseLocalDate($date, array $allowed = ['.', '-']) {
$datePieces = explode(' ', $date, 2);
$date = array_shift($datePieces);
if (strpos($date, '.') !== false) {
$pieces = explode('.', $date);
$year = $pieces[2];
if (strlen($year) === 2) {
if ($year < 50) {
$year = '20' . $year;
} else {
$year = '19' . $year;
}
}
$date = mktime(0, 0, 0, $pieces[1], $pieces[0], $year);
} elseif (strpos($date, '-') !== false) {
//$pieces = explode('-', $date);
$date = strtotime($date);
} else {
return 0;
}
return $date;
} | php | public static function parseLocalDate($date, array $allowed = ['.', '-']) {
$datePieces = explode(' ', $date, 2);
$date = array_shift($datePieces);
if (strpos($date, '.') !== false) {
$pieces = explode('.', $date);
$year = $pieces[2];
if (strlen($year) === 2) {
if ($year < 50) {
$year = '20' . $year;
} else {
$year = '19' . $year;
}
}
$date = mktime(0, 0, 0, $pieces[1], $pieces[0], $year);
} elseif (strpos($date, '-') !== false) {
//$pieces = explode('-', $date);
$date = strtotime($date);
} else {
return 0;
}
return $date;
} | [
"public",
"static",
"function",
"parseLocalDate",
"(",
"$",
"date",
",",
"array",
"$",
"allowed",
"=",
"[",
"'.'",
",",
"'-'",
"]",
")",
"{",
"$",
"datePieces",
"=",
"explode",
"(",
"' '",
",",
"$",
"date",
",",
"2",
")",
";",
"$",
"date",
"=",
"... | Parse 2022-11-12 or 12.11.2022 or even 12.11.22
@param string $date
@param array $allowed
@return int Seconds | [
"Parse",
"2022",
"-",
"11",
"-",
"12",
"or",
"12",
".",
"11",
".",
"2022",
"or",
"even",
"12",
".",
"11",
".",
"22"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Time.php#L1213-L1235 | train |
dereuromark/cakephp-tools | src/View/Helper/ObfuscateHelper.php | ObfuscateHelper.wordCensor | public function wordCensor($str, array $censored, $replacement = null) {
if (empty($censored)) {
return $str;
}
$str = ' ' . $str . ' ';
// \w, \b and a few others do not match on a unicode character
// set for performance reasons. As a result words like ..ber
// will not match on a word boundary. Instead, we'll assume that
// a bad word will be bookended by any of these characters.
$delim = '[-_\'\"`() {}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
foreach ($censored as $badword) {
if ($replacement !== null) {
$str = preg_replace("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/i", "\\1{$replacement}\\3", $str);
} else {
$str = preg_replace_callback("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/i", function ($matches) {
return $matches[1] . str_repeat('#', strlen($matches[2])) . $matches[3];
}, $str);
}
}
return trim($str);
} | php | public function wordCensor($str, array $censored, $replacement = null) {
if (empty($censored)) {
return $str;
}
$str = ' ' . $str . ' ';
// \w, \b and a few others do not match on a unicode character
// set for performance reasons. As a result words like ..ber
// will not match on a word boundary. Instead, we'll assume that
// a bad word will be bookended by any of these characters.
$delim = '[-_\'\"`() {}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';
foreach ($censored as $badword) {
if ($replacement !== null) {
$str = preg_replace("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/i", "\\1{$replacement}\\3", $str);
} else {
$str = preg_replace_callback("/({$delim})(" . str_replace('\*', '\w*?', preg_quote($badword, '/')) . ")({$delim})/i", function ($matches) {
return $matches[1] . str_repeat('#', strlen($matches[2])) . $matches[3];
}, $str);
}
}
return trim($str);
} | [
"public",
"function",
"wordCensor",
"(",
"$",
"str",
",",
"array",
"$",
"censored",
",",
"$",
"replacement",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"censored",
")",
")",
"{",
"return",
"$",
"str",
";",
"}",
"$",
"str",
"=",
"' '",
"... | Word Censoring Function
Supply a string and an array of disallowed words and any
matched words will be converted to #### or to the replacement
word you've submitted.
@param string $str the text string
@param array $censored the array of censored words
@param string|null $replacement the optional replacement value
@return string | [
"Word",
"Censoring",
"Function"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/ObfuscateHelper.php#L160-L183 | train |
dereuromark/cakephp-tools | src/Controller/ShuntRequestController.php | ShuntRequestController.language | public function language($language = null) {
$this->getRequest()->allowMethod(['post']);
$allowedLanguages = (array)Configure::read('Config.allowedLanguages');
if (!$language) {
$language = Configure::read('Config.defaultLanguage');
}
if (!$language) {
$keys = array_keys($allowedLanguages);
$language = $allowedLanguages[array_shift($keys)];
}
if (!array_key_exists($language, $allowedLanguages)) {
throw new RuntimeException('Invalid Language');
}
$language = $allowedLanguages[$language];
$this->getRequest()->getSession()->write('Config.language', $language['locale']);
I18n::setLocale($language['locale']);
$this->Flash->success(__d('tools', 'Language switched to {0}', $language['name']));
return $this->redirect($this->referer('/', true));
} | php | public function language($language = null) {
$this->getRequest()->allowMethod(['post']);
$allowedLanguages = (array)Configure::read('Config.allowedLanguages');
if (!$language) {
$language = Configure::read('Config.defaultLanguage');
}
if (!$language) {
$keys = array_keys($allowedLanguages);
$language = $allowedLanguages[array_shift($keys)];
}
if (!array_key_exists($language, $allowedLanguages)) {
throw new RuntimeException('Invalid Language');
}
$language = $allowedLanguages[$language];
$this->getRequest()->getSession()->write('Config.language', $language['locale']);
I18n::setLocale($language['locale']);
$this->Flash->success(__d('tools', 'Language switched to {0}', $language['name']));
return $this->redirect($this->referer('/', true));
} | [
"public",
"function",
"language",
"(",
"$",
"language",
"=",
"null",
")",
"{",
"$",
"this",
"->",
"getRequest",
"(",
")",
"->",
"allowMethod",
"(",
"[",
"'post'",
"]",
")",
";",
"$",
"allowedLanguages",
"=",
"(",
"array",
")",
"Configure",
"::",
"read"... | Switch language as post link.
@param string|null $language
@return \Cake\Http\Response
@throws \RuntimeException | [
"Switch",
"language",
"as",
"post",
"link",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Controller/ShuntRequestController.php#L32-L53 | train |
dereuromark/cakephp-tools | src/Utility/Language.php | Language.parseLanguageList | public static function parseLanguageList($languageList = null, $options = []) {
$defaultOptions = [
'forceLowerCase' => true,
];
if (!is_array($options)) {
$options = ['forceLowerCase' => $options];
}
$options += $defaultOptions;
if ($languageList === null) {
if (!env('HTTP_ACCEPT_LANGUAGE')) {
return [];
}
$languageList = env('HTTP_ACCEPT_LANGUAGE');
}
$languages = [];
$languagesRanks = [];
$languageRanges = explode(',', trim($languageList));
foreach ($languageRanges as $languageRange) {
$pattern = '/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/';
if (preg_match($pattern, trim($languageRange), $match)) {
if (!isset($match[2])) {
$rank = '1.0';
} else {
$rank = (string)(float)($match[2]);
}
if (!isset($languages[$rank])) {
if ($rank === '1') {
$rank = '1.0';
}
$languages[$rank] = [];
}
$language = $match[1];
if ($options['forceLowerCase']) {
$language = strtolower($language);
} else {
$language = substr_replace($language, strtolower(substr($language, 0, 2)), 0, 2);
if (strlen($language) === 5) {
$language = substr_replace($language, strtoupper(substr($language, 3, 2)), 3, 2);
}
}
if (array_key_exists($language, $languagesRanks) === false) {
$languages[$rank][] = $language;
$languagesRanks[$language] = $rank;
} elseif ($rank > $languagesRanks[$language]) {
foreach ($languages as $existRank => $existLangs) {
$key = array_search($existLangs, $languages);
if ($key !== false) {
unset($languages[$existRank][$key]);
if (empty($languages[$existRank])) {
unset($languages[$existRank]);
}
}
}
$languages[$rank][] = $language;
$languagesRanks[$language] = $rank;
}
}
}
krsort($languages);
return $languages;
} | php | public static function parseLanguageList($languageList = null, $options = []) {
$defaultOptions = [
'forceLowerCase' => true,
];
if (!is_array($options)) {
$options = ['forceLowerCase' => $options];
}
$options += $defaultOptions;
if ($languageList === null) {
if (!env('HTTP_ACCEPT_LANGUAGE')) {
return [];
}
$languageList = env('HTTP_ACCEPT_LANGUAGE');
}
$languages = [];
$languagesRanks = [];
$languageRanges = explode(',', trim($languageList));
foreach ($languageRanges as $languageRange) {
$pattern = '/(\*|[a-zA-Z0-9]{1,8}(?:-[a-zA-Z0-9]{1,8})*)(?:\s*;\s*q\s*=\s*(0(?:\.\d{0,3})|1(?:\.0{0,3})))?/';
if (preg_match($pattern, trim($languageRange), $match)) {
if (!isset($match[2])) {
$rank = '1.0';
} else {
$rank = (string)(float)($match[2]);
}
if (!isset($languages[$rank])) {
if ($rank === '1') {
$rank = '1.0';
}
$languages[$rank] = [];
}
$language = $match[1];
if ($options['forceLowerCase']) {
$language = strtolower($language);
} else {
$language = substr_replace($language, strtolower(substr($language, 0, 2)), 0, 2);
if (strlen($language) === 5) {
$language = substr_replace($language, strtoupper(substr($language, 3, 2)), 3, 2);
}
}
if (array_key_exists($language, $languagesRanks) === false) {
$languages[$rank][] = $language;
$languagesRanks[$language] = $rank;
} elseif ($rank > $languagesRanks[$language]) {
foreach ($languages as $existRank => $existLangs) {
$key = array_search($existLangs, $languages);
if ($key !== false) {
unset($languages[$existRank][$key]);
if (empty($languages[$existRank])) {
unset($languages[$existRank]);
}
}
}
$languages[$rank][] = $language;
$languagesRanks[$language] = $rank;
}
}
}
krsort($languages);
return $languages;
} | [
"public",
"static",
"function",
"parseLanguageList",
"(",
"$",
"languageList",
"=",
"null",
",",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"defaultOptions",
"=",
"[",
"'forceLowerCase'",
"=>",
"true",
",",
"]",
";",
"if",
"(",
"!",
"is_array",
"(",
... | Parse languages from a browser language list.
Options
- forceLowerCase: defaults to true
@param string|null $languageList List of locales/language codes.
@param array|bool|null $options Flags to forceLowerCase or removeDuplicates locales/language codes
deprecated: Set to true/false to toggle lowercase
@return array | [
"Parse",
"languages",
"from",
"a",
"browser",
"language",
"list",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Language.php#L22-L87 | train |
dereuromark/cakephp-tools | src/Utility/Language.php | Language._matchLanguage | protected static function _matchLanguage($a, $b) {
$a = explode('-', strtolower($a));
$b = explode('-', strtolower($b));
for ($i = 0, $n = min(count($a), count($b)); $i < $n; $i++) {
if ($a[$i] !== $b[$i]) {
break;
}
}
return $i === 0 ? 0 : (float)$i / count($a);
} | php | protected static function _matchLanguage($a, $b) {
$a = explode('-', strtolower($a));
$b = explode('-', strtolower($b));
for ($i = 0, $n = min(count($a), count($b)); $i < $n; $i++) {
if ($a[$i] !== $b[$i]) {
break;
}
}
return $i === 0 ? 0 : (float)$i / count($a);
} | [
"protected",
"static",
"function",
"_matchLanguage",
"(",
"$",
"a",
",",
"$",
"b",
")",
"{",
"$",
"a",
"=",
"explode",
"(",
"'-'",
",",
"strtolower",
"(",
"$",
"a",
")",
")",
";",
"$",
"b",
"=",
"explode",
"(",
"'-'",
",",
"strtolower",
"(",
"$",... | Compare two language tags and distinguish the degree of matching
@param string $a
@param string $b
@return float | [
"Compare",
"two",
"language",
"tags",
"and",
"distinguish",
"the",
"degree",
"of",
"matching"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Language.php#L157-L167 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.inArray | public static function inArray($needle, $haystack) {
$strict = !is_numeric($needle);
return in_array((string)$needle, $haystack, $strict);
} | php | public static function inArray($needle, $haystack) {
$strict = !is_numeric($needle);
return in_array((string)$needle, $haystack, $strict);
} | [
"public",
"static",
"function",
"inArray",
"(",
"$",
"needle",
",",
"$",
"haystack",
")",
"{",
"$",
"strict",
"=",
"!",
"is_numeric",
"(",
"$",
"needle",
")",
";",
"return",
"in_array",
"(",
"(",
"string",
")",
"$",
"needle",
",",
"$",
"haystack",
",... | Clean implementation of inArray to avoid false positives.
in_array itself has some PHP flaws regarding cross-type comparison:
- in_array('50x', array(40, 50, 60)) would be true!
- in_array(50, array('40x', '50x', '60x')) would be true!
@param mixed $needle
@param array $haystack
@return bool Success | [
"Clean",
"implementation",
"of",
"inArray",
"to",
"avoid",
"false",
"positives",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L51-L54 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.getClientIp | public static function getClientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} elseif (!$safe && env('HTTP_CLIENT_IP')) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
return trim($ipaddr);
} | php | public static function getClientIp($safe = true) {
if (!$safe && env('HTTP_X_FORWARDED_FOR')) {
$ipaddr = preg_replace('/(?:,.*)/', '', env('HTTP_X_FORWARDED_FOR'));
} elseif (!$safe && env('HTTP_CLIENT_IP')) {
$ipaddr = env('HTTP_CLIENT_IP');
} else {
$ipaddr = env('REMOTE_ADDR');
}
return trim($ipaddr);
} | [
"public",
"static",
"function",
"getClientIp",
"(",
"$",
"safe",
"=",
"true",
")",
"{",
"if",
"(",
"!",
"$",
"safe",
"&&",
"env",
"(",
"'HTTP_X_FORWARDED_FOR'",
")",
")",
"{",
"$",
"ipaddr",
"=",
"preg_replace",
"(",
"'/(?:,.*)/'",
",",
"''",
",",
"env... | Get the current IP address.
@param bool $safe
@return string IP address | [
"Get",
"the",
"current",
"IP",
"address",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L161-L170 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.getReferer | public static function getReferer($full = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
if (empty($ref)) {
return $ref;
}
if ($full) {
$ref = Router::url($ref, $full);
}
return $ref;
} | php | public static function getReferer($full = false) {
$ref = env('HTTP_REFERER');
$forwarded = env('HTTP_X_FORWARDED_HOST');
if ($forwarded) {
$ref = $forwarded;
}
if (empty($ref)) {
return $ref;
}
if ($full) {
$ref = Router::url($ref, $full);
}
return $ref;
} | [
"public",
"static",
"function",
"getReferer",
"(",
"$",
"full",
"=",
"false",
")",
"{",
"$",
"ref",
"=",
"env",
"(",
"'HTTP_REFERER'",
")",
";",
"$",
"forwarded",
"=",
"env",
"(",
"'HTTP_X_FORWARDED_HOST'",
")",
";",
"if",
"(",
"$",
"forwarded",
")",
"... | Get the current referrer if available.
@param bool $full (defaults to false and leaves the url untouched)
@return string referer (local or foreign) | [
"Get",
"the",
"current",
"referrer",
"if",
"available",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L178-L191 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.getHeaderFromUrl | public static function getHeaderFromUrl($url) {
// @codingStandardsIgnoreStart
$url = @parse_url($url);
// @codingStandardsIgnoreEnd
if (empty($url)) {
return false;
}
$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
$path = (isset($url['path'])) ? $url['path'] : '';
if (empty($path)) {
$path = '/';
}
$path .= (isset($url['query'])) ? "?$url[query]" : '';
$defaults = [
'http' => [
'header' => "Accept: text/html\r\n" .
"Connection: Close\r\n" .
"User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
]
];
stream_context_get_default($defaults);
if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
$url = "$url[scheme]://$url[host]$url[port]$path";
$headers = get_headers($url);
if (is_array($headers)) {
return $headers;
}
}
return false;
} | php | public static function getHeaderFromUrl($url) {
// @codingStandardsIgnoreStart
$url = @parse_url($url);
// @codingStandardsIgnoreEnd
if (empty($url)) {
return false;
}
$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? '' : (':' . (int)$url['port']);
$path = (isset($url['path'])) ? $url['path'] : '';
if (empty($path)) {
$path = '/';
}
$path .= (isset($url['query'])) ? "?$url[query]" : '';
$defaults = [
'http' => [
'header' => "Accept: text/html\r\n" .
"Connection: Close\r\n" .
"User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64)\r\n",
]
];
stream_context_get_default($defaults);
if (isset($url['host']) && $url['host'] !== gethostbyname($url['host'])) {
$url = "$url[scheme]://$url[host]$url[port]$path";
$headers = get_headers($url);
if (is_array($headers)) {
return $headers;
}
}
return false;
} | [
"public",
"static",
"function",
"getHeaderFromUrl",
"(",
"$",
"url",
")",
"{",
"// @codingStandardsIgnoreStart",
"$",
"url",
"=",
"@",
"parse_url",
"(",
"$",
"url",
")",
";",
"// @codingStandardsIgnoreEnd",
"if",
"(",
"empty",
"(",
"$",
"url",
")",
")",
"{",... | Parse headers from a specific URL content.
@param string $url
@return mixed array of headers or FALSE on failure | [
"Parse",
"headers",
"from",
"a",
"specific",
"URL",
"content",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L292-L327 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.typeCast | public static function typeCast($value, $type) {
switch ($type) {
case 'int':
$value = (int)$value;
break;
case 'float':
$value = (float)$value;
break;
case 'double':
$value = (double)$value;
break;
case 'array':
$value = (array)$value;
break;
case 'bool':
$value = (bool)$value;
break;
case 'string':
$value = (string)$value;
break;
default:
return null;
}
return $value;
} | php | public static function typeCast($value, $type) {
switch ($type) {
case 'int':
$value = (int)$value;
break;
case 'float':
$value = (float)$value;
break;
case 'double':
$value = (double)$value;
break;
case 'array':
$value = (array)$value;
break;
case 'bool':
$value = (bool)$value;
break;
case 'string':
$value = (string)$value;
break;
default:
return null;
}
return $value;
} | [
"public",
"static",
"function",
"typeCast",
"(",
"$",
"value",
",",
"$",
"type",
")",
"{",
"switch",
"(",
"$",
"type",
")",
"{",
"case",
"'int'",
":",
"$",
"value",
"=",
"(",
"int",
")",
"$",
"value",
";",
"break",
";",
"case",
"'float'",
":",
"$... | Convenience function for automatic casting in form methods etc.
@param mixed $value
@param string $type
@return mixed Safe value for DB query, or NULL if type was not a valid one | [
"Convenience",
"function",
"for",
"automatic",
"casting",
"in",
"form",
"methods",
"etc",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L413-L437 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.arrayFlatten | public static function arrayFlatten($array, $preserveKeys = false) {
if ($preserveKeys) {
return static::_arrayFlatten($array);
}
if (!$array) {
return [];
}
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, static::arrayFlatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
} | php | public static function arrayFlatten($array, $preserveKeys = false) {
if ($preserveKeys) {
return static::_arrayFlatten($array);
}
if (!$array) {
return [];
}
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, static::arrayFlatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
} | [
"public",
"static",
"function",
"arrayFlatten",
"(",
"$",
"array",
",",
"$",
"preserveKeys",
"=",
"false",
")",
"{",
"if",
"(",
"$",
"preserveKeys",
")",
"{",
"return",
"static",
"::",
"_arrayFlatten",
"(",
"$",
"array",
")",
";",
"}",
"if",
"(",
"!",
... | Force-flattens an array.
Careful with this method. It can lose information.
The keys will not be changed, thus possibly overwrite each other.
//TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
@param array $array Array to flatten
@param bool $preserveKeys
@return array | [
"Force",
"-",
"flattens",
"an",
"array",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L612-L628 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility._arrayFlatten | protected static function _arrayFlatten($a, $f = []) {
if (!$a) {
return [];
}
foreach ($a as $k => $v) {
if (is_array($v)) {
$f = static::_arrayFlatten($v, $f);
} else {
$f[$k] = $v;
}
}
return $f;
} | php | protected static function _arrayFlatten($a, $f = []) {
if (!$a) {
return [];
}
foreach ($a as $k => $v) {
if (is_array($v)) {
$f = static::_arrayFlatten($v, $f);
} else {
$f[$k] = $v;
}
}
return $f;
} | [
"protected",
"static",
"function",
"_arrayFlatten",
"(",
"$",
"a",
",",
"$",
"f",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"!",
"$",
"a",
")",
"{",
"return",
"[",
"]",
";",
"}",
"foreach",
"(",
"$",
"a",
"as",
"$",
"k",
"=>",
"$",
"v",
")",
"{",... | Force-flattens an array and preserves the keys.
Careful with this method. It can lose information.
The keys will not be changed, thus possibly overwrite each other.
//TODO: check if it can be replace by Hash::flatten() or Utility::flatten().
@param array $a
@param array $f
@return array | [
"Force",
"-",
"flattens",
"an",
"array",
"and",
"preserves",
"the",
"keys",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L642-L654 | train |
dereuromark/cakephp-tools | src/Utility/Utility.php | Utility.prettyJson | public static function prettyJson($json, $indString = "\t") {
// Replace any escaped \" marks so we don't get tripped up on quotemarks_counter
$tokens = preg_split('|([\{\}\]\[,])|', str_replace('\"', '~~PRETTY_JSON_QUOTEMARK~~', $json), -1, PREG_SPLIT_DELIM_CAPTURE);
$indent = 0;
$result = '';
$quotemarksCounter = 0;
$nextTokenUsePrefix = true;
foreach ($tokens as $token) {
$quotemarksCounter = $quotemarksCounter + (count(explode('"', $token)) - 1);
if ($token === '') {
continue;
}
if ($nextTokenUsePrefix) {
$prefix = str_repeat($indString, $indent);
} else {
$prefix = null;
}
// Determine if the quote marks are open or closed
if ($quotemarksCounter & 1) {
// odd - thus quotemarks open
$nextTokenUsePrefix = false;
$newLine = null;
} else {
// even - thus quotemarks closed
$nextTokenUsePrefix = true;
$newLine = "\n";
}
if ($token === '{' || $token === '[') {
$indent++;
$result .= $token . $newLine;
} elseif ($token === '}' || $token === ']') {
$indent--;
if ($indent >= 0) {
$prefix = str_repeat($indString, $indent);
}
if ($nextTokenUsePrefix) {
$result .= $newLine . $prefix . $token;
} else {
$result .= $newLine . $token;
}
} elseif ($token === ',') {
$result .= $token . $newLine;
} else {
$result .= $prefix . $token;
}
}
return str_replace('~~PRETTY_JSON_QUOTEMARK~~', '\"', $result);
} | php | public static function prettyJson($json, $indString = "\t") {
// Replace any escaped \" marks so we don't get tripped up on quotemarks_counter
$tokens = preg_split('|([\{\}\]\[,])|', str_replace('\"', '~~PRETTY_JSON_QUOTEMARK~~', $json), -1, PREG_SPLIT_DELIM_CAPTURE);
$indent = 0;
$result = '';
$quotemarksCounter = 0;
$nextTokenUsePrefix = true;
foreach ($tokens as $token) {
$quotemarksCounter = $quotemarksCounter + (count(explode('"', $token)) - 1);
if ($token === '') {
continue;
}
if ($nextTokenUsePrefix) {
$prefix = str_repeat($indString, $indent);
} else {
$prefix = null;
}
// Determine if the quote marks are open or closed
if ($quotemarksCounter & 1) {
// odd - thus quotemarks open
$nextTokenUsePrefix = false;
$newLine = null;
} else {
// even - thus quotemarks closed
$nextTokenUsePrefix = true;
$newLine = "\n";
}
if ($token === '{' || $token === '[') {
$indent++;
$result .= $token . $newLine;
} elseif ($token === '}' || $token === ']') {
$indent--;
if ($indent >= 0) {
$prefix = str_repeat($indString, $indent);
}
if ($nextTokenUsePrefix) {
$result .= $newLine . $prefix . $token;
} else {
$result .= $newLine . $token;
}
} elseif ($token === ',') {
$result .= $token . $newLine;
} else {
$result .= $prefix . $token;
}
}
return str_replace('~~PRETTY_JSON_QUOTEMARK~~', '\"', $result);
} | [
"public",
"static",
"function",
"prettyJson",
"(",
"$",
"json",
",",
"$",
"indString",
"=",
"\"\\t\"",
")",
"{",
"// Replace any escaped \\\" marks so we don't get tripped up on quotemarks_counter",
"$",
"tokens",
"=",
"preg_split",
"(",
"'|([\\{\\}\\]\\[,])|'",
",",
"str... | Returns pretty JSON
@link https://github.com/ndejong/pretty_json/blob/master/pretty_json.php
@param string $json The original JSON string
@param string $indString The string to indent with
@return string
@deprecated Now there is a JSON_PRETTY_PRINT option available on json_encode() | [
"Returns",
"pretty",
"JSON"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Utility/Utility.php#L729-L784 | train |
dereuromark/cakephp-tools | src/Model/Table/TokensTable.php | TokensTable.newKey | public function newKey($type, $key = null, $uid = null, $content = null) {
if (!$type) {
return false;
}
if (!$key) {
$key = $this->generateKey($this->defaultLength);
$keyLength = $this->defaultLength;
} else {
$keyLength = mb_strlen($key);
}
if (is_array($content)) {
$content = json_encode($content);
}
$data = [
'type' => $type,
'user_id' => $uid,
'content' => (string)$content,
'key' => $key,
];
$entity = $this->newEntity($data);
$max = 99;
while (!$this->save($entity)) {
$entity['key'] = $this->generateKey($keyLength);
$max--;
if ($max === 0) {
return false;
}
}
return $entity['key'];
} | php | public function newKey($type, $key = null, $uid = null, $content = null) {
if (!$type) {
return false;
}
if (!$key) {
$key = $this->generateKey($this->defaultLength);
$keyLength = $this->defaultLength;
} else {
$keyLength = mb_strlen($key);
}
if (is_array($content)) {
$content = json_encode($content);
}
$data = [
'type' => $type,
'user_id' => $uid,
'content' => (string)$content,
'key' => $key,
];
$entity = $this->newEntity($data);
$max = 99;
while (!$this->save($entity)) {
$entity['key'] = $this->generateKey($keyLength);
$max--;
if ($max === 0) {
return false;
}
}
return $entity['key'];
} | [
"public",
"function",
"newKey",
"(",
"$",
"type",
",",
"$",
"key",
"=",
"null",
",",
"$",
"uid",
"=",
"null",
",",
"$",
"content",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"type",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"$",... | Stores new key in DB
Checks if this key is already used (should be unique in table)
@param string $type Type: necessary
@param string|null $key Key: optional key, otherwise a key will be generated
@param mixed|null $uid Uid: optional (if used, only this user can use this key)
@param string|array|null $content Content: up to 255 characters of content may be added (optional)
@return string|bool Key on success, boolean false otherwise | [
"Stores",
"new",
"key",
"in",
"DB"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/TokensTable.php#L86-L120 | train |
dereuromark/cakephp-tools | src/Model/Table/TokensTable.php | TokensTable.stats | public function stats() {
$keys = [];
$keys['unused_valid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 0, $this->getAlias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['used_valid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 1, $this->getAlias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['unused_invalid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 0, $this->getAlias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['used_invalid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 1, $this->getAlias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$types = $this->find('all', ['conditions' => [], 'fields' => ['DISTINCT type']])->toArray();
$keys['types'] = !empty($types) ? Hash::extract($types, '{n}.type') : [];
return $keys;
} | php | public function stats() {
$keys = [];
$keys['unused_valid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 0, $this->getAlias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['used_valid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 1, $this->getAlias() . '.created >=' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['unused_invalid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 0, $this->getAlias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$keys['used_invalid'] = $this->find('count', ['conditions' => [$this->getAlias() . '.used' => 1, $this->getAlias() . '.created <' => date(FORMAT_DB_DATETIME, time() - $this->validity)]]);
$types = $this->find('all', ['conditions' => [], 'fields' => ['DISTINCT type']])->toArray();
$keys['types'] = !empty($types) ? Hash::extract($types, '{n}.type') : [];
return $keys;
} | [
"public",
"function",
"stats",
"(",
")",
"{",
"$",
"keys",
"=",
"[",
"]",
";",
"$",
"keys",
"[",
"'unused_valid'",
"]",
"=",
"$",
"this",
"->",
"find",
"(",
"'count'",
",",
"[",
"'conditions'",
"=>",
"[",
"$",
"this",
"->",
"getAlias",
"(",
")",
... | Get admin stats
@return array | [
"Get",
"admin",
"stats"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/TokensTable.php#L206-L217 | train |
dereuromark/cakephp-tools | src/Model/Table/TokensTable.php | TokensTable.generateKey | public function generateKey($length = null) {
if (!$length) {
$length = $this->defaultLength;
}
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
$function = 'random_bytes';
} elseif (extension_loaded('openssl')) {
$function = 'openssl_random_pseudo_bytes';
} else {
trigger_error('Not secure', E_USER_DEPRECATED);
return Random::pwd($length);
}
$value = bin2hex($function($length / 2));
if (strlen($value) !== $length) {
$value = str_pad($value, $length, '0');
}
return $value;
} | php | public function generateKey($length = null) {
if (!$length) {
$length = $this->defaultLength;
}
if (version_compare(PHP_VERSION, '7.0.0') >= 0) {
$function = 'random_bytes';
} elseif (extension_loaded('openssl')) {
$function = 'openssl_random_pseudo_bytes';
} else {
trigger_error('Not secure', E_USER_DEPRECATED);
return Random::pwd($length);
}
$value = bin2hex($function($length / 2));
if (strlen($value) !== $length) {
$value = str_pad($value, $length, '0');
}
return $value;
} | [
"public",
"function",
"generateKey",
"(",
"$",
"length",
"=",
"null",
")",
"{",
"if",
"(",
"!",
"$",
"length",
")",
"{",
"$",
"length",
"=",
"$",
"this",
"->",
"defaultLength",
";",
"}",
"if",
"(",
"version_compare",
"(",
"PHP_VERSION",
",",
"'7.0.0'",... | Generator of secure random tokens.
Note that it is best to use an even number for the length.
@param int|null $length (defaults to defaultLength)
@return string Key | [
"Generator",
"of",
"secure",
"random",
"tokens",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Table/TokensTable.php#L227-L246 | train |
dereuromark/cakephp-tools | src/View/Helper/TextHelper.php | TextHelper.minimizeUrl | public function minimizeUrl($url, $max = null, array $options = []) {
// check if there is nothing to do
if (empty($url) || mb_strlen($url) <= (int)$max) {
return $url;
}
// http:// etc has not to be displayed, so
$url = Utility::stripProtocol($url);
// cut the parameters
if (mb_strpos($url, '/') !== false) {
$url = strtok($url, '/');
}
// return if the url is short enough
if (mb_strlen($url) <= (int)$max) {
return $url;
}
// otherwise cut a part in the middle (but only if long enough!)
// TODO: more dynamically
$placeholder = CHAR_HELLIP;
if (!empty($options['placeholder'])) {
$placeholder = $options['placeholder'];
}
$end = mb_substr($url, -5, 5);
$front = mb_substr($url, 0, (int)$max - 8);
return $front . $placeholder . $end;
} | php | public function minimizeUrl($url, $max = null, array $options = []) {
// check if there is nothing to do
if (empty($url) || mb_strlen($url) <= (int)$max) {
return $url;
}
// http:// etc has not to be displayed, so
$url = Utility::stripProtocol($url);
// cut the parameters
if (mb_strpos($url, '/') !== false) {
$url = strtok($url, '/');
}
// return if the url is short enough
if (mb_strlen($url) <= (int)$max) {
return $url;
}
// otherwise cut a part in the middle (but only if long enough!)
// TODO: more dynamically
$placeholder = CHAR_HELLIP;
if (!empty($options['placeholder'])) {
$placeholder = $options['placeholder'];
}
$end = mb_substr($url, -5, 5);
$front = mb_substr($url, 0, (int)$max - 8);
return $front . $placeholder . $end;
} | [
"public",
"function",
"minimizeUrl",
"(",
"$",
"url",
",",
"$",
"max",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"// check if there is nothing to do",
"if",
"(",
"empty",
"(",
"$",
"url",
")",
"||",
"mb_strlen",
"(",
"$",
"url... | Minimizes the given URL to a maximum length
@param string $url the url
@param int|null $max the maximum length
@param array $options
- placeholder
@return string the manipulated url (+ eventuell ...) | [
"Minimizes",
"the",
"given",
"URL",
"to",
"a",
"maximum",
"length"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TextHelper.php#L58-L83 | train |
dereuromark/cakephp-tools | src/Model/Behavior/TypographicBehavior.php | TypographicBehavior.updateTypography | public function updateTypography($dryRun = false) {
$options = ['limit' => 100, 'offset' => 0];
$count = 0;
while ($records = $this->getTable()->find('all', $options)->toArray()) {
foreach ($records as $record) {
$changed = false;
foreach ($this->_config['fields'] as $field) {
if (empty($record[$field])) {
continue;
}
$tmp = $this->_prepareInput($record[$field]);
if ($tmp == $record[$field]) {
continue;
}
$record[$field] = $tmp;
$changed = true;
}
if ($changed) {
if (!$dryRun) {
$this->getTable()->save($record, ['validate' => false]);
}
$count++;
}
}
$options['offset'] += 100;
}
return $count;
} | php | public function updateTypography($dryRun = false) {
$options = ['limit' => 100, 'offset' => 0];
$count = 0;
while ($records = $this->getTable()->find('all', $options)->toArray()) {
foreach ($records as $record) {
$changed = false;
foreach ($this->_config['fields'] as $field) {
if (empty($record[$field])) {
continue;
}
$tmp = $this->_prepareInput($record[$field]);
if ($tmp == $record[$field]) {
continue;
}
$record[$field] = $tmp;
$changed = true;
}
if ($changed) {
if (!$dryRun) {
$this->getTable()->save($record, ['validate' => false]);
}
$count++;
}
}
$options['offset'] += 100;
}
return $count;
} | [
"public",
"function",
"updateTypography",
"(",
"$",
"dryRun",
"=",
"false",
")",
"{",
"$",
"options",
"=",
"[",
"'limit'",
"=>",
"100",
",",
"'offset'",
"=>",
"0",
"]",
";",
"$",
"count",
"=",
"0",
";",
"while",
"(",
"$",
"records",
"=",
"$",
"this... | Run the behavior over all records of this model
This is useful if you attach it after some records have already been saved without it.
@param bool $dryRun
@return int count Number of affected/changed records | [
"Run",
"the",
"behavior",
"over",
"all",
"records",
"of",
"this",
"model",
"This",
"is",
"useful",
"if",
"you",
"attach",
"it",
"after",
"some",
"records",
"have",
"already",
"been",
"saved",
"without",
"it",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/TypographicBehavior.php#L157-L184 | train |
dereuromark/cakephp-tools | src/Model/Behavior/TypographicBehavior.php | TypographicBehavior.process | public function process(ArrayAccess $data) {
foreach ($this->_config['fields'] as $field) {
if (!empty($data[$field])) {
$data[$field] = $this->_prepareInput($data[$field]);
}
}
} | php | public function process(ArrayAccess $data) {
foreach ($this->_config['fields'] as $field) {
if (!empty($data[$field])) {
$data[$field] = $this->_prepareInput($data[$field]);
}
}
} | [
"public",
"function",
"process",
"(",
"ArrayAccess",
"$",
"data",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"_config",
"[",
"'fields'",
"]",
"as",
"$",
"field",
")",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"data",
"[",
"$",
"field",
"]",
")",
... | Run before a model is saved
@param \ArrayAccess $data
@return void | [
"Run",
"before",
"a",
"model",
"is",
"saved"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/TypographicBehavior.php#L192-L198 | train |
dereuromark/cakephp-tools | src/Model/Behavior/StringBehavior.php | StringBehavior._process | public function _process($val, $map) {
foreach ($map as $m => $arg) {
if (is_numeric($m)) {
$m = $arg;
$arg = null;
}
if ($arg !== null) {
$ret = call_user_func($m, $val, $arg);
} else {
$ret = call_user_func($m, $val);
}
if ($ret !== false) {
$val = $ret;
}
}
return $val;
} | php | public function _process($val, $map) {
foreach ($map as $m => $arg) {
if (is_numeric($m)) {
$m = $arg;
$arg = null;
}
if ($arg !== null) {
$ret = call_user_func($m, $val, $arg);
} else {
$ret = call_user_func($m, $val);
}
if ($ret !== false) {
$val = $ret;
}
}
return $val;
} | [
"public",
"function",
"_process",
"(",
"$",
"val",
",",
"$",
"map",
")",
"{",
"foreach",
"(",
"$",
"map",
"as",
"$",
"m",
"=>",
"$",
"arg",
")",
"{",
"if",
"(",
"is_numeric",
"(",
"$",
"m",
")",
")",
"{",
"$",
"m",
"=",
"$",
"arg",
";",
"$"... | Process val via map
@param string $val
@param array $map
@return string | [
"Process",
"val",
"via",
"map"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/Model/Behavior/StringBehavior.php#L119-L137 | train |
dereuromark/cakephp-tools | src/View/Helper/HtmlHelper.php | HtmlHelper.imageFromBlob | public function imageFromBlob($content, array $options = []) {
$options += ['type' => 'png'];
$mimeType = 'image/' . $options['type'];
$text = 'data:' . $mimeType . ';base64,' . base64_encode($content);
return $this->formatTemplate('image', [
'url' => $text,
'attrs' => $this->templater()->formatAttributes($options, ['block', 'link'])
]);
} | php | public function imageFromBlob($content, array $options = []) {
$options += ['type' => 'png'];
$mimeType = 'image/' . $options['type'];
$text = 'data:' . $mimeType . ';base64,' . base64_encode($content);
return $this->formatTemplate('image', [
'url' => $text,
'attrs' => $this->templater()->formatAttributes($options, ['block', 'link'])
]);
} | [
"public",
"function",
"imageFromBlob",
"(",
"$",
"content",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"$",
"options",
"+=",
"[",
"'type'",
"=>",
"'png'",
"]",
";",
"$",
"mimeType",
"=",
"'image/'",
".",
"$",
"options",
"[",
"'type'",
"]"... | Display image tag from blob content.
Enhancement for HtmlHelper. Defaults to png image
Options:
- type: png, gif, jpg, ...
@param string $content Data in binary form
@param array $options Attributes
@return string HTML image tag | [
"Display",
"image",
"tag",
"from",
"blob",
"content",
".",
"Enhancement",
"for",
"HtmlHelper",
".",
"Defaults",
"to",
"png",
"image"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/HtmlHelper.php#L38-L48 | train |
dereuromark/cakephp-tools | src/View/Helper/HtmlHelper.php | HtmlHelper.linkReset | public function linkReset($title, $url = null, array $options = []) {
if (is_array($url)) {
$url += ['prefix' => false, 'plugin' => false];
}
return parent::link($title, $url, $options);
} | php | public function linkReset($title, $url = null, array $options = []) {
if (is_array($url)) {
$url += ['prefix' => false, 'plugin' => false];
}
return parent::link($title, $url, $options);
} | [
"public",
"function",
"linkReset",
"(",
"$",
"title",
",",
"$",
"url",
"=",
"null",
",",
"array",
"$",
"options",
"=",
"[",
"]",
")",
"{",
"if",
"(",
"is_array",
"(",
"$",
"url",
")",
")",
"{",
"$",
"url",
"+=",
"[",
"'prefix'",
"=>",
"false",
... | Creates a reset HTML link.
The prefix and plugin params are resetting to default false.
### Options
- `escape` Set to false to disable escaping of title and attributes.
- `escapeTitle` Set to false to disable escaping of title. Takes precedence
over value of `escape`)
- `confirm` JavaScript confirmation message.
@param string $title The content to be wrapped by <a> tags.
@param string|array|null $url URL or array of URL parameters, or
external URL (starts with http://)
@param array $options Array of options and HTML attributes.
@return string An `<a />` element. | [
"Creates",
"a",
"reset",
"HTML",
"link",
".",
"The",
"prefix",
"and",
"plugin",
"params",
"are",
"resetting",
"to",
"default",
"false",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/HtmlHelper.php#L67-L72 | train |
dereuromark/cakephp-tools | src/View/Helper/TreeHelper.php | TreeHelper._suffix | protected function _suffix($reset = false) {
static $_splitCount = 0;
static $_splitCounter = 0;
if ($reset) {
$_splitCount = 0;
$_splitCounter = 0;
}
extract($this->_config);
if ($splitDepth || $splitCount) {
if (!$splitDepth) {
$_splitCount = $totalNodes / $splitCount;
$rounded = (int)$_splitCount;
if ($rounded < $_splitCount) {
$_splitCount = $rounded + 1;
}
} elseif ($depth == $splitDepth - 1) {
$total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
if ($total) {
$_splitCounter = 0;
$_splitCount = $total / $splitCount;
$rounded = (int)$_splitCount;
if ($rounded < $_splitCount) {
$_splitCount = $rounded + 1;
}
}
}
if (!$splitDepth || $depth == $splitDepth) {
$_splitCounter++;
if ($type && ($_splitCounter % $_splitCount) === 0 && !$lastChild) {
unset($this->_config['callback']);
return '</' . $type . '><' . $type . '>';
}
}
}
} | php | protected function _suffix($reset = false) {
static $_splitCount = 0;
static $_splitCounter = 0;
if ($reset) {
$_splitCount = 0;
$_splitCounter = 0;
}
extract($this->_config);
if ($splitDepth || $splitCount) {
if (!$splitDepth) {
$_splitCount = $totalNodes / $splitCount;
$rounded = (int)$_splitCount;
if ($rounded < $_splitCount) {
$_splitCount = $rounded + 1;
}
} elseif ($depth == $splitDepth - 1) {
$total = $numberOfDirectChildren ? $numberOfDirectChildren : $numberOfTotalChildren;
if ($total) {
$_splitCounter = 0;
$_splitCount = $total / $splitCount;
$rounded = (int)$_splitCount;
if ($rounded < $_splitCount) {
$_splitCount = $rounded + 1;
}
}
}
if (!$splitDepth || $depth == $splitDepth) {
$_splitCounter++;
if ($type && ($_splitCounter % $_splitCount) === 0 && !$lastChild) {
unset($this->_config['callback']);
return '</' . $type . '><' . $type . '>';
}
}
}
} | [
"protected",
"function",
"_suffix",
"(",
"$",
"reset",
"=",
"false",
")",
"{",
"static",
"$",
"_splitCount",
"=",
"0",
";",
"static",
"$",
"_splitCounter",
"=",
"0",
";",
"if",
"(",
"$",
"reset",
")",
"{",
"$",
"_splitCount",
"=",
"0",
";",
"$",
"_... | Suffix method.
Used to close and reopen a ul/ol to allow easier listings
@param bool $reset Reset
@return string | [
"Suffix",
"method",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TreeHelper.php#L432-L468 | train |
dereuromark/cakephp-tools | src/View/Helper/TreeHelper.php | TreeHelper._attributes | protected function _attributes($rType, array $elementData = [], $clear = true) {
extract($this->_config);
if ($rType === $type) {
$attributes = $this->_typeAttributes;
if ($clear) {
$this->_typeAttributes = $this->_typeAttributesNext;
$this->_typeAttributesNext = [];
}
} else {
$attributes = $this->_itemAttributes;
$this->_itemAttributes = [];
if ($clear) {
$this->_itemAttributes = [];
}
}
if ($rType === $itemType && $elementData['activePathElement']) {
if ($elementData['activePathElement'] === true) {
$attributes['class'][] = $autoPath[2];
} else {
$attributes['class'][] = $elementData['activePathElement'];
}
}
if (!$attributes) {
return '';
}
foreach ($attributes as $type => $values) {
foreach ($values as $key => $val) {
if (is_array($val)) {
$attributes[$type][$key] = '';
foreach ($val as $vKey => $v) {
$attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
}
$attributes[$type][$key] = implode(';', $attributes[$type][$key]);
}
if (is_string($key)) {
$attributes[$type][$key] = $key . ':' . $val . ';';
}
}
$attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
}
return ' ' . implode(' ', $attributes);
} | php | protected function _attributes($rType, array $elementData = [], $clear = true) {
extract($this->_config);
if ($rType === $type) {
$attributes = $this->_typeAttributes;
if ($clear) {
$this->_typeAttributes = $this->_typeAttributesNext;
$this->_typeAttributesNext = [];
}
} else {
$attributes = $this->_itemAttributes;
$this->_itemAttributes = [];
if ($clear) {
$this->_itemAttributes = [];
}
}
if ($rType === $itemType && $elementData['activePathElement']) {
if ($elementData['activePathElement'] === true) {
$attributes['class'][] = $autoPath[2];
} else {
$attributes['class'][] = $elementData['activePathElement'];
}
}
if (!$attributes) {
return '';
}
foreach ($attributes as $type => $values) {
foreach ($values as $key => $val) {
if (is_array($val)) {
$attributes[$type][$key] = '';
foreach ($val as $vKey => $v) {
$attributes[$type][$key][$vKey] .= $vKey . ':' . $v;
}
$attributes[$type][$key] = implode(';', $attributes[$type][$key]);
}
if (is_string($key)) {
$attributes[$type][$key] = $key . ':' . $val . ';';
}
}
$attributes[$type] = $type . '="' . implode(' ', $attributes[$type]) . '"';
}
return ' ' . implode(' ', $attributes);
} | [
"protected",
"function",
"_attributes",
"(",
"$",
"rType",
",",
"array",
"$",
"elementData",
"=",
"[",
"]",
",",
"$",
"clear",
"=",
"true",
")",
"{",
"extract",
"(",
"$",
"this",
"->",
"_config",
")",
";",
"if",
"(",
"$",
"rType",
"===",
"$",
"type... | Attributes function.
Logic to apply styles to tags.
@param string $rType rType
@param array $elementData Element data
@param bool $clear Clear
@return string | [
"Attributes",
"function",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TreeHelper.php#L480-L522 | train |
dereuromark/cakephp-tools | src/View/Helper/TimelineHelper.php | TimelineHelper.finalize | public function finalize($return = false, array $scriptOptions = []) {
$settings = $this->getConfig();
$timelineId = $settings['id'];
$data = $this->_format($this->_items);
$current = '';
if ($settings['current']) {
$dateString = date('Y-m-d H:i:s', time());
$current = 'timeline.setCurrentTime(' . $this->_date($dateString) . ');';
}
unset($settings['id']);
unset($settings['current']);
$options = $this->_options($settings);
$script = <<<JS
var timeline;
var data;
var options;
// Called when the Visualization API is loaded.
function drawVisualization() {
// Create a JSON data table
data = $data
options = $options
// Instantiate our timeline object.
timeline = new links.Timeline(document.getElementById('$timelineId'));
// Draw our timeline with the created data and options
timeline.draw(data, options);
$current
}
drawVisualization();
JS;
if ($return) {
return $script;
}
$this->_buffer($script, $scriptOptions);
} | php | public function finalize($return = false, array $scriptOptions = []) {
$settings = $this->getConfig();
$timelineId = $settings['id'];
$data = $this->_format($this->_items);
$current = '';
if ($settings['current']) {
$dateString = date('Y-m-d H:i:s', time());
$current = 'timeline.setCurrentTime(' . $this->_date($dateString) . ');';
}
unset($settings['id']);
unset($settings['current']);
$options = $this->_options($settings);
$script = <<<JS
var timeline;
var data;
var options;
// Called when the Visualization API is loaded.
function drawVisualization() {
// Create a JSON data table
data = $data
options = $options
// Instantiate our timeline object.
timeline = new links.Timeline(document.getElementById('$timelineId'));
// Draw our timeline with the created data and options
timeline.draw(data, options);
$current
}
drawVisualization();
JS;
if ($return) {
return $script;
}
$this->_buffer($script, $scriptOptions);
} | [
"public",
"function",
"finalize",
"(",
"$",
"return",
"=",
"false",
",",
"array",
"$",
"scriptOptions",
"=",
"[",
"]",
")",
"{",
"$",
"settings",
"=",
"$",
"this",
"->",
"getConfig",
"(",
")",
";",
"$",
"timelineId",
"=",
"$",
"settings",
"[",
"'id'"... | Finalize the timeline and write the javascript to the buffer.
Make sure that your view does also output the buffer at some place!
@param bool $return If the output should be returned instead
@param array $scriptOptions
@return null|string Javascript if $return is true | [
"Finalize",
"the",
"timeline",
"and",
"write",
"the",
"javascript",
"to",
"the",
"buffer",
".",
"Make",
"sure",
"that",
"your",
"view",
"does",
"also",
"output",
"the",
"buffer",
"at",
"some",
"place!"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TimelineHelper.php#L108-L147 | train |
dereuromark/cakephp-tools | src/View/Helper/TimelineHelper.php | TimelineHelper._options | protected function _options($options) {
$e = [];
foreach ($options as $option => $value) {
if ($value === null) {
continue;
}
if (is_string($value)) {
$value = '\'' . $value . '\'';
} elseif (is_object($value)) { // Datetime?
$value = $this->_date($value);
} elseif (is_bool($value)) {
$value = $value ? 'true' : 'false';
} else {
$value = str_replace('\'', '\\\'', $value);
}
$e[] = '\'' . $option . '\': ' . $value;
}
$string = '{' . PHP_EOL . "\t" . implode(',' . PHP_EOL . "\t", $e) . PHP_EOL . '}';
return $string;
} | php | protected function _options($options) {
$e = [];
foreach ($options as $option => $value) {
if ($value === null) {
continue;
}
if (is_string($value)) {
$value = '\'' . $value . '\'';
} elseif (is_object($value)) { // Datetime?
$value = $this->_date($value);
} elseif (is_bool($value)) {
$value = $value ? 'true' : 'false';
} else {
$value = str_replace('\'', '\\\'', $value);
}
$e[] = '\'' . $option . '\': ' . $value;
}
$string = '{' . PHP_EOL . "\t" . implode(',' . PHP_EOL . "\t", $e) . PHP_EOL . '}';
return $string;
} | [
"protected",
"function",
"_options",
"(",
"$",
"options",
")",
"{",
"$",
"e",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"options",
"as",
"$",
"option",
"=>",
"$",
"value",
")",
"{",
"if",
"(",
"$",
"value",
"===",
"null",
")",
"{",
"continue",
";"... | Format options to JS code
@param array $options
@return string | [
"Format",
"options",
"to",
"JS",
"code"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TimelineHelper.php#L155-L174 | train |
dereuromark/cakephp-tools | src/View/Helper/TimelineHelper.php | TimelineHelper._format | protected function _format($items) {
$e = [];
foreach ($items as $item) {
$tmp = [];
foreach ($item as $key => $row) {
switch ($key) {
case 'editable':
$tmp[] = $row ? 'true' : 'false';
break;
case 'start':
case 'end':
$tmp[] = '\'' . $key . '\': ' . $this->_date($row);
break;
default:
$tmp[] = '\'' . $key . '\': \'' . str_replace('\'', '\\\'', $row) . '\'';
}
}
$e[] = '{' . implode(',' . PHP_EOL, $tmp) . '}';
}
$string = '[' . implode(',' . PHP_EOL, $e) . '];';
return $string;
} | php | protected function _format($items) {
$e = [];
foreach ($items as $item) {
$tmp = [];
foreach ($item as $key => $row) {
switch ($key) {
case 'editable':
$tmp[] = $row ? 'true' : 'false';
break;
case 'start':
case 'end':
$tmp[] = '\'' . $key . '\': ' . $this->_date($row);
break;
default:
$tmp[] = '\'' . $key . '\': \'' . str_replace('\'', '\\\'', $row) . '\'';
}
}
$e[] = '{' . implode(',' . PHP_EOL, $tmp) . '}';
}
$string = '[' . implode(',' . PHP_EOL, $e) . '];';
return $string;
} | [
"protected",
"function",
"_format",
"(",
"$",
"items",
")",
"{",
"$",
"e",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"items",
"as",
"$",
"item",
")",
"{",
"$",
"tmp",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"item",
"as",
"$",
"key",
"=>",
"$"... | Format items to JS code
@see \Tools\View\Helper\TimelineHelper::addItem()
@param array $items
@return string | [
"Format",
"items",
"to",
"JS",
"code"
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TimelineHelper.php#L183-L204 | train |
dereuromark/cakephp-tools | src/View/Helper/TimelineHelper.php | TimelineHelper._date | protected function _date($date = null) {
if ($date === null || !$date instanceof \DateTimeInterface) {
return '';
}
$datePieces = [];
$datePieces[] = $date->format('Y');
// JavaScript uses 0-indexed months, so we need to subtract 1 month from PHP's output
$datePieces[] = (int)($date->format('m')) - 1;
$datePieces[] = (int)$date->format('d');
$datePieces[] = (int)$date->format('H');
$datePieces[] = (int)$date->format('i');
$datePieces[] = (int)$date->format('s');
return 'new Date(' . implode(', ', $datePieces) . ')';
} | php | protected function _date($date = null) {
if ($date === null || !$date instanceof \DateTimeInterface) {
return '';
}
$datePieces = [];
$datePieces[] = $date->format('Y');
// JavaScript uses 0-indexed months, so we need to subtract 1 month from PHP's output
$datePieces[] = (int)($date->format('m')) - 1;
$datePieces[] = (int)$date->format('d');
$datePieces[] = (int)$date->format('H');
$datePieces[] = (int)$date->format('i');
$datePieces[] = (int)$date->format('s');
return 'new Date(' . implode(', ', $datePieces) . ')';
} | [
"protected",
"function",
"_date",
"(",
"$",
"date",
"=",
"null",
")",
"{",
"if",
"(",
"$",
"date",
"===",
"null",
"||",
"!",
"$",
"date",
"instanceof",
"\\",
"DateTimeInterface",
")",
"{",
"return",
"''",
";",
"}",
"$",
"datePieces",
"=",
"[",
"]",
... | Format date to JS code.
@param \DateTimeInterface|null $date
@return string | [
"Format",
"date",
"to",
"JS",
"code",
"."
] | 6242560dc77e0d9e5ebb4325ead05565e7a361a3 | https://github.com/dereuromark/cakephp-tools/blob/6242560dc77e0d9e5ebb4325ead05565e7a361a3/src/View/Helper/TimelineHelper.php#L212-L226 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.