_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q267200
Container.arrayify
test
protected function arrayify(Container $o) { $a = []; foreach ($o->props as $k => $v) { if ($v instanceof Container) { $a[$k] = $this->arrayify($v); } else { $a[$k] = $v; } } return $a; }
php
{ "resource": "" }
q267201
Container.apply
test
public function apply($modifier) { if (is_callable($modifier)) { foreach ($this->props as $prop => $value) { $this->__set($prop, $modifier($value, $prop)); } } else { foreach ($modifier as $key => $mod) { if (is_callable($mod)) { $this->props->$key = $mod(isset($this->props->$key) ? $this->props->$key : null, $key); } elseif (is_array($mod)) { $this->props->$key->apply($mod); } else { /* */ } } } return $this; }
php
{ "resource": "" }
q267202
CssResource.fromUrl
test
public static function fromUrl($cssUrl, $baseUrl, $mediaType = 'all') { // Match URL. if (strpos($cssUrl, $baseUrl) === false) { throw new \InvalidArgumentException('The CSS URL does not begin with the base URL'); } // Create. $baseLength = strlen(rtrim($baseUrl, '/')) + 1; $path = substr($cssUrl, $baseLength); return new CssResource($path, $mediaType); }
php
{ "resource": "" }
q267203
MessagingController.getAddressBook
test
public function getAddressBook() { $acquaintances = Auth::user()->getAcquaintances(); return view('mustard::messages.address-book', [ 'acquaintances' => new Paginator($acquaintances, $acquaintances->count(), config('per_page', 25)), ]); }
php
{ "resource": "" }
q267204
MessagingController.getCompose
test
public function getCompose() { $acquaintances = Auth::user()->getAcquaintances(); if ($acquaintances->isEmpty()) { return redirect()->to('/account/contacts')->withStatus('Your contacts list is empty.'); } return view('mustard::messages.compose', [ 'acquaintances' => $acquaintances->sortBy('username', SORT_NATURAL | SORT_FLAG_CASE), 'message' => new Message(), ]); }
php
{ "resource": "" }
q267205
MessagingController.getView
test
public function getView($messageId) { $message = Message::find($messageId); $message->read = true; $message->save(); return view('mustard::messages.view', [ 'message' => $message, ]); }
php
{ "resource": "" }
q267206
MessagingController.postManage
test
public function postManage(Request $request) { foreach ($request->input('messages') as $message_id) { $message = Message::find($message_id); if (is_null($message) || !$request->has('action')) { continue; } switch ($request->input('action')) { case 'mark_read': if ($message->read == false) { $message->read = true; $message->save(); } break; case 'mark_unread': if ($message->read == true) { $message->read = false; $message->save(); } break; case 'delete': $message->delete(); break; } } return redirect()->back(); }
php
{ "resource": "" }
q267207
WindowsExtensionAppenderTrait._appendExtensionsToPaths
test
protected function _appendExtensionsToPaths(array $paths, array $extensions) { $getPathsWithExtensions = function($path) use($extensions) { if ($this->_hasExtension($path)) { return [$path]; } $addExtension = function($extension) use($path) { return $this->_addExtension($path, $extension); }; return array_map($addExtension, $extensions); }; return call_user_func_array('array_merge', array_map($getPathsWithExtensions, $paths)); }
php
{ "resource": "" }
q267208
Session.destroy
test
public function destroy(): void { // see example here http://goo.gl/nBVl0 $this->logout(); $p = session_get_cookie_params(); setcookie(session_name(), "", time() - 42000, $p["path"], $p["domain"], $p["secure"], $p["httponly"]); session_destroy(); }
php
{ "resource": "" }
q267209
PEAR_Autoloader.addAutoload
test
function addAutoload($method, $classname = null) { if (is_array($method)) { array_walk($method, create_function('$a,&$b', '$b = strtolower($b);')); $this->_autoload_map = array_merge($this->_autoload_map, $method); } else { $this->_autoload_map[strtolower($method)] = $classname; } }
php
{ "resource": "" }
q267210
PEAR_Autoloader.removeAutoload
test
function removeAutoload($method) { $method = strtolower($method); $ok = isset($this->_autoload_map[$method]); unset($this->_autoload_map[$method]); return $ok; }
php
{ "resource": "" }
q267211
PEAR_Autoloader.removeAggregateObject
test
function removeAggregateObject($classname) { $ok = false; $classname = strtolower($classname); reset($this->_method_map); while (list($method, $obj) = each($this->_method_map)) { if (is_a($obj, $classname)) { unset($this->_method_map[$method]); $ok = true; } } return $ok; }
php
{ "resource": "" }
q267212
Console_Getopt.getopt2
test
function getopt2($args, $short_options, $long_options = null, $skip_unknown = false) { return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown); }
php
{ "resource": "" }
q267213
Console_Getopt.doGetopt
test
function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false) { // in case you pass directly readPHPArgv() as the first arg if (PEAR::isError($args)) { return $args; } if (empty($args)) { return array(array(), array()); } $non_opts = $opts = array(); settype($args, 'array'); if ($long_options) { sort($long_options); } /* * Preserve backwards compatibility with callers that relied on * erroneous POSIX fix. */ if ($version < 2) { if (isset($args[0]{0}) && $args[0]{0} != '-') { array_shift($args); } } reset($args); while (list($i, $arg) = each($args)) { /* The special element '--' means explicit end of options. Treat the rest of the arguments as non-options and end the loop. */ if ($arg == '--') { $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); break; } if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) { $non_opts = array_merge($non_opts, array_slice($args, $i)); break; } elseif (strlen($arg) > 1 && $arg{1} == '-') { $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args, $skip_unknown); if (PEAR::isError($error)) { return $error; } } elseif ($arg == '-') { // - is stdin $non_opts = array_merge($non_opts, array_slice($args, $i)); break; } else { $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args, $skip_unknown); if (PEAR::isError($error)) { return $error; } } } return array($opts, $non_opts); }
php
{ "resource": "" }
q267214
Console_Getopt._parseShortOption
test
function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown) { for ($i = 0; $i < strlen($arg); $i++) { $opt = $arg{$i}; $opt_arg = null; /* Try to find the short option in the specifier string. */ if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') { if ($skip_unknown === true) { break; } $msg = "Console_Getopt: unrecognized option -- $opt"; return PEAR::raiseError($msg); } if (strlen($spec) > 1 && $spec{1} == ':') { if (strlen($spec) > 2 && $spec{2} == ':') { if ($i + 1 < strlen($arg)) { /* Option takes an optional argument. Use the remainder of the arg string if there is anything left. */ $opts[] = array($opt, substr($arg, $i + 1)); break; } } else { /* Option requires an argument. Use the remainder of the arg string if there is anything left. */ if ($i + 1 < strlen($arg)) { $opts[] = array($opt, substr($arg, $i + 1)); break; } else if (list(, $opt_arg) = each($args)) { /* Else use the next argument. */; if (Console_Getopt::_isShortOpt($opt_arg) || Console_Getopt::_isLongOpt($opt_arg)) { $msg = "option requires an argument --$opt"; return PEAR::raiseError("Console_Getopt:" . $msg); } } else { $msg = "option requires an argument --$opt"; return PEAR::raiseError("Console_Getopt:" . $msg); } } } $opts[] = array($opt, $opt_arg); } }
php
{ "resource": "" }
q267215
System._parseArgs
test
function _parseArgs($argv, $short_options, $long_options = null) { if (!is_array($argv) && $argv !== null) { // Find all items, quoted or otherwise preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av); $argv = $av[1]; foreach ($av[2] as $k => $a) { if (empty($a)) { continue; } $argv[$k] = trim($a) ; } } return Console_Getopt::getopt2($argv, $short_options, $long_options); }
php
{ "resource": "" }
q267216
System._dirToStruct
test
function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false) { $struct = array('dirs' => array(), 'files' => array()); if (($dir = @opendir($sPath)) === false) { if (!$silent) { System::raiseError("Could not open dir $sPath"); } return $struct; // XXX could not open error } $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ? $list = array(); while (false !== ($file = readdir($dir))) { if ($file != '.' && $file != '..') { $list[] = $file; } } closedir($dir); natsort($list); if ($aktinst < $maxinst || $maxinst == 0) { foreach ($list as $val) { $path = $sPath . DIRECTORY_SEPARATOR . $val; if (is_dir($path) && !is_link($path)) { $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1, $silent); $struct = array_merge_recursive($struct, $tmp); } else { $struct['files'][] = $path; } } } return $struct; }
php
{ "resource": "" }
q267217
System._multipleToStruct
test
function _multipleToStruct($files) { $struct = array('dirs' => array(), 'files' => array()); settype($files, 'array'); foreach ($files as $file) { if (is_dir($file) && !is_link($file)) { $tmp = System::_dirToStruct($file, 0); $struct = array_merge_recursive($tmp, $struct); } else { if (!in_array($file, $struct['files'])) { $struct['files'][] = $file; } } } return $struct; }
php
{ "resource": "" }
q267218
System.rm
test
function rm($args) { $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-) if (PEAR::isError($opts)) { return System::raiseError($opts); } foreach ($opts[0] as $opt) { if ($opt[0] == 'r') { $do_recursive = true; } } $ret = true; if (isset($do_recursive)) { $struct = System::_multipleToStruct($opts[1]); foreach ($struct['files'] as $file) { if (!@unlink($file)) { $ret = false; } } rsort($struct['dirs']); foreach ($struct['dirs'] as $dir) { if (!@rmdir($dir)) { $ret = false; } } } else { foreach ($opts[1] as $file) { $delete = (is_dir($file)) ? 'rmdir' : 'unlink'; if (!@$delete($file)) { $ret = false; } } } return $ret; }
php
{ "resource": "" }
q267219
System.mkDir
test
function mkDir($args) { $opts = System::_parseArgs($args, 'pm:'); if (PEAR::isError($opts)) { return System::raiseError($opts); } $mode = 0777; // default mode foreach ($opts[0] as $opt) { if ($opt[0] == 'p') { $create_parents = true; } elseif ($opt[0] == 'm') { // if the mode is clearly an octal number (starts with 0) // convert it to decimal if (strlen($opt[1]) && $opt[1]{0} == '0') { $opt[1] = octdec($opt[1]); } else { // convert to int $opt[1] += 0; } $mode = $opt[1]; } } $ret = true; if (isset($create_parents)) { foreach ($opts[1] as $dir) { $dirstack = array(); while ((!file_exists($dir) || !is_dir($dir)) && $dir != DIRECTORY_SEPARATOR) { array_unshift($dirstack, $dir); $dir = dirname($dir); } while ($newdir = array_shift($dirstack)) { if (!is_writeable(dirname($newdir))) { $ret = false; break; } if (!mkdir($newdir, $mode)) { $ret = false; } } } } else { foreach($opts[1] as $dir) { if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) { $ret = false; } } } return $ret; }
php
{ "resource": "" }
q267220
System.mktemp
test
function mktemp($args = null) { static $first_time = true; $opts = System::_parseArgs($args, 't:d'); if (PEAR::isError($opts)) { return System::raiseError($opts); } foreach ($opts[0] as $opt) { if ($opt[0] == 'd') { $tmp_is_dir = true; } elseif ($opt[0] == 't') { $tmpdir = $opt[1]; } } $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp'; if (!isset($tmpdir)) { $tmpdir = System::tmpdir(); } if (!System::mkDir(array('-p', $tmpdir))) { return false; } $tmp = tempnam($tmpdir, $prefix); if (isset($tmp_is_dir)) { unlink($tmp); // be careful possible race condition here if (!mkdir($tmp, 0700)) { return System::raiseError("Unable to create temporary directory $tmpdir"); } } $GLOBALS['_System_temp_files'][] = $tmp; if (isset($tmp_is_dir)) { //$GLOBALS['_System_temp_files'][] = dirname($tmp); } if ($first_time) { PEAR::registerShutdownFunc(array('System', '_removeTmpFiles')); $first_time = false; } return $tmp; }
php
{ "resource": "" }
q267221
System._removeTmpFiles
test
function _removeTmpFiles() { if (count($GLOBALS['_System_temp_files'])) { $delete = $GLOBALS['_System_temp_files']; array_unshift($delete, '-r'); System::rm($delete); $GLOBALS['_System_temp_files'] = array(); } }
php
{ "resource": "" }
q267222
System.find
test
function find($args) { if (!is_array($args)) { $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY); } $dir = realpath(array_shift($args)); if (!$dir) { return array(); } $patterns = array(); $depth = 0; $do_files = $do_dirs = true; $args_count = count($args); for ($i = 0; $i < $args_count; $i++) { switch ($args[$i]) { case '-type': if (in_array($args[$i+1], array('d', 'f'))) { if ($args[$i+1] == 'd') { $do_files = false; } else { $do_dirs = false; } } $i++; break; case '-name': $name = preg_quote($args[$i+1], '#'); // our magic characters ? and * have just been escaped, // so now we change the escaped versions to PCRE operators $name = strtr($name, array('\?' => '.', '\*' => '.*')); $patterns[] = '('.$name.')'; $i++; break; case '-maxdepth': $depth = $args[$i+1]; break; } } $path = System::_dirToStruct($dir, $depth, 0, true); if ($do_files && $do_dirs) { $files = array_merge($path['files'], $path['dirs']); } elseif ($do_dirs) { $files = $path['dirs']; } else { $files = $path['files']; } if (count($patterns)) { $dsq = preg_quote(DIRECTORY_SEPARATOR, '#'); $pattern = '#(^|'.$dsq.')'.implode('|', $patterns).'($|'.$dsq.')#'; $ret = array(); $files_count = count($files); for ($i = 0; $i < $files_count; $i++) { // only search in the part of the file below the current directory $filepart = basename($files[$i]); if (preg_match($pattern, $filepart)) { $ret[] = $files[$i]; } } return $ret; } return $files; }
php
{ "resource": "" }
q267223
Logger.getLog
test
protected function getLog(string $message, PriorityInterface $priority = null, array $metaData = null): LogInterface { return new Log($message, $priority ?? null, null, $metaData ?? null); }
php
{ "resource": "" }
q267224
BudgetCategoryAbstract.setBudgetId
test
public function setBudgetId($budgetId) { $budgetId = (int) $budgetId; if ($this->budgetId < 0) { throw new \UnderflowException('Value of "budgetId" must be greater than 0'); } if ($this->exists() && $this->budgetId !== $budgetId) { $this->updated['budgetId'] = true; } $this->budgetId = $budgetId; return $this; }
php
{ "resource": "" }
q267225
BudgetCategoryAbstract.getBudget
test
public function getBudget($isForceReload = false) { if ($isForceReload || null === $this->joinOneCacheBudget) { $mapper = new BudgetMapper($this->dependencyContainer->getDatabase('money')); $this->joinOneCacheBudget = $mapper->findByKeys(array( 'budget_id' => $this->getBudgetId(), )); } return $this->joinOneCacheBudget; }
php
{ "resource": "" }
q267226
BudgetCategoryAbstract.getAllTransaction
test
public function getAllTransaction($isForceReload = false) { if ($isForceReload || null === $this->joinManyCacheTransaction) { $mapper = new TransactionMapper($this->dependencyContainer->getDatabase('money')); $mapper->addWhere('category_id', $this->getCategoryId()); $this->joinManyCacheTransaction = $mapper->select(); } return $this->joinManyCacheTransaction; }
php
{ "resource": "" }
q267227
Zend_Config_Writer_Ini._prepareValue
test
protected function _prepareValue($value) { if (is_integer($value) || is_float($value)) { return $value; } elseif (is_bool($value)) { return ($value ? 'true' : 'false'); } elseif (strpos($value, '"') === false) { return '"' . $value . '"'; } else { /** @see Zend_Config_Exception */ throw new Zend_Config_Exception('Value can not contain double quotes "'); } }
php
{ "resource": "" }
q267228
HTTP_Request2.setUrl
test
public function setUrl($url) { if (is_string($url)) { $url = new Net_URL2( $url, array(Net_URL2::OPTION_USE_BRACKETS => $this->config['use_brackets']) ); } if (!$url instanceof Net_URL2) { throw new HTTP_Request2_LogicException( 'Parameter is not a valid HTTP URL', HTTP_Request2_Exception::INVALID_ARGUMENT ); } // URL contains username / password? if ($url->getUserinfo()) { $username = $url->getUser(); $password = $url->getPassword(); $this->setAuth(rawurldecode($username), $password? rawurldecode($password): ''); $url->setUserinfo(''); } if ('' == $url->getPath()) { $url->setPath('/'); } $this->url = $url; return $this; }
php
{ "resource": "" }
q267229
HTTP_Request2.setMethod
test
public function setMethod($method) { // Method name should be a token: http://tools.ietf.org/html/rfc2616#section-5.1.1 if (preg_match(self::REGEXP_INVALID_TOKEN, $method)) { throw new HTTP_Request2_LogicException( "Invalid request method '{$method}'", HTTP_Request2_Exception::INVALID_ARGUMENT ); } $this->method = $method; return $this; }
php
{ "resource": "" }
q267230
HTTP_Request2.setAuth
test
public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC) { if (empty($user)) { $this->auth = null; } else { $this->auth = array( 'user' => (string)$user, 'password' => (string)$password, 'scheme' => $scheme ); } return $this; }
php
{ "resource": "" }
q267231
HTTP_Request2.addCookie
test
public function addCookie($name, $value) { if (!empty($this->cookieJar)) { $this->cookieJar->store( array('name' => $name, 'value' => $value), $this->url ); } else { $cookie = $name . '=' . $value; if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) { throw new HTTP_Request2_LogicException( "Invalid cookie: '{$cookie}'", HTTP_Request2_Exception::INVALID_ARGUMENT ); } $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; '; $this->setHeader('cookie', $cookies . $cookie); } return $this; }
php
{ "resource": "" }
q267232
HTTP_Request2.setBody
test
public function setBody($body, $isFilename = false) { if (!$isFilename && !is_resource($body)) { if (!$body instanceof HTTP_Request2_MultipartBody) { $this->body = (string)$body; } else { $this->body = $body; } } else { $fileData = $this->fopenWrapper($body, empty($this->headers['content-type'])); $this->body = $fileData['fp']; if (empty($this->headers['content-type'])) { $this->setHeader('content-type', $fileData['type']); } } $this->postParams = $this->uploads = array(); return $this; }
php
{ "resource": "" }
q267233
HTTP_Request2.getBody
test
public function getBody() { if (self::METHOD_POST == $this->method && (!empty($this->postParams) || !empty($this->uploads)) ) { if (0 === strpos($this->headers['content-type'], 'application/x-www-form-urlencoded')) { $body = http_build_query($this->postParams, '', '&'); if (!$this->getConfig('use_brackets')) { $body = preg_replace('/%5B\d+%5D=/', '=', $body); } // support RFC 3986 by not encoding '~' symbol (request #15368) return str_replace('%7E', '~', $body); } elseif (0 === strpos($this->headers['content-type'], 'multipart/form-data')) { require_once 'HTTP/Request2/MultipartBody.php'; return new HTTP_Request2_MultipartBody( $this->postParams, $this->uploads, $this->getConfig('use_brackets') ); } } return $this->body; }
php
{ "resource": "" }
q267234
HTTP_Request2.addUpload
test
public function addUpload( $fieldName, $filename, $sendFilename = null, $contentType = null ) { if (!is_array($filename)) { $fileData = $this->fopenWrapper($filename, empty($contentType)); $this->uploads[$fieldName] = array( 'fp' => $fileData['fp'], 'filename' => !empty($sendFilename)? $sendFilename :(is_string($filename)? basename($filename): 'anonymous.blob') , 'size' => $fileData['size'], 'type' => empty($contentType)? $fileData['type']: $contentType ); } else { $fps = $names = $sizes = $types = array(); foreach ($filename as $f) { if (!is_array($f)) { $f = array($f); } $fileData = $this->fopenWrapper($f[0], empty($f[2])); $fps[] = $fileData['fp']; $names[] = !empty($f[1])? $f[1] :(is_string($f[0])? basename($f[0]): 'anonymous.blob'); $sizes[] = $fileData['size']; $types[] = empty($f[2])? $fileData['type']: $f[2]; } $this->uploads[$fieldName] = array( 'fp' => $fps, 'filename' => $names, 'size' => $sizes, 'type' => $types ); } if (empty($this->headers['content-type']) || 'application/x-www-form-urlencoded' == $this->headers['content-type'] ) { $this->setHeader('content-type', 'multipart/form-data'); } return $this; }
php
{ "resource": "" }
q267235
HTTP_Request2.attach
test
public function attach(SplObserver $observer) { foreach ($this->observers as $attached) { if ($attached === $observer) { return; } } $this->observers[] = $observer; }
php
{ "resource": "" }
q267236
HTTP_Request2.detach
test
public function detach(SplObserver $observer) { foreach ($this->observers as $key => $attached) { if ($attached === $observer) { unset($this->observers[$key]); return; } } }
php
{ "resource": "" }
q267237
HTTP_Request2.setLastEvent
test
public function setLastEvent($name, $data = null) { $this->lastEvent = array( 'name' => $name, 'data' => $data ); $this->notify(); }
php
{ "resource": "" }
q267238
HTTP_Request2.setAdapter
test
public function setAdapter($adapter) { if (is_string($adapter)) { if (!class_exists($adapter, false)) { if (false === strpos($adapter, '_')) { $adapter = 'HTTP_Request2_Adapter_' . ucfirst($adapter); } if (!class_exists($adapter, false) && preg_match('/^HTTP_Request2_Adapter_([a-zA-Z0-9]+)$/', $adapter) ) { include_once str_replace('_', DIRECTORY_SEPARATOR, $adapter) . '.php'; } if (!class_exists($adapter, false)) { throw new HTTP_Request2_LogicException( "Class {$adapter} not found", HTTP_Request2_Exception::MISSING_VALUE ); } } $adapter = new $adapter; } if (!$adapter instanceof HTTP_Request2_Adapter) { throw new HTTP_Request2_LogicException( 'Parameter is not a HTTP request adapter', HTTP_Request2_Exception::INVALID_ARGUMENT ); } $this->adapter = $adapter; return $this; }
php
{ "resource": "" }
q267239
HTTP_Request2.setCookieJar
test
public function setCookieJar($jar = true) { if (!class_exists('HTTP_Request2_CookieJar', false)) { require_once 'HTTP/Request2/CookieJar.php'; } if ($jar instanceof HTTP_Request2_CookieJar) { $this->cookieJar = $jar; } elseif (true === $jar) { $this->cookieJar = new HTTP_Request2_CookieJar(); } elseif (!$jar) { $this->cookieJar = null; } else { throw new HTTP_Request2_LogicException( 'Invalid parameter passed to setCookieJar()', HTTP_Request2_Exception::INVALID_ARGUMENT ); } return $this; }
php
{ "resource": "" }
q267240
HTTP_Request2.send
test
public function send() { // Sanity check for URL if (!$this->url instanceof Net_URL2 || !$this->url->isAbsolute() || !in_array(strtolower($this->url->getScheme()), array('https', 'http')) ) { throw new HTTP_Request2_LogicException( 'HTTP_Request2 needs an absolute HTTP(S) request URL, ' . ($this->url instanceof Net_URL2 ? "'" . $this->url->__toString() . "'" : 'none') . ' given', HTTP_Request2_Exception::INVALID_ARGUMENT ); } if (empty($this->adapter)) { $this->setAdapter($this->getConfig('adapter')); } // magic_quotes_runtime may break file uploads and chunked response // processing; see bug #4543. Don't use ini_get() here; see bug #16440. if ($magicQuotes = get_magic_quotes_runtime()) { set_magic_quotes_runtime(false); } // force using single byte encoding if mbstring extension overloads // strlen() and substr(); see bug #1781, bug #10605 if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) { $oldEncoding = mb_internal_encoding(); mb_internal_encoding('8bit'); } try { $response = $this->adapter->sendRequest($this); } catch (Exception $e) { } // cleanup in either case (poor man's "finally" clause) if ($magicQuotes) { set_magic_quotes_runtime(true); } if (!empty($oldEncoding)) { mb_internal_encoding($oldEncoding); } // rethrow the exception if (!empty($e)) { throw $e; } return $response; }
php
{ "resource": "" }
q267241
HTTP_Request2.detectMimeType
test
protected static function detectMimeType($filename) { // finfo extension from PECL available if (function_exists('finfo_open')) { if (!isset(self::$_fileinfoDb)) { self::$_fileinfoDb = @finfo_open(FILEINFO_MIME); } if (self::$_fileinfoDb) { $info = finfo_file(self::$_fileinfoDb, $filename); } } // (deprecated) mime_content_type function available if (empty($info) && function_exists('mime_content_type')) { return mime_content_type($filename); } return empty($info)? 'application/octet-stream': $info; }
php
{ "resource": "" }
q267242
SettingController.showAction
test
public function showAction(Setting $setting) { $editForm = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting, array( 'action' => $this->generateUrl('admin_amulen_setting_update', array('id' => $setting->getid())), 'method' => 'PUT', )); $deleteForm = $this->createDeleteForm($setting->getId(), 'admin_amulen_setting_delete'); return array( 'setting' => $setting, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q267243
SettingController.newAction
test
public function newAction() { $setting = new Setting(); $form = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting); return array( 'setting' => $setting, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q267244
SettingController.createAction
test
public function createAction(Request $request) { $setting = new Setting(); $form = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting); if ($form->handleRequest($request)->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($setting); $em->flush(); return $this->redirect($this->generateUrl('admin_amulen_setting_show', array('id' => $setting->getId()))); } return array( 'setting' => $setting, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q267245
SettingController.updateAction
test
public function updateAction(Setting $setting, Request $request) { $editForm = $this->createForm($this->get('amulen.dashboard.form.setting'), $setting, array( 'action' => $this->generateUrl('admin_amulen_setting_update', array('id' => $setting->getid())), 'method' => 'PUT', )); if ($editForm->handleRequest($request)->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirect($this->generateUrl('admin_amulen_setting_show', array('id' => $setting->getId()))); } $deleteForm = $this->createDeleteForm($setting->getId(), 'admin_amulen_setting_delete'); return array( 'setting' => $setting, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q267246
Query.where
test
public function where($expression, $value = null) { // shortcut : id if(is_int($expression) and !$value) { $expression = ['id' => $expression]; } // force array elseif(!is_array($expression)) { $expression = [$expression => $value]; } // parse each expression foreach($expression as $condition => $input) { // parse condition if(!preg_match('/^(?P<field>[a-zA-Z_0-9]+)( (?P<operator>.+))?$/', $condition, $extract)) { throw new \PDOException('Invalid expression "' . $condition . '"'); } // clean condition $field = trim($extract['field']); $operator = isset($extract['operator']) ? strtolower(trim($extract['operator'], ' ?')) : null; // implicit '=' or 'in' if(!$operator) { $operator = is_array($input) ? reset($this->complexOperators) : reset($this->simpleOperators); } // simple operators if(in_array($operator, $this->simpleOperators)) { if(is_array($input)) { throw new \PDOException('Operator "' . $operator . '" needs only one input value, in "' . $condition . '"'); } $condition = '`' . $field . '` ' . $operator . ' ?'; } // complex operators elseif(in_array($operator, $this->complexOperators)) { if(!is_array($input) or empty($input)) { throw new \PDOException('Operator "' . $operator . '" needs multiple input values, in "' . $condition . '"'); } $placeholders = array_fill(0, count($input), '?'); $condition = '`' . $field . '` ' . $operator . ' (' . implode(', ', $placeholders) . ')'; } // tuple operators elseif(in_array($operator, $this->tupleOperators)) { if(!is_array($input) or count($input) != 2) { throw new \PDOException('Operator "' . $operator . '" needs exactly two input value, in "' . $condition . '"'); } $condition = '`' . $field . '` ' . $operator . ' ? and ?'; } // unknown operator else { throw new \PDOException('Invalid operator in "' . $condition . '"'); } $this->where[$condition] = $input; } return $this; }
php
{ "resource": "" }
q267247
Response.withStatus
test
public function withStatus($code, $reason_phrase = '') { if (!in_array($code, array_keys($this->status_codes))) { throw new InvalidArgumentException( 'HTTP Status Code is invalid' ); } $response = clone $this; $response->status_code = (int)$code; $response->reason_phrase = (string)$reason_phrase ?? $this->status_code[$code]; return $response; }
php
{ "resource": "" }
q267248
Remover.remove
test
public function remove($params = array()) { $this->adapter->execute($this->toSql(), array_merge($this->params(), $this->params(true), $params)); return true; }
php
{ "resource": "" }
q267249
Component.hasEventListeners
test
public function hasEventListeners($event) { return !empty($this->listeners[$event]) || !empty($this->onceListeners[$event]); }
php
{ "resource": "" }
q267250
Validation.field
test
protected function field($name, $default = null) { return array_key_exists($name, $this->data) ? $this->data[$name] : $default; }
php
{ "resource": "" }
q267251
Validation.msg
test
protected function msg($msg, array $params = []) { return array_key_exists($msg, $this->messages) ? vsprintf($this->messages[$msg], $params) : null; }
php
{ "resource": "" }
q267252
ResourceController.createAccessDeniedHttpException
test
public function createAccessDeniedHttpException($message = 'Permission Denied!', \Exception $previous = null) { return new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException($message, $previous); }
php
{ "resource": "" }
q267253
ResourceController.setFlash
test
protected function setFlash($type,$message,$parameters = array(),$domain = 'flashes') { return $this->get('session')->getBag('flashes')->add($type,$this->trans($message, $parameters, $domain)); }
php
{ "resource": "" }
q267254
MySql.commitTransaction
test
function commitTransaction(){ $this->log("COMMIT SAVE_POINT_".$this->transactionCount); $this->transactionCount--; if($this->transactionCount == 0){ parent::commit(); $this->log("COMMIT REAL"); } return $this->transactionCount; }
php
{ "resource": "" }
q267255
MySql.formatDate
test
function formatDate($dateStr=null,$includeTime=null){ if($dateStr === null){ $date = time(); }else if(is_string($dateStr)){ $date = strtotime($dateStr); }else if(is_integer($dateStr)){ $date = $dateStr; }else{ throw new InvalidInputException('1st parameter should be either a string or integer or null'); } $format = "Y-m-d"; if(isset($includeTime)){ $format .= " H:i:s"; } $mysqlDate = date($format,$date); return $mysqlDate; }
php
{ "resource": "" }
q267256
MySql.formatTime
test
function formatTime($hh=0,$mm=0,$ss=0,$ampm="AM"){ $ampm = strtoupper($ampm); $hhUpperBound = 12; if($ampm == "PM"){ $hhUpperBound--; } if(!( (0 <= $hh && $hh <= $hhUpperBound) && (0 <= $mm && $mm <= 60) && (0 <= $ss && $ss <= 60) ) ){ throw new InvalidInputException('invalid parameters'); } if($ampm == "PM"){ if($hh != 12){ $hh = $hh+12; } }else if($ampm == "AM"){ if($hh == 12){ $hh = 0; } }else{ throw new InvalidInputException('last parameter should be either a AM or PM in string'); } if($hh < 10){ $hh = "0".$hh; } if($mm < 10){ $mm = "0".$mm; } if($ss < 10){ $ss = "0".$ss; } $mysqlTime = $hh.":".$mm.":".$ss; return $mysqlTime; }
php
{ "resource": "" }
q267257
MySql.formatBoolean
test
function formatBoolean($value){ if(is_string($value)){ if(strtoupper($value) == "TRUE"){ $value = '1'; }else if(strtoupper($value) == "FALSE"){ $value = '0'; }else{ throw new InvalidInputException("Not a boolean value"); } }elseif ($value == true){ $value = '1'; }elseif ($value == false){ $value = '0'; }else{ throw new InvalidInputException("Not a boolean value"); } return $value; }
php
{ "resource": "" }
q267258
MySql.setTimeZone
test
function setTimeZone($timeZone){ if($this->currentTimeZone == $timeZone){ // $timeZone is set already return; } $this->currentTimeZone = $timeZone; //convert php timezone into mysql timezone format $dtz = new \DateTimeZone($timeZone); $timeInTimeZone = new \DateTime('now', $dtz); $sign = "+"; $offset = $dtz->getOffset( $timeInTimeZone ) / 3600; if($offset < 0){ $sign = "-"; $offset = -1 * $offset; } $hourPart = intval($offset); $minutePart = $offset-$hourPart; $minutePart = $minutePart * 60; $timeZoneForMySql = $sign.$hourPart.":".$minutePart; // set the timezone in mysql $this->query("SET time_zone='$timeZoneForMySql'"); }
php
{ "resource": "" }
q267259
Container.get
test
public function get($className, array $parameters = []) { if ($this->injectSelf($className)) { return $this; } $parameterKey = $this->getParameterStoreKey($parameters); $className = $this->resolve($className); if (!isset($this->services[$className][$parameterKey])) { $this->services[$className][$parameterKey] = $this->create($className, $parameters); } return $this->services[$className][$parameterKey]; }
php
{ "resource": "" }
q267260
Container.has
test
public function has($className, array $parameters = []) { if ($this->injectSelf($className)) { return true; } $parameterKey = $this->getParameterStoreKey($parameters); $className = $this->resolve($className); return isset($this->services[$className][$parameterKey]); }
php
{ "resource": "" }
q267261
Container.create
test
public function create($className, array $parameters = []) { if ($this->injectSelf($className)) { return $this; } $className = $this->resolve($className); $classMeta = $this->reflectionService->getClassMetaReflection($className); if ($classMeta->isInterface()) { throw new RuntimeException('Tried to create an interface ( ' . $className . ' ) without registered implementation.'); } $object = $this->createObject($className, $parameters, $classMeta); return $object; }
php
{ "resource": "" }
q267262
Container.addResolver
test
public function addResolver(ResolverInterface $resolver, $priority = 0) { if (!isset($this->prioritizedResolvers[$priority])) { $this->prioritizedResolvers[$priority] = []; } array_push($this->prioritizedResolvers[$priority], $resolver); krsort($this->prioritizedResolvers); }
php
{ "resource": "" }
q267263
Container.add
test
public function add($object) { $className = '\\' . get_class($object); if ($this->injectSelf($className)) { throw new InvalidArgumentException('Tried to add a container instance'); } $parameterKey = $this->getParameterStoreKey([]); if (isset($this->services[$className][$parameterKey])) { throw new InvalidArgumentException('Tried to add a service instance which already exists'); } $this->services[$className][$parameterKey] = $object; }
php
{ "resource": "" }
q267264
PgClient.getPool
test
public function getPool() { if (!isset($this->_pool)) { $poolConfig = [ 'loop' => $this->loop, 'clientConfig' => [ ['class' => pgConnection::class], [ $this->connectionParams, $this->loop, $this->connector ] ] ]; $poolConfig = ArrayHelper::merge($this->poolConfigDefault, $this->poolConfig, $poolConfig); $this->_pool = new Pool($poolConfig); } return $this->_pool; }
php
{ "resource": "" }
q267265
PgClient.query
test
public function query($s) { return Observable::defer(function() use ($s) { $conn = $this->getLeastBusyConnection(); return $conn->query($s); }); }
php
{ "resource": "" }
q267266
PgClient.executeStatement
test
public function executeStatement(string $queryString, array $parameters = []) { return Observable::defer(function() use ($queryString, $parameters) { $conn = $this->getLeastBusyConnection(); return $conn->executeStatement($queryString, $parameters); }); }
php
{ "resource": "" }
q267267
PgClient.createNewConnection
test
private function createNewConnection($addToPool = true, $params = []) { // no idle connections were found - spin up new one $params = ArrayHelper::merge($this->connectionParams, $params); $connection = new pgConnection($params, $this->loop, $this->connector); if (!$addToPool || $this->autoDisconnect) { return $connection; } $this->connections[] = $connection; $connection->on('close', function() use ($connection) { $this->connections = array_filter($this->connections, function($c) use ($connection) { return $connection !== $c; }); $this->connections = array_values($this->connections); }); return $connection; }
php
{ "resource": "" }
q267268
PgClient.getLeastBusyConnectionOld
test
private function getLeastBusyConnectionOld() : pgConnection { if (count($this->connections) === 0) { // try to spin up another connection to return $conn = $this->createNewConnection(); if ($conn === null) { throw new Exception('There are no connections. Cannot find least busy one and could not create a new one.'); } return $conn; } $min = reset($this->connections); foreach ($this->connections as $connection) { // if this connection is idle - just return it if ($connection->getBacklogLength() === 0 && $connection->getState() === pgConnection::STATE_READY) { return $connection; } if ($min->getBacklogLength() > $connection->getBacklogLength()) { $min = $connection; } } if (count($this->connections) < $this->maxConnections) { return $this->createNewConnection(); } return $min; }
php
{ "resource": "" }
q267269
ScriptHandler.assetsInstall
test
public static function assetsInstall(Event $event) { $options = self::getOptions($event); $consoleDir = self::getConsoleDir($event, 'install assets'); if (null === $consoleDir) { return; } $webDir = $options['web-dir']; $symlink = ''; if ($options['assets-install'] == 'symlink') { $symlink = '--symlink '; } elseif ($options['assets-install'] == 'relative') { $symlink = '--symlink --relative '; } if (!self::hasDirectory( $event, 'web-dir', $webDir, 'install assets' )) { return; } static::executeCommand( $event, $consoleDir, 'assets:install '. $symlink.escapeshellarg($webDir) ); }
php
{ "resource": "" }
q267270
VersionReader.getReflectionClass
test
public function getReflectionClass($className) { if (isset($this->classReflections[$className])) { return $this->classReflections[$className]; } $class = new \ReflectionClass($className); $this->classReflections[$className] = $class; return $class; }
php
{ "resource": "" }
q267271
VersionReader.getClassVersion
test
public function getClassVersion($className) { if (isset($this->classVersions[$className])) { return $this->classVersions[$className]; } $class = $this->getReflectionClass($className); $versionAnnotation = $this->reader->getClassAnnotation( $class, 'Evispa\ObjectMigration\Annotations\Version' ); if (null === $versionAnnotation) { throw new Exception\NotVersionedException($className); } $version = $versionAnnotation->version; $this->classVersions[$className] = $version; return $version; }
php
{ "resource": "" }
q267272
VersionReader.findClassNameByVersion
test
private function findClassNameByVersion($startFromClassName, $version, &$visited = array()) { $versionAnnotation = $this->reader->getClassAnnotation( new \ReflectionClass($startFromClassName), 'Evispa\ObjectMigration\Annotations\Version' ); if ($versionAnnotation->version === $version) { return $startFromClassName; } $migrationAnnotations = $this->getClassMigrationMethodInfo($startFromClassName); /** @var MethodInfo $methodInfo */ foreach ($migrationAnnotations as $methodInfo) { if ($methodInfo->annotation->from && !in_array($methodInfo->annotation->from, $visited)) { $visited[] = $methodInfo->annotation->from; $className = $this->getClassNameByVersion($methodInfo->annotation->from, $version, $visited); if ($className) { return $className; } } if ($methodInfo->annotation->to && !in_array($methodInfo->annotation->to, $visited)) { $visited[] = $methodInfo->annotation->to; $className = $this->getClassNameByVersion($methodInfo->annotation->to, $version, $visited); if ($className) { return $className; } } } return null; }
php
{ "resource": "" }
q267273
VersionReader.getClassMigrationMethods
test
public function getClassMigrationMethods($className) { if (isset($this->classMigrationMethods[$className])) { return $this->classMigrationMethods[$className]; } $migrationAnnotations = $this->getClassMigrationMethodInfo($className); $migrationMethods = new MigrationMethods(); foreach ($migrationAnnotations as $migrationAnnotation) { $method = $migrationAnnotation->method; $migrationAnnotation = $migrationAnnotation->annotation; if (null !== $migrationAnnotation->from) { if (false === $method->isStatic() || 2 !== $method->getNumberOfParameters()) { throw new \LogicException( 'Method "' . $method->getName( ) . '" in "' . $className . '" should be static and require 2 parameters.' ); } if ($migrationAnnotation->from === $className) { throw new \LogicException( 'Method "' . $method->getName( ) . '" in "' . $className . '" should have a migration from a different class.' ); } $otherClass = $migrationAnnotation->from; $otherClassVersion = $this->getClassVersion($otherClass); $migrationMethods->from[$otherClassVersion] = new CreateAction($method); } elseif (null !== $migrationAnnotation->to) { if (true === $method->isStatic() || 1 !== $method->getNumberOfParameters()) { throw new \LogicException( 'Method "' . $method->getName( ) . '" in "' . $className . '" should not be static and require 1 parameter.' ); } if ($migrationAnnotation->to === $className) { throw new \LogicException( 'Method "' . $method->getName( ) . '" in "' . $className . '" should have a migration to a different class.' ); } $otherClass = $migrationAnnotation->to; $otherClassVersion = $this->getClassVersion($otherClass); $migrationMethods->to[$otherClassVersion] = new CloneAction($method); } } $this->classMigrationMethods[$className] = $migrationMethods; return $migrationMethods; }
php
{ "resource": "" }
q267274
VersionReader.getRequiredClassOptions
test
public function getRequiredClassOptions($className) { $requiredOptions = array(); $scanList = array($className => true); $scannedSourceNames = array(); while (true) { if (0 === count($scanList)) { break; } // find new class names foreach ($scanList as $scanName => $_) { $annotations = $this->getClassMigrationMethodInfo($scanName); foreach ($annotations as $annotationInfo) { if (null !== $annotationInfo->annotation->from) { $newClass = $annotationInfo->annotation->from; foreach ($annotationInfo->annotation->require as $requiredOption) { $requiredOptions[$requiredOption] = array('from' => $newClass, 'to' => $scanName); } } elseif (null !== $annotationInfo->annotation->to) { $newClass = $annotationInfo->annotation->to; foreach ($annotationInfo->annotation->require as $requiredOption) { $requiredOptions[$requiredOption] = array('from' => $scanName, 'to' => $newClass); } } if (!isset($scannedSourceNames[$newClass])) { $scanList[$newClass] = true; } } unset($scanList[$scanName]); if (!isset($scannedSourceNames[$scanName])) { $scannedSourceNames[$scanName] = true; } } } return $requiredOptions; }
php
{ "resource": "" }
q267275
JobController.showAction
test
public function showAction(Job $job) { $editForm = $this->createForm(new JobType(), $job, array( 'action' => $this->generateUrl('admin_amulen_job_update', array('id' => $job->getid())), 'method' => 'PUT', )); $deleteForm = $this->createDeleteForm($job->getId(), 'admin_amulen_job_delete'); return array( 'job' => $job, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q267276
JobController.newAction
test
public function newAction() { $job = new Job(); $form = $this->createForm(new JobType(), $job); return array( 'job' => $job, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q267277
JobController.createAction
test
public function createAction(Request $request) { $job = new Job(); $form = $this->createForm(new JobType(), $job); if ($form->handleRequest($request)->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($job); $em->flush(); return $this->redirect($this->generateUrl('admin_amulen_job_show', array('id' => $job->getId()))); } return array( 'job' => $job, 'form' => $form->createView(), ); }
php
{ "resource": "" }
q267278
JobController.updateAction
test
public function updateAction(Job $job, Request $request) { $editForm = $this->createForm(new JobType(), $job, array( 'action' => $this->generateUrl('admin_amulen_job_update', array('id' => $job->getid())), 'method' => 'PUT', )); if ($editForm->handleRequest($request)->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirect($this->generateUrl('admin_amulen_job_show', array('id' => $job->getId()))); } $deleteForm = $this->createDeleteForm($job->getId(), 'admin_amulen_job_delete'); return array( 'job' => $job, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), ); }
php
{ "resource": "" }
q267279
File.setClientFilename
test
public function setClientFilename($file_name) { if (is_string($file_name)) { $this->client_file_name = $file_name; $_ext = $this->guessExtension(); if (!empty($_ext) && !strstr($file_name, $_ext)) $this->client_file_name .= '.'.$_ext; } else { throw new InvalidArgumentException( sprintf('Client name of a file must be a string (got "%s")!', gettype($file_name)) ); } }
php
{ "resource": "" }
q267280
File.guessExtension
test
public function guessExtension() { $_ext = $this->getExtension(); if (empty($_ext) && $this->getRealPath()) { $finfo = new \finfo(); $mime = $finfo->file( $this->getRealPath(), FILEINFO_MIME_TYPE ); $_ext = str_replace('image/', '', $mime); } return $_ext; }
php
{ "resource": "" }
q267281
File.getMime
test
public function getMime() { if ($this->getRealPath()) { $finfo = new \finfo(); return $finfo->file( $this->getRealPath(), FILEINFO_MIME_TYPE ); } return null; }
php
{ "resource": "" }
q267282
File.getHumanSize
test
public function getHumanSize( $decimals=2 ) { $sz = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); $factor = floor((strlen($this->getSize()) - 1) / 3); if ($factor >= count($sz)) $factor = count($sz)-1; return sprintf("%.{$decimals}f", $this->getSize() / pow(1024, $factor)) . $sz[$factor]; }
php
{ "resource": "" }
q267283
File.getATimeAsDatetime
test
public function getATimeAsDatetime() { $_date = $this->getATime(); if (!empty($_date)) return \DateTime::createFromFormat( 'U', $_date ); return null; }
php
{ "resource": "" }
q267284
File.getCTimeAsDatetime
test
public function getCTimeAsDatetime() { $_date = $this->getCTime(); if (!empty($_date)) return \DateTime::createFromFormat( 'U', $_date ); return null; }
php
{ "resource": "" }
q267285
File.getMTimeAsDatetime
test
public function getMTimeAsDatetime() { $_date = $this->getMTime(); if (!empty($_date)) return \DateTime::createFromFormat( 'U', $_date ); return null; }
php
{ "resource": "" }
q267286
File.createFromContent
test
public static function createFromContent( $file_content, $filename=null, $client_file_name=null ) { $finfo = new \finfo(); $mime = $finfo->buffer( $file_content, FILEINFO_MIME_TYPE ); $extension = end(explode('/', $mime)); if (is_null($filename)) { $_tmp_filename = md5( $file_content ).'.'.$extension; $filename = CarteBlanche::getFullPath('web_tmp_dir').$_tmp_filename; if (file_exists($filename)) { return new File( $filename, $client_file_name ); } } elseif (end(explode('.', $filename))!=$extension) { $filename .= '.'.$extension; } $_tf = fopen($filename, 'a+'); if ($_tf) { fwrite($_tf, $file_content); fclose($_tf); return new File( $filename, $client_file_name ); } return null; }
php
{ "resource": "" }
q267287
ApplicationRepository.findAll
test
public function findAll() { $applications = array(); foreach ($this->getRows() as $row) { $application = $this->createNew(); $application->setId($row['id']); $application->setName($row['name']); $application->setUrl($row['url']); $applications[] = $application; } return $applications; }
php
{ "resource": "" }
q267288
ApplicationRepository.find
test
public function find($id) { foreach ($this->findAll() as $application) { if ($id == $application->getId()) { return $application; } } return null; }
php
{ "resource": "" }
q267289
ApplicationRepository.create
test
public function create(Application $application) { $rows = $this->getRows(); $id = sizeof($rows) + 1; $rows[] = array( 'id' => $id, 'name' => $application->getName(), 'url' => $application->getUrl() ); file_put_contents($this->filename, Yaml::dump($rows)); }
php
{ "resource": "" }
q267290
ApplicationRepository.delete
test
public function delete(Application $application) { $rows = array(); foreach ($this->getRows() as $row) { if ($row['id'] == $application->getId()) { continue; } $rows[] = $row; } file_put_contents($this->filename, Yaml::dump($rows)); }
php
{ "resource": "" }
q267291
ApplicationRepository.update
test
public function update(Application $application) { $rows = array(); foreach ($this->getRows() as $row) { if ($row['id'] == $application->getId()) { $row = array( 'id' => $application->getId(), 'name' => $application->getName(), 'url' => $application->getUrl() ); } $rows[] = $row; } file_put_contents($this->filename, Yaml::dump($rows)); }
php
{ "resource": "" }
q267292
BusinessHours.getClosestDateIntervalBefore
test
private function getClosestDateIntervalBefore(\DateTime $date): DateTimeInterval { $tmpDate = clone $date; $dayOfWeek = (int)$tmpDate->format('N'); $time = TimeBuilder::fromDate($tmpDate); if (null !== $day = $this->getDay($dayOfWeek)) { if (null !== $closestTime = $day->getClosestPreviousOpeningHoursInterval($time)) { return $this->buildDateTimeInterval($tmpDate, $closestTime); } } $tmpDate = $this->getDateBefore($tmpDate); $closestDay = $this->getClosestDayBefore((int)$tmpDate->format('N')); $closingTime = $closestDay->getClosingTime(); $closestTime = $closestDay->getClosestPreviousOpeningHoursInterval($closingTime); return $this->buildDateTimeInterval($tmpDate, $closestTime); }
php
{ "resource": "" }
q267293
BusinessHours.getClosestDateIntervalAfter
test
private function getClosestDateIntervalAfter(\DateTime $date): DateTimeInterval { $tmpDate = clone $date; $dayOfWeek = (int)$tmpDate->format('N'); $time = TimeBuilder::fromDate($tmpDate); if (null !== $day = $this->getDay($dayOfWeek)) { if (null !== $closestTime = $day->getClosestNextOpeningHoursInterval($time)) { return $this->buildDateTimeInterval($tmpDate, $closestTime); } } $tmpDate = $this->getDateAfter($tmpDate); $closestDay = $this->getClosestDayBefore((int)$tmpDate->format('N')); $openingTime = $closestDay->getOpeningTime(); $closestTime = $closestDay->getClosestNextOpeningHoursInterval($openingTime); return $this->buildDateTimeInterval($tmpDate, $closestTime); }
php
{ "resource": "" }
q267294
BusinessHours.buildDateTimeInterval
test
private function buildDateTimeInterval(\DateTime $date, TimeIntervalInterface $timeInterval): DateTimeInterval { $intervalStart = clone $date; $intervalEnd = clone $date; $intervalStart->setTime( $timeInterval->getStart()->getHours(), $timeInterval->getStart()->getMinutes(), $timeInterval->getStart()->getSeconds() ); $intervalEnd->setTime( $timeInterval->getEnd()->getHours(), $timeInterval->getEnd()->getMinutes(), $timeInterval->getEnd()->getSeconds() ); return new DateTimeInterval($intervalStart, $intervalEnd); }
php
{ "resource": "" }
q267295
BusinessHours.getDayBefore
test
private function getDayBefore(int $dayNumber) { $tmpDayNumber = $dayNumber; for ($i = 0; $i < 6; $i++) { $tmpDayNumber = (DayInterface::WEEK_DAY_MONDAY === $tmpDayNumber) ? DayInterface::WEEK_DAY_SUNDAY : --$tmpDayNumber; if (null !== $day = $this->getDay($tmpDayNumber)) { return $day; } } return $this->getDay($dayNumber); }
php
{ "resource": "" }
q267296
BusinessHours.getDayAfter
test
private function getDayAfter($dayNumber) { $tmpDayNumber = $dayNumber; for ($i = 0; $i < 6; $i++) { $tmpDayNumber = (DayInterface::WEEK_DAY_SUNDAY === $tmpDayNumber) ? DayInterface::WEEK_DAY_MONDAY : ++$tmpDayNumber; if (null !== $day = $this->getDay($tmpDayNumber)) { return $day; } } return $this->getDay($dayNumber); }
php
{ "resource": "" }
q267297
PEAR_Installer_Role_Common.getInfo
test
function getInfo($role) { if (empty($GLOBALS['_PEAR_INSTALLER_ROLES'][$role])) { return PEAR::raiseError('Unknown Role class: "' . $role . '"'); } return $GLOBALS['_PEAR_INSTALLER_ROLES'][$role]; }
php
{ "resource": "" }
q267298
Transaction.commit
test
public function commit() { if (!$this->getIsActive()) { throw new Exception('Failed to commit transaction: transaction was inactive.'); } $connection = $this->getConnection(); $this->_level--; if ($this->_level === 0) { Reaction::debug('Commit transaction'); return $connection->commitTransaction() ->thenLazy(function() { $this->closeConnection(); }); } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { Reaction::debug('Release savepoint ' . $this->_level); return $connection->releaseSavepoint('LEVEL' . $this->_level); } else { Reaction::info('Transaction not committed: nested transaction not supported'); } return Reaction\Promise\rejectLazy(null); }
php
{ "resource": "" }
q267299
Transaction.rollBack
test
public function rollBack($final = false) { if (!$this->getIsActive()) { // do nothing if transaction is not active: this could be the transaction is committed // but the event handler to "commitTransaction" throw an exception return Reaction\Promise\reject(new Exception("There is no active transactions")); } //Roll back all transaction with save points if ($final && $this->_level > 1) { $promises = []; while ($this->_level > 0) { $promises[] = $this->rollBack(false); } return !empty($promises) ? Reaction\Promise\allInOrder($promises)->then(function() { return true; }) : Reaction\Promise\resolve(true); } $connection = $this->getConnection(); $this->_level--; if ($this->_level === 0) { Reaction::debug('Roll back transaction'); return $connection->rollBackTransaction() ->thenLazy(function() { $this->closeConnection(); }); } $schema = $this->db->getSchema(); if ($schema->supportsSavepoint()) { Reaction::debug('Roll back to savepoint ' . $this->_level); return $connection->rollBackSavepoint('LEVEL' . $this->_level); } else { Reaction::info('Transaction not rolled back: nested transaction not supported'); // throw an exception to fail the outer transaction return Reaction\Promise\reject(new Exception('Roll back failed: nested transaction not supported.')); } }
php
{ "resource": "" }