code
stringlengths
15
9.96M
docstring
stringlengths
1
10.1k
func_name
stringlengths
1
124
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
6
186
url
stringlengths
50
236
license
stringclasses
4 values
public function incrementDate($startDate, $years = 0, $months = 0, $days = 0, $timezone = null) { $dateTime = $startDate; if (!is_object($startDate)) { $dateTime = new CakeDateTime($startDate); if ($timezone) { $dateTime = $dateTime->setTimezone($this->safeCreateDateTimeZone($timezone)); } } $startingTimeStamp = $dateTime->getTimestamp(); // Get the month value of the given date: $monthString = date('Y-m', $startingTimeStamp); // Create a date string corresponding to the 1st of the give month, // making it safe for monthly/yearly calculations: $safeDateString = "first day of $monthString"; // offset is wrong $months++; // Increment date by given month/year increments: $incrementedDateString = "$safeDateString $months month $years year"; $newTimeStamp = strtotime($incrementedDateString) + $days * DAY; $newDate = static::createFromFormat('U', (string)$newTimeStamp); return $newDate; }
Handles month/year increment calculations in a safe way, avoiding the pitfall of "fuzzy" month units. @param mixed $startDate Either a date string or a DateTime object @param int $years Years to increment/decrement @param int $months Months to increment/decrement @param int $days Days @param \DateTimeZone|string|null $timezone Timezone string or DateTimeZone object @return object DateTime with incremented/decremented month/year values.
incrementDate
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function localDate(?string $dateString, ?string $format = null, array $options = []) { $defaults = [ 'default' => '-----', 'timezone' => null, 'language' => 'en', 'oclock' => null, ]; $options += $defaults; /** @var \DateTimeZone|string|null $timezone */ $timezone = $options['timezone']; if ($timezone === null && $dateString && strlen($dateString) === 10) { $timezone = static::_getDefaultOutputTimezone(); } if ($dateString === null) { $dateString = time(); } if ($timezone) { $timezone = static::safeCreateDateTimeZone($timezone); } $date = new self($dateString, $timezone); if ($format === null) { if (is_int($dateString) || str_contains($dateString, ' ')) { $format = 'd.m.Y, H:i'; } else { $format = 'd.m.Y'; } } $date = static::formatLocalized($date, $format, $options['language']); if ($options['oclock']) { if (strpos($format, 'H:i') !== false) { $date .= ' ' . __d('tools', 'o\'clock'); } } return $date; }
Outputs Date(time) Sting nicely formatted (+ localized!) Options: - timezone: User's timezone - default: Default string (defaults to "-----") - oclock: Set to true to append oclock string @param string|null $dateString @param string|null $format Format (YYYY-MM-DD, DD.MM.YYYY) @param array<string, mixed> $options @return string
localDate
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function niceTime($time) { $pos = strpos($time, ' '); if ($pos !== false) { $time = substr($time, $pos + 1); } return substr($time, 0, 5); }
Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss @param string $time @return string Time in format hh:mm
niceTime
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
protected static function _getDefaultOutputTimezone() { return Configure::read('App.defaultOutputTimezone') ?: date_default_timezone_get(); }
@return string
_getDefaultOutputTimezone
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function fuzzy($timestamp) { // Determine the difference in seconds $offset = abs(time() - $timestamp); return static::fuzzyFromOffset($offset, $timestamp <= time()); }
Returns the difference between a time and now in a "fuzzy" way. Note that unlike [span], the "local" timestamp will always be the current time. Displaying a fuzzy time instead of a date is usually faster to read and understand. $span = fuzzy(time() - 10); // "moments ago" $span = fuzzy(time() + 20); // "in moments" @param int $timestamp "remote" timestamp @return string
fuzzy
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function fuzzyFromOffset($offset, $past = null) { if ($offset <= MINUTE) { $span = 'moments'; } elseif ($offset < (MINUTE * 20)) { $span = 'a few minutes'; } elseif ($offset < HOUR) { $span = 'less than an hour'; } elseif ($offset < (HOUR * 4)) { $span = 'a couple of hours'; } elseif ($offset < DAY) { $span = 'less than a day'; } elseif ($offset < (DAY * 2)) { $span = 'about a day'; } elseif ($offset < (DAY * 4)) { $span = 'a couple of days'; } elseif ($offset < WEEK) { $span = 'less than a week'; } elseif ($offset < (WEEK * 2)) { $span = 'about a week'; } elseif ($offset < MONTH) { $span = 'less than a month'; } elseif ($offset < (MONTH * 2)) { $span = 'about a month'; } elseif ($offset < (MONTH * 4)) { $span = 'a couple of months'; } elseif ($offset < YEAR) { $span = 'less than a year'; } elseif ($offset < (YEAR * 2)) { $span = 'about a year'; } elseif ($offset < (YEAR * 4)) { $span = 'a couple of years'; } elseif ($offset < (YEAR * 8)) { $span = 'a few years'; } elseif ($offset < (YEAR * 12)) { $span = 'about a decade'; } elseif ($offset < (YEAR * 24)) { $span = 'a couple of decades'; } elseif ($offset < (YEAR * 64)) { $span = 'several decades'; } else { $span = 'a long time'; } if ($past === true) { // This is in the past return __d('tools', '{0} ago', __d('tools', $span)); } if ($past === false) { // This in the future return __d('tools', 'in {0}', __d('tools', $span)); } if ($past !== null) { // Custom translation return __d('tools', $past, __d('tools', $span)); } return __d('tools', $span); }
@param int $offset in seconds @param string|bool|null $past (defaults to null: return plain text) - new: if not boolean but a string use this as translating text @return string text (i18n!)
fuzzyFromOffset
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function standardToDecimalTime($value) { $base = (int)$value; $tmp = $value - $base; $tmp *= 100; $tmp *= 1 / 60; $value = $base + $tmp; return $value; }
Hours, minutes e.g. 9.3 => 9.5 @param int $value @return float
standardToDecimalTime
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function decimalToStandardTime($value, $pad = null, $decPoint = '.') { $base = (int)$value; $tmp = $value - $base; $tmp /= 1 / 60; $tmp /= 100; $value = $base + $tmp; if ($pad === null) { return (string)$value; } return number_format($value, $pad, $decPoint, ''); }
Hours, minutes e.g. 9.5 => 9.3 with pad=2: 9.30 @param float|int $value @param int|null $pad @param string $decPoint @return string
decimalToStandardTime
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function duration($duration, $format = '%h:%I:%S') { if (!$duration instanceof DateInterval) { $d1 = new NativeDateTime(); $d2 = new NativeDateTime(); $d2 = $d2->add(new DateInterval('PT' . $duration . 'S')); $duration = $d2->diff($d1); } if (stripos($format, 'd') === false && $duration->d) { $duration->h += $duration->d * 24; } if (stripos($format, 'h') === false && $duration->h) { $duration->i += $duration->h * 60; } if (stripos($format, 'i') === false && $duration->i) { $duration->s += $duration->m * 60; } return $duration->format($format); }
Returns nicely formatted duration difference as string like 2:30 (H:MM) or 2:30:06 (H:MM:SS) etc. Note that the more than days is currently not supported accurately. E.g. for days and hours set format to: $d:$H @param \DateInterval|int $duration Duration in seconds or as DateInterval object @param string $format Defaults to hours, minutes and seconds @return string Time
duration
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function buildTime($duration, $format = 'H:MM:SS') { if ($duration instanceof DateInterval) { $m = $duration->invert ? -1 : 1; $duration = ($duration->y * YEAR) + ($duration->m * MONTH) + ($duration->d * DAY) + ($duration->h * HOUR) + ($duration->i * MINUTE) + $duration->s; $duration *= $m; } if ($duration < 0) { $duration = abs($duration); $isNegative = true; } $minutes = $duration % HOUR; $hours = ($duration - $minutes) / HOUR; $res = []; if (strpos($format, 'H') !== false) { $res[] = (int)$hours . ':' . static::pad((string)($minutes / MINUTE)); } else { $res[] = (int)($minutes / MINUTE); } if (strpos($format, 'SS') !== false) { $seconds = $duration % MINUTE; $res[] = static::pad((string)$seconds); } $res = implode(':', $res); if (!empty($isNegative)) { $res = '-' . $res; } return $res; }
Returns nicely formatted duration difference as string like 2:30 or 2:30:06. Note that the more than hours is currently not supported. Note that duration with DateInterval supports only values < month with accuracy, as it approximates month as "30". @deprecated Use duration() instead? @param \DateInterval|int $duration Duration in seconds or as DateInterval object @param string $format Defaults to hours and minutes @return string Time
buildTime
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public static function pad($value, $length = 2, $string = '0') { return str_pad((string)(int)$value, $length, $string, STR_PAD_LEFT); }
@param string $value @param int $length @param string $string @return string
pad
php
dereuromark/cakephp-tools
src/I18n/DateTime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/I18n/DateTime.php
MIT
public function __construct(array $config = []) { $config += (array)Configure::read('Error'); $config += [ 'logger' => ErrorLogger::class, ]; parent::__construct($config); }
Constructor @param array $config The options for error handling.
__construct
php
dereuromark/cakephp-tools
src/Error/ExceptionTrap.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Error/ExceptionTrap.php
MIT
public function __construct(ErrorExceptionTrap|array $exceptionTrap = []) { if (is_array($exceptionTrap)) { $exceptionTrap += (array)Configure::read('Error'); } parent::__construct($exceptionTrap); $this->exceptionTrap = new ExceptionTrap($this->getConfig()); }
@param \Cake\Error\ExceptionTrap|array $exceptionTrap The error handler instance or config array.
__construct
php
dereuromark/cakephp-tools
src/Error/Middleware/ErrorHandlerMiddleware.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Error/Middleware/ErrorHandlerMiddleware.php
MIT
public function all(bool $coreHasPrecedence = false) { if ($coreHasPrecedence) { return $this->_mimeTypes += $this->_mimeTypesExt; } return $this->_mimeTypesExt += $this->_mimeTypes; }
Get all mime types that are supported right now @param bool $coreHasPrecedence @return array<string, array<string>|string>
all
php
dereuromark/cakephp-tools
src/Utility/MimeTypes.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/MimeTypes.php
MIT
public function getMimeType( string $alias, bool $primaryOnly = true, bool $coreHasPrecedence = false, ) { if (!$this->_mimeTypesTmp) { $this->_mimeTypesTmp = $this->all($coreHasPrecedence); } if (!isset($this->_mimeTypesTmp[$alias])) { return null; } $mimeType = $this->_mimeTypesTmp[$alias]; if ($primaryOnly && is_array($mimeType)) { $mimeType = array_shift($mimeType); } return $mimeType; }
Returns the primary mime type definition for an alias/extension. e.g `getMimeType('pdf'); // returns 'application/pdf'` @param string $alias the content type alias to map @param bool $primaryOnly @param bool $coreHasPrecedence @return array<string>|string|null Mapped mime type or null if $alias is not mapped
getMimeType
php
dereuromark/cakephp-tools
src/Utility/MimeTypes.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/MimeTypes.php
MIT
public static function findFirstMatch(array $accepted, array $available = [], bool $onlyTwoLetters = false) { $matches = static::findMatches($accepted, $available, $onlyTwoLetters); if (!$matches) { return null; } $match = array_shift($matches); if (!$match) { return null; } return array_shift($match); }
Compares two parsed arrays of language tags and find the matches @param array<string> $accepted @param array $available @param bool $onlyTwoLetters @return string|null
findFirstMatch
php
dereuromark/cakephp-tools
src/Utility/Language.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Language.php
MIT
protected static function _matchLanguage(string $a, string $b, bool $onlyTwoLetters = false) { $a = explode('-', strtolower($a)); $b = explode('-', strtolower($b)); if ($onlyTwoLetters) { return $a[0] === $b[0] ? 1 : 0; } 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); }
Compare two language tags and distinguish the degree of matching @param string $a @param string $b @param bool $onlyTwoLetters @return float
_matchLanguage
php
dereuromark/cakephp-tools
src/Utility/Language.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Language.php
MIT
public static function numberOfChars($text, array $options = []) { $text = str_replace(["\r", "\n", "\t", ' '], '', $text); $count = mb_strlen($text); return $count; }
Count chars in a text. Options: - 'whitespace': If whitespace should be counted, as well, defaults to false @param string $text @param array<string, mixed> $options @return int
numberOfChars
php
dereuromark/cakephp-tools
src/Utility/Text.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Text.php
MIT
public static function abbreviate($text, $length = 20, $ending = '...') { if (mb_strlen($text) <= $length) { return $text; } return rtrim(mb_substr($text, 0, (int)round(($length - 3) / 2))) . $ending . ltrim(mb_substr($text, (($length - 3) / 2) * -1)); }
Return an abbreviated string, with characters in the middle of the excessively long string replaced by $ending. @param string $text The original string. @param int $length The length at which to abbreviate. @param string $ending Defaults to ... @return string The abbreviated string, if longer than $length.
abbreviate
php
dereuromark/cakephp-tools
src/Utility/Text.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Text.php
MIT
public static function calcElapsedTime($start, $end, $precision = 8) { $elapsed = $end - $start; return round($elapsed, $precision); }
Returns microtime as float value (to be subtracted right away) @param float $start @param float $end @param int $precision @return float
calcElapsedTime
php
dereuromark/cakephp-tools
src/Utility/Clock.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Clock.php
MIT
public function __construct(array $options = []) { if (class_exists(MimeType::class)) { $mimeType = new MimeType(); $coreMimeTypes = $this->invokeProperty($mimeType, 'mimeTypes'); } else { $response = new Response(); $coreMimeTypes = $this->invokeProperty($response, '_mimeTypes'); } $this->_mimeTypesCore = $coreMimeTypes; }
Override constructor @param array<string, mixed> $options
__construct
php
dereuromark/cakephp-tools
src/Utility/Mime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Mime.php
MIT
public function mimeTypes($coreHasPrecedence = false) { if ($coreHasPrecedence) { return $this->_mimeTypesCore += $this->_mimeTypesExt; } return $this->_mimeTypesExt += $this->_mimeTypesCore; }
Get all mime types that are supported right now @param bool $coreHasPrecedence @return array
mimeTypes
php
dereuromark/cakephp-tools
src/Utility/Mime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Mime.php
MIT
public function getMimeTypeByAlias( string $alias, bool $primaryOnly = true, bool $coreHasPrecedence = false, ) { if (!$this->_mimeTypesTmp) { $this->_mimeTypesTmp = $this->mimeTypes($coreHasPrecedence); } if (!isset($this->_mimeTypesTmp[$alias])) { return null; } $mimeType = $this->_mimeTypesTmp[$alias]; if ($primaryOnly && is_array($mimeType)) { $mimeType = array_shift($mimeType); } return $mimeType; }
Returns the primary mime type definition for an alias/extension. e.g `getMimeType('pdf'); // returns 'application/pdf'` @param string $alias the content type alias to map @param bool $primaryOnly @param bool $coreHasPrecedence @return array|string|null Mapped mime type or null if $alias is not mapped
getMimeTypeByAlias
php
dereuromark/cakephp-tools
src/Utility/Mime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Mime.php
MIT
public static function _detectMimeType($file) { if (!function_exists('finfo_open')) { //throw new InternalErrorException('finfo_open() required - please enable'); } // Treat non local files differently $pattern = '~^https?://~i'; if (preg_match($pattern, $file)) { // @codingStandardsIgnoreStart $headers = @get_headers($file); // @codingStandardsIgnoreEnd if (!$headers || !preg_match("|\b200\b|", $headers[0])) { return ''; } foreach ($headers as $header) { if (strpos($header, 'Content-Type:') === 0) { return trim(substr($header, 13)); } } return ''; } if (!is_file($file)) { return ''; } $finfo = finfo_open(FILEINFO_MIME); $mimetype = finfo_file($finfo, $file); $pos = strpos($mimetype, ';'); if ($pos !== false) { $mimetype = substr($mimetype, 0, $pos); } if ($mimetype) { return $mimetype; } $extension = static::_getExtension($file); /** @var string|null $mimeType */ $mimeType = static::getMimeTypeByAlias($extension); if ($mimeType) { return $mimeType; } return 'application/octet-stream'; }
Utility::getMimeType() @param string $file File @return string Mime type
_detectMimeType
php
dereuromark/cakephp-tools
src/Utility/Mime.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Mime.php
MIT
public static function typeCast($value, $type) { switch ($type) { case 'int': $value = (int)$value; break; case 'float': $value = (float)$value; break; case 'double': $value = (float)$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; }
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
typeCast
php
dereuromark/cakephp-tools
src/Utility/Utility.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Utility.php
MIT
public static function deep($function, $value) { $callable = 'self::' . $function; /** * @var callable&non-falsy-string $callable * @var callable $function */ $value = is_array($value) ? array_map($callable, $value) : $function($value); return $value; }
Main deep method @param string $function Callable or function name. @param mixed $value @return array|string
deep
php
dereuromark/cakephp-tools
src/Utility/Utility.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Utility.php
MIT
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; }
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
_arrayFlatten
php
dereuromark/cakephp-tools
src/Utility/Utility.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Utility/Utility.php
MIT
public function __construct(Table $table, array $config = []) { $defaults = $this->_defaultConfig; $configureDefaults = Configure::read('Passwordable'); if ($configureDefaults) { $defaults = $configureDefaults + $defaults; } $config += $defaults; parent::__construct($table, $config); }
Adding validation rules also adds and merges config settings (direct + configure) @param \Cake\ORM\Table $table @param array $config
__construct
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options) { $formField = $this->_config['formField']; $formFieldRepeat = $this->_config['formFieldRepeat']; $formFieldCurrent = $this->_config['formFieldCurrent']; if (!isset($options['fields']) && $this->_config['forceFieldList']) { $options['fields'] = array_keys((array)$data); } if (isset($options['fields'])) { if (!in_array($formField, $options['fields'])) { $options['fields'][] = $formField; } if (!in_array($formFieldRepeat, $options['fields'])) { $options['fields'][] = $formFieldRepeat; } if (!in_array($formFieldCurrent, $options['fields'])) { $options['fields'][] = $formFieldCurrent; } } // Make sure fields are set and validation rules are triggered - prevents tempering of form data if (!isset($data[$formField])) { $data[$formField] = ''; } if ($this->_config['confirm'] && !isset($data[$formFieldRepeat])) { $data[$formFieldRepeat] = ''; } if ($this->_config['current'] && !isset($data[$formFieldCurrent])) { $data[$formFieldCurrent] = ''; } // Check if we need to trigger any validation rules if (!$this->_config['require']) { $new = !empty($data[$formField]) || !empty($data[$formFieldRepeat]); // Make sure we trigger validation if allowEmpty is set but we have the password field set if ($new) { if ($this->_config['confirm'] && empty($data[$formFieldRepeat])) { //$entity->errors($formFieldRepeat, __d('tools', 'valErrPwdNotMatch')); } } } }
Preparing the data @param \Cake\Event\EventInterface $event @param \ArrayObject $data @param \ArrayObject $options @return void
beforeMarshal
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation) { $formField = $this->_config['formField']; $formFieldRepeat = $this->_config['formFieldRepeat']; $formFieldCurrent = $this->_config['formFieldCurrent']; // Check if we need to trigger any validation rules if (!$this->_config['require']) { $current = $entity->get($formFieldCurrent); $new = $entity->get($formField) || $entity->get($formFieldRepeat); if (!$new && !$current) { $entity->unset($formField); if ($this->_config['confirm']) { $entity->unset($formFieldRepeat); } if ($this->_config['current']) { $entity->unset($formFieldCurrent); } return; } } }
Preparing the data @param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @param string $operation @return void
beforeRules
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function beforeSave(EventInterface $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->unset($formField); if ($this->_config['confirm']) { $formFieldRepeat = $this->_config['formFieldRepeat']; $entity->unset($formFieldRepeat); } if ($this->_config['current']) { $formFieldCurrent = $this->_config['formFieldCurrent']; $entity->unset($formFieldCurrent); } } else { // To help mitigate timing-based user enumeration attacks. $PasswordHasher->hash(''); } }
Hashing the password and whitelisting @param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @throws \RuntimeException @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function needsPasswordRehash($hash) { $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']); if (!method_exists($PasswordHasher, 'needsRehash')) { return false; } return $PasswordHasher->needsRehash($hash); }
Checks if the PasswordHasher class supports this and if so, whether the password needs to be rehashed or not. This is mainly supported by Tools.Modern (using Bcrypt) yet. @param string $hash Currently hashed password. @return bool Success
needsPasswordRehash
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function validateCurrentPwd($pwd, $context) { $uid = null; if (!empty($context['data'][$this->_table->getPrimaryKey()])) { $uid = $context['data'][$this->_table->getPrimaryKey()]; } else { trigger_error('No user id given'); return false; } return $this->_validateSameHash($pwd, $context); }
If not implemented in Table class Note: requires the used Auth component to be App::uses() loaded. It also reqires the same Auth setup as in your AppController's beforeFilter(). So if you set up any special passwordHasher or auth type, you need to provide those with the settings passed to the behavior: 'passwordHasher' => array( 'className' => 'Simple', 'hashType' => 'sha256' ) @param string $pwd @param array $context @return bool Success
validateCurrentPwd
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function validateNotSameHash($data, $context) { $field = $this->_config['field']; /** @var string $primaryKey */ $primaryKey = $this->_table->getPrimaryKey(); if (empty($context['data'][$primaryKey])) { return true; } $primaryKeyValue = $context['data'][$primaryKey]; $value = $context['data'][$context['field']]; $dbValue = $this->_table->find()->where([$this->_table->getAlias() . '.' . $primaryKey => $primaryKeyValue])->first(); if (!$dbValue) { return true; } $dbValue = $dbValue[$field]; if (!$dbValue) { return true; } $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']); return !$PasswordHasher->check($value, $dbValue); }
If not implemented in Table class @param string $data @param array $context @return bool Success
validateNotSameHash
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
protected function _validateSameHash($pwd, $context) { $field = $this->_config['field']; /** @var string $primaryKey */ $primaryKey = $this->_table->getPrimaryKey(); $primaryKeyValue = $context['data'][$primaryKey]; $dbValue = $this->_table->find()->where([$this->_table->getAlias() . '.' . $primaryKey => $primaryKeyValue])->first(); if (!$dbValue) { return false; } $dbValue = $dbValue[$field]; if (!$dbValue && $pwd) { return false; } $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']); return $PasswordHasher->check($pwd, $dbValue); }
@param string $pwd @param array $context @return bool Success
_validateSameHash
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
protected function _getPasswordHasher($hasher, array $options = []) { if ($this->_passwordHasher) { return $this->_passwordHasher; } $config = []; if (is_string($hasher)) { $class = $hasher; } else { $class = $hasher['className']; $config = $hasher; unset($config['className']); } $config['className'] = $class; $cost = !empty($this->_config['hashCost']) ? $this->_config['hashCost'] : 10; $config['cost'] = $cost; $config += $options; return $this->_passwordHasher = PasswordHasherFactory::build($config); }
@param array<string, mixed>|string $hasher Name or options array. @param array<string, mixed> $options @return \Tools\Auth\AbstractPasswordHasher
_getPasswordHasher
php
dereuromark/cakephp-tools
src/Model/Behavior/PasswordableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/PasswordableBehavior.php
MIT
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, $primary) { $query->formatResults(function (CollectionInterface $results) { return $results->map(function ($row) { if (!$row instanceof Entity) { return $row; } $this->decodeItems($row); return $row; }); }); }
Decode the fields on after find @param \Cake\Event\EventInterface $event @param \Cake\ORM\Query\SelectQuery $query @param \ArrayObject $options @param bool $primary @return void
beforeFind
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
protected function _getMappedFields() { $usedFields = $this->_config['fields']; $mappedFields = $this->_config['map']; if (!$mappedFields) { $mappedFields = $usedFields; } $fields = []; foreach ($mappedFields as $index => $map) { if (!$map || $map == $usedFields[$index]) { $fields[$usedFields[$index]] = $usedFields[$index]; continue; } $fields[$map] = $usedFields[$index]; } return $fields; }
@return array
_getMappedFields
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
public function _toParam($val) { $res = []; foreach ($val as $key => $v) { $res[] = $key . $this->_config['keyValueSeparator'] . $v; } return implode($this->_config['separator'], $res); }
array() => param1:value1|param2:value2|... @param array $val @return string
_toParam
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
public function _toList($val) { return implode($this->_config['separator'], $val); }
array() => value1|value2|value3|... @param array<string> $val @return string
_toList
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
public function _fromList($val) { $separator = $this->_config['separator']; $leftBound = $this->_config['leftBound']; $rightBound = $this->_config['rightBound']; return (array)Text::tokenize($val, $separator, $leftBound, $rightBound); }
@param string $val @return array<string>
_fromList
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
public function isEncoded($str) { $this->decoded = $this->_decode($str); if ($this->decoded !== false) { return true; } return false; }
Checks if string is encoded array/object @param string $str String to check @return bool
isEncoded
php
dereuromark/cakephp-tools
src/Model/Behavior/JsonableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/JsonableBehavior.php
MIT
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { $this->_entity = clone $entity; }
@param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/AfterSaveBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/AfterSaveBehavior.php
MIT
public function getEntityBeforeSave() { if (!$this->_entity) { throw new LogicException('You need to successfully save first - including beforeSave() callback fired.'); } return $this->_entity; }
@throws \LogicException @return \Cake\Datasource\EntityInterface
getEntityBeforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/AfterSaveBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/AfterSaveBehavior.php
MIT
public function __construct(Table $table, array $config = []) { $defaults = $this->_defaultConfig; $configureDefaults = Configure::read('Reset'); if ($configureDefaults) { $defaults = $configureDefaults + $defaults; } $config += $defaults; parent::__construct($table, $config); }
Adding validation rules also adds and merges config settings (direct + configure) @param \Cake\ORM\Table $table @param array $config
__construct
php
dereuromark/cakephp-tools
src/Model/Behavior/ResetBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ResetBehavior.php
MIT
public function beforeFind(EventInterface $event, SelectQuery $query, ArrayObject $options, $primary) { $query->formatResults(function (ResultSetInterface $results) { return $results->map(function ($row) { $this->processItems($row, 'output'); return $row; }); }); }
Decode the fields on after find @param \Cake\Event\EventInterface $event @param \Cake\ORM\Query\SelectQuery $query @param \ArrayObject $options @param bool $primary @return void
beforeFind
php
dereuromark/cakephp-tools
src/Model/Behavior/StringBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/StringBehavior.php
MIT
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { $this->processItems($entity, 'input'); }
Saves all fields that do not belong to the current Model into 'with' helper model. @param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/StringBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/StringBehavior.php
MIT
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; }
Process val via map @param string $val @param array $map @return string
_process
php
dereuromark/cakephp-tools
src/Model/Behavior/StringBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/StringBehavior.php
MIT
public function __construct(Table $table, array $config = []) { parent::__construct($table, $config); if (!$this->_config['message']) { $this->_config['message'] = __d('tools', 'Please confirm the checkbox'); } }
@param \Cake\ORM\Table $table @param array $config
__construct
php
dereuromark/cakephp-tools
src/Model/Behavior/ConfirmableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ConfirmableBehavior.php
MIT
public function buildValidator(EventInterface $event, Validator $validator, $name) { $this->build($validator, $name); }
@param \Cake\Event\EventInterface $event @param \Cake\Validation\Validator $validator @param string $name @return void
buildValidator
php
dereuromark/cakephp-tools
src/Model/Behavior/ConfirmableBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ConfirmableBehavior.php
MIT
public function encodeBitmaskDataRaw(ArrayObject $data) { $field = $this->_config['field']; $mappedField = $this->_config['mappedField']; if (!$mappedField) { $mappedField = $field; } $default = $this->_getDefault($field); if (!isset($data[$mappedField])) { return; } $data[$field] = $this->encodeBitmask($data[$mappedField], $default); }
@param \ArrayObject $data @return void
encodeBitmaskDataRaw
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function encodeBitmaskData(EntityInterface $entity) { $field = $this->_config['field']; $mappedField = $this->_config['mappedField']; if (!$mappedField) { $mappedField = $field; } $default = $this->_getDefault($field); if ($entity->get($mappedField) === null) { return; } $entity->set($field, $this->encodeBitmask($entity->get($mappedField), $default)); if ($field !== $mappedField) { $entity->unset($mappedField); } }
@param \Cake\Datasource\EntityInterface $entity @return void
encodeBitmaskData
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function isBit($bits) { $bits = (array)$bits; $bitmask = $this->encodeBitmask($bits); $field = $this->_config['field']; return [$this->_table->getAlias() . '.' . $field => $bitmask]; }
@param array<int>|int $bits @return array SQL snippet.
isBit
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function isNotBit($bits) { return ['NOT' => $this->isBit($bits)]; }
@param array<int>|int $bits @return array SQL snippet.
isNotBit
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function containsBit($bits) { return $this->_containsBit($bits); }
@param array<int>|int $bits @return array SQL snippet.
containsBit
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function containsNotBit($bits) { return $this->_containsBit($bits, false); }
@param array<int>|int $bits @return array SQL snippet.
containsNotBit
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
protected function _containsBit($bits, $contain = true) { $bits = (array)$bits; $bitmask = $this->encodeBitmask($bits); $field = $this->_config['field']; if ($bitmask === null) { $emptyValue = $this->_getDefaultValue($field); return [$this->_table->getAlias() . '.' . $field . ' IS' => $emptyValue]; } $contain = $contain ? ' & %s = %s' : ' & %s != %s'; $contain = sprintf($contain, (string)$bitmask, (string)$bitmask); // Hack for Postgres for now $connection = $this->_table->getConnection(); $config = $connection->config(); if ((str_contains($config['driver'], 'Postgres'))) { return ['("' . $this->_table->getAlias() . '"."' . $field . '"' . $contain . ')']; } return ['(' . $this->_table->getAlias() . '.' . $field . $contain . ')']; }
@param array<int>|int $bits @param bool $contain @return array SQL snippet.
_containsBit
php
dereuromark/cakephp-tools
src/Model/Behavior/BitmaskedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/BitmaskedBehavior.php
MIT
public function afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options) { $field = $this->getConfig('field'); $value = $entity->get($field); if (!$value) { return; } $conditions = $this->buildConditions($entity); $order = $this->getConfig('findOrder'); if ($order === null) { $order = []; if ($this->_table->getSchema()->getColumn('modified')) { $order['modified'] = 'DESC'; } } /** @var \Cake\Datasource\EntityInterface|null $entity */ $entity = $this->_table->find()->where($conditions)->orderBy($order)->first(); if (!$entity) { // This should be caught with a validation rule if at least one "primary" must exist return; } $entity->set($field, true); $this->_table->saveOrFail($entity); }
@param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @return void
afterDelete
php
dereuromark/cakephp-tools
src/Model/Behavior/ToggleBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ToggleBehavior.php
MIT
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { $field = $this->getConfig('field'); if ($entity->isNew() && !$entity->get($field)) { if (!$this->getCurrent($entity)) { $entity->set($field, true); } } if ($this->_config['on'] !== 'beforeSave') { return; } $value = $entity->get($this->getConfig('field')); if (!$value && !$this->getCurrent($entity)) { // This should be caught with a validation rule as this is not normal behavior throw new LogicException(); } $this->removeFromOthers($entity); }
@param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @throws \LogicException @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/ToggleBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ToggleBehavior.php
MIT
public function afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { if ($this->_config['on'] !== 'afterSave') { return; } if (!$entity->isDirty($this->getConfig('field'))) { return; } $value = $entity->get($this->getConfig('field')); if (!$value && !$this->getCurrent($entity)) { // This should be caught with a validation rule as this is not normal behavior throw new LogicException(); } $this->removeFromOthers($entity); }
@param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @throws \LogicException @return void
afterSave
php
dereuromark/cakephp-tools
src/Model/Behavior/ToggleBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ToggleBehavior.php
MIT
protected function getCurrent(EntityInterface $entity) { $conditions = $this->buildConditions($entity); /** @var \Cake\Datasource\EntityInterface|null */ return $this->_table->find() ->where($conditions) ->first(); }
@param \Cake\Datasource\EntityInterface $entity @return \Cake\Datasource\EntityInterface|null
getCurrent
php
dereuromark/cakephp-tools
src/Model/Behavior/ToggleBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/ToggleBehavior.php
MIT
public function beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options) { if ($this->_config['before'] === 'marshal') { $this->process($data); } return true; }
@param \Cake\Event\EventInterface $event @param \ArrayObject $data @param \ArrayObject $options @return bool
beforeMarshal
php
dereuromark/cakephp-tools
src/Model/Behavior/TypographicBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/TypographicBehavior.php
MIT
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { if ($this->_config['before'] === 'save') { $this->process($entity); } }
@param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/TypographicBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/TypographicBehavior.php
MIT
public function process(ArrayAccess $data) { foreach ($this->_config['fields'] as $field) { if (!empty($data[$field])) { $data[$field] = $this->_prepareInput($data[$field]); } } }
Run before a model is saved @param \ArrayAccess $data @return void
process
php
dereuromark/cakephp-tools
src/Model/Behavior/TypographicBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/TypographicBehavior.php
MIT
protected function _prepareInput($string) { $map = $this->_map['in']; if ($this->_config['mergeQuotes']) { foreach ($map as $key => $val) { $map[$key] = $this->_config['mergeQuotes']; } } return str_replace(array_keys($map), array_values($map), $string); }
@param string $string @return string cleanedInput
_prepareInput
php
dereuromark/cakephp-tools
src/Model/Behavior/TypographicBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/TypographicBehavior.php
MIT
public function beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, $operation) { if ($this->_config['on'] === 'beforeRules') { $this->slug($entity); } }
SluggedBehavior::beforeRules() @param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @param string $operation @return void
beforeRules
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
public function beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options) { if ($this->_config['on'] === 'beforeSave') { $this->slug($entity); } }
SluggedBehavior::beforeSave() @param \Cake\Event\EventInterface $event @param \Cake\Datasource\EntityInterface $entity @param \ArrayObject $options @return void
beforeSave
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
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; }
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
needsSlugUpdate
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
protected function _multiSlug(EntityInterface $entity) { $label = $this->getConfig('label'); $field = current($label); $fields = (array)$entity->get($field); $locales = []; 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); } } $locales[$locale] = $res; } $entity->set($this->getConfig('slugField'), $locales); }
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
_multiSlug
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
protected function _pregReplace($pattern, $replace, $string) { return (string)preg_replace($pattern, $replace, $string); }
Wrapper for preg replace taking care of encoding @param array|string $pattern @param array|string $replace @param string $string @return string
_pregReplace
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
protected function _regex($mode) { $return = '\x00-\x1f\x26\x3c\x7f-\x9f\x{fffe}-\x{ffff}'; if ($mode === 'display') { return $return; } $return .= preg_quote(' \'"/?<>.$/:;?@=+&%\#,', '@'); if ($mode === 'url') { return $return; } $return .= ''; if ($mode === 'class') { return $return; } if ($mode === 'id') { return '\x{0000}-\x{002f}\x{003a}-\x{0040}\x{005b}-\x{005e}\x{0060}\x{007b}-\x{007e}\x{00a0}-\x{00b6}' . '\x{00b8}-\x{00bf}\x{00d7}\x{00f7}\x{0132}-\x{0133}\x{013f}-\x{0140}\x{0149}\x{017f}\x{01c4}-\x{01cc}' . '\x{01f1}-\x{01f3}\x{01f6}-\x{01f9}\x{0218}-\x{024f}\x{02a9}-\x{02ba}\x{02c2}-\x{02cf}\x{02d2}-\x{02ff}' . '\x{0346}-\x{035f}\x{0362}-\x{0385}\x{038b}\x{038d}\x{03a2}\x{03cf}\x{03d7}-\x{03d9}\x{03db}\x{03dd}\x{03df}' . '\x{03e1}\x{03f4}-\x{0400}\x{040d}\x{0450}\x{045d}\x{0482}\x{0487}-\x{048f}\x{04c5}-\x{04c6}\x{04c9}-\x{04ca}' . '\x{04cd}-\x{04cf}\x{04ec}-\x{04ed}\x{04f6}-\x{04f7}\x{04fa}-\x{0530}\x{0557}-\x{0558}\x{055a}-\x{0560}' . '\x{0587}-\x{0590}\x{05a2}\x{05ba}\x{05be}\x{05c0}\x{05c3}\x{05c5}-\x{05cf}\x{05eb}-\x{05ef}\x{05f3}-\x{0620}' . '\x{063b}-\x{063f}\x{0653}-\x{065f}\x{066a}-\x{066f}\x{06b8}-\x{06b9}\x{06bf}\x{06cf}\x{06d4}\x{06e9}' . '\x{06ee}-\x{06ef}\x{06fa}-\x{0900}\x{0904}\x{093a}-\x{093b}\x{094e}-\x{0950}\x{0955}-\x{0957}' . '\x{0964}-\x{0965}\x{0970}-\x{0980}\x{0984}\x{098d}-\x{098e}\x{0991}-\x{0992}\x{09a9}\x{09b1}\x{09b3}-\x{09b5}' . '\x{09ba}-\x{09bb}\x{09bd}\x{09c5}-\x{09c6}\x{09c9}-\x{09ca}\x{09ce}-\x{09d6}\x{09d8}-\x{09db}\x{09de}' . '\x{09e4}-\x{09e5}\x{09f2}-\x{0a01}\x{0a03}-\x{0a04}\x{0a0b}-\x{0a0e}\x{0a11}-\x{0a12}\x{0a29}\x{0a31}\x{0a34}' . '\x{0a37}\x{0a3a}-\x{0a3b}\x{0a3d}\x{0a43}-\x{0a46}\x{0a49}-\x{0a4a}\x{0a4e}-\x{0a58}\x{0a5d}\x{0a5f}-\x{0a65}' . '\x{0a75}-\x{0a80}\x{0a84}\x{0a8c}\x{0a8e}\x{0a92}\x{0aa9}\x{0ab1}\x{0ab4}\x{0aba}-\x{0abb}\x{0ac6}\x{0aca}' . '\x{0ace}-\x{0adf}\x{0ae1}-\x{0ae5}\x{0af0}-\x{0b00}\x{0b04}\x{0b0d}-\x{0b0e}\x{0b11}-\x{0b12}\x{0b29}\x{0b31}' . '\x{0b34}-\x{0b35}\x{0b3a}-\x{0b3b}\x{0b44}-\x{0b46}\x{0b49}-\x{0b4a}\x{0b4e}-\x{0b55}\x{0b58}-\x{0b5b}\x{0b5e}' . '\x{0b62}-\x{0b65}\x{0b70}-\x{0b81}\x{0b84}\x{0b8b}-\x{0b8d}\x{0b91}\x{0b96}-\x{0b98}\x{0b9b}\x{0b9d}' . '\x{0ba0}-\x{0ba2}\x{0ba5}-\x{0ba7}\x{0bab}-\x{0bad}\x{0bb6}\x{0bba}-\x{0bbd}\x{0bc3}-\x{0bc5}\x{0bc9}' . '\x{0bce}-\x{0bd6}\x{0bd8}-\x{0be6}\x{0bf0}-\x{0c00}\x{0c04}\x{0c0d}\x{0c11}\x{0c29}\x{0c34}\x{0c3a}-\x{0c3d}' . '\x{0c45}\x{0c49}\x{0c4e}-\x{0c54}\x{0c57}-\x{0c5f}\x{0c62}-\x{0c65}\x{0c70}-\x{0c81}\x{0c84}\x{0c8d}\x{0c91}' . '\x{0ca9}\x{0cb4}\x{0cba}-\x{0cbd}\x{0cc5}\x{0cc9}\x{0cce}-\x{0cd4}\x{0cd7}-\x{0cdd}\x{0cdf}\x{0ce2}-\x{0ce5}' . '\x{0cf0}-\x{0d01}\x{0d04}\x{0d0d}\x{0d11}\x{0d29}\x{0d3a}-\x{0d3d}\x{0d44}-\x{0d45}\x{0d49}\x{0d4e}-\x{0d56}' . '\x{0d58}-\x{0d5f}\x{0d62}-\x{0d65}\x{0d70}-\x{0e00}\x{0e2f}\x{0e3b}-\x{0e3f}\x{0e4f}\x{0e5a}-\x{0e80}\x{0e83}' . '\x{0e85}-\x{0e86}\x{0e89}\x{0e8b}-\x{0e8c}\x{0e8e}-\x{0e93}\x{0e98}\x{0ea0}\x{0ea4}\x{0ea6}\x{0ea8}-\x{0ea9}' . '\x{0eac}\x{0eaf}\x{0eba}\x{0ebe}-\x{0ebf}\x{0ec5}\x{0ec7}\x{0ece}-\x{0ecf}\x{0eda}-\x{0f17}\x{0f1a}-\x{0f1f}' . '\x{0f2a}-\x{0f34}\x{0f36}\x{0f38}\x{0f3a}-\x{0f3d}\x{0f48}\x{0f6a}-\x{0f70}\x{0f85}\x{0f8c}-\x{0f8f}\x{0f96}' . '\x{0f98}\x{0fae}-\x{0fb0}\x{0fb8}\x{0fba}-\x{109f}\x{10c6}-\x{10cf}\x{10f7}-\x{10ff}\x{1101}\x{1104}\x{1108}' . '\x{110a}\x{110d}\x{1113}-\x{113b}\x{113d}\x{113f}\x{1141}-\x{114b}\x{114d}\x{114f}\x{1151}-\x{1153}' . '\x{1156}-\x{1158}\x{115a}-\x{115e}\x{1162}\x{1164}\x{1166}\x{1168}\x{116a}-\x{116c}\x{116f}-\x{1171}\x{1174}' . '\x{1176}-\x{119d}\x{119f}-\x{11a7}\x{11a9}-\x{11aa}\x{11ac}-\x{11ad}\x{11b0}-\x{11b6}\x{11b9}\x{11bb}' . '\x{11c3}-\x{11ea}\x{11ec}-\x{11ef}\x{11f1}-\x{11f8}\x{11fa}-\x{1dff}\x{1e9c}-\x{1e9f}\x{1efa}-\x{1eff}' . '\x{1f16}-\x{1f17}\x{1f1e}-\x{1f1f}\x{1f46}-\x{1f47}\x{1f4e}-\x{1f4f}\x{1f58}\x{1f5a}\x{1f5c}\x{1f5e}' . '\x{1f7e}-\x{1f7f}\x{1fb5}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fc5}\x{1fcd}-\x{1fcf}\x{1fd4}-\x{1fd5}\x{1fdc}-\x{1fdf}' . '\x{1fed}-\x{1ff1}\x{1ff5}\x{1ffd}-\x{20cf}\x{20dd}-\x{20e0}\x{20e2}-\x{2125}\x{2127}-\x{2129}' . '\x{212c}-\x{212d}\x{212f}-\x{217f}\x{2183}-\x{3004}\x{3006}\x{3008}-\x{3020}\x{3030}\x{3036}-\x{3040}' . '\x{3095}-\x{3098}\x{309b}-\x{309c}\x{309f}-\x{30a0}\x{30fb}\x{30ff}-\x{3104}\x{312d}-\x{4dff}' . '\x{9fa6}-\x{abff}\x{d7a4}-\x{d7ff}\x{e000}-\x{ffff}'; } return null; }
Regex method Based upon the mode return a partial regex to generate a valid string for the intended use. Note that you can use almost litterally anything in a url - the limitation is only in what your own application understands. See the test case for info on how these regex patterns were generated. @param string $mode @return string|null A partial regex or false on failure
_regex
php
dereuromark/cakephp-tools
src/Model/Behavior/SluggedBehavior.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Behavior/SluggedBehavior.php
MIT
public static function enum($value, array $options, $default = null) { if ($value !== null && !is_array($value)) { if (array_key_exists($value, $options)) { return $options[$value]; } return $default; } if ($value !== null) { $newOptions = []; foreach ($value as $v) { $newOptions[$v] = $options[$v]; } return $newOptions; } return $options; }
The main method for any enumeration, should be called statically Now also supports reordering/filtering @link https://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/ @param array<string|int>|string|int|null $value Integer or array of keys or NULL for complete array result @param array<string|int, mixed> $options Options @param string|null $default Default value @return array<string|int, mixed>|string|null
enum
php
dereuromark/cakephp-tools
src/Model/Entity/EnumTrait.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Entity/EnumTrait.php
MIT
public function validateUrl($url, array $options = [], array $context = []) { if (!$url) { if (!empty($options['allowEmpty']) && empty($options['required'])) { return true; } return false; } if (!isset($options['autoComplete']) || $options['autoComplete'] !== false) { if (!is_string($url)) { throw new InvalidArgumentException('Can only accept string for autoComplete case'); } $url = $this->_autoCompleteUrl($url); } if (!isset($options['strict']) || $options['strict'] !== false) { $options['strict'] = true; } // validation if (!Validation::url($url, $options['strict']) && env('REMOTE_ADDR') && env('REMOTE_ADDR') !== '127.0.0.1') { return false; } // same domain? if (!empty($options['sameDomain']) && env('HTTP_HOST')) { if (!is_string($url)) { throw new InvalidArgumentException('Can only accept string for sameDomain case'); } /** @var string $is */ $is = parse_url($url, PHP_URL_HOST); $expected = (string)env('HTTP_HOST'); if (mb_strtolower($is) !== mb_strtolower($expected)) { return false; } } if (isset($options['deep']) && $options['deep'] === false) { return true; } if (!is_string($url)) { throw new InvalidArgumentException('Can only accept string for deep case'); } return $this->_validUrl($url); }
Checks if a URL is valid AND accessible (returns false otherwise) Options: - allowEmpty TRUE/FALSE (TRUE: if empty => return TRUE) - required TRUE/FALSE (TRUE: overrides allowEmpty) - autoComplete (default: TRUE) - deep (default: TRUE) @param array|string $url Full URL starting with http://... @param array<string, mixed> $options @param array $context @return bool Success
validateUrl
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
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; }
Prepend protocol if missing @param string $url @return string URL
_autoCompleteUrl
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
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; }
Checks if a url is valid @param string $url @return bool Success
_validUrl
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
public function validateDateTime($value, array $options = [], array $context = []) { if (!$value) { if (!empty($options['allowEmpty'])) { return true; } return false; } $format = !empty($options['dateFormat']) ? $options['dateFormat'] : 'ymd'; /** @var \Cake\Chronos\Chronos|mixed $datetime */ $datetime = $value; if (!is_object($value)) { $datetime = new DateTime($value); } $pieces = $datetime->format(FORMAT_DB_DATETIME); $dateTimeParts = explode(' ', $pieces, 2); $datePart = $dateTimeParts[0]; $timePart = (!empty($dateTimeParts[1]) ? $dateTimeParts[1] : ''); if (!empty($options['allowEmpty']) && (empty($datePart) && empty($timePart))) { return true; } if (Validation::date($datePart, $format) && Validation::time($timePart)) { // after/before? $seconds = $options['min'] ?? 1; if (!empty($options['after'])) { if (!is_object($options['after']) && isset($context['data'][$options['after']])) { $options['after'] = $context['data'][$options['after']]; if (!is_object($options['after'])) { $options['after'] = new DateTime($options['after']); } } elseif (!is_object($options['after'])) { return false; } } if (!empty($options['before'])) { if (!is_object($options['before']) && isset($context['data'][$options['before']])) { $options['before'] = $context['data'][$options['before']]; if (!is_object($options['before'])) { $options['before'] = new DateTime($options['before']); } } elseif (!is_object($options['before'])) { return false; } } // We need this for those not using immutable objects just yet $compareValue = clone $datetime; if (!empty($options['after'])) { $compare = $compareValue->subSeconds($seconds); if ($options['after']->greaterThan($compare)) { return false; } if (!empty($options['max'])) { $after = $options['after']->addSeconds($options['max']); if ($datetime->greaterThan($after)) { return false; } } } if (!empty($options['before'])) { $compare = $compareValue->addSeconds($seconds); if ($options['before']->lessThan($compare)) { return false; } if (!empty($options['max'])) { $after = $options['before']->subSeconds($options['max']); if ($datetime->lessThan($after)) { return false; } } } return true; } return false; }
Validation of DateTime Fields (both Date and Time together) @param mixed $value @param array<string, mixed> $options - dateFormat (defaults to 'ymd') - allowEmpty - after/before (fieldName to validate against) - min/max (defaults to >= 1 - at least 1 minute apart) @param array $context @return bool Success
validateDateTime
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
public function validateDate($value, array $options = [], array $context = []) { if (!$value) { if (!empty($options['allowEmpty'])) { return true; } return false; } $format = !empty($options['format']) ? $options['format'] : 'ymd'; /** @var \Cake\Chronos\ChronosDate|mixed $date */ $date = $value; if (!is_object($value)) { if (is_array($value)) { $value = $value['year'] . '-' . $value['month'] . '-' . $value['day']; } $date = new Date($value); } if (!empty($options['allowEmpty']) && empty($date)) { return true; } if (Validation::date($value, $format)) { // after/before? $days = !empty($options['min']) ? $options['min'] : 0; if (!empty($options['after']) && isset($context['data'][$options['after']])) { $compare = $date->subDays($days); /** @var \Cake\I18n\DateTime $after */ $after = $context['data'][$options['after']]; if (!is_object($after)) { $after = new Date($after); } if ($after->greaterThan($compare)) { return false; } } if (!empty($options['before']) && isset($context['data'][$options['before']])) { $compare = $date->addDays($days); /** @var \Cake\I18n\DateTime $before */ $before = $context['data'][$options['before']]; if (!is_object($before)) { $before = new Date($before); } if ($before->lessThan($compare)) { return false; } } return true; } return false; }
Validation of Date fields (as the core one is buggy!!!) @param mixed $value @param array<string, mixed> $options - dateFormat (defaults to 'ymd') - allowEmpty - after/before (fieldName to validate against) - min (defaults to 0 - equal is OK too) @param array $context @return bool Success
validateDate
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
public function validateTime($value, array $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; }
Validation of Time fields @param mixed $value @param array<string, mixed> $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
validateTime
php
dereuromark/cakephp-tools
src/Model/Table/Table.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/Model/Table/Table.php
MIT
public function addItem($item) { $this->_items[] = $item; }
Add timeline item. Requires at least: - start (date or datetime) - content (string) Further data options: - end (date or datetime) - group (string) - className (string) - editable (boolean) @link http://almende.github.io/chap-links-library/js/timeline/doc/ @param array $item @return void
addItem
php
dereuromark/cakephp-tools
src/View/Helper/TimelineHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/TimelineHelper.php
MIT
public function addItems($items) { foreach ($items as $item) { $this->_items[] = $item; } }
Add timeline items as an array of items. @see \Tools\View\Helper\TimelineHelper::addItem() @param array $items @return void
addItems
php
dereuromark/cakephp-tools
src/View/Helper/TimelineHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/TimelineHelper.php
MIT
protected function _date($date = null) { if ($date === null) { 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) . ')'; }
Format date to JS code. @param \DateTimeInterface|\Cake\Chronos\Chronos|null $date @return string
_date
php
dereuromark/cakephp-tools
src/View/Helper/TimelineHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/TimelineHelper.php
MIT
protected function _buffer($script, array $options = []) { $defaults = [ 'block' => true, ]; $options += $defaults; $this->Html->scriptBlock($script, $options); }
Options: - `safe` (boolean) Whether the $script should be wrapped in `<![CDATA[ ]]>`. Defaults to `false`. - `block` You can choose a different view block to write to (defaults to "script" one). @param string $script @param array<string, mixed> $options @return void
_buffer
php
dereuromark/cakephp-tools
src/View/Helper/TimelineHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/TimelineHelper.php
MIT
public function __construct(View $View, array $config = []) { if (class_exists(IconHelper::class)) { $this->helpers[] = 'Templating.Icon'; } else { $this->helpers[] = 'Tools.Icon'; } $defaults = (array)Configure::read('Format') + $this->_defaults; $config += $defaults; $this->template = new StringTemplate($config['templates']); parent::__construct($View, $config); }
@param \Cake\View\View $View @param array<string, mixed> $config
__construct
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function siteIconUrl($domain) { if (str_starts_with($domain, 'http')) { // Strip protocol $pieces = parse_url($domain); if ($pieces !== false) { $domain = $pieces['host'] ?? null; } } return 'https://www.google.com/s2/favicons?domain=' . $domain; }
Gets URL of a png img of a website (16x16 pixel). @param string $domain @return string
siteIconUrl
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function siteIcon($domain, array $options = []) { $url = $this->siteIconUrl($domain); $options['width'] = 16; $options['height'] = 16; if (!isset($options['alt'])) { $options['alt'] = $domain; } if (!isset($options['title'])) { $options['title'] = $domain; } return $this->Html->image($url, $options); }
Display a png img of a website (16x16 pixel) if not available, will return a fallback image (a globe) @param string $domain (preferably without protocol, e.g. "www.site.com") @param array<string, mixed> $options @return string
siteIcon
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function pad($input, $padLength, $padString, $padType = STR_PAD_RIGHT) { $length = mb_strlen($input); if ($padLength - $length > 0) { switch ($padType) { case STR_PAD_LEFT: $input = str_repeat($padString, $padLength - $length) . $input; break; case STR_PAD_RIGHT: $input .= str_repeat($padString, $padLength - $length); break; } } return $input; }
Fixes utf8 problems of native php str_pad function //TODO: move to textext helper? Also note there is Text::wrap() now. @param string $input @param int $padLength @param string $padString @param mixed $padType @return string input
pad
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function warning($value, $ok = false) { if (!$ok) { return $this->ok($value, false); } return $value; }
Returns red colored if not ok. WARNING: This method requires manual escaping of input - h() must be used for non HTML content. @deprecated Use Templating.Templating helper instead. @param string $value @param mixed $ok Boolish value @return string Value in HTML tags
warning
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
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); }
Returns green on ok, red otherwise. WARNING: This method requires manual escaping of input - h() must be used for non HTML content. @deprecated Use Templating.Templating helper instead. @param mixed $content Output @param bool $ok Boolish value @param array<string, mixed> $attributes @return string Value nicely formatted/colored
ok
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function slug($string) { if ($this->_config['slugger']) { $callable = $this->_config['slugger']; if (!is_callable($callable)) { throw new RuntimeException('Invalid callable passed as slugger.'); } return $callable($string); } return ShimInflector::slug($string); }
@param string $string @throws \RuntimeException @return string
slug
php
dereuromark/cakephp-tools
src/View/Helper/FormatHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/FormatHelper.php
MIT
public function __construct(View $View, array $config = []) { parent::__construct($View, $config); $this->reset(); }
@param \Cake\View\View $View @param array<string, mixed> $config
__construct
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
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<string, mixed> $options Options @return string HTML
image
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function uri($text) { $params = []; $params['chl'] = rawurlencode($text); return $this->_uri($params); }
Just the url - without image tag Note: cannot be url() due to AppHelper conflicts @param string $text @return string URL
uri
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
protected function _uri($params = []) { $params += $this->options; $pieces = []; foreach ($params as $key => $value) { $pieces[] = $key . '=' . $value; } return $this->url . implode('&', $pieces); }
@param array $params @return string Url
_uri
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function formatText($text, $type = null) { switch ($type) { case 'text': break; case 'url': $text = $this->Url->build($text, ['fullBase' => 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; }
Format a text in a specific format - url, sms, tel, email, market, geo @param array|string $text @param string|null $type @return string formattedText
formatText
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function formatEvent() { }
//TODO calendar event e.g.: BEGIN:VEVENT SUMMARY:dfdfd DTSTART:20100226T092900Z DTEND:20100226T102900Z END:VEVENT @see http://zxing.appspot.com/generator/ @return void
formatEvent
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function format($protocol, $string) { return $protocol . ':' . $string; }
QrCodeHelper::format() @param mixed $protocol @param mixed $string @return string
format
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function setLevel($level, $margin = null) { if (in_array($level, $this->ecLevels)) { if ($margin === null) { $margin = 4; # minimum } $this->options['chld'] = strtoupper($level) . '|' . $margin; return true; } return false; }
Change level and margin - optional result format: chld=<EC level>|<margin> @param string $level @param int|null $margin @return bool Success
setLevel
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function setEncoding() { //TODO }
@return void
setEncoding
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function reset() { $this->setSize(static::DEFAULT_SIZE); //$this->setLevel(QS_CODE_DEFAULT_LEVEL); $this->options['chld'] = ''; $this->options['choe'] = Configure::read('App.encoding'); }
@return void
reset
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT
public function debug() { return $this->options; }
Show current options - for debugging only @return array
debug
php
dereuromark/cakephp-tools
src/View/Helper/QrCodeHelper.php
https://github.com/dereuromark/cakephp-tools/blob/master/src/View/Helper/QrCodeHelper.php
MIT