id
int32
0
241k
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
35,900
tipsyphp/tipsy
src/Resource.php
Resource.delete
public function delete() { if ($this->dbId()) { $this->db()->query('DELETE FROM `'.$this->table().'` WHERE `'.$this->idVar().'` = ?', [$this->dbId()]); } else { throw new Exception('Cannot delete. No ID was given.'); } return $this; }
php
public function delete() { if ($this->dbId()) { $this->db()->query('DELETE FROM `'.$this->table().'` WHERE `'.$this->idVar().'` = ?', [$this->dbId()]); } else { throw new Exception('Cannot delete. No ID was given.'); } return $this; }
[ "public", "function", "delete", "(", ")", "{", "if", "(", "$", "this", "->", "dbId", "(", ")", ")", "{", "$", "this", "->", "db", "(", ")", "->", "query", "(", "'DELETE FROM `'", ".", "$", "this", "->", "table", "(", ")", ".", "'` WHERE `'", ".", "$", "this", "->", "idVar", "(", ")", ".", "'` = ?'", ",", "[", "$", "this", "->", "dbId", "(", ")", "]", ")", ";", "}", "else", "{", "throw", "new", "Exception", "(", "'Cannot delete. No ID was given.'", ")", ";", "}", "return", "$", "this", ";", "}" ]
Delete a row in a table
[ "Delete", "a", "row", "in", "a", "table" ]
9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af
https://github.com/tipsyphp/tipsy/blob/9d46d31dd6d29664a0dd5f85bd6a96d8b21e24af/src/Resource.php#L411-L418
35,901
elcobvg/laravel-opcache
src/Repository.php
Repository.flush
public function flush() { $this->tags->getNames() ? $this->store->flushSub() : $this->store->flush(); }
php
public function flush() { $this->tags->getNames() ? $this->store->flushSub() : $this->store->flush(); }
[ "public", "function", "flush", "(", ")", "{", "$", "this", "->", "tags", "->", "getNames", "(", ")", "?", "$", "this", "->", "store", "->", "flushSub", "(", ")", ":", "$", "this", "->", "store", "->", "flush", "(", ")", ";", "}" ]
Remove all items from the cache. If called with tags, only reset them. @return void
[ "Remove", "all", "items", "from", "the", "cache", ".", "If", "called", "with", "tags", "only", "reset", "them", "." ]
2b559c22521a78b089f7121f01203e03be0ee987
https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Repository.php#L35-L38
35,902
elcobvg/laravel-opcache
src/Store.php
Store.exists
protected function exists($key) { if ($this->enabled && opcache_is_script_cached($this->filePath($key))) { return true; } return file_exists($this->filePath($key)); }
php
protected function exists($key) { if ($this->enabled && opcache_is_script_cached($this->filePath($key))) { return true; } return file_exists($this->filePath($key)); }
[ "protected", "function", "exists", "(", "$", "key", ")", "{", "if", "(", "$", "this", "->", "enabled", "&&", "opcache_is_script_cached", "(", "$", "this", "->", "filePath", "(", "$", "key", ")", ")", ")", "{", "return", "true", ";", "}", "return", "file_exists", "(", "$", "this", "->", "filePath", "(", "$", "key", ")", ")", ";", "}" ]
Determines whether the key exists within the cache. @param string $key @return bool
[ "Determines", "whether", "the", "key", "exists", "within", "the", "cache", "." ]
2b559c22521a78b089f7121f01203e03be0ee987
https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L101-L107
35,903
elcobvg/laravel-opcache
src/Store.php
Store.writeFile
protected function writeFile(string $key, int $exp, $val) { // Write to temp file first to ensure atomicity. Use crc32 for speed $dir = $this->getFullDirectory(); $this->checkDirectory($dir); $tmp = $dir . DIRECTORY_SEPARATOR . crc32($key) . '-' . uniqid('', true) . '.tmp'; file_put_contents($tmp, '<?php $exp = ' . $exp . '; $val = ' . $val . ';', LOCK_EX); return rename($tmp, $this->filePath($key)); }
php
protected function writeFile(string $key, int $exp, $val) { // Write to temp file first to ensure atomicity. Use crc32 for speed $dir = $this->getFullDirectory(); $this->checkDirectory($dir); $tmp = $dir . DIRECTORY_SEPARATOR . crc32($key) . '-' . uniqid('', true) . '.tmp'; file_put_contents($tmp, '<?php $exp = ' . $exp . '; $val = ' . $val . ';', LOCK_EX); return rename($tmp, $this->filePath($key)); }
[ "protected", "function", "writeFile", "(", "string", "$", "key", ",", "int", "$", "exp", ",", "$", "val", ")", "{", "// Write to temp file first to ensure atomicity. Use crc32 for speed", "$", "dir", "=", "$", "this", "->", "getFullDirectory", "(", ")", ";", "$", "this", "->", "checkDirectory", "(", "$", "dir", ")", ";", "$", "tmp", "=", "$", "dir", ".", "DIRECTORY_SEPARATOR", ".", "crc32", "(", "$", "key", ")", ".", "'-'", ".", "uniqid", "(", "''", ",", "true", ")", ".", "'.tmp'", ";", "file_put_contents", "(", "$", "tmp", ",", "'<?php $exp = '", ".", "$", "exp", ".", "'; $val = '", ".", "$", "val", ".", "';'", ",", "LOCK_EX", ")", ";", "return", "rename", "(", "$", "tmp", ",", "$", "this", "->", "filePath", "(", "$", "key", ")", ")", ";", "}" ]
Write the cache file to disk @param string $key @param int $exp @param mixed $val @return bool
[ "Write", "the", "cache", "file", "to", "disk" ]
2b559c22521a78b089f7121f01203e03be0ee987
https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L353-L361
35,904
elcobvg/laravel-opcache
src/Store.php
Store.extendExpiration
public function extendExpiration(string $key, int $minutes = 1) { @include $this->filePath($key); if (isset($exp)) { $extended = strtotime('+' . $minutes . ' minutes', $exp); return $this->writeFile($key, $extended, var_export($val, true)); } return false; }
php
public function extendExpiration(string $key, int $minutes = 1) { @include $this->filePath($key); if (isset($exp)) { $extended = strtotime('+' . $minutes . ' minutes', $exp); return $this->writeFile($key, $extended, var_export($val, true)); } return false; }
[ "public", "function", "extendExpiration", "(", "string", "$", "key", ",", "int", "$", "minutes", "=", "1", ")", "{", "@", "include", "$", "this", "->", "filePath", "(", "$", "key", ")", ";", "if", "(", "isset", "(", "$", "exp", ")", ")", "{", "$", "extended", "=", "strtotime", "(", "'+'", ".", "$", "minutes", ".", "' minutes'", ",", "$", "exp", ")", ";", "return", "$", "this", "->", "writeFile", "(", "$", "key", ",", "$", "extended", ",", "var_export", "(", "$", "val", ",", "true", ")", ")", ";", "}", "return", "false", ";", "}" ]
Extend expiration time with given minutes @param string $key @param int $minutes @return bool
[ "Extend", "expiration", "time", "with", "given", "minutes" ]
2b559c22521a78b089f7121f01203e03be0ee987
https://github.com/elcobvg/laravel-opcache/blob/2b559c22521a78b089f7121f01203e03be0ee987/src/Store.php#L392-L401
35,905
hocza/sendy-laravel
src/Sendy.php
Sendy.subscribe
public function subscribe(array $values) { $result = $this->buildAndSend('subscribe', $values); /** * Prepare the array to return */ $notice = [ 'status' => true, 'message' => '', ]; /** * Handle results */ switch (strval($result)) { case '1': $notice['message'] = 'Subscribed.'; break; case 'Already subscribed.': $notice['message'] = $result; break; default: $notice = [ 'status' => false, 'message' => $result ]; break; } return $notice; }
php
public function subscribe(array $values) { $result = $this->buildAndSend('subscribe', $values); /** * Prepare the array to return */ $notice = [ 'status' => true, 'message' => '', ]; /** * Handle results */ switch (strval($result)) { case '1': $notice['message'] = 'Subscribed.'; break; case 'Already subscribed.': $notice['message'] = $result; break; default: $notice = [ 'status' => false, 'message' => $result ]; break; } return $notice; }
[ "public", "function", "subscribe", "(", "array", "$", "values", ")", "{", "$", "result", "=", "$", "this", "->", "buildAndSend", "(", "'subscribe'", ",", "$", "values", ")", ";", "/**\n * Prepare the array to return\n */", "$", "notice", "=", "[", "'status'", "=>", "true", ",", "'message'", "=>", "''", ",", "]", ";", "/**\n * Handle results\n */", "switch", "(", "strval", "(", "$", "result", ")", ")", "{", "case", "'1'", ":", "$", "notice", "[", "'message'", "]", "=", "'Subscribed.'", ";", "break", ";", "case", "'Already subscribed.'", ":", "$", "notice", "[", "'message'", "]", "=", "$", "result", ";", "break", ";", "default", ":", "$", "notice", "=", "[", "'status'", "=>", "false", ",", "'message'", "=>", "$", "result", "]", ";", "break", ";", "}", "return", "$", "notice", ";", "}" ]
Method to add a new subscriber to a list @param array $values @return array
[ "Method", "to", "add", "a", "new", "subscriber", "to", "a", "list" ]
d1e7b8e1ee8315e4aa4d1d33e86deeae55357110
https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L69-L103
35,906
hocza/sendy-laravel
src/Sendy.php
Sendy.unsubscribe
public function unsubscribe($email) { $result = $this->buildAndSend('unsubscribe', ['email' => $email]); /** * Prepare the array to return */ $notice = [ 'status' => true, 'message' => '', ]; /** * Handle results */ switch (strval($result)) { case '1': $notice['message'] = 'Unsubscribed'; break; default: $notice = [ 'status' => false, 'message' => $result ]; break; } return $notice; }
php
public function unsubscribe($email) { $result = $this->buildAndSend('unsubscribe', ['email' => $email]); /** * Prepare the array to return */ $notice = [ 'status' => true, 'message' => '', ]; /** * Handle results */ switch (strval($result)) { case '1': $notice['message'] = 'Unsubscribed'; break; default: $notice = [ 'status' => false, 'message' => $result ]; break; } return $notice; }
[ "public", "function", "unsubscribe", "(", "$", "email", ")", "{", "$", "result", "=", "$", "this", "->", "buildAndSend", "(", "'unsubscribe'", ",", "[", "'email'", "=>", "$", "email", "]", ")", ";", "/**\n * Prepare the array to return\n */", "$", "notice", "=", "[", "'status'", "=>", "true", ",", "'message'", "=>", "''", ",", "]", ";", "/**\n * Handle results\n */", "switch", "(", "strval", "(", "$", "result", ")", ")", "{", "case", "'1'", ":", "$", "notice", "[", "'message'", "]", "=", "'Unsubscribed'", ";", "break", ";", "default", ":", "$", "notice", "=", "[", "'status'", "=>", "false", ",", "'message'", "=>", "$", "result", "]", ";", "break", ";", "}", "return", "$", "notice", ";", "}" ]
Method to unsubscribe a user from a list @param $email @return array
[ "Method", "to", "unsubscribe", "a", "user", "from", "a", "list" ]
d1e7b8e1ee8315e4aa4d1d33e86deeae55357110
https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L130-L160
35,907
hocza/sendy-laravel
src/Sendy.php
Sendy.checkProperties
private function checkProperties() { if (!isset($this->listId)) { throw new \Exception('[listId] is not set', 1); } if (!isset($this->installationUrl)) { throw new \Exception('[installationUrl] is not set', 1); } if (!isset($this->apiKey)) { throw new \Exception('[apiKey] is not set', 1); } }
php
private function checkProperties() { if (!isset($this->listId)) { throw new \Exception('[listId] is not set', 1); } if (!isset($this->installationUrl)) { throw new \Exception('[installationUrl] is not set', 1); } if (!isset($this->apiKey)) { throw new \Exception('[apiKey] is not set', 1); } }
[ "private", "function", "checkProperties", "(", ")", "{", "if", "(", "!", "isset", "(", "$", "this", "->", "listId", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'[listId] is not set'", ",", "1", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "installationUrl", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'[installationUrl] is not set'", ",", "1", ")", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "apiKey", ")", ")", "{", "throw", "new", "\\", "Exception", "(", "'[apiKey] is not set'", ",", "1", ")", ";", "}", "}" ]
Checks the properties @throws \Exception
[ "Checks", "the", "properties" ]
d1e7b8e1ee8315e4aa4d1d33e86deeae55357110
https://github.com/hocza/sendy-laravel/blob/d1e7b8e1ee8315e4aa4d1d33e86deeae55357110/src/Sendy.php#L285-L298
35,908
CarbonDate/Carbon
src/Carbon/Carbon.php
Carbon.createSafe
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) { $fields = array( 'year' => array(0, 9999), 'month' => array(0, 12), 'day' => array(0, 31), 'hour' => array(0, 24), 'minute' => array(0, 59), 'second' => array(0, 59), ); foreach ($fields as $field => $range) { if ($$field !== null && (!is_int($$field) || $$field < $range[0] || $$field > $range[1])) { throw new InvalidDateException($field, $$field); } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $tz); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!is_int($$field) || $$field !== $instance->$field)) { throw new InvalidDateException($field, $$field); } } return $instance; }
php
public static function createSafe($year = null, $month = null, $day = null, $hour = null, $minute = null, $second = null, $tz = null) { $fields = array( 'year' => array(0, 9999), 'month' => array(0, 12), 'day' => array(0, 31), 'hour' => array(0, 24), 'minute' => array(0, 59), 'second' => array(0, 59), ); foreach ($fields as $field => $range) { if ($$field !== null && (!is_int($$field) || $$field < $range[0] || $$field > $range[1])) { throw new InvalidDateException($field, $$field); } } $instance = static::create($year, $month, $day, $hour, $minute, $second, $tz); foreach (array_reverse($fields) as $field => $range) { if ($$field !== null && (!is_int($$field) || $$field !== $instance->$field)) { throw new InvalidDateException($field, $$field); } } return $instance; }
[ "public", "static", "function", "createSafe", "(", "$", "year", "=", "null", ",", "$", "month", "=", "null", ",", "$", "day", "=", "null", ",", "$", "hour", "=", "null", ",", "$", "minute", "=", "null", ",", "$", "second", "=", "null", ",", "$", "tz", "=", "null", ")", "{", "$", "fields", "=", "array", "(", "'year'", "=>", "array", "(", "0", ",", "9999", ")", ",", "'month'", "=>", "array", "(", "0", ",", "12", ")", ",", "'day'", "=>", "array", "(", "0", ",", "31", ")", ",", "'hour'", "=>", "array", "(", "0", ",", "24", ")", ",", "'minute'", "=>", "array", "(", "0", ",", "59", ")", ",", "'second'", "=>", "array", "(", "0", ",", "59", ")", ",", ")", ";", "foreach", "(", "$", "fields", "as", "$", "field", "=>", "$", "range", ")", "{", "if", "(", "$", "$", "field", "!==", "null", "&&", "(", "!", "is_int", "(", "$", "$", "field", ")", "||", "$", "$", "field", "<", "$", "range", "[", "0", "]", "||", "$", "$", "field", ">", "$", "range", "[", "1", "]", ")", ")", "{", "throw", "new", "InvalidDateException", "(", "$", "field", ",", "$", "$", "field", ")", ";", "}", "}", "$", "instance", "=", "static", "::", "create", "(", "$", "year", ",", "$", "month", ",", "$", "day", ",", "$", "hour", ",", "$", "minute", ",", "$", "second", ",", "$", "tz", ")", ";", "foreach", "(", "array_reverse", "(", "$", "fields", ")", "as", "$", "field", "=>", "$", "range", ")", "{", "if", "(", "$", "$", "field", "!==", "null", "&&", "(", "!", "is_int", "(", "$", "$", "field", ")", "||", "$", "$", "field", "!==", "$", "instance", "->", "$", "field", ")", ")", "{", "throw", "new", "InvalidDateException", "(", "$", "field", ",", "$", "$", "field", ")", ";", "}", "}", "return", "$", "instance", ";", "}" ]
Create a new safe Carbon instance from a specific date and time. If any of $year, $month or $day are set to null their now() values will be used. If $hour is null it will be set to its now() value and the default values for $minute and $second will be their now() values. If $hour is not null then the default values for $minute and $second will be 0. If one of the set values is not valid, an \InvalidArgumentException will be thrown. @param int|null $year @param int|null $month @param int|null $day @param int|null $hour @param int|null $minute @param int|null $second @param \DateTimeZone|string|null $tz @throws \Carbon\Exceptions\InvalidDateException|\InvalidArgumentException @return static
[ "Create", "a", "new", "safe", "Carbon", "instance", "from", "a", "specific", "date", "and", "time", "." ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L728-L754
35,909
CarbonDate/Carbon
src/Carbon/Carbon.php
Carbon.setTimeFrom
public function setTimeFrom($date) { $date = static::instance($date); $this->setTime($date->hour, $date->minute, $date->second); return $this; }
php
public function setTimeFrom($date) { $date = static::instance($date); $this->setTime($date->hour, $date->minute, $date->second); return $this; }
[ "public", "function", "setTimeFrom", "(", "$", "date", ")", "{", "$", "date", "=", "static", "::", "instance", "(", "$", "date", ")", ";", "$", "this", "->", "setTime", "(", "$", "date", "->", "hour", ",", "$", "date", "->", "minute", ",", "$", "date", "->", "second", ")", ";", "return", "$", "this", ";", "}" ]
Set the hour, day, and time for this instance to that of the passed instance. @param \Carbon\Carbon|\DateTimeInterface $date @return static
[ "Set", "the", "hour", "day", "and", "time", "for", "this", "instance", "to", "that", "of", "the", "passed", "instance", "." ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L1339-L1346
35,910
CarbonDate/Carbon
src/Carbon/Carbon.php
Carbon.toArray
public function toArray() { return array( 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->format(self::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ); }
php
public function toArray() { return array( 'year' => $this->year, 'month' => $this->month, 'day' => $this->day, 'dayOfWeek' => $this->dayOfWeek, 'dayOfYear' => $this->dayOfYear, 'hour' => $this->hour, 'minute' => $this->minute, 'second' => $this->second, 'micro' => $this->micro, 'timestamp' => $this->timestamp, 'formatted' => $this->format(self::DEFAULT_TO_STRING_FORMAT), 'timezone' => $this->timezone, ); }
[ "public", "function", "toArray", "(", ")", "{", "return", "array", "(", "'year'", "=>", "$", "this", "->", "year", ",", "'month'", "=>", "$", "this", "->", "month", ",", "'day'", "=>", "$", "this", "->", "day", ",", "'dayOfWeek'", "=>", "$", "this", "->", "dayOfWeek", ",", "'dayOfYear'", "=>", "$", "this", "->", "dayOfYear", ",", "'hour'", "=>", "$", "this", "->", "hour", ",", "'minute'", "=>", "$", "this", "->", "minute", ",", "'second'", "=>", "$", "this", "->", "second", ",", "'micro'", "=>", "$", "this", "->", "micro", ",", "'timestamp'", "=>", "$", "this", "->", "timestamp", ",", "'formatted'", "=>", "$", "this", "->", "format", "(", "self", "::", "DEFAULT_TO_STRING_FORMAT", ")", ",", "'timezone'", "=>", "$", "this", "->", "timezone", ",", ")", ";", "}" ]
Get default array representation @return array
[ "Get", "default", "array", "representation" ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L1835-L1851
35,911
CarbonDate/Carbon
src/Carbon/Carbon.php
Carbon.mixin
public static function mixin($mixin) { $reflection = new \ReflectionClass($mixin); $methods = $reflection->getMethods( \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED ); foreach ($methods as $method) { $method->setAccessible(true); static::macro($method->name, $method->invoke($mixin)); } }
php
public static function mixin($mixin) { $reflection = new \ReflectionClass($mixin); $methods = $reflection->getMethods( \ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED ); foreach ($methods as $method) { $method->setAccessible(true); static::macro($method->name, $method->invoke($mixin)); } }
[ "public", "static", "function", "mixin", "(", "$", "mixin", ")", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "$", "mixin", ")", ";", "$", "methods", "=", "$", "reflection", "->", "getMethods", "(", "\\", "ReflectionMethod", "::", "IS_PUBLIC", "|", "\\", "ReflectionMethod", "::", "IS_PROTECTED", ")", ";", "foreach", "(", "$", "methods", "as", "$", "method", ")", "{", "$", "method", "->", "setAccessible", "(", "true", ")", ";", "static", "::", "macro", "(", "$", "method", "->", "name", ",", "$", "method", "->", "invoke", "(", "$", "mixin", ")", ")", ";", "}", "}" ]
Mix another object into the class. @param object $mixin @throws \ReflectionException @return void
[ "Mix", "another", "object", "into", "the", "class", "." ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/Carbon.php#L4454-L4466
35,912
CarbonDate/Carbon
src/Carbon/CarbonInterval.php
CarbonInterval.fromString
public static function fromString($intervalDefinition) { if (empty($intervalDefinition)) { return new static(0); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ($match = array_shift($parts)) { list($part, $value, $unit) = $match; $intValue = intval($value); $fraction = floatval($value) - $intValue; switch (strtolower($unit)) { case 'year': case 'years': case 'y': $years += $intValue; break; case 'month': case 'months': case 'mo': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::DAYS_PER_WEEK, 'd'); } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::HOURS_PER_DAY, 'h'); } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::MINUTES_PER_HOUR, 'm'); } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction != 0) { $seconds += round($fraction * Carbon::SECONDS_PER_MINUTE); } break; case 'second': case 'seconds': case 's': $seconds += $intValue; break; default: throw new InvalidArgumentException( sprintf('Invalid part %s in definition %s', $part, $intervalDefinition) ); } } return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds); }
php
public static function fromString($intervalDefinition) { if (empty($intervalDefinition)) { return new static(0); } $years = 0; $months = 0; $weeks = 0; $days = 0; $hours = 0; $minutes = 0; $seconds = 0; $pattern = '/(\d+(?:\.\d+)?)\h*([^\d\h]*)/i'; preg_match_all($pattern, $intervalDefinition, $parts, PREG_SET_ORDER); while ($match = array_shift($parts)) { list($part, $value, $unit) = $match; $intValue = intval($value); $fraction = floatval($value) - $intValue; switch (strtolower($unit)) { case 'year': case 'years': case 'y': $years += $intValue; break; case 'month': case 'months': case 'mo': $months += $intValue; break; case 'week': case 'weeks': case 'w': $weeks += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::DAYS_PER_WEEK, 'd'); } break; case 'day': case 'days': case 'd': $days += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::HOURS_PER_DAY, 'h'); } break; case 'hour': case 'hours': case 'h': $hours += $intValue; if ($fraction != 0) { $parts[] = array(null, $fraction * Carbon::MINUTES_PER_HOUR, 'm'); } break; case 'minute': case 'minutes': case 'm': $minutes += $intValue; if ($fraction != 0) { $seconds += round($fraction * Carbon::SECONDS_PER_MINUTE); } break; case 'second': case 'seconds': case 's': $seconds += $intValue; break; default: throw new InvalidArgumentException( sprintf('Invalid part %s in definition %s', $part, $intervalDefinition) ); } } return new static($years, $months, $weeks, $days, $hours, $minutes, $seconds); }
[ "public", "static", "function", "fromString", "(", "$", "intervalDefinition", ")", "{", "if", "(", "empty", "(", "$", "intervalDefinition", ")", ")", "{", "return", "new", "static", "(", "0", ")", ";", "}", "$", "years", "=", "0", ";", "$", "months", "=", "0", ";", "$", "weeks", "=", "0", ";", "$", "days", "=", "0", ";", "$", "hours", "=", "0", ";", "$", "minutes", "=", "0", ";", "$", "seconds", "=", "0", ";", "$", "pattern", "=", "'/(\\d+(?:\\.\\d+)?)\\h*([^\\d\\h]*)/i'", ";", "preg_match_all", "(", "$", "pattern", ",", "$", "intervalDefinition", ",", "$", "parts", ",", "PREG_SET_ORDER", ")", ";", "while", "(", "$", "match", "=", "array_shift", "(", "$", "parts", ")", ")", "{", "list", "(", "$", "part", ",", "$", "value", ",", "$", "unit", ")", "=", "$", "match", ";", "$", "intValue", "=", "intval", "(", "$", "value", ")", ";", "$", "fraction", "=", "floatval", "(", "$", "value", ")", "-", "$", "intValue", ";", "switch", "(", "strtolower", "(", "$", "unit", ")", ")", "{", "case", "'year'", ":", "case", "'years'", ":", "case", "'y'", ":", "$", "years", "+=", "$", "intValue", ";", "break", ";", "case", "'month'", ":", "case", "'months'", ":", "case", "'mo'", ":", "$", "months", "+=", "$", "intValue", ";", "break", ";", "case", "'week'", ":", "case", "'weeks'", ":", "case", "'w'", ":", "$", "weeks", "+=", "$", "intValue", ";", "if", "(", "$", "fraction", "!=", "0", ")", "{", "$", "parts", "[", "]", "=", "array", "(", "null", ",", "$", "fraction", "*", "Carbon", "::", "DAYS_PER_WEEK", ",", "'d'", ")", ";", "}", "break", ";", "case", "'day'", ":", "case", "'days'", ":", "case", "'d'", ":", "$", "days", "+=", "$", "intValue", ";", "if", "(", "$", "fraction", "!=", "0", ")", "{", "$", "parts", "[", "]", "=", "array", "(", "null", ",", "$", "fraction", "*", "Carbon", "::", "HOURS_PER_DAY", ",", "'h'", ")", ";", "}", "break", ";", "case", "'hour'", ":", "case", "'hours'", ":", "case", "'h'", ":", "$", "hours", "+=", "$", "intValue", ";", "if", "(", "$", "fraction", "!=", "0", ")", "{", "$", "parts", "[", "]", "=", "array", "(", "null", ",", "$", "fraction", "*", "Carbon", "::", "MINUTES_PER_HOUR", ",", "'m'", ")", ";", "}", "break", ";", "case", "'minute'", ":", "case", "'minutes'", ":", "case", "'m'", ":", "$", "minutes", "+=", "$", "intValue", ";", "if", "(", "$", "fraction", "!=", "0", ")", "{", "$", "seconds", "+=", "round", "(", "$", "fraction", "*", "Carbon", "::", "SECONDS_PER_MINUTE", ")", ";", "}", "break", ";", "case", "'second'", ":", "case", "'seconds'", ":", "case", "'s'", ":", "$", "seconds", "+=", "$", "intValue", ";", "break", ";", "default", ":", "throw", "new", "InvalidArgumentException", "(", "sprintf", "(", "'Invalid part %s in definition %s'", ",", "$", "part", ",", "$", "intervalDefinition", ")", ")", ";", "}", "}", "return", "new", "static", "(", "$", "years", ",", "$", "months", ",", "$", "weeks", ",", "$", "days", ",", "$", "hours", ",", "$", "minutes", ",", "$", "seconds", ")", ";", "}" ]
Creates a CarbonInterval from string Format: Suffix | Unit | Example | DateInterval expression -------|---------|---------|------------------------ y | years | 1y | P1Y mo | months | 3mo | P3M w | weeks | 2w | P2W d | days | 28d | P28D h | hours | 4h | PT4H m | minutes | 12m | PT12M s | seconds | 59s | PT59S e. g. `1w 3d 4h 32m 23s` is converted to 10 days 4 hours 32 minutes and 23 seconds. Special cases: - An empty string will return a zero interval - Fractions are allowed for weeks, days, hours and minutes and will be converted and rounded to the next smaller value (caution: 0.5w = 4d) @param string $intervalDefinition @return static
[ "Creates", "a", "CarbonInterval", "from", "string" ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/CarbonInterval.php#L244-L327
35,913
CarbonDate/Carbon
src/Carbon/CarbonInterval.php
CarbonInterval.compareDateIntervals
public static function compareDateIntervals(DateInterval $a, DateInterval $b) { $current = Carbon::now(); $passed = $current->copy()->add($b); $current->add($a); if ($current < $passed) { return -1; } elseif ($current > $passed) { return 1; } return 0; }
php
public static function compareDateIntervals(DateInterval $a, DateInterval $b) { $current = Carbon::now(); $passed = $current->copy()->add($b); $current->add($a); if ($current < $passed) { return -1; } elseif ($current > $passed) { return 1; } return 0; }
[ "public", "static", "function", "compareDateIntervals", "(", "DateInterval", "$", "a", ",", "DateInterval", "$", "b", ")", "{", "$", "current", "=", "Carbon", "::", "now", "(", ")", ";", "$", "passed", "=", "$", "current", "->", "copy", "(", ")", "->", "add", "(", "$", "b", ")", ";", "$", "current", "->", "add", "(", "$", "a", ")", ";", "if", "(", "$", "current", "<", "$", "passed", ")", "{", "return", "-", "1", ";", "}", "elseif", "(", "$", "current", ">", "$", "passed", ")", "{", "return", "1", ";", "}", "return", "0", ";", "}" ]
Comparing 2 date intervals @param DateInterval $a @param DateInterval $b @return int
[ "Comparing", "2", "date", "intervals" ]
81476b3fb6b907087ddbe4eabd581eba38d55661
https://github.com/CarbonDate/Carbon/blob/81476b3fb6b907087ddbe4eabd581eba38d55661/src/Carbon/CarbonInterval.php#L703-L716
35,914
oat-sa/extension-tao-outcomerds
model/RdsResultStorage.php
RdsResultStorage.storeRelatedDelivery
public function storeRelatedDelivery($deliveryResultIdentifier, $deliveryIdentifier) { $sql = 'SELECT COUNT(*) FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $params = array($deliveryResultIdentifier); if ($this->getPersistence()->query($sql, $params)->fetchColumn() == 0) { $this->getPersistence()->insert( self::RESULTS_TABLENAME, array(self::DELIVERY_COLUMN => $deliveryIdentifier, self::RESULTS_TABLE_ID => $deliveryResultIdentifier) ); } else { $sqlUpdate = 'UPDATE ' . self::RESULTS_TABLENAME . ' SET ' . self::DELIVERY_COLUMN . ' = ? WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $paramsUpdate = array($deliveryIdentifier, $deliveryResultIdentifier); $this->getPersistence()->exec($sqlUpdate, $paramsUpdate); } }
php
public function storeRelatedDelivery($deliveryResultIdentifier, $deliveryIdentifier) { $sql = 'SELECT COUNT(*) FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $params = array($deliveryResultIdentifier); if ($this->getPersistence()->query($sql, $params)->fetchColumn() == 0) { $this->getPersistence()->insert( self::RESULTS_TABLENAME, array(self::DELIVERY_COLUMN => $deliveryIdentifier, self::RESULTS_TABLE_ID => $deliveryResultIdentifier) ); } else { $sqlUpdate = 'UPDATE ' . self::RESULTS_TABLENAME . ' SET ' . self::DELIVERY_COLUMN . ' = ? WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $paramsUpdate = array($deliveryIdentifier, $deliveryResultIdentifier); $this->getPersistence()->exec($sqlUpdate, $paramsUpdate); } }
[ "public", "function", "storeRelatedDelivery", "(", "$", "deliveryResultIdentifier", ",", "$", "deliveryIdentifier", ")", "{", "$", "sql", "=", "'SELECT COUNT(*) FROM '", ".", "self", "::", "RESULTS_TABLENAME", ".", "' WHERE '", ".", "self", "::", "RESULTS_TABLE_ID", ".", "' = ?'", ";", "$", "params", "=", "array", "(", "$", "deliveryResultIdentifier", ")", ";", "if", "(", "$", "this", "->", "getPersistence", "(", ")", "->", "query", "(", "$", "sql", ",", "$", "params", ")", "->", "fetchColumn", "(", ")", "==", "0", ")", "{", "$", "this", "->", "getPersistence", "(", ")", "->", "insert", "(", "self", "::", "RESULTS_TABLENAME", ",", "array", "(", "self", "::", "DELIVERY_COLUMN", "=>", "$", "deliveryIdentifier", ",", "self", "::", "RESULTS_TABLE_ID", "=>", "$", "deliveryResultIdentifier", ")", ")", ";", "}", "else", "{", "$", "sqlUpdate", "=", "'UPDATE '", ".", "self", "::", "RESULTS_TABLENAME", ".", "' SET '", ".", "self", "::", "DELIVERY_COLUMN", ".", "' = ? WHERE '", ".", "self", "::", "RESULTS_TABLE_ID", ".", "' = ?'", ";", "$", "paramsUpdate", "=", "array", "(", "$", "deliveryIdentifier", ",", "$", "deliveryResultIdentifier", ")", ";", "$", "this", "->", "getPersistence", "(", ")", "->", "exec", "(", "$", "sqlUpdate", ",", "$", "paramsUpdate", ")", ";", "}", "}" ]
Store Delivery corresponding to the current test @param $deliveryResultIdentifier @param $deliveryIdentifier
[ "Store", "Delivery", "corresponding", "to", "the", "current", "test" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L234-L249
35,915
oat-sa/extension-tao-outcomerds
model/RdsResultStorage.php
RdsResultStorage.getVariable
public function getVariable($callId, $variableIdentifier) { $sql = 'SELECT * FROM ' . self::VARIABLES_TABLENAME . ' WHERE (' . self::CALL_ID_ITEM_COLUMN . ' = ? OR ' . self::CALL_ID_TEST_COLUMN . ' = ?) AND ' . self::VARIABLE_IDENTIFIER . ' = ?'; $params = array($callId, $callId, $variableIdentifier); $variables = $this->getPersistence()->query($sql, $params); $returnValue = array(); // for each variable we construct the array foreach ($variables as $variable) { $returnValue[$variable[self::VARIABLES_TABLE_ID]] = $this->getResultRow($variable); } return $returnValue; }
php
public function getVariable($callId, $variableIdentifier) { $sql = 'SELECT * FROM ' . self::VARIABLES_TABLENAME . ' WHERE (' . self::CALL_ID_ITEM_COLUMN . ' = ? OR ' . self::CALL_ID_TEST_COLUMN . ' = ?) AND ' . self::VARIABLE_IDENTIFIER . ' = ?'; $params = array($callId, $callId, $variableIdentifier); $variables = $this->getPersistence()->query($sql, $params); $returnValue = array(); // for each variable we construct the array foreach ($variables as $variable) { $returnValue[$variable[self::VARIABLES_TABLE_ID]] = $this->getResultRow($variable); } return $returnValue; }
[ "public", "function", "getVariable", "(", "$", "callId", ",", "$", "variableIdentifier", ")", "{", "$", "sql", "=", "'SELECT * FROM '", ".", "self", "::", "VARIABLES_TABLENAME", ".", "'\n WHERE ('", ".", "self", "::", "CALL_ID_ITEM_COLUMN", ".", "' = ? OR '", ".", "self", "::", "CALL_ID_TEST_COLUMN", ".", "' = ?)\n AND '", ".", "self", "::", "VARIABLE_IDENTIFIER", ".", "' = ?'", ";", "$", "params", "=", "array", "(", "$", "callId", ",", "$", "callId", ",", "$", "variableIdentifier", ")", ";", "$", "variables", "=", "$", "this", "->", "getPersistence", "(", ")", "->", "query", "(", "$", "sql", ",", "$", "params", ")", ";", "$", "returnValue", "=", "array", "(", ")", ";", "// for each variable we construct the array", "foreach", "(", "$", "variables", "as", "$", "variable", ")", "{", "$", "returnValue", "[", "$", "variable", "[", "self", "::", "VARIABLES_TABLE_ID", "]", "]", "=", "$", "this", "->", "getResultRow", "(", "$", "variable", ")", ";", "}", "return", "$", "returnValue", ";", "}" ]
Get a variable from callId and Variable identifier @param $callId @param $variableIdentifier @return array
[ "Get", "a", "variable", "from", "callId", "and", "Variable", "identifier" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L321-L338
35,916
oat-sa/extension-tao-outcomerds
model/RdsResultStorage.php
RdsResultStorage.getDelivery
public function getDelivery($deliveryResultIdentifier) { $sql = 'SELECT ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $params = array($deliveryResultIdentifier); return $this->getPersistence()->query($sql, $params)->fetchColumn(); }
php
public function getDelivery($deliveryResultIdentifier) { $sql = 'SELECT ' . self::DELIVERY_COLUMN . ' FROM ' . self::RESULTS_TABLENAME . ' WHERE ' . self::RESULTS_TABLE_ID . ' = ?'; $params = array($deliveryResultIdentifier); return $this->getPersistence()->query($sql, $params)->fetchColumn(); }
[ "public", "function", "getDelivery", "(", "$", "deliveryResultIdentifier", ")", "{", "$", "sql", "=", "'SELECT '", ".", "self", "::", "DELIVERY_COLUMN", ".", "' FROM '", ".", "self", "::", "RESULTS_TABLENAME", ".", "' WHERE '", ".", "self", "::", "RESULTS_TABLE_ID", ".", "' = ?'", ";", "$", "params", "=", "array", "(", "$", "deliveryResultIdentifier", ")", ";", "return", "$", "this", "->", "getPersistence", "(", ")", "->", "query", "(", "$", "sql", ",", "$", "params", ")", "->", "fetchColumn", "(", ")", ";", "}" ]
get delivery corresponding to a result @param $deliveryResultIdentifier @return mixed
[ "get", "delivery", "corresponding", "to", "a", "result" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L374-L379
35,917
oat-sa/extension-tao-outcomerds
model/RdsResultStorage.php
RdsResultStorage.getResultByDelivery
public function getResultByDelivery($delivery, $options = array()) { $returnValue = array(); $sql = 'SELECT * FROM ' . self::RESULTS_TABLENAME; $params = array(); if (count($delivery) > 0) { $sql .= ' WHERE '; $inQuery = implode(',', array_fill(0, count($delivery), '?')); $sql .= self::DELIVERY_COLUMN . ' IN (' . $inQuery . ')'; $params = array_merge($params, $delivery); } if(isset($options['order']) && in_array($options['order'], [self::DELIVERY_COLUMN, self::TEST_TAKER_COLUMN, self::RESULTS_TABLE_ID])){ $sql .= ' ORDER BY ' . $options['order']; if(isset($options['orderdir']) && (strtolower($options['orderdir']) === 'asc' || strtolower($options['orderdir']) === 'desc')) { $sql .= ' ' . $options['orderdir']; } } if(isset($options['offset']) || isset($options['limit'])){ $offset = (isset($options['offset']))?$options['offset']:0; $limit = (isset($options['limit']))?$options['limit']:1000; $sql = $this->getPersistence()->getPlatForm()->limitStatement($sql, $limit, $offset); } $results = $this->getPersistence()->query($sql, $params); foreach ($results as $value) { $returnValue[] = array( "deliveryResultIdentifier" => $value[self::RESULTS_TABLE_ID], "testTakerIdentifier" => $value[self::TEST_TAKER_COLUMN], "deliveryIdentifier" => $value[self::DELIVERY_COLUMN] ); } return $returnValue; }
php
public function getResultByDelivery($delivery, $options = array()) { $returnValue = array(); $sql = 'SELECT * FROM ' . self::RESULTS_TABLENAME; $params = array(); if (count($delivery) > 0) { $sql .= ' WHERE '; $inQuery = implode(',', array_fill(0, count($delivery), '?')); $sql .= self::DELIVERY_COLUMN . ' IN (' . $inQuery . ')'; $params = array_merge($params, $delivery); } if(isset($options['order']) && in_array($options['order'], [self::DELIVERY_COLUMN, self::TEST_TAKER_COLUMN, self::RESULTS_TABLE_ID])){ $sql .= ' ORDER BY ' . $options['order']; if(isset($options['orderdir']) && (strtolower($options['orderdir']) === 'asc' || strtolower($options['orderdir']) === 'desc')) { $sql .= ' ' . $options['orderdir']; } } if(isset($options['offset']) || isset($options['limit'])){ $offset = (isset($options['offset']))?$options['offset']:0; $limit = (isset($options['limit']))?$options['limit']:1000; $sql = $this->getPersistence()->getPlatForm()->limitStatement($sql, $limit, $offset); } $results = $this->getPersistence()->query($sql, $params); foreach ($results as $value) { $returnValue[] = array( "deliveryResultIdentifier" => $value[self::RESULTS_TABLE_ID], "testTakerIdentifier" => $value[self::TEST_TAKER_COLUMN], "deliveryIdentifier" => $value[self::DELIVERY_COLUMN] ); } return $returnValue; }
[ "public", "function", "getResultByDelivery", "(", "$", "delivery", ",", "$", "options", "=", "array", "(", ")", ")", "{", "$", "returnValue", "=", "array", "(", ")", ";", "$", "sql", "=", "'SELECT * FROM '", ".", "self", "::", "RESULTS_TABLENAME", ";", "$", "params", "=", "array", "(", ")", ";", "if", "(", "count", "(", "$", "delivery", ")", ">", "0", ")", "{", "$", "sql", ".=", "' WHERE '", ";", "$", "inQuery", "=", "implode", "(", "','", ",", "array_fill", "(", "0", ",", "count", "(", "$", "delivery", ")", ",", "'?'", ")", ")", ";", "$", "sql", ".=", "self", "::", "DELIVERY_COLUMN", ".", "' IN ('", ".", "$", "inQuery", ".", "')'", ";", "$", "params", "=", "array_merge", "(", "$", "params", ",", "$", "delivery", ")", ";", "}", "if", "(", "isset", "(", "$", "options", "[", "'order'", "]", ")", "&&", "in_array", "(", "$", "options", "[", "'order'", "]", ",", "[", "self", "::", "DELIVERY_COLUMN", ",", "self", "::", "TEST_TAKER_COLUMN", ",", "self", "::", "RESULTS_TABLE_ID", "]", ")", ")", "{", "$", "sql", ".=", "' ORDER BY '", ".", "$", "options", "[", "'order'", "]", ";", "if", "(", "isset", "(", "$", "options", "[", "'orderdir'", "]", ")", "&&", "(", "strtolower", "(", "$", "options", "[", "'orderdir'", "]", ")", "===", "'asc'", "||", "strtolower", "(", "$", "options", "[", "'orderdir'", "]", ")", "===", "'desc'", ")", ")", "{", "$", "sql", ".=", "' '", ".", "$", "options", "[", "'orderdir'", "]", ";", "}", "}", "if", "(", "isset", "(", "$", "options", "[", "'offset'", "]", ")", "||", "isset", "(", "$", "options", "[", "'limit'", "]", ")", ")", "{", "$", "offset", "=", "(", "isset", "(", "$", "options", "[", "'offset'", "]", ")", ")", "?", "$", "options", "[", "'offset'", "]", ":", "0", ";", "$", "limit", "=", "(", "isset", "(", "$", "options", "[", "'limit'", "]", ")", ")", "?", "$", "options", "[", "'limit'", "]", ":", "1000", ";", "$", "sql", "=", "$", "this", "->", "getPersistence", "(", ")", "->", "getPlatForm", "(", ")", "->", "limitStatement", "(", "$", "sql", ",", "$", "limit", ",", "$", "offset", ")", ";", "}", "$", "results", "=", "$", "this", "->", "getPersistence", "(", ")", "->", "query", "(", "$", "sql", ",", "$", "params", ")", ";", "foreach", "(", "$", "results", "as", "$", "value", ")", "{", "$", "returnValue", "[", "]", "=", "array", "(", "\"deliveryResultIdentifier\"", "=>", "$", "value", "[", "self", "::", "RESULTS_TABLE_ID", "]", ",", "\"testTakerIdentifier\"", "=>", "$", "value", "[", "self", "::", "TEST_TAKER_COLUMN", "]", ",", "\"deliveryIdentifier\"", "=>", "$", "value", "[", "self", "::", "DELIVERY_COLUMN", "]", ")", ";", "}", "return", "$", "returnValue", ";", "}" ]
order, orderdir, offset, limit
[ "order", "orderdir", "offset", "limit" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/model/RdsResultStorage.php#L474-L510
35,918
oat-sa/extension-tao-outcomerds
scripts/tools/KvToRdsMigration.php
KvToRdsMigration.getCurrentKvResultStorage
protected function getCurrentKvResultStorage() { /** @var ResultServerService $resultService */ $resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID); $resultStorageKey = $resultService->getOption(ResultServerService::OPTION_RESULT_STORAGE); if ($resultStorageKey != 'taoAltResultStorage/KeyValueResultStorage') { throw new \common_Exception('Result storage is not on KeyValue storage mode.'); } return $resultService->instantiateResultStorage($resultStorageKey); }
php
protected function getCurrentKvResultStorage() { /** @var ResultServerService $resultService */ $resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID); $resultStorageKey = $resultService->getOption(ResultServerService::OPTION_RESULT_STORAGE); if ($resultStorageKey != 'taoAltResultStorage/KeyValueResultStorage') { throw new \common_Exception('Result storage is not on KeyValue storage mode.'); } return $resultService->instantiateResultStorage($resultStorageKey); }
[ "protected", "function", "getCurrentKvResultStorage", "(", ")", "{", "/** @var ResultServerService $resultService */", "$", "resultService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "ResultServerService", "::", "SERVICE_ID", ")", ";", "$", "resultStorageKey", "=", "$", "resultService", "->", "getOption", "(", "ResultServerService", "::", "OPTION_RESULT_STORAGE", ")", ";", "if", "(", "$", "resultStorageKey", "!=", "'taoAltResultStorage/KeyValueResultStorage'", ")", "{", "throw", "new", "\\", "common_Exception", "(", "'Result storage is not on KeyValue storage mode.'", ")", ";", "}", "return", "$", "resultService", "->", "instantiateResultStorage", "(", "$", "resultStorageKey", ")", ";", "}" ]
Get the configured service to deal with result storage @return \taoResultServer_models_classes_WritableResultStorage @throws \common_exception If the service is not a key value interface
[ "Get", "the", "configured", "service", "to", "deal", "with", "result", "storage" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/scripts/tools/KvToRdsMigration.php#L198-L207
35,919
oat-sa/extension-tao-outcomerds
scripts/tools/KvToRdsMigration.php
KvToRdsMigration.setCurrentResultStorageToRdsStorage
protected function setCurrentResultStorageToRdsStorage() { if ($this->isDryrun()) { return; } /** @var ResultServerService $resultService */ $resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID); $resultService->setOption(ResultServerService::OPTION_RESULT_STORAGE, RdsResultStorage::SERVICE_ID); $this->registerService(ResultServerService::SERVICE_ID, $resultService); $this->report->add(\common_report_Report::createSuccess('Storage type successfully updated to RDS Storage')); }
php
protected function setCurrentResultStorageToRdsStorage() { if ($this->isDryrun()) { return; } /** @var ResultServerService $resultService */ $resultService = $this->getServiceLocator()->get(ResultServerService::SERVICE_ID); $resultService->setOption(ResultServerService::OPTION_RESULT_STORAGE, RdsResultStorage::SERVICE_ID); $this->registerService(ResultServerService::SERVICE_ID, $resultService); $this->report->add(\common_report_Report::createSuccess('Storage type successfully updated to RDS Storage')); }
[ "protected", "function", "setCurrentResultStorageToRdsStorage", "(", ")", "{", "if", "(", "$", "this", "->", "isDryrun", "(", ")", ")", "{", "return", ";", "}", "/** @var ResultServerService $resultService */", "$", "resultService", "=", "$", "this", "->", "getServiceLocator", "(", ")", "->", "get", "(", "ResultServerService", "::", "SERVICE_ID", ")", ";", "$", "resultService", "->", "setOption", "(", "ResultServerService", "::", "OPTION_RESULT_STORAGE", ",", "RdsResultStorage", "::", "SERVICE_ID", ")", ";", "$", "this", "->", "registerService", "(", "ResultServerService", "::", "SERVICE_ID", ",", "$", "resultService", ")", ";", "$", "this", "->", "report", "->", "add", "(", "\\", "common_report_Report", "::", "createSuccess", "(", "'Storage type successfully updated to RDS Storage'", ")", ")", ";", "}" ]
Register rdsStorage as default result storage @throws \common_Exception
[ "Register", "rdsStorage", "as", "default", "result", "storage" ]
692699d12dafe84eafece38fad03e7728370c9ac
https://github.com/oat-sa/extension-tao-outcomerds/blob/692699d12dafe84eafece38fad03e7728370c9ac/scripts/tools/KvToRdsMigration.php#L214-L224
35,920
simoebenhida/Laramin
publishable/database/seeds/LaratrustSeeder.php
LaratrustSeeder.truncateLaratrustTables
public function truncateLaratrustTables() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('permission_role')->truncate(); DB::table('permission_user')->truncate(); DB::table('role_user')->truncate(); \App\User::truncate(); \Simoja\Laramin\Models\Role::truncate(); \Simoja\Laramin\Models\Permission::truncate(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); }
php
public function truncateLaratrustTables() { DB::statement('SET FOREIGN_KEY_CHECKS = 0'); DB::table('permission_role')->truncate(); DB::table('permission_user')->truncate(); DB::table('role_user')->truncate(); \App\User::truncate(); \Simoja\Laramin\Models\Role::truncate(); \Simoja\Laramin\Models\Permission::truncate(); DB::statement('SET FOREIGN_KEY_CHECKS = 1'); }
[ "public", "function", "truncateLaratrustTables", "(", ")", "{", "DB", "::", "statement", "(", "'SET FOREIGN_KEY_CHECKS = 0'", ")", ";", "DB", "::", "table", "(", "'permission_role'", ")", "->", "truncate", "(", ")", ";", "DB", "::", "table", "(", "'permission_user'", ")", "->", "truncate", "(", ")", ";", "DB", "::", "table", "(", "'role_user'", ")", "->", "truncate", "(", ")", ";", "\\", "App", "\\", "User", "::", "truncate", "(", ")", ";", "\\", "Simoja", "\\", "Laramin", "\\", "Models", "\\", "Role", "::", "truncate", "(", ")", ";", "\\", "Simoja", "\\", "Laramin", "\\", "Models", "\\", "Permission", "::", "truncate", "(", ")", ";", "DB", "::", "statement", "(", "'SET FOREIGN_KEY_CHECKS = 1'", ")", ";", "}" ]
Truncates all the laratrust tables and the users table @return void
[ "Truncates", "all", "the", "laratrust", "tables", "and", "the", "users", "table" ]
4012b5a7f19c639dab1b238926679e09fee79c31
https://github.com/simoebenhida/Laramin/blob/4012b5a7f19c639dab1b238926679e09fee79c31/publishable/database/seeds/LaratrustSeeder.php#L103-L113
35,921
phpmyadmin/motranslator
src/Translator.php
Translator.sanitizePluralExpression
public static function sanitizePluralExpression($expr) { // Parse equation $expr = explode(';', $expr); if (count($expr) >= 2) { $expr = $expr[1]; } else { $expr = $expr[0]; } $expr = trim(strtolower($expr)); // Strip plural prefix if (substr($expr, 0, 6) === 'plural') { $expr = ltrim(substr($expr, 6)); } // Strip equals if (substr($expr, 0, 1) === '=') { $expr = ltrim(substr($expr, 1)); } // Cleanup from unwanted chars $expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr); return $expr; }
php
public static function sanitizePluralExpression($expr) { // Parse equation $expr = explode(';', $expr); if (count($expr) >= 2) { $expr = $expr[1]; } else { $expr = $expr[0]; } $expr = trim(strtolower($expr)); // Strip plural prefix if (substr($expr, 0, 6) === 'plural') { $expr = ltrim(substr($expr, 6)); } // Strip equals if (substr($expr, 0, 1) === '=') { $expr = ltrim(substr($expr, 1)); } // Cleanup from unwanted chars $expr = preg_replace('@[^n0-9:\(\)\?=!<>/%&| ]@', '', $expr); return $expr; }
[ "public", "static", "function", "sanitizePluralExpression", "(", "$", "expr", ")", "{", "// Parse equation", "$", "expr", "=", "explode", "(", "';'", ",", "$", "expr", ")", ";", "if", "(", "count", "(", "$", "expr", ")", ">=", "2", ")", "{", "$", "expr", "=", "$", "expr", "[", "1", "]", ";", "}", "else", "{", "$", "expr", "=", "$", "expr", "[", "0", "]", ";", "}", "$", "expr", "=", "trim", "(", "strtolower", "(", "$", "expr", ")", ")", ";", "// Strip plural prefix", "if", "(", "substr", "(", "$", "expr", ",", "0", ",", "6", ")", "===", "'plural'", ")", "{", "$", "expr", "=", "ltrim", "(", "substr", "(", "$", "expr", ",", "6", ")", ")", ";", "}", "// Strip equals", "if", "(", "substr", "(", "$", "expr", ",", "0", ",", "1", ")", "===", "'='", ")", "{", "$", "expr", "=", "ltrim", "(", "substr", "(", "$", "expr", ",", "1", ")", ")", ";", "}", "// Cleanup from unwanted chars", "$", "expr", "=", "preg_replace", "(", "'@[^n0-9:\\(\\)\\?=!<>/%&| ]@'", ",", "''", ",", "$", "expr", ")", ";", "return", "$", "expr", ";", "}" ]
Sanitize plural form expression for use in ExpressionLanguage. @param string $expr Expression to sanitize @return string sanitized plural form expression
[ "Sanitize", "plural", "form", "expression", "for", "use", "in", "ExpressionLanguage", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L176-L199
35,922
phpmyadmin/motranslator
src/Translator.php
Translator.extractPluralCount
public static function extractPluralCount($expr) { $parts = explode(';', $expr, 2); $nplurals = explode('=', trim($parts[0]), 2); if (strtolower(rtrim($nplurals[0])) != 'nplurals') { return 1; } if (count($nplurals) == 1) { return 1; } return intval($nplurals[1]); }
php
public static function extractPluralCount($expr) { $parts = explode(';', $expr, 2); $nplurals = explode('=', trim($parts[0]), 2); if (strtolower(rtrim($nplurals[0])) != 'nplurals') { return 1; } if (count($nplurals) == 1) { return 1; } return intval($nplurals[1]); }
[ "public", "static", "function", "extractPluralCount", "(", "$", "expr", ")", "{", "$", "parts", "=", "explode", "(", "';'", ",", "$", "expr", ",", "2", ")", ";", "$", "nplurals", "=", "explode", "(", "'='", ",", "trim", "(", "$", "parts", "[", "0", "]", ")", ",", "2", ")", ";", "if", "(", "strtolower", "(", "rtrim", "(", "$", "nplurals", "[", "0", "]", ")", ")", "!=", "'nplurals'", ")", "{", "return", "1", ";", "}", "if", "(", "count", "(", "$", "nplurals", ")", "==", "1", ")", "{", "return", "1", ";", "}", "return", "intval", "(", "$", "nplurals", "[", "1", "]", ")", ";", "}" ]
Extracts number of plurals from plurals form expression. @param string $expr Expression to process @return int Total number of plurals
[ "Extracts", "number", "of", "plurals", "from", "plurals", "form", "expression", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L208-L220
35,923
phpmyadmin/motranslator
src/Translator.php
Translator.extractPluralsForms
public static function extractPluralsForms($header) { $headers = explode("\n", $header); $expr = 'nplurals=2; plural=n == 1 ? 0 : 1;'; foreach ($headers as $header) { if (stripos($header, 'Plural-Forms:') === 0) { $expr = substr($header, 13); } } return $expr; }
php
public static function extractPluralsForms($header) { $headers = explode("\n", $header); $expr = 'nplurals=2; plural=n == 1 ? 0 : 1;'; foreach ($headers as $header) { if (stripos($header, 'Plural-Forms:') === 0) { $expr = substr($header, 13); } } return $expr; }
[ "public", "static", "function", "extractPluralsForms", "(", "$", "header", ")", "{", "$", "headers", "=", "explode", "(", "\"\\n\"", ",", "$", "header", ")", ";", "$", "expr", "=", "'nplurals=2; plural=n == 1 ? 0 : 1;'", ";", "foreach", "(", "$", "headers", "as", "$", "header", ")", "{", "if", "(", "stripos", "(", "$", "header", ",", "'Plural-Forms:'", ")", "===", "0", ")", "{", "$", "expr", "=", "substr", "(", "$", "header", ",", "13", ")", ";", "}", "}", "return", "$", "expr", ";", "}" ]
Parse full PO header and extract only plural forms line. @param string $header Gettext header @return string verbatim plural form header field
[ "Parse", "full", "PO", "header", "and", "extract", "only", "plural", "forms", "line", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L229-L240
35,924
phpmyadmin/motranslator
src/Translator.php
Translator.getPluralForms
private function getPluralForms() { // lets assume message number 0 is header // this is true, right? // cache header field for plural forms if (is_null($this->pluralequation)) { if (isset($this->cache_translations[''])) { $header = $this->cache_translations['']; } else { $header = ''; } $expr = $this->extractPluralsForms($header); $this->pluralequation = $this->sanitizePluralExpression($expr); $this->pluralcount = $this->extractPluralCount($expr); } return $this->pluralequation; }
php
private function getPluralForms() { // lets assume message number 0 is header // this is true, right? // cache header field for plural forms if (is_null($this->pluralequation)) { if (isset($this->cache_translations[''])) { $header = $this->cache_translations['']; } else { $header = ''; } $expr = $this->extractPluralsForms($header); $this->pluralequation = $this->sanitizePluralExpression($expr); $this->pluralcount = $this->extractPluralCount($expr); } return $this->pluralequation; }
[ "private", "function", "getPluralForms", "(", ")", "{", "// lets assume message number 0 is header", "// this is true, right?", "// cache header field for plural forms", "if", "(", "is_null", "(", "$", "this", "->", "pluralequation", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "cache_translations", "[", "''", "]", ")", ")", "{", "$", "header", "=", "$", "this", "->", "cache_translations", "[", "''", "]", ";", "}", "else", "{", "$", "header", "=", "''", ";", "}", "$", "expr", "=", "$", "this", "->", "extractPluralsForms", "(", "$", "header", ")", ";", "$", "this", "->", "pluralequation", "=", "$", "this", "->", "sanitizePluralExpression", "(", "$", "expr", ")", ";", "$", "this", "->", "pluralcount", "=", "$", "this", "->", "extractPluralCount", "(", "$", "expr", ")", ";", "}", "return", "$", "this", "->", "pluralequation", ";", "}" ]
Get possible plural forms from MO header. @return string plural form header
[ "Get", "possible", "plural", "forms", "from", "MO", "header", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L247-L265
35,925
phpmyadmin/motranslator
src/Translator.php
Translator.selectString
private function selectString($n) { if (is_null($this->pluralexpression)) { $this->pluralexpression = new ExpressionLanguage(); } try { $plural = $this->pluralexpression->evaluate( $this->getPluralForms(), ['n' => $n] ); } catch (\Exception $e) { $plural = 0; } if ($plural >= $this->pluralcount) { $plural = $this->pluralcount - 1; } return $plural; }
php
private function selectString($n) { if (is_null($this->pluralexpression)) { $this->pluralexpression = new ExpressionLanguage(); } try { $plural = $this->pluralexpression->evaluate( $this->getPluralForms(), ['n' => $n] ); } catch (\Exception $e) { $plural = 0; } if ($plural >= $this->pluralcount) { $plural = $this->pluralcount - 1; } return $plural; }
[ "private", "function", "selectString", "(", "$", "n", ")", "{", "if", "(", "is_null", "(", "$", "this", "->", "pluralexpression", ")", ")", "{", "$", "this", "->", "pluralexpression", "=", "new", "ExpressionLanguage", "(", ")", ";", "}", "try", "{", "$", "plural", "=", "$", "this", "->", "pluralexpression", "->", "evaluate", "(", "$", "this", "->", "getPluralForms", "(", ")", ",", "[", "'n'", "=>", "$", "n", "]", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "plural", "=", "0", ";", "}", "if", "(", "$", "plural", ">=", "$", "this", "->", "pluralcount", ")", "{", "$", "plural", "=", "$", "this", "->", "pluralcount", "-", "1", ";", "}", "return", "$", "plural", ";", "}" ]
Detects which plural form to take. @param int $n count of objects @return int array index of the right plural form
[ "Detects", "which", "plural", "form", "to", "take", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L274-L293
35,926
phpmyadmin/motranslator
src/Translator.php
Translator.pgettext
public function pgettext($msgctxt, $msgid) { $key = implode(chr(4), [$msgctxt, $msgid]); $ret = $this->gettext($key); if (strpos($ret, chr(4)) !== false) { return $msgid; } return $ret; }
php
public function pgettext($msgctxt, $msgid) { $key = implode(chr(4), [$msgctxt, $msgid]); $ret = $this->gettext($key); if (strpos($ret, chr(4)) !== false) { return $msgid; } return $ret; }
[ "public", "function", "pgettext", "(", "$", "msgctxt", ",", "$", "msgid", ")", "{", "$", "key", "=", "implode", "(", "chr", "(", "4", ")", ",", "[", "$", "msgctxt", ",", "$", "msgid", "]", ")", ";", "$", "ret", "=", "$", "this", "->", "gettext", "(", "$", "key", ")", ";", "if", "(", "strpos", "(", "$", "ret", ",", "chr", "(", "4", ")", ")", "!==", "false", ")", "{", "return", "$", "msgid", ";", "}", "return", "$", "ret", ";", "}" ]
Translate with context. @param string $msgctxt Context @param string $msgid String to be translated @return string translated plural form
[ "Translate", "with", "context", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L333-L342
35,927
phpmyadmin/motranslator
src/Translator.php
Translator.npgettext
public function npgettext($msgctxt, $msgid, $msgidPlural, $number) { $key = implode(chr(4), [$msgctxt, $msgid]); $ret = $this->ngettext($key, $msgidPlural, $number); if (strpos($ret, chr(4)) !== false) { return $msgid; } return $ret; }
php
public function npgettext($msgctxt, $msgid, $msgidPlural, $number) { $key = implode(chr(4), [$msgctxt, $msgid]); $ret = $this->ngettext($key, $msgidPlural, $number); if (strpos($ret, chr(4)) !== false) { return $msgid; } return $ret; }
[ "public", "function", "npgettext", "(", "$", "msgctxt", ",", "$", "msgid", ",", "$", "msgidPlural", ",", "$", "number", ")", "{", "$", "key", "=", "implode", "(", "chr", "(", "4", ")", ",", "[", "$", "msgctxt", ",", "$", "msgid", "]", ")", ";", "$", "ret", "=", "$", "this", "->", "ngettext", "(", "$", "key", ",", "$", "msgidPlural", ",", "$", "number", ")", ";", "if", "(", "strpos", "(", "$", "ret", ",", "chr", "(", "4", ")", ")", "!==", "false", ")", "{", "return", "$", "msgid", ";", "}", "return", "$", "ret", ";", "}" ]
Plural version of pgettext. @param string $msgctxt Context @param string $msgid Single form @param string $msgidPlural Plural form @param int $number Number of objects @return string translated plural form
[ "Plural", "version", "of", "pgettext", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Translator.php#L354-L363
35,928
phpmyadmin/motranslator
src/StringReader.php
StringReader.read
public function read($pos, $bytes) { if ($pos + $bytes > $this->_len) { throw new ReaderException('Not enough bytes!'); } return substr($this->_str, $pos, $bytes); }
php
public function read($pos, $bytes) { if ($pos + $bytes > $this->_len) { throw new ReaderException('Not enough bytes!'); } return substr($this->_str, $pos, $bytes); }
[ "public", "function", "read", "(", "$", "pos", ",", "$", "bytes", ")", "{", "if", "(", "$", "pos", "+", "$", "bytes", ">", "$", "this", "->", "_len", ")", "{", "throw", "new", "ReaderException", "(", "'Not enough bytes!'", ")", ";", "}", "return", "substr", "(", "$", "this", "->", "_str", ",", "$", "pos", ",", "$", "bytes", ")", ";", "}" ]
Read number of bytes from given offset. @param int $pos Offset @param int $bytes Number of bytes to read @return string
[ "Read", "number", "of", "bytes", "from", "given", "offset", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L54-L61
35,929
phpmyadmin/motranslator
src/StringReader.php
StringReader.readint
public function readint($unpack, $pos) { $data = unpack($unpack, $this->read($pos, 4)); $result = $data[1]; /* We're reading unsigned int, but PHP will happily * give us negative number on 32-bit platforms. * * See also documentation: * https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes */ return $result < 0 ? PHP_INT_MAX : $result; }
php
public function readint($unpack, $pos) { $data = unpack($unpack, $this->read($pos, 4)); $result = $data[1]; /* We're reading unsigned int, but PHP will happily * give us negative number on 32-bit platforms. * * See also documentation: * https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes */ return $result < 0 ? PHP_INT_MAX : $result; }
[ "public", "function", "readint", "(", "$", "unpack", ",", "$", "pos", ")", "{", "$", "data", "=", "unpack", "(", "$", "unpack", ",", "$", "this", "->", "read", "(", "$", "pos", ",", "4", ")", ")", ";", "$", "result", "=", "$", "data", "[", "1", "]", ";", "/* We're reading unsigned int, but PHP will happily\n * give us negative number on 32-bit platforms.\n *\n * See also documentation:\n * https://secure.php.net/manual/en/function.unpack.php#refsect1-function.unpack-notes\n */", "return", "$", "result", "<", "0", "?", "PHP_INT_MAX", ":", "$", "result", ";", "}" ]
Reads a 32bit integer from the stream. @param string $unpack Unpack string @param int $pos Position @return int Ingerer from the stream
[ "Reads", "a", "32bit", "integer", "from", "the", "stream", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L71-L83
35,930
phpmyadmin/motranslator
src/StringReader.php
StringReader.readintarray
public function readintarray($unpack, $pos, $count) { return unpack($unpack . $count, $this->read($pos, 4 * $count)); }
php
public function readintarray($unpack, $pos, $count) { return unpack($unpack . $count, $this->read($pos, 4 * $count)); }
[ "public", "function", "readintarray", "(", "$", "unpack", ",", "$", "pos", ",", "$", "count", ")", "{", "return", "unpack", "(", "$", "unpack", ".", "$", "count", ",", "$", "this", "->", "read", "(", "$", "pos", ",", "4", "*", "$", "count", ")", ")", ";", "}" ]
Reads an array of integers from the stream. @param string $unpack Unpack string @param int $pos Position @param int $count How many elements should be read @return array Array of Integers
[ "Reads", "an", "array", "of", "integers", "from", "the", "stream", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/StringReader.php#L94-L97
35,931
nimbusoftltd/flysystem-openstack-swift
src/SwiftAdapter.php
SwiftAdapter.getObjectInstance
protected function getObjectInstance($path) { $location = $this->applyPathPrefix($path); $object = $this->container->getObject($location); return $object; }
php
protected function getObjectInstance($path) { $location = $this->applyPathPrefix($path); $object = $this->container->getObject($location); return $object; }
[ "protected", "function", "getObjectInstance", "(", "$", "path", ")", "{", "$", "location", "=", "$", "this", "->", "applyPathPrefix", "(", "$", "path", ")", ";", "$", "object", "=", "$", "this", "->", "container", "->", "getObject", "(", "$", "location", ")", ";", "return", "$", "object", ";", "}" ]
Get an object instance. @param string $path @return StorageObject
[ "Get", "an", "object", "instance", "." ]
7dbf0164245592104eead065ed56d0453b07f0da
https://github.com/nimbusoftltd/flysystem-openstack-swift/blob/7dbf0164245592104eead065ed56d0453b07f0da/src/SwiftAdapter.php#L262-L269
35,932
nimbusoftltd/flysystem-openstack-swift
src/SwiftAdapter.php
SwiftAdapter.normalizeObject
protected function normalizeObject(StorageObject $object) { $name = $this->removePathPrefix($object->name); $mimetype = explode('; ', $object->contentType); if ($object->lastModified instanceof \DateTimeInterface) { $timestamp = $object->lastModified->getTimestamp(); } else { $timestamp = strtotime($object->lastModified); } return [ 'type' => 'file', 'dirname' => Util::dirname($name), 'path' => $name, 'timestamp' => $timestamp, 'mimetype' => reset($mimetype), 'size' => $object->contentLength, ]; }
php
protected function normalizeObject(StorageObject $object) { $name = $this->removePathPrefix($object->name); $mimetype = explode('; ', $object->contentType); if ($object->lastModified instanceof \DateTimeInterface) { $timestamp = $object->lastModified->getTimestamp(); } else { $timestamp = strtotime($object->lastModified); } return [ 'type' => 'file', 'dirname' => Util::dirname($name), 'path' => $name, 'timestamp' => $timestamp, 'mimetype' => reset($mimetype), 'size' => $object->contentLength, ]; }
[ "protected", "function", "normalizeObject", "(", "StorageObject", "$", "object", ")", "{", "$", "name", "=", "$", "this", "->", "removePathPrefix", "(", "$", "object", "->", "name", ")", ";", "$", "mimetype", "=", "explode", "(", "'; '", ",", "$", "object", "->", "contentType", ")", ";", "if", "(", "$", "object", "->", "lastModified", "instanceof", "\\", "DateTimeInterface", ")", "{", "$", "timestamp", "=", "$", "object", "->", "lastModified", "->", "getTimestamp", "(", ")", ";", "}", "else", "{", "$", "timestamp", "=", "strtotime", "(", "$", "object", "->", "lastModified", ")", ";", "}", "return", "[", "'type'", "=>", "'file'", ",", "'dirname'", "=>", "Util", "::", "dirname", "(", "$", "name", ")", ",", "'path'", "=>", "$", "name", ",", "'timestamp'", "=>", "$", "timestamp", ",", "'mimetype'", "=>", "reset", "(", "$", "mimetype", ")", ",", "'size'", "=>", "$", "object", "->", "contentLength", ",", "]", ";", "}" ]
Normalize Openstack "StorageObject" object into an array @param StorageObject $object @return array
[ "Normalize", "Openstack", "StorageObject", "object", "into", "an", "array" ]
7dbf0164245592104eead065ed56d0453b07f0da
https://github.com/nimbusoftltd/flysystem-openstack-swift/blob/7dbf0164245592104eead065ed56d0453b07f0da/src/SwiftAdapter.php#L292-L311
35,933
phpmyadmin/motranslator
src/Loader.php
Loader.getTranslator
public function getTranslator($domain = '') { if (empty($domain)) { $domain = $this->default_domain; } if (! isset($this->domains[$this->locale])) { $this->domains[$this->locale] = []; } if (! isset($this->domains[$this->locale][$domain])) { if (isset($this->paths[$domain])) { $base = $this->paths[$domain]; } else { $base = './'; } $locale_names = $this->listLocales($this->locale); $filename = ''; foreach ($locale_names as $locale) { $filename = "$base/$locale/LC_MESSAGES/$domain.mo"; if (file_exists($filename)) { break; } } // We don't care about invalid path, we will get fallback // translator here $this->domains[$this->locale][$domain] = new Translator($filename); } return $this->domains[$this->locale][$domain]; }
php
public function getTranslator($domain = '') { if (empty($domain)) { $domain = $this->default_domain; } if (! isset($this->domains[$this->locale])) { $this->domains[$this->locale] = []; } if (! isset($this->domains[$this->locale][$domain])) { if (isset($this->paths[$domain])) { $base = $this->paths[$domain]; } else { $base = './'; } $locale_names = $this->listLocales($this->locale); $filename = ''; foreach ($locale_names as $locale) { $filename = "$base/$locale/LC_MESSAGES/$domain.mo"; if (file_exists($filename)) { break; } } // We don't care about invalid path, we will get fallback // translator here $this->domains[$this->locale][$domain] = new Translator($filename); } return $this->domains[$this->locale][$domain]; }
[ "public", "function", "getTranslator", "(", "$", "domain", "=", "''", ")", "{", "if", "(", "empty", "(", "$", "domain", ")", ")", "{", "$", "domain", "=", "$", "this", "->", "default_domain", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "domains", "[", "$", "this", "->", "locale", "]", ")", ")", "{", "$", "this", "->", "domains", "[", "$", "this", "->", "locale", "]", "=", "[", "]", ";", "}", "if", "(", "!", "isset", "(", "$", "this", "->", "domains", "[", "$", "this", "->", "locale", "]", "[", "$", "domain", "]", ")", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "paths", "[", "$", "domain", "]", ")", ")", "{", "$", "base", "=", "$", "this", "->", "paths", "[", "$", "domain", "]", ";", "}", "else", "{", "$", "base", "=", "'./'", ";", "}", "$", "locale_names", "=", "$", "this", "->", "listLocales", "(", "$", "this", "->", "locale", ")", ";", "$", "filename", "=", "''", ";", "foreach", "(", "$", "locale_names", "as", "$", "locale", ")", "{", "$", "filename", "=", "\"$base/$locale/LC_MESSAGES/$domain.mo\"", ";", "if", "(", "file_exists", "(", "$", "filename", ")", ")", "{", "break", ";", "}", "}", "// We don't care about invalid path, we will get fallback", "// translator here", "$", "this", "->", "domains", "[", "$", "this", "->", "locale", "]", "[", "$", "domain", "]", "=", "new", "Translator", "(", "$", "filename", ")", ";", "}", "return", "$", "this", "->", "domains", "[", "$", "this", "->", "locale", "]", "[", "$", "domain", "]", ";", "}" ]
Returns Translator object for domain or for default domain. @param string $domain Translation domain @return Translator
[ "Returns", "Translator", "object", "for", "domain", "or", "for", "default", "domain", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Loader.php#L155-L188
35,934
phpmyadmin/motranslator
src/Loader.php
Loader.detectlocale
public function detectlocale() { if (isset($GLOBALS['lang'])) { return $GLOBALS['lang']; } elseif (getenv('LC_ALL')) { return getenv('LC_ALL'); } elseif (getenv('LC_MESSAGES')) { return getenv('LC_MESSAGES'); } elseif (getenv('LANG')) { return getenv('LANG'); } return 'en'; }
php
public function detectlocale() { if (isset($GLOBALS['lang'])) { return $GLOBALS['lang']; } elseif (getenv('LC_ALL')) { return getenv('LC_ALL'); } elseif (getenv('LC_MESSAGES')) { return getenv('LC_MESSAGES'); } elseif (getenv('LANG')) { return getenv('LANG'); } return 'en'; }
[ "public", "function", "detectlocale", "(", ")", "{", "if", "(", "isset", "(", "$", "GLOBALS", "[", "'lang'", "]", ")", ")", "{", "return", "$", "GLOBALS", "[", "'lang'", "]", ";", "}", "elseif", "(", "getenv", "(", "'LC_ALL'", ")", ")", "{", "return", "getenv", "(", "'LC_ALL'", ")", ";", "}", "elseif", "(", "getenv", "(", "'LC_MESSAGES'", ")", ")", "{", "return", "getenv", "(", "'LC_MESSAGES'", ")", ";", "}", "elseif", "(", "getenv", "(", "'LANG'", ")", ")", "{", "return", "getenv", "(", "'LANG'", ")", ";", "}", "return", "'en'", ";", "}" ]
Detects currently configured locale. It checks: - global lang variable - environment for LC_ALL, LC_MESSAGES and LANG @return string with locale name
[ "Detects", "currently", "configured", "locale", "." ]
3938b916952f22234bf461541d30eb1889cc1f4a
https://github.com/phpmyadmin/motranslator/blob/3938b916952f22234bf461541d30eb1889cc1f4a/src/Loader.php#L237-L250
35,935
mateusjatenee/php-json-feed
src/FeedItem.php
FeedItem.build
public function build() { return array_filter( $this->flatMap($this->acceptedProperties, function ($property) { return [$property => $this->getValueForProperty($property)]; }) ); }
php
public function build() { return array_filter( $this->flatMap($this->acceptedProperties, function ($property) { return [$property => $this->getValueForProperty($property)]; }) ); }
[ "public", "function", "build", "(", ")", "{", "return", "array_filter", "(", "$", "this", "->", "flatMap", "(", "$", "this", "->", "acceptedProperties", ",", "function", "(", "$", "property", ")", "{", "return", "[", "$", "property", "=>", "$", "this", "->", "getValueForProperty", "(", "$", "property", ")", "]", ";", "}", ")", ")", ";", "}" ]
Builds the structure of the feed item @return array
[ "Builds", "the", "structure", "of", "the", "feed", "item" ]
07281c090894e892be5b762b8fd93eda5a082033
https://github.com/mateusjatenee/php-json-feed/blob/07281c090894e892be5b762b8fd93eda5a082033/src/FeedItem.php#L58-L65
35,936
mateusjatenee/php-json-feed
src/JsonFeed.php
JsonFeed.build
public function build() { if (!$this->hasCorrectStructure()) { throw (new IncorrectFeedStructureException)->setProperties($this->getMissingProperties()); } return $this ->filterProperties() + ['version' => $this->getVersion(), 'items' => $this->buildItems()]; }
php
public function build() { if (!$this->hasCorrectStructure()) { throw (new IncorrectFeedStructureException)->setProperties($this->getMissingProperties()); } return $this ->filterProperties() + ['version' => $this->getVersion(), 'items' => $this->buildItems()]; }
[ "public", "function", "build", "(", ")", "{", "if", "(", "!", "$", "this", "->", "hasCorrectStructure", "(", ")", ")", "{", "throw", "(", "new", "IncorrectFeedStructureException", ")", "->", "setProperties", "(", "$", "this", "->", "getMissingProperties", "(", ")", ")", ";", "}", "return", "$", "this", "->", "filterProperties", "(", ")", "+", "[", "'version'", "=>", "$", "this", "->", "getVersion", "(", ")", ",", "'items'", "=>", "$", "this", "->", "buildItems", "(", ")", "]", ";", "}" ]
Builds a collection following the JSON Feed spec @throws \Mateusjatenee\JsonFeed\Exceptions\IncorrectFeedStructureException @return \Illuminate\Support\Collection
[ "Builds", "a", "collection", "following", "the", "JSON", "Feed", "spec" ]
07281c090894e892be5b762b8fd93eda5a082033
https://github.com/mateusjatenee/php-json-feed/blob/07281c090894e892be5b762b8fd93eda5a082033/src/JsonFeed.php#L74-L82
35,937
async-interop/event-loop
src/Loop.php
Loop.setFactory
public static function setFactory(DriverFactory $factory = null) { if (self::$level > 0) { throw new \RuntimeException("Setting a new factory while running isn't allowed!"); } self::$factory = $factory; // reset it here, it will be actually instantiated inside execute() or get() self::$driver = null; }
php
public static function setFactory(DriverFactory $factory = null) { if (self::$level > 0) { throw new \RuntimeException("Setting a new factory while running isn't allowed!"); } self::$factory = $factory; // reset it here, it will be actually instantiated inside execute() or get() self::$driver = null; }
[ "public", "static", "function", "setFactory", "(", "DriverFactory", "$", "factory", "=", "null", ")", "{", "if", "(", "self", "::", "$", "level", ">", "0", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "\"Setting a new factory while running isn't allowed!\"", ")", ";", "}", "self", "::", "$", "factory", "=", "$", "factory", ";", "// reset it here, it will be actually instantiated inside execute() or get()", "self", "::", "$", "driver", "=", "null", ";", "}" ]
Set the factory to be used to create a default drivers. Setting a factory is only allowed as long as no loop is currently running. Passing null will reset the default driver and remove the factory. The factory will be invoked if none is passed to `Loop::execute`. A default driver will be created to support synchronous waits in traditional applications. @param DriverFactory|null $factory New factory to replace the previous one.
[ "Set", "the", "factory", "to", "be", "used", "to", "create", "a", "default", "drivers", "." ]
ca3a70f6dc91f03336f33f040405b4d3ab4bff50
https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L43-L53
35,938
async-interop/event-loop
src/Loop.php
Loop.execute
public static function execute(callable $callback, Driver $driver = null) { $previousDriver = self::$driver; self::$driver = $driver ?: self::createDriver(); self::$level++; try { self::$driver->defer($callback); self::$driver->run(); } finally { self::$driver = $previousDriver; self::$level--; } }
php
public static function execute(callable $callback, Driver $driver = null) { $previousDriver = self::$driver; self::$driver = $driver ?: self::createDriver(); self::$level++; try { self::$driver->defer($callback); self::$driver->run(); } finally { self::$driver = $previousDriver; self::$level--; } }
[ "public", "static", "function", "execute", "(", "callable", "$", "callback", ",", "Driver", "$", "driver", "=", "null", ")", "{", "$", "previousDriver", "=", "self", "::", "$", "driver", ";", "self", "::", "$", "driver", "=", "$", "driver", "?", ":", "self", "::", "createDriver", "(", ")", ";", "self", "::", "$", "level", "++", ";", "try", "{", "self", "::", "$", "driver", "->", "defer", "(", "$", "callback", ")", ";", "self", "::", "$", "driver", "->", "run", "(", ")", ";", "}", "finally", "{", "self", "::", "$", "driver", "=", "$", "previousDriver", ";", "self", "::", "$", "level", "--", ";", "}", "}" ]
Execute a callback within the scope of an event loop driver. The loop MUST continue to run until it is either stopped explicitly, no referenced watchers exist anymore, or an exception is thrown that cannot be handled. Exceptions that cannot be handled are exceptions thrown from an error handler or exceptions that would be passed to an error handler but none exists to handle them. @param callable $callback The callback to execute. @param Driver $driver The event loop driver. If `null`, a new one is created from the set factory. @return void @see \AsyncInterop\Loop::setFactory()
[ "Execute", "a", "callback", "within", "the", "scope", "of", "an", "event", "loop", "driver", "." ]
ca3a70f6dc91f03336f33f040405b4d3ab4bff50
https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L69-L83
35,939
async-interop/event-loop
src/Loop.php
Loop.createDriver
private static function createDriver() { if (self::$factory === null) { throw new \Exception("No loop driver factory set; Either pass a driver to Loop::execute or set a factory."); } $driver = self::$factory->create(); if (!$driver instanceof Driver) { $type = is_object($driver) ? "an instance of " . get_class($driver) : gettype($driver); throw new \Exception("Loop driver factory returned {$type}, but must return an instance of Driver."); } return $driver; }
php
private static function createDriver() { if (self::$factory === null) { throw new \Exception("No loop driver factory set; Either pass a driver to Loop::execute or set a factory."); } $driver = self::$factory->create(); if (!$driver instanceof Driver) { $type = is_object($driver) ? "an instance of " . get_class($driver) : gettype($driver); throw new \Exception("Loop driver factory returned {$type}, but must return an instance of Driver."); } return $driver; }
[ "private", "static", "function", "createDriver", "(", ")", "{", "if", "(", "self", "::", "$", "factory", "===", "null", ")", "{", "throw", "new", "\\", "Exception", "(", "\"No loop driver factory set; Either pass a driver to Loop::execute or set a factory.\"", ")", ";", "}", "$", "driver", "=", "self", "::", "$", "factory", "->", "create", "(", ")", ";", "if", "(", "!", "$", "driver", "instanceof", "Driver", ")", "{", "$", "type", "=", "is_object", "(", "$", "driver", ")", "?", "\"an instance of \"", ".", "get_class", "(", "$", "driver", ")", ":", "gettype", "(", "$", "driver", ")", ";", "throw", "new", "\\", "Exception", "(", "\"Loop driver factory returned {$type}, but must return an instance of Driver.\"", ")", ";", "}", "return", "$", "driver", ";", "}" ]
Create a new driver if a factory is present, otherwise throw. @return Driver @throws \Exception If no factory is set or no driver returned from factory.
[ "Create", "a", "new", "driver", "if", "a", "factory", "is", "present", "otherwise", "throw", "." ]
ca3a70f6dc91f03336f33f040405b4d3ab4bff50
https://github.com/async-interop/event-loop/blob/ca3a70f6dc91f03336f33f040405b4d3ab4bff50/src/Loop.php#L92-L106
35,940
traderinteractive/memoize-php
src/Predis.php
Predis.cache
private function cache(string $key, string $value, int $cacheTime = null) { try { $this->client->set($key, $value); if ($cacheTime !== null) { $this->client->expire($key, $cacheTime); } } catch (\Exception $e) { // We don't want exceptions in accessing the cache to break functionality. // The cache should be as transparent as possible. // If insight is needed into these exceptions, // a better way would be by notifying an observer with the errors. } }
php
private function cache(string $key, string $value, int $cacheTime = null) { try { $this->client->set($key, $value); if ($cacheTime !== null) { $this->client->expire($key, $cacheTime); } } catch (\Exception $e) { // We don't want exceptions in accessing the cache to break functionality. // The cache should be as transparent as possible. // If insight is needed into these exceptions, // a better way would be by notifying an observer with the errors. } }
[ "private", "function", "cache", "(", "string", "$", "key", ",", "string", "$", "value", ",", "int", "$", "cacheTime", "=", "null", ")", "{", "try", "{", "$", "this", "->", "client", "->", "set", "(", "$", "key", ",", "$", "value", ")", ";", "if", "(", "$", "cacheTime", "!==", "null", ")", "{", "$", "this", "->", "client", "->", "expire", "(", "$", "key", ",", "$", "cacheTime", ")", ";", "}", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "// We don't want exceptions in accessing the cache to break functionality.", "// The cache should be as transparent as possible.", "// If insight is needed into these exceptions,", "// a better way would be by notifying an observer with the errors.", "}", "}" ]
Caches the value into redis with errors suppressed. @param string $key The key. @param string $value The value. @param int $cacheTime The optional cache time @return void
[ "Caches", "the", "value", "into", "redis", "with", "errors", "suppressed", "." ]
0e8a29e372bb30255b93a09d704228741581a930
https://github.com/traderinteractive/memoize-php/blob/0e8a29e372bb30255b93a09d704228741581a930/src/Predis.php#L80-L94
35,941
br-monteiro/htr-core
src/Init/Bootstrap.php
Bootstrap.setUp
private function setUp(): self { fn::allowCors(); fn::allowHeader(); $this->configApp(); $this->configRoutes(); return $this; }
php
private function setUp(): self { fn::allowCors(); fn::allowHeader(); $this->configApp(); $this->configRoutes(); return $this; }
[ "private", "function", "setUp", "(", ")", ":", "self", "{", "fn", "::", "allowCors", "(", ")", ";", "fn", "::", "allowHeader", "(", ")", ";", "$", "this", "->", "configApp", "(", ")", ";", "$", "this", "->", "configRoutes", "(", ")", ";", "return", "$", "this", ";", "}" ]
SetUp the system @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @return $this
[ "SetUp", "the", "system" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Init/Bootstrap.php#L31-L39
35,942
chameleon-system/sanitycheck
src/Handler/CheckHandler.php
CheckHandler.doChecks
private function doChecks(array $checkList) { $retValue = array(); if (empty($checkList)) { $retValue[] = new CheckOutcome('message.nochecks', array(), CheckOutcome::NOTICE); return $retValue; } /** @var CheckInterface $check */ foreach ($checkList as $check) { try { $retValue = array_merge($retValue, $check->performCheck()); } catch (\Exception $e) { $retValue[] = new CheckOutcome( 'message.exception', array('%0%' => $e->getMessage()), CheckOutcome::EXCEPTION ); } } if (empty($retValue)) { $retValue[] = new CheckOutcome('message.nooutcome', array(), CheckOutcome::NOTICE); } return $retValue; }
php
private function doChecks(array $checkList) { $retValue = array(); if (empty($checkList)) { $retValue[] = new CheckOutcome('message.nochecks', array(), CheckOutcome::NOTICE); return $retValue; } /** @var CheckInterface $check */ foreach ($checkList as $check) { try { $retValue = array_merge($retValue, $check->performCheck()); } catch (\Exception $e) { $retValue[] = new CheckOutcome( 'message.exception', array('%0%' => $e->getMessage()), CheckOutcome::EXCEPTION ); } } if (empty($retValue)) { $retValue[] = new CheckOutcome('message.nooutcome', array(), CheckOutcome::NOTICE); } return $retValue; }
[ "private", "function", "doChecks", "(", "array", "$", "checkList", ")", "{", "$", "retValue", "=", "array", "(", ")", ";", "if", "(", "empty", "(", "$", "checkList", ")", ")", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'message.nochecks'", ",", "array", "(", ")", ",", "CheckOutcome", "::", "NOTICE", ")", ";", "return", "$", "retValue", ";", "}", "/** @var CheckInterface $check */", "foreach", "(", "$", "checkList", "as", "$", "check", ")", "{", "try", "{", "$", "retValue", "=", "array_merge", "(", "$", "retValue", ",", "$", "check", "->", "performCheck", "(", ")", ")", ";", "}", "catch", "(", "\\", "Exception", "$", "e", ")", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'message.exception'", ",", "array", "(", "'%0%'", "=>", "$", "e", "->", "getMessage", "(", ")", ")", ",", "CheckOutcome", "::", "EXCEPTION", ")", ";", "}", "}", "if", "(", "empty", "(", "$", "retValue", ")", ")", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'message.nooutcome'", ",", "array", "(", ")", ",", "CheckOutcome", "::", "NOTICE", ")", ";", "}", "return", "$", "retValue", ";", "}" ]
Does the actual work on the concrete and configured checks. @param $checkList [CheckInterface] @return CheckOutcome[]
[ "Does", "the", "actual", "work", "on", "the", "concrete", "and", "configured", "checks", "." ]
373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d
https://github.com/chameleon-system/sanitycheck/blob/373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d/src/Handler/CheckHandler.php#L97-L123
35,943
AeonDigital/PHP-Tools
src/JSON.php
JSON.indent
public static function indent(string $strJSON) : string { $strReturn = ""; $indentLevel = 0; $insideQuotes = false; $insideEscape = false; $endLineLevel = null; $utf8split = preg_split('//u', $strJSON, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0; $i < count($utf8split); $i++) { $c = $utf8split[$i]; $newLineLevel = null; $post = ""; if ($endLineLevel !== null) { $newLineLevel = $endLineLevel; $endLineLevel = null; } if ($insideEscape === true) { $insideEscape = false; } elseif ($c === '"') { $insideQuotes = !$insideQuotes; } elseif ($insideQuotes === false) { switch ($c) { case "}": case "]": $indentLevel--; $endLineLevel = null; $newLineLevel = $indentLevel; break; case "{": case "[": $indentLevel++; case ",": $endLineLevel = $indentLevel; break; case ":": $post = " "; break; case " ": case "\t": case "\n": case "\r": $c = ""; $endLineLevel = $newLineLevel; $newLineLevel = null; break; } } elseif ($c === "\\") { $insideEscape = true; } if ($newLineLevel !== null) { $strReturn .= "\n" . str_repeat("\t", $newLineLevel); } $strReturn .= $c . $post; } return $strReturn; }
php
public static function indent(string $strJSON) : string { $strReturn = ""; $indentLevel = 0; $insideQuotes = false; $insideEscape = false; $endLineLevel = null; $utf8split = preg_split('//u', $strJSON, -1, PREG_SPLIT_NO_EMPTY); for ($i = 0; $i < count($utf8split); $i++) { $c = $utf8split[$i]; $newLineLevel = null; $post = ""; if ($endLineLevel !== null) { $newLineLevel = $endLineLevel; $endLineLevel = null; } if ($insideEscape === true) { $insideEscape = false; } elseif ($c === '"') { $insideQuotes = !$insideQuotes; } elseif ($insideQuotes === false) { switch ($c) { case "}": case "]": $indentLevel--; $endLineLevel = null; $newLineLevel = $indentLevel; break; case "{": case "[": $indentLevel++; case ",": $endLineLevel = $indentLevel; break; case ":": $post = " "; break; case " ": case "\t": case "\n": case "\r": $c = ""; $endLineLevel = $newLineLevel; $newLineLevel = null; break; } } elseif ($c === "\\") { $insideEscape = true; } if ($newLineLevel !== null) { $strReturn .= "\n" . str_repeat("\t", $newLineLevel); } $strReturn .= $c . $post; } return $strReturn; }
[ "public", "static", "function", "indent", "(", "string", "$", "strJSON", ")", ":", "string", "{", "$", "strReturn", "=", "\"\"", ";", "$", "indentLevel", "=", "0", ";", "$", "insideQuotes", "=", "false", ";", "$", "insideEscape", "=", "false", ";", "$", "endLineLevel", "=", "null", ";", "$", "utf8split", "=", "preg_split", "(", "'//u'", ",", "$", "strJSON", ",", "-", "1", ",", "PREG_SPLIT_NO_EMPTY", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "count", "(", "$", "utf8split", ")", ";", "$", "i", "++", ")", "{", "$", "c", "=", "$", "utf8split", "[", "$", "i", "]", ";", "$", "newLineLevel", "=", "null", ";", "$", "post", "=", "\"\"", ";", "if", "(", "$", "endLineLevel", "!==", "null", ")", "{", "$", "newLineLevel", "=", "$", "endLineLevel", ";", "$", "endLineLevel", "=", "null", ";", "}", "if", "(", "$", "insideEscape", "===", "true", ")", "{", "$", "insideEscape", "=", "false", ";", "}", "elseif", "(", "$", "c", "===", "'\"'", ")", "{", "$", "insideQuotes", "=", "!", "$", "insideQuotes", ";", "}", "elseif", "(", "$", "insideQuotes", "===", "false", ")", "{", "switch", "(", "$", "c", ")", "{", "case", "\"}\"", ":", "case", "\"]\"", ":", "$", "indentLevel", "--", ";", "$", "endLineLevel", "=", "null", ";", "$", "newLineLevel", "=", "$", "indentLevel", ";", "break", ";", "case", "\"{\"", ":", "case", "\"[\"", ":", "$", "indentLevel", "++", ";", "case", "\",\"", ":", "$", "endLineLevel", "=", "$", "indentLevel", ";", "break", ";", "case", "\":\"", ":", "$", "post", "=", "\" \"", ";", "break", ";", "case", "\" \"", ":", "case", "\"\\t\"", ":", "case", "\"\\n\"", ":", "case", "\"\\r\"", ":", "$", "c", "=", "\"\"", ";", "$", "endLineLevel", "=", "$", "newLineLevel", ";", "$", "newLineLevel", "=", "null", ";", "break", ";", "}", "}", "elseif", "(", "$", "c", "===", "\"\\\\\"", ")", "{", "$", "insideEscape", "=", "true", ";", "}", "if", "(", "$", "newLineLevel", "!==", "null", ")", "{", "$", "strReturn", ".=", "\"\\n\"", ".", "str_repeat", "(", "\"\\t\"", ",", "$", "newLineLevel", ")", ";", "}", "$", "strReturn", ".=", "$", "c", ".", "$", "post", ";", "}", "return", "$", "strReturn", ";", "}" ]
Identa adequadamente uma string representante de um objeto JSON. @param string $strJSON String que será identada. @return string
[ "Identa", "adequadamente", "uma", "string", "representante", "de", "um", "objeto", "JSON", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/JSON.php#L80-L148
35,944
AeonDigital/PHP-Tools
src/JSON.php
JSON.save
public static function save(string $absoluteSystemPathToFile, $JSON, int $options = 0) : bool { $strJSON = $JSON; // Se o objeto passado não for uma string, converte-o if (is_string($JSON) === false) { $strJSON = json_encode($JSON, $options); } // Identa corretamente o objeto JSON $strJSON = self::indent($strJSON); // Salva-o no local definido. $r = file_put_contents($absoluteSystemPathToFile, $strJSON); return (($r === false) ? false : true); }
php
public static function save(string $absoluteSystemPathToFile, $JSON, int $options = 0) : bool { $strJSON = $JSON; // Se o objeto passado não for uma string, converte-o if (is_string($JSON) === false) { $strJSON = json_encode($JSON, $options); } // Identa corretamente o objeto JSON $strJSON = self::indent($strJSON); // Salva-o no local definido. $r = file_put_contents($absoluteSystemPathToFile, $strJSON); return (($r === false) ? false : true); }
[ "public", "static", "function", "save", "(", "string", "$", "absoluteSystemPathToFile", ",", "$", "JSON", ",", "int", "$", "options", "=", "0", ")", ":", "bool", "{", "$", "strJSON", "=", "$", "JSON", ";", "// Se o objeto passado não for uma string, converte-o", "if", "(", "is_string", "(", "$", "JSON", ")", "===", "false", ")", "{", "$", "strJSON", "=", "json_encode", "(", "$", "JSON", ",", "$", "options", ")", ";", "}", "// Identa corretamente o objeto JSON", "$", "strJSON", "=", "self", "::", "indent", "(", "$", "strJSON", ")", ";", "// Salva-o no local definido.", "$", "r", "=", "file_put_contents", "(", "$", "absoluteSystemPathToFile", ",", "$", "strJSON", ")", ";", "return", "(", "(", "$", "r", "===", "false", ")", "?", "false", ":", "true", ")", ";", "}" ]
Salva o um objeto JSON (representado por uma String, Array Associativo ou objeto "StdClass" no caminho informado. @param string $absoluteSystemPathToFile Caminho completo até o arquivo que será salvo. @param string|array|StdClass $JSON Objeto que será salvo como um arquivo JSON. @param int $options [Flags](http://php.net/manual/pt_BR/json.constants.php) para salvar o documeno JSON. @return bool
[ "Salva", "o", "um", "objeto", "JSON", "(", "representado", "por", "uma", "String", "Array", "Associativo", "ou", "objeto", "StdClass", "no", "caminho", "informado", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/JSON.php#L170-L186
35,945
CMProductions/http-client
src/RequestFactory.php
RequestFactory.create
public function create($serviceKey, $requestKey, array $parameters = []) { $config = $this->getParamOrFail($this->config, $serviceKey); $service = $this->getServiceParams($config); $request = $this->getRequestParams($config, $requestKey, $service); $uri = $this->buildUri($service['endpoint'], $request['path'], $request['query']); list($optionalParameters, $placeholders) = $this->separateParameters($request['body'], $parameters); $values = array_values($parameters); $body = $this->buildBody($request['body'], $request['headers'], $placeholders, $values, $optionalParameters); return $this->buildRequest( $request['method'], $this->replace($uri, $placeholders, $values), $this->replaceAll($request['headers'], $placeholders, $values), $body, $request['version'], $request['retries'], $request['options'], $serviceKey, $requestKey ); }
php
public function create($serviceKey, $requestKey, array $parameters = []) { $config = $this->getParamOrFail($this->config, $serviceKey); $service = $this->getServiceParams($config); $request = $this->getRequestParams($config, $requestKey, $service); $uri = $this->buildUri($service['endpoint'], $request['path'], $request['query']); list($optionalParameters, $placeholders) = $this->separateParameters($request['body'], $parameters); $values = array_values($parameters); $body = $this->buildBody($request['body'], $request['headers'], $placeholders, $values, $optionalParameters); return $this->buildRequest( $request['method'], $this->replace($uri, $placeholders, $values), $this->replaceAll($request['headers'], $placeholders, $values), $body, $request['version'], $request['retries'], $request['options'], $serviceKey, $requestKey ); }
[ "public", "function", "create", "(", "$", "serviceKey", ",", "$", "requestKey", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "$", "config", "=", "$", "this", "->", "getParamOrFail", "(", "$", "this", "->", "config", ",", "$", "serviceKey", ")", ";", "$", "service", "=", "$", "this", "->", "getServiceParams", "(", "$", "config", ")", ";", "$", "request", "=", "$", "this", "->", "getRequestParams", "(", "$", "config", ",", "$", "requestKey", ",", "$", "service", ")", ";", "$", "uri", "=", "$", "this", "->", "buildUri", "(", "$", "service", "[", "'endpoint'", "]", ",", "$", "request", "[", "'path'", "]", ",", "$", "request", "[", "'query'", "]", ")", ";", "list", "(", "$", "optionalParameters", ",", "$", "placeholders", ")", "=", "$", "this", "->", "separateParameters", "(", "$", "request", "[", "'body'", "]", ",", "$", "parameters", ")", ";", "$", "values", "=", "array_values", "(", "$", "parameters", ")", ";", "$", "body", "=", "$", "this", "->", "buildBody", "(", "$", "request", "[", "'body'", "]", ",", "$", "request", "[", "'headers'", "]", ",", "$", "placeholders", ",", "$", "values", ",", "$", "optionalParameters", ")", ";", "return", "$", "this", "->", "buildRequest", "(", "$", "request", "[", "'method'", "]", ",", "$", "this", "->", "replace", "(", "$", "uri", ",", "$", "placeholders", ",", "$", "values", ")", ",", "$", "this", "->", "replaceAll", "(", "$", "request", "[", "'headers'", "]", ",", "$", "placeholders", ",", "$", "values", ")", ",", "$", "body", ",", "$", "request", "[", "'version'", "]", ",", "$", "request", "[", "'retries'", "]", ",", "$", "request", "[", "'options'", "]", ",", "$", "serviceKey", ",", "$", "requestKey", ")", ";", "}" ]
Builds a request based on the service and request name, with the given parameters @param string $serviceKey @param string $requestKey @param array $parameters @return Request
[ "Builds", "a", "request", "based", "on", "the", "service", "and", "request", "name", "with", "the", "given", "parameters" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/RequestFactory.php#L35-L58
35,946
Orbitale/DoctrineTools
AbstractFixture.php
AbstractFixture.fixtureObject
private function fixtureObject(array $data): void { $obj = $this->createNewInstance($data); // Sometimes keys are specified in fixtures. // We must make sure Doctrine will force them to be saved. // Support for non-composite primary keys only. // /!\ Be careful, this will override the generator type for ALL objects of the same entity class! // This means that it _may_ break objects for which ids are not provided in the fixtures. $metadata = $this->manager->getClassMetadata($this->getEntityClass()); $primaryKey = $metadata->getIdentifierFieldNames(); if (1 === \count($primaryKey) && isset($data[$primaryKey[0]])) { $metadata->setIdGeneratorType($metadata::GENERATOR_TYPE_NONE); $metadata->setIdGenerator(new AssignedGenerator()); } // And finally we persist the item $this->manager->persist($obj); // If we need to flush it, then we do it too. if ( $this->numberOfIteratedObjects > 0 && $this->flushEveryXIterations() > 0 && $this->numberOfIteratedObjects % $this->flushEveryXIterations() === 0 ) { $this->manager->flush(); if ($this->clearEMOnFlush) { $this->manager->clear(); } } // If we have to add a reference, we do it if ($prefix = $this->getReferencePrefix()) { $methodName = $this->getMethodNameForReference(); $reference = null; if (method_exists($obj, $methodName)) { $reference = $obj->{$methodName}(); } elseif (method_exists($obj, '__toString')) { $reference = (string) $obj; } if (!$reference) { throw new RuntimeException(sprintf( 'If you want to specify a reference with prefix "%s", method "%s" or "%s" must exist in the class, or you can override the "%s" method and add your own.', $prefix, $methodName, '__toString()', 'getMethodNameForReference' )); } $this->addReference($prefix.$reference, $obj); } }
php
private function fixtureObject(array $data): void { $obj = $this->createNewInstance($data); // Sometimes keys are specified in fixtures. // We must make sure Doctrine will force them to be saved. // Support for non-composite primary keys only. // /!\ Be careful, this will override the generator type for ALL objects of the same entity class! // This means that it _may_ break objects for which ids are not provided in the fixtures. $metadata = $this->manager->getClassMetadata($this->getEntityClass()); $primaryKey = $metadata->getIdentifierFieldNames(); if (1 === \count($primaryKey) && isset($data[$primaryKey[0]])) { $metadata->setIdGeneratorType($metadata::GENERATOR_TYPE_NONE); $metadata->setIdGenerator(new AssignedGenerator()); } // And finally we persist the item $this->manager->persist($obj); // If we need to flush it, then we do it too. if ( $this->numberOfIteratedObjects > 0 && $this->flushEveryXIterations() > 0 && $this->numberOfIteratedObjects % $this->flushEveryXIterations() === 0 ) { $this->manager->flush(); if ($this->clearEMOnFlush) { $this->manager->clear(); } } // If we have to add a reference, we do it if ($prefix = $this->getReferencePrefix()) { $methodName = $this->getMethodNameForReference(); $reference = null; if (method_exists($obj, $methodName)) { $reference = $obj->{$methodName}(); } elseif (method_exists($obj, '__toString')) { $reference = (string) $obj; } if (!$reference) { throw new RuntimeException(sprintf( 'If you want to specify a reference with prefix "%s", method "%s" or "%s" must exist in the class, or you can override the "%s" method and add your own.', $prefix, $methodName, '__toString()', 'getMethodNameForReference' )); } $this->addReference($prefix.$reference, $obj); } }
[ "private", "function", "fixtureObject", "(", "array", "$", "data", ")", ":", "void", "{", "$", "obj", "=", "$", "this", "->", "createNewInstance", "(", "$", "data", ")", ";", "// Sometimes keys are specified in fixtures.", "// We must make sure Doctrine will force them to be saved.", "// Support for non-composite primary keys only.", "// /!\\ Be careful, this will override the generator type for ALL objects of the same entity class!", "// This means that it _may_ break objects for which ids are not provided in the fixtures.", "$", "metadata", "=", "$", "this", "->", "manager", "->", "getClassMetadata", "(", "$", "this", "->", "getEntityClass", "(", ")", ")", ";", "$", "primaryKey", "=", "$", "metadata", "->", "getIdentifierFieldNames", "(", ")", ";", "if", "(", "1", "===", "\\", "count", "(", "$", "primaryKey", ")", "&&", "isset", "(", "$", "data", "[", "$", "primaryKey", "[", "0", "]", "]", ")", ")", "{", "$", "metadata", "->", "setIdGeneratorType", "(", "$", "metadata", "::", "GENERATOR_TYPE_NONE", ")", ";", "$", "metadata", "->", "setIdGenerator", "(", "new", "AssignedGenerator", "(", ")", ")", ";", "}", "// And finally we persist the item", "$", "this", "->", "manager", "->", "persist", "(", "$", "obj", ")", ";", "// If we need to flush it, then we do it too.", "if", "(", "$", "this", "->", "numberOfIteratedObjects", ">", "0", "&&", "$", "this", "->", "flushEveryXIterations", "(", ")", ">", "0", "&&", "$", "this", "->", "numberOfIteratedObjects", "%", "$", "this", "->", "flushEveryXIterations", "(", ")", "===", "0", ")", "{", "$", "this", "->", "manager", "->", "flush", "(", ")", ";", "if", "(", "$", "this", "->", "clearEMOnFlush", ")", "{", "$", "this", "->", "manager", "->", "clear", "(", ")", ";", "}", "}", "// If we have to add a reference, we do it", "if", "(", "$", "prefix", "=", "$", "this", "->", "getReferencePrefix", "(", ")", ")", "{", "$", "methodName", "=", "$", "this", "->", "getMethodNameForReference", "(", ")", ";", "$", "reference", "=", "null", ";", "if", "(", "method_exists", "(", "$", "obj", ",", "$", "methodName", ")", ")", "{", "$", "reference", "=", "$", "obj", "->", "{", "$", "methodName", "}", "(", ")", ";", "}", "elseif", "(", "method_exists", "(", "$", "obj", ",", "'__toString'", ")", ")", "{", "$", "reference", "=", "(", "string", ")", "$", "obj", ";", "}", "if", "(", "!", "$", "reference", ")", "{", "throw", "new", "RuntimeException", "(", "sprintf", "(", "'If you want to specify a reference with prefix \"%s\", method \"%s\" or \"%s\" must exist in the class, or you can override the \"%s\" method and add your own.'", ",", "$", "prefix", ",", "$", "methodName", ",", "'__toString()'", ",", "'getMethodNameForReference'", ")", ")", ";", "}", "$", "this", "->", "addReference", "(", "$", "prefix", ".", "$", "reference", ",", "$", "obj", ")", ";", "}", "}" ]
Creates the object and persist it in database. @param object $data
[ "Creates", "the", "object", "and", "persist", "it", "in", "database", "." ]
517a321786073a9bc935bb0cb3014df4bb25dade
https://github.com/Orbitale/DoctrineTools/blob/517a321786073a9bc935bb0cb3014df4bb25dade/AbstractFixture.php#L119-L170
35,947
Orbitale/DoctrineTools
AbstractFixture.php
AbstractFixture.createNewInstance
protected function createNewInstance(array $data): object { $instance = self::getInstantiator()->instantiate($this->getEntityClass()); $refl = $this->getReflection(); foreach ($data as $key => $value) { $prop = $refl->getProperty($key); $prop->setAccessible(true); if ($value instanceof Closure) { $value = $value($instance, $this, $this->manager); } $prop->setValue($instance, $value); } return $instance; }
php
protected function createNewInstance(array $data): object { $instance = self::getInstantiator()->instantiate($this->getEntityClass()); $refl = $this->getReflection(); foreach ($data as $key => $value) { $prop = $refl->getProperty($key); $prop->setAccessible(true); if ($value instanceof Closure) { $value = $value($instance, $this, $this->manager); } $prop->setValue($instance, $value); } return $instance; }
[ "protected", "function", "createNewInstance", "(", "array", "$", "data", ")", ":", "object", "{", "$", "instance", "=", "self", "::", "getInstantiator", "(", ")", "->", "instantiate", "(", "$", "this", "->", "getEntityClass", "(", ")", ")", ";", "$", "refl", "=", "$", "this", "->", "getReflection", "(", ")", ";", "foreach", "(", "$", "data", "as", "$", "key", "=>", "$", "value", ")", "{", "$", "prop", "=", "$", "refl", "->", "getProperty", "(", "$", "key", ")", ";", "$", "prop", "->", "setAccessible", "(", "true", ")", ";", "if", "(", "$", "value", "instanceof", "Closure", ")", "{", "$", "value", "=", "$", "value", "(", "$", "instance", ",", "$", "this", ",", "$", "this", "->", "manager", ")", ";", "}", "$", "prop", "->", "setValue", "(", "$", "instance", ",", "$", "value", ")", ";", "}", "return", "$", "instance", ";", "}" ]
Creates a new instance of the class associated with the fixture. Override this method if you have constructor arguments to manage yourself depending on input data. @param array $data @return object
[ "Creates", "a", "new", "instance", "of", "the", "class", "associated", "with", "the", "fixture", ".", "Override", "this", "method", "if", "you", "have", "constructor", "arguments", "to", "manage", "yourself", "depending", "on", "input", "data", "." ]
517a321786073a9bc935bb0cb3014df4bb25dade
https://github.com/Orbitale/DoctrineTools/blob/517a321786073a9bc935bb0cb3014df4bb25dade/AbstractFixture.php#L251-L269
35,948
chameleon-system/sanitycheck
src/Check/DiskSpaceCheck.php
DiskSpaceCheck.checkDiskSpace
private function checkDiskSpace() { $retValue = array(); $freeSpace = disk_free_space($this->directory); $totalSpace = disk_total_space($this->directory); if (0 === $totalSpace) { $retValue[] = new CheckOutcome( 'check.disk_space.totalzero', array('%0%' => $this->directory), CheckOutcome::ERROR ); return $retValue; } $percentage = 100 * ($freeSpace / $totalSpace); $maxLevel = 0; $maxStrategy = self::STRATEGY_ABSOLUTE; foreach ($this->thresholdData as $level => $data) { $threshold = $data[0]; $strategy = $data[1]; switch ($strategy) { case self::STRATEGY_ABSOLUTE: if (($freeSpace < $threshold) && $level > $maxLevel) { $maxLevel = $level; $maxStrategy = self::STRATEGY_ABSOLUTE; } break; case self::STRATEGY_PERCENTAGE: if (($percentage < $threshold) && $level > $maxLevel) { $maxLevel = $level; $maxStrategy = self::STRATEGY_PERCENTAGE; } break; default: $retValue[] = new CheckOutcome( 'check.disk_space.invalid_strategy', array('%0%' => $strategy), CheckOutcome::ERROR ); break; } } if ($maxLevel > 0) { $retValue[] = new CheckOutcome( 'check.disk_space.lowspace', array( '%0%' => $this->directory, '%1%' => $this->formatSpaceLeft($freeSpace, $totalSpace, $maxStrategy), ), $maxLevel ); } else { $retValue[] = new CheckOutcome('check.disk_space.ok', array(), CheckOutcome::OK); } return $retValue; }
php
private function checkDiskSpace() { $retValue = array(); $freeSpace = disk_free_space($this->directory); $totalSpace = disk_total_space($this->directory); if (0 === $totalSpace) { $retValue[] = new CheckOutcome( 'check.disk_space.totalzero', array('%0%' => $this->directory), CheckOutcome::ERROR ); return $retValue; } $percentage = 100 * ($freeSpace / $totalSpace); $maxLevel = 0; $maxStrategy = self::STRATEGY_ABSOLUTE; foreach ($this->thresholdData as $level => $data) { $threshold = $data[0]; $strategy = $data[1]; switch ($strategy) { case self::STRATEGY_ABSOLUTE: if (($freeSpace < $threshold) && $level > $maxLevel) { $maxLevel = $level; $maxStrategy = self::STRATEGY_ABSOLUTE; } break; case self::STRATEGY_PERCENTAGE: if (($percentage < $threshold) && $level > $maxLevel) { $maxLevel = $level; $maxStrategy = self::STRATEGY_PERCENTAGE; } break; default: $retValue[] = new CheckOutcome( 'check.disk_space.invalid_strategy', array('%0%' => $strategy), CheckOutcome::ERROR ); break; } } if ($maxLevel > 0) { $retValue[] = new CheckOutcome( 'check.disk_space.lowspace', array( '%0%' => $this->directory, '%1%' => $this->formatSpaceLeft($freeSpace, $totalSpace, $maxStrategy), ), $maxLevel ); } else { $retValue[] = new CheckOutcome('check.disk_space.ok', array(), CheckOutcome::OK); } return $retValue; }
[ "private", "function", "checkDiskSpace", "(", ")", "{", "$", "retValue", "=", "array", "(", ")", ";", "$", "freeSpace", "=", "disk_free_space", "(", "$", "this", "->", "directory", ")", ";", "$", "totalSpace", "=", "disk_total_space", "(", "$", "this", "->", "directory", ")", ";", "if", "(", "0", "===", "$", "totalSpace", ")", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'check.disk_space.totalzero'", ",", "array", "(", "'%0%'", "=>", "$", "this", "->", "directory", ")", ",", "CheckOutcome", "::", "ERROR", ")", ";", "return", "$", "retValue", ";", "}", "$", "percentage", "=", "100", "*", "(", "$", "freeSpace", "/", "$", "totalSpace", ")", ";", "$", "maxLevel", "=", "0", ";", "$", "maxStrategy", "=", "self", "::", "STRATEGY_ABSOLUTE", ";", "foreach", "(", "$", "this", "->", "thresholdData", "as", "$", "level", "=>", "$", "data", ")", "{", "$", "threshold", "=", "$", "data", "[", "0", "]", ";", "$", "strategy", "=", "$", "data", "[", "1", "]", ";", "switch", "(", "$", "strategy", ")", "{", "case", "self", "::", "STRATEGY_ABSOLUTE", ":", "if", "(", "(", "$", "freeSpace", "<", "$", "threshold", ")", "&&", "$", "level", ">", "$", "maxLevel", ")", "{", "$", "maxLevel", "=", "$", "level", ";", "$", "maxStrategy", "=", "self", "::", "STRATEGY_ABSOLUTE", ";", "}", "break", ";", "case", "self", "::", "STRATEGY_PERCENTAGE", ":", "if", "(", "(", "$", "percentage", "<", "$", "threshold", ")", "&&", "$", "level", ">", "$", "maxLevel", ")", "{", "$", "maxLevel", "=", "$", "level", ";", "$", "maxStrategy", "=", "self", "::", "STRATEGY_PERCENTAGE", ";", "}", "break", ";", "default", ":", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'check.disk_space.invalid_strategy'", ",", "array", "(", "'%0%'", "=>", "$", "strategy", ")", ",", "CheckOutcome", "::", "ERROR", ")", ";", "break", ";", "}", "}", "if", "(", "$", "maxLevel", ">", "0", ")", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'check.disk_space.lowspace'", ",", "array", "(", "'%0%'", "=>", "$", "this", "->", "directory", ",", "'%1%'", "=>", "$", "this", "->", "formatSpaceLeft", "(", "$", "freeSpace", ",", "$", "totalSpace", ",", "$", "maxStrategy", ")", ",", ")", ",", "$", "maxLevel", ")", ";", "}", "else", "{", "$", "retValue", "[", "]", "=", "new", "CheckOutcome", "(", "'check.disk_space.ok'", ",", "array", "(", ")", ",", "CheckOutcome", "::", "OK", ")", ";", "}", "return", "$", "retValue", ";", "}" ]
Checks the space left on the disk given by the configured directory. @return array
[ "Checks", "the", "space", "left", "on", "the", "disk", "given", "by", "the", "configured", "directory", "." ]
373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d
https://github.com/chameleon-system/sanitycheck/blob/373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d/src/Check/DiskSpaceCheck.php#L100-L158
35,949
br-monteiro/htr-core
src/Common/ValidateAuthentication.php
ValidateAuthentication.token
public static function token(Request $request) { $authorization = $request->getHeader('Authorization'); if (!isset($authorization[0])) { throw new HeaderWithoutAuthorizationException('The request does not contain the Authorization header'); } $token = preg_replace('/^\w+\s/', '', $authorization[0]); return Authenticator::decodeToken($token); }
php
public static function token(Request $request) { $authorization = $request->getHeader('Authorization'); if (!isset($authorization[0])) { throw new HeaderWithoutAuthorizationException('The request does not contain the Authorization header'); } $token = preg_replace('/^\w+\s/', '', $authorization[0]); return Authenticator::decodeToken($token); }
[ "public", "static", "function", "token", "(", "Request", "$", "request", ")", "{", "$", "authorization", "=", "$", "request", "->", "getHeader", "(", "'Authorization'", ")", ";", "if", "(", "!", "isset", "(", "$", "authorization", "[", "0", "]", ")", ")", "{", "throw", "new", "HeaderWithoutAuthorizationException", "(", "'The request does not contain the Authorization header'", ")", ";", "}", "$", "token", "=", "preg_replace", "(", "'/^\\w+\\s/'", ",", "''", ",", "$", "authorization", "[", "0", "]", ")", ";", "return", "Authenticator", "::", "decodeToken", "(", "$", "token", ")", ";", "}" ]
Returns the data of token passed on Request @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param Request $request @return \stdClass @throws HeaderWithoutAuthorizationException
[ "Returns", "the", "data", "of", "token", "passed", "on", "Request" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Common/ValidateAuthentication.php#L27-L38
35,950
br-monteiro/htr-core
src/Common/ValidateAuthentication.php
ValidateAuthentication.user
public static function user(Request $request) { try { $data = self::token($request); $repository = db::em()->getRepository(cfg::USER_ENTITY); return $repository->find($data->data->id ?? 0); } catch (HeaderWithoutAuthorizationException $ex) { return false; } }
php
public static function user(Request $request) { try { $data = self::token($request); $repository = db::em()->getRepository(cfg::USER_ENTITY); return $repository->find($data->data->id ?? 0); } catch (HeaderWithoutAuthorizationException $ex) { return false; } }
[ "public", "static", "function", "user", "(", "Request", "$", "request", ")", "{", "try", "{", "$", "data", "=", "self", "::", "token", "(", "$", "request", ")", ";", "$", "repository", "=", "db", "::", "em", "(", ")", "->", "getRepository", "(", "cfg", "::", "USER_ENTITY", ")", ";", "return", "$", "repository", "->", "find", "(", "$", "data", "->", "data", "->", "id", "??", "0", ")", ";", "}", "catch", "(", "HeaderWithoutAuthorizationException", "$", "ex", ")", "{", "return", "false", ";", "}", "}" ]
Returns the data of User according Database @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0 @param Request $request @return boolean|{UserEntity}
[ "Returns", "the", "data", "of", "User", "according", "Database" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Common/ValidateAuthentication.php#L47-L57
35,951
electro-modules/matisse-components
MatisseComponents/Models/File.php
File.scopeOfField
public function scopeOfField ($query, $fieldName) { $fieldName = str_segmentsLast ($fieldName, '.'); return exists ($fieldName) ? $query->where ('group', $fieldName) : $query; }
php
public function scopeOfField ($query, $fieldName) { $fieldName = str_segmentsLast ($fieldName, '.'); return exists ($fieldName) ? $query->where ('group', $fieldName) : $query; }
[ "public", "function", "scopeOfField", "(", "$", "query", ",", "$", "fieldName", ")", "{", "$", "fieldName", "=", "str_segmentsLast", "(", "$", "fieldName", ",", "'.'", ")", ";", "return", "exists", "(", "$", "fieldName", ")", "?", "$", "query", "->", "where", "(", "'group'", ",", "$", "fieldName", ")", ":", "$", "query", ";", "}" ]
A query scope that restricts results to files bound to a specific field on the owner model. @param Builder $query @param string $fieldName @return mixed
[ "A", "query", "scope", "that", "restricts", "results", "to", "files", "bound", "to", "a", "specific", "field", "on", "the", "owner", "model", "." ]
3a746f796157ef72b585a5994394483fbe500861
https://github.com/electro-modules/matisse-components/blob/3a746f796157ef72b585a5994394483fbe500861/MatisseComponents/Models/File.php#L101-L105
35,952
stubbles/stubbles-console
src/main/php/WorkingDirectory.php
WorkingDirectory.changeTo
public function changeTo(string $target): bool { if (file_exists($target) && @chdir($target) === true) { $this->current = $target; return true; } return false; }
php
public function changeTo(string $target): bool { if (file_exists($target) && @chdir($target) === true) { $this->current = $target; return true; } return false; }
[ "public", "function", "changeTo", "(", "string", "$", "target", ")", ":", "bool", "{", "if", "(", "file_exists", "(", "$", "target", ")", "&&", "@", "chdir", "(", "$", "target", ")", "===", "true", ")", "{", "$", "this", "->", "current", "=", "$", "target", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
change current working directory to given target Please note that this really has a side effect - it doesn't just change a value inside this object, it really changed the global current working directory for the whole PHP application! @param string $target directory to change current working directory to @return bool whether change was successful
[ "change", "current", "working", "directory", "to", "given", "target" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/WorkingDirectory.php#L65-L73
35,953
cedx/which.php
RoboFile.php
RoboFile.build
function build(): Result { $version = $this->taskSemVer('.semver')->setFormat('%M.%m.%p')->__toString(); return $this->taskReplaceInFile('bin/which')->regex("/const packageVersion = '\d+(\.\d+){2}'/")->to("const packageVersion = '$version'")->run(); }
php
function build(): Result { $version = $this->taskSemVer('.semver')->setFormat('%M.%m.%p')->__toString(); return $this->taskReplaceInFile('bin/which')->regex("/const packageVersion = '\d+(\.\d+){2}'/")->to("const packageVersion = '$version'")->run(); }
[ "function", "build", "(", ")", ":", "Result", "{", "$", "version", "=", "$", "this", "->", "taskSemVer", "(", "'.semver'", ")", "->", "setFormat", "(", "'%M.%m.%p'", ")", "->", "__toString", "(", ")", ";", "return", "$", "this", "->", "taskReplaceInFile", "(", "'bin/which'", ")", "->", "regex", "(", "\"/const packageVersion = '\\d+(\\.\\d+){2}'/\"", ")", "->", "to", "(", "\"const packageVersion = '$version'\"", ")", "->", "run", "(", ")", ";", "}" ]
Builds the project. @return Result The task result.
[ "Builds", "the", "project", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/RoboFile.php#L27-L30
35,954
AeonDigital/PHP-Tools
src/StringExtension.php
StringExtension.insert
public static function insert(string $s, int $i, string $n) : string { return mb_substr_replace($s, $n, $i, 0); }
php
public static function insert(string $s, int $i, string $n) : string { return mb_substr_replace($s, $n, $i, 0); }
[ "public", "static", "function", "insert", "(", "string", "$", "s", ",", "int", "$", "i", ",", "string", "$", "n", ")", ":", "string", "{", "return", "mb_substr_replace", "(", "$", "s", ",", "$", "n", ",", "$", "i", ",", "0", ")", ";", "}" ]
Insere uma string no indice indicado da string original. @param string $s String original. @param int $i Indice a partir de onde o texto novo será adicionado. @param string $n String que será adicionada naquela posição. @return string
[ "Insere", "uma", "string", "no", "indice", "indicado", "da", "string", "original", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/StringExtension.php#L47-L50
35,955
AeonDigital/PHP-Tools
src/StringExtension.php
StringExtension.remove
public static function remove(string $s, int $i, int $l) : string { return mb_substr_replace($s, "", $i, $l); }
php
public static function remove(string $s, int $i, int $l) : string { return mb_substr_replace($s, "", $i, $l); }
[ "public", "static", "function", "remove", "(", "string", "$", "s", ",", "int", "$", "i", ",", "int", "$", "l", ")", ":", "string", "{", "return", "mb_substr_replace", "(", "$", "s", ",", "\"\"", ",", "$", "i", ",", "$", "l", ")", ";", "}" ]
Remove uma cadeia de caracteres dentro dos limites indicados. @param string $s String original. @param int $i Índice onde começará o corte de caracteres. @param int $l Quantidade de caracteres que serão removidos. @return string
[ "Remove", "uma", "cadeia", "de", "caracteres", "dentro", "dos", "limites", "indicados", "." ]
502fad10aadb37fce98bd3994e866a8bfdc8dc00
https://github.com/AeonDigital/PHP-Tools/blob/502fad10aadb37fce98bd3994e866a8bfdc8dc00/src/StringExtension.php#L70-L73
35,956
chameleon-system/sanitycheck
src/Output/LogCheckOutput.php
LogCheckOutput.getLogLevel
protected function getLogLevel($outcomeLevel) { switch ($outcomeLevel) { case CheckOutcome::OK: return LogLevel::INFO; case CheckOutcome::NOTICE: return LogLevel::NOTICE; case CheckOutcome::WARNING: return LogLevel::WARNING; case CheckOutcome::ERROR: return LogLevel::ERROR; case CheckOutcome::EXCEPTION: return LogLevel::ERROR; default: return LogLevel::ERROR; } }
php
protected function getLogLevel($outcomeLevel) { switch ($outcomeLevel) { case CheckOutcome::OK: return LogLevel::INFO; case CheckOutcome::NOTICE: return LogLevel::NOTICE; case CheckOutcome::WARNING: return LogLevel::WARNING; case CheckOutcome::ERROR: return LogLevel::ERROR; case CheckOutcome::EXCEPTION: return LogLevel::ERROR; default: return LogLevel::ERROR; } }
[ "protected", "function", "getLogLevel", "(", "$", "outcomeLevel", ")", "{", "switch", "(", "$", "outcomeLevel", ")", "{", "case", "CheckOutcome", "::", "OK", ":", "return", "LogLevel", "::", "INFO", ";", "case", "CheckOutcome", "::", "NOTICE", ":", "return", "LogLevel", "::", "NOTICE", ";", "case", "CheckOutcome", "::", "WARNING", ":", "return", "LogLevel", "::", "WARNING", ";", "case", "CheckOutcome", "::", "ERROR", ":", "return", "LogLevel", "::", "ERROR", ";", "case", "CheckOutcome", "::", "EXCEPTION", ":", "return", "LogLevel", "::", "ERROR", ";", "default", ":", "return", "LogLevel", "::", "ERROR", ";", "}", "}" ]
Translates a given check level to a log level. @param int $outcomeLevel the outcome level @return string A log level as defined in Psr\Log\LogLevel
[ "Translates", "a", "given", "check", "level", "to", "a", "log", "level", "." ]
373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d
https://github.com/chameleon-system/sanitycheck/blob/373aee88ccd64f8b61a8001cd0c8c5af5ff0c59d/src/Output/LogCheckOutput.php#L77-L93
35,957
stubbles/stubbles-console
src/main/php/ConsoleApp.php
ConsoleApp.getBindingsForApp
protected static function getBindingsForApp(string $className): array { $bindings = parent::getBindingsForApp($className); $bindings[] = function(Binder $binder) { $binder->bind(InputStream::class) ->named('stdin') ->toInstance(ConsoleInputStream::forIn()); $binder->bind(OutputStream::class) ->named('stdout') ->toInstance(ConsoleOutputStream::forOut()); $binder->bind(OutputStream::class) ->named('stderr') ->toInstance(ConsoleOutputStream::forError()); }; return $bindings; }
php
protected static function getBindingsForApp(string $className): array { $bindings = parent::getBindingsForApp($className); $bindings[] = function(Binder $binder) { $binder->bind(InputStream::class) ->named('stdin') ->toInstance(ConsoleInputStream::forIn()); $binder->bind(OutputStream::class) ->named('stdout') ->toInstance(ConsoleOutputStream::forOut()); $binder->bind(OutputStream::class) ->named('stderr') ->toInstance(ConsoleOutputStream::forError()); }; return $bindings; }
[ "protected", "static", "function", "getBindingsForApp", "(", "string", "$", "className", ")", ":", "array", "{", "$", "bindings", "=", "parent", "::", "getBindingsForApp", "(", "$", "className", ")", ";", "$", "bindings", "[", "]", "=", "function", "(", "Binder", "$", "binder", ")", "{", "$", "binder", "->", "bind", "(", "InputStream", "::", "class", ")", "->", "named", "(", "'stdin'", ")", "->", "toInstance", "(", "ConsoleInputStream", "::", "forIn", "(", ")", ")", ";", "$", "binder", "->", "bind", "(", "OutputStream", "::", "class", ")", "->", "named", "(", "'stdout'", ")", "->", "toInstance", "(", "ConsoleOutputStream", "::", "forOut", "(", ")", ")", ";", "$", "binder", "->", "bind", "(", "OutputStream", "::", "class", ")", "->", "named", "(", "'stderr'", ")", "->", "toInstance", "(", "ConsoleOutputStream", "::", "forError", "(", ")", ")", ";", "}", ";", "return", "$", "bindings", ";", "}" ]
creates list of bindings from given class @internal @param string $className full qualified class name of class to create an instance of @return \stubbles\ioc\module\BindingModule[]
[ "creates", "list", "of", "bindings", "from", "given", "class" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/ConsoleApp.php#L59-L75
35,958
stubbles/stubbles-console
src/main/php/ConsoleOutputStream.php
ConsoleOutputStream.forError
public static function forError(): OutputStream { if (null === self::$err) { self::$err = self::create('php://stderr'); } return self::$err; }
php
public static function forError(): OutputStream { if (null === self::$err) { self::$err = self::create('php://stderr'); } return self::$err; }
[ "public", "static", "function", "forError", "(", ")", ":", "OutputStream", "{", "if", "(", "null", "===", "self", "::", "$", "err", ")", "{", "self", "::", "$", "err", "=", "self", "::", "create", "(", "'php://stderr'", ")", ";", "}", "return", "self", "::", "$", "err", ";", "}" ]
comfort method for getting a console error stream @return \stubbles\streams\OutputStream
[ "comfort", "method", "for", "getting", "a", "console", "error", "stream" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/ConsoleOutputStream.php#L62-L69
35,959
stubbles/stubbles-console
src/main/php/ConsoleOutputStream.php
ConsoleOutputStream.create
private static function create(string $target): OutputStream { $out = new self(fopen($target, 'w')); $encoding = self::detectOutputEncoding(); if ('UTF-8' !== $encoding) { $out = new EncodingOutputStream($out, $encoding . '//IGNORE'); } return $out; }
php
private static function create(string $target): OutputStream { $out = new self(fopen($target, 'w')); $encoding = self::detectOutputEncoding(); if ('UTF-8' !== $encoding) { $out = new EncodingOutputStream($out, $encoding . '//IGNORE'); } return $out; }
[ "private", "static", "function", "create", "(", "string", "$", "target", ")", ":", "OutputStream", "{", "$", "out", "=", "new", "self", "(", "fopen", "(", "$", "target", ",", "'w'", ")", ")", ";", "$", "encoding", "=", "self", "::", "detectOutputEncoding", "(", ")", ";", "if", "(", "'UTF-8'", "!==", "$", "encoding", ")", "{", "$", "out", "=", "new", "EncodingOutputStream", "(", "$", "out", ",", "$", "encoding", ".", "'//IGNORE'", ")", ";", "}", "return", "$", "out", ";", "}" ]
creates output stream with respect to output encoding @param string $target @return \stubbles\streams\OutputStream
[ "creates", "output", "stream", "with", "respect", "to", "output", "encoding" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/ConsoleOutputStream.php#L77-L86
35,960
edmondscommerce/phpqa
src/Helper.php
Helper.getProjectRootDirectory
public static function getProjectRootDirectory(): string { if (null === self::$projectRootDirectory) { $reflection = new \ReflectionClass(ClassLoader::class); self::$projectRootDirectory = \dirname((string)$reflection->getFileName(), 3); } return self::$projectRootDirectory; }
php
public static function getProjectRootDirectory(): string { if (null === self::$projectRootDirectory) { $reflection = new \ReflectionClass(ClassLoader::class); self::$projectRootDirectory = \dirname((string)$reflection->getFileName(), 3); } return self::$projectRootDirectory; }
[ "public", "static", "function", "getProjectRootDirectory", "(", ")", ":", "string", "{", "if", "(", "null", "===", "self", "::", "$", "projectRootDirectory", ")", "{", "$", "reflection", "=", "new", "\\", "ReflectionClass", "(", "ClassLoader", "::", "class", ")", ";", "self", "::", "$", "projectRootDirectory", "=", "\\", "dirname", "(", "(", "string", ")", "$", "reflection", "->", "getFileName", "(", ")", ",", "3", ")", ";", "}", "return", "self", "::", "$", "projectRootDirectory", ";", "}" ]
Get the absolute path to the root of the current project It does this by working from the Composer autoloader which we know will be in a certain place in `vendor` @return string @throws \Exception
[ "Get", "the", "absolute", "path", "to", "the", "root", "of", "the", "current", "project" ]
fdcaa19f7505d16f7c751991cc2e4d113891be91
https://github.com/edmondscommerce/phpqa/blob/fdcaa19f7505d16f7c751991cc2e4d113891be91/src/Helper.php#L22-L30
35,961
symbiote/php-wordpress-database-tools
src/WordpressUtility.php
WordpressUtility.utf8_json_encode
public static function utf8_json_encode($arr, $options = 0, $depth = 512) { // NOTE(Jake): Might be able to get more speed out of this (if need be) by making it just json_encode // and if it fails with JSON_ERROR_UTF8, then do the recursive walk $utf8_arr = $arr; array_walk_recursive($utf8_arr, array(__CLASS__, '_utf8_json_encode_recursive')); $result = json_encode($utf8_arr, $options, $depth); return $result; }
php
public static function utf8_json_encode($arr, $options = 0, $depth = 512) { // NOTE(Jake): Might be able to get more speed out of this (if need be) by making it just json_encode // and if it fails with JSON_ERROR_UTF8, then do the recursive walk $utf8_arr = $arr; array_walk_recursive($utf8_arr, array(__CLASS__, '_utf8_json_encode_recursive')); $result = json_encode($utf8_arr, $options, $depth); return $result; }
[ "public", "static", "function", "utf8_json_encode", "(", "$", "arr", ",", "$", "options", "=", "0", ",", "$", "depth", "=", "512", ")", "{", "// NOTE(Jake): Might be able to get more speed out of this (if need be) by making it just json_encode", "//\t\t\t and if it fails with JSON_ERROR_UTF8, then do the recursive walk", "$", "utf8_arr", "=", "$", "arr", ";", "array_walk_recursive", "(", "$", "utf8_arr", ",", "array", "(", "__CLASS__", ",", "'_utf8_json_encode_recursive'", ")", ")", ";", "$", "result", "=", "json_encode", "(", "$", "utf8_arr", ",", "$", "options", ",", "$", "depth", ")", ";", "return", "$", "result", ";", "}" ]
Encodes an array of data to be UTF8 over using html entities @var array
[ "Encodes", "an", "array", "of", "data", "to", "be", "UTF8", "over", "using", "html", "entities" ]
93b1ae969722d7235dbbe6374f381daea0e0d5d7
https://github.com/symbiote/php-wordpress-database-tools/blob/93b1ae969722d7235dbbe6374f381daea0e0d5d7/src/WordpressUtility.php#L102-L109
35,962
CMProductions/http-client
src/Client/Traits/RequestBuilderTrait.php
RequestBuilderTrait.createRequest
protected function createRequest($service, $requestId, array $parameters = []) { try { return $this->factory()->create($service, $requestId, $parameters); } catch (RuntimeException $exception) { $this->logBuildError($service, $requestId, $exception); throw $exception; } catch (\Exception $exception) { $this->logBuildError($service, $requestId, $exception); throw new RequestBuildException($exception); } }
php
protected function createRequest($service, $requestId, array $parameters = []) { try { return $this->factory()->create($service, $requestId, $parameters); } catch (RuntimeException $exception) { $this->logBuildError($service, $requestId, $exception); throw $exception; } catch (\Exception $exception) { $this->logBuildError($service, $requestId, $exception); throw new RequestBuildException($exception); } }
[ "protected", "function", "createRequest", "(", "$", "service", ",", "$", "requestId", ",", "array", "$", "parameters", "=", "[", "]", ")", "{", "try", "{", "return", "$", "this", "->", "factory", "(", ")", "->", "create", "(", "$", "service", ",", "$", "requestId", ",", "$", "parameters", ")", ";", "}", "catch", "(", "RuntimeException", "$", "exception", ")", "{", "$", "this", "->", "logBuildError", "(", "$", "service", ",", "$", "requestId", ",", "$", "exception", ")", ";", "throw", "$", "exception", ";", "}", "catch", "(", "\\", "Exception", "$", "exception", ")", "{", "$", "this", "->", "logBuildError", "(", "$", "service", ",", "$", "requestId", ",", "$", "exception", ")", ";", "throw", "new", "RequestBuildException", "(", "$", "exception", ")", ";", "}", "}" ]
Builds a request @param string $service @param string $requestId @param array $parameters @return Request @throws RequestBuildException @throws RuntimeException
[ "Builds", "a", "request" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/Client/Traits/RequestBuilderTrait.php#L35-L46
35,963
br-monteiro/htr-core
src/Database/EntityAbstract.php
EntityAbstract.configEntityManager
private static function configEntityManager() { if (self::$entityManager) { return; } $isDevMode = cfg::htrFileConfigs()->devmode ?? false; $paths = [cfg::baseDir() . cfg::PATH_ENTITIES]; // the connection configuration if ($isDevMode) { $dbParams = cfg::DATABASE_CONFIGS_DEV; } else { $dbParams = cfg::DATABASE_CONFIGS_PRD; } $cache = new ArrayCache(); $reader = new AnnotationReader(); $driver = new AnnotationDriver($reader, $paths); $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); $config->setMetadataDriverImpl($driver); self::$entityManager = EntityManager::create($dbParams, $config); }
php
private static function configEntityManager() { if (self::$entityManager) { return; } $isDevMode = cfg::htrFileConfigs()->devmode ?? false; $paths = [cfg::baseDir() . cfg::PATH_ENTITIES]; // the connection configuration if ($isDevMode) { $dbParams = cfg::DATABASE_CONFIGS_DEV; } else { $dbParams = cfg::DATABASE_CONFIGS_PRD; } $cache = new ArrayCache(); $reader = new AnnotationReader(); $driver = new AnnotationDriver($reader, $paths); $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode); $config->setMetadataCacheImpl($cache); $config->setQueryCacheImpl($cache); $config->setMetadataDriverImpl($driver); self::$entityManager = EntityManager::create($dbParams, $config); }
[ "private", "static", "function", "configEntityManager", "(", ")", "{", "if", "(", "self", "::", "$", "entityManager", ")", "{", "return", ";", "}", "$", "isDevMode", "=", "cfg", "::", "htrFileConfigs", "(", ")", "->", "devmode", "??", "false", ";", "$", "paths", "=", "[", "cfg", "::", "baseDir", "(", ")", ".", "cfg", "::", "PATH_ENTITIES", "]", ";", "// the connection configuration", "if", "(", "$", "isDevMode", ")", "{", "$", "dbParams", "=", "cfg", "::", "DATABASE_CONFIGS_DEV", ";", "}", "else", "{", "$", "dbParams", "=", "cfg", "::", "DATABASE_CONFIGS_PRD", ";", "}", "$", "cache", "=", "new", "ArrayCache", "(", ")", ";", "$", "reader", "=", "new", "AnnotationReader", "(", ")", ";", "$", "driver", "=", "new", "AnnotationDriver", "(", "$", "reader", ",", "$", "paths", ")", ";", "$", "config", "=", "Setup", "::", "createAnnotationMetadataConfiguration", "(", "$", "paths", ",", "$", "isDevMode", ")", ";", "$", "config", "->", "setMetadataCacheImpl", "(", "$", "cache", ")", ";", "$", "config", "->", "setQueryCacheImpl", "(", "$", "cache", ")", ";", "$", "config", "->", "setMetadataDriverImpl", "(", "$", "driver", ")", ";", "self", "::", "$", "entityManager", "=", "EntityManager", "::", "create", "(", "$", "dbParams", ",", "$", "config", ")", ";", "}" ]
Config the Entity Manager of Doctrine @author Edson B S Monteiro <bruno.monteirodg@gmail.com> @since 1.0
[ "Config", "the", "Entity", "Manager", "of", "Doctrine" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Database/EntityAbstract.php#L22-L48
35,964
dmvdbrugge/dynamic-components
src/Executor.php
Executor.setInterval
public function setInterval(int $seconds, ?int $microseconds = null): void { if (func_num_args() === 1) { $microseconds = $seconds; $seconds = 0; } Assert::notNull($microseconds, 'Cannot set $microseconds to null. Set to 0 for no microseconds.'); parent::setInterval($seconds, $microseconds); $this->seconds = $seconds; $this->microseconds = $microseconds; }
php
public function setInterval(int $seconds, ?int $microseconds = null): void { if (func_num_args() === 1) { $microseconds = $seconds; $seconds = 0; } Assert::notNull($microseconds, 'Cannot set $microseconds to null. Set to 0 for no microseconds.'); parent::setInterval($seconds, $microseconds); $this->seconds = $seconds; $this->microseconds = $microseconds; }
[ "public", "function", "setInterval", "(", "int", "$", "seconds", ",", "?", "int", "$", "microseconds", "=", "null", ")", ":", "void", "{", "if", "(", "func_num_args", "(", ")", "===", "1", ")", "{", "$", "microseconds", "=", "$", "seconds", ";", "$", "seconds", "=", "0", ";", "}", "Assert", "::", "notNull", "(", "$", "microseconds", ",", "'Cannot set $microseconds to null. Set to 0 for no microseconds.'", ")", ";", "parent", "::", "setInterval", "(", "$", "seconds", ",", "$", "microseconds", ")", ";", "$", "this", "->", "seconds", "=", "$", "seconds", ";", "$", "this", "->", "microseconds", "=", "$", "microseconds", ";", "}" ]
Just like \UI\Executor, if you only give 1 param, it will be treated as microseconds.
[ "Just", "like", "\\", "UI", "\\", "Executor", "if", "you", "only", "give", "1", "param", "it", "will", "be", "treated", "as", "microseconds", "." ]
f5d6b48ee3ce16d15c60b637452873a9f2c75769
https://github.com/dmvdbrugge/dynamic-components/blob/f5d6b48ee3ce16d15c60b637452873a9f2c75769/src/Executor.php#L53-L65
35,965
netlogix/Netlogix.Cqrs
Classes/Netlogix/Cqrs/Log/CommandLogger.php
CommandLogger.logCommand
public function logCommand(AbstractCommand $command, \Exception $exception = null) { $commandLogEntry = $this->commandLogEntryRepository->findOneByCommand($command); $isNewObject = !$commandLogEntry; if ($isNewObject) { $commandLogEntry = new CommandLogEntry($command); } $commandLogEntry->setException($exception === null ? null : new ExceptionData($exception)); if ($isNewObject) { $this->commandLogEntryRepository->add($commandLogEntry); } else { $this->commandLogEntryRepository->update($commandLogEntry); } $this->entityManager->flush($commandLogEntry); }
php
public function logCommand(AbstractCommand $command, \Exception $exception = null) { $commandLogEntry = $this->commandLogEntryRepository->findOneByCommand($command); $isNewObject = !$commandLogEntry; if ($isNewObject) { $commandLogEntry = new CommandLogEntry($command); } $commandLogEntry->setException($exception === null ? null : new ExceptionData($exception)); if ($isNewObject) { $this->commandLogEntryRepository->add($commandLogEntry); } else { $this->commandLogEntryRepository->update($commandLogEntry); } $this->entityManager->flush($commandLogEntry); }
[ "public", "function", "logCommand", "(", "AbstractCommand", "$", "command", ",", "\\", "Exception", "$", "exception", "=", "null", ")", "{", "$", "commandLogEntry", "=", "$", "this", "->", "commandLogEntryRepository", "->", "findOneByCommand", "(", "$", "command", ")", ";", "$", "isNewObject", "=", "!", "$", "commandLogEntry", ";", "if", "(", "$", "isNewObject", ")", "{", "$", "commandLogEntry", "=", "new", "CommandLogEntry", "(", "$", "command", ")", ";", "}", "$", "commandLogEntry", "->", "setException", "(", "$", "exception", "===", "null", "?", "null", ":", "new", "ExceptionData", "(", "$", "exception", ")", ")", ";", "if", "(", "$", "isNewObject", ")", "{", "$", "this", "->", "commandLogEntryRepository", "->", "add", "(", "$", "commandLogEntry", ")", ";", "}", "else", "{", "$", "this", "->", "commandLogEntryRepository", "->", "update", "(", "$", "commandLogEntry", ")", ";", "}", "$", "this", "->", "entityManager", "->", "flush", "(", "$", "commandLogEntry", ")", ";", "}" ]
Log the given command @param AbstractCommand $command @param \Exception $exception
[ "Log", "the", "given", "command" ]
5f3a151c8189d744feb0ee802d6766450aaa4dd0
https://github.com/netlogix/Netlogix.Cqrs/blob/5f3a151c8189d744feb0ee802d6766450aaa4dd0/Classes/Netlogix/Cqrs/Log/CommandLogger.php#L35-L52
35,966
br-monteiro/htr-core
src/Common/HttpFunctions.php
HttpFunctions.allowCors
public static function allowCors() { $origin = filter_input(INPUT_SERVER, 'HTTP_ORIGIN'); $protocol = filter_input(INPUT_SERVER, 'REQUEST_SCHEME') ?? 'http'; $host = preg_replace("/^http(s)?:\/{2}/", "", $origin); $allowedHosts = cfg::ALLOW_CORS; $allowedHosts[] = cfg::HOST_DEV; if (in_array($host, $allowedHosts)) { header("Access-Control-Allow-Origin: " . $protocol . "://" . $host); } }
php
public static function allowCors() { $origin = filter_input(INPUT_SERVER, 'HTTP_ORIGIN'); $protocol = filter_input(INPUT_SERVER, 'REQUEST_SCHEME') ?? 'http'; $host = preg_replace("/^http(s)?:\/{2}/", "", $origin); $allowedHosts = cfg::ALLOW_CORS; $allowedHosts[] = cfg::HOST_DEV; if (in_array($host, $allowedHosts)) { header("Access-Control-Allow-Origin: " . $protocol . "://" . $host); } }
[ "public", "static", "function", "allowCors", "(", ")", "{", "$", "origin", "=", "filter_input", "(", "INPUT_SERVER", ",", "'HTTP_ORIGIN'", ")", ";", "$", "protocol", "=", "filter_input", "(", "INPUT_SERVER", ",", "'REQUEST_SCHEME'", ")", "??", "'http'", ";", "$", "host", "=", "preg_replace", "(", "\"/^http(s)?:\\/{2}/\"", ",", "\"\"", ",", "$", "origin", ")", ";", "$", "allowedHosts", "=", "cfg", "::", "ALLOW_CORS", ";", "$", "allowedHosts", "[", "]", "=", "cfg", "::", "HOST_DEV", ";", "if", "(", "in_array", "(", "$", "host", ",", "$", "allowedHosts", ")", ")", "{", "header", "(", "\"Access-Control-Allow-Origin: \"", ".", "$", "protocol", ".", "\"://\"", ".", "$", "host", ")", ";", "}", "}" ]
Set header Access-Control-Allow-Origin to Allowed hosts
[ "Set", "header", "Access", "-", "Control", "-", "Allow", "-", "Origin", "to", "Allowed", "hosts" ]
04c85684e9317fdc52c47aacb357661b4939fb4b
https://github.com/br-monteiro/htr-core/blob/04c85684e9317fdc52c47aacb357661b4939fb4b/src/Common/HttpFunctions.php#L12-L23
35,967
marczhermo/search-list
src/Client/MySQLClient.php
MySQLClient.createClient
public function createClient() { $indexConfig = ArrayList::create(Config::config()->get('indices')) ->filter(['name' => $this->indexName])->first(); $this->clientAPI = new DataList($indexConfig['class']); $this->indexConfig = $indexConfig; return $this->clientAPI; }
php
public function createClient() { $indexConfig = ArrayList::create(Config::config()->get('indices')) ->filter(['name' => $this->indexName])->first(); $this->clientAPI = new DataList($indexConfig['class']); $this->indexConfig = $indexConfig; return $this->clientAPI; }
[ "public", "function", "createClient", "(", ")", "{", "$", "indexConfig", "=", "ArrayList", "::", "create", "(", "Config", "::", "config", "(", ")", "->", "get", "(", "'indices'", ")", ")", "->", "filter", "(", "[", "'name'", "=>", "$", "this", "->", "indexName", "]", ")", "->", "first", "(", ")", ";", "$", "this", "->", "clientAPI", "=", "new", "DataList", "(", "$", "indexConfig", "[", "'class'", "]", ")", ";", "$", "this", "->", "indexConfig", "=", "$", "indexConfig", ";", "return", "$", "this", "->", "clientAPI", ";", "}" ]
Instantiates the Client Library API
[ "Instantiates", "the", "Client", "Library", "API" ]
851f42b021c5934a2905026d57feb85e595b8f80
https://github.com/marczhermo/search-list/blob/851f42b021c5934a2905026d57feb85e595b8f80/src/Client/MySQLClient.php#L22-L31
35,968
CharlotteDunois/Validator
src/Rules/Callback.php
Callback.prototype
static function prototype(callable $callable) { /** @var \ReflectionMethod|\ReflectionFunction $prototype */ if(\is_array($callable)) { $prototype = new \ReflectionMethod($callable[0], $callable[1]); } else { $prototype = new \ReflectionFunction($callable); } $signature = ''; /** @var \ReflectionParameter $param */ foreach($prototype->getParameters() as $param) { $type = $param->getType(); $signature .= ($type->allowsNull() ? '?' : '').$type->getName().($param->isOptional() ? '?' : '').','; } $signature = \substr($signature, 0, -1); $return = $prototype->getReturnType(); if($return !== null) { $signature .= '='.($return->allowsNull() ? '?' : '').$return->getName(); } if(empty($signature)) { throw new \InvalidArgumentException('Given callable has no signature to build'); } return $signature; }
php
static function prototype(callable $callable) { /** @var \ReflectionMethod|\ReflectionFunction $prototype */ if(\is_array($callable)) { $prototype = new \ReflectionMethod($callable[0], $callable[1]); } else { $prototype = new \ReflectionFunction($callable); } $signature = ''; /** @var \ReflectionParameter $param */ foreach($prototype->getParameters() as $param) { $type = $param->getType(); $signature .= ($type->allowsNull() ? '?' : '').$type->getName().($param->isOptional() ? '?' : '').','; } $signature = \substr($signature, 0, -1); $return = $prototype->getReturnType(); if($return !== null) { $signature .= '='.($return->allowsNull() ? '?' : '').$return->getName(); } if(empty($signature)) { throw new \InvalidArgumentException('Given callable has no signature to build'); } return $signature; }
[ "static", "function", "prototype", "(", "callable", "$", "callable", ")", "{", "/** @var \\ReflectionMethod|\\ReflectionFunction $prototype */", "if", "(", "\\", "is_array", "(", "$", "callable", ")", ")", "{", "$", "prototype", "=", "new", "\\", "ReflectionMethod", "(", "$", "callable", "[", "0", "]", ",", "$", "callable", "[", "1", "]", ")", ";", "}", "else", "{", "$", "prototype", "=", "new", "\\", "ReflectionFunction", "(", "$", "callable", ")", ";", "}", "$", "signature", "=", "''", ";", "/** @var \\ReflectionParameter $param */", "foreach", "(", "$", "prototype", "->", "getParameters", "(", ")", "as", "$", "param", ")", "{", "$", "type", "=", "$", "param", "->", "getType", "(", ")", ";", "$", "signature", ".=", "(", "$", "type", "->", "allowsNull", "(", ")", "?", "'?'", ":", "''", ")", ".", "$", "type", "->", "getName", "(", ")", ".", "(", "$", "param", "->", "isOptional", "(", ")", "?", "'?'", ":", "''", ")", ".", "','", ";", "}", "$", "signature", "=", "\\", "substr", "(", "$", "signature", ",", "0", ",", "-", "1", ")", ";", "$", "return", "=", "$", "prototype", "->", "getReturnType", "(", ")", ";", "if", "(", "$", "return", "!==", "null", ")", "{", "$", "signature", ".=", "'='", ".", "(", "$", "return", "->", "allowsNull", "(", ")", "?", "'?'", ":", "''", ")", ".", "$", "return", "->", "getName", "(", ")", ";", "}", "if", "(", "empty", "(", "$", "signature", ")", ")", "{", "throw", "new", "\\", "InvalidArgumentException", "(", "'Given callable has no signature to build'", ")", ";", "}", "return", "$", "signature", ";", "}" ]
Turns a callable into a callback signature. @param callable $callable @return string @throws \InvalidArgumentException
[ "Turns", "a", "callable", "into", "a", "callback", "signature", "." ]
0c7abddc87174039145bf0ce21d56937f1851365
https://github.com/CharlotteDunois/Validator/blob/0c7abddc87174039145bf0ce21d56937f1851365/src/Rules/Callback.php#L93-L122
35,969
honey-comb/starter
src/Repositories/Traits/HCQueryBuilderTrait.php
HCQueryBuilderTrait.checkForTrashed
protected function checkForTrashed(Builder $query, Request $request): Builder { if ($request->filled('trashed') && $request->input('trashed') === '1') { $query->onlyTrashed(); } return $query; }
php
protected function checkForTrashed(Builder $query, Request $request): Builder { if ($request->filled('trashed') && $request->input('trashed') === '1') { $query->onlyTrashed(); } return $query; }
[ "protected", "function", "checkForTrashed", "(", "Builder", "$", "query", ",", "Request", "$", "request", ")", ":", "Builder", "{", "if", "(", "$", "request", "->", "filled", "(", "'trashed'", ")", "&&", "$", "request", "->", "input", "(", "'trashed'", ")", "===", "'1'", ")", "{", "$", "query", "->", "onlyTrashed", "(", ")", ";", "}", "return", "$", "query", ";", "}" ]
Check for trashed records option @param Builder $query @param Request $request @return mixed
[ "Check", "for", "trashed", "records", "option" ]
2c5330a49eb5204a6b748368aca835b7ecb02393
https://github.com/honey-comb/starter/blob/2c5330a49eb5204a6b748368aca835b7ecb02393/src/Repositories/Traits/HCQueryBuilderTrait.php#L226-L233
35,970
GrottoPress/jentil
app/libraries/Jentil.php
Jentil.is
public function is(string $mode): bool { $rel_dir = $this->getUtilities()->fileSystem->relativeDir(); return ('package' === $mode && $rel_dir) || ('theme' === $mode && !$rel_dir); }
php
public function is(string $mode): bool { $rel_dir = $this->getUtilities()->fileSystem->relativeDir(); return ('package' === $mode && $rel_dir) || ('theme' === $mode && !$rel_dir); }
[ "public", "function", "is", "(", "string", "$", "mode", ")", ":", "bool", "{", "$", "rel_dir", "=", "$", "this", "->", "getUtilities", "(", ")", "->", "fileSystem", "->", "relativeDir", "(", ")", ";", "return", "(", "'package'", "===", "$", "mode", "&&", "$", "rel_dir", ")", "||", "(", "'theme'", "===", "$", "mode", "&&", "!", "$", "rel_dir", ")", ";", "}" ]
Checks if installed as 'theme' or as 'package'
[ "Checks", "if", "installed", "as", "theme", "or", "as", "package" ]
ad3341c91e0386256d4a2fbe8b7a201c9b706c10
https://github.com/GrottoPress/jentil/blob/ad3341c91e0386256d4a2fbe8b7a201c9b706c10/app/libraries/Jentil.php#L67-L74
35,971
bytic/omnipay-mobilpay
src/Models/Request.php
Request.buildAccessParameters
public function buildAccessParameters($public_key, &$env_key, &$enc_data) { $params = $this->builParametersList(); if (is_null($params)) { return false; } $src_data = Mobilpay_Payment_Request::buildQueryString($params); $enc_data = ''; $env_keys = []; $result = openssl_seal($src_data, $enc_data, $env_keys, array($public_key)); if ($result === false) { $env_key = null; $enc_data = null; return false; } $env_key = base64_encode($env_keys[0]); $enc_data = base64_encode($enc_data); return true; }
php
public function buildAccessParameters($public_key, &$env_key, &$enc_data) { $params = $this->builParametersList(); if (is_null($params)) { return false; } $src_data = Mobilpay_Payment_Request::buildQueryString($params); $enc_data = ''; $env_keys = []; $result = openssl_seal($src_data, $enc_data, $env_keys, array($public_key)); if ($result === false) { $env_key = null; $enc_data = null; return false; } $env_key = base64_encode($env_keys[0]); $enc_data = base64_encode($enc_data); return true; }
[ "public", "function", "buildAccessParameters", "(", "$", "public_key", ",", "&", "$", "env_key", ",", "&", "$", "enc_data", ")", "{", "$", "params", "=", "$", "this", "->", "builParametersList", "(", ")", ";", "if", "(", "is_null", "(", "$", "params", ")", ")", "{", "return", "false", ";", "}", "$", "src_data", "=", "Mobilpay_Payment_Request", "::", "buildQueryString", "(", "$", "params", ")", ";", "$", "enc_data", "=", "''", ";", "$", "env_keys", "=", "[", "]", ";", "$", "result", "=", "openssl_seal", "(", "$", "src_data", ",", "$", "enc_data", ",", "$", "env_keys", ",", "array", "(", "$", "public_key", ")", ")", ";", "if", "(", "$", "result", "===", "false", ")", "{", "$", "env_key", "=", "null", ";", "$", "enc_data", "=", "null", ";", "return", "false", ";", "}", "$", "env_key", "=", "base64_encode", "(", "$", "env_keys", "[", "0", "]", ")", ";", "$", "enc_data", "=", "base64_encode", "(", "$", "enc_data", ")", ";", "return", "true", ";", "}" ]
access Mobilpay.Ro secure payment portal @param resource $public_key - obtained by calling openssl_pkey_get_public @param string &$env_key - returns envelope key base64 encoded or null if function fails @param string &$enc_data - returns data to post base64 encoded or null if function fails @return boolean
[ "access", "Mobilpay", ".", "Ro", "secure", "payment", "portal" ]
2195de762a587d05cef90f2d92b90e91939a45a6
https://github.com/bytic/omnipay-mobilpay/blob/2195de762a587d05cef90f2d92b90e91939a45a6/src/Models/Request.php#L124-L144
35,972
wikimedia/mediawiki-tools-minus-x
src/CheckCommand.php
CheckCommand.progress
protected function progress( $marker ) { $this->output->write( $marker ); $this->progressCount++; if ( $this->progressCount > 60 ) { $this->progressCount = 0; $this->output->write( "\n" ); } }
php
protected function progress( $marker ) { $this->output->write( $marker ); $this->progressCount++; if ( $this->progressCount > 60 ) { $this->progressCount = 0; $this->output->write( "\n" ); } }
[ "protected", "function", "progress", "(", "$", "marker", ")", "{", "$", "this", "->", "output", "->", "write", "(", "$", "marker", ")", ";", "$", "this", "->", "progressCount", "++", ";", "if", "(", "$", "this", "->", "progressCount", ">", "60", ")", "{", "$", "this", "->", "progressCount", "=", "0", ";", "$", "this", "->", "output", "->", "write", "(", "\"\\n\"", ")", ";", "}", "}" ]
Output a progress marker @param string $marker Either ".", "E" or "S"
[ "Output", "a", "progress", "marker" ]
5b4651983be787d30e58503891e6a8981295e4f5
https://github.com/wikimedia/mediawiki-tools-minus-x/blob/5b4651983be787d30e58503891e6a8981295e4f5/src/CheckCommand.php#L104-L111
35,973
wikimedia/mediawiki-tools-minus-x
src/CheckCommand.php
CheckCommand.setup
protected function setup() { $this->output->writeln( [ 'MinusX', '======', ] ); $rawPath = $this->input->getArgument( 'path' ); $path = realpath( $rawPath ); if ( !$path ) { $this->output->writeln( 'Error: Invalid path specified' ); return 1; } return $path; }
php
protected function setup() { $this->output->writeln( [ 'MinusX', '======', ] ); $rawPath = $this->input->getArgument( 'path' ); $path = realpath( $rawPath ); if ( !$path ) { $this->output->writeln( 'Error: Invalid path specified' ); return 1; } return $path; }
[ "protected", "function", "setup", "(", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "[", "'MinusX'", ",", "'======'", ",", "]", ")", ";", "$", "rawPath", "=", "$", "this", "->", "input", "->", "getArgument", "(", "'path'", ")", ";", "$", "path", "=", "realpath", "(", "$", "rawPath", ")", ";", "if", "(", "!", "$", "path", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "'Error: Invalid path specified'", ")", ";", "return", "1", ";", "}", "return", "$", "path", ";", "}" ]
Do basic setup @return int|string If an int, it should be the status code to exit with
[ "Do", "basic", "setup" ]
5b4651983be787d30e58503891e6a8981295e4f5
https://github.com/wikimedia/mediawiki-tools-minus-x/blob/5b4651983be787d30e58503891e6a8981295e4f5/src/CheckCommand.php#L118-L132
35,974
wikimedia/mediawiki-tools-minus-x
src/CheckCommand.php
CheckCommand.loadConfig
protected function loadConfig( $path ) { $confPath = $path . '/.minus-x.json'; if ( !file_exists( $confPath ) ) { return; } $config = json_decode( file_get_contents( $confPath ), true ); if ( !is_array( $config ) ) { $this->output->writeln( 'Error: .minus-x.json is not valid JSON' ); return 1; } if ( isset( $config['ignore'] ) ) { $this->ignoredFiles = array_map( function ( $a ) use ( $path ) { return realpath( $path . '/' . $a ); }, $config['ignore'] ); } if ( isset( $config['ignoreDirectories'] ) ) { $this->ignoredDirs = array_map( function ( $a ) use ( $path ) { return realpath( $path . '/' . $a ); }, $config['ignoreDirectories'] ); } if ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' ) { // On Windows, is_executable() always returns true, so whitelist those // files $this->whitelist[] = 'application/x-dosexec'; } }
php
protected function loadConfig( $path ) { $confPath = $path . '/.minus-x.json'; if ( !file_exists( $confPath ) ) { return; } $config = json_decode( file_get_contents( $confPath ), true ); if ( !is_array( $config ) ) { $this->output->writeln( 'Error: .minus-x.json is not valid JSON' ); return 1; } if ( isset( $config['ignore'] ) ) { $this->ignoredFiles = array_map( function ( $a ) use ( $path ) { return realpath( $path . '/' . $a ); }, $config['ignore'] ); } if ( isset( $config['ignoreDirectories'] ) ) { $this->ignoredDirs = array_map( function ( $a ) use ( $path ) { return realpath( $path . '/' . $a ); }, $config['ignoreDirectories'] ); } if ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' ) { // On Windows, is_executable() always returns true, so whitelist those // files $this->whitelist[] = 'application/x-dosexec'; } }
[ "protected", "function", "loadConfig", "(", "$", "path", ")", "{", "$", "confPath", "=", "$", "path", ".", "'/.minus-x.json'", ";", "if", "(", "!", "file_exists", "(", "$", "confPath", ")", ")", "{", "return", ";", "}", "$", "config", "=", "json_decode", "(", "file_get_contents", "(", "$", "confPath", ")", ",", "true", ")", ";", "if", "(", "!", "is_array", "(", "$", "config", ")", ")", "{", "$", "this", "->", "output", "->", "writeln", "(", "'Error: .minus-x.json is not valid JSON'", ")", ";", "return", "1", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'ignore'", "]", ")", ")", "{", "$", "this", "->", "ignoredFiles", "=", "array_map", "(", "function", "(", "$", "a", ")", "use", "(", "$", "path", ")", "{", "return", "realpath", "(", "$", "path", ".", "'/'", ".", "$", "a", ")", ";", "}", ",", "$", "config", "[", "'ignore'", "]", ")", ";", "}", "if", "(", "isset", "(", "$", "config", "[", "'ignoreDirectories'", "]", ")", ")", "{", "$", "this", "->", "ignoredDirs", "=", "array_map", "(", "function", "(", "$", "a", ")", "use", "(", "$", "path", ")", "{", "return", "realpath", "(", "$", "path", ".", "'/'", ".", "$", "a", ")", ";", "}", ",", "$", "config", "[", "'ignoreDirectories'", "]", ")", ";", "}", "if", "(", "strtoupper", "(", "substr", "(", "PHP_OS", ",", "0", ",", "3", ")", ")", "===", "'WIN'", ")", "{", "// On Windows, is_executable() always returns true, so whitelist those", "// files", "$", "this", "->", "whitelist", "[", "]", "=", "'application/x-dosexec'", ";", "}", "}" ]
Load configuration from .minus-x.json @param string $path Root directory that JSON file should be in @return int|null If an int, status code to exit with
[ "Load", "configuration", "from", ".", "minus", "-", "x", ".", "json" ]
5b4651983be787d30e58503891e6a8981295e4f5
https://github.com/wikimedia/mediawiki-tools-minus-x/blob/5b4651983be787d30e58503891e6a8981295e4f5/src/CheckCommand.php#L140-L169
35,975
wikimedia/mediawiki-tools-minus-x
src/CheckCommand.php
CheckCommand.filterDirs
public function filterDirs( SplFileInfo $current ) { if ( $current->isDir() ) { if ( in_array( $current->getFilename(), $this->defaultIgnoredDirs ) ) { // Default ignored directories can be anywhere in the directory structure return false; } elseif ( in_array( $current->getRealPath(), $this->ignoredDirs ) ) { // Ignored dirs are relative to root, and stored as absolute paths return false; } } return true; }
php
public function filterDirs( SplFileInfo $current ) { if ( $current->isDir() ) { if ( in_array( $current->getFilename(), $this->defaultIgnoredDirs ) ) { // Default ignored directories can be anywhere in the directory structure return false; } elseif ( in_array( $current->getRealPath(), $this->ignoredDirs ) ) { // Ignored dirs are relative to root, and stored as absolute paths return false; } } return true; }
[ "public", "function", "filterDirs", "(", "SplFileInfo", "$", "current", ")", "{", "if", "(", "$", "current", "->", "isDir", "(", ")", ")", "{", "if", "(", "in_array", "(", "$", "current", "->", "getFilename", "(", ")", ",", "$", "this", "->", "defaultIgnoredDirs", ")", ")", "{", "// Default ignored directories can be anywhere in the directory structure", "return", "false", ";", "}", "elseif", "(", "in_array", "(", "$", "current", "->", "getRealPath", "(", ")", ",", "$", "this", "->", "ignoredDirs", ")", ")", "{", "// Ignored dirs are relative to root, and stored as absolute paths", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Filter out ignored directories, split into a separate function for easier readability. Used by RecursiveCallbackFilterIterator @param SplFileInfo $current File/directory to check @return bool
[ "Filter", "out", "ignored", "directories", "split", "into", "a", "separate", "function", "for", "easier", "readability", ".", "Used", "by", "RecursiveCallbackFilterIterator" ]
5b4651983be787d30e58503891e6a8981295e4f5
https://github.com/wikimedia/mediawiki-tools-minus-x/blob/5b4651983be787d30e58503891e6a8981295e4f5/src/CheckCommand.php#L213-L225
35,976
wikimedia/mediawiki-tools-minus-x
src/CheckCommand.php
CheckCommand.checkPath
protected function checkPath( $path ) { $iterator = new RecursiveIteratorIterator( new RecursiveCallbackFilterIterator( new RecursiveDirectoryIterator( $path ), [ $this, 'filterDirs' ] ) ); $bad = []; /** @var SplFileInfo $file */ foreach ( $iterator as $file ) { // Skip directories if ( !$file->isFile() ) { continue; } // Skip whitelisted files if ( in_array( $file->getPathname(), $this->ignoredFiles ) ) { $this->progress( 'S' ); continue; } if ( !$file->isExecutable() ) { $this->progress( '.' ); continue; } if ( !$this->checkFile( $file ) ) { $this->progress( 'E' ); $bad[] = $file; } else { $this->progress( '.' ); } } return $bad; }
php
protected function checkPath( $path ) { $iterator = new RecursiveIteratorIterator( new RecursiveCallbackFilterIterator( new RecursiveDirectoryIterator( $path ), [ $this, 'filterDirs' ] ) ); $bad = []; /** @var SplFileInfo $file */ foreach ( $iterator as $file ) { // Skip directories if ( !$file->isFile() ) { continue; } // Skip whitelisted files if ( in_array( $file->getPathname(), $this->ignoredFiles ) ) { $this->progress( 'S' ); continue; } if ( !$file->isExecutable() ) { $this->progress( '.' ); continue; } if ( !$this->checkFile( $file ) ) { $this->progress( 'E' ); $bad[] = $file; } else { $this->progress( '.' ); } } return $bad; }
[ "protected", "function", "checkPath", "(", "$", "path", ")", "{", "$", "iterator", "=", "new", "RecursiveIteratorIterator", "(", "new", "RecursiveCallbackFilterIterator", "(", "new", "RecursiveDirectoryIterator", "(", "$", "path", ")", ",", "[", "$", "this", ",", "'filterDirs'", "]", ")", ")", ";", "$", "bad", "=", "[", "]", ";", "/** @var SplFileInfo $file */", "foreach", "(", "$", "iterator", "as", "$", "file", ")", "{", "// Skip directories", "if", "(", "!", "$", "file", "->", "isFile", "(", ")", ")", "{", "continue", ";", "}", "// Skip whitelisted files", "if", "(", "in_array", "(", "$", "file", "->", "getPathname", "(", ")", ",", "$", "this", "->", "ignoredFiles", ")", ")", "{", "$", "this", "->", "progress", "(", "'S'", ")", ";", "continue", ";", "}", "if", "(", "!", "$", "file", "->", "isExecutable", "(", ")", ")", "{", "$", "this", "->", "progress", "(", "'.'", ")", ";", "continue", ";", "}", "if", "(", "!", "$", "this", "->", "checkFile", "(", "$", "file", ")", ")", "{", "$", "this", "->", "progress", "(", "'E'", ")", ";", "$", "bad", "[", "]", "=", "$", "file", ";", "}", "else", "{", "$", "this", "->", "progress", "(", "'.'", ")", ";", "}", "}", "return", "$", "bad", ";", "}" ]
Recursively search a directory and check it @param string $path Directory @return SplFileInfo[]
[ "Recursively", "search", "a", "directory", "and", "check", "it" ]
5b4651983be787d30e58503891e6a8981295e4f5
https://github.com/wikimedia/mediawiki-tools-minus-x/blob/5b4651983be787d30e58503891e6a8981295e4f5/src/CheckCommand.php#L233-L268
35,977
honey-comb/starter
src/Models/HCModel.php
HCModel.getFillableFields
public static function getFillableFields(bool $join = false) { $list = with(new static)->getFillable(); if ($join) { //to use default sort_by command array_push($list, 'created_at'); foreach ($list as &$value) $value = self::getTableName() . '.' . $value; } return $list; }
php
public static function getFillableFields(bool $join = false) { $list = with(new static)->getFillable(); if ($join) { //to use default sort_by command array_push($list, 'created_at'); foreach ($list as &$value) $value = self::getTableName() . '.' . $value; } return $list; }
[ "public", "static", "function", "getFillableFields", "(", "bool", "$", "join", "=", "false", ")", "{", "$", "list", "=", "with", "(", "new", "static", ")", "->", "getFillable", "(", ")", ";", "if", "(", "$", "join", ")", "{", "//to use default sort_by command", "array_push", "(", "$", "list", ",", "'created_at'", ")", ";", "foreach", "(", "$", "list", "as", "&", "$", "value", ")", "$", "value", "=", "self", "::", "getTableName", "(", ")", ".", "'.'", ".", "$", "value", ";", "}", "return", "$", "list", ";", "}" ]
Function which gets fillable fields array @param bool $join @return array
[ "Function", "which", "gets", "fillable", "fields", "array" ]
2c5330a49eb5204a6b748368aca835b7ecb02393
https://github.com/honey-comb/starter/blob/2c5330a49eb5204a6b748368aca835b7ecb02393/src/Models/HCModel.php#L63-L76
35,978
hiqdev/hipanel-module-client
src/models/Client.php
Client.getSortedPurses
public function getSortedPurses() { $purses = $this->purses; if (empty($purses)) { return $purses; } $getOrder = function ($currency) { $order = ['usd' => 0, 'eur' => 1]; return $order[$currency] ?? 100; }; usort($purses, function ($a, $b) use ($getOrder) { return $getOrder($a->currency) <=> $getOrder($b->currency); }); return $purses; }
php
public function getSortedPurses() { $purses = $this->purses; if (empty($purses)) { return $purses; } $getOrder = function ($currency) { $order = ['usd' => 0, 'eur' => 1]; return $order[$currency] ?? 100; }; usort($purses, function ($a, $b) use ($getOrder) { return $getOrder($a->currency) <=> $getOrder($b->currency); }); return $purses; }
[ "public", "function", "getSortedPurses", "(", ")", "{", "$", "purses", "=", "$", "this", "->", "purses", ";", "if", "(", "empty", "(", "$", "purses", ")", ")", "{", "return", "$", "purses", ";", "}", "$", "getOrder", "=", "function", "(", "$", "currency", ")", "{", "$", "order", "=", "[", "'usd'", "=>", "0", ",", "'eur'", "=>", "1", "]", ";", "return", "$", "order", "[", "$", "currency", "]", "??", "100", ";", "}", ";", "usort", "(", "$", "purses", ",", "function", "(", "$", "a", ",", "$", "b", ")", "use", "(", "$", "getOrder", ")", "{", "return", "$", "getOrder", "(", "$", "a", "->", "currency", ")", "<=>", "$", "getOrder", "(", "$", "b", "->", "currency", ")", ";", "}", ")", ";", "return", "$", "purses", ";", "}" ]
Sort related purses like `usd`, `eur`, other... @return array
[ "Sort", "related", "purses", "like", "usd", "eur", "other", "..." ]
569d87de369ccf8646087dde566d26a41995c8cb
https://github.com/hiqdev/hipanel-module-client/blob/569d87de369ccf8646087dde566d26a41995c8cb/src/models/Client.php#L438-L456
35,979
edineibauer/uebConfig
public/src/Config/UpdateSystem.php
UpdateSystem.createCoreImages
private function createCoreImages() { Helper::createFolderIfNoExist(PATH_HOME . "assetsPublic/img"); $config = json_decode(file_get_contents(PATH_HOME . "_config/config.json"), true); copy(PATH_HOME . VENDOR . "config/public/assets/dino.png", PATH_HOME . "assetsPublic/img/dino.png"); copy(PATH_HOME . VENDOR . "config/public/assets/file.png", PATH_HOME . "assetsPublic/img/file.png"); copy(PATH_HOME . VENDOR . "config/public/assets/save.gif", PATH_HOME . "assetsPublic/img/save.gif"); copy(PATH_HOME . VENDOR . "config/public/assets/file_type.svg", PATH_HOME . "assetsPublic/img/file_type.svg"); copy(PATH_HOME . VENDOR . "config/public/assets/image-not-found.png", PATH_HOME . "assetsPublic/img/img.png"); if(file_exists(PATH_HOME . (!empty($config['favicon']) ? "uploads/site/favicon.png" : VENDOR . "config/public/assets/favicon.png"))) copy(PATH_HOME . (!empty($config['favicon']) ? "uploads/site/favicon.png" : VENDOR . "config/public/assets/favicon.png"), PATH_HOME . "assetsPublic/img/favicon.png"); if(!empty($config['logo']) && file_exists(PATH_HOME . "uploads/site/logo.png")) copy(PATH_HOME . "uploads/site/logo.png", PATH_HOME . "assetsPublic/img/logo.png"); elseif(file_exists(PATH_HOME . "assetsPublic/img/logo.png")) unlink(PATH_HOME . "assetsPublic/img/logo.png"); }
php
private function createCoreImages() { Helper::createFolderIfNoExist(PATH_HOME . "assetsPublic/img"); $config = json_decode(file_get_contents(PATH_HOME . "_config/config.json"), true); copy(PATH_HOME . VENDOR . "config/public/assets/dino.png", PATH_HOME . "assetsPublic/img/dino.png"); copy(PATH_HOME . VENDOR . "config/public/assets/file.png", PATH_HOME . "assetsPublic/img/file.png"); copy(PATH_HOME . VENDOR . "config/public/assets/save.gif", PATH_HOME . "assetsPublic/img/save.gif"); copy(PATH_HOME . VENDOR . "config/public/assets/file_type.svg", PATH_HOME . "assetsPublic/img/file_type.svg"); copy(PATH_HOME . VENDOR . "config/public/assets/image-not-found.png", PATH_HOME . "assetsPublic/img/img.png"); if(file_exists(PATH_HOME . (!empty($config['favicon']) ? "uploads/site/favicon.png" : VENDOR . "config/public/assets/favicon.png"))) copy(PATH_HOME . (!empty($config['favicon']) ? "uploads/site/favicon.png" : VENDOR . "config/public/assets/favicon.png"), PATH_HOME . "assetsPublic/img/favicon.png"); if(!empty($config['logo']) && file_exists(PATH_HOME . "uploads/site/logo.png")) copy(PATH_HOME . "uploads/site/logo.png", PATH_HOME . "assetsPublic/img/logo.png"); elseif(file_exists(PATH_HOME . "assetsPublic/img/logo.png")) unlink(PATH_HOME . "assetsPublic/img/logo.png"); }
[ "private", "function", "createCoreImages", "(", ")", "{", "Helper", "::", "createFolderIfNoExist", "(", "PATH_HOME", ".", "\"assetsPublic/img\"", ")", ";", "$", "config", "=", "json_decode", "(", "file_get_contents", "(", "PATH_HOME", ".", "\"_config/config.json\"", ")", ",", "true", ")", ";", "copy", "(", "PATH_HOME", ".", "VENDOR", ".", "\"config/public/assets/dino.png\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/dino.png\"", ")", ";", "copy", "(", "PATH_HOME", ".", "VENDOR", ".", "\"config/public/assets/file.png\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/file.png\"", ")", ";", "copy", "(", "PATH_HOME", ".", "VENDOR", ".", "\"config/public/assets/save.gif\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/save.gif\"", ")", ";", "copy", "(", "PATH_HOME", ".", "VENDOR", ".", "\"config/public/assets/file_type.svg\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/file_type.svg\"", ")", ";", "copy", "(", "PATH_HOME", ".", "VENDOR", ".", "\"config/public/assets/image-not-found.png\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/img.png\"", ")", ";", "if", "(", "file_exists", "(", "PATH_HOME", ".", "(", "!", "empty", "(", "$", "config", "[", "'favicon'", "]", ")", "?", "\"uploads/site/favicon.png\"", ":", "VENDOR", ".", "\"config/public/assets/favicon.png\"", ")", ")", ")", "copy", "(", "PATH_HOME", ".", "(", "!", "empty", "(", "$", "config", "[", "'favicon'", "]", ")", "?", "\"uploads/site/favicon.png\"", ":", "VENDOR", ".", "\"config/public/assets/favicon.png\"", ")", ",", "PATH_HOME", ".", "\"assetsPublic/img/favicon.png\"", ")", ";", "if", "(", "!", "empty", "(", "$", "config", "[", "'logo'", "]", ")", "&&", "file_exists", "(", "PATH_HOME", ".", "\"uploads/site/logo.png\"", ")", ")", "copy", "(", "PATH_HOME", ".", "\"uploads/site/logo.png\"", ",", "PATH_HOME", ".", "\"assetsPublic/img/logo.png\"", ")", ";", "elseif", "(", "file_exists", "(", "PATH_HOME", ".", "\"assetsPublic/img/logo.png\"", ")", ")", "unlink", "(", "PATH_HOME", ".", "\"assetsPublic/img/logo.png\"", ")", ";", "}" ]
Cria Imagens do sistema
[ "Cria", "Imagens", "do", "sistema" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/src/Config/UpdateSystem.php#L395-L413
35,980
edineibauer/uebConfig
public/src/Config/UpdateSystem.php
UpdateSystem.createMinifyAssetsLib
private function createMinifyAssetsLib() { Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/cache'); Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/view'); //Remove todos os dados das pastas de assets foreach (Helper::listFolder(PATH_HOME . "assetsPublic/cache") as $cache) { if(!is_dir(PATH_HOME . "assetsPublic/cache/" . $cache)) unlink(PATH_HOME . "assetsPublic/cache/" . $cache); } foreach (Helper::listFolder(PATH_HOME . "assetsPublic/view") as $cache) { if(!is_dir(PATH_HOME . "assetsPublic/view/" . $cache)) unlink(PATH_HOME . "assetsPublic/view/" . $cache); } $vendors = Config::getViewPermissoes(); $this->createRepositorioCache($vendors); $this->downloadAssetsCache($vendors); foreach ($vendors as $lib) { $path = PATH_HOME . VENDOR . $lib . "/public/"; if (file_exists($path . "view")) { foreach (Helper::listFolder($path . "view") as $view) { if (preg_match('/.php$/i', $view)) { //para cada view $nameView = str_replace('.php', '', $view); if(!in_array($nameView, ['updateSystema'])) $this->createViewAssets($path, $nameView); } } } } }
php
private function createMinifyAssetsLib() { Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/cache'); Helper::createFolderIfNoExist(PATH_HOME . 'assetsPublic/view'); //Remove todos os dados das pastas de assets foreach (Helper::listFolder(PATH_HOME . "assetsPublic/cache") as $cache) { if(!is_dir(PATH_HOME . "assetsPublic/cache/" . $cache)) unlink(PATH_HOME . "assetsPublic/cache/" . $cache); } foreach (Helper::listFolder(PATH_HOME . "assetsPublic/view") as $cache) { if(!is_dir(PATH_HOME . "assetsPublic/view/" . $cache)) unlink(PATH_HOME . "assetsPublic/view/" . $cache); } $vendors = Config::getViewPermissoes(); $this->createRepositorioCache($vendors); $this->downloadAssetsCache($vendors); foreach ($vendors as $lib) { $path = PATH_HOME . VENDOR . $lib . "/public/"; if (file_exists($path . "view")) { foreach (Helper::listFolder($path . "view") as $view) { if (preg_match('/.php$/i', $view)) { //para cada view $nameView = str_replace('.php', '', $view); if(!in_array($nameView, ['updateSystema'])) $this->createViewAssets($path, $nameView); } } } } }
[ "private", "function", "createMinifyAssetsLib", "(", ")", "{", "Helper", "::", "createFolderIfNoExist", "(", "PATH_HOME", ".", "'assetsPublic/cache'", ")", ";", "Helper", "::", "createFolderIfNoExist", "(", "PATH_HOME", ".", "'assetsPublic/view'", ")", ";", "//Remove todos os dados das pastas de assets", "foreach", "(", "Helper", "::", "listFolder", "(", "PATH_HOME", ".", "\"assetsPublic/cache\"", ")", "as", "$", "cache", ")", "{", "if", "(", "!", "is_dir", "(", "PATH_HOME", ".", "\"assetsPublic/cache/\"", ".", "$", "cache", ")", ")", "unlink", "(", "PATH_HOME", ".", "\"assetsPublic/cache/\"", ".", "$", "cache", ")", ";", "}", "foreach", "(", "Helper", "::", "listFolder", "(", "PATH_HOME", ".", "\"assetsPublic/view\"", ")", "as", "$", "cache", ")", "{", "if", "(", "!", "is_dir", "(", "PATH_HOME", ".", "\"assetsPublic/view/\"", ".", "$", "cache", ")", ")", "unlink", "(", "PATH_HOME", ".", "\"assetsPublic/view/\"", ".", "$", "cache", ")", ";", "}", "$", "vendors", "=", "Config", "::", "getViewPermissoes", "(", ")", ";", "$", "this", "->", "createRepositorioCache", "(", "$", "vendors", ")", ";", "$", "this", "->", "downloadAssetsCache", "(", "$", "vendors", ")", ";", "foreach", "(", "$", "vendors", "as", "$", "lib", ")", "{", "$", "path", "=", "PATH_HOME", ".", "VENDOR", ".", "$", "lib", ".", "\"/public/\"", ";", "if", "(", "file_exists", "(", "$", "path", ".", "\"view\"", ")", ")", "{", "foreach", "(", "Helper", "::", "listFolder", "(", "$", "path", ".", "\"view\"", ")", "as", "$", "view", ")", "{", "if", "(", "preg_match", "(", "'/.php$/i'", ",", "$", "view", ")", ")", "{", "//para cada view", "$", "nameView", "=", "str_replace", "(", "'.php'", ",", "''", ",", "$", "view", ")", ";", "if", "(", "!", "in_array", "(", "$", "nameView", ",", "[", "'updateSystema'", "]", ")", ")", "$", "this", "->", "createViewAssets", "(", "$", "path", ",", "$", "nameView", ")", ";", "}", "}", "}", "}", "}" ]
Minifica todos os assets das bibliotecas
[ "Minifica", "todos", "os", "assets", "das", "bibliotecas" ]
6792d15656f5a9f78f2510d4850aa21102f96c1f
https://github.com/edineibauer/uebConfig/blob/6792d15656f5a9f78f2510d4850aa21102f96c1f/public/src/Config/UpdateSystem.php#L660-L694
35,981
CMProductions/http-client
src/Provider/HttpClientServiceProvider.php
HttpClientServiceProvider.getBuilder
private function getBuilder(Container $pimple) { $builder = ClientBuilder::create(); $this->setFactory($builder, $pimple); $this->setSender($builder, $pimple); $this->setLogger($builder, $pimple); return $builder; }
php
private function getBuilder(Container $pimple) { $builder = ClientBuilder::create(); $this->setFactory($builder, $pimple); $this->setSender($builder, $pimple); $this->setLogger($builder, $pimple); return $builder; }
[ "private", "function", "getBuilder", "(", "Container", "$", "pimple", ")", "{", "$", "builder", "=", "ClientBuilder", "::", "create", "(", ")", ";", "$", "this", "->", "setFactory", "(", "$", "builder", ",", "$", "pimple", ")", ";", "$", "this", "->", "setSender", "(", "$", "builder", ",", "$", "pimple", ")", ";", "$", "this", "->", "setLogger", "(", "$", "builder", ",", "$", "pimple", ")", ";", "return", "$", "builder", ";", "}" ]
Builds the container @param Container $pimple @return Client
[ "Builds", "the", "container" ]
d7e5a74cdf94b6b50a229db6698c81fd055ff2ce
https://github.com/CMProductions/http-client/blob/d7e5a74cdf94b6b50a229db6698c81fd055ff2ce/src/Provider/HttpClientServiceProvider.php#L62-L71
35,982
cedx/which.php
lib/Finder.php
Finder.find
function find(string $command): \Generator { foreach ($this->getPath() as $directory) yield from $this->findExecutables($directory, $command); }
php
function find(string $command): \Generator { foreach ($this->getPath() as $directory) yield from $this->findExecutables($directory, $command); }
[ "function", "find", "(", "string", "$", "command", ")", ":", "\\", "Generator", "{", "foreach", "(", "$", "this", "->", "getPath", "(", ")", "as", "$", "directory", ")", "yield", "from", "$", "this", "->", "findExecutables", "(", "$", "directory", ",", "$", "command", ")", ";", "}" ]
Finds the instances of an executable in the system path. @param string $command The command to be resolved. @return \Generator The paths of the executables found.
[ "Finds", "the", "instances", "of", "an", "executable", "in", "the", "system", "path", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/lib/Finder.php#L60-L62
35,983
cedx/which.php
lib/Finder.php
Finder.isExecutable
function isExecutable(string $file): bool { $fileInfo = new \SplFileInfo($file); if (!$fileInfo->isFile()) return false; if ($fileInfo->isExecutable()) return true; return static::isWindows() ? $this->checkFileExtension($fileInfo) : $this->checkFilePermissions($fileInfo); }
php
function isExecutable(string $file): bool { $fileInfo = new \SplFileInfo($file); if (!$fileInfo->isFile()) return false; if ($fileInfo->isExecutable()) return true; return static::isWindows() ? $this->checkFileExtension($fileInfo) : $this->checkFilePermissions($fileInfo); }
[ "function", "isExecutable", "(", "string", "$", "file", ")", ":", "bool", "{", "$", "fileInfo", "=", "new", "\\", "SplFileInfo", "(", "$", "file", ")", ";", "if", "(", "!", "$", "fileInfo", "->", "isFile", "(", ")", ")", "return", "false", ";", "if", "(", "$", "fileInfo", "->", "isExecutable", "(", ")", ")", "return", "true", ";", "return", "static", "::", "isWindows", "(", ")", "?", "$", "this", "->", "checkFileExtension", "(", "$", "fileInfo", ")", ":", "$", "this", "->", "checkFilePermissions", "(", "$", "fileInfo", ")", ";", "}" ]
Gets a value indicating whether the specified file is executable. @param string $file The path of the file to be checked. @return bool `true` if the specified file is executable, otherwise `false`.
[ "Gets", "a", "value", "indicating", "whether", "the", "specified", "file", "is", "executable", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/lib/Finder.php#L93-L98
35,984
cedx/which.php
lib/Finder.php
Finder.checkFileExtension
private function checkFileExtension(\SplFileInfo $fileInfo): bool { $extension = mb_strtolower($fileInfo->getExtension()); return mb_strlen($extension) ? in_array(".$extension", $this->getExtensions()->getArrayCopy()) : false; }
php
private function checkFileExtension(\SplFileInfo $fileInfo): bool { $extension = mb_strtolower($fileInfo->getExtension()); return mb_strlen($extension) ? in_array(".$extension", $this->getExtensions()->getArrayCopy()) : false; }
[ "private", "function", "checkFileExtension", "(", "\\", "SplFileInfo", "$", "fileInfo", ")", ":", "bool", "{", "$", "extension", "=", "mb_strtolower", "(", "$", "fileInfo", "->", "getExtension", "(", ")", ")", ";", "return", "mb_strlen", "(", "$", "extension", ")", "?", "in_array", "(", "\".$extension\"", ",", "$", "this", "->", "getExtensions", "(", ")", "->", "getArrayCopy", "(", ")", ")", ":", "false", ";", "}" ]
Checks that the specified file is executable according to the executable file extensions. @param \SplFileInfo $fileInfo The file to be checked. @return bool Value indicating whether the specified file is executable.
[ "Checks", "that", "the", "specified", "file", "is", "executable", "according", "to", "the", "executable", "file", "extensions", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/lib/Finder.php#L105-L108
35,985
cedx/which.php
lib/Finder.php
Finder.checkFilePermissions
private function checkFilePermissions(\SplFileInfo $fileInfo): bool { // Others. $perms = $fileInfo->getPerms(); if ($perms & 0001) return true; // Group. $gid = function_exists('posix_getgid') ? posix_getgid() : -1; if ($perms & 0010) return $gid == $fileInfo->getGroup(); // Owner. $uid = function_exists('posix_getuid') ? posix_getuid() : -1; if ($perms & 0100) return $uid == $fileInfo->getOwner(); // Root. return $perms & (0100 | 0010) ? $uid == 0 : false; }
php
private function checkFilePermissions(\SplFileInfo $fileInfo): bool { // Others. $perms = $fileInfo->getPerms(); if ($perms & 0001) return true; // Group. $gid = function_exists('posix_getgid') ? posix_getgid() : -1; if ($perms & 0010) return $gid == $fileInfo->getGroup(); // Owner. $uid = function_exists('posix_getuid') ? posix_getuid() : -1; if ($perms & 0100) return $uid == $fileInfo->getOwner(); // Root. return $perms & (0100 | 0010) ? $uid == 0 : false; }
[ "private", "function", "checkFilePermissions", "(", "\\", "SplFileInfo", "$", "fileInfo", ")", ":", "bool", "{", "// Others.", "$", "perms", "=", "$", "fileInfo", "->", "getPerms", "(", ")", ";", "if", "(", "$", "perms", "&", "0001", ")", "return", "true", ";", "// Group.", "$", "gid", "=", "function_exists", "(", "'posix_getgid'", ")", "?", "posix_getgid", "(", ")", ":", "-", "1", ";", "if", "(", "$", "perms", "&", "0010", ")", "return", "$", "gid", "==", "$", "fileInfo", "->", "getGroup", "(", ")", ";", "// Owner.", "$", "uid", "=", "function_exists", "(", "'posix_getuid'", ")", "?", "posix_getuid", "(", ")", ":", "-", "1", ";", "if", "(", "$", "perms", "&", "0100", ")", "return", "$", "uid", "==", "$", "fileInfo", "->", "getOwner", "(", ")", ";", "// Root.", "return", "$", "perms", "&", "(", "0100", "|", "0010", ")", "?", "$", "uid", "==", "0", ":", "false", ";", "}" ]
Checks that the specified file is executable according to its permissions. @param \SplFileInfo $fileInfo The file to be checked. @return bool Value indicating whether the specified file is executable.
[ "Checks", "that", "the", "specified", "file", "is", "executable", "according", "to", "its", "permissions", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/lib/Finder.php#L115-L130
35,986
cedx/which.php
lib/Finder.php
Finder.findExecutables
private function findExecutables(string $directory, string $command): \Generator { foreach (array_merge([''], $this->getExtensions()->getArrayCopy()) as $extension) { $resolvedPath = Path::makeAbsolute(Path::join($directory, $command).mb_strtolower($extension), getcwd() ?: '.'); if ($this->isExecutable($resolvedPath)) yield str_replace('/', DIRECTORY_SEPARATOR, $resolvedPath); } }
php
private function findExecutables(string $directory, string $command): \Generator { foreach (array_merge([''], $this->getExtensions()->getArrayCopy()) as $extension) { $resolvedPath = Path::makeAbsolute(Path::join($directory, $command).mb_strtolower($extension), getcwd() ?: '.'); if ($this->isExecutable($resolvedPath)) yield str_replace('/', DIRECTORY_SEPARATOR, $resolvedPath); } }
[ "private", "function", "findExecutables", "(", "string", "$", "directory", ",", "string", "$", "command", ")", ":", "\\", "Generator", "{", "foreach", "(", "array_merge", "(", "[", "''", "]", ",", "$", "this", "->", "getExtensions", "(", ")", "->", "getArrayCopy", "(", ")", ")", "as", "$", "extension", ")", "{", "$", "resolvedPath", "=", "Path", "::", "makeAbsolute", "(", "Path", "::", "join", "(", "$", "directory", ",", "$", "command", ")", ".", "mb_strtolower", "(", "$", "extension", ")", ",", "getcwd", "(", ")", "?", ":", "'.'", ")", ";", "if", "(", "$", "this", "->", "isExecutable", "(", "$", "resolvedPath", ")", ")", "yield", "str_replace", "(", "'/'", ",", "DIRECTORY_SEPARATOR", ",", "$", "resolvedPath", ")", ";", "}", "}" ]
Finds the instances of an executable in the specified directory. @param string $directory The directory path. @param string $command The command to be resolved. @return \Generator The paths of the executables found.
[ "Finds", "the", "instances", "of", "an", "executable", "in", "the", "specified", "directory", "." ]
3ab7702edaec4cc0059af609f7edb84bf3a8bb91
https://github.com/cedx/which.php/blob/3ab7702edaec4cc0059af609f7edb84bf3a8bb91/lib/Finder.php#L138-L143
35,987
chameleon-system/sanitycheck-bundle
Resolver/SymfonyContainerCheckResolver.php
SymfonyContainerCheckResolver.lookupCheckByServiceId
protected function lookupCheckByServiceId($name) { try { return $this->container->get($name); } catch (\InvalidArgumentException $e) { throw new CheckNotFoundException('Check not found: '.$name, 0, $e); } }
php
protected function lookupCheckByServiceId($name) { try { return $this->container->get($name); } catch (\InvalidArgumentException $e) { throw new CheckNotFoundException('Check not found: '.$name, 0, $e); } }
[ "protected", "function", "lookupCheckByServiceId", "(", "$", "name", ")", "{", "try", "{", "return", "$", "this", "->", "container", "->", "get", "(", "$", "name", ")", ";", "}", "catch", "(", "\\", "InvalidArgumentException", "$", "e", ")", "{", "throw", "new", "CheckNotFoundException", "(", "'Check not found: '", ".", "$", "name", ",", "0", ",", "$", "e", ")", ";", "}", "}" ]
Gets a check from the container. @param string $name The check's service id @throws CheckNotFoundException if the check is not registered as a service @return CheckInterface
[ "Gets", "a", "check", "from", "the", "container", "." ]
7d95fabd0af212acbdee226dbe754dca3046f225
https://github.com/chameleon-system/sanitycheck-bundle/blob/7d95fabd0af212acbdee226dbe754dca3046f225/Resolver/SymfonyContainerCheckResolver.php#L95-L102
35,988
stubbles/stubbles-console
src/main/php/input/HelpScreen.php
HelpScreen.readAppDescription
private function readAppDescription($object): string { $annotations = annotationsOf($object); if (!$annotations->contain('AppDescription')) { return ''; } return $annotations->firstNamed('AppDescription')->getValue() . "\n"; }
php
private function readAppDescription($object): string { $annotations = annotationsOf($object); if (!$annotations->contain('AppDescription')) { return ''; } return $annotations->firstNamed('AppDescription')->getValue() . "\n"; }
[ "private", "function", "readAppDescription", "(", "$", "object", ")", ":", "string", "{", "$", "annotations", "=", "annotationsOf", "(", "$", "object", ")", ";", "if", "(", "!", "$", "annotations", "->", "contain", "(", "'AppDescription'", ")", ")", "{", "return", "''", ";", "}", "return", "$", "annotations", "->", "firstNamed", "(", "'AppDescription'", ")", "->", "getValue", "(", ")", ".", "\"\\n\"", ";", "}" ]
retrieves app description for given object @param object $object @return string
[ "retrieves", "app", "description", "for", "given", "object" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/input/HelpScreen.php#L68-L76
35,989
stubbles/stubbles-console
src/main/php/input/HelpScreen.php
HelpScreen.getOptionName
private function getOptionName(TargetMethod $targetMethod): string { $name = $targetMethod->paramName(); $prefix = strlen($name) === 1 ? '-' : '--'; $suffix = $targetMethod->requiresParameter() ? ' ' . $targetMethod->valueDescription() : ''; return $prefix . $name . $suffix; }
php
private function getOptionName(TargetMethod $targetMethod): string { $name = $targetMethod->paramName(); $prefix = strlen($name) === 1 ? '-' : '--'; $suffix = $targetMethod->requiresParameter() ? ' ' . $targetMethod->valueDescription() : ''; return $prefix . $name . $suffix; }
[ "private", "function", "getOptionName", "(", "TargetMethod", "$", "targetMethod", ")", ":", "string", "{", "$", "name", "=", "$", "targetMethod", "->", "paramName", "(", ")", ";", "$", "prefix", "=", "strlen", "(", "$", "name", ")", "===", "1", "?", "'-'", ":", "'--'", ";", "$", "suffix", "=", "$", "targetMethod", "->", "requiresParameter", "(", ")", "?", "' '", ".", "$", "targetMethod", "->", "valueDescription", "(", ")", ":", "''", ";", "return", "$", "prefix", ".", "$", "name", ".", "$", "suffix", ";", "}" ]
retrieves name of option @param \stubbles\input\broker\TargetMethod $targetMethod @return string
[ "retrieves", "name", "of", "option" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/input/HelpScreen.php#L84-L90
35,990
electro-modules/matisse-components
MatisseComponents/Handlers/FileFieldHandler.php
FileFieldHandler.newUpload
private function newUpload (BaseModel $model, $fieldName, UploadedFileInterface $file) { // Check is there are already files on this field. $filesRelation = $model->files (); /** @var Builder $filesQuery */ $filesQuery = $filesRelation->ofField ($fieldName); /** @var File[] $files */ $files = $filesQuery->get (); // Save new file $data = File::getFileData ($file->getClientFilename (), FileUtil::getUploadedFilePath ($file), $fieldName); /** @var File $fileModel */ $fileModel = $filesRelation->create ($data); $this->repository->saveUploadedFile ($fileModel->path, $file); // Delete the previous files of this field, if any exists. // This is only performed AFTER the new file is successfully uploaded. foreach ($files as $file) $file->delete (); // If everything went ok, save the models. if (!in_array ($fieldName, $model::GALLERY_FIELDS)) $model[$fieldName] = $fileModel->path; $model->save (); }
php
private function newUpload (BaseModel $model, $fieldName, UploadedFileInterface $file) { // Check is there are already files on this field. $filesRelation = $model->files (); /** @var Builder $filesQuery */ $filesQuery = $filesRelation->ofField ($fieldName); /** @var File[] $files */ $files = $filesQuery->get (); // Save new file $data = File::getFileData ($file->getClientFilename (), FileUtil::getUploadedFilePath ($file), $fieldName); /** @var File $fileModel */ $fileModel = $filesRelation->create ($data); $this->repository->saveUploadedFile ($fileModel->path, $file); // Delete the previous files of this field, if any exists. // This is only performed AFTER the new file is successfully uploaded. foreach ($files as $file) $file->delete (); // If everything went ok, save the models. if (!in_array ($fieldName, $model::GALLERY_FIELDS)) $model[$fieldName] = $fileModel->path; $model->save (); }
[ "private", "function", "newUpload", "(", "BaseModel", "$", "model", ",", "$", "fieldName", ",", "UploadedFileInterface", "$", "file", ")", "{", "// Check is there are already files on this field.", "$", "filesRelation", "=", "$", "model", "->", "files", "(", ")", ";", "/** @var Builder $filesQuery */", "$", "filesQuery", "=", "$", "filesRelation", "->", "ofField", "(", "$", "fieldName", ")", ";", "/** @var File[] $files */", "$", "files", "=", "$", "filesQuery", "->", "get", "(", ")", ";", "// Save new file", "$", "data", "=", "File", "::", "getFileData", "(", "$", "file", "->", "getClientFilename", "(", ")", ",", "FileUtil", "::", "getUploadedFilePath", "(", "$", "file", ")", ",", "$", "fieldName", ")", ";", "/** @var File $fileModel */", "$", "fileModel", "=", "$", "filesRelation", "->", "create", "(", "$", "data", ")", ";", "$", "this", "->", "repository", "->", "saveUploadedFile", "(", "$", "fileModel", "->", "path", ",", "$", "file", ")", ";", "// Delete the previous files of this field, if any exists.", "// This is only performed AFTER the new file is successfully uploaded.", "foreach", "(", "$", "files", "as", "$", "file", ")", "$", "file", "->", "delete", "(", ")", ";", "// If everything went ok, save the models.", "if", "(", "!", "in_array", "(", "$", "fieldName", ",", "$", "model", "::", "GALLERY_FIELDS", ")", ")", "$", "model", "[", "$", "fieldName", "]", "=", "$", "fileModel", "->", "path", ";", "$", "model", "->", "save", "(", ")", ";", "}" ]
Handle the case where a file has been uploaded for a field, possibly replacing another already set on the field. @param BaseModel|FilesModelTrait $model @param string $fieldName @param UploadedFileInterface $file @throws \Exception @throws \League\Flysystem\FileExistsException @throws \League\Flysystem\InvalidArgumentException
[ "Handle", "the", "case", "where", "a", "file", "has", "been", "uploaded", "for", "a", "field", "possibly", "replacing", "another", "already", "set", "on", "the", "field", "." ]
3a746f796157ef72b585a5994394483fbe500861
https://github.com/electro-modules/matisse-components/blob/3a746f796157ef72b585a5994394483fbe500861/MatisseComponents/Handlers/FileFieldHandler.php#L158-L182
35,991
electro-modules/matisse-components
MatisseComponents/Handlers/FileFieldHandler.php
FileFieldHandler.noUpload
private function noUpload (BaseModel $model, $fieldName) { if (!isset ($model[$fieldName])) { // Check is there are already files on this field. $filesRelation = $model->files (); /** @var Builder $filesQuery */ $filesQuery = $filesRelation->ofField ($fieldName); /** @var File[] $files */ $files = $filesQuery->get (); // Delete the previous files of this field, if any exists. foreach ($files as $file) $file->delete (); } }
php
private function noUpload (BaseModel $model, $fieldName) { if (!isset ($model[$fieldName])) { // Check is there are already files on this field. $filesRelation = $model->files (); /** @var Builder $filesQuery */ $filesQuery = $filesRelation->ofField ($fieldName); /** @var File[] $files */ $files = $filesQuery->get (); // Delete the previous files of this field, if any exists. foreach ($files as $file) $file->delete (); } }
[ "private", "function", "noUpload", "(", "BaseModel", "$", "model", ",", "$", "fieldName", ")", "{", "if", "(", "!", "isset", "(", "$", "model", "[", "$", "fieldName", "]", ")", ")", "{", "// Check is there are already files on this field.", "$", "filesRelation", "=", "$", "model", "->", "files", "(", ")", ";", "/** @var Builder $filesQuery */", "$", "filesQuery", "=", "$", "filesRelation", "->", "ofField", "(", "$", "fieldName", ")", ";", "/** @var File[] $files */", "$", "files", "=", "$", "filesQuery", "->", "get", "(", ")", ";", "// Delete the previous files of this field, if any exists.", "foreach", "(", "$", "files", "as", "$", "file", ")", "$", "file", "->", "delete", "(", ")", ";", "}", "}" ]
Handle the case where no file has been uploaded for a field, but the field may have been cleared. @param BaseModel|FilesModelTrait $model @param string $fieldName @throws \Exception
[ "Handle", "the", "case", "where", "no", "file", "has", "been", "uploaded", "for", "a", "field", "but", "the", "field", "may", "have", "been", "cleared", "." ]
3a746f796157ef72b585a5994394483fbe500861
https://github.com/electro-modules/matisse-components/blob/3a746f796157ef72b585a5994394483fbe500861/MatisseComponents/Handlers/FileFieldHandler.php#L191-L205
35,992
stubbles/stubbles-console
src/main/php/creator/FileCreator.php
FileCreator.fileNameforClass
protected function fileNameforClass(string $className, string $type = 'main'): string { if (file_exists($this->rootpath->to('composer.json'))) { $composer = json_decode( file_get_contents($this->rootpath->to('composer.json')), true ); if (isset($composer['autoload']['psr-4'])) { return $this->fileNameForPsr4( $composer['autoload']['psr-4'], $className, $type ); } } // assume psr-0 with standard stubbles pathes return $this->rootpath->to( 'src', $type, 'php', str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php' ); }
php
protected function fileNameforClass(string $className, string $type = 'main'): string { if (file_exists($this->rootpath->to('composer.json'))) { $composer = json_decode( file_get_contents($this->rootpath->to('composer.json')), true ); if (isset($composer['autoload']['psr-4'])) { return $this->fileNameForPsr4( $composer['autoload']['psr-4'], $className, $type ); } } // assume psr-0 with standard stubbles pathes return $this->rootpath->to( 'src', $type, 'php', str_replace('\\', DIRECTORY_SEPARATOR, $className) . '.php' ); }
[ "protected", "function", "fileNameforClass", "(", "string", "$", "className", ",", "string", "$", "type", "=", "'main'", ")", ":", "string", "{", "if", "(", "file_exists", "(", "$", "this", "->", "rootpath", "->", "to", "(", "'composer.json'", ")", ")", ")", "{", "$", "composer", "=", "json_decode", "(", "file_get_contents", "(", "$", "this", "->", "rootpath", "->", "to", "(", "'composer.json'", ")", ")", ",", "true", ")", ";", "if", "(", "isset", "(", "$", "composer", "[", "'autoload'", "]", "[", "'psr-4'", "]", ")", ")", "{", "return", "$", "this", "->", "fileNameForPsr4", "(", "$", "composer", "[", "'autoload'", "]", "[", "'psr-4'", "]", ",", "$", "className", ",", "$", "type", ")", ";", "}", "}", "// assume psr-0 with standard stubbles pathes", "return", "$", "this", "->", "rootpath", "->", "to", "(", "'src'", ",", "$", "type", ",", "'php'", ",", "str_replace", "(", "'\\\\'", ",", "DIRECTORY_SEPARATOR", ",", "$", "className", ")", ".", "'.php'", ")", ";", "}" ]
returns name of class file to create @param string $className @param string $type @return string
[ "returns", "name", "of", "class", "file", "to", "create" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/creator/FileCreator.php#L67-L90
35,993
stubbles/stubbles-console
src/main/php/creator/FileCreator.php
FileCreator.fileNameForPsr4
private function fileNameForPsr4(array $psr4Pathes, string $className, string $type): string { foreach ($psr4Pathes as $prefix => $path) { if (substr($className, 0, strlen($prefix)) === $prefix) { return $this->rootpath->to( str_replace('main', $type, $path), str_replace( '\\', DIRECTORY_SEPARATOR, str_replace($prefix, '', $className) ) . '.php' ); } } throw new \UnexpectedValueException( 'No PSR-4 path for class ' . $className . ' found in composer.json' ); }
php
private function fileNameForPsr4(array $psr4Pathes, string $className, string $type): string { foreach ($psr4Pathes as $prefix => $path) { if (substr($className, 0, strlen($prefix)) === $prefix) { return $this->rootpath->to( str_replace('main', $type, $path), str_replace( '\\', DIRECTORY_SEPARATOR, str_replace($prefix, '', $className) ) . '.php' ); } } throw new \UnexpectedValueException( 'No PSR-4 path for class ' . $className . ' found in composer.json' ); }
[ "private", "function", "fileNameForPsr4", "(", "array", "$", "psr4Pathes", ",", "string", "$", "className", ",", "string", "$", "type", ")", ":", "string", "{", "foreach", "(", "$", "psr4Pathes", "as", "$", "prefix", "=>", "$", "path", ")", "{", "if", "(", "substr", "(", "$", "className", ",", "0", ",", "strlen", "(", "$", "prefix", ")", ")", "===", "$", "prefix", ")", "{", "return", "$", "this", "->", "rootpath", "->", "to", "(", "str_replace", "(", "'main'", ",", "$", "type", ",", "$", "path", ")", ",", "str_replace", "(", "'\\\\'", ",", "DIRECTORY_SEPARATOR", ",", "str_replace", "(", "$", "prefix", ",", "''", ",", "$", "className", ")", ")", ".", "'.php'", ")", ";", "}", "}", "throw", "new", "\\", "UnexpectedValueException", "(", "'No PSR-4 path for class '", ".", "$", "className", ".", "' found in composer.json'", ")", ";", "}" ]
retrieve psr-4 compatible file name @param array $psr4Pathes map of psr-4 pathes from composer.json @param string $className name of class to retrieve file name for @param string $type whether it a normal class or a test class @return string @throws \UnexpectedValueException
[ "retrieve", "psr", "-", "4", "compatible", "file", "name" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/creator/FileCreator.php#L101-L119
35,994
stubbles/stubbles-console
src/main/php/creator/FileCreator.php
FileCreator.createFile
protected function createFile(string $fileName, string $className, string $template) { $directory = dirname($fileName); if (!file_exists($directory . '/.')) { mkdir($directory, 0755, true); } file_put_contents( $fileName, str_replace( ['{NAMESPACE}', '{CLASS}'], [$this->namespaceOf($className), $this->nonQualifiedClassNameOf($className) ], $this->resourceLoader->load($this->pathForTemplate($template)) ) ); }
php
protected function createFile(string $fileName, string $className, string $template) { $directory = dirname($fileName); if (!file_exists($directory . '/.')) { mkdir($directory, 0755, true); } file_put_contents( $fileName, str_replace( ['{NAMESPACE}', '{CLASS}'], [$this->namespaceOf($className), $this->nonQualifiedClassNameOf($className) ], $this->resourceLoader->load($this->pathForTemplate($template)) ) ); }
[ "protected", "function", "createFile", "(", "string", "$", "fileName", ",", "string", "$", "className", ",", "string", "$", "template", ")", "{", "$", "directory", "=", "dirname", "(", "$", "fileName", ")", ";", "if", "(", "!", "file_exists", "(", "$", "directory", ".", "'/.'", ")", ")", "{", "mkdir", "(", "$", "directory", ",", "0755", ",", "true", ")", ";", "}", "file_put_contents", "(", "$", "fileName", ",", "str_replace", "(", "[", "'{NAMESPACE}'", ",", "'{CLASS}'", "]", ",", "[", "$", "this", "->", "namespaceOf", "(", "$", "className", ")", ",", "$", "this", "->", "nonQualifiedClassNameOf", "(", "$", "className", ")", "]", ",", "$", "this", "->", "resourceLoader", "->", "load", "(", "$", "this", "->", "pathForTemplate", "(", "$", "template", ")", ")", ")", ")", ";", "}" ]
creates file of given type for given class @param string $fileName @param string $className @param string $template
[ "creates", "file", "of", "given", "type", "for", "given", "class" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/creator/FileCreator.php#L128-L145
35,995
stubbles/stubbles-console
src/main/php/creator/FileCreator.php
FileCreator.pathForTemplate
private function pathForTemplate(string $template): string { $pathes = $this->resourceLoader->availableResourceUris('creator/' . $template); if (!isset($pathes[0])) { throw new \RuntimeException('Could not load template ' . $template); } return $pathes[0]; }
php
private function pathForTemplate(string $template): string { $pathes = $this->resourceLoader->availableResourceUris('creator/' . $template); if (!isset($pathes[0])) { throw new \RuntimeException('Could not load template ' . $template); } return $pathes[0]; }
[ "private", "function", "pathForTemplate", "(", "string", "$", "template", ")", ":", "string", "{", "$", "pathes", "=", "$", "this", "->", "resourceLoader", "->", "availableResourceUris", "(", "'creator/'", ".", "$", "template", ")", ";", "if", "(", "!", "isset", "(", "$", "pathes", "[", "0", "]", ")", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Could not load template '", ".", "$", "template", ")", ";", "}", "return", "$", "pathes", "[", "0", "]", ";", "}" ]
finds absolute path for given template file @param string $template @return string @throws \RuntimeException
[ "finds", "absolute", "path", "for", "given", "template", "file" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/creator/FileCreator.php#L154-L162
35,996
stubbles/stubbles-console
src/main/php/input/ArgumentParser.php
ArgumentParser.parseArgs
private function parseArgs(): array { if (null === $this->options && count($this->longopts) === 0 && null === $this->userInput) { return $this->fixArgs($_SERVER['argv']); } if (null !== $this->userInput) { $this->collectOptionsFromUserInputClass(); } $parseCommandLineOptions = $this->cliOptionParser; $parsedVars = $parseCommandLineOptions($this->options, $this->longopts); if (false === $parsedVars) { throw new \RuntimeException( 'Error parsing "' . join(' ', $_SERVER['argv']) . '" with ' . $this->options . ' and ' . join(' ', $this->longopts) ); } return $this->fixArgs($_SERVER['argv'], $parsedVars); }
php
private function parseArgs(): array { if (null === $this->options && count($this->longopts) === 0 && null === $this->userInput) { return $this->fixArgs($_SERVER['argv']); } if (null !== $this->userInput) { $this->collectOptionsFromUserInputClass(); } $parseCommandLineOptions = $this->cliOptionParser; $parsedVars = $parseCommandLineOptions($this->options, $this->longopts); if (false === $parsedVars) { throw new \RuntimeException( 'Error parsing "' . join(' ', $_SERVER['argv']) . '" with ' . $this->options . ' and ' . join(' ', $this->longopts) ); } return $this->fixArgs($_SERVER['argv'], $parsedVars); }
[ "private", "function", "parseArgs", "(", ")", ":", "array", "{", "if", "(", "null", "===", "$", "this", "->", "options", "&&", "count", "(", "$", "this", "->", "longopts", ")", "===", "0", "&&", "null", "===", "$", "this", "->", "userInput", ")", "{", "return", "$", "this", "->", "fixArgs", "(", "$", "_SERVER", "[", "'argv'", "]", ")", ";", "}", "if", "(", "null", "!==", "$", "this", "->", "userInput", ")", "{", "$", "this", "->", "collectOptionsFromUserInputClass", "(", ")", ";", "}", "$", "parseCommandLineOptions", "=", "$", "this", "->", "cliOptionParser", ";", "$", "parsedVars", "=", "$", "parseCommandLineOptions", "(", "$", "this", "->", "options", ",", "$", "this", "->", "longopts", ")", ";", "if", "(", "false", "===", "$", "parsedVars", ")", "{", "throw", "new", "\\", "RuntimeException", "(", "'Error parsing \"'", ".", "join", "(", "' '", ",", "$", "_SERVER", "[", "'argv'", "]", ")", ".", "'\" with '", ".", "$", "this", "->", "options", ".", "' and '", ".", "join", "(", "' '", ",", "$", "this", "->", "longopts", ")", ")", ";", "}", "return", "$", "this", "->", "fixArgs", "(", "$", "_SERVER", "[", "'argv'", "]", ",", "$", "parsedVars", ")", ";", "}" ]
returns parsed arguments @return array @throws \RuntimeException
[ "returns", "parsed", "arguments" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/input/ArgumentParser.php#L141-L162
35,997
stubbles/stubbles-console
src/main/php/input/ArgumentParser.php
ArgumentParser.fixArgs
private function fixArgs(array $args, array $parsedVars = []): array { array_shift($args); // script name $vars = []; $position = 0; foreach ($args as $arg) { if (isset($parsedVars[substr($arg, 1)]) || isset($parsedVars[substr($arg, 2)]) || in_array($arg, $parsedVars)) { continue; } $vars['argv.' . $position] = $arg; $position++; } return array_merge($vars, $parsedVars); }
php
private function fixArgs(array $args, array $parsedVars = []): array { array_shift($args); // script name $vars = []; $position = 0; foreach ($args as $arg) { if (isset($parsedVars[substr($arg, 1)]) || isset($parsedVars[substr($arg, 2)]) || in_array($arg, $parsedVars)) { continue; } $vars['argv.' . $position] = $arg; $position++; } return array_merge($vars, $parsedVars); }
[ "private", "function", "fixArgs", "(", "array", "$", "args", ",", "array", "$", "parsedVars", "=", "[", "]", ")", ":", "array", "{", "array_shift", "(", "$", "args", ")", ";", "// script name", "$", "vars", "=", "[", "]", ";", "$", "position", "=", "0", ";", "foreach", "(", "$", "args", "as", "$", "arg", ")", "{", "if", "(", "isset", "(", "$", "parsedVars", "[", "substr", "(", "$", "arg", ",", "1", ")", "]", ")", "||", "isset", "(", "$", "parsedVars", "[", "substr", "(", "$", "arg", ",", "2", ")", "]", ")", "||", "in_array", "(", "$", "arg", ",", "$", "parsedVars", ")", ")", "{", "continue", ";", "}", "$", "vars", "[", "'argv.'", ".", "$", "position", "]", "=", "$", "arg", ";", "$", "position", "++", ";", "}", "return", "array_merge", "(", "$", "vars", ",", "$", "parsedVars", ")", ";", "}" ]
retrieves list of arguments @param array $args @param array $parsedVars @return array
[ "retrieves", "list", "of", "arguments" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/input/ArgumentParser.php#L171-L186
35,998
stubbles/stubbles-console
src/main/php/input/ArgumentParser.php
ArgumentParser.collectOptionsFromUserInputClass
private function collectOptionsFromUserInputClass() { foreach (RequestBroker::targetMethodsOf($this->userInput) as $targetMethod) { $name = $targetMethod->paramName(); if (substr($name, 0, 5) === 'argv.') { continue; } if (strlen($name) === 1) { $this->options .= $name . ($targetMethod->requiresParameter() ? ':' : ''); } else { $this->longopts[] = $name . ($targetMethod->requiresParameter() ? ':' : ''); } } if (null === $this->options || !strpos($this->options, 'h')) { $this->options .= 'h'; } if (!in_array('help', $this->longopts)) { $this->longopts[] = 'help'; } }
php
private function collectOptionsFromUserInputClass() { foreach (RequestBroker::targetMethodsOf($this->userInput) as $targetMethod) { $name = $targetMethod->paramName(); if (substr($name, 0, 5) === 'argv.') { continue; } if (strlen($name) === 1) { $this->options .= $name . ($targetMethod->requiresParameter() ? ':' : ''); } else { $this->longopts[] = $name . ($targetMethod->requiresParameter() ? ':' : ''); } } if (null === $this->options || !strpos($this->options, 'h')) { $this->options .= 'h'; } if (!in_array('help', $this->longopts)) { $this->longopts[] = 'help'; } }
[ "private", "function", "collectOptionsFromUserInputClass", "(", ")", "{", "foreach", "(", "RequestBroker", "::", "targetMethodsOf", "(", "$", "this", "->", "userInput", ")", "as", "$", "targetMethod", ")", "{", "$", "name", "=", "$", "targetMethod", "->", "paramName", "(", ")", ";", "if", "(", "substr", "(", "$", "name", ",", "0", ",", "5", ")", "===", "'argv.'", ")", "{", "continue", ";", "}", "if", "(", "strlen", "(", "$", "name", ")", "===", "1", ")", "{", "$", "this", "->", "options", ".=", "$", "name", ".", "(", "$", "targetMethod", "->", "requiresParameter", "(", ")", "?", "':'", ":", "''", ")", ";", "}", "else", "{", "$", "this", "->", "longopts", "[", "]", "=", "$", "name", ".", "(", "$", "targetMethod", "->", "requiresParameter", "(", ")", "?", "':'", ":", "''", ")", ";", "}", "}", "if", "(", "null", "===", "$", "this", "->", "options", "||", "!", "strpos", "(", "$", "this", "->", "options", ",", "'h'", ")", ")", "{", "$", "this", "->", "options", ".=", "'h'", ";", "}", "if", "(", "!", "in_array", "(", "'help'", ",", "$", "this", "->", "longopts", ")", ")", "{", "$", "this", "->", "longopts", "[", "]", "=", "'help'", ";", "}", "}" ]
parses options from user input class
[ "parses", "options", "from", "user", "input", "class" ]
9b8d8e0d92e3c6b629a0fa860ace957016d20047
https://github.com/stubbles/stubbles-console/blob/9b8d8e0d92e3c6b629a0fa860ace957016d20047/src/main/php/input/ArgumentParser.php#L191-L213
35,999
GrottoPress/jentil
app/libraries/Jentil/Utilities/Page.php
Page.getType
private function getType(): array { if (!$this->type || $this->is('customize_preview')) { $this->type = parent::type(); } return $this->type; }
php
private function getType(): array { if (!$this->type || $this->is('customize_preview')) { $this->type = parent::type(); } return $this->type; }
[ "private", "function", "getType", "(", ")", ":", "array", "{", "if", "(", "!", "$", "this", "->", "type", "||", "$", "this", "->", "is", "(", "'customize_preview'", ")", ")", "{", "$", "this", "->", "type", "=", "parent", "::", "type", "(", ")", ";", "}", "return", "$", "this", "->", "type", ";", "}" ]
Page type is used too many times on archives for getting posts mods, so let's make sure method is called only once per page cycle, except, of course, in the customizer. @return string[int]
[ "Page", "type", "is", "used", "too", "many", "times", "on", "archives", "for", "getting", "posts", "mods", "so", "let", "s", "make", "sure", "method", "is", "called", "only", "once", "per", "page", "cycle", "except", "of", "course", "in", "the", "customizer", "." ]
ad3341c91e0386256d4a2fbe8b7a201c9b706c10
https://github.com/GrottoPress/jentil/blob/ad3341c91e0386256d4a2fbe8b7a201c9b706c10/app/libraries/Jentil/Utilities/Page.php#L82-L89