_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q251900 | AbstractTransport.normalizeHeaderName | validation | protected function normalizeHeaderName($keyName)
{
if (!is_string($keyName)) {
return null;
}
return ucwords(trim(strtolower($keyName)), '-') ?: null;
} | php | {
"resource": ""
} |
q251901 | AbstractTransport.withHeaders | validation | public function withHeaders(array $headers)
{
$object = clone $this;
$object->configs['headers'] = [];
$object->inProcessingLoop = true;
$object->replaceHeaders($headers);
$object->inProcessingLoop = true;
return $object->buildConfigClient();
} | php | {
"resource": ""
} |
q251902 | AbstractTransport.withoutCookie | validation | public function withoutCookie($cookieName = null)
{
$object = clone $this;
if (! $this->configs['cookies'] instanceof CookieJarInterface) {
return $object;
}
if (!$cookieName) {
unset($object->configs['cookies']);
} else {
if (!is_array($cookieName)) {
$cookieName = [$cookieName];
}
$cookies = $this->configs['cookies']->toArray();
foreach ($cookieName as $cookie) {
if (!is_string($cookie) || !$cookie) {
continue;
}
unset($cookies[$cookie]);
}
$this->configs['cookies'] = new CookieJar($cookies);
}
return $object->buildConfigClient();
} | php | {
"resource": ""
} |
q251903 | AbstractTransport.withoutParam | validation | public function withoutParam($paramName = null)
{
$object = clone $this;
if (is_null($paramName)) {
unset($object->configs[$this->currentParamType]);
} else {
if (isset($object->configs[$this->currentParamType])) {
if (!is_array($object->configs[$this->currentParamType])) {
unset($object->configs[$this->currentParamType]);
} else {
if (is_array($paramName)) {
$paramName = [$paramName];
}
foreach ($paramName as $paramKey) {
if (is_string($paramKey) || is_numeric($paramKey)) {
unset($object->configs[$this->currentParamType][$paramName]);
}
}
}
}
}
return $object->buildConfigClient();
} | php | {
"resource": ""
} |
q251904 | AbstractTransport.setParamType | validation | public function setParamType($type)
{
if (! is_string($type) || ! in_array($type, [self::PARAM_MULTIPART, self::PARAM_FORM])
) {
throw new InvalidArgumentException(
sprintf(
"Invalid parameter form type, form type only allowed $1s and $2s",
self::PARAM_FORM,
self::PARAM_MULTIPART
),
E_USER_ERROR
);
}
$this->currentParamType = $type;
$reverse_params = $type == self::PARAM_FORM
? self::PARAM_MULTIPART
: self::PARAM_FORM;
$reverse_params_value = isset($this->configs[$reverse_params])
? $this->configs[$reverse_params]
: null;
$params_value = isset($this->configs[$type])
? $this->configs[$type]
: null;
unset(
$this->configs[self::PARAM_FORM],
$this->configs[self::PARAM_MULTIPART]
);
$this->configs[$type] = is_array($reverse_params_value)
? $reverse_params_value
: (is_array($params_value) ? $params_value : []);
return $this->buildConfigClient();
} | php | {
"resource": ""
} |
q251905 | AbstractTransport.withRequest | validation | public function withRequest(RequestInterface $request)
{
$object = clone $this;
$object->request = $request;
$object->method = $request->getMethod();
return $object;
} | php | {
"resource": ""
} |
q251906 | XssProtectionMiddleware.enableBlockMode | validation | public function enableBlockMode():void
{
if (!$this->enableProtection) {
throw new MiddlewareException(
$this,
"You can't enable the block mode because the XSS protection is disabled"
);
}
if ($this->reportUri) {
throw new MiddlewareException(
$this,
sprintf(
"You can't enable the block mode because the report mode is already enabled (see %s)",
'https://developer.mozilla.org/docs/Web/HTTP/Headers/X-XSS-Protection'
)
);
}
$this->blockMode = true;
} | php | {
"resource": ""
} |
q251907 | XssProtectionMiddleware.setReportUri | validation | public function setReportUri(string $reportUri):void
{
if (!$this->enableProtection) {
throw new MiddlewareException(
$this,
"You can't set the report URI because the XSS protection is disabled"
);
}
if ($this->blockMode) {
throw new MiddlewareException(
$this,
sprintf(
"You can't set the report URI because the block mode is already enabled (see %s)",
'https://developer.mozilla.org/docs/Web/HTTP/Headers/X-XSS-Protection'
)
);
}
$this->reportUri = $reportUri;
} | php | {
"resource": ""
} |
q251908 | OnDupTrait.buildOnDup | validation | protected function buildOnDup()/*# : array */
{
$result = [];
foreach ($this->clause_ondup as $col => $expr) {
$result[] = $col . ' = ' . $expr;
}
return $result;
} | php | {
"resource": ""
} |
q251909 | Xml.build | validation | public static function build($input, array $options = [])
{
if (!\is_array($options)) {
$options = ['return' => (string)$options];
}
$defaults = [
'return' => 'simplexml',
];
$options = array_merge($defaults, $options);
if (is_array($input) || is_object($input)) {
return self::fromArray((array)$input, $options);
}
if (strpos($input, '<') !== false) {
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
return new \SimpleXMLElement($input, LIBXML_NOCDATA);
}
$dom = new \DOMDocument();
$dom->loadXML($input);
return $dom;
}
if (file_exists($input) || strpos($input, 'http://') === 0 || strpos($input, 'https://') === 0) {
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
return new \SimpleXMLElement($input, LIBXML_NOCDATA, true);
}
$dom = new \DOMDocument();
$dom->load($input);
return $dom;
}
if (!\is_string($input)) {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid input.'));
}
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'XML cannot be read.'));
} | php | {
"resource": ""
} |
q251910 | Xml.fromArray | validation | public static function fromArray($input, array $options = [])
{
if (!\is_array($input) || \count($input) !== 1) {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid input.'));
}
$key = key($input);
if (\is_int($key)) {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'The key of input must be alphanumeric.'));
}
if (!\is_array($options)) {
$options = ['format' => (string)$options];
}
$defaults = [
'format' => 'tags',
'version' => '1.0',
'encoding' => 'utf-8',
'return' => 'simplexml',
];
$options = array_merge($defaults, $options);
$dom = new \DOMDocument($options['version'], $options['encoding']);
self::_fromArray($dom, $dom, $input, $options['format']);
$options['return'] = strtolower($options['return']);
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
return new \SimpleXMLElement($dom->saveXML());
}
return $dom;
} | php | {
"resource": ""
} |
q251911 | Xml._fromArray | validation | protected static function _fromArray($dom, $node, &$data, $format)
{
if ($data === null || $data === '' || !\is_array($data)) {
return;
}
foreach ($data as $key => $value) {
if (\is_string($key)) {
if (!\is_array($value)) {
if (\is_bool($value)) {
$value = (int)$value;
} elseif ($value === null) {
$value = '';
}
$isNamespace = strpos($key, 'xmlns:');
if ($isNamespace !== false) {
$node->setAttributeNS('http://www.w3.org/2000/xmlns/', $key, $value);
continue;
}
if ($key[0] !== '@' && $format === 'tags') {
$child = null;
if (!is_numeric($value)) {
// Escape special characters
// http://www.w3.org/TR/REC-xml/#syntax
// https://bugs.php.net/bug.php?id=36795
$child = $dom->createElement($key, '');
$child->appendChild(new \DOMText($value));
} else {
$child = $dom->createElement($key, $value);
}
$node->appendChild($child);
} else {
if ($key[0] === '@') {
$key = substr($key, 1);
}
$attribute = $dom->createAttribute($key);
$attribute->appendChild($dom->createTextNode($value));
$node->appendChild($attribute);
}
} else {
if ($key[0] === '@') {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid array'));
}
if (array_keys($value) === range(0, \count($value) - 1)) { // List
foreach ($value as $item) {
$data = compact('dom', 'node', 'key', 'format');
$data['value'] = $item;
self::_createChild($data);
}
} else { // Struct
self::_createChild(compact('dom', 'node', 'key', 'value', 'format'));
}
}
} else {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'Invalid array'));
}
}
} | php | {
"resource": ""
} |
q251912 | Xml.toArray | validation | public static function toArray($obj)
{
if ($obj instanceof \DOMNode) {
$obj = simplexml_import_dom($obj);
}
if (!($obj instanceof \SimpleXMLElement)) {
throw new \RuntimeException(Tools::poorManTranslate('fts-shared', 'The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.'));
}
$result = [];
$namespaces = array_merge(['' => ''], $obj->getNamespaces(true));
self::_toArray($obj, $result, '', array_keys($namespaces));
return $result;
} | php | {
"resource": ""
} |
q251913 | Path.addSegmentsToPath | validation | private static function addSegmentsToPath($path, $segments)
{
$segments = Arr::toArray($segments);
if (count($segments) > 0) {
$path .= '/' . implode('/', $segments);
}
return $path;
} | php | {
"resource": ""
} |
q251914 | GetCachedCapableTrait._getCached | validation | protected function _getCached($key, $default = null, $ttl = null)
{
try {
return $this->_get($key);
} catch (NotFoundExceptionInterface $e) {
if (is_callable($default)) {
try {
$args = $this->_normalizeArray($this->_getGeneratorArgs($key, $default, $ttl));
$default = $this->_invokeCallable($default, $args);
} catch (RootException $e) {
throw $this->_createRuntimeException($this->__('Could not generate value'), null, $e);
}
}
$this->_set($key, $default, $ttl);
return $default;
}
} | php | {
"resource": ""
} |
q251915 | Inflection._cmpFrm | validation | private function _cmpFrm($txt)
{
$CmpFrmRV = '';
$length = mb_strlen($txt, 'UTF-8');
for ($CmpFrmI = 0; $CmpFrmI < $length; $CmpFrmI++) {
if (mb_substr($txt, $CmpFrmI, 1, 'UTF-8') === '0') {
$CmpFrmRV .= $this->aCmpReg[0];
} elseif (mb_substr($txt, $CmpFrmI, 1, 'UTF-8') === '1') {
$CmpFrmRV .= $this->aCmpReg[1];
} elseif (mb_substr($txt, $CmpFrmI, 1, 'UTF-8') === '2') {
$CmpFrmRV .= $this->aCmpReg[2];
} else {
$CmpFrmRV .= mb_substr($txt, $CmpFrmI, 1, 'UTF-8');
}
}
return $CmpFrmRV;
} | php | {
"resource": ""
} |
q251916 | Inflection._sklon | validation | private function _sklon($nPad, $vzndx, $txt, $zivotne = false)
{
if ($vzndx < 0 || $vzndx >= \count($this->vzor)) {
return '???';
}
$txt3 = $this->_xEdeten($txt);
$kndx = $this->_isShoda($this->vzor[$vzndx][1], $txt3);
if ($kndx < 0 || $nPad < 1 || $nPad > 14) {
//8-14 je pro plural
return '???';
}
if ($this->vzor[$vzndx][$nPad] === '?') {
return '?';
}
if (!$this->isDbgMode & $nPad === 1) {
// 1. pad nemenime
$rv = $this->_xDetene($txt3);
} else {
$rv = $this->_leftStr($kndx, $txt3) . '-' . $this->_cmpFrm($this->vzor[$vzndx][$nPad]);
}
if ($this->isDbgMode) {
//preskoceni filtrovani
return $rv;
}
// Formatovani zivotneho sklonovani
// - nalezeni pomlcky
$length = mb_strlen($rv, 'UTF-8');
for ($nnn = 0; $nnn < $length; $nnn++) {
if (mb_substr($rv, $nnn, 1, 'UTF-8') === '-') {
break;
}
}
$ndx1 = $nnn;
// - nalezeni lomitka
for ($nnn = 0; $nnn < $length; $nnn++) {
if (mb_substr($rv, $nnn, 1, 'UTF-8') === '/') {
break;
}
}
$ndx2 = $nnn;
if ($ndx1 !== $length && $ndx2 !== $length) {
if ($zivotne) {
// 'text-xxx/yyy' -> 'textyyy'
$rv = $this->_leftStr($ndx1, $rv) . $this->_rightStr($ndx2 + 1, $rv);
} else {
// 'text-xxx/yyy' -> 'text-xxx'
$rv = $this->_leftStr($ndx2, $rv);
}
$length = mb_strlen($rv, 'UTF-8');
}
// vypusteni pomocnych znaku
$txt3 = '';
for ($nnn = 0; $nnn < $length; $nnn++) {
$subStr = mb_substr($rv, $nnn, 1, 'UTF-8');
if (!($subStr === '-' || $subStr === '/')) {
$txt3 .= mb_substr($rv, $nnn, 1, 'UTF-8');
}
}
$rv = $this->_xDetene($txt3);
return $rv;
// return $this->LeftStr( $kndx, $txt ) + $this->vzor[$vzndx][$nPad];
} | php | {
"resource": ""
} |
q251917 | Inflection._rightStr | validation | private function _rightStr($n, $txt)
{
$rv = '';
$length = mb_strlen($txt, 'UTF-8');
for ($i = $n; $i < $length; $i++) {
$rv .= mb_substr($txt, $i, 1, 'UTF-8');
}
return $rv;
} | php | {
"resource": ""
} |
q251918 | Inflection._txtSplit | validation | private function _txtSplit($txt)
{
$skp = 1;
$rv = [];
$rvx = 0;
$acc = '';
$length = mb_strlen($txt, 'UTF-8');
for ($i = 0; $i < $length; $i++) {
if (mb_substr($txt, $i, 1, 'UTF-8') === ' ') {
if ($skp) {
continue;
}
$skp = 1;
$rv[$rvx++] = $acc;
$acc = '';
continue;
}
$skp = 0;
$acc .= mb_substr($txt, $i, 1, 'UTF-8');
}
if (!$skp) {
$rv[$rvx] = $acc;
}
return $rv;
} | php | {
"resource": ""
} |
q251919 | Inflection.inflect | validation | public function inflect($text, $zivotne = false, $preferovanyRod = '')
{
$aTxt = $this->_txtSplit($text);
$this->PrefRod = '0';
$out = [];
for ($i = \count($aTxt) - 1; $i >= 0; $i--) {
// vysklonovani
$this->_skl2($aTxt[$i], $preferovanyRod, $zivotne);
// vynuceni rodu podle posledniho slova
if ($i === \count($aTxt) - 1) {
$this->PrefRod = $this->astrTvar[0];
}
// pokud nenajdeme vzor tak nesklonujeme
if ($i < \count($aTxt) - 1 && mb_substr($this->PrefRod, 0, 1, 'UTF-8') !== '?' && mb_substr($this->astrTvar[0], 0, 1, 'UTF-8') === '?') {
for ($j = 1; $j < 15; $j++) {
$this->astrTvar[$j] = $aTxt[$i];
}
}
if (mb_substr($this->astrTvar[0], 0, 1, 'UTF-8') === '?') {
$this->astrTvar[0] = '';
}
if ($i < \count($aTxt)) {
for ($j = 1; $j < 15; $j++) {
@$out[$j] = $this->astrTvar[$j] . ' ' . @$out[$j];
}
} else {
for ($j = 1; $j < 15; $j++) {
@$out[$j] = $this->astrTvar[$j];
}
}
}
return $out;
} | php | {
"resource": ""
} |
q251920 | Inflection._sklStd | validation | private function _sklStd($slovo, $ii, $zivotne)
{
if ($ii < 0 || $ii > \count($this->vzor)) {
$this->astrTvar[0] = '!!!???';
}
// - seznam nedoresenych slov
$count = \count($this->v0);
for ($jj = 0; $jj < $count; $jj++) {
if ($this->_isShoda($this->v0[$jj], $slovo) >= 0) {
//str = 'Seznam výjimek [' + $jj + ']. '
//alert(str + 'Lituji, toto $slovo zatím neumím správně vyskloňovat.');
return null;
}
}
// nastaveni rodu
$this->astrTvar[0] = $this->vzor[$ii][0];
// vlastni sklonovani
for ($jj = 1; $jj < 15; $jj++) {
$this->astrTvar[$jj] = $this->_sklon($jj, $ii, $slovo, $zivotne);
}
// - seznam nepresneho sklonovani
$count = \count($this->v3);
for ($jj = 0; $jj < $count; $jj++) {
if ($this->_isShoda($this->v3[$jj], $slovo) >= 0) {
//alert('Pozor, v některých pádech nemusí být skloňování tohoto slova přesné.');
return;
}
}
// return SklFmt( $this->astrTvar );
} | php | {
"resource": ""
} |
q251921 | SeoFriendlyDataObject.generateURLSegment | validation | protected function generateURLSegment($title){
$filter = URLSegmentFilter::create();
$t = $filter->filter($title);
// Fallback to generic name if path is empty (= no valid, convertable characters)
if(!$t || $t == '-' || $t == '-1') {
$t = "{$this->owner->ClassName}-{$this->owner->ID}";
} else {
// Make sure that it does not already exists for another object
$class = $this->owner->ClassName;
$obj = $class::get()
->filter(array("URLSegment" => $t))
->exclude(array("ID" => $this->owner->ID))
->first();
if($obj){
$t .= "-{$this->owner->ID}";
}
}
return $t;
} | php | {
"resource": ""
} |
q251922 | SeoFriendlyDataObject.onBeforeWrite | validation | public function onBeforeWrite(){
if($this->owner->Title){
$this->owner->URLSegment = $this->generateURLSegment($this->owner->Title);
}
parent::onBeforeWrite();
} | php | {
"resource": ""
} |
q251923 | Str.quoteWith | validation | public static function quoteWith($o, $quote = '\'')
{
if (strlen($quote) !== 1) {
throw new InvalidArgumentException('2nd parameter must be single character, two or more characters are given');
}
if (is_array($o)) {
$len = count($o);
for ($i = 0; $i < $len; $i++) {
$tmp[$i] = $quote . $o[$i] . $quote;
}
return $tmp;
}
return $quote . $o . $quote;
} | php | {
"resource": ""
} |
q251924 | AcceptTypes.preferred | validation | public function preferred(array $types): ?string
{
if (empty($types)) {
return null;
}
foreach ($this->types as $type) {
if (in_array($type, $types, true)) {
return $type;
} elseif ('*/*' == $type) {
return current($types);
} elseif (strlen($type) > 2 && substr($type, -2, 2) == '/*') {
$prefix = substr($type, 0, strpos($type, '/') + 1);
$plen = strlen($prefix);
foreach ($types as $t) {
if (strncmp($prefix, $t, $plen) === 0) {
return $t;
}
}
}
}
return null;
} | php | {
"resource": ""
} |
q251925 | Application.bootstrap | validation | private function bootstrap()
{
// Attach the error handler - all PHP Errors should be thrown as Exceptions
ErrorInterceptor::registerErrorHandler();
set_exception_handler(array(static::class, 'handleException'));
// Set character set
ini_set('default_charset', 'UTF-8');
mb_internal_encoding('UTF-8');
// Set up logging
ini_set('log_errors', '1');
// Load configuration
$this->loadConfig();
$this->injector->setInstance(Configuration::class, $this->config);
$this->cachemanager = $this->injector->getInstance(Cache\Manager::class);
$this->dev = $this->config->dget('site', 'dev', true);
// Set up the autoloader
$this->configureAutoloaderAndResolver();
// Make sure permissions are adequate
try
{
$this->path_config->checkPaths();
}
catch (PermissionError $e)
{
return $this->showPermissionError($e);
}
$test = defined('WEDETO_TEST') && WEDETO_TEST === 1 ? 'test' : '';
if (PHP_SAPI === 'cli')
ini_set('error_log', $this->path_config->log . '/error-php-cli' . $test . '.log');
else
ini_set('error_log', $this->path_config->log . '/error-php' . $test . '.log');
// Set default permissions for files and directories
$this->setCreatePermissions();
// Autoloader requires manual logger setup to avoid depending on external files
LoggerFactory::setLoggerFactory(new LoggerFactory());
Autoloader::setLogger(LoggerFactory::getLogger(['class' => Autoloader::class]));
// Set up root logger
$this->setupLogging();
// Save the cache if configured so
if ($this->path_config->cache)
{
$this->cachemanager->setCachePath($this->path_config->cache);
$this->cachemanager->setHook($this->config->dget('cache', 'expiry', 60));
}
// Find installed modules and initialize them
$this->module_manager = new Module\Manager($this->resolver);
// Prepare the HTTP Request Object
$this->request = Request::createFromGlobals();
// Load plugins
$this->setupPlugins();
} | php | {
"resource": ""
} |
q251926 | Application.get | validation | public function get($parameter)
{
switch ($parameter)
{
// Essential components are instantiated during application set up
case "dev":
return $this->dev ?? true;
case "config":
return $this->config;
case "injector":
return $this->injector;
case "pathConfig":
return $this->path_config;
case "request":
return $this->request;
case "resolver":
return $this->resolver;
case "moduleManager":
return $this->module_manager;
// Non-essential components are created on-the-fly
case "auth":
return $this->injector->getInstance(Authentication::class);
case "db":
return $this->injector->getInstance(DB::class);
case "dispatcher":
return $this->injector->getInstance(Dispatcher::class);
case "template":
return $this->injector->getInstance(Template::class);
case "mailer":
return $this->injector->getInstance(SMTPSender::class);
case "i18n":
return $this->injector->getInstance(I18n::class);
case "processChain":
return $this->injector->getInstance(ProcessChain::class);
}
throw new InvalidArgumentException("No such object: $parameter");
} | php | {
"resource": ""
} |
q251927 | Application.showPermissionError | validation | private function showPermissionError(PermissionError $e)
{
if (PHP_SAPI !== "cli")
{
http_response_code(500);
header("Content-type: text/plain");
}
if ($this->dev)
{
$file = $e->path;
echo "{$e->getMessage()}\n";
echo "\n";
echo WF::str($e, false);
}
else
{
echo "A permission error is preventing this page from displaying properly.";
}
die();
} | php | {
"resource": ""
} |
q251928 | Application.setCreatePermissions | validation | private function setCreatePermissions()
{
if ($this->config->has('io', 'group'))
Path::setDefaultFileGroup($this->config->get('io', 'group'));
$file_mode = (int)$this->config->get('io', 'file_mode');
if ($file_mode)
{
$of = $file_mode;
$file_mode = octdec(sprintf("%04d", $file_mode));
Path::setDefaultFileMode($file_mode);
}
$dir_mode = (int)$this->config->get('io', 'dir_mode');
if ($dir_mode)
{
$of = $dir_mode;
$dir_mode = octdec(sprintf("%04d", $dir_mode));
Path::setDefaultDirMode($dir_mode);
}
} | php | {
"resource": ""
} |
q251929 | Application.configureAutoloaderAndResolver | validation | private function configureAutoloaderAndResolver()
{
if ($this->autoloader !== null)
return;
// Construct the Wedeto autoloader and resolver
$cache = $this->cachemanager->getCache("resolution");
$this->autoloader = new Autoloader();
$this->autoloader->setCache($cache);
$this->injector->setInstance(Autoloader::class, $this->autoloader);
$this->resolver = new Resolver($cache);
$this->resolver
->addResolverType('template', 'template', '.php')
->addResolverType('assets', 'assets')
->addResolverType('app', 'app')
->addResolverType('code', 'src')
->addResolverType('language', 'language')
->addResolverType('migrations', 'migrations')
->setResolver("app", new Router("router"));
$this->injector->setInstance(Resolver::class, $this->resolver);
spl_autoload_register(array($this->autoloader, 'autoload'), true, true);
$cl = Autoloader::findComposerAutoloader();
if (!empty($cl))
{
$vendor_dir = Autoloader::findComposerAutoloaderVendorDir($cl);
$this->autoloader->importComposerAutoloaderConfiguration($vendor_dir);
$this->resolver->autoConfigureFromComposer($vendor_dir);
}
else
{
// Apparently, composer is not in use. Assume that Wedeto is packaged in one directory and add that
$my_dir = __DIR__;
$wedeto_dir = dirname(dirname($my_dir));
$this->autoloader->registerNS("Wedeto\\", $wedeto_dir, Autoloader::PSR4);
// Find modules containing assets, templates or apps
$modules = $this->resolver->findModules($wedeto_dir , '/modules', "", 0);
foreach ($modules as $name => $path)
$this->resolver->registerModule($name, $path);
}
} | php | {
"resource": ""
} |
q251930 | Application.setupLogging | validation | private function setupLogging()
{
$test = defined('WEDETO_TEST') && WEDETO_TEST === 1 ? 'test' : '';
$root_logger = Logger::getLogger();
$root_logger->setLevel(LogLevel::INFO);
if ($this->path_config->log)
{
$logfile = $this->path_config->log . '/wedeto' . $test . '.log';
$root_logger->addLogWriter(new FileWriter($logfile, LogLevel::DEBUG));
}
// Set up logger based on ini file
if ($this->config->has('log', Type::ARRAY))
{
foreach ($this->config['log'] as $logname => $level)
{
if ($logname === "writer")
{
foreach ($level as $logname => $parameters)
{
$logger = Logger::getLogger($logname);
$parameters = str_replace('{LOGDIR}', $this->path_config->log, $parameters);
$parameters = explode(';', $parameters);
$class = array_shift($parameters);
if (!class_exists($class))
throw new \DomainException("Invalid logger class: $class");
$refl = new \ReflectionClass($class);
$writer = $refl->newInstanceArgs($parameters);
if (!($writer instanceof AbstractWriter))
throw new \DomainException("Class $class is not a log writer");
$logger->addLogWriter($writer);
}
continue;
}
$logger = Logger::getLogger($logname);
$level = strtolower($level);
try
{
$logger->setLevel($level);
}
catch (\DomainException $e)
{
self::$logger->error("Failed to set log level for {0} to {1}: {2}", [$logname, $level, $e->getMessage()]);
}
}
}
// Load the configuration file
// Attach the dev logger when dev-mode is enabled
if ($this->dev)
{
$devlogger = new MemLogWriter(LogLevel::DEBUG);
$root_logger->addLogWriter($devlogger);
}
// Log beginning of request handling
if (isset($_SERVER['REQUEST_URI']))
{
self::$logger->debug(
"*** Starting processing for {0} request to {1}",
[$_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']]
);
}
// Change settings for CLI
if (Request::cli())
{
$limit = (int)$this->config->dget('cli', 'memory_limit', 1024);
ini_set('memory_limit', $limit . 'M');
ini_set('max_execution_time', 0);
ini_set('display_errors', 1);
}
else
ini_set('display_errors', 0);
} | php | {
"resource": ""
} |
q251931 | Application.handleException | validation | public static function handleException(\Throwable $e)
{
$app = self::getInstance();
if ($app->request === null)
$app->request = Request::createFromGlobals();
$req = $app->request;
try
{
// Try to form a good looking response
if (!Request::cli())
{
$mgr = $app->resolver;
$res = $mgr->getResolver('template');
$assets = $mgr->getResolver('assets');
$amgr = new AssetManager($assets);
$tpl = new Template($res, $amgr, $req);
$tpl->setExceptionTemplate($e);
$tpl->assign('exception', $e);
$tpl->assign('request', $req);
$tpl->assign('dev', $app->dev);
$app->i18n;
$response = $tpl->renderReturn();
$responder = new \Wedeto\HTTP\Responder();
$result = new \Wedeto\HTTP\Result();
$result->setResponse($response);
$responder->setRequest($req);
$responder->setResult($result);
// Inject CSS/JS
$params = new Dictionary(['responder' => $responder, 'mime' => 'text/html']);
$amgr->executeHook($params);
$responder->respond();
}
}
catch (\Throwable $e2)
{
echo "<h1>Error while showing error template:</h1>\n\n";
echo "<pre>" . WF::html($e2) . "</pre>\n";
}
if (Request::cli())
{
fprintf(STDERR, \Wedeto\Application\CLI\ANSI::bright("An uncaught exception has occurred:") . "\n\n");
WF::debug(WF::str($e));
}
else
{
echo "<h2>Original error:</h2>\n\n";
echo "<pre>" . WF::html($e) . "</pre>\n";
}
} | php | {
"resource": ""
} |
q251932 | Application.shutdown | validation | public function shutdown()
{
if (!$this->is_shutdown)
{
$this->is_shutdown = true;
// Unregister the autoloader
if (!empty($this->autoloader))
spl_autoload_unregister(array($this->autoloader, 'autoload'));
// Unregister the error handler
ErrorInterceptor::unregisterErrorHandler();
// Unregister the exception handler
restore_exception_handler();
}
} | php | {
"resource": ""
} |
q251933 | Builder.getDialectStatement | validation | protected function getDialectStatement(
/*# string */ $method,
/*# bool */ $setTable = true
)/*# StatementInterface */ {
// dialect
$dialect = $this->getDialect();
// check method
if (!method_exists($dialect, $method)) {
throw new BadMethodCallException(
Message::get(Message::BUILDER_UNKNOWN_METHOD, $method),
Message::BUILDER_UNKNOWN_METHOD
);
}
/* @var $statement StatementInterface */
$statement = call_user_func([$dialect, $method], $this);
// prevous statement like in UNION
if ($this->hasPrevious()) {
$statement->setPrevious($this->getPrevious());
$this->setPrevious(null);
// set tables
} elseif ($setTable && count($this->tables)) {
if (method_exists($statement, 'from')) {
// FROM all tables
$statement->from($this->tables);
} else {
// INTO the first table
$statement->into($this->tables[array_keys($this->tables)[0]]);
}
}
return $statement;
} | php | {
"resource": ""
} |
q251934 | Builder.fixTable | validation | protected function fixTable(
$table,
/*# string */ $tableAlias = ''
)/*# : array */ {
if (empty($table)) {
$table = [];
} else {
if (!is_array($table)) {
$table = empty($tableAlias) ? [$table] :
[$table => $tableAlias];
}
}
return $table;
} | php | {
"resource": ""
} |
q251935 | Session.startOrRestart | validation | protected function startOrRestart()
{
// if we have an active session: stop here
if ( session_status() == PHP_SESSION_ACTIVE )
return;
// set the session dir if needed
if ( $this->SessionDir )
{
if ( !file_exists( $this->SessionDir ) )
{
mkdir( $this->SessionDir, 0777, true );
}
session_save_path( $this->SessionDir );
}
// start the session
session_start();
// check ip and browser info first
$FingerPrint = "";
if ( $this->IpAddress )
{
if ( !$this->IpAddress->isValid() )
{
session_unset();
session_destroy();
throw new \Exception(
"Cannot start session. Reason: Invalid IP " . $this->IpAddress->getValue() . " detected", 403 );
}
else
$FingerPrint = $this->IpAddress->getValue();
}
if ( $this->Browser )
{
if ( !$this->Browser->isKnownBrowser() )
{
session_unset();
session_destroy();
throw new \Exception(
"Cannot start session. Reason: Invalid Browser " . $this->Browser->getSignature() . " detected.", 403 );
}
else
$FingerPrint .= $this->Browser->getSignature();
}
// now check for changes if we had a session before or a timeout
$currFp = md5( $FingerPrint );
$prevFp = isset( $_SESSION[ "FingerPrint" ] ) ? $_SESSION[ "FingerPrint" ] : null;
if ( $prevFp )
{
if ( $prevFp != $currFp )
{
session_unset();
session_destroy();
throw new \Exception( "Cannot start session. Reason: IP changed. Current is $currFp, previous was: $prevFp", Interfaces\HttpResponder::EXIT_CODE_UNAUTHORIZED );
}
}
// check timeout
$currTime = time();
$prevTime = isset( $_SESSION[ "LastSessionStart" ] ) ? $_SESSION[ "LastSessionStart" ] : null;
$timeOutSecs = isset( $_SESSION[ "TimeOutSecs" ] ) ? $_SESSION[ "TimeOutSecs" ] : null;
if ( $prevTime && $timeOutSecs )
{
if ( $prevTime + $timeOutSecs < $currTime )
{
session_unset();
session_destroy();
throw new \Exception( "Session timeout", Interfaces\HttpResponder::EXIT_CODE_UNAUTHORIZED );
}
}
$_SESSION[ "FingerPrint" ] = $currFp;
$_SESSION[ "LastSessionStart" ] = $currTime;
} | php | {
"resource": ""
} |
q251936 | Insert.select | validation | public function select(
$col = '',
/*# string */ $colAlias = ''
)/*# : SelectStatementInterface */ {
return $this->getBuilder()->setPrevious($this)->select($col, $colAlias);
} | php | {
"resource": ""
} |
q251937 | ProblemDetails.toArray | validation | public function toArray(): array
{
if (empty($this->output)) {
$problem = [
'type' => $this->type ? (string)$this->type : 'about:blank'
];
if ($this->title) {
$problem['title'] = $this->title;
}
if ($this->status) {
$problem['status'] = $this->status;
}
if ($this->detail) {
$problem['detail'] = $this->detail;
}
if ($this->instance) {
$problem['instance'] = (string)$this->instance;
}
$this->output = array_merge($problem, $this->extensions);
}
return $this->output;
} | php | {
"resource": ""
} |
q251938 | ProblemDetails.send | validation | public function send(ResponseInterface $response): ResponseInterface
{
$response->getBody()->write(json_encode($this->toArray()));
return $response->withHeader('Content-Type', self::MIME_TYPE_JSON);
} | php | {
"resource": ""
} |
q251939 | Validate.isPasswd | validation | public static function isPasswd($passwd, $size = Validate::PASSWORD_LENGTH)
{
return self::getPasswordComplexity($passwd, $size) >= self::PASSWORD_COMPLEXITY_MEDIUM;
} | php | {
"resource": ""
} |
q251940 | Validate.isBirthDate | validation | public static function isBirthDate($date)
{
if ($date === null || $date === '0000-00-00') {
return true;
}
if (preg_match('/^(\d{4})-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[1-2]\d)|(?:3[01]))(\d{2}:\d{2}:\d{2})?$/', $date, $birth_date)) {
return !(($birth_date[1] > date('Y') && $birth_date[2] > date('m') && $birth_date[3] > date('d')) ||
($birth_date[1] === date('Y') && $birth_date[2] === date('m') && $birth_date[3] > date('d')) ||
($birth_date[1] === date('Y') && $birth_date[2] > date('m'))
);
}
return false;
} | php | {
"resource": ""
} |
q251941 | Validate.isMobilePhoneNumber | validation | public static function isMobilePhoneNumber($phone)
{
$phoneNumber = substr(Tools::removeSpace($phone), -9, 1);
return (!self::isCzechPhoneNumber($phoneNumber) || ($phoneNumber === '6' || $phoneNumber === '7'));
} | php | {
"resource": ""
} |
q251942 | Validate.isBirthNumber | validation | public static function isBirthNumber($no)
{
if (!preg_match('#^\s*(\d\d)(\d\d)(\d\d)[ /]*(\d\d\d)(\d?)\s*$#', $no, $matches)) {
return false;
}
list(, $year, $month, $day, $ext, $c) = $matches;
if ($c === '') {
$year += $year < 54 ? 1900 : 1800;
} else {
$mod = ($year . $month . $day . $ext) % 11;
if ($mod === 10) {
$mod = 0;
}
if ($mod !== (int)$c) {
return false;
}
$year += $year < 54 ? 2000 : 1900;
}
if ($year > 2003) {
if ($month > 70) {
$month -= 70;
}
if ($month > 20 && $month < 50) {
$month -= 20;
}
}
if ($month > 50) {
$month -= 50;
}
return checkdate($month, $day, $year);
} | php | {
"resource": ""
} |
q251943 | Validate.getPasswordComplexity | validation | public static function getPasswordComplexity($password, $minLength)
{
$group = [
'upper' => '/[A-Z]/',
'lower' => '/[a-z]/',
'number' => '/[0-9]/',
'special' => '/[^A-Za-z0-9]/',
];
$score = 0;
$length = \strlen($password);
if ($length < $minLength) {
return 0;
}
// Increment the score for each of these conditions
foreach ($group as $pattern) {
if (preg_match($pattern, $password)) {
$score++;
}
}
// Penalize if there aren't at least three char types
if ($score < 3) {
$score--;
}
// Increment the score for every 2 chars longer than the minimum
if ($length > $minLength) {
$score += (int)floor(($length - $minLength) / 2);
}
return $score;
} | php | {
"resource": ""
} |
q251944 | LEController.loadLanguage | validation | public function loadLanguage( $controller, $language = 'en_US', $return = FALSE )
{
$langDirEvent = new GetLanguageDirEvent();
$this->dispatcher->fire( Events::EVENT_GET_LANG_DIR, $langDirEvent );
$langDir = $langDirEvent->getLangDir();
$retVal = FALSE;
if ( NULL === $langDir )
{
$retVal = FALSE;
}
else
{
$file = $langDir . $controller . DS . $language . '_lang.php';
if ( !file_exists( $file ) )
{
$defaultLangEvent = new GetDefaultLanguageEvent();
$this->dispatcher->fire( Events::EVENT_GET_DEFAULT_LANG, $defaultLangEvent );
$defaultLang = $defaultLangEvent->getDefaultLanguage();
if ( NULL === $defaultLang )
{
$retval = FALSE;
}
else
{
$file = $langDir
. $controller . DS
. $defaultLang
. '_lang.php';
}
}
if ( NULL === $file )
{
throw new RawException( 'Failed to load language file for ' . $controller );
}
$lang = include_once $file;
$this->language = array_merge( $this->language, $lang );
$retVal = $lang;
}
return $retVal;
} | php | {
"resource": ""
} |
q251945 | RestController.getModel | validation | public function getModel()
{
if(null === $this->model) {
$mainService = $this->getServiceLocator()->get('neobazaar.service.main');
$this->model = $mainService->getUserEntityRepository();
}
return $this->model;
} | php | {
"resource": ""
} |
q251946 | RestController.getEntityManager | validation | public function getEntityManager()
{
if (null === $this->em) {
$mainService = $this->getServiceLocator()->get('neobazaar.service.main');
$this->em = $mainService->getEntityManager();
}
return $this->em;
} | php | {
"resource": ""
} |
q251947 | RestController.getUserAddForm | validation | public function getUserAddForm()
{
if (null === $this->userAddForm) {
$this->userAddForm = $this->getServiceLocator()->get('user.form.useradd');
}
return $this->userAddForm;
} | php | {
"resource": ""
} |
q251948 | BaseRepository.applyCriteria | validation | public function applyCriteria($criteria)
{
$query = $this->getQuery();
if($criteria instanceof Criteria){
$criteria->apply($query);
return $this;
}
if($criteria instanceof Closure){
$criteria($query);
return $this;
}
throw new RepositoryException("Must be an instance of " . Criteria::class . " or \\Closure");
} | php | {
"resource": ""
} |
q251949 | BaseRepository.getMany | validation | public function getMany($columns = ['*'], $paginated = false, $perPage = null)
{
$results = $paginated
? $this->getManyPaginated($perPage, $columns)
: $this->getQuery()->get($columns);
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251950 | BaseRepository.getManyPaginated | validation | public function getManyPaginated($perPage = null, $columns = ['*'])
{
$query = $this->getQuery();
$results = $query->paginate($perPage, $columns);
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251951 | BaseRepository.getById | validation | public function getById($id, $columns = ['*'])
{
try {
$results = $this->getQuery()->findOrFail($id, $columns);
}
catch(ModelNotFoundException $e){
throw new NotFoundRepositoryException($e);
}
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251952 | BaseRepository.getManyByIds | validation | public function getManyByIds(array $ids, $columns = ['*'])
{
$results = $this->getQuery()->findMany($ids, $columns);
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251953 | BaseRepository.create | validation | public function create(array $attributes = [])
{
$model = $this->newModel();
$model->fill($attributes);
$this->save($model);
return $model;
} | php | {
"resource": ""
} |
q251954 | BaseRepository.saveMany | validation | public function saveMany(ArrayAccess $models)
{
//transform to collection
if(!$models instanceof Collection){
$models = collect($models);
}
foreach ($models as $model) {
$this->save($model);
}
return $models;
} | php | {
"resource": ""
} |
q251955 | BaseRepository.updateById | validation | public function updateById($id, array $newAttributes)
{
$model = $this->getById($id);
$results = $model->update($newAttributes);
if(!$results){
throw new UpdateFailedRepositoryException();
}
return $model;
} | php | {
"resource": ""
} |
q251956 | BaseRepository.update | validation | public function update(Model $model, array $newAttributes)
{
$results = $model->update($newAttributes);
if(!$results){
throw new UpdateFailedRepositoryException();
}
return $model;
} | php | {
"resource": ""
} |
q251957 | BaseRepository.deleteMany | validation | public function deleteMany(ArrayAccess $models)
{
$results = [];
foreach ($models as $model) {
$results[] = $this->delete($model);
}
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251958 | BaseRepository.newModel | validation | public function newModel()
{
$model = app()->make($this->modelClass);
if (!$model instanceof Model) {
throw new RepositoryException("Class {$this->modelClass} must be an instance of Illuminate\\Database\\Eloquent\\Model");
}
return $model;
} | php | {
"resource": ""
} |
q251959 | BaseRepository.paginate | validation | public function paginate($page = 1, $perPage = null, $columns = ['*'])
{
$perPage = $perPage ?: $this->defaultPageSize;
$query = $this->getQuery();
$total = $query->getQuery()->getCountForPagination($columns);
$query->getQuery()->forPage($page, $perPage);
$results = $query->get($columns);
$results = new LengthAwarePaginator($results, $total, $perPage, $page);
return $this->returnResults($results);
} | php | {
"resource": ""
} |
q251960 | OverviewNavigationItem.addThumbnail | validation | public function addThumbnail(\TYPO3\CMS\Extbase\Domain\Model\FileReference $thumbnail) {
$this->thumbnails->attach($thumbnail);
} | php | {
"resource": ""
} |
q251961 | OverviewNavigationItem.removeThumbnail | validation | public function removeThumbnail(\TYPO3\CMS\Extbase\Domain\Model\FileReference $thumbnail) {
$this->thumbnails->detach($thumbnail);
} | php | {
"resource": ""
} |
q251962 | OverviewNavigationItem.getLabel | validation | public function getLabel() {
$label = $this->label;
$title = $this->title;
if ($label) {
return $label;
} else {
return $title;
}
} | php | {
"resource": ""
} |
q251963 | Connection.count | validation | public function count($col, $alias, $distinct = false)
{
$this->counts[] = [$col, $alias, $distinct];
return $this;
} | php | {
"resource": ""
} |
q251964 | Connection.raw | validation | public function raw($sql, array $params)
{
$stmt = $this->connect()->prepare($sql);
$stmt->execute($params);
if (stripos($sql, 'select') === 0) {
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if (stripos($sql, 'insert') === 0) {
return $this->connect()->lastInsertId();
}
// if (stripos($sql, 'update') === 0 || stripos($sql, 'delete') === 0 || stripos($sql, 'replace') === 0) {
return $stmt->execute();
// }
} | php | {
"resource": ""
} |
q251965 | Connection.getNumRows | validation | public function getNumRows()
{
$builtSql = SqlBuilder::buildRowCountSql($this);
if (is_array($builtSql)) {
$preparedSth = $this->connect()->prepare($builtSql[0]);
$boundSth = StatementBuilder::bindValues($preparedSth, $builtSql[1]);
$boundSth->execute();
} else {
$boundSth = $this->connect()->query($builtSql);
}
$result = $boundSth->fetch(PDO::FETCH_ASSOC);
return (int)$result['total_count'];
} | php | {
"resource": ""
} |
q251966 | MelisPageHistoricTable.getPageHistoricListOfActions | validation | public function getPageHistoricListOfActions($order = 'ASC')
{
$select = $this->tableGateway->getSql()->select();
$select->columns(["action" => new Expression('DISTINCT(hist_action)')]);
$select->order('hist_action' . ' ' . $order);
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
} | php | {
"resource": ""
} |
q251967 | MelisPageHistoricTable.getUsers | validation | public function getUsers() {
$select = $this->tableGateway->getSql()->select();
$select->columns(["fullname" => new Expression("DISTINCT(CONCAT(usr_firstname, ' ', usr_lastname))")]);
$select->join('melis_core_user',
'melis_core_user.usr_id = melis_hist_page_historic.hist_user_id',
[],
$select::JOIN_INNER
);
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
} | php | {
"resource": ""
} |
q251968 | TimeType.getYear | validation | public function getYear()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['year'];
}
} | php | {
"resource": ""
} |
q251969 | TimeType.getMonth | validation | public function getMonth()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['month'];
}
} | php | {
"resource": ""
} |
q251970 | TimeType.getDay | validation | public function getDay()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['day'];
}
} | php | {
"resource": ""
} |
q251971 | TimeType.getHour | validation | public function getHour()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['hour'];
}
} | php | {
"resource": ""
} |
q251972 | TimeType.getMinute | validation | public function getMinute()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['minute'];
}
} | php | {
"resource": ""
} |
q251973 | TimeType.getSecond | validation | public function getSecond()
{
if ($this->value !== null) {
preg_match('/^(?P<year>[0-9]{4,4})-(?P<month>[0-9]{2,2})-(?P<day>[0-9]{2,2}) (?P<hour>[0-9]{2,2}):(?P<minute>[0-9]{2,2}):(?P<second>[0-9]{2,2})$/ui', $this->value, $m);
return (int) $m['second'];
}
} | php | {
"resource": ""
} |
q251974 | TimeType.checkLeapYear | validation | public static function checkLeapYear($year)
{
$year = Cast::_Int($year);
if ($year % 4 !== 0) {
return false;
} elseif ($year % 100 !== 0) {
return true;
} elseif ($year % 400 !== 0) {
return false;
} elseif ($year === 0) {
return false;
}
return true;
} | php | {
"resource": ""
} |
q251975 | Interval.setLower | validation | public function setLower($lower): self
{
// if $lower is not a number, short-circuit
if ( ! is_numeric($lower)) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, lower, to be a number"
);
}
$this->lower = +$lower;
return $this;
} | php | {
"resource": ""
} |
q251976 | Interval.setUpper | validation | public function setUpper($upper): self
{
if ( ! is_numeric($upper)) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, upper, to be a number"
);
}
$this->upper = $upper;
return $this;
} | php | {
"resource": ""
} |
q251977 | Interval.compare | validation | public function compare($x): int
{
// if $x is not numeric, short-circuit
if ( ! is_numeric($x)) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, x, to be a number"
);
}
if (
$x < $this->lower
|| ( ! $this->isLowerInclusive && $x == $this->lower)
) {
return -1;
} elseif (
$x > $this->upper
|| ( ! $this->isUpperInclusive && $x == $this->upper)
) {
return 1;
} else {
return 0;
}
} | php | {
"resource": ""
} |
q251978 | Interval.parse | validation | public function parse(string $string): self
{
// if the $string is not valid interval, short-circuit
$pattern = '/^[\[\(]-?(\d*[\.]?\d+|INF), -?(\d*[\.]?\d+|INF)[\]\)]$/';
if ( ! preg_match($pattern, $string)) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, string, to be a valid "
. "interval; see the README for details"
);
}
// otherwise, check the boundaries
$this->isLowerInclusive = substr($string, 0, 1) === '[';
$this->isUpperInclusive = substr($string, -1, 1) === ']';
// get the endpoints
$endpoints = explode($this->separator, substr($string, 1, -1));
// loop through the endpoints
foreach ($endpoints as &$endpoint) {
// if the endpoint is negative or positive infinity, convert the value
// to the PHP constant; otherwise, cast the value to int or float
//
if ($endpoint === self::INFINITY_NEGATIVE) {
$endpoint = -INF;
} elseif ($endpoint === self::INFINITY_POSITIVE) {
$endpoint = INF;
} else {
$endpoint = +$endpoint;
}
}
// if the endpoints are out of order, short-circuit
if ($endpoints[1] < $endpoints[0]) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, string, to be a valid "
. "interval, however, the upper bound appears to be greater "
. "than the lower bound"
);
}
// if the endpoints are equal, the boundaries must match
if (
$endpoints[0] == $endpoints[1]
&& $this->isLowerInclusive !== $this->isUpperInclusive
) {
throw new InvalidArgumentException(
__METHOD__ . "() expects parameter one, string, to be a valid "
. "interval, however, the endpoints are the same but the "
. "boundaries are different"
);
}
// otherwise, set the endpoints
$this->lower = $endpoints[0];
$this->upper = $endpoints[1];
return $this;
} | php | {
"resource": ""
} |
q251979 | ChainEngine.search | validation | public function search($query)
{
$results = new ResultCollection();
foreach ($this->engines as $eachEngine) {
if (!$eachEngine->supports($query)) {
continue;
}
if ($more = $eachEngine->search($query)) {
if (!is_array($more) and !$more instanceof \Traversable) {
throw new DomainException('The returned result set is not traversable.');
}
foreach ($more as $eachResult) {
$results->add($eachResult);
}
}
}
return $results;
} | php | {
"resource": ""
} |
q251980 | ChainEngine.supports | validation | public function supports($query)
{
foreach ($this->engines as $eachEngine) {
if ($eachEngine->supports($query)) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q251981 | Action._init | validation | private function _init( $params )
{
if ( NULL !== $params && 0 < count( $params ) )
{
foreach ( $params as $key => $value )
{
$this->_params[ ] = $value;
}
}
} | php | {
"resource": ""
} |
q251982 | DeleteRecordTrait.buildRecord | validation | protected function buildRecord()/*# : array */
{
$res = [];
foreach ($this->clause_records as $tbl) {
$res[] = $this->quote($tbl) . '.*';
}
if (!empty($res)) {
return [join(', ', $res)];
} else {
return [];
}
} | php | {
"resource": ""
} |
q251983 | DataContainer.get | validation | public function get($keys, $default = null)
{
$result = $this->data;
foreach (is_array($keys) ? $keys : [$keys] as $key) {
if (is_array($result) && isset($result[$key])) {
$result = $result[$key];
} else {
$result = $default;
break;
}
}
return $result;
} | php | {
"resource": ""
} |
q251984 | DataContainer.getDateTime | validation | public function getDateTime($keys, DateTime $default = null)
{
$value = $this->getString($keys);
if (empty($value)) {
$result = $default;
} elseif ($value === (string)(int)$value) {
$result = new DateTime();
$result->setTimestamp((int)$value);
} else {
$result = new DateTime($value);
}
return $result;
} | php | {
"resource": ""
} |
q251985 | DataContainer.getArray | validation | public function getArray($keys, array $default = []): array
{
$result = $this->get($keys, $default);
if (!is_array($result)) {
$result = $default;
}
return $result;
} | php | {
"resource": ""
} |
q251986 | DataContainer.getObjectArray | validation | public function getObjectArray($keys): array
{
return array_map(function ($value) {
return $this->createObject($value);
}, $this->getArray($keys));
} | php | {
"resource": ""
} |
q251987 | JsonHelper.sendJson | validation | protected function sendJson(Response $response, $payload): Response
{
$response->getBody()->write(json_encode($payload));
return $response->withHeader('Content-Type', 'application/json');
} | php | {
"resource": ""
} |
q251988 | JsonHelper.sendItems | validation | protected function sendItems(Response $response, iterable $items, ?Pagination $pagination = null, ?int $total = null): Response
{
$items = is_array($items) ? $items : ($items instanceof \Traversable ? iterator_to_array($items, false) : []);
$total = $total ?? count($items);
$start = $pagination === null ? 0 : $pagination->getOffset();
$max = $pagination === null ? 0 : $pagination->getMax();
// make sure $end is no higher than $total and isn't negative
$end = max(min((PHP_INT_MAX - $max < $start ? PHP_INT_MAX : $start + $max), $total) - 1, 0);
return $this->sendJson(
$response->withHeader('Content-Range', "items $start-$end/$total"),
$items
);
} | php | {
"resource": ""
} |
q251989 | JsonHelper.sendCreated | validation | protected function sendCreated(Response $response, string $type, array $ids, array $extra = []): Response
{
return $this->sendVerb('created', $response, $type, $ids, $extra)
->withStatus(201, "Created");
} | php | {
"resource": ""
} |
q251990 | JsonHelper.sendDeleted | validation | protected function sendDeleted(Response $response, string $type, array $ids, array $extra = []): Response
{
return $this->sendVerb('deleted', $response, $type, $ids, $extra);
} | php | {
"resource": ""
} |
q251991 | JsonHelper.sendVerb | validation | protected function sendVerb(string $verb, Response $response, string $type, array $ids, array $extra = []): Response
{
$send = array_merge([], $extra);
$send['success'] = true;
$send['message'] = "Objects $verb successfully";
$send['objects'] = array_map(function ($id) use ($type) {
return ['type' => $type, 'id' => $id];
}, $ids);
return $this->sendJson($response, $send);
} | php | {
"resource": ""
} |
q251992 | User.init | validation | public function init(UserEntity $user, ServiceManager $sm)
{
$main = $sm->get('neobazaar.service.main');
$userRepository = $main->getUserEntityRepository();
$this->hashId = $userRepository->getEncryptedId($user->getUserId());
$this->name = $user->getName();
$this->surname = $user->getSurname();
$this->email = $user->getEmail();
$this->gender = $user->getGender();
$this->dateBorn = $this->getDateBorn($user, $sm);
$this->nicename = $user->getNicename();
$this->mobile = $this->getMobile($user);
$this->isAdmin = 'god' == $user->getRole();
$this->fullname = $this->getFullname($user);
$this->role = $user->getRole();
$this->state = $user->getState();
$this->stateFormatted = $this->getStateFormatted($user);
$this->editAddress = '/#/edituseerrr';
$this->isActive = $user->getState() == UserEntity::USER_STATE_ACTIVE;
$this->isDeactive = $user->getState() == UserEntity::USER_STATE_DEACTIVE;
$this->isDeleted = $user->getState() == UserEntity::USER_STATE_DELETED;
$this->isBanned = $user->getState() == UserEntity::USER_STATE_BANNED;
//$this->count = $this->countClassifieds($user, $sm);
$this->count = 'disabled';
return $this;
} | php | {
"resource": ""
} |
q251993 | User.getStateFormatted | validation | protected function getStateFormatted(UserEntity $user)
{
switch($user->getState()) {
case UserEntity::USER_STATE_ACTIVE:
$this->stateClass = 'success';
return 'Attivo';
break;
case UserEntity::USER_STATE_BANNED:
$this->stateClass = 'danger';
return 'Bannato';
break;
case UserEntity::USER_STATE_DEACTIVE:
$this->stateClass = 'warning';
return 'Disattivo';
break;
case UserEntity::USER_STATE_DELETED:
$this->stateClass = 'danger';
return 'Eliminato';
break;
}
$this->stateClass = 'danger';
return 'Error with user state';
} | php | {
"resource": ""
} |
q251994 | User.getMobile | validation | protected function getMobile(UserEntity $user)
{
$metadata = $user->getMetadata();
foreach($metadata as $meta) {
if('cellulare' == $meta->getKey()) {
return $meta->getValue();
}
}
return null;
} | php | {
"resource": ""
} |
q251995 | User.getDateBorn | validation | public function getDateBorn(UserEntity $user, $sm)
{
$dateFormatter = new \IntlDateFormatter(
\Locale::getDefault(),
\IntlDateFormatter::NONE,
\IntlDateFormatter::NONE,
\date_default_timezone_get(),
\IntlDateFormatter::GREGORIAN,
"dd MMMM YYYY"
);
$date = $user->getDateBorn();
return $dateFormatter->format($date);
} | php | {
"resource": ""
} |
q251996 | TableOptionTrait.buildTblOpt | validation | protected function buildTblOpt()/*# : array */
{
$result = [];
foreach ($this->tbl_option as $opt) {
$result[] = $opt;
}
if (empty($result)) {
$result[] = '';
}
return $result;
} | php | {
"resource": ""
} |
q251997 | HaltoRouter.map | validation | public function map($method, $route, $target, $name = null, $hostGroup = null, $prepend = false)
{
if (!$hostGroup) {
$hostGroup = null;
}
if ($prepend) {
array_unshift($this->routes, array($method, $route, $target, $name, $hostGroup));
} else {
$this->routes[] = array($method, $route, $target, $name, $hostGroup);
}
if ($name) {
if (array_key_exists($name, $this->namedRoutes)) {
throw new HaltoRouterException("Can not redeclare route $name");
}
$this->namedRoutes[$name] = array($route, $hostGroup);
}
return $this;
} | php | {
"resource": ""
} |
q251998 | StatsTable.totals | validation | public function totals($locale = null)
{
$this->setLocale($locale);
$totals = Collection::make();
foreach (Arr::except($this->footer(), 'all') as $level => $count) {
$totals->put($level, [
'label' => trans('dashboard::logs.'.$level),
'value' => $count,
'color' => $this->color($level),
'highlight' => $this->color($level),
]);
}
return $totals;
} | php | {
"resource": ""
} |
q251999 | StatsTable.prepareHeader | validation | protected function prepareHeader(array $data)
{
return array_merge_recursive(
[
'date' => trans('dashboard::logs.date'),
'all' => trans('dashboard::logs.all'),
],
$this->levels->names($this->locale)
);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.