_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q1200
|
Dispatcher.close
|
train
|
public function close(Server $server, int $fd)
{
try {
if (!$path = WebSocketContext::getMeta('path', $fd)) {
throw new ContextLostException(
"The connection info has lost of the fd#$fd, on connection closed"
);
}
$className = $this->getHandler($path)[0];
/** @var HandlerInterface $handler */
$handler = \bean($className);
if (\method_exists($handler, 'onClose')) {
$handler->onClose($server, $fd);
}
} catch (\Throwable $e) {
App::error($e->getMessage(), ['fd' => $fd]);
}
}
|
php
|
{
"resource": ""
}
|
q1201
|
UserAgentStringParser.parse
|
train
|
public function parse($string, $strict = true)
{
// Parse quickly (with medium accuracy)
$information = $this->doParse($string);
// Run some filters to increase accuracy
if ($strict) {
$information = $this->definition->filter($information);
}
return $information;
}
|
php
|
{
"resource": ""
}
|
q1202
|
UserAgentStringParser.parseFromGlobal
|
train
|
public function parseFromGlobal($strict = true)
{
$string = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
return $this->parse($string, $strict);
}
|
php
|
{
"resource": ""
}
|
q1203
|
UserAgentStringParser.doParse
|
train
|
protected function doParse($string)
{
$userAgent = array(
'string' => $this->cleanString($string),
'browser_name' => null,
'browser_version' => null,
'browser_engine' => null,
'operating_system' => null,
'device' => 'Other'
);
if (empty($userAgent['string'])) {
return $userAgent;
}
$browsers = $this->definition->getKnownBrowsers();
$bots = $this->definition->getKnownBots();
$userAgents = $browsers + $bots;
// Find the right name/version phrase (or return empty array if none found)
foreach ($userAgents as $name => $regexes) {
if ($matches = $this->matchBrowser($regexes, $userAgent['string'])) {
if (isset($matches[3])) {
$name = str_replace('*', strtolower($matches[2]), $name);
}
$userAgent['browser_name'] = $name;
$userAgent['browser_version'] = end($matches);
break;
}
}
// Find browser engine
$engines = $this->definition->getKnownEngines();
if ($result = $this->find($engines, $userAgent['string'])) {
$userAgent['browser_engine'] = $result;
}
// Find operating system
$operatingSystems = $this->definition->getKnownOperatingSystems();
if ($result = $this->find($operatingSystems, $userAgent['string'])) {
$userAgent['operating_system'] = $result;
}
// Find device name
$devices = $this->definition->getKnownDevices();
if ($result = $this->find($devices, $userAgent['string'], true)) {
$userAgent['device'] = $result;
}
return $userAgent;
}
|
php
|
{
"resource": ""
}
|
q1204
|
UserAgentStringParser.matchBrowser
|
train
|
protected function matchBrowser(array $regexes, $string)
{
// Build regex that matches phrases for known browsers (e.g. "Firefox/2.0" or "MSIE 6.0").
// This only matches the major and minor version numbers (e.g. "2.0.0.6" is parsed as simply "2.0").
$pattern = '#('.join('|', $regexes).')[/ ]+([0-9]+(?:\.[0-9]+)?)#i';
if (preg_match($pattern, $string, $matches)) {
return $matches;
}
return false;
}
|
php
|
{
"resource": ""
}
|
q1205
|
DeleteCommand.removeByPrefix
|
train
|
private function removeByPrefix(InputInterface $input, OutputInterface $output)
{
$prefix = $input->getOption('prefix');
$output->writeln(
sprintf('<comment>Removing all resources from <info>%s</info></comment>', $prefix)
);
$api = $this->getCloudinaryApi();
$response = $api->delete_resources_by_prefix($prefix);
$this->outputApiResponse($response, 'deleted', $output);
}
|
php
|
{
"resource": ""
}
|
q1206
|
DeleteCommand.removeResource
|
train
|
private function removeResource(InputInterface $input, OutputInterface $output)
{
$resource = $input->getOption('resource');
$output->writeln(
sprintf('<comment>Removing resource <info>%s</info></comment>', $resource)
);
$api = $this->getCloudinaryApi();
$response = $api->delete_resources($resource);
$this->outputApiResponse($response, 'deleted', $output);
}
|
php
|
{
"resource": ""
}
|
q1207
|
DeleteCommand.outputApiResponse
|
train
|
private function outputApiResponse(Response $response, $part, OutputInterface $output)
{
$table = new Table($output);
$table->setHeaders(['Resource', 'Status']);
foreach ($response[$part] as $file => $status) {
$table->addRow([$file, $status]);
}
$table->render();
}
|
php
|
{
"resource": ""
}
|
q1208
|
CategoriesController.publish
|
train
|
public function publish(Category $category)
{
$category->togglePublishedState();
$category->getDescendants()->each(
function (Category $cat) use ($category) {
$cat->published = $category->published;
$cat->save();
}
);
$message = $category->published ? trans('cms::categories.publish.success') : trans('cms::categories.publish.error');
return $this->notifySuccess($message);
}
|
php
|
{
"resource": ""
}
|
q1209
|
LogoutGuard.isActiveGuard
|
train
|
public function isActiveGuard(Request $request, $guard)
{
$name = Auth::guard($guard)->getName();
return ($this->sessionHas($request, $name) && $this->sessionGet($request,
$name) === $this->getAuthIdentifier($guard));
}
|
php
|
{
"resource": ""
}
|
q1210
|
Push.open
|
train
|
public function open($id, $label = null) {
return $this->webService->post("SELECT FROM 'PUSH'.'DOCUMENT'", array_filter([
"id" => $id,
"label" => $label
]));
}
|
php
|
{
"resource": ""
}
|
q1211
|
Push.changeInterval
|
train
|
public function changeInterval($id, $interval) {
return $this->webService->post("UPDATE 'PUSH'.'PUSHINTERVAL'", [
self::PARAMETER_PUSH_ID => $id,
self::PARAMETER_PUSH_INTERVAL => $interval
]);
}
|
php
|
{
"resource": ""
}
|
q1212
|
MenuPresenter.url
|
train
|
public function url()
{
/** @var \Yajra\CMS\Repositories\Extension\Repository $repository */
$repository = app('extensions');
/** @var \Yajra\CMS\Entities\Extension $extension */
$extension = $repository->findOrFail($this->entity->extension_id);
$class = $extension->param('class');
if (class_exists($class)) {
$entity = app($class)->findOrNew($this->entity->param('id'));
if ($entity instanceof UrlGenerator) {
if (! $entity->exists) {
return '#';
}
return $entity->getUrl($this->entity->param('data'));
}
}
return url($this->entity->url);
}
|
php
|
{
"resource": ""
}
|
q1213
|
MenuPresenter.linkTitle
|
train
|
public function linkTitle()
{
return $this->entity->param('link_title') ? $this->entity->param('link_title') : $this->entity->title;
}
|
php
|
{
"resource": ""
}
|
q1214
|
ConfigurationsController.store
|
train
|
public function store(Request $request)
{
$config = $request->input('config');
foreach (array_dot($request->input('data')) as $key => $value) {
$path = $config . '.' . $key;
$this->destroy($path);
if (is_array($value)) {
$value = implode(',', $value);
}
Configuration::create(['key' => $path, 'value' => $value]);
}
return $this->notifySuccess(trans('cms::config.success', ['config' => $config]));
}
|
php
|
{
"resource": ""
}
|
q1215
|
ConfigurationsController.show
|
train
|
public function show($key)
{
$config = config($key) ?? [];
if (! isset($this->limits[$key])) {
return $this->filter($config);
}
return response()->json(
$this->filter(array_only($config, $this->limits[$key]))
);
}
|
php
|
{
"resource": ""
}
|
q1216
|
ConfigurationsController.filter
|
train
|
protected function filter(array $array)
{
$config = collect(array_dot($array))->map(function ($value, $key) {
if (str_contains($key, $this->hidden)) {
return '';
}
if (in_array($key, $this->boolean)) {
return (bool) $value;
}
return $value;
});
$array = [];
foreach ($config as $key => $value) {
array_set($array, $key, $value);
}
return $array;
}
|
php
|
{
"resource": ""
}
|
q1217
|
ProfileController.removeAvatar
|
train
|
public function removeAvatar()
{
$profile = auth()->user();
$profile->avatar = '';
$profile->save();
event(new ProfileWasUpdated($profile));
return redirect()->route('administrator.profile.edit');
}
|
php
|
{
"resource": ""
}
|
q1218
|
UserAgent.configureFromUserAgentString
|
train
|
public function configureFromUserAgentString($string, UserAgentStringParser $parser = null)
{
$parser = $parser ?: new UserAgentStringParser();
$result = $string !== null ? $parser->parse($string) : $parser->parseFromGlobal();
$this->setUserAgentString($string);
$this->fromArray($result);
}
|
php
|
{
"resource": ""
}
|
q1219
|
UserAgent.toArray
|
train
|
public function toArray()
{
return array(
'browser_name' => $this->getBrowserName(),
'browser_version' => $this->getBrowserVersion(),
'browser_engine' => $this->getBrowserEngine(),
'operating_system' => $this->getOperatingSystem(),
'device' => $this->getDevice()
);
}
|
php
|
{
"resource": ""
}
|
q1220
|
UserAgent.fromArray
|
train
|
private function fromArray(array $data)
{
$this->browserName = $data['browser_name'];
$this->browserVersion = $data['browser_version'];
$this->browserEngine = $data['browser_engine'];
$this->operatingSystem = $data['operating_system'];
$this->device = $data['device'];
}
|
php
|
{
"resource": ""
}
|
q1221
|
BundleDependency.registerBundleDependencies
|
train
|
protected function registerBundleDependencies(ContainerBuilder $container)
{
if (true === $this->booted) {
return;
}
$this->bundles = $container->getParameter('kernel.bundles');
if ($this->createBundles($this->getBundleDependencies())) {
$container->setParameter('kernel.bundles', $this->bundles);
$this->initializeBundles($container);
$pass = new Compiler\ExtensionLoadPass($this->instances);
$container->addCompilerPass($pass);
}
$this->booted = true;
}
|
php
|
{
"resource": ""
}
|
q1222
|
BundleDependency.createBundles
|
train
|
protected function createBundles(array $dependencies)
{
foreach ($dependencies as $bundleClass) {
$name = substr($bundleClass, strrpos($bundleClass, '\\') + 1);
if (false === isset($this->bundles[$name])) {
$bundle = new $bundleClass();
$this->bundles[$name] = $bundleClass;
$this->instances[$name] = $bundle;
if ($bundle instanceof BundleDependencyInterface) {
$this->createBundles($bundle->getBundleDependencies());
}
}
}
return count($this->instances) > 0;
}
|
php
|
{
"resource": ""
}
|
q1223
|
Extractor.extractFromFile
|
train
|
public function extractFromFile($filePath)
{
if (!is_file($filePath)) {
throw new FileNotFoundException($filePath);
}
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
$this->checkDirectory();
$extractorAdapterNamespace = $this->getAdapterNamespaceGivenExtension($extension);
$extractorAdapter = $this
->instanceExtractorAdapter($extractorAdapterNamespace);
if (!$extractorAdapter->isAvailable()) {
throw new AdapterNotAvailableException($extractorAdapter->getIdentifier());
}
return $extractorAdapter->extract($filePath);
}
|
php
|
{
"resource": ""
}
|
q1224
|
Extractor.checkDirectory
|
train
|
protected function checkDirectory()
{
$directoryPath = $this
->directory
->getDirectoryPath();
if (!is_dir($directoryPath)) {
mkdir($directoryPath);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q1225
|
Extractor.getAdapterNamespaceGivenExtension
|
train
|
protected function getAdapterNamespaceGivenExtension($fileExtension)
{
$adapterNamespace = '\Mmoreram\Extractor\Adapter\\';
switch ($fileExtension) {
case 'zip':
$adapterNamespace .= 'ZipExtractorAdapter';
break;
case 'rar':
$adapterNamespace .= 'RarExtractorAdapter';
break;
case 'phar':
$adapterNamespace .= 'PharExtractorAdapter';
break;
case 'tar':
$adapterNamespace .= 'TarExtractorAdapter';
break;
case 'gz':
$adapterNamespace .= 'TarGzExtractorAdapter';
break;
case 'bz2':
$adapterNamespace .= 'TarBz2ExtractorAdapter';
break;
default:
throw new ExtensionNotSupportedException($fileExtension);
}
return $adapterNamespace;
}
|
php
|
{
"resource": ""
}
|
q1226
|
Extension.widget
|
train
|
public static function widget($name)
{
$builder = static::query();
return $builder->where('type', 'widget')
->whereRaw('LOWER(name) = ?', [Str::lower($name)])
->first();
}
|
php
|
{
"resource": ""
}
|
q1227
|
JsonPretty.prettify
|
train
|
public function prettify($json, $flags = null, $indent = "\t", $is_json=null)
{
if (!isset($is_json)) {
$is_json = $this->isJson($json);
}
if (!$is_json) {
return $this->process(json_encode($json, $flags), $indent);
}
return $this->process($json, $indent);
}
|
php
|
{
"resource": ""
}
|
q1228
|
NavigationController.store
|
train
|
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|max:255',
'type' => 'required|max:255|alpha|unique:navigation,type',
]);
$navigation = new Navigation;
$navigation->fill($request->all());
$navigation->published = $request->get('published', false);
$navigation->save();
flash()->success(trans('cms::navigation.store.success'));
return redirect()->route('administrator.navigation.index');
}
|
php
|
{
"resource": ""
}
|
q1229
|
OpenGraphHelper.html
|
train
|
public function html(array $options = [], array $namespaces = [])
{
$this->addNamespace('og', 'http://ogp.me/ns#');
$this->addNamespace('fb', 'http://ogp.me/ns/fb#');
if ($namespaces) {
foreach ($namespaces as $ns => $url) {
$this->addNamespace($ns, $url);
}
}
$this->setType($this->config('type'));
$this->setUri($this->request->here);
$this->setTitle($this->_View->fetch('title'));
if ($appId = $this->config('app_id')) {
$this->setAppId($appId);
}
return $this->Html->tag('html', null, $this->config('namespaces') + $options);
}
|
php
|
{
"resource": ""
}
|
q1230
|
BoletoBuilder.cedente
|
train
|
public function cedente($nome, $documento, Endereco $endereco)
{
$this->cedente = new Cedente($nome, $documento, $endereco);
return $this;
}
|
php
|
{
"resource": ""
}
|
q1231
|
BoletoBuilder.banco
|
train
|
public function banco($agencia, $conta)
{
$reflection = new ReflectionClass($this->namespace . '\\' . $this->type);
$this->banco = $reflection->newInstanceArgs(array($agencia, $conta));
return $this;
}
|
php
|
{
"resource": ""
}
|
q1232
|
BoletoBuilder.carteira
|
train
|
public function carteira($carteira)
{
$reflection = new ReflectionClass($this->namespace . '\\Carteira\\Carteira' . $carteira);
$this->carteira = $reflection->newInstanceArgs();
return $this;
}
|
php
|
{
"resource": ""
}
|
q1233
|
EloquentRepository.getPublished
|
train
|
public function getPublished()
{
return $this->getModel()->with([
'menus' => function ($query) {
$query->limitDepth(1)->orderBy('order', 'asc');
},
'menus.permissions',
'menus.children',
])->published()->get();
}
|
php
|
{
"resource": ""
}
|
q1234
|
FuelPHP_Sniffs_NamingConventions_UnderscoredWithScopeFunctionNameSniff.isUnderscoreName
|
train
|
public static function isUnderscoreName($string)
{
// If there are space in the name, it can't be valid.
if (strpos($string, ' ') !== false) {
return false;
}
if ($string !== strtolower($string)) {
return false;
}
$validName = true;
$nameBits = explode('_', $string);
foreach ($nameBits as $bit) {
if ($bit === '') {
continue;
}
if ($bit{0} !== strtolower($bit{0})) {
$validName = false;
break;
}
}
return $validName;
}
|
php
|
{
"resource": ""
}
|
q1235
|
ByteCodeCacheDataCollector.getByteCodeCache
|
train
|
public function getByteCodeCache()
{
if (count($this->data) === 0) {
return $this->byteCodeCache;
}
$mapper = new ArrayMapper();
return $mapper->fromArray($this->data);
}
|
php
|
{
"resource": ""
}
|
q1236
|
RouteServiceProvider.mapWebRoutes
|
train
|
protected function mapWebRoutes(Router $router)
{
$this->mapArticleRoutes($router);
$this->mapCategoryRoutes($router);
$this->mapTagsRoutes($router);
$this->mapAdministratorAuthenticationRoutes($router);
$this->mapAdministratorRoutes($router);
$this->mapFrontendRoutes($router);
}
|
php
|
{
"resource": ""
}
|
q1237
|
RouteServiceProvider.mapAdministratorAuthenticationRoutes
|
train
|
protected function mapAdministratorAuthenticationRoutes(Router $router)
{
$router->group(['prefix' => admin_prefix(), 'middleware' => 'web'], function () use ($router) {
$router->get('login', AuthController::class . '@showLoginForm')->name('administrator.login');
$router->get('logout', AuthController::class . '@logout')->name('administrator.logout');
$router->post('login', AuthController::class . '@login')->name('administrator.login');
});
}
|
php
|
{
"resource": ""
}
|
q1238
|
ReflectionTools.getClassMethods
|
train
|
public function getClassMethods(\ReflectionClass $class) : array
{
$classes = $this->getClassHierarchy($class);
$methods = [];
foreach ($classes as $hClass) {
$hClassName = $hClass->getName();
foreach ($hClass->getMethods() as $method) {
if ($method->isStatic()) {
// exclude static methods
continue;
}
if ($method->getDeclaringClass()->getName() !== $hClassName) {
// exclude inherited methods
continue;
}
$methods[] = $method;
}
}
return $this->filterReflectors($methods);
}
|
php
|
{
"resource": ""
}
|
q1239
|
ReflectionTools.getClassProperties
|
train
|
public function getClassProperties(\ReflectionClass $class) : array
{
$classes = $this->getClassHierarchy($class);
/** @var \ReflectionProperty[] $properties */
$properties = [];
foreach ($classes as $hClass) {
$hClassName = $hClass->getName();
foreach ($hClass->getProperties() as $property) {
if ($property->isStatic()) {
// exclude static properties
continue;
}
if ($property->getDeclaringClass()->getName() !== $hClassName) {
// exclude inherited properties
continue;
}
$properties[] = $property;
}
}
return $this->filterReflectors($properties);
}
|
php
|
{
"resource": ""
}
|
q1240
|
ReflectionTools.filterReflectors
|
train
|
private function filterReflectors(array $reflectors) : array
{
$filteredReflectors = [];
foreach ($reflectors as $index => $reflector) {
if ($reflector->isPrivate()) {
$filteredReflectors[] = $reflector;
continue;
}
foreach ($reflectors as $index2 => $reflector2) {
if ($index2 <= $index) {
continue;
}
if ($reflector->getName() === $reflector2->getName()) {
// overridden
continue 2;
}
}
$filteredReflectors[] = $reflector;
}
return $filteredReflectors;
}
|
php
|
{
"resource": ""
}
|
q1241
|
ReflectionTools.getFunctionParameterTypes
|
train
|
public function getFunctionParameterTypes(\ReflectionFunctionAbstract $function) : array
{
return $this->cache(__FUNCTION__, $function, static function() use ($function) {
$docComment = $function->getDocComment();
if ($docComment === false) {
return [];
}
preg_match_all('/@param\s+(\S+)\s+\$(\S+)/', $docComment, $matches, PREG_SET_ORDER);
$types = [];
foreach ($matches as $match) {
$types[$match[2]] = explode('|', $match[1]);
}
return $types;
});
}
|
php
|
{
"resource": ""
}
|
q1242
|
ReflectionTools.getParameterTypes
|
train
|
public function getParameterTypes(\ReflectionParameter $parameter) : array
{
$name = $parameter->getName();
$function = $parameter->getDeclaringFunction();
$types = $this->getFunctionParameterTypes($function);
return isset($types[$name]) ? $types[$name] : [];
}
|
php
|
{
"resource": ""
}
|
q1243
|
ReflectionTools.getPropertyTypes
|
train
|
public function getPropertyTypes(\ReflectionProperty $property) : array
{
$docComment = $property->getDocComment();
if ($docComment === false) {
return [];
}
if (preg_match('/@var\s+(\S+)/', $docComment, $matches) !== 1) {
return [];
}
return explode('|', $matches[1]);
}
|
php
|
{
"resource": ""
}
|
q1244
|
ReflectionTools.getPropertyClass
|
train
|
public function getPropertyClass(\ReflectionProperty $property) : ?string
{
$types = $this->getPropertyTypes($property);
if (count($types) === 1) {
$type = $types[0];
if ($type[0] === '\\') {
return substr($type, 1);
}
}
return null;
}
|
php
|
{
"resource": ""
}
|
q1245
|
ReflectionTools.exportFunction
|
train
|
public function exportFunction(\ReflectionFunctionAbstract $function, int $excludeModifiers = 0) : string
{
$result = '';
if ($function instanceof \ReflectionMethod) {
$modifiers = $function->getModifiers();
$modifiers &= ~ $excludeModifiers;
foreach (\Reflection::getModifierNames($modifiers) as $modifier) {
$result .= $modifier . ' ';
}
}
$result .= 'function ' . $function->getShortName();
$result .= '(' . $this->exportFunctionParameters($function) . ')';
if (null !== $returnType = $function->getReturnType()) {
$result .= ' : ';
if ($returnType->allowsNull()) {
$result .= '?';
}
if (! $returnType->isBuiltin()) {
$result .= '\\';
}
$result .= $returnType->getName();
}
return $result;
}
|
php
|
{
"resource": ""
}
|
q1246
|
ReflectionTools.cache
|
train
|
private function cache(string $method, $object, callable $callback)
{
$hash = spl_object_hash($object);
if (! isset($this->cache[$method][$hash])) {
$this->cache[$method][$hash] = $callback();
}
return $this->cache[$method][$hash];
}
|
php
|
{
"resource": ""
}
|
q1247
|
Widget.getAssignmentAttribute
|
train
|
public function getAssignmentAttribute()
{
if (! $this->exists) {
return static::ALL_PAGES;
}
$count = $this->menuPivot()->count();
if ($count === 0) {
return static::NO_PAGES;
} elseif ($count > 1) {
return static::SELECTED_PAGES;
} elseif ($count === 1) {
$pivot = $this->menuPivot()->first();
if ($pivot->menu_id > 0) {
return static::SELECTED_PAGES;
}
}
return static::ALL_PAGES;
}
|
php
|
{
"resource": ""
}
|
q1248
|
Widget.menuPivot
|
train
|
public function menuPivot()
{
return $this->getConnection()->table('widget_menu')
->where('widget_id', $this->id)
->orWhere(function ($query) {
$query->where('menu_id', 0)
->where('widget_id', $this->id);
});
}
|
php
|
{
"resource": ""
}
|
q1249
|
Widget.syncMenuAssignment
|
train
|
public function syncMenuAssignment($menu, $assignment)
{
switch ($assignment) {
case static::ALL_PAGES:
$this->menus()->sync([static::ALL_PAGES]);
break;
case static::NO_PAGES:
$this->menus()->detach();
break;
case static::SELECTED_PAGES:
$this->menus()->sync($menu);
break;
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q1250
|
EloquentRepository.install
|
train
|
public function install($type, array $attributes)
{
$extension = new Extension;
$extension->type = $type;
$extension->name = $attributes['name'];
if (isset($attributes['parameters'])) {
$extension->parameters = $attributes['parameters'];
}
$extension->manifest = json_encode($attributes);
$extension->save();
return $extension;
}
|
php
|
{
"resource": ""
}
|
q1251
|
EloquentRepository.uninstall
|
train
|
public function uninstall($id)
{
$extension = $this->getModel()->query()->findOrFail($id);
// TODO: remove extension files.
$extension->delete();
}
|
php
|
{
"resource": ""
}
|
q1252
|
EloquentRepository.registerManifest
|
train
|
public function registerManifest($path)
{
if (! File::exists($path)) {
throw new \Exception('Extension manifest file does not exist! Path: ' . $path);
}
$manifest = File::get($path);
$manifest = json_decode($manifest, true);
$this->register($manifest);
}
|
php
|
{
"resource": ""
}
|
q1253
|
FuelPHP_Sniffs_WhiteSpace_ControlStructureSpacingSniff.isNextTokenAnException
|
train
|
protected function isNextTokenAnException($tokens, $ptr)
{
return in_array($tokens[($ptr + 1)]['code'], $this->exceptions)
&& $tokens[($ptr + 1)]['column'] - $tokens[($ptr)]['column'] == 1;
}
|
php
|
{
"resource": ""
}
|
q1254
|
Convenio.ajustarNossoNumero
|
train
|
public function ajustarNossoNumero(ArrayObject $data)
{
$carteira = $this->carteira;
switch (strlen($this->convenio)) {
case 6:
if (!$carteira instanceof Carteira21) {
$data['NossoNumero'] = $this->convenio . $data['NossoNumero'];
}
break;
case 4:
case 7:
$data['NossoNumero'] = $this->convenio . $data['NossoNumero'];
break;
default:
throw new \LogicException('O codigo do convenio precisa ter 4, 6 ou 7 digitos!');
}
return $data;
}
|
php
|
{
"resource": ""
}
|
q1255
|
RedirectService.buildResponseIfApplicable
|
train
|
public function buildResponseIfApplicable(Request $httpRequest)
{
try {
$redirect = $this->redirectStorage->getOneBySourceUriPathAndHost($httpRequest->getRelativePath(), $httpRequest->getBaseUri()->getHost());
if ($redirect === null) {
return null;
}
if (isset($this->featureSwitch['hitCounter']) && $this->featureSwitch['hitCounter'] === true) {
$this->redirectStorage->incrementHitCount($redirect);
}
return $this->buildResponse($httpRequest, $redirect);
} catch (\Exception $exception) {
// Throw exception if it's a \Neos\RedirectHandler\Exception (used for custom exception handling)
if ($exception instanceof Exception) {
throw $exception;
}
// skip triggering the redirect if there was an error accessing the database (wrong credentials, ...)
return null;
}
}
|
php
|
{
"resource": ""
}
|
q1256
|
SphinxClient.setServer
|
train
|
public function setServer($host, $port = 0)
{
assert(is_string($host));
if ($host[0] == '/') {
$this->_path = 'unix://'.$host;
return;
}
if (substr($host, 0, 7) == 'unix://') {
$this->_path = $host;
return;
}
$this->_host = $host;
if (is_int($port)) {
if ($port) {
$this->_port = $port;
}
}
$this->_path = '';
return $this;
}
|
php
|
{
"resource": ""
}
|
q1257
|
SphinxClient.setLimits
|
train
|
public function setLimits($offset, $limit, $max = 0, $cutoff = 0)
{
assert(is_int($offset));
assert(is_int($limit));
assert(is_int($max));
assert(is_int($cutoff));
assert($offset >= 0);
assert($limit > 0);
assert($max >= 0);
assert($cutoff >= 0);
$this->_offset = $offset;
$this->_limit = $limit;
if ($max > 0) {
$this->_maxmatches = $max;
}
if ($cutoff > 0) {
$this->_cutoff = $cutoff;
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q1258
|
SphinxClient.setMaxQueryTime
|
train
|
public function setMaxQueryTime($max)
{
assert(is_int($max));
assert($max >= 0);
$this->_maxquerytime = $max;
return $this;
}
|
php
|
{
"resource": ""
}
|
q1259
|
SphinxClient.setMatchMode
|
train
|
public function setMatchMode($mode)
{
assert($mode == SPH_MATCH_ALL
|| $mode == SPH_MATCH_ANY
|| $mode == SPH_MATCH_PHRASE
|| $mode == SPH_MATCH_BOOLEAN
|| $mode == SPH_MATCH_EXTENDED
|| $mode == SPH_MATCH_FULLSCAN
|| $mode == SPH_MATCH_EXTENDED2);
$this->_mode = $mode;
return $this;
}
|
php
|
{
"resource": ""
}
|
q1260
|
SphinxClient.setRankingMode
|
train
|
public function setRankingMode($ranker, $rankexpr = '')
{
assert($ranker === 0 || $ranker >= 1 && $ranker < SPH_RANK_TOTAL);
assert(is_string($rankexpr));
$this->_ranker = $ranker;
$this->_rankexpr = $rankexpr;
return $this;
}
|
php
|
{
"resource": ""
}
|
q1261
|
SphinxClient.setIndexWeights
|
train
|
public function setIndexWeights(array $weights)
{
assert(is_array($weights));
foreach ($weights as $index => $weight) {
assert(is_string($index));
assert(is_int($weight));
}
$this->_indexweights = $weights;
return $this;
}
|
php
|
{
"resource": ""
}
|
q1262
|
SphinxClient.setRetries
|
train
|
public function setRetries($count, $delay = 0)
{
assert(is_int($count) && $count >= 0);
assert(is_int($delay) && $delay >= 0);
$this->_retrycount = $count;
$this->_retrydelay = $delay;
return $this;
}
|
php
|
{
"resource": ""
}
|
q1263
|
SphinxClient.query
|
train
|
public function query($query, $index = '*', $comment = '')
{
assert(empty($this->_reqs));
$this->AddQuery($query, $index, $comment);
$results = $this->RunQueries();
$this->_reqs = array(); // just in case it failed too early
if (!is_array($results)) {
return false;
} // probably network error; error message should be already filled
$this->_error = $results[0]['error'];
$this->_warning = $results[0]['warning'];
if ($results[0]['status'] == SEARCHD_ERROR) {
return false;
} else {
return $results[0];
}
}
|
php
|
{
"resource": ""
}
|
q1264
|
SphinxClient.runQueries
|
train
|
public function runQueries()
{
if (empty($this->_reqs)) {
$this->_error = 'no queries defined, issue AddQuery() first';
return false;
}
// mbstring workaround
$this->_MBPush();
if (!($fp = $this->_Connect())) {
$this->_MBPop();
return false;
}
// send query, get response
$nreqs = count($this->_reqs);
$req = implode('', $this->_reqs);
$len = 8 + strlen($req);
$req = pack('nnNNN', SEARCHD_COMMAND_SEARCH, VER_COMMAND_SEARCH, $len, 0, $nreqs).$req; // add header
if (!($this->_Send($fp, $req, $len + 8)) ||
!($response = $this->_GetResponse($fp, VER_COMMAND_SEARCH))
) {
$this->_MBPop();
return false;
}
// query sent ok; we can reset reqs now
$this->_reqs = array();
// parse and return response
return $this->_ParseSearchResponse($response, $nreqs);
}
|
php
|
{
"resource": ""
}
|
q1265
|
SphinxClient.open
|
train
|
public function open()
{
if ($this->_socket !== false) {
$this->_error = 'already connected';
return false;
}
if (!$fp = $this->_Connect()) {
return false;
}
// command, command version = 0, body length = 4, body = 1
$req = pack('nnNN', SEARCHD_COMMAND_PERSIST, 0, 4, 1);
if (!$this->_Send($fp, $req, 12)) {
return false;
}
$this->_socket = $fp;
return true;
}
|
php
|
{
"resource": ""
}
|
q1266
|
SphinxClient.close
|
train
|
public function close()
{
if ($this->_socket === false) {
$this->_error = 'not connected';
return false;
}
fclose($this->_socket);
$this->_socket = false;
return true;
}
|
php
|
{
"resource": ""
}
|
q1267
|
SphinxClient.status
|
train
|
public function status()
{
$this->_MBPush();
if (!($fp = $this->_Connect())) {
$this->_MBPop();
return false;
}
$req = pack('nnNN', SEARCHD_COMMAND_STATUS, VER_COMMAND_STATUS, 4, 1); // len=4, body=1
if (!($this->_Send($fp, $req, 12)) ||
!($response = $this->_GetResponse($fp, VER_COMMAND_STATUS))
) {
$this->_MBPop();
return false;
}
substr($response, 4); // just ignore length, error handling, etc
$p = 0;
list($rows, $cols) = array_values(unpack('N*N*', substr($response, $p, 8)));
$p += 8;
$res = array();
for ($i = 0; $i < $rows; ++$i) {
for ($j = 0; $j < $cols; ++$j) {
list(, $len) = unpack('N*', substr($response, $p, 4));
$p += 4;
$res[$i][] = substr($response, $p, $len);
$p += $len;
}
}
$this->_MBPop();
return $res;
}
|
php
|
{
"resource": ""
}
|
q1268
|
SphinxClient.removeFilter
|
train
|
public function removeFilter($attribute)
{
assert(is_string($attribute));
foreach ($this->_filters as $key => $filter) {
if ($filter['attr'] == $attribute) {
unset($this->_filters[$key]);
return $this;
}
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q1269
|
SphinxClient._Connect
|
train
|
protected function _Connect()
{
if ($this->_socket !== false) {
// we are in persistent connection mode, so we have a socket
// however, need to check whether it's still alive
if (!@feof($this->_socket)) {
return $this->_socket;
}
// force reopen
$this->_socket = false;
}
$errno = 0;
$errstr = '';
$this->_connerror = false;
if ($this->_path) {
$host = $this->_path;
$port = 0;
} else {
$host = $this->_host;
$port = $this->_port;
}
if ($this->_timeout <= 0) {
$fp = @fsockopen($host, $port, $errno, $errstr);
} else {
$fp = @fsockopen($host, $port, $errno, $errstr, $this->_timeout);
}
if (!$fp) {
if ($this->_path) {
$location = $this->_path;
} else {
$location = "{$this->_host}:{$this->_port}";
}
$errstr = trim($errstr);
$this->_error = "connection to $location failed (errno=$errno, msg=$errstr)";
$this->_connerror = true;
return false;
}
// send my version
// this is a subtle part. we must do it before (!) reading back from searchd.
// because otherwise under some conditions (reported on FreeBSD for instance)
// TCP stack could throttle write-write-read pattern because of Nagle.
if (!$this->_Send($fp, pack('N', 1), 4)) {
fclose($fp);
$this->_error = 'failed to send client protocol version';
return false;
}
// check version
list(, $v) = unpack('N*', fread($fp, 4));
$v = (int) $v;
if ($v < 1) {
fclose($fp);
$this->_error = "expected searchd protocol version 1+, got version '$v'";
return false;
}
return $fp;
}
|
php
|
{
"resource": ""
}
|
q1270
|
SphinxClient._GetResponse
|
train
|
protected function _GetResponse($fp, $client_ver)
{
$status = '';
$response = '';
$len = 0;
$ver = '';
$header = fread($fp, 8);
if (strlen($header) == 8) {
list($status, $ver, $len) = array_values(unpack('n2a/Nb', $header));
$left = $len;
while ($left > 0 && !feof($fp)) {
$chunk = fread($fp, min(8192, $left));
if ($chunk) {
$response .= $chunk;
$left -= strlen($chunk);
}
}
}
if ($this->_socket === false) {
fclose($fp);
}
// check response
$read = strlen($response);
if (!$response || $read != $len) {
$this->_error = $len
? "failed to read searchd response (status=$status, ver=$ver, len=$len, read=$read)"
: 'received zero-sized searchd response';
return false;
}
// check status
if ($status == SEARCHD_WARNING) {
list($temp, $wlen) = unpack('N*', substr($response, 0, 4));
unset($temp);
$this->_warning = substr($response, 4, $wlen);
return substr($response, 4 + $wlen);
}
if ($status == SEARCHD_ERROR) {
$this->_error = 'searchd error: '.substr($response, 4);
return false;
}
if ($status == SEARCHD_RETRY) {
$this->_error = 'temporary searchd error: '.substr($response, 4);
return false;
}
if ($status != SEARCHD_OK) {
$this->_error = "unknown status code '$status'";
return false;
}
// check version
if ($ver < $client_ver) {
$this->_warning = sprintf("searchd command v.%d.%d older than client's v.%d.%d, some options might not work",
$ver >> 8, $ver & 0xff, $client_ver >> 8, $client_ver & 0xff);
}
return $response;
}
|
php
|
{
"resource": ""
}
|
q1271
|
SphinxClient.sphPackI64
|
train
|
protected function sphPackI64($v)
{
assert(is_numeric($v));
// x64
if (PHP_INT_SIZE >= 8) {
$v = (int) $v;
return pack('NN', $v >> 32, $v & 0xFFFFFFFF);
}
// x32, int
if (is_int($v)) {
return pack('NN', $v < 0 ? -1 : 0, $v);
}
// x32, bcmath
if (function_exists('bcmul')) {
if (bccomp($v, 0) == -1) {
$v = bcadd('18446744073709551616', $v);
}
$h = bcdiv($v, '4294967296', 0);
$l = bcmod($v, '4294967296');
return pack('NN', (float) $h, (float) $l); // conversion to float is intentional; int would lose 31st bit
}
// x32, no-bcmath
$p = max(0, strlen($v) - 13);
$lo = abs((float) substr($v, $p));
$hi = abs((float) substr($v, 0, $p));
$m = $lo + $hi * 1316134912.0; // (10 ^ 13) % (1 << 32) = 1316134912
$q = floor($m / 4294967296.0);
$l = $m - ($q * 4294967296.0);
$h = $hi * 2328.0 + $q; // (10 ^ 13) / (1 << 32) = 2328
if ($v < 0) {
if ($l == 0) {
$h = 4294967296.0 - $h;
} else {
$h = 4294967295.0 - $h;
$l = 4294967296.0 - $l;
}
}
return pack('NN', $h, $l);
}
|
php
|
{
"resource": ""
}
|
q1272
|
SphinxClient.sphPackU64
|
train
|
protected function sphPackU64($v)
{
assert(is_numeric($v));
// x64
if (PHP_INT_SIZE >= 8) {
assert($v >= 0);
// x64, int
if (is_int($v)) {
return pack('NN', $v >> 32, $v & 0xFFFFFFFF);
}
// x64, bcmath
if (function_exists('bcmul')) {
$h = bcdiv($v, 4294967296, 0);
$l = bcmod($v, 4294967296);
return pack('NN', $h, $l);
}
// x64, no-bcmath
$p = max(0, strlen($v) - 13);
$lo = (int) substr($v, $p);
$hi = (int) substr($v, 0, $p);
$m = $lo + $hi * 1316134912;
$l = $m % 4294967296;
$h = $hi * 2328 + (int) ($m / 4294967296);
return pack('NN', $h, $l);
}
// x32, int
if (is_int($v)) {
return pack('NN', 0, $v);
}
// x32, bcmath
if (function_exists('bcmul')) {
$h = bcdiv($v, '4294967296', 0);
$l = bcmod($v, '4294967296');
return pack('NN', (float) $h, (float) $l); // conversion to float is intentional; int would lose 31st bit
}
// x32, no-bcmath
$p = max(0, strlen($v) - 13);
$lo = (float) substr($v, $p);
$hi = (float) substr($v, 0, $p);
$m = $lo + $hi * 1316134912.0;
$q = floor($m / 4294967296.0);
$l = $m - ($q * 4294967296.0);
$h = $hi * 2328.0 + $q;
return pack('NN', $h, $l);
}
|
php
|
{
"resource": ""
}
|
q1273
|
SphinxClient.sphUnpackU64
|
train
|
protected function sphUnpackU64($v)
{
list($hi, $lo) = array_values(unpack('N*N*', $v));
if (PHP_INT_SIZE >= 8) {
if ($hi < 0) {
$hi += (1 << 32);
} // because php 5.2.2 to 5.2.5 is totally fucked up again
if ($lo < 0) {
$lo += (1 << 32);
}
// x64, int
if ($hi <= 2147483647) {
return ($hi << 32) + $lo;
}
// x64, bcmath
if (function_exists('bcmul')) {
return bcadd($lo, bcmul($hi, '4294967296'));
}
// x64, no-bcmath
$C = 100000;
$h = ((int) ($hi / $C) << 32) + (int) ($lo / $C);
$l = (($hi % $C) << 32) + ($lo % $C);
if ($l > $C) {
$h += (int) ($l / $C);
$l = $l % $C;
}
if ($h == 0) {
return $l;
}
return sprintf('%d%05d', $h, $l);
}
// x32, int
if ($hi == 0) {
if ($lo > 0) {
return $lo;
}
return sprintf('%u', $lo);
}
$hi = sprintf('%u', $hi);
$lo = sprintf('%u', $lo);
// x32, bcmath
if (function_exists('bcmul')) {
return bcadd($lo, bcmul($hi, '4294967296'));
}
// x32, no-bcmath
$hi = (float) $hi;
$lo = (float) $lo;
$q = floor($hi / 10000000.0);
$r = $hi - $q * 10000000.0;
$m = $lo + $r * 4967296.0;
$mq = floor($m / 10000000.0);
$l = $m - $mq * 10000000.0;
$h = $q * 4294967296.0 + $r * 429.0 + $mq;
$h = sprintf('%.0f', $h);
$l = sprintf('%07.0f', $l);
if ($h == '0') {
return sprintf('%.0f', (float) $l);
}
return $h.$l;
}
|
php
|
{
"resource": ""
}
|
q1274
|
SphinxClient.sphUnpackI64
|
train
|
protected function sphUnpackI64($v)
{
list($hi, $lo) = array_values(unpack('N*N*', $v));
// x64
if (PHP_INT_SIZE >= 8) {
if ($hi < 0) {
$hi += (1 << 32);
} // because php 5.2.2 to 5.2.5 is totally fucked up again
if ($lo < 0) {
$lo += (1 << 32);
}
return ($hi << 32) + $lo;
}
// x32, int
if ($hi == 0) {
if ($lo > 0) {
return $lo;
}
return sprintf('%u', $lo);
} // x32, int
elseif ($hi == -1) {
if ($lo < 0) {
return $lo;
}
return sprintf('%.0f', $lo - 4294967296.0);
}
$neg = '';
$c = 0;
if ($hi < 0) {
$hi = ~$hi;
$lo = ~$lo;
$c = 1;
$neg = '-';
}
$hi = sprintf('%u', $hi);
$lo = sprintf('%u', $lo);
// x32, bcmath
if (function_exists('bcmul')) {
return $neg.bcadd(bcadd($lo, bcmul($hi, '4294967296')), $c);
}
// x32, no-bcmath
$hi = (float) $hi;
$lo = (float) $lo;
$q = floor($hi / 10000000.0);
$r = $hi - $q * 10000000.0;
$m = $lo + $r * 4967296.0;
$mq = floor($m / 10000000.0);
$l = $m - $mq * 10000000.0 + $c;
$h = $q * 4294967296.0 + $r * 429.0 + $mq;
if ($l == 10000000) {
$l = 0;
$h += 1;
}
$h = sprintf('%.0f', $h);
$l = sprintf('%07.0f', $l);
if ($h == '0') {
return $neg.sprintf('%.0f', (float) $l);
}
return $neg.$h.$l;
}
|
php
|
{
"resource": ""
}
|
q1275
|
CategoryController.actionTree
|
train
|
public function actionTree()
{
$models = Category::find()->orderBy('position DESC, title')->all();
$model = new Category();
return $this->render('tree', [
'model' => $model,
'models' => $models,
]);
}
|
php
|
{
"resource": ""
}
|
q1276
|
ThemesController.store
|
train
|
public function store(Request $request)
{
$this->validate($request, [
'theme' => 'required',
]);
/** @var Configuration $config */
$config = Configuration::query()->firstOrCreate(['key' => 'theme.frontend']);
$config->value = $request->get('theme');
$config->save();
flash()->success(trans('cms::theme.success', ['theme' => $request->get('theme')]));
return back();
}
|
php
|
{
"resource": ""
}
|
q1277
|
CategoriesDataTable.dataTable
|
train
|
public function dataTable()
{
return (new EloquentDataTable($this->query()))
->editColumn('lft', '<i class="fa fa-dot-circle-o"></i>')
->addColumn('action', function (Category $category) {
return view('administrator.categories.datatables.action', $category->toArray());
})
->editColumn('authenticated', function (Category $category) {
return view('administrator.categories.datatables.authenticated', $category->toArray());
})
->addColumn('pub', function (Category $category) {
return '<span class="badge bg-green">' . $category->countPublished() . '</span>';
})
->addColumn('unpub', function (Category $category) {
return '<span class="badge bg-yellow">' . $category->countUnpublished() . '</span>';
})
->editColumn('hits', function (Category $category) {
return '<span class="badge bg-blue">' . $category->hits . '</span>';
})
->editColumn('title', function (Category $category) {
return view('administrator.categories.datatables.title', compact('category'));
})
->editColumn('created_at', function (Category $category) {
return $category->created_at->format('Y-m-d');
})
->rawColumns(['lft', 'published', 'authenticated', 'hits', 'title', 'action', 'pub', 'unpub']);
}
|
php
|
{
"resource": ""
}
|
q1278
|
Category.getPublishedPosts
|
train
|
public function getPublishedPosts()
{
return PostSearch::find()
->joinWith('category')
->where(['publish_status' => Post::STATUS_PUBLISHED, 'blog_category.id' => $this->id])
->all();
}
|
php
|
{
"resource": ""
}
|
q1279
|
SnapshotAssertions.assertEqualsSnapshot
|
train
|
protected function assertEqualsSnapshot($expected, $identifier = null, $message = null)
{
SnapshotsManager::setSuite($this);
$snapshot = SnapshotsManager::upsertSnapshotContents($identifier, $expected);
$this->assertEquals($snapshot, $expected, $message);
}
|
php
|
{
"resource": ""
}
|
q1280
|
Table.generatePush
|
train
|
public function generatePush(Array $parameters, $label, $pushCallback, $pushClass = "\BIPBOP\Client\Push") {
$reflection = new \ReflectionClass($pushClass);
$query = sprintf("SELECT FROM '%s'.'%s'", $this->database->name(), $this->domNode->getAttribute("name"));
$instance = $reflection->newInstance($this->ws);
$this->validateParameters($parameters);
/* @var $instance \BIPBOP\Push */
return $instance->create($label, $pushCallback, $query, $parameters);
}
|
php
|
{
"resource": ""
}
|
q1281
|
Category.recomputeSlug
|
train
|
protected function recomputeSlug()
{
$slug = $this->computeSlug();
$this->getConnection()->table($this->getTable())
->where($this->getKeyName(), $this->id)
->update(['slug' => $slug]);
$this->articles()->get()->each->touch();
}
|
php
|
{
"resource": ""
}
|
q1282
|
Category.getUrl
|
train
|
public function getUrl($layout = null)
{
$layout = $layout ? '?layout=' . $layout : '';
return url($this->slug) . $layout;
}
|
php
|
{
"resource": ""
}
|
q1283
|
Attachment.addAction
|
train
|
public function addAction($action)
{
if ($action instanceof AttachmentAction) {
$this->actions[] = $action;
return $this;
} elseif (is_array($action)) {
$this->actions[] = new AttachmentAction($action);
return $this;
}
throw new InvalidArgumentException('The attachment action must be an instance of jeremykenedy\Slack\AttachmentAction or a keyed array');
}
|
php
|
{
"resource": ""
}
|
q1284
|
Article.boot
|
train
|
protected static function boot()
{
parent::boot();
static::saving(function (Article $article) {
$article->slug = $article->computeSlug();
});
}
|
php
|
{
"resource": ""
}
|
q1285
|
Article.computeSlug
|
train
|
public function computeSlug()
{
if ($this->is_page) {
return $this->alias;
}
if (! $this->exists) {
$category = Category::query()->findOrFail($this->category_id);
} else {
$category = $this->category;
}
return $category->slug . '/' . $this->alias;
}
|
php
|
{
"resource": ""
}
|
q1286
|
Article.getRouteName
|
train
|
public function getRouteName()
{
if ($this->is_page) {
return $this->alias;
}
return str_replace('category-', '', $this->category->getRouteName() . '.' . $this->alias);
}
|
php
|
{
"resource": ""
}
|
q1287
|
Article.visited
|
train
|
public function visited()
{
$this->hits++;
$this->newQuery()
->toBase()
->where($this->getKeyName(), $this->getKey())
->increment('hits');
return $this;
}
|
php
|
{
"resource": ""
}
|
q1288
|
Article.getTemplate
|
train
|
public function getTemplate()
{
$view = 'articles' . str_replace('//', '.', $this->slug);
if (view()->exists($view)) {
return $view;
}
return $this->hasTemplate() ? $this->blade_template : 'article.show';
}
|
php
|
{
"resource": ""
}
|
q1289
|
WidgetMakeCommand.createJsonConfig
|
train
|
protected function createJsonConfig($name)
{
if ($this->files->exists($path = $this->getJsonPath())) {
$this->error('Widget json config already exists!');
return;
}
$stub = $this->files->get($this->getJsonStubPath());
$stub = $this->replaceNamespace($stub, $name)->replaceClass($stub, $name);
$stub = $this->replaceFQCN($stub, $name);
$stub = $this->replaceView($stub);
$this->files->put($path, $stub);
$this->info('Json config created successfully.');
}
|
php
|
{
"resource": ""
}
|
q1290
|
WidgetMakeCommand.getJsonStubPath
|
train
|
protected function getJsonStubPath()
{
$stubPath = $this->laravel->make('config')->get('laravel-widgets.widget_json_stub');
return $this->laravel->basePath() . '/' . $stubPath;
}
|
php
|
{
"resource": ""
}
|
q1291
|
WidgetMakeCommand.createView
|
train
|
protected function createView()
{
if ($this->files->exists($path = $this->getViewPath())) {
$this->error('View already exists!');
return;
}
$this->makeDirectory($path);
$view = $this->files->get($this->getViewStub('view'));
$this->files->put($path, $view);
$form = $this->files->get($this->getViewStub('form'));
$this->files->put($this->getViewPath('_form'), $form);
$this->info('Views successfully created.');
}
|
php
|
{
"resource": ""
}
|
q1292
|
WidgetMakeCommand.getViewStub
|
train
|
public function getViewStub($key)
{
$stubPath = $this->laravel->make('config')->get('laravel-widgets.widget_' . $key . '_stub');
return $this->laravel->basePath() . '/' . $stubPath;
}
|
php
|
{
"resource": ""
}
|
q1293
|
WebService.post
|
train
|
public function post($query, Array $parameters = [], $autoParser = true) {
curl_setopt_array($this->resource, [
CURLOPT_POSTFIELDS => array_merge($parameters, [
self::PARAMETER_QUERY => $query,
self::PARAMETER_APIKEY => $this->apiKey
])
]);
$dom = new \DOMDocument;
$ret = curl_exec($this->resource);
if (!$autoParser) return $ret;
$dom->loadXML($ret);
static::assert($dom);
return $dom;
}
|
php
|
{
"resource": ""
}
|
q1294
|
WebService.assert
|
train
|
public static function assert(\DOMDocument $dom) {
$queryNode = (new \DOMXPath($dom))->query("/BPQL/header/exception");
if ($queryNode->length) {
$nodeException = $queryNode->item(0);
$source = $nodeException->getAttribute("source");
$code = $nodeException->getAttribute("code");
$id = $nodeException->getAttribute("id");
$pushable = ($nodeException->getAttribute("pushable") ?: $nodeException->getAttribute("push")) === "true";
$message = $nodeException->nodeValue;
$e = new Exception(sprintf("[%s:%s/%s] %s", $code, $source, $id, $message, $pushable), $code);
$e->setAttributes($code, $source, $id, $message, $pushable);
throw $e;
}
}
|
php
|
{
"resource": ""
}
|
q1295
|
MediaController.browse
|
train
|
public function browse(Request $request, $filter = null)
{
$this->template = 'layouts.component';
$this->filter = $filter;
return $this->index($request);
}
|
php
|
{
"resource": ""
}
|
q1296
|
MediaController.folderIsNotAccessible
|
train
|
protected function folderIsNotAccessible(Request $request)
{
if (isset($request['folder']) && empty($request->get('folder'))) {
return true;
}
return ! Storage::exists($this->currentDir) && $request->has('folder') || $request->get('folder') === 'public';
}
|
php
|
{
"resource": ""
}
|
q1297
|
MediaController.scanFiles
|
train
|
protected function scanFiles($current_directory)
{
$files = collect(Storage::files($current_directory));
$files = $files->filter(function ($file) {
$ext = File::extension($file);
if ($this->filter === 'images') {
return in_array($ext, $this->config->get('media.images_ext'));
} elseif ($this->filter === 'files') {
return in_array($ext, $this->config->get('media.files_ext'));
}
return true;
});
return $files;
}
|
php
|
{
"resource": ""
}
|
q1298
|
MediaController.buildThumbnails
|
train
|
protected function buildThumbnails($files)
{
$thumbnails = [];
foreach ($files as $file) {
if (file_can_have_thumbnail($file)) {
$thumbnails[$file] = (string) $this->image
->make(Storage::get($file))
->resize(20, 20)->encode('data-url');
}
}
return $thumbnails;
}
|
php
|
{
"resource": ""
}
|
q1299
|
MediaController.buildDirectory
|
train
|
protected function buildDirectory($directories, $parent)
{
$directories = $directories->map(function ($dir) use ($parent) {
$dir = str_replace($parent . '/', '', $dir);
return $dir;
});
$html = '<ul>';
$directories->each(function ($dir) use (&$html, $parent) {
$subParent = $parent . '/' . $dir;
$url = request()->url() . '?folder=' . $dir;
$dir = str_replace('public/', 'storage/', $dir);
$html .= "<li>";
$html .= "<a href='{$url}'>{$dir}</a>";
if ($child = $this->scanDirectory($subParent)) {
$html .= $this->buildDirectory($child, $subParent);
}
$html .= "</li>";
});
$html .= '</ul>';
return $html;
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.