_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q239800
|
Arr.filterNullValues
|
train
|
public static function filterNullValues($properties, array $allowed = null)
{
// If provided, only use allowed properties
$properties = static::only($properties, $allowed);
return array_filter(
$properties,
function ($value) {
return !is_null($value);
}
);
}
|
php
|
{
"resource": ""
}
|
q239801
|
Arr.filterKeys
|
train
|
public static function filterKeys(array $input, $included = [])
{
if (is_null($included) || count($included) == 0) {
return $input;
}
return array_intersect_key($input, array_flip($included));
}
|
php
|
{
"resource": ""
}
|
q239802
|
Arr.except
|
train
|
public static function except(array $input, $excluded = [])
{
Arguments::define(Boa::arrOf(Boa::either(
Boa::string(),
Boa::integer()
)))->check($excluded);
return Std::filter(function ($_, $key) use ($excluded) {
return !in_array($key, $excluded);
},
$input);
}
|
php
|
{
"resource": ""
}
|
q239803
|
Arr.exchange
|
train
|
public static function exchange(array &$elements, $indexA, $indexB)
{
$count = count($elements);
if (($indexA < 0 || $indexA > ($count - 1))
|| $indexB < 0
|| $indexB > ($count - 1)
) {
throw new IndexOutOfBoundsException();
}
$temp = $elements[$indexA];
$elements[$indexA] = $elements[$indexB];
$elements[$indexB] = $temp;
}
|
php
|
{
"resource": ""
}
|
q239804
|
Arr.indexOf
|
train
|
public static function indexOf(array $input, $value)
{
foreach ($input as $key => $inputValue) {
if ($inputValue === $value) {
return $key;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239805
|
CacheFactory.store
|
train
|
public function store($name = null)
{
if (is_null($name)) {
$name = $this->defaultStore;
}
if (isset($this->caches[$name])) {
return $this->caches[$name];
}
$config = config('cache.stores.' . $name);
if ($config === null) {
throw new InvalidArgumentException('Cache store "' . $name . '" is not defined.');
}
if (!isset($config['driver'])) {
throw new InvalidArgumentException('Cache driver for store "' . $name . '" is not specified.');
}
switch ($config['driver']) {
case 'APCu':
$provider = new ApcuCache;
break;
case 'Array':
$provider = new ArrayCache;
break;
case 'File':
$provider = new FilesystemCache($config['path']);
break;
case 'Memcached':
$memcached = new Memcached();
$memcached->addServer($config['host'], $config['port'], $config['weight']);
$provider = new MemcachedCache();
$provider->setMemcached($memcached);
break;
case 'Redis':
$redis = new Redis;
$redis->connect($config['host'], $config['port'], $config['timeout']);
$provider = new RedisCache;
$provider->setRedis($redis);
break;
default:
throw new InvalidArgumentException('Cache driver "' . $config['driver'] . '" is not supported.');
}
return $this->caches[$name] = new Cache($provider);
}
|
php
|
{
"resource": ""
}
|
q239806
|
FilesystemCache.generatePathname
|
train
|
protected function generatePathname($id)
{
if (!file_exists($this->basePath)) {
mkdir($this->basePath, 0777, true);
}
return $this->basePath.'/'.$id;
}
|
php
|
{
"resource": ""
}
|
q239807
|
GroupLabelCssClasses.&
|
train
|
public function & SetGroupLabelCssClasses ($groupLabelCssClasses) {
/** @var $this \MvcCore\Ext\Forms\IField */
if (gettype($groupLabelCssClasses) == 'array') {
$this->groupLabelCssClasses = $groupLabelCssClasses;
} else {
$this->groupLabelCssClasses = explode(' ', (string) $groupLabelCssClasses);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239808
|
GroupLabelCssClasses.AddGroupLabelCssClasses
|
train
|
public function AddGroupLabelCssClasses ($groupLabelCssClasses) {
/** @var $this \MvcCore\Ext\Forms\IField */
if (gettype($groupLabelCssClasses) == 'array') {
$groupCssClasses = $groupLabelCssClasses;
} else {
$groupCssClasses = explode(' ', (string) $groupLabelCssClasses);
}
$this->groupLabelCssClasses = array_merge($this->groupLabelCssClasses, $groupCssClasses);
return $this;
}
|
php
|
{
"resource": ""
}
|
q239809
|
Plugin.changeUserMode
|
train
|
public function changeUserMode(EventInterface $event, EventQueueInterface $queue)
{
$logger = $this->getLogger();
$params = $event->getParams();
$logger->debug('Changing user mode', array('params' => $params));
// Disregard mode changes without both an associated channel and user
if (!isset($params['channel']) || !isset($params['user'])) {
$logger->debug('Missing channel or user, skipping');
return;
}
$connectionMask = $this->getConnectionMask($event->getConnection());
$channel = $params['channel'];
$nick = $params['user'];
$modes = str_split($params['mode']);
$operation = array_shift($modes);
$logger->debug('Extracted event data', array(
'connectionMask' => $connectionMask,
'channel' => $channel,
'nick' => $nick,
'operation' => $operation,
'modes' => $modes,
));
foreach ($modes as $mode) {
switch ($operation) {
case '+':
if (!isset($this->modes[$connectionMask])) {
$this->modes[$connectionMask] = array();
}
if (!isset($this->modes[$connectionMask][$channel])) {
$this->modes[$connectionMask][$channel] = array();
}
if (!isset($this->modes[$connectionMask][$channel][$nick])) {
$this->modes[$connectionMask][$channel][$nick] = array();
}
$this->modes[$connectionMask][$channel][$nick][$mode] = true;
break;
case '-':
unset($this->modes[$connectionMask][$channel][$nick][$mode]);
break;
default:
$logger->warning('Encountered unknown operation', array(
'operation' => $operation,
));
break;
}
}
}
|
php
|
{
"resource": ""
}
|
q239810
|
Plugin.removeUserData
|
train
|
protected function removeUserData($connectionMask, array $channels, $nick)
{
$logger = $this->getLogger();
foreach ($channels as $channel) {
$logger->debug('Removing user mode data', array(
'connectionMask' => $connectionMask,
'channel' => $channel,
'nick' => $nick,
));
unset($this->modes[$connectionMask][$channel][$nick]);
}
}
|
php
|
{
"resource": ""
}
|
q239811
|
Plugin.changeUserNick
|
train
|
public function changeUserNick(UserEventInterface $event, EventQueueInterface $queue)
{
$logger = $this->getLogger();
$connectionMask = $this->getConnectionMask($event->getConnection());
$old = $event->getNick();
$params = $event->getParams();
$new = $params['nickname'];
$logger->debug('Changing user nick', array(
'connectionMask' => $connectionMask,
'oldNick' => $old,
'newNick' => $new,
));
foreach (array_keys($this->modes[$connectionMask]) as $channel) {
if (!isset($this->modes[$connectionMask][$channel][$old])) {
continue;
}
$logger->debug('Moving user mode data', array(
'connectionMask' => $connectionMask,
'channel' => $channel,
'oldNick' => $old,
'newNick' => $new,
));
$this->modes[$connectionMask][$channel][$new] = $this->modes[$connectionMask][$channel][$old];
unset($this->modes[$connectionMask][$channel][$old]);
}
}
|
php
|
{
"resource": ""
}
|
q239812
|
Plugin.loadUserModes
|
train
|
public function loadUserModes(EventInterface $event, EventQueueInterface $queue)
{
$logger = $this->getLogger();
$connectionMask = $this->getConnectionMask($event->getConnection());
$params = $event->getParams();
$channel = $params[1];
$validPrefixes = implode('', array_keys($this->prefixes));
$pattern = '/^([' . preg_quote($validPrefixes) . ']+)(.+)$/';
$logger->debug('Gathering initial user mode data', array(
'connectionMask' => $connectionMask,
'channel' => $channel,
));
foreach ($params['iterable'] as $fullNick) {
if (!preg_match($pattern, $fullNick, $match)) {
continue;
}
$nickPrefixes = str_split($match[1]);
$nick = $match[2];
foreach ($nickPrefixes as $prefix) {
$mode = $this->prefixes[$prefix];
$logger->debug('Recording user mode', array(
'connectionMask' => $connectionMask,
'channel' => $channel,
'nick' => $nick,
'mode' => $mode,
));
$this->modes[$connectionMask][$channel][$nick][$mode] = true;
}
}
}
|
php
|
{
"resource": ""
}
|
q239813
|
Plugin.userHasMode
|
train
|
public function userHasMode(ConnectionInterface $connection, $channel, $nick, $mode)
{
$connectionMask = $this->getConnectionMask($connection);
return isset($this->modes[$connectionMask][$channel][$nick][$mode]);
}
|
php
|
{
"resource": ""
}
|
q239814
|
Plugin.getUserModes
|
train
|
public function getUserModes(ConnectionInterface $connection, $channel, $nick)
{
$connectionMask = $this->getConnectionMask($connection);
if (isset($this->modes[$connectionMask][$channel][$nick])) {
return array_keys($this->modes[$connectionMask][$channel][$nick]);
}
return array();
}
|
php
|
{
"resource": ""
}
|
q239815
|
Plugin.getConnectionMask
|
train
|
protected function getConnectionMask(ConnectionInterface $connection)
{
return strtolower(sprintf(
'%s!%s@%s',
$connection->getNickname(),
$connection->getUsername(),
$connection->getServerHostname()
));
}
|
php
|
{
"resource": ""
}
|
q239816
|
Container.make
|
train
|
public function make(string $name, array $params = null)
{
if (isset($this->bindings[$name]))
return $this->bindings[$name];
// cached constructor lists
static $constructors = null;
if (isset($constructors[$name])) {
$constructor = $constructors[$name];
}
else {
$constructors[$name] = $constructor = method_exists($name, '__construct') ? new \ReflectionMethod($name, '__construct') : null;
}
return $constructor ?
(new \ReflectionClass($name))->newInstanceArgs($this->_buildArgList($constructor, $params)) :
(new \ReflectionClass($name))->newInstance();
}
|
php
|
{
"resource": ""
}
|
q239817
|
Configuration.base
|
train
|
public static function base()
{
// Charset by default
self::write('application.encoding', 'UTF8');
// Application environnement
self::write('application.env', 'dev');
// Application name
self::write('application.name', 'Awesome Application');
// Namespace for application
self::write('application.namespace', '\App');
// Absolute path to application
self::write('application.path', 'auto');
// Defined if bootstrap is use by application
self::write('bootstrap.enable', true);
// Set config file for route collection
self::write('database.config.enable', true);
// Set config file for route collection
self::write('database.config.file', 'databases.php');
// Set debug level to all
self::write('debug.level', E_ALL);
// Define if script file existence is tested
self::write('html.script.test_file_existance', true);
// Define if css file existence is tested
self::write('html.css.test_file_existance', true);
// Set autoloading of shared var between componant
self::write('mvc.autoload_shared_var', true);
// Set namespace for controller
self::write('mvc.controller.namespace', '\App\Controller');
// Set namespace for layout
self::write('mvc.layout.namespace', '\App\Layout');
// Set path for Layout
self::write('mvc.layout.path', '/src/Layout');
// Set default layout
self::write('mvc.layout.default', 'Application');
// Set extension for layout
self::write('mvc.layout.extension', 'php');
// Set auto render for layout
self::write('mvc.layout.auto_render', true);
// Set namespace for model
self::write('mvc.model.namespace', '\App\Model');
// Set auto render for view
self::write('mvc.view.auto_render', true);
// Set extension for view
self::write('mvc.view.extension', 'php');
// Set path for view
self::write('mvc.view.path', '/src/View');
// Set auto routing
self::write('routing.auto', true);
// Set config file for route collection
self::write('routing.config.enable', true);
// Set config file for route collection
self::write('routing.config.file', 'routes.php');
// Set error action (if not route is avaiable)
self::write('routing.fallback.action', 'index');
// Set error controller (if not route is avaiable)
self::write('routing.fallback.controller', 'Error');
// Set config file for route collection
self::write('routing.default_separator', '/');
}
|
php
|
{
"resource": ""
}
|
q239818
|
Configuration.prepare
|
train
|
public static function prepare($key, $value)
{
if ($value == 'true') {
return true;
} elseif ($value == 'false') {
return false;
} elseif ($key == 'debug.level' && substr($value, 0, 2) == "E_") {
return eval('return ' . $value . ';');
} elseif ($key == 'application.path' && ($value === false || $value === 'false' || $value === 'auto')) {
$sLibraryPath = DS . 'vendor' . DS . 'pabana' . DS . 'pabana' . DS . 'src' . DS . 'Core';
return str_replace($sLibraryPath, '', __DIR__);
}
return $value;
}
|
php
|
{
"resource": ""
}
|
q239819
|
Configuration.prepareArray
|
train
|
public static function prepareArray($configList)
{
$preparedConfigList = array();
foreach ($configList as $key => $value) {
$preparedConfigList[$key] = self::prepare($key, $value);
}
return $preparedConfigList;
}
|
php
|
{
"resource": ""
}
|
q239820
|
Configuration.read
|
train
|
public static function read($key)
{
// Check key existence
if (!self::check($key)) {
throw new \Exception('Configuration key "' . $key . '" doesn\'t exists');
return false;
}
// Get value of key
return self::$configList[$key];
}
|
php
|
{
"resource": ""
}
|
q239821
|
Configuration.write
|
train
|
public static function write($key, $value, $force = true)
{
// Check key existence
if (self::check($key) && $force === false) {
throw new \Exception('Configuration key "' . $key . '" already exist (use force argument to modify an already defined key).');
return false;
}
// Prepare value (transform 'true' to true, etc...)
$preparedValue = self::prepare($key, $value);
// Write value content
self::$configList[$key] = $preparedValue;
return true;
}
|
php
|
{
"resource": ""
}
|
q239822
|
MediaPathGenerator.generate
|
train
|
public function generate(MediaProviderInterface $mediaProvider)
{
$path = rtrim($this->basePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR .
$mediaProvider->getMedia()->getContext() . DIRECTORY_SEPARATOR .
date('Y') . DIRECTORY_SEPARATOR .
date('m') . DIRECTORY_SEPARATOR .
date('d')
;
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
return $path;
}
|
php
|
{
"resource": ""
}
|
q239823
|
GUIDGenerator.generate
|
train
|
public function generate(string $content = null): string
{
if (empty($content)) {
$guid = Uuid::uuid4();
} else {
$guid = Uuid::uuid5(Uuid::NAMESPACE_DNS, $content);
}
return $guid->toString();
}
|
php
|
{
"resource": ""
}
|
q239824
|
Dump.html
|
train
|
public static function html() {
$fargs = func_get_args();
$mode = self::enabled();
self::enabled(self::MODE_RICH);
$ret = self::dump(empty($fargs) ? null : $fargs[0]);
self::enabled($mode);
return $ret;
}
|
php
|
{
"resource": ""
}
|
q239825
|
iForm.addFormField
|
train
|
public function addFormField($type, $params = array()) {
$namespace = "\\iJos\\iForms\\Fields\\" . ucfirst($type);
$field = new $namespace( $params );
array_push($this -> form_fields, $field);
}
|
php
|
{
"resource": ""
}
|
q239826
|
FormTagTrait.normalizeFormFieldTagParams
|
train
|
public function normalizeFormFieldTagParams($name, $value, array $attributes, $fieldType = null)
{
if (!isset($attributes['id'])) {
$attributes['id'] = trim(
str_replace(['[', ']', '()', '__'], ['_', '_', '', '_'], $name),
'_'
);
}
if ($name) {
$attributes['name'] = $name;
}
return [$name, (string)$value, $attributes];
}
|
php
|
{
"resource": ""
}
|
q239827
|
FormTagTrait.normalizeFormTagOptions
|
train
|
public function normalizeFormTagOptions($urlOptions, $options, $block)
{
if (!$urlOptions || !$options || !$block) {
if ($urlOptions instanceof Closure) {
$block = $urlOptions;
$urlOptions = null;
$options = [];
} elseif (is_array($urlOptions) && is_string(key($urlOptions))) {
$block = $options;
$options = $urlOptions;
$urlOptions = null;
} elseif ($options instanceof Closure) {
$block = $options;
$options = [];
}
}
if (!$block instanceof Closure) {
throw new Exception\BadMethodCallException(
"One of the arguments for formTag must be a Closure"
);
}
if (empty($options['method'])) {
$options['method'] = 'post';
}
if (!empty($options['multipart'])) {
$options['enctype'] = 'multipart/form-data';
unset($options['multipart']);
}
if ($urlOptions) {
if (!$this->isUrl($urlOptions)) {
$options['action'] = $this->urlFor($urlOptions);
} else {
$options['action'] = $urlOptions;
}
}
return [$urlOptions, $options, $block];
}
|
php
|
{
"resource": ""
}
|
q239828
|
FormTagTrait.runContentBlock
|
train
|
protected function runContentBlock(Closure $block)
{
ob_start();
$result = $block();
$contents = ob_get_clean();
return $result ?: $contents;
}
|
php
|
{
"resource": ""
}
|
q239829
|
FormTagTrait.normalizeSizeOption
|
train
|
protected function normalizeSizeOption(array &$options)
{
if (isset($options['size'])) {
$size = explode('x', $options['size']);
if (
isset($size[0]) &&
isset($size[1])
) {
list($options['cols'], $options['rows']) = $size;
}
unset($options['size']);
}
}
|
php
|
{
"resource": ""
}
|
q239830
|
JavascriptHandler.&
|
train
|
public function &createScript($content, $defer = true, $combine = true, $minify = true): JavascriptObjectInterface
{
$obj = new JavascriptObject();
$obj->setType($obj::TYPE_SCRIPT);
$obj->setContent($content);
$obj->setDefer($defer);
$obj->setCombine($combine);
$obj->setMinify($minify);
$this->addObject($obj);
return $obj;
}
|
php
|
{
"resource": ""
}
|
q239831
|
JavascriptHandler.&
|
train
|
public function &createBlock($content, $defer = true, $combine = true, $minify = true): JavascriptObjectInterface
{
$obj = new JavascriptObject();
$obj->setType($obj::TYPE_BLOCK);
$obj->setContent($content);
$obj->setDefer($defer);
$obj->setCombine($combine);
$obj->setMinify($minify);
$this->addObject($obj);
return $obj;
}
|
php
|
{
"resource": ""
}
|
q239832
|
Request.matchUrl
|
train
|
public function matchUrl($pattern)
{
if ($this->matchValue($this->getUrl(), $pattern)) {
return $this->getUrl();
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239833
|
Request.matchHeader
|
train
|
public function matchHeader($name, $pattern = null)
{
if (isset($this->getHeaders()[$name])) {
if (!empty($pattern)) {
if ($this->matchValue($this->getHeaders()[$name], $pattern)) {
return $this->getHeaders()[$name];
}
} else {
if (empty($this->getHeaders()[$name])) {
return true;
} else {
return $this->getHeaders()[$name];
}
}
} elseif ($pattern == '?') {
// in case of optional pattern we just return true
return true;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239834
|
Request.matchCookie
|
train
|
public function matchCookie($name, $pattern = null)
{
if (isset($this->getCookies()[$name])) {
if (!empty($pattern)) {
if ($this->matchValue($this->getCookies()[$name], $pattern)) {
return $this->getCookies()[$name];
}
} else {
if (empty($this->getCookies()[$name])) {
return true;
} else {
return $this->getCookies()[$name];
}
}
} elseif ($pattern == '?') {
// in case of optional pattern we just return true
return true;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239835
|
Request.matchQueryParam
|
train
|
public function matchQueryParam($name, $pattern = null)
{
if (isset($this->getQueryParams()[$name])) {
if (!empty($pattern)) {
if ($this->matchValue($this->getQueryParams()[$name], $pattern)) {
return $this->getQueryParams()[$name];
}
} else {
if (empty($this->getQueryParams()[$name])) {
return true;
} else {
return $this->getQueryParams()[$name];
}
}
} elseif ($pattern == '?') {
// in case of optional pattern we just return true
return true;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239836
|
Request.matchValue
|
train
|
private function matchValue($value, $pattern)
{
// basic check
if ($value == $pattern) {
return true;
}
// simple check in case of optional param
if ($pattern == '?') {
return true;
}
// simple match in case pattern is just "*"
if ($pattern == '*' && $value != '') {
return true;
}
// more complex match in case when wildcard is part of a larger match
$pattern = str_replace('*', '(.+)', $pattern);
// regex match
if (strpos($pattern, '(') !== false || strpos($pattern, '[') !== false || strpos($pattern, '\\') !== false) {
return preg_match('#^' . $pattern . '$#', $value);
}
return false;
}
|
php
|
{
"resource": ""
}
|
q239837
|
Encode.strlen
|
train
|
protected static function strlen($text)
{
$exits = (function_exists('mb_strlen') && ((int) ini_get('mbstring.func_overload')) & 2);
return $exits ? mb_strlen($text,'8bit') : strlen($text);
}
|
php
|
{
"resource": ""
}
|
q239838
|
Encode.normalizeEncoding
|
train
|
protected static function normalizeEncoding($encodingLabel)
{
$encoding = strtoupper($encodingLabel);
$encoding = preg_replace('/[^a-zA-Z0-9\s]/', '', $encoding);
$equivalences = [
'ISO88591' => 'ISO-8859-1',
'ISO8859' => 'ISO-8859-1',
'ISO' => 'ISO-8859-1',
'LATIN1' => 'ISO-8859-1',
'LATIN' => 'ISO-8859-1',
'UTF8' => 'UTF-8',
'UTF' => 'UTF-8',
'WIN1252' => 'ISO-8859-1',
'WINDOWS1252' => 'ISO-8859-1'
];
if (empty($equivalences[$encoding])) {
return 'UTF-8';
}
return $equivalences[$encoding];
}
|
php
|
{
"resource": ""
}
|
q239839
|
Encode.to
|
train
|
public static function to($encodingLabel, $text)
{
$encodingLabel = static::normalizeEncoding($encodingLabel);
if ($encodingLabel == 'ISO-8859-1') {
return static::toLatin1($text);
}
return static::toUTF8($text);
}
|
php
|
{
"resource": ""
}
|
q239840
|
Encode.utf8Decode
|
train
|
protected static function utf8Decode($text, $option)
{
if ($option == self::WITHOUT_ICONV || !function_exists('iconv')) {
$decoded = utf8_decode(
str_replace(array_keys(static::$utf8ToWin1252), array_values(static::$utf8ToWin1252), static::toUTF8($text))
);
} else {
$decoded = iconv("UTF-8", "Windows-1252" . ($option == self::ICONV_TRANSLIT ? '//TRANSLIT' : ($option == self::ICONV_IGNORE ? '//IGNORE' : '')), $text);
}
return $decoded;
}
|
php
|
{
"resource": ""
}
|
q239841
|
Configuration.allFor
|
train
|
public function allFor($name) {
// Loop through environments
$result = array();
foreach ($this->_envSettings as $env => $settings) {
$result[$env] = $settings[$name];
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q239842
|
ErrorTrait.getError
|
train
|
public function getError($attribute)
{
$result = null;
if ($this->isErrorExists($attribute)) {
$result = $this->errors[$attribute];
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q239843
|
AbstractViewHelper.html
|
train
|
protected function html($newLine, $condition = true)
{
if ($condition) {
$this->lines[] = ltrim($newLine);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239844
|
Publisher.getPageUrl
|
train
|
public function getPageUrl(Page $page)
{
return $this->config['base_url'].'/'.
($page->getSubFolder() === null ? '' : $page->getSubFolder().'/').
$this->getPagePublishFilename($page);
}
|
php
|
{
"resource": ""
}
|
q239845
|
Publisher.getPagePublishDirectory
|
train
|
public function getPagePublishDirectory(Page $page)
{
return $this->getPublishDirectory().
rtrim(DIRECTORY_SEPARATOR.$page->getSubFolder(), DIRECTORY_SEPARATOR);
}
|
php
|
{
"resource": ""
}
|
q239846
|
Publisher.getPagePublishPath
|
train
|
public function getPagePublishPath(Page $page)
{
return $this->getPagePublishDirectory($page).
DIRECTORY_SEPARATOR.
$this->getPagePublishFilename($page);
}
|
php
|
{
"resource": ""
}
|
q239847
|
PhotoCollection.transform
|
train
|
public function transform(\Closure $callback)
{
$this->photos = array_map($callback, $this->photos);
return $this;
}
|
php
|
{
"resource": ""
}
|
q239848
|
Settings.createNew
|
train
|
public function createNew(
string $section,
string $property,
string $value,
bool $protected
) : array {
return $this->sendPost(
sprintf('/companies/%s/settings', $this->companySlug),
[],
[
'section' => $section,
'property' => $property,
'value' => $value,
'protected' => $protected
]
);
}
|
php
|
{
"resource": ""
}
|
q239849
|
GuardRoute._verifyIsBannedRoute
|
train
|
function _verifyIsBannedRoute($currentRoute)
{
$r = false;
$currentRoute = rtrim($currentRoute, '/');
foreach ($this->routesDenied as $deniedRoute) {
$deniedRoute = rtrim($deniedRoute, '/');
$allowLeft = false;
if (substr($deniedRoute, -1) == '*') {
// remove star
$allowLeft = true;
$deniedRoute = substr($deniedRoute, 0, strlen($deniedRoute) -1 );
}
if ( ($left = str_replace($deniedRoute, '', $currentRoute)) !== $currentRoute ) {
if ($allowLeft || $left == '')
return true;
}
}
return $r;
}
|
php
|
{
"resource": ""
}
|
q239850
|
ArrayLoader.minimal
|
train
|
public static function minimal(string $filePath = null)
{
if (is_file($filePath)) {
/** @noinspection PhpIncludeInspection */
$configItems = require_once $filePath;
!is_array($configItems) || Config::items($configItems);
ini_set('error_reporting',
Config::exists('errors.error_reporting', 0));
ini_set('display_errors',
Config::exists('errors.display_errors', 0));
Event::dispatch('minimal.loaded.minimal', [
$filePath,
is_array($configItems) ? $configItems : []
]);
}
}
|
php
|
{
"resource": ""
}
|
q239851
|
Zip.dir
|
train
|
public static function dir($sourcePath, $outZipPath)
{
$sourcePath = rtrim($sourcePath, "/");
$zip = new ZipArchive();
$zip->open($outZipPath, ZipArchive::CREATE);
self::folderToZip($sourcePath, $zip, strlen($sourcePath . "/"));
$zip->close();
}
|
php
|
{
"resource": ""
}
|
q239852
|
Logger.add
|
train
|
public function add($message)
{
$this->_messages[] = $this->log_timestamp() . $message . PHP_EOL;
$this->debug($message);
}
|
php
|
{
"resource": ""
}
|
q239853
|
Logger.error
|
train
|
public function error($message)
{
$this->_errors[] = $this->log_timestamp() . $message . PHP_EOL;
$this->debug('ERROR: '.$message);
}
|
php
|
{
"resource": ""
}
|
q239854
|
Logger.shutdown
|
train
|
public function shutdown()
{
if ($this->ondebug === TRUE)
{
$this->_debugs[] = $this->log_debug_event('end') . PHP_EOL;
}
$this->sync();
}
|
php
|
{
"resource": ""
}
|
q239855
|
Logger.sync
|
train
|
public function sync()
{
$this->sync_single_log($this->_messages, '');
$this->sync_single_log($this->_debugs, '_debug');
$this->sync_single_log($this->_errors, '_error');
}
|
php
|
{
"resource": ""
}
|
q239856
|
Logger.sync_single_log
|
train
|
protected function sync_single_log(&$buffer, $suffix)
{
if ( ! empty($buffer))
{
$this->write($buffer, $this->dir . $this->prefix . $suffix . '.log');
$buffer = array();
}
}
|
php
|
{
"resource": ""
}
|
q239857
|
Logger.write
|
train
|
protected function write($messages, $file)
{
$f = @fopen($file, 'a');
if ($f === false)
{
throw new \Exception("Logfile $file is not writeable!");
}
foreach($messages as $msg)
{
fwrite($f, $msg);
}
fclose($f);
}
|
php
|
{
"resource": ""
}
|
q239858
|
ConfigurationProvider.setConfiguration
|
train
|
public function setConfiguration(array $configuration): ConfigurationProviderInterface
{
if (isset($configuration['configuration']) && $configuration['configuration']) {
$configuration = array_merge(
$configuration,
$this->load($configuration['configuration']),
array_filter($configuration)
);
}
$this->configuration = $configuration;
return $this;
}
|
php
|
{
"resource": ""
}
|
q239859
|
Config.initConnectionData
|
train
|
protected function initConnectionData()
{
if ($this->connectionData) {
return;
}
if (!$this->connectionUrl) {
throw new \UnexpectedValueException(
'Expected a connectionUrl, got nowt.'
);
}
$parsed = parse_url($this->connectionUrl);
if ($parsed === false) {
throw new UnexpectedValueException(
'Expected a sensible connectionUrl, got nowt but rubbish.'
);
}
$this->connectionData = $parsed;
}
|
php
|
{
"resource": ""
}
|
q239860
|
AtomicFileReader.readFileLine
|
train
|
public function readFileLine($length = null)
{
$this->openFile();
//gets warning "fgets(): Length parameter must be greater than 0" when parameter is null and is passed to function
if($length === null)
{
$line = fgets($this->getFile());
}
else
{
$line = fgets($this->getFile(), $length);
}
return $line;
}
|
php
|
{
"resource": ""
}
|
q239861
|
RelationsUtilityMethods.getParentRepository
|
train
|
public function getParentRepository()
{
if (null == $this->parentRepository) {
$this->setParentRepository(
Orm::getRepository($this->getParentEntity())
);
}
return $this->parentRepository;
}
|
php
|
{
"resource": ""
}
|
q239862
|
Queue.dequeue
|
train
|
public function dequeue(&$item) : Queue
{
$values = $this->_shift($item);
$this->setValues($values);
return $this;
}
|
php
|
{
"resource": ""
}
|
q239863
|
Queue.enqueue
|
train
|
public function enqueue(... $items) : Queue
{
$values = $this->_pushAll($items);
$this->setValues($values);
return $this;
}
|
php
|
{
"resource": ""
}
|
q239864
|
Message.normalizeBody
|
train
|
private function normalizeBody($body = null)
{
$body = $body ? $body : new Stream(fopen('php://temp', 'r+'));
if (is_string($body)) {
$memoryStream = fopen('php://temp', 'r+');
fwrite($memoryStream, $body);
rewind($memoryStream);
$body = new Stream($memoryStream);
} elseif (!($body instanceof StreamInterface)) {
throw new InvalidArgumentException(
'Body must be a string, null or implement Psr\Http\Message\StreamInterface'
);
}
return $body;
}
|
php
|
{
"resource": ""
}
|
q239865
|
Message.normalizeHeaders
|
train
|
private function normalizeHeaders($headers)
{
if (is_array($headers)) {
$headers = new Headers($headers);
} elseif (!($headers instanceof Headers)) {
throw new InvalidArgumentException(
'Headers must be an array or instance of Headers'
);
}
return $headers;
}
|
php
|
{
"resource": ""
}
|
q239866
|
Message.validateProtocol
|
train
|
private function validateProtocol($version)
{
$valid = [
'1.0' => true,
'1.1' => true,
'2.0' => true,
];
if (!isset($valid[$version])) {
throw new InvalidArgumentException('Invalid HTTP version. Must be one of: 1.0, 1.1, 2.0');
}
}
|
php
|
{
"resource": ""
}
|
q239867
|
ExtensionManager.getPackages
|
train
|
public function getPackages()
{
$filename = $this->vendorPath . '/composer/installed.json';
if (!file_exists($filename)) {
throw new Exception($filename . ' not exists!');
}
$packages = [];
foreach (json_decode(file_get_contents($filename), true) as $package) {
if ($package['type'] === 'teamelf-extension') {
$packages[] = $package;
}
}
return $packages;
}
|
php
|
{
"resource": ""
}
|
q239868
|
ExtensionManager.load
|
train
|
public function load()
{
$this->extensions = [];
foreach ($this->getPackages() as $package) {
[$v, $p] = explode('/', $package['name']);
$extension = Extension::findBy([
'vendor' => $v,
'package' => $p
]);
if (!$extension) {
$extension = (new Extension())
->vendor($v)
->package($p);
}
$extension
->version($package['version'] ?? '')
->description($package['description'] ?? '')
->save();
$this->extensions[] = $extension;
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239869
|
Group.countSkillGroups
|
train
|
public function countSkillGroups(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collSkillGroupsPartial && !$this->isNew();
if (null === $this->collSkillGroups || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collSkillGroups) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getSkillGroups());
}
$query = ChildSkillGroupQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByGroup($this)
->count($con);
}
return count($this->collSkillGroups);
}
|
php
|
{
"resource": ""
}
|
q239870
|
Group.initSkills
|
train
|
public function initSkills()
{
$this->collSkills = new ObjectCollection();
$this->collSkillsPartial = true;
$this->collSkills->setModel('\gossi\trixionary\model\Skill');
}
|
php
|
{
"resource": ""
}
|
q239871
|
Group.countSkills
|
train
|
public function countSkills(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collSkillsPartial && !$this->isNew();
if (null === $this->collSkills || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collSkills) {
return 0;
} else {
if ($partial && !$criteria) {
return count($this->getSkills());
}
$query = ChildSkillQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByGroup($this)
->count($con);
}
} else {
return count($this->collSkills);
}
}
|
php
|
{
"resource": ""
}
|
q239872
|
Group.addSkill
|
train
|
public function addSkill(ChildSkill $skill)
{
if ($this->collSkills === null) {
$this->initSkills();
}
if (!$this->getSkills()->contains($skill)) {
// only add it if the **same** object is not already associated
$this->collSkills->push($skill);
$this->doAddSkill($skill);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239873
|
Group.removeSkill
|
train
|
public function removeSkill(ChildSkill $skill)
{
if ($this->getSkills()->contains($skill)) { $skillGroup = new ChildSkillGroup();
$skillGroup->setSkill($skill);
if ($skill->isGroupsLoaded()) {
//remove the back reference if available
$skill->getGroups()->removeObject($this);
}
$skillGroup->setGroup($this);
$this->removeSkillGroup(clone $skillGroup);
$skillGroup->clear();
$this->collSkills->remove($this->collSkills->search($skill));
if (null === $this->skillsScheduledForDeletion) {
$this->skillsScheduledForDeletion = clone $this->collSkills;
$this->skillsScheduledForDeletion->clear();
}
$this->skillsScheduledForDeletion->push($skill);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239874
|
EventHandlers.get
|
train
|
public function get(string $name) : EventHandlerInterface
{
if (!isset($this->eventHandlers[$name])) {
throw new \InvalidArgumentException(sprintf('DataGrid event handler %s not found', $name));
}
return $this->eventHandlers[$name];
}
|
php
|
{
"resource": ""
}
|
q239875
|
AbstractController.makeRequest
|
train
|
protected function makeRequest($type) {
if(isset($this->{$type . 'Request'}) && $this->{$type . 'Request'}) {
$request = app()->make($this->{$type . 'Request'});
if (!$request instanceof Request) {
throw new \Exception("Class {$this->{$type . 'Request'}} must be an instance of Illuminate\\Http\\Request");
}
return $request;
}
}
|
php
|
{
"resource": ""
}
|
q239876
|
AbstractController.maybeMakeResource
|
train
|
protected function maybeMakeResource($type, $data, $status = 200) {
$resourceName = $type . 'Resource';
if(isset($this->$resourceName) && $this->$resourceName) {
$class = $this->$resourceName;
return (new $class($data))->response()
->setStatusCode($status);
} elseif(is_bool($data)){
return strval($data);
} else {
return $data;
}
}
|
php
|
{
"resource": ""
}
|
q239877
|
AutoBuild.getDefaultParameters
|
train
|
public static function getDefaultParameters($className)
{
if (!isset(static::$registeredClasses[$className])) {
return null;
}
$params = static::$registeredClasses[$className];
if (is_callable($params)) {
$params = $params();
}
return $params;
}
|
php
|
{
"resource": ""
}
|
q239878
|
AutoBuild.getInstance
|
train
|
public static function getInstance($className)
{
if (!isset(static::$registeredClasses[$className])) {
return null;
}
/** @var DI $object */
$object = $className::build()->auto();
return $object;
}
|
php
|
{
"resource": ""
}
|
q239879
|
AuthorizationServiceProvider.defineMany
|
train
|
protected function defineMany($gate, $class, array $policies)
{
foreach ($policies as $method => $ability) {
$gate->define($ability, "$class@$method");
}
}
|
php
|
{
"resource": ""
}
|
q239880
|
StringHelper.normalize
|
train
|
public static function normalize($pattern)
{
//normalize the string pattern and return safe pattern for use
return self::$delimiter.trim($pattern, self::$delimiter).self::$delimiter;
}
|
php
|
{
"resource": ""
}
|
q239881
|
StringHelper.sanitize
|
train
|
public static function sanitize($string, $mask)
{
//check if the input mask is an array
if( is_array($mask))
{
//assign value to parts
$parts = $mask;
}
//check if $mask is a string
else if( is_string($mask))
{
//divide string into substrings
$parts = str_split($mask);
}
//not any of the above, return the string
else
{
//return string
return $string;
}
//loop through the parts array normalizing each part
foreach ($parts as $part)
{
//normalize the part
$normalized = self::normalize("\\{$part}");
//search string and replace normalized string in place of original string from input $string
$string = preg_replace("{$normalized}m", "\\{$part}", $string);
}
//return the string after sanitizing is complete
return $string;
}
|
php
|
{
"resource": ""
}
|
q239882
|
StringHelper.unique
|
train
|
public static function unique($string)
{
//set intitial unique var sting as empty
$unique = '';
//split the string into substrings
$parts = str_split($string);
//loop through the sting parts array removing duplicated characters
foreach ($parts as $part)
{
//add this character if it doesnt exist yet
if( ! strstr($unique, $part) )
{
//add this character to the main unique array
$unique .= $part;
}
}
//return the unique string
return $unique;
}
|
php
|
{
"resource": ""
}
|
q239883
|
StringHelper.indexOf
|
train
|
public static function indexOf($string, $substring, $offset = null)
{
//get the position of this string in the main string
$position = strpos($string, $substring, $offset);
//return -1 of the substring was not found
if( ! is_int($position) )
{
//return string position as -1
return -1;
}
//return actual string position if found
return $position;
}
|
php
|
{
"resource": ""
}
|
q239884
|
StringHelper.singular
|
train
|
public static function singular($string)
{
//assing the input string to a result variable
$result = $string;
//loop through the array of singular patterns, getting the regular exppression patters
foreach ($self::$singulars as $rule => $replacement)
{
//get the regular expression friendly pattern
$rule = self::normalize($rule);
//check if there is a matching pattern in the input string
if ( preg_match($rule, $string) )
{
//replace with the appropriate string and return
$result = preg_replace($rule, $replacement, $string);
//once a replacement is found, break out of the loop
break;
}
}
//return the result that was found
return $result;
}
|
php
|
{
"resource": ""
}
|
q239885
|
StringHelper.plural
|
train
|
public static function plural($string)
{
//assign the input string to a result variable
$result = $string;
//loop through the array of plural patterns, getting the regular exppression friendly pattern
foreach (self::$plurals as $rule => $replacement)
{
//get the regular axpression friendlt pattern
$result = $string;
//check if there is a match for this pattern in the input string
if ( preg_match($rule, $string) )
{
//if match found, replace rule with the replacement string
$result = preg_replace($rule, $replacement, $string);
//break out of loop once match is found
break;
}
}
//return the new string contained in result
return $result;
}
|
php
|
{
"resource": ""
}
|
q239886
|
ConfigCollection.addConfig
|
train
|
public function addConfig(ConfigInterface $config) {
// Add to config list
$this->configs->attach($config);
// If collection is in merge mode, add config data to common store
$this->store->merge($config->dump());
return $this;
}
|
php
|
{
"resource": ""
}
|
q239887
|
ConfigCollection.removeConfig
|
train
|
public function removeConfig(ConfigInterface $config) {
// If collection is in merge mode, don't permit removing configs (cannot unmerge)
if ($this->merge) {
throw new Exception("Cannot remove configs from merged collection.");
}
$this->configs->detach($config);
return $this;
}
|
php
|
{
"resource": ""
}
|
q239888
|
ConfigCollection.addFile
|
train
|
public function addFile($file, $writeable = false): ConfigCollection {
$config = FileConfig::load($file, $writeable);
if ($config) {
$this->addConfig($config);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239889
|
ConfigCollection.addVirtual
|
train
|
public function addVirtual($data): ConfigCollection {
$config = VirtualConfig::load($data);
if ($config) {
$this->addConfig($config);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239890
|
ConfigCollection.addFolder
|
train
|
public function addFolder($folder, $extension): ConfigCollection {
$extLen = strlen($extension);
$files = scandir($folder, SCANDIR_SORT_ASCENDING);
foreach ($files as $file) {
if (in_array($file, ['.','..'])) {
continue;
}
if (substr($file, -$extLen) != $extension) {
continue;
}
$config = FileConfig::load(paths($folder, $file), false);
if ($config) {
$this->addConfig($config);
}
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q239891
|
Cache.getPool
|
train
|
public function getPool ($name = 'default')
{
if (isset($this->pools[$name])) {
return $this->pools[$name];
}
throw new NotFoundException('Caching Pool not found with given name \''.$name.'\'');
}
|
php
|
{
"resource": ""
}
|
q239892
|
Cache.initiatePools
|
train
|
protected function initiatePools ()
{
foreach ($this->configuration['pools'] as $name => $poolConfiguration) {
// Try to get the driver class. Will throw an exception if not exists.
new \ReflectionClass($poolConfiguration['driver']);
$options = $poolConfiguration['options'];
/** @var DriverInterface $driverInstance */
$driverInstance = new $poolConfiguration['driver']($options);
$poolInstance = new Pool($driverInstance, $name);
// Register in the local instance holding variable.
$this->pools[$name] = $poolInstance;
}
}
|
php
|
{
"resource": ""
}
|
q239893
|
Middleware.fatalAccess
|
train
|
public static function fatalAccess(string $userGroup, string $error)
{
if (!isset($_SESSION[$userGroup])) {
exit($error);
}
}
|
php
|
{
"resource": ""
}
|
q239894
|
Middleware.fatalElseAccess
|
train
|
public static function fatalElseAccess(string $userGroup, string $error)
{
if (isset($_SESSION[$userGroup])) {
exit($error);
}
}
|
php
|
{
"resource": ""
}
|
q239895
|
ArrayHelper.set
|
train
|
public static function set($array, $key, $value = null, $useDotSyntax = false)
{
// Normalize array
$array = $array ?: [];
// Check if key is empty
if (StringHelper::emptyString($key, true)) {
throw new InvalidArgumentException(__METHOD__ . ': Key cannot be empty');
}
/**
* Split name using dots.
*
* Just checking whether the key doesn't have any dots
* but $useDotSyntax is true by default.
*/
$keyParts = explode('.', $key);
$useDotSyntax = $useDotSyntax && count($keyParts) > 1;
// Set simple value, without dot syntax
if (!$useDotSyntax) {
if (is_null($value) && isset($array[$key])) {
unset($array[$key]);
} elseif (!is_null($value)) {
$array[$key] = $value;
}
} else {
// Recursive call
$base = $keyParts[0];
unset($keyParts[0]);
// Check if the base array exists
if (!isset($array[$base])) {
$array[$base] = [];
}
// Get key, base array and continue
$key = implode('.', $keyParts);
$innerArray = $array[$base];
$array[$base] = static::set($innerArray, $key, $value, $useDotSyntax);
}
return $array;
}
|
php
|
{
"resource": ""
}
|
q239896
|
Client.getProfile
|
train
|
public function getProfile($email)
{
$url = $this->getProfileUrl($email);
$httpClient = &$this->httpClient;
$response = $httpClient->get($url);
$data = $response->json();
return $data['entry'][0];
}
|
php
|
{
"resource": ""
}
|
q239897
|
Client.getAvatarUrl
|
train
|
public function getAvatarUrl($email, $size = 80, $extension = 'jpg', $default = 404, $rating = 'g')
{
$url = 'https://www.gravatar.com/avatar/';
$url .= md5(strtolower(trim($email))).'.'.$extension;
$url .= '?'.http_build_query([
'd' => $default,
'r' => $rating,
's' => $size,
]);
return $url;
}
|
php
|
{
"resource": ""
}
|
q239898
|
AnnotationReader.get
|
train
|
public function get($entity, $annotation)
{
$properties = $this->getProperties($entity);
$return = array();
foreach ($properties as $reflectionProperty) {
$propertyAnnotation = $this->reader->getPropertyAnnotation($reflectionProperty, $annotation);
if (!is_null($propertyAnnotation) && get_class($propertyAnnotation) == $annotation) {
$return[$reflectionProperty->name] = $reflectionProperty;
}
}
return $return;
}
|
php
|
{
"resource": ""
}
|
q239899
|
AnnotationReader.all
|
train
|
public function all($entity)
{
$reflectionClass = new \ReflectionClass($entity);
$properties = $reflectionClass->getProperties();
$class = new \ReflectionClass($entity);
while ($parent = $class->getParentClass()) {
$parentProperties = $parent->getProperties();
$properties = array_merge($parentProperties, $properties);
$class = $parent;
}
$return = array();
foreach ($properties as $reflectionProperty) {
$propertyAnnotation = $this->reader->getPropertyAnnotation($reflectionProperty, $this->annotationClass);
if (!is_null($propertyAnnotation) && $propertyAnnotation->listable) {
$return[] = array(
'property' => $reflectionProperty->name,
'type' => $propertyAnnotation->type
);
}
}
return $return;
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.