_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q267300 | Transaction.setIsolationLevel | test | public function setIsolationLevel($level)
{
if (!$this->getIsActive()) {
throw new Exception('Failed to set isolation level: transaction was inactive.');
}
Reaction::debug('Setting transaction isolation level to ' . $level);
return $this->getConnection()->setTransactionIsolationLevel($level);
} | php | {
"resource": ""
} |
q267301 | Transaction.getConnection | test | public function getConnection() {
if (!isset($this->connection)) {
$this->connection = $this->db->getDedicatedConnection();
}
return $this->connection;
} | php | {
"resource": ""
} |
q267302 | ImageConverter.setBackend | test | public function setBackend($backend)
{
if (!is_string($backend)) {
throw new Exception\InvalidArgumentException(__METHOD__ . " backend parameter must be a valid string.");
}
if (!in_array($backend, $this->supported_backends)) {
$valid_backends = implode(',', $this->supported_backends);
throw new Exception\UnsupportedBackendException(__METHOD__ . " Backend '$backend' is not supported, supported backends are '$valid_backends'''");
}
$this->backend = $backend;
return $this;
} | php | {
"resource": ""
} |
q267303 | MonologLogger.debug | test | public function debug(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::DEBUG}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267304 | MonologLogger.info | test | public function info(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::INFO}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267305 | MonologLogger.notice | test | public function notice(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::NOTICE}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267306 | MonologLogger.warning | test | public function warning(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::WARNING}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267307 | MonologLogger.error | test | public function error(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::ERROR}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267308 | MonologLogger.critical | test | public function critical(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::CRITICAL}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267309 | MonologLogger.alert | test | public function alert(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::ALERT}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267310 | MonologLogger.emergency | test | public function emergency(string $message, array $context = []): Logger
{
$this->logger->{LogLevel::EMERGENCY}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267311 | MonologLogger.log | test | public function log(LogLevel $level, string $message, array $context = []): Logger
{
$this->logger->{$level->getValue()}($message, $context);
return $this;
} | php | {
"resource": ""
} |
q267312 | UtilsExtension.getProperty | test | public function getProperty($object, $propertyPath, $required = true)
{
if (!$required) {
try {
return $this->accessor->getValue($object, $propertyPath);
} catch(NoSuchIndexException $e) {
return null;
}
}
return $this->accessor->getValue($object, $propertyPath);
} | php | {
"resource": ""
} |
q267313 | UtilsExtension.truncateHtml | test | public function truncateHtml($html, $limit, $endChar = '…')
{
$output = new TruncateHtml($html);
return $output->cut($limit, $endChar);
} | php | {
"resource": ""
} |
q267314 | PEAR_Installer.PEAR_Installer | test | function PEAR_Installer(&$ui)
{
parent::PEAR_Common();
$this->setFrontendObject($ui);
$this->debug = $this->config->get('verbose');
} | php | {
"resource": ""
} |
q267315 | PEAR_Installer._deletePackageFiles | test | function _deletePackageFiles($package, $channel = false, $backup = false)
{
if (!$channel) {
$channel = 'pear.php.net';
}
if (!strlen($package)) {
return $this->raiseError("No package to uninstall given");
}
if (strtolower($package) == 'pear' && $channel == 'pear.php.net') {
// to avoid race conditions, include all possible needed files
require_once 'PEAR/Task/Common.php';
require_once 'PEAR/Task/Replace.php';
require_once 'PEAR/Task/Unixeol.php';
require_once 'PEAR/Task/Windowseol.php';
require_once 'PEAR/PackageFile/v1.php';
require_once 'PEAR/PackageFile/v2.php';
require_once 'PEAR/PackageFile/Generator/v1.php';
require_once 'PEAR/PackageFile/Generator/v2.php';
}
$filelist = $this->_registry->packageInfo($package, 'filelist', $channel);
if ($filelist == null) {
return $this->raiseError("$channel/$package not installed");
}
$ret = array();
foreach ($filelist as $file => $props) {
if (empty($props['installed_as'])) {
continue;
}
$path = $props['installed_as'];
if ($backup) {
$this->addFileOperation('backup', array($path));
$ret[] = $path;
}
$this->addFileOperation('delete', array($path));
}
if ($backup) {
return $ret;
}
return true;
} | php | {
"resource": ""
} |
q267316 | PEAR_Installer.addFileOperation | test | function addFileOperation($type, $data)
{
if (!is_array($data)) {
return $this->raiseError('Internal Error: $data in addFileOperation'
. ' must be an array, was ' . gettype($data));
}
if ($type == 'chmod') {
$octmode = decoct($data[0]);
$this->log(3, "adding to transaction: $type $octmode $data[1]");
} else {
$this->log(3, "adding to transaction: $type " . implode(" ", $data));
}
$this->file_operations[] = array($type, $data);
} | php | {
"resource": ""
} |
q267317 | PEAR_Installer.download | test | function download($packages, $options, &$config, &$installpackages,
&$errors, $installed = false, $willinstall = false, $state = false)
{
// trickiness: initialize here
parent::PEAR_Downloader($this->ui, $options, $config);
$ret = parent::download($packages);
$errors = $this->getErrorMsgs();
$installpackages = $this->getDownloadedPackages();
trigger_error("PEAR Warning: PEAR_Installer::download() is deprecated " .
"in favor of PEAR_Downloader class", E_USER_WARNING);
return $ret;
} | php | {
"resource": ""
} |
q267318 | PEAR_Installer.setDownloadedPackages | test | function setDownloadedPackages(&$pkgs)
{
PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
$err = $this->analyzeDependencies($pkgs);
PEAR::popErrorHandling();
if (PEAR::isError($err)) {
return $err;
}
$this->_downloadedPackages = &$pkgs;
} | php | {
"resource": ""
} |
q267319 | Triangle.isValidPoint | test | public function isValidPoint(PointInterface $a)
{
return (bool) (
$this->getSegmentAB()->isValidPoint($a) ||
$this->getSegmentBC()->isValidPoint($a) ||
$this->getSegmentCA()->isValidPoint($a)
);
} | php | {
"resource": ""
} |
q267320 | CreateIteratingExceptionCapableTrait._createIteratingException | test | protected function _createIteratingException($message = null, $code = null, RootException $previous = null)
{
return new IteratingException($message, $code, $previous);
} | php | {
"resource": ""
} |
q267321 | OrdercloudBuilder.registerComponents | test | public function registerComponents(Container $container)
{
$this->bindClient($container);
$this->bindCommandBus($container);
$container->singleton('Ordercloud\Support\ExceptionGenerators\ExceptionGeneratorService', function () use ($container)
{
return new ChainedExceptionGeneratorService($container, [
'Ordercloud\Requests\Orders\Exceptions\OrderExceptionGenerator',
'Ordercloud\Requests\Payments\Exceptions\PaymentExceptionGenerator',
'Ordercloud\Requests\Exceptions\RequestExceptionGenerator', // Always chain default handler last
]);
});
$container->singleton('Ordercloud\Support\Parser');
$container->singleton('Ordercloud\Services\UserService');
$container->singleton('Ordercloud\Services\OrganisationService');
$container->singleton('Ordercloud\Ordercloud', function () use ($container)
{
return new Ordercloud($container);
});
} | php | {
"resource": ""
} |
q267322 | AttributeTrait.addArrayAttributes | test | private function addArrayAttributes($attribute, array $values)
{
array_map(function ($value) use ($attribute) {
$this->attributes->put($attribute, $value);
}, $values);
return $this;
} | php | {
"resource": ""
} |
q267323 | AttributeTrait.changeClasses | test | private function changeClasses($method, $class)
{
array_map(function ($class) use ($method) {
if ($method === 'add') {
return $this->classes->put($class, $class);
}
return $this->classes->remove($class);
}, explode(' ', $class));
return $this;
} | php | {
"resource": ""
} |
q267324 | AttributeTrait.parseClasses | test | private function parseClasses()
{
if ($this->classes->count() > 0) {
$this->attributes->put('class', implode(' ', $this->classes->all()));
}
return $this;
} | php | {
"resource": ""
} |
q267325 | SchemaBuilderTrait.json | test | public function json()
{
/*
* TODO Remove in Yii 2.1
*
* Disabled due to bug in MySQL extension
* @link https://bugs.php.net/bug.php?id=70384
*/
if (version_compare(PHP_VERSION, '5.6', '<') && $this->getDb()->getDriverName() === 'mysql') {
throw new \Reaction\Exceptions\Exception('JSON column type is not supported in PHP < 5.6');
}
return $this->getDb()->getSchema()->createColumnSchemaBuilder(Schema::TYPE_JSON);
} | php | {
"resource": ""
} |
q267326 | Container.bindIf | test | public function bindIf( $abstract, $concrete = NULL, $shared = FALSE )
{
if ( !$this->bound( $abstract ) )
{
$this->bind( $abstract, $concrete, $shared );
}
return $this;
} | php | {
"resource": ""
} |
q267327 | Container.bindShared | test | public function bindShared( $abstract, Closure $closure )
{
$this->bind( $abstract, $this->share( $closure ), TRUE );
return $this;
} | php | {
"resource": ""
} |
q267328 | Container.rebinding | test | public function rebinding( $abstract, Closure $callback )
{
$this->reboundCallbacks[ $abstract ][ ] = $callback;
if ( $this->bound( $abstract ) )
{
return $this->make( $abstract );
}
return $this;
} | php | {
"resource": ""
} |
q267329 | Container.isShared | test | public function isShared( $abstract )
{
if ( isset( $this->bindings[ $abstract ][ 'shared' ] ) )
{
$shared = $this->bindings[ $abstract ][ 'shared' ];
}
else
{
$shared = FALSE;
}
return isset( $this->instances[ $abstract ] ) || TRUE === $shared;
} | php | {
"resource": ""
} |
q267330 | Container.getClosure | test | protected function getClosure( $abstract, $concrete )
{
return function ( $c, $parameters = [ ] ) use ( $abstract, $concrete )
{
$method = ( $abstract == $concrete ) ? 'build' : 'make';
return $c->$method( $concrete, $parameters );
};
} | php | {
"resource": ""
} |
q267331 | Container.addDependencyForCallParameter | test | protected function addDependencyForCallParameter( ReflectionParameter $parameter, array &$parameters, array &$dependencies )
{
if ( array_key_exists( $parameter->name, $parameters ) )
{
$dependencies[ ] = $parameters[ $parameter->name ];
}
elseif ( $parameter->getClass() )
{
$dependencies[ ] = $this->make( $parameter->getClass()->name );
}
elseif ( $parameter->isDefaultValueAvailable() )
{
$dependencies[ ] = $parameter->getDefaultValue();
}
} | php | {
"resource": ""
} |
q267332 | Container.getContextualConcrete | test | public function getContextualConcrete( $abstract )
{
if ( isset( $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ] ) )
{
return $this->contextual[ Util::last( $this->buildStack ) ][ $abstract ];
}
return NULL;
} | php | {
"resource": ""
} |
q267333 | MiddlewareAwareTrait.requestMiddleware | test | public function requestMiddleware(Request $request, array $middleware = null)
{
// Set the middleware to any middleware passed or the base middleware
$middleware = $middleware ?? self::$middleware;
$modifiedRequest = $request;
// Get the application
$app = $this->getApplication();
// Iterate through the middleware
foreach ($middleware as $item) {
// If the middleware is a group
if ($this->isMiddlewareGroup($item)) {
// Recurse into that middleware group
$this->requestMiddleware(
$request,
$this->getMiddlewareGroup($item)
);
continue;
}
/* @var \Valkyrja\Http\Middleware\Middleware $item */
$modifiedRequest = $item::before($request);
if ($modifiedRequest instanceof Response) {
return $modifiedRequest;
}
// Set the returned request in the container
$app->container()->singleton(Request::class, $modifiedRequest);
}
return $modifiedRequest;
} | php | {
"resource": ""
} |
q267334 | MiddlewareAwareTrait.responseMiddleware | test | public function responseMiddleware(Request $request, Response $response, array $middleware = null)
{
// Set the middleware to any middleware passed or the base middleware
$middleware = $middleware ?? self::$middleware;
// Get the application
$app = $this->getApplication();
// Iterate through the middleware
foreach ($middleware as $item) {
// If the middleware is a group
if ($this->isMiddlewareGroup($item)) {
// Recurse into that middleware group
$this->responseMiddleware(
$request,
$response,
$this->getMiddlewareGroup($item)
);
continue;
}
/* @var \Valkyrja\Http\Middleware\Middleware $item */
$response = $item::after($request, $response);
// Set the returned response in the container
$app->container()->singleton(Response::class, $response);
}
return $response;
} | php | {
"resource": ""
} |
q267335 | MiddlewareAwareTrait.terminableMiddleware | test | public function terminableMiddleware(Request $request, Response $response, array $middleware = null): void
{
// Set the middleware to any middleware passed or the base middleware
$middleware = $middleware ?? self::$middleware;
// Iterate through the middleware
foreach ($middleware as $item) {
// If the middleware is a group
if ($this->isMiddlewareGroup($item)) {
// Recurse into that middleware group
$this->terminableMiddleware(
$request,
$response,
$this->getMiddlewareGroup($item)
);
continue;
}
/* @var \Valkyrja\Http\Middleware\Middleware $item */
$item::terminate($request, $response);
}
} | php | {
"resource": ""
} |
q267336 | WSDLCtrl.index | test | public function index() {
$rep = $this->getResponse('html', true);
$webservices = jWSDL::getSoapControllers();
if(sizeof($webservices) != 0){
$service = $this->param('service');
if (empty($service)) {
$module = $webservices[0]['module'];
$controller = $webservices[0]['class'];
}else{
if(!strpos($service, '~')===FALSE){
list($module, $controller) = explode('~',$service);
}
if (empty($module) || empty($controller)) {
throw new JException("jsoap~errors.service.param.invalid");
}
}
//Used for documentation of data structures classes
$className = $this->param('className');
$wsdl = new jWSDL($module, $controller);
$doc = $wsdl->doc($className);
$doc['menu'] = $webservices;
$rep->body->assign("doc", $doc);
$rep->title = "Documentation - ".$controller;
}else{
$rep->title = "Documentation - Web services";
}
$rep->bodyTpl = 'jsoap~soap_doc';
return $rep;
} | php | {
"resource": ""
} |
q267337 | WSDLCtrl.wsdl | test | public function wsdl() {
$rep = $this->getResponse('xml');
$rep->sendXMLHeader = FALSE;
$service = $this->param('service');
if (empty($service)) {
throw new jException("jsoap~errors.service.param.required");
}
if(!strpos($service, '~')===FALSE){
list($module, $controller) = explode('~',$service);
}
if (empty($module) || empty($controller)) {
throw new jException("jsoap~errors.service.param.invalid");
}
$wsdl = new jWSDL($module, $controller);
$rep->content = $wsdl->getWSDLFile();
return $rep;
} | php | {
"resource": ""
} |
q267338 | MinifySetup.initOptions | test | static function initOptions() {
global $min_allowDebugFlag;
global $min_errorLogger;
global $min_enableBuilder;
global $min_cachePath;
global $min_documentRoot;
global $min_cacheFileLocking;
global $min_symlinks;
global $min_serveOptions;
global $min_uploaderHoursBehind;
global $min_customConfigPaths;
if (!isset($min_allowDebugFlag))
$min_allowDebugFlag = false;
if (!isset($min_errorLogger)) {
$min_errorLogger = false;
}
$min_enableBuilder = false;
$min_cachePath = \jApp::tempPath('minify/');
if (!file_exists($min_cachePath)) {
mkdir($min_cachePath, 0775);
}
if (!isset($min_documentRoot)) {
$min_documentRoot = self::getDocumentRoot();
}
if (!isset($min_cacheFileLocking)) {
$min_cacheFileLocking = true;
}
if (!isset($min_serveOptions['bubbleCssImports'])) {
$min_serveOptions['bubbleCssImports'] = false;
}
if (!isset($min_serveOptions['maxAge'])) {
$min_serveOptions['maxAge'] = 1800;
}
$min_serveOptions['minApp']['groupsOnly'] = false;
if (!isset($min_serveOptions['minApp']['maxFiles'])) {
$min_serveOptions['minApp']['maxFiles'] = 10;
}
if (!isset($min_symlinks)) {
$min_symlinks = array();
}
if (!isset($min_uploaderHoursBehind)) {
$min_uploaderHoursBehind = 0;
}
if (!isset($min_customConfigPaths)) {
$min_customConfigPaths = array(
'groups' => \jApp::configPath('minifyGroupsConfig.php')
);
}
ini_set('zlib.output_compression', '0');
} | php | {
"resource": ""
} |
q267339 | Time.toTimestamp | test | public function toTimestamp(string $date, string $time = ''): int
{
if (empty($time)) {
$time = '00:00:01';
}
// create unix_timestamp
return strtotime($date . ' ' . $time);
} | php | {
"resource": ""
} |
q267340 | Time.fromTimestamp | test | public function fromTimestamp(int $timestamp, string $dateformat = 'Y-m-d', string $timeformat = 'H:i'): array
{
return [
'stamp' => $timestamp,
'date' => date($dateformat, $timestamp),
'time' => date($timeformat, $timestamp),
'week' => date('W', $timestamp),
'day' => date('d', $timestamp),
'month' => date('m', $timestamp),
'hour' => date('H', $timestamp),
'minute' => date('i', $timestamp)
];
} | php | {
"resource": ""
} |
q267341 | Time.dateConversion | test | public function dateConversion(string $date, string $format = 'Y-m-d'): string
{
return date($format, strtotime($date));
} | php | {
"resource": ""
} |
q267342 | Time.timeLeft | test | public function timeLeft(int $timestamp, bool $Left = true): string
{
$diff = $bLeft == true ? time() - $timestamp : $timestamp;
$showdiff = [
"y" => 0,
"m" => 0,
"w" => 0,
"d" => 0,
"h" => 0,
"min" => 0
];
while ($diff >= 31536000) {
// 1 year = 31536000 seconds
$diff -= 31536000;
$showdiff['y'] ++;
}
while ($diff >= 2419200) {
// 1 day = 2592000 seconds
$diff -= 2419200;
$showdiff['m'] ++;
}
while ($diff >= 648000) {
// 1 week = 604800 seconds
$diff -= 648000;
$showdiff['w'] ++;
}
while ($diff >= 86400) {
// 1 day = 86400 seconds
$diff -= 86400;
$showdiff['d'] ++;
}
while ($diff >= 3600) {
// 1 hour = 3600 seconds
$diff -= 3600;
$showdiff['h'] ++;
}
while ($diff >= 60) {
// 1 minute = 60 seconds
$diff -= 60;
$showdiff['min'] ++;
}
return $showdiff;
} | php | {
"resource": ""
} |
q267343 | Model.getProperties | test | public function getProperties()
{
$properties = get_object_vars($this);
foreach ($this->getAdditionalProperties() as $notImportantProperty) {
unset($properties[$notImportantProperty]);
}
return $properties;
} | php | {
"resource": ""
} |
q267344 | CallTimesPrediction.check | test | public function check(array $calls, FunctionProphecy $prophecy)
{
if ($this->times == count($calls)) {
return;
}
$methodCalls = $prophecy->getNamespace()->findCalls(
$prophecy->getName(),
new ArgumentsWildcard([new AnyValuesToken()])
);
if (count($calls)) {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s(%s)\n".
"but %d were made:\n%s",
$this->times,
$prophecy->getName(),
$prophecy->getArgumentsWildcard(),
count($calls),
$this->util->stringifyCalls($calls)
);
} elseif (count($methodCalls)) {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s(%s)\n".
"but none were made.\n".
"Recorded `%s(...)` calls:\n%s",
$this->times,
$prophecy->getName(),
$prophecy->getArgumentsWildcard(),
$prophecy->getName(),
$this->util->stringifyCalls($methodCalls)
);
} else {
$message = sprintf(
"Expected exactly %d calls that match:\n".
" %s(%s)\n".
'but none were made.',
$this->times,
$prophecy->getName(),
$prophecy->getArgumentsWildcard()
);
}
throw new UnexpectedCallsCountException($message);
} | php | {
"resource": ""
} |
q267345 | ScenarioYamlBuilder.parseParameter | test | private function parseParameter(&$optionValues)
{
if (!\is_callable($optionValues) && !empty($optionValues)) {
if (\is_array($optionValues) && '$' === $optionValues[0][0]) {
if (isset($this->parameters[$optionValues[0]])) {
$optionValues[0] = $this->parameters[$optionValues[0]];
}
} elseif (\is_string($optionValues) && '$' === $optionValues[0]) {
if (isset($this->parameters[$optionValues])) {
$optionValues = $this->parameters[$optionValues];
}
}
}
} | php | {
"resource": ""
} |
q267346 | ScenarioYamlBuilder.setParameter | test | public function setParameter(string $parameterName, $object): ScenarioYamlBuilder
{
$this->parameters['$'.$parameterName] = $object;
return $this;
} | php | {
"resource": ""
} |
q267347 | Trim.filter | test | public function filter($str)
{
if (is_null($str)) {
return null;
}
if (is_array($str)) {
foreach ($str as $k => $v) {
$str[$k] = trim($v);
}
return $str;
}
return trim($str);
} | php | {
"resource": ""
} |
q267348 | Evil.breakpoint | test | public static function breakpoint($message, $line = false, $file = false, $status = null)
{
if (!is_scalar($message)) {
$message = print_r($message, 1);
}
$message = self::appendFL($message, $line, $file);
if (php_sapi_name() === 'cli') {
$message .= PHP_EOL;
} else {
$message = '<pre>'.htmlspecialchars($message, ENT_COMPAT, 'UTF-8').'</pre>';
}
self::out($message);
self::stop($status);
} | php | {
"resource": ""
} |
q267349 | PEAR_Command_Mirror.doDownloadAll | test | function doDownloadAll($command, $options, $params)
{
$savechannel = $this->config->get('default_channel');
$reg = &$this->config->getRegistry();
$channel = isset($options['channel']) ? $options['channel'] :
$this->config->get('default_channel');
if (!$reg->channelExists($channel)) {
$this->config->set('default_channel', $savechannel);
return $this->raiseError('Channel "' . $channel . '" does not exist');
}
$this->config->set('default_channel', $channel);
$this->ui->outputData('Using Channel ' . $this->config->get('default_channel'));
$chan = $reg->getChannel($channel);
if (PEAR::isError($chan)) {
return $this->raiseError($chan);
}
if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
$base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
$rest = &$this->config->getREST('1.0', array());
$remoteInfo = array_flip($rest->listPackages($base, $channel));
}
if (PEAR::isError($remoteInfo)) {
return $remoteInfo;
}
$cmd = &$this->factory("download");
if (PEAR::isError($cmd)) {
return $cmd;
}
$this->ui->outputData('Using Preferred State of ' .
$this->config->get('preferred_state'));
$this->ui->outputData('Gathering release information, please wait...');
/**
* Error handling not necessary, because already done by
* the download command
*/
PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
$err = $cmd->run('download', array('downloadonly' => true), array_keys($remoteInfo));
PEAR::staticPopErrorHandling();
$this->config->set('default_channel', $savechannel);
if (PEAR::isError($err)) {
$this->ui->outputData($err->getMessage());
}
return true;
} | php | {
"resource": ""
} |
q267350 | Factory.addInstance | test | public function addInstance($className, $mockObject)
{
if(!isset($this->objects[$className])) {
$this->objects[$className] = [];
}
$this->objects[$className][] = $mockObject;
} | php | {
"resource": ""
} |
q267351 | Factory._createNew | test | protected function _createNew($className)
{
if (!empty($this->objects[$className])) {
return array_shift($this->objects[$className]);
}
if (class_exists($className) == false) {
throw new ClassNotFoundException('The class '.$className.' cannot be found');
}
$constructArguments = func_get_args();
array_shift($constructArguments);
return new $className( ...$constructArguments);
} | php | {
"resource": ""
} |
q267352 | SettingsController.actionProfile | test | public function actionProfile() {
$model = $this->finder->findProfileById(Yii::$app->user->identity->getId());
if ($model == null) {
$model = Yii::createObject(Profile::className());
$model->link('user', Yii::$app->user->identity);
}
$event = $this->getProfileEvent($model);
$this->performAjaxValidation($model);
$this->trigger(self::EVENT_BEFORE_PROFILE_UPDATE, $event);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->getSession()->setFlash('success', Yii::t('user', 'Your profile has been updated'));
$this->trigger(self::EVENT_AFTER_PROFILE_UPDATE, $event);
return $this->refresh();
}
return $this->render('profile', [
'model' => $model,
]);
} | php | {
"resource": ""
} |
q267353 | Getter.exist | test | public function exist(Array $namespaces): string {
$exist = false;
foreach ($namespaces as $namespace) {
if (in_array($namespace, $_SERVER['argv'])) {
$exist = true;
}
}
return $exist;
} | php | {
"resource": ""
} |
q267354 | Getter.variable | test | public function variable(Array $namespaces): string {
$value = "";
if (count($namespaces)) {
for ($index = 0; $index < count($_SERVER['argv']); $index++) {
if (!is_object($_SERVER['argv'][$index]) && in_array($_SERVER['argv'][$index], $namespaces)) {
$value = "";
if (isset($_SERVER['argv'][++$index])) {
$value = $_SERVER['argv'][$index];
}
break;
}
}
}
return $value;
} | php | {
"resource": ""
} |
q267355 | NativeResponseBuilder.make | test | public function make(string $content = '', int $statusCode = StatusCode::OK, array $headers = []): Response
{
return $this->app->response($content, $statusCode, $headers);
} | php | {
"resource": ""
} |
q267356 | NativeResponseBuilder.view | test | public function view(
string $template,
array $data = [],
int $statusCode = StatusCode::OK,
array $headers = []
): Response {
$content = $this->app->view()->make($template, $data)->render();
return $this->make($content, $statusCode, $headers);
} | php | {
"resource": ""
} |
q267357 | NativeResponseBuilder.json | test | public function json(array $data = [], int $statusCode = StatusCode::OK, array $headers = []): JsonResponse
{
return $this->app->json($data, $statusCode, $headers);
} | php | {
"resource": ""
} |
q267358 | NativeResponseBuilder.jsonp | test | public function jsonp(
string $callback,
array $data = [],
int $statusCode = StatusCode::OK,
array $headers = []
): JsonResponse {
return $this->json($data, $statusCode, $headers)->setCallback(
$callback
);
} | php | {
"resource": ""
} |
q267359 | NativeResponseBuilder.redirect | test | public function redirect(
string $uri = '/',
int $statusCode = StatusCode::FOUND,
array $headers = []
): RedirectResponse {
return $this->app->redirect($uri, $statusCode, $headers);
} | php | {
"resource": ""
} |
q267360 | NativeResponseBuilder.route | test | public function route(
string $route,
array $parameters = [],
int $statusCode = StatusCode::FOUND,
array $headers = []
): RedirectResponse {
return $this->app->redirectRoute(
$route,
$parameters,
$statusCode,
$headers
);
} | php | {
"resource": ""
} |
q267361 | Email.validate | test | private function validate($email): void {
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidArgumentException('Expected email address, but got [' . var_export($email, true) . '] instead');
}
} | php | {
"resource": ""
} |
q267362 | Khayyam.diffInYears | test | public function diffInYears(Carbon $dt = null, $abs = true)
{
$dt = ($dt === null) ? static::now($this->tz) : $dt;
return (int) $this->diff($dt, $abs)->format('%r%y');
} | php | {
"resource": ""
} |
q267363 | Khayyam.diffInWeekdays | test | public function diffInWeekdays(Carbon $dt = null, $abs = true)
{
return $this->diffInDaysFiltered(function (Carbon $date) {
return $date->isWeekday();
}, $dt, $abs);
} | php | {
"resource": ""
} |
q267364 | Khayyam.diffInSeconds | test | public function diffInSeconds(Carbon $dt = null, $abs = true)
{
$dt = ($dt === null) ? static::now($this->tz) : $dt;
$value = $dt->getTimestamp() - $this->getTimestamp();
return $abs ? abs($value) : $value;
} | php | {
"resource": ""
} |
q267365 | Khayyam.diffForHumans | test | public function diffForHumans(Carbon $other = null, $absolute = false)
{
$isNow = $other === null;
if ($isNow) {
$other = static::now($this->tz);
}
$diffInterval = $this->diff($other);
switch (true) {
case ($diffInterval->y > 0):
$unit = 'year';
$delta = $diffInterval->y;
break;
case ($diffInterval->m > 0):
$unit = 'month';
$delta = $diffInterval->m;
break;
case ($diffInterval->d > 0):
$unit = 'day';
$delta = $diffInterval->d;
if ($delta >= self::DAYS_PER_WEEK) {
$unit = 'week';
$delta = floor($delta / self::DAYS_PER_WEEK);
}
break;
case ($diffInterval->h > 0):
$unit = 'hour';
$delta = $diffInterval->h;
break;
case ($diffInterval->i > 0):
$unit = 'minute';
$delta = $diffInterval->i;
break;
default:
$delta = $diffInterval->s;
$unit = 'second';
break;
}
if ($delta == 0) {
$delta = 1;
}
$txt = $delta . ' ' . $unit;
$txt .= $delta == 1 ? '' : 's';
if ($absolute) {
return $txt;
}
$isFuture = $diffInterval->invert === 1;
if ($isNow) {
if ($isFuture) {
return $txt . ' from now';
}
return $txt . ' ago';
}
if ($isFuture) {
return $txt . ' after';
}
return $txt . ' before';
} | php | {
"resource": ""
} |
q267366 | NativeCommandAnnotations.getCommands | test | public function getCommands(string ...$classes): array
{
$annotations = [];
// Iterate through all the classes
foreach ($classes as $class) {
// Get all the annotations for each class and iterate through them
/** @var \Valkyrja\Console\Annotations\Command $annotation */
foreach ($this->classAnnotationsType(
'Command',
$class
) as $annotation) {
$this->setCommandProperties($annotation);
// Set the annotation in the annotations list
$annotations[] = $this->getCommandFromAnnotation($annotation);
}
// Get all the annotations for each class and iterate through them
/** @var \Valkyrja\Console\Annotations\Command $annotation */
foreach ($this->methodsAnnotationsType(
'Command',
$class
) as $annotation) {
$this->setCommandProperties($annotation);
// Set the annotation in the annotations list
$annotations[] = $this->getCommandFromAnnotation($annotation);
}
}
return $annotations;
} | php | {
"resource": ""
} |
q267367 | NativeCommandAnnotations.setCommandProperties | test | protected function setCommandProperties(Annotation $annotation): void
{
$classReflection = $this->getClassReflection($annotation->getClass());
if ($annotation->getMethod() || $classReflection->hasMethod(
'__construct'
)
) {
$methodReflection = $this->getMethodReflection(
$annotation->getClass(),
$annotation->getMethod() ?? '__construct'
);
$parameters = $methodReflection->getParameters();
// Set the dependencies
$annotation->setDependencies(
$this->getDependencies(...$parameters)
);
}
$annotation->setMatches();
} | php | {
"resource": ""
} |
q267368 | NativeCommandAnnotations.getCommandFromAnnotation | test | protected function getCommandFromAnnotation(Command $command): ConsoleCommand
{
$consoleCommand = new ConsoleCommand();
$consoleCommand
->setPath($command->getRegex())
->setRegex($command->getRegex())
->setParams($command->getParams())
->setSegments($command->getSegments())
->setDescription($command->getDescription())
->setId($command->getId())
->setName($command->getName())
->setClass($command->getClass())
->setProperty($command->getProperty())
->setMethod($command->getMethod())
->setStatic($command->isStatic())
->setFunction($command->getFunction())
->setMatches($command->getMatches())
->setDependencies($command->getDependencies())
->setArguments($command->getArguments());
return $consoleCommand;
} | php | {
"resource": ""
} |
q267369 | ItemController.storagePath | test | protected function storagePath()
{
if (\Yii::$app->controller != $this) {
return false;
}
return $this->_storagePath
? $this->_storagePath
: $this->_storagePath
= str_replace('@app/web', '', $this->findModel(Yii::$app->request->get('id'))->getStoragePath());
} | php | {
"resource": ""
} |
q267370 | ItemController.findModel | test | public function findModel($id = false, $search = false)
{
$model = Module::getModel(
$this,
($search ? $this->searchModelName : $this->modelName),
['controllers' => 'models'],
['scenario' => $this->getScenario()]
);
if ($id && (!$model = $model->search(compact('id'))->one())) {
throw new NotFoundHttpException('The requested page does not exist.');
}
$model->scenario = $this->getScenario(); // for found model too
return $model;
} | php | {
"resource": ""
} |
q267371 | PEAR_Task_Postinstallscript_rw.getParam | test | function getParam($name, $prompt, $type = 'string', $default = null)
{
if ($default !== null) {
return
array(
$this->_pkg->getTasksNs() . ':name' => $name,
$this->_pkg->getTasksNs() . ':prompt' => $prompt,
$this->_pkg->getTasksNs() . ':type' => $type,
$this->_pkg->getTasksNs() . ':default' => $default
);
}
return
array(
$this->_pkg->getTasksNs() . ':name' => $name,
$this->_pkg->getTasksNs() . ':prompt' => $prompt,
$this->_pkg->getTasksNs() . ':type' => $type,
);
} | php | {
"resource": ""
} |
q267372 | GuzzleClient.request | test | public function request(string $method, string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->request($method, $uri, $options);
} | php | {
"resource": ""
} |
q267373 | GuzzleClient.get | test | public function get(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->get($uri, $options);
} | php | {
"resource": ""
} |
q267374 | GuzzleClient.post | test | public function post(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->post($uri, $options);
} | php | {
"resource": ""
} |
q267375 | GuzzleClient.head | test | public function head(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->head($uri, $options);
} | php | {
"resource": ""
} |
q267376 | GuzzleClient.put | test | public function put(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->put($uri, $options);
} | php | {
"resource": ""
} |
q267377 | GuzzleClient.patch | test | public function patch(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->patch($uri, $options);
} | php | {
"resource": ""
} |
q267378 | GuzzleClient.delete | test | public function delete(string $uri, array $options = []): ResponseInterface
{
return $this->guzzle->delete($uri, $options);
} | php | {
"resource": ""
} |
q267379 | Printable.desensitization | test | private function desensitization(string $host) : string
{
if ($px1 = strpos($host, '@')) {
$px2 = strpos($host, ':', ($pxs = strpos($host, '://')) ? $pxs + 3 : 0);
return substr($host, 0, $px2 + 1) . '***' . substr($host, $px1);
}
return $host;
} | php | {
"resource": ""
} |
q267380 | Timer.checkpoint | test | public function checkpoint(string $name)
{
$this->checkpoints[$name] = microtime(true) - end($this->checkpoints);
} | php | {
"resource": ""
} |
q267381 | Model.mergeWithData | test | public function mergeWithData($data) {
foreach ($data as $key => $value) {
if ($key != $this->_primaryKey && (
(!array_key_exists($key, $this->_data) && $this->_structure->hasColumn($key))
|| (array_key_exists($key, $this->_data) && $value != $this->_data[$key])
)
) {
$this->offsetSet($key, $value);
}
}
} | php | {
"resource": ""
} |
q267382 | FileReader.read | test | public function read(array $options)
{
if (!isset($options['file'])) {
throw MissingOptionException::create('file');
}
if (!is_string($options['file'])) {
throw InvalidOptionTypeException::create('file', 'string');
}
if (!is_file($options['file'])) {
throw FileDoesNotExistException::create($options['file']);
}
if (!is_readable($options['file'])) {
throw FileIsNotReadableException::create($options['file']);
}
$file = $this->_factory->createInstance($options['file'], null, $options);
return $file->getContents();
} | php | {
"resource": ""
} |
q267383 | Container.package | test | public function package($name)
{
if( ! isset($this->packages[ $name ]))
{
throw new PackageNotDefinedException("$name is not defined");
}
return $this->packages[ $name ];
} | php | {
"resource": ""
} |
q267384 | LivePubHelper.init_pub | test | public static function init_pub()
{
global $project;
self::$is_publishing = true;
// if we've set up a global static configuration, add that in
$file = BASE_PATH . '/' . $project . '/_config_static.php';
if (file_exists($file) && strpos(self::$base_init_code, $file) === false) {
self::$base_init_code .= "\n<?php include_once('$file') ?>\n";
}
} | php | {
"resource": ""
} |
q267385 | LivePubHelper.clear_init_code | test | public static function clear_init_code()
{
self::$init_code = array();
self::$vars = array();
self::$silverstripe_db_included = false;
if (self::$base_init_code) {
array_unshift(self::$init_code, self::$base_init_code);
}
} | php | {
"resource": ""
} |
q267386 | LivePubHelper.get_init_code | test | public static function get_init_code()
{
if (self::is_publishing()) {
$code = "";
// if objects have set up initialization code, add that in
foreach (self::$init_code as $block) {
$block = trim($block);
if (strlen($block) == 0) {
continue;
}
if (substr($block, 0, 5) != '<?php') {
$code .= '<?php ';
}
$code .= $block;
if (substr($block, -2) != '?>') {
$code .= ' ?>';
}
$code .= "\n";
}
// if there are variables to initialize, add that in
if (count(self::$vars) > 0) {
$code .= "\n<?php\n";
foreach (self::$vars as $var => $valCode) {
if ($valCode === true) {
continue;
} // this means it was already set in the initialization
$code .= '$' . $var . ' = ' . $valCode . ";\n";
}
$code .= "\n?>\n";
}
return $code;
}
} | php | {
"resource": ""
} |
q267387 | LivePubHelper.eval_php | test | public static function eval_php($code)
{
if (self::is_publishing()) {
return self::$context=='html'
? '<?php echo eval(\'' . addcslashes($code, "'") . '\'); ?>'
: 'eval(\'' . addcslashes($code, "'") . '\')';
} else {
return eval($code);
}
} | php | {
"resource": ""
} |
q267388 | LivePubHelper.init_template_paths | test | protected static function init_template_paths()
{
global $project;
self::$template_path = array();
self::$template_path[] = BASE_PATH . '/' . SSViewer::get_theme_folder() . '/templates/php';
self::$template_path[] = BASE_PATH . '/' . $project . '/templates/php';
} | php | {
"resource": ""
} |
q267389 | LivePubHelper.add_template_path | test | public static function add_template_path($path)
{
if (!isset(self::$template_path) || empty(self::$template_path)) {
self::init_template_paths();
}
if ($path[0] != '/') {
$path = BASE_PATH . '/' . $path;
}
self::$template_path[] = rtrim($path, '/');
} | php | {
"resource": ""
} |
q267390 | LivePubHelper.wrap | test | public static function wrap($object, $class = 'ViewableWrapper', $add_init_code=true)
{
if (self::is_publishing()) {
$class2 = "{$class}_LivePub";
if (class_exists($class2, true)) {
$class = $class2;
}
$obj = new $class($object);
if ($add_init_code && ($init = $obj->getStaticInit())) {
self::$init_code[] = $init;
}
} else {
$obj = new $class($object);
}
return $obj;
} | php | {
"resource": ""
} |
q267391 | Schema.getSchemaNames | test | public function getSchemaNames($refresh = false)
{
if ($this->_schemaNames === null || $refresh) {
return $this->findSchemaNames()->then(
function($names) use($refresh) {
$this->_schemaNames = $names;
return $names;
}
);
}
return resolve($this->_schemaNames);
} | php | {
"resource": ""
} |
q267392 | Schema.getTableNames | test | public function getTableNames($schema = '', $refresh = false)
{
if (!isset($this->_tableNames[$schema]) || $refresh) {
return $this->findTableNames($schema)->then(
function($names) use ($schema) {
$this->_tableNames[$schema] = $names;
return $names;
}
);
}
return resolve($this->_tableNames[$schema]);
} | php | {
"resource": ""
} |
q267393 | Schema.refreshTableMetadata | test | public function refreshTableMetadata($tableName, $nameIsRaw = false) {
$rawName = $nameIsRaw ? $tableName : $this->getRawTableName($tableName);
$metaTypes = $this->tableMetaImplemented;
if (isset($this->_tableMetadata[$rawName])) {
unset($this->_tableMetadata[$rawName]);
}
foreach ($metaTypes as $metaType) {
$promises[] = $this->getTableMetadataRaw($rawName, $metaType, true)->otherwise(function() { return true; });
}
return !empty($promises) ? all($promises) : resolve(true);
} | php | {
"resource": ""
} |
q267394 | Schema.getTableMetadata | test | protected function getTableMetadata($name, $type = self::META_SCHEMA, $refresh = false)
{
$rawName = $this->getRawTableName($name);
if ($refresh) {
$this->getTableMetadataRaw($rawName, $type, true);
}
if (isset($this->_tableMetadata[$rawName][$type])) {
return $this->_tableMetadata[$rawName][$type];
}
return null;
} | php | {
"resource": ""
} |
q267395 | Schema.getTableMetadataRaw | test | protected function getTableMetadataRaw($name, $type, $refresh = false)
{
/** @var ExtendedPromiseInterface $promise */
$promise = $this->{'loadTable' . ucfirst($type)}($name);
if ($refresh) {
$promise->then(function($data) use ($name, $type) {
$this->_tableMetadata[$name] = isset($this->_tableMetadata[$name]) ? $this->_tableMetadata[$name] : [];
$this->_tableMetadata[$name][$type] = $data;
return $data;
});
}
return $promise;
} | php | {
"resource": ""
} |
q267396 | Schema.setTableMetadata | test | protected function setTableMetadata($name, $type, $data)
{
$rawName = $this->getRawTableName($name);
$this->_tableMetadata[$rawName] = isset($this->_tableMetadata[$rawName]) ? $this->_tableMetadata[$rawName] : [];
$this->_tableMetadata[$rawName][$type] = $data;
} | php | {
"resource": ""
} |
q267397 | Schema.getCacheKey | test | protected function getCacheKey($name)
{
return [
__CLASS__,
$this->db->getDsn(),
$this->db->username,
$this->getRawTableName($name),
];
} | php | {
"resource": ""
} |
q267398 | Zend_Cache_Backend.getOption | test | public function getOption($name)
{
$name = strtolower($name);
if (array_key_exists($name, $this->_options)) {
return $this->_options[$name];
}
if (array_key_exists($name, $this->_directives)) {
return $this->_directives[$name];
}
Zend_Cache::throwException("Incorrect option name : {$name}");
} | php | {
"resource": ""
} |
q267399 | Zend_Cache_Backend.getTmpDir | test | public function getTmpDir()
{
$tmpdir = array();
foreach (array($_ENV, $_SERVER) as $tab) {
foreach (array('TMPDIR', 'TEMP', 'TMP', 'windir', 'SystemRoot') as $key) {
if (isset($tab[$key]) && is_string($tab[$key])) {
if (($key == 'windir') or ($key == 'SystemRoot')) {
$dir = realpath($tab[$key] . '\\temp');
} else {
$dir = realpath($tab[$key]);
}
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
}
}
$upload = ini_get('upload_tmp_dir');
if ($upload) {
$dir = realpath($upload);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if (function_exists('sys_get_temp_dir')) {
$dir = sys_get_temp_dir();
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
// Attemp to detect by creating a temporary file
$tempFile = tempnam(md5(uniqid(rand(), TRUE)), '');
if ($tempFile) {
$dir = realpath(dirname($tempFile));
unlink($tempFile);
if ($this->_isGoodTmpDir($dir)) {
return $dir;
}
}
if ($this->_isGoodTmpDir('/tmp')) {
return '/tmp';
}
if ($this->_isGoodTmpDir('\\temp')) {
return '\\temp';
}
Zend_Cache::throwException('Could not determine temp directory, please specify a cache_dir manually');
} | php | {
"resource": ""
} |
Subsets and Splits