_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q262000
ProfileController.index
test
public function index() { $userData = Auth::guard('canvas')->user()->toArray(); $blogData = config('blog'); $data = array_merge($userData, $blogData); return view('canvas::backend.profile.index', compact('data')); }
php
{ "resource": "" }
q262001
ProfileController.update
test
public function update(ProfileUpdateRequest $request, $id) { $user = User::findOrFail($id); $user->fill($request->toArray())->save(); $user->save(); Session::put('_profile', trans('canvas::messages.update_success', ['entity' => 'Profile'])); return redirect()->route('canvas.admin.profile.index'); }
php
{ "resource": "" }
q262002
CanvasHelper.authenticated
test
public static function authenticated(Request $request, User $user) { // Get and record latest version. self::getLatestVersion(); // Set login message. Session::put('_login', trans('canvas::messages.login', ['display_name' => $user->display_name])); }
php
{ "resource": "" }
q262003
CanvasHelper.getCurrentVersion
test
public static function getCurrentVersion($update = true) { $extMan = new ExtensionManager(resolve('app'), resolve('files')); $packageName = self::CORE_PACKAGE; $version = 'Unknown'; // Retrieve framework (Easel) package info. $core = $extMan->getExtension(str_replace('/', '-', self::CORE_PACKAGE), ['canvas-framework']); $version = $core->getVersion(); $dist = $core->__get('dist'); if (substr($version, 0, 4) === 'dev-') { $version .= ' '.substr($dist['reference'], 0, 12); } // Save to Canvas Settings if ($update) { $setting = Settings::updateOrCreate( ['setting_name' => 'canvas_version'], ['setting_value' => $version] ); } return $version; }
php
{ "resource": "" }
q262004
PostUpdateRequest.postFillData
test
public function postFillData() { return [ 'user_id' => $this->user_id, 'title' => $this->title, 'slug' => $this->slug, 'subtitle' => $this->subtitle, 'page_image' => $this->page_image, 'content_raw' => $this->get('content'), 'meta_description' => $this->meta_description, 'is_published' => (bool) $this->is_published, 'published_at' => $this->published_at, 'layout' => config('blog.post_layout'), ]; }
php
{ "resource": "" }
q262005
ExtensionManager.enable
test
public function enable($name) { if (! $this->isEnabled($name)) { $extension = $this->getExtension($name); $enabled = $this->getEnabled(); $enabled[] = $name; $this->migrate($extension); $this->publishAssets($extension); $this->setEnabled($enabled); $extension->setEnabled(true); } }
php
{ "resource": "" }
q262006
ExtensionManager.disable
test
public function disable($name) { $enabled = $this->getEnabled(); if (($k = array_search($name, $enabled)) !== false) { unset($enabled[$k]); $extension = $this->getExtension($name); $this->setEnabled($enabled); $extension->setEnabled(false); } }
php
{ "resource": "" }
q262007
ExtensionManager.uninstall
test
public function uninstall($name) { $extension = $this->getExtension($name); $this->disable($name); $this->migrateDown($extension); $this->unpublishAssets($extension); $extension->setInstalled(false); }
php
{ "resource": "" }
q262008
ExtensionManager.migrate
test
public function migrate(Extension $extension, $up = true) { if ($extension->hasMigrations()) { $migrationDir = $extension->getPath().'/migrations'; $this->app->bind('Illuminate\Database\Schema\Builder', function ($container) { return $container->make('Illuminate\Database\ConnectionInterface')->getSchemaBuilder(); }); if ($up) { $this->migrator->run($migrationDir, $extension); } else { $this->migrator->reset($migrationDir, $extension); } } }
php
{ "resource": "" }
q262009
ExtensionManager.getEnabledBootstrappers
test
public function getEnabledBootstrappers() { $bootstrappers = new Collection; foreach ($this->getEnabledExtensions() as $extension) { if ($this->filesystem->exists($file = $extension->getPath().'/bootstrap.php')) { $bootstrappers->push($file); } } return $bootstrappers; }
php
{ "resource": "" }
q262010
SettingsUpdateRequest.sanitiseInput
test
public function sanitiseInput() { $source = $this->getInputSource(); $data = $source->all(); $data['post_is_published_default'] = filter_var( $this->post_is_published_default, FILTER_VALIDATE_BOOLEAN ); $source->replace($data); }
php
{ "resource": "" }
q262011
HomeController.index
test
public function index() { $data = [ 'posts' => Post::all(), 'recentPosts' => Post::orderBy('created_at', 'desc')->take(4)->get(), 'tags' => Tag::all(), 'users' => User::all(), 'disqus' => Settings::disqus(), 'analytics' => Settings::gaId(), 'status' => App::isDownForMaintenance() ? CanvasHelper::MAINTENANCE_MODE_ENABLED : CanvasHelper::MAINTENANCE_MODE_DISABLED, 'canvasVersion' => Settings::canvasVersion(), 'latestRelease' => Settings::latestRelease(), ]; return view('canvas::backend.home.index', compact('data')); }
php
{ "resource": "" }
q262012
PostFormFields.fieldsFromModel
test
protected function fieldsFromModel($id, array $fields) { $post = Post::findOrFail($id); $fieldNames = array_keys(array_except($fields, ['tags'])); $fields = ['id' => $id]; foreach ($fieldNames as $field) { $fields[$field] = $post->{$field}; } $fields['tags'] = $post->tags()->pluck('tag')->all(); return $fields; }
php
{ "resource": "" }
q262013
BlogIndexData.tagIndexData
test
protected function tagIndexData($tag) { $tag = Tag::where('tag', $tag)->firstOrFail(); $reverse_direction = (bool) $tag->reverse_direction; $posts = Post::where('published_at', '<=', Carbon::now()) ->whereHas('tags', function ($q) use ($tag) { $q->where('id', '=', $tag->id); }) ->where('is_published', 1) ->orderBy('published_at', $reverse_direction ? 'asc' : 'desc') ->simplePaginate(config('blog.posts_per_page')); $posts->appends('tag', $tag->tag); $page_image = $tag->page_image ?: config('blog.page_image'); return [ 'title' => $tag->title, 'subtitle' => $tag->subtitle, 'posts' => $posts, 'page_image' => $page_image, 'tag' => $tag, 'reverse_direction' => $reverse_direction, 'meta_description' => $tag->meta_description ?: \ Settings::where('setting_name', 'blog_description')->find(1), ]; }
php
{ "resource": "" }
q262014
BlogIndexData.normalIndexData
test
protected function normalIndexData() { $posts = Post::with('tags') ->where('published_at', '<=', Carbon::now()) ->where('is_published', 1) ->orderBy('published_at', 'desc') ->simplePaginate(config('blog.posts_per_page')); return [ 'title' => Settings::where('setting_name', 'blog_title')->find(1), 'subtitle' => Settings::where('setting_name', 'blog_subtitle')->find(1), 'posts' => $posts, 'page_image' => config('blog.page_image'), 'meta_description' => Settings::where('setting_name', 'blog_description')->find(1), 'reverse_direction' => false, 'tag' => null, ]; }
php
{ "resource": "" }
q262015
PostController.store
test
public function store(PostCreateRequest $request) { $post = Post::create($request->postFillData()); $post->syncTags($request->get('tags', [])); Session::put('_new-post', trans('canvas::messages.create_success', ['entity' => 'post'])); return redirect()->route('canvas.admin.post.edit', $post->id); }
php
{ "resource": "" }
q262016
PostController.update
test
public function update(PostUpdateRequest $request, $id) { $post = Post::findOrFail($id); $post->fill($request->postFillData()); $post->save(); $post->syncTags($request->get('tags', [])); Session::put('_update-post', trans('canvas::messages.update_success', ['entity' => 'Post'])); return redirect()->route('canvas.admin.post.edit', $id); }
php
{ "resource": "" }
q262017
ThemeManager.publishThemePublic
test
protected function publishThemePublic(Theme $theme) { $target = public_path(self::TARGET_DIR); // Merge/overwrite theme public files. return $this->filesystem->copyDirectory($theme->getPublicDirectory(), $target); }
php
{ "resource": "" }
q262018
ThemeManager.publishThemeViews
test
protected function publishThemeViews(Theme $theme, $clean = true) { $target = base_path('resources/views/'.self::TARGET_DIR); // Skip the ordeal if theme doesn't have views if (! $this->filesystem->exists($theme->getViewsDirectory())) { return true; } // Clean views directory. if ($clean) { $clean = $this->filesystem->deleteDirectory($target) || true; } // Publish theme views. $published = $this->filesystem->copyDirectory($theme->getViewsDirectory(), $target); return $published; }
php
{ "resource": "" }
q262019
ThemeManager.unTheme
test
public function unTheme() { $publicTarget = public_path(self::TARGET_DIR); $publicSource = __DIR__.'/../../public'; $viewsTarget = base_path('resources/views/'.self::TARGET_DIR); // Clean Views $clean = $this->filesystem->deleteDirectory($viewsTarget) || true; // Clean Public assets $clean = $clean && ($this->filesystem->cleanDirectory($publicTarget) || true); // Republish original/default public assets $unthemed = $clean && $this->filesystem->copyDirectory($publicSource, $publicTarget); // Actions to be taken after theme deactivation if ($unthemed) { // Update DB Setting Settings::updateOrCreate(['setting_name' => self::ACTIVE_KEY], ['setting_value' => 'default']); } return $unthemed; }
php
{ "resource": "" }
q262020
ThemeManager.getDefaultTheme
test
public function getDefaultTheme() { $theme = new Theme('/', [ 'name' => 'cnvs/canvas-theme-default', 'extra' => [ 'canvas-theme' => [ 'title' => $this->getDefaultThemeName(), ], ], ]); $theme->setVersion(Constants::DEFAULT_THEME_VERSION); return $theme; }
php
{ "resource": "" }
q262021
ThemeManager.getActive
test
public function getActive() { return $active = Settings::getByName(self::ACTIVE_KEY) ?: ($this->config->get(self::ACTIVE_KEY) ?: 'default'); }
php
{ "resource": "" }
q262022
RouteHelper.getGeneralMiddleware
test
public static function getGeneralMiddleware() { $config = ConfigHelper::getWriter(); $val = $config->get('route_middleware_general'); return is_null($val) ? self::ROUTE_MIDDLEWARE_GROUPS_GENERAL : $val; }
php
{ "resource": "" }
q262023
RouteHelper.getInstalledMiddleware
test
public static function getInstalledMiddleware() { $config = ConfigHelper::getWriter(); $val = $config->get('route_middleware_installed'); return is_null($val) ? self::ROUTE_MIDDLEWARE_INSTALLED : $val; }
php
{ "resource": "" }
q262024
RouteHelper.getAdminMiddleware
test
public static function getAdminMiddleware() { $config = ConfigHelper::getWriter(); $val = $config->get('route_middleware_admin'); return is_null($val) ? self::ROUTE_MIDDLEWARE_ADMIN : $val; }
php
{ "resource": "" }
q262025
RouteHelper.getBlogMain
test
public static function getBlogMain() { $config = ConfigHelper::getWriter(); $val = $config->get('blog_path'); return is_null($val) ? self::ROUTE_DEFAULT_BLOG_MAIN : $val; }
php
{ "resource": "" }
q262026
RouteHelper.getBlogPrefix
test
public static function getBlogPrefix() { $config = ConfigHelper::getWriter(); $val = $config->get('blog_prefix'); return is_null($val) ? self::ROUTE_DEFAULT_BLOG_PREFIX : $val; }
php
{ "resource": "" }
q262027
RouteHelper.getAdminPrefix
test
public static function getAdminPrefix($withSlashes = false, $slashPos = 0) { $config = ConfigHelper::getWriter(); $val = $config->get('admin_prefix'); $prefix = is_null($val) ? self::ROUTE_DEFAULT_ADMIN_PREFIX : $val; // add slashes if requested if ($withSlashes && (! empty($prefix) && $prefix != '/')) { if ($slashPos == -1) { $prefix = "/{$prefix}"; } elseif ($slashPos == 1) { $prefix = "{$prefix}/"; } else { $prefix = "/{$prefix}/"; } } // remove any duplicate slashes $prefix = str_replace('//', '/', $prefix); return $prefix; }
php
{ "resource": "" }
q262028
RouteHelper.getAuthPrefix
test
public static function getAuthPrefix() { $config = ConfigHelper::getWriter(); $val = $config->get('auth_prefix'); return is_null($val) ? self::ROUTE_DEFAULT_AUTH_PREFIX : $val; }
php
{ "resource": "" }
q262029
RouteHelper.getPasswordPrefix
test
public static function getPasswordPrefix() { $config = ConfigHelper::getWriter(); $val = $config->get('password_prefix'); return is_null($val) ? self::ROUTE_DEFAULT_PASSWORD_PREFIX : $val; }
php
{ "resource": "" }
q262030
SearchController.index
test
public function index() { $params = request('search'); $posts = Post::search($params)->get(); $tags = Tag::search($params)->get(); $users = User::search($params)->get(); return view('canvas::backend.search.index', compact('posts', 'tags', 'users')); }
php
{ "resource": "" }
q262031
PxPayAuthorizeRequest.getData
test
public function getData() { $this->validate('amount', 'returnUrl'); $data = new SimpleXMLElement('<GenerateRequest/>'); $data->PxPayUserId = $this->getUsername(); $data->PxPayKey = $this->getPassword(); $data->TxnType = $this->action; $data->AmountInput = $this->getAmount(); $data->CurrencyInput = $this->getCurrency(); $data->UrlSuccess = $this->getReturnUrl(); $data->UrlFail = $this->getCancelUrl() ?: $this->getReturnUrl(); if ($this->getDescription()) { $data->MerchantReference = $this->getDescription(); } if ($this->getTransactionId()) { $data->TxnId = $this->getTransactionId(); } if ($this->getTransactionData1()) { $data->TxnData1 = $this->getTransactionData1(); } if ($this->getTransactionData2()) { $data->TxnData2 = $this->getTransactionData2(); } if ($this->getTransactionData3()) { $data->TxnData3 = $this->getTransactionData3(); } if ($this->getCardReference()) { $data->DpsBillingId = $this->getCardReference(); } return $data; }
php
{ "resource": "" }
q262032
Client.scanFile
test
public function scanFile($file) { $this->_sendCommand('SCAN ' . $file); $response = $this->_receiveResponse(); return $this->_parseResponse($response); }
php
{ "resource": "" }
q262033
Client.multiscanFile
test
public function multiscanFile($file) { $this->_sendCommand('MULTISCAN ' . $file); $response = $this->_receiveResponse(); return $this->_parseResponse($response); }
php
{ "resource": "" }
q262034
Client.contScan
test
public function contScan($file) { $this->_sendCommand('CONTSCAN ' . $file); $response = $this->_receiveResponse(); return $this->_parseResponse($response); }
php
{ "resource": "" }
q262035
Client._receiveResponse
test
private function _receiveResponse($removeId = false, $readUntil = "\n") { $result = null; $readUntilLen = strlen($readUntil); do { if ($this->_socket->selectRead($this->_timeout)) { $rt = $this->_socket->read(4096, $this->_mode); if ($rt === "") { break; } $result .= $rt; if (strcmp(substr($result, 0 - $readUntilLen), $readUntil) == 0) { break; } } else if ($this->_mode === PHP_NORMAL_READ) { throw new ConnectionException("Timeout waiting to read response"); } else { break; } } while (true); if (!$this->_inSession) { $this->_closeConnection(); } else if ($removeId) { $result = preg_replace('/^\d+: /', "", $result, 1); } return trim($result); }
php
{ "resource": "" }
q262036
Handler.processSingleFile
test
protected function processSingleFile(array $file) { // store it for future reference $file['original_name'] = $file['name']; // sanitize the file name $file['name'] = $this->sanitizeFileName($file['name']); $file = $this->validateFile($file); // if there are messages the file is not valid if (isset($file['messages']) && $file['messages']) { return $file; } // add the prefix $prefix = ''; if (is_callable($this->prefix)) { $prefix = (string) call_user_func($this->prefix, $file['name']); } elseif (is_string($this->prefix)) { $prefix = (string) $this->prefix; } // if overwrite is not allowed, check if the file is already in the container if (!$this->overwrite) { if ($this->container->has($prefix . $file['name'])) { // add the timestamp to ensure the file is unique // method is not bulletproof but it's pretty safe $file['name'] = time() . '_' . $file['name']; } } // attempt to move the uploaded file into the container if (!$this->container->moveUploadedFile($file['tmp_name'], $prefix . $file['name'])) { $file['name'] = false; return $file; } $file['name'] = $prefix . $file['name']; // create the lock file if autoconfirm is disabled if (!$this->autoconfirm) { $this->container->save($file['name'] . '.lock', (string) time()); } return $file; }
php
{ "resource": "" }
q262037
Handler.validateFile
test
protected function validateFile($file) { if (!$this->validator->validate($file)) { $file['messages'] = $this->validator->getMessages(); } return $file; }
php
{ "resource": "" }
q262038
Handler.sanitizeFileName
test
protected function sanitizeFileName($name) { if ($this->sanitizerCallback) { return call_user_func($this->sanitizerCallback, $name); } return preg_replace('/[^A-Za-z0-9\.]+/', '_', $name); }
php
{ "resource": "" }
q262039
Local.delete
test
public function delete($file) { $file = $this->normalizePath($file); if (file_exists($this->baseDirectory . $file)) { return unlink($this->baseDirectory . $file); } return true; }
php
{ "resource": "" }
q262040
Local.moveUploadedFile
test
public function moveUploadedFile($localFile, $destination) { $dir = dirname($this->baseDirectory . $destination); if (file_exists($localFile) && $this->ensureDirectory($dir)) { /** * we could use is_uploaded_file() and move_uploaded_file() * but in case of ajax uploads that would fail */ if (is_readable($localFile)) { // rename() would be good but this is better because $localFile may become 'unwritable' $result = copy($localFile, $this->baseDirectory . $destination); @unlink($localFile); return $result; } } return false; }
php
{ "resource": "" }
q262041
Theme.getList
test
public function getList() { // read theme path $path = $this->app['config']->get('theme.path', base_path('resources/themes')); if (file_exists($path)) { $dir_list = dir($path); while (false !== ($entry = $dir_list->read())) { if (file_exists($path . '/' . $entry . '/' . 'config.php')) $list[] = $entry; } } return $list; }
php
{ "resource": "" }
q262042
Theme.asset
test
public function asset($path, $secure = null, $version = false) { if (!$this->theme) throw new ThemeException('Theme should be init first'); $full_path = $this->_assetFullpath($path); $asset = $this->app['url']->asset($full_path, $secure); if ($version) { if (is_bool($version)) { $asset .= '?v=' . $this->_assetVersion($path); } else { $asset .= '?v=' . $version; } } return $asset; }
php
{ "resource": "" }
q262043
Theme._assetVersion
test
private function _assetVersion($path) { $full_path = $this->_assetFullpath($path); $file_path = public_path($full_path); if (file_exists($file_path)) { return filemtime($file_path); } return null; }
php
{ "resource": "" }
q262044
ThemeDestroyCommand.getPath
test
protected function getPath($path) { $rootPath = $this->config->get('theme::path', base_path('resources/themes')); return $rootPath.'/'.strtolower($this->getTheme()).'/' . $path; }
php
{ "resource": "" }
q262045
ThemeGeneratorCommand.makeDir
test
protected function makeDir($path) { if ( ! $this->files->isDirectory($path)) { $this->files->makeDirectory($path, 0777, true); } }
php
{ "resource": "" }
q262046
ThemeGeneratorCommand.makeFile
test
protected function makeFile($file, $template = null, $assets = false) { if ( ! $this->files->exists($this->getPath($file))) { $content = $assets ? $this->getAssetsPath($file, true) : $this->getPath($file); $this->files->put($content, $template); } }
php
{ "resource": "" }
q262047
ThemeGeneratorCommand.getAssetsPath
test
protected function getAssetsPath($path, $absolute = true) { $rootPath = $this->config->get('theme.assets_path', 'assets/themes'); if ($absolute) $rootPath = public_path($rootPath); return $rootPath.'/'.strtolower($this->getTheme()).'/' . $path; }
php
{ "resource": "" }
q262048
ThemeGeneratorCommand.getTemplate
test
protected function getTemplate($template, $replacements = array()) { $path = realpath(__DIR__ . '/../templates/' . $template . '.txt'); $content = $this->files->get($path); if (!empty($replacements)) { $content = str_replace(array_keys($replacements), array_values($replacements), $content); } return $content; }
php
{ "resource": "" }
q262049
ProfilerController.createAssetsAction
test
public function createAssetsAction(Request $request, $token) { if (!$request->isXmlHttpRequest()) { return $this->redirectToRoute('_profiler', ['token' => $token]); } $messages = $this->getSelectedMessages($request, $token); if ($messages instanceof Data) { $messages = $messages->getValue(true); } if (empty($messages)) { return new Response('No translations selected.'); } $uploaded = array(); $trans = $this->get('happyr.translation'); foreach ($messages as $message) { if ($trans->createAsset($message)) { $uploaded[] = $message; } } $saved = count($uploaded); if ($saved > 0) { $this->get('happyr.translation.filesystem')->updateMessageCatalog($uploaded); } return new Response(sprintf('%s new assets created!', $saved)); }
php
{ "resource": "" }
q262050
Loco.fetchTranslation
test
public function fetchTranslation(Message $message, $updateFs = false) { $project = $this->getProject($message); try { $resource = sprintf('translations/%s/%s', $message->getId(), $message->getLocale()); $response = $this->makeApiRequest($project['api_key'], 'GET', $resource); } catch (HttpException $e) { if ($e->getCode() === 404) { //Message does not exist return; } throw $e; } $logoTranslation = $response['translation']; $messageTranslation = $message->getTranslation(); $message->setTranslation($logoTranslation); // update filesystem if ($updateFs && $logoTranslation !== $messageTranslation) { $this->filesystemService->updateMessageCatalog([$message]); } return $logoTranslation; }
php
{ "resource": "" }
q262051
Loco.updateTranslation
test
public function updateTranslation(Message $message) { $project = $this->getProject($message); try { $resource = sprintf('translations/%s/%s', $message->getId(), $message->getLocale()); $this->makeApiRequest($project['api_key'], 'POST', $resource, $message->getTranslation()); } catch (HttpException $e) { if ($e->getCode() === 404) { //Asset does not exist if ($this->createAsset($message)) { //Try again return $this->updateTranslation($message); } return false; } throw $e; } $this->filesystemService->updateMessageCatalog([$message]); return true; }
php
{ "resource": "" }
q262052
Loco.flagTranslation
test
public function flagTranslation(Message $message, $type = 0) { $project = $this->getProject($message); $flags = ['fuzzy', 'incorrect', 'provisional', 'unapproved', 'incomplete']; try { $resource = sprintf('translations/%s/%s/flag', $message->getId(), $message->getLocale()); $this->makeApiRequest($project['api_key'], 'POST', $resource, ['flag' => $flags[$type]]); } catch (HttpException $e) { if ($e->getCode() === 404) { //Message does not exist return false; } throw $e; } return true; }
php
{ "resource": "" }
q262053
Loco.createAsset
test
public function createAsset(Message $message) { $project = $this->getProject($message); try { $response = $this->makeApiRequest($project['api_key'], 'POST', 'assets', [ 'id' => $message->getId(), 'name' => $message->getId(), 'type' => 'text', // Tell Loco not to translate the asset 'default' => 'untranslated', ]); if ($message->hasParameters()) { // Send those parameter as a note to Loco $notes = ''; foreach ($message->getParameters() as $key => $value) { if (!is_array($value)) { $notes .= 'Parameter: ' . $key . ' (i.e. : ' . $value . ")\n"; } else { foreach ($value as $k => $v) { $notes .= 'Parameter: ' . $k . ' (i.e. : ' . $v . ")\n"; } } } $resource = sprintf('assets/%s.json', $message->getId()); $this->makeApiRequest($project['api_key'], 'PATCH', $resource, ['notes' => $notes], 'json'); } } catch (HttpException $e) { if ($e->getCode() === 409) { //conflict.. ignore return false; } throw $e; } // if this project has multiple domains. Make sure to tag it if (!empty($project['domains'])) { $this->addTagToAsset($project, $response['id'], $message->getDomain()); } return true; }
php
{ "resource": "" }
q262054
Loco.downloadAllTranslations
test
public function downloadAllTranslations() { $data = []; foreach ($this->projects as $name => $config) { if (empty($config['domains'])) { $this->getUrls($data, $config, $name, false); } else { foreach ($config['domains'] as $domain) { $this->getUrls($data, $config, $domain, true); } } } $this->requestManager->downloadFiles($this->filesystemService, $data); }
php
{ "resource": "" }
q262055
Loco.uploadAllTranslations
test
public function uploadAllTranslations() { foreach ($this->projects as $name => $config) { if (empty($config['domains'])) { $this->doUploadDomains($config, $name, false); } else { foreach ($config['domains'] as $domain) { $this->doUploadDomains($config, $domain, true); } } } }
php
{ "resource": "" }
q262056
Loco.synchronizeAllTranslations
test
public function synchronizeAllTranslations() { foreach ($this->projects as $name => $config) { if (empty($config['domains'])) { $this->doSynchronizeDomain($config, $name, false); } else { foreach ($config['domains'] as $domain) { $this->doSynchronizeDomain($config, $domain, true); } } } }
php
{ "resource": "" }
q262057
FilesystemUpdater.onTerminate
test
public function onTerminate(Event $event) { if (empty($this->messages)) { return; } /** @var MessageCatalogue[] $catalogues */ $catalogues = array(); foreach ($this->messages as $m) { $key = $m->getLocale().$m->getDomain(); if (!isset($catalogues[$key])) { $file = sprintf('%s/%s.%s.%s', $this->targetDir, $m->getDomain(), $m->getLocale(), $this->getFileExtension()); try { $catalogues[$key] = $this->loader->load($file, $m->getLocale(), $m->getDomain()); } catch (NotFoundResourceException $e) { $catalogues[$key] = new MessageCatalogue($m->getLocale()); } } $translation = $m->getTranslation(); if (empty($translation)) { if ($this->syncEmptyTranslations) { $translation = sprintf('[%s]', $m->getId()); } else { continue; } } $catalogues[$key]->set($m->getId(), $translation, $m->getDomain()); } foreach ($catalogues as $catalogue) { try { $this->dumper->dump($catalogue, ['path' => $this->targetDir]); } catch (\ErrorException $e) { // Could not save file // TODO better error handling throw $e; } } }
php
{ "resource": "" }
q262058
HappyrTranslationExtension.copyValuesFromParentToProject
test
private function copyValuesFromParentToProject($key, array &$config) { if (empty($config[$key])) { return; } foreach ($config['projects'] as &$project) { if (empty($project[$key])) { $project[$key] = $config[$key]; } } }
php
{ "resource": "" }
q262059
ContentSecurityPolicyHeaderBuilder.addHash
test
public function addHash($type, $hash) { $directive = self::DIRECTIVE_SCRIPT_SRC; if (!(isset($this->directives[$directive]) && is_array($this->directives[$directive]))) { $this->directives[$directive] = []; } if (!(isset($this->directives[$directive]['hashes']) && is_array($this->directives[$directive]['hashes']))) { $this->directives[$directive]['hashes'] = []; } $this->directives[$directive]['hashes'][$type][] = $hash; }
php
{ "resource": "" }
q262060
ContentSecurityPolicyHeaderBuilder.getValue
test
public function getValue() { $directives = []; foreach ($this->directives as $name => $value) { $directives[] = sprintf('%s %s', $name, $this->parseDirectiveValue($value)); } if (!is_null($this->reflectedXssValue)) { $directives[] = sprintf('%s %s', 'reflected-xss', $this->reflectedXssValue); } if ($this->upgradeInsecureRequests) { $directives[] = $this->upgradeInsecureRequestsDirective; } if (!is_null($this->referrerValue)) { $directives[] = sprintf('%s %s', 'referrer', $this->referrerValue); } if (!is_null($this->reportUri)) { $directives[] = sprintf('%s %s', 'report-uri', $this->reportUri); } // No CSP policies set? if (count($directives) < 1) { return null; } return trim(sprintf('%s%s', implode($this->directiveSeparator, $directives), $this->directiveSeparator)); }
php
{ "resource": "" }
q262061
ClassFinder.searchClassMap
test
protected function searchClassMap() { foreach ($this->composer->getClassMap() as $fqcn => $file) { if (Str::s($fqcn)->is($this->namespace.'*')) { $this->foundClasses[realpath($file)] = $fqcn; } } }
php
{ "resource": "" }
q262062
ClassFinder.searchPsrMaps
test
protected function searchPsrMaps() { $prefixes = array_merge ( $this->composer->getPrefixes(), $this->composer->getPrefixesPsr4() ); $trimmedNs = Str::s($this->namespace)->trimRight('\\'); $nsSegments = $trimmedNs->split('\\'); foreach ($prefixes as $ns => $dirs) { $foundSegments = Str::s($ns)->trimRight('\\') ->longestCommonPrefix($trimmedNs)->split('\\'); foreach ($foundSegments as $key => $segment) { if ((string) $nsSegments[$key] !== (string) $segment) { continue 2; } } foreach ($dirs as $dir) { foreach ((new Finder)->in($dir)->files()->name('*.php') as $file) { if ($file instanceof SplFileInfo) { $fqcn = (string)Str::s($file->getRelativePathname()) ->trimRight('.php') ->replace('/', '\\') ->ensureLeft($ns); if (Str::s($fqcn)->is($this->namespace.'*')) { $this->foundClasses[$file->getRealPath()] = $fqcn; } } } } } }
php
{ "resource": "" }
q262063
ProjectRepository.afterSave
test
public function afterSave($project, $attributes) { // if "relation" is not present in the input, we simply detach all // related models by passing an empty array. $ids = isset($attributes['relation']) ? $attributes['relation'] : []; $project->manyToManyRelation()->sync($ids); }
php
{ "resource": "" }
q262064
ProjectRepository.beforeQuery
test
protected function beforeQuery($query, $many) { // if this->active has been set to something, we add it to the query if ($this->active !== null) { $query->where('is_active', '=', $this->active); } // we want to always eager load members and comments. $query->with('members', 'comments'); // let's say guests can only view projects with access level 1 or less. if (!$this->user) { $query->where('access_level', '<=', 1); } // unless user is an admin, we restrict every query to only show // projects with access_level lower than the logged in user's. else if (!$this->user->isAdmin()) { $query->where('access_level', '<=', $user->access_level); } }
php
{ "resource": "" }
q262065
ProjectRepository.afterQuery
test
protected function afterQuery($result) { // $result can be a single model, a paginator or a collection. We can // standardize the variable in this way to be able to use the same code // on all three types. if ($result instanceof \Illuminate\Database\Eloquent\Model) { // we might just do `return;` here if we didn't want our logic // applied to a single model. $projects = $result->newCollection([$result]); } else if ($result instanceof \Illuminate\Pagination\Paginator) { $projects = $result->getCollection(); } // let's say we want to add some data onto the models after they've // been retrieved from the database. we want to add the count of a // relation, but don't want to mess with sub-selects and don't want to // waste memory by eager loading the relation, nor do we want to run // one query for each model. // build the query that gets the relationship count. some of this logic // could be moved into model scopes if you want. this is a rather // complex query so if you don't understand what is going on here, // don't worry too much. basically just getting the number of relations // attached to each project. $results = $this->model->relation() ->getRelated()->newQuery() ->whereIn('parent_id', $projects->lists('id')) ->selectRaw('parent_id, count(*) as relation_count') ->groupBy('parent_id') ->lists('relation_count', 'parent_id'); // now add the attribute to each model. $projects->each(function($project) { $project->relation_count = $results[$project->id]; }); }
php
{ "resource": "" }
q262066
ItemRepository.syncNewWastageItems
test
public function syncNewWastageItems(WastageModel $wastage, Collection $products, array $items) { $this->setWastage($wastage); $itemModels = []; foreach ($items as $key => $value) { $data = $this->buildItemData($key, $value, $products); $item = $this->create($data); $itemModels[] = $item; } return $itemModels; }
php
{ "resource": "" }
q262067
ItemRepository.syncExistingWastageItems
test
public function syncExistingWastageItems(WastageModel $wastage, Collection $products, array $items) { $itemModels = []; foreach ($items as $key => $value) { if ($item = $this->findProductItem($wastage->items, $key)) { $this->checkIntegrity($item); $item->update($value); } else { $data = $this->buildItemData($key, $value, $products); $item = $this->create($data); } $itemModels[] = $item; } return $itemModels; }
php
{ "resource": "" }
q262068
ItemRepository.findProductItem
test
protected function findProductItem(Collection $items, $key) { if ($key instanceof ItemModel) { $key = $key->getKey(); } return $items->first(function($id, $item) use($key) { return $item->product_id == $key; }); }
php
{ "resource": "" }
q262069
ItemRepository.checkIntegrity
test
protected function checkIntegrity(ItemModel $item) { if ($item->department_id < 1) { $item->department()->associate($this->department); } if ($item->wastage_id < 1) { $item->wastage()->associate($this->wastage); } }
php
{ "resource": "" }
q262070
ItemRepository.buildItemData
test
protected function buildItemData($key, array $data, Collection $products) { if (!$product = $products->find($key)) { throw new \RuntimeException("ID $key not found in products collection"); } $this->setProduct($product); if (!empty($data['purchased_amount'])) { $data['purchased_for'] = $product->in_price; } if (!empty($data['sold_amount'])) { $data['sold_for'] = $product->out_price; } return $data; }
php
{ "resource": "" }
q262071
DatabaseRepository.fillEntityAttributes
test
protected function fillEntityAttributes($entity, array $attributes) { foreach ($attributes as $key => $value) { $entity->$key = $value; } }
php
{ "resource": "" }
q262072
AbstractRepository.setupDefaultCriteria
test
protected function setupDefaultCriteria() { $defaultCriteria = $this->defaultCriteria; $this->defaultCriteria = []; foreach ($defaultCriteria as $criteria) { $this->addDefaultCriteria(new $criteria); } }
php
{ "resource": "" }
q262073
AbstractRepository.perform
test
protected function perform($action, $object, $attributes = array(), $validate = true) { $perform = 'perform' . ucfirst($action); if (!method_exists($this, $perform)) { throw new \BadMethodCallException("Method $perform does not exist on this class"); } if ($validate === true) { if ($this->validateEntity) { if (!$this->valid($action, $this->getEntityAttributes($object))) return false; } else { if (!$this->valid($action, $attributes)) return false; } } $beforeResult = $this->doBefore($action, $object, $attributes); if ($beforeResult === false) return $beforeResult; $result = call_user_func_array([$this, $perform], [$object, $attributes]); if ($result === false) return $result; $this->doAfter($action, $result, $attributes); return $result; }
php
{ "resource": "" }
q262074
AbstractRepository.doBeforeOrAfter
test
protected function doBeforeOrAfter($which, $action, array $args) { $method = $which.ucfirst($action); if (method_exists($this, $method)) { $result = call_user_func_array([$this, $method], $args); if ($result === false) return $result; } return null; }
php
{ "resource": "" }
q262075
AbstractRepository.valid
test
public function valid($action, array $attributes) { if ($this->validator === null) { return true; } $result = $this->validator->valid($action, $attributes); if ($result === false) { $this->errors->merge($this->validator->getErrors()); } return $result; }
php
{ "resource": "" }
q262076
AbstractRepository.performQuery
test
protected function performQuery($query, $many) { $this->applyCriteria($query); if ($many === false) { $result = $this->getRegularQueryResults($query, false); if (!$result && $this->throwExceptions === true) { throw $this->getNotFoundException($query); } return $result; } return $this->paginate === false ? $this->getRegularQueryResults($query, true) : $this->getPaginatedQueryResults($query); }
php
{ "resource": "" }
q262077
AbstractRepository.paginate
test
public function paginate($toggle) { $this->paginate = $toggle === false ? false : (int) $toggle; return $this; }
php
{ "resource": "" }
q262078
AbstractRepository.toggleExceptions
test
public function toggleExceptions($toggle, $toggleValidator = true) { $this->throwExceptions = (bool) $toggle; if ($this->validator && $toggleValidator) { $this->validator->toggleExceptions((bool) $toggle); } return $this; }
php
{ "resource": "" }
q262079
AbstractRepository.applyCriteria
test
public function applyCriteria($query) { foreach ($this->defaultCriteria as $criteria) { $criteria->apply($query); } if (empty($this->criteria)) return; foreach ($this->criteria as $criteria) { $criteria->apply($query); } if ($this->resetCriteria) { $this->resetCriteria(); } }
php
{ "resource": "" }
q262080
AbstractRepository.update
test
public function update($entity, array $attributes) { if ($this->validator) { $this->validator->replace('key', $this->getEntityKey($entity)); } return $this->perform('update', $entity, $attributes, true) ? true : false; }
php
{ "resource": "" }
q262081
AbstractRepository.fetchList
test
protected function fetchList($query, $column = 'id', $key = null) { $this->doBefore('query', $query, true); $this->applyCriteria($query); return $query->lists($column, $key); }
php
{ "resource": "" }
q262082
AbstractRepository.findByKey
test
public function findByKey($key) { $query = $this->newQuery() ->where($this->getKeyName(), '=', $key); return $this->fetchSingle($query); }
php
{ "resource": "" }
q262083
AbstractRepository.findByCriteria
test
public function findByCriteria(CriteriaInterface $criteria) { $this->resetCriteria(); $this->pushCriteria($criteria); return $this->fetchSingle($this->newQuery()); }
php
{ "resource": "" }
q262084
AbstractRepository.getByCriteria
test
public function getByCriteria(CriteriaInterface $criteria) { $this->resetCriteria(); $this->pushCriteria($criteria); return $this->fetchMany($this->newQuery()); }
php
{ "resource": "" }
q262085
AbstractRepository.getByKeys
test
public function getByKeys(array $keys) { if (count($keys) < 1) { throw new \InvalidArgumentException('Cannot getByKeys with an empty array'); } $query = $this->newQuery() ->whereIn($this->getKeyName(), $keys); return $this->fetchMany($query); }
php
{ "resource": "" }
q262086
AbstractRepository.getList
test
public function getList($column = 'id', $key = null) { return $this->fetchList($this->newQuery(), $column, $key); }
php
{ "resource": "" }
q262087
AbstractRepository.newAttributesQuery
test
protected function newAttributesQuery(array $attributes, $operator = '=') { $query = $this->newQuery(); foreach ($attributes as $key => $value) { $query->where($key, $operator, $value); } return $query; }
php
{ "resource": "" }
q262088
Config.replaceConfigValuePlaceholders
test
private function replaceConfigValuePlaceholders($value) { if (is_array($value)) { foreach ($value as $subKey => $subValue) { $value[$subKey] = $this->replaceConfigValuePlaceholders($subValue); } } else { // replace environment variable if (preg_match(self::ENV_PARAMETER_PATTERN, $value, $matches)) { $envValue = getenv($matches[1]); if ($envValue === false) { throw new \RuntimeException(sprintf( 'No environment variable found with name %s', $matches[1] )); } $value = $envValue; } } return $value; }
php
{ "resource": "" }
q262089
HttpViewResolver.setViewPath
test
public function setViewPath($path) { $len = strlen($path) - 1; if ($path[$len] == '/') { $path = substr($path, 0, -1); } $realpath = realpath($path);; $this->_path = $realpath === false ? $path : $realpath; }
php
{ "resource": "" }
q262090
sendfile.send
test
public function send($file_path, $withDisposition=TRUE) { if (!is_readable($file_path)) { throw new \Exception('File not found or inaccessible!'); } $size = filesize($file_path); if (!$this->disposition) { $this->disposition = $this->name($file_path); } if (!$this->type) { $this->type = $this->getContentType($file_path); } //turn off output buffering to decrease cpu usage $this->cleanAll(); // required for IE, otherwise Content-Disposition may be ignored if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } header('Content-Type: ' . $this->type); if ($withDisposition) { header('Content-Disposition: attachment; filename="' . $this->disposition . '"'); } header('Accept-Ranges: bytes'); // The three lines below basically make the // download non-cacheable header("Cache-control: private"); header('Pragma: private'); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // multipart-download and download resuming support if (isset($_SERVER['HTTP_RANGE'])) { list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2); list($range) = explode(",", $range, 2); list($range, $range_end) = explode("-", $range); $range = intval($range); if (!$range_end) { $range_end = $size - 1; } else { $range_end = intval($range_end); } $new_length = $range_end - $range + 1; header("HTTP/1.1 206 Partial Content"); header("Content-Length: $new_length"); header("Content-Range: bytes $range-$range_end/$size"); } else { $new_length = $size; header("Content-Length: " . $size); } /* output the file itself */ $chunksize = $this->bytes; //you may want to change this $bytes_send = 0; $file = @fopen($file_path, 'rb'); if ($file) { if (isset($_SERVER['HTTP_RANGE'])) { fseek($file, $range); } while (!feof($file) && (!connection_aborted()) && ($bytes_send < $new_length) ) { $buffer = fread($file, $chunksize); echo($buffer); //echo($buffer); // is also possible flush(); usleep($this->sec * 1000000); $bytes_send += strlen($buffer); } fclose($file); } else { throw new \Exception('Error - can not open file.'); } }
php
{ "resource": "" }
q262091
sendfile.getContentType
test
private function getContentType($path) { $result = false; if (is_file($path) === true) { if (function_exists('finfo_open') === true) { $finfo = finfo_open(FILEINFO_MIME_TYPE); if (is_resource($finfo) === true) { $result = finfo_file($finfo, $path); } finfo_close($finfo); } else if (function_exists('mime_content_type') === true) { $result = preg_replace('~^(.+);.*$~', '$1', mime_content_type($path)); } else if (function_exists('exif_imagetype') === true) { $result = image_type_to_mime_type(exif_imagetype($path)); } } return $result; }
php
{ "resource": "" }
q262092
HttpExceptionMapper.map
test
public function map(Action $action) { $exception = $action->getArguments(); $exception = $exception['exception']; $this->_logger->debug('Exception mapper invoked with: ' . $action->getId()); // Lookup a controller that can handle this url. foreach ($this->_map as $map) { $controllerException = $map[0]; $controller = $map[1]; if (!($exception instanceof $controllerException)) { continue; } return new DispatchInfo( $action, $controller, str_replace('\\', '_', $controllerException) . 'Exception' ); } return false; }
php
{ "resource": "" }
q262093
AspectManager.setAspect
test
public function setAspect(AspectDefinition $aspect) { $name = $aspect->getName(); $this->_aspects[$name] = $aspect; $this->_cache->store('AspectManagerAspect' . $name, $aspect); $this->_cache->store('Aspects', $this->_aspects); }
php
{ "resource": "" }
q262094
AspectManager.setPointcut
test
public function setPointcut(PointcutDefinition $pointcut) { $name = $pointcut->getName(); $this->_pointcuts[$name] = $pointcut; $this->_cache->store('AspectManagerPointcut' . $name, $pointcut); }
php
{ "resource": "" }
q262095
AspectManager.getPointcut
test
public function getPointcut($pointcut) { if (isset($this->_pointcuts[$pointcut])) { return $this->_pointcuts[$pointcut]; } else { $result = false; $value = $this->_cache->fetch('AspectManagerPointcut' . $pointcut, $result); if ($result === true) { $this->_pointcuts[$pointcut] = $value; return $value; } else { foreach ($this->_pointcutProviders as $provider) { $value = $provider->getPointcut($pointcut); if ($value !== false) { $this->setPointcut($value); return $value; } } } } return false; }
php
{ "resource": "" }
q262096
AnnotationDiscovererDriver._getCandidateFilesForClassScanning
test
private function _getCandidateFilesForClassScanning($path) { $cacheKey = "$path.candidatefiles"; $result = false; $files = $this->_cache->fetch($cacheKey, $result); if ($result === true) { return $files; } $files = array(); if (is_dir($path)) { foreach (scandir($path) as $entry) { if ($entry == '.' || $entry == '..') { continue; } $entry = "$path/$entry"; foreach ($this->_getCandidateFilesForClassScanning($entry) as $file) { $files[] = $file; } } } else if ($this->_isScannable($path)) { $files[] = realpath($path); } $this->_cache->store($cacheKey, $files); return $files; }
php
{ "resource": "" }
q262097
AnnotationDiscovererDriver._isScannable
test
private function _isScannable($path) { $extensionPos = strrpos($path, '.'); if ($extensionPos === false) { return false; } if (substr($path, $extensionPos, 4) != '.php') { return false; } return true; }
php
{ "resource": "" }
q262098
ErrorInfo.typeToString
test
public static function typeToString($type) { switch($type) { case E_USER_ERROR: return 'User Error'; case E_USER_WARNING: return 'User Warning'; case E_USER_NOTICE: return 'User Notice'; case E_USER_DEPRECATED: return 'User deprecated'; case E_DEPRECATED: return 'Deprecated'; case E_RECOVERABLE_ERROR: return 'Recoverable error'; case E_STRICT: return 'Strict'; case E_WARNING: return 'Warning'; case E_NOTICE: return 'Notice'; case E_ERROR: return 'Error'; default: return 'Unknown'; } }
php
{ "resource": "" }
q262099
Dispatcher.dispatch
test
public function dispatch(DispatchInfo $dispatchInfo) { $controller = $dispatchInfo->handler; $actionHandler = $dispatchInfo->method; $action = $dispatchInfo->action; if (!method_exists($controller, $actionHandler)) { throw new MvcException('No valid action handler found: ' . $actionHandler); } $interceptors = $dispatchInfo->interceptors; $filtersPassed = true; $result = false; foreach ($interceptors as $interceptor) { $this->_logger->debug("Running pre filter: " . get_class($interceptor)); $result = $interceptor->preHandle($action, $controller); if ($result === false) { $filtersPassed = false; $this->_logger->debug("Filter returned false, stopping dispatch"); break; } else if ($result instanceof ModelAndView) { return $result; } } if ($filtersPassed) { $result = $this->invokeAction($controller, $actionHandler, $action->getArguments()); foreach ($interceptors as $interceptor) { $this->_logger->debug("Running post filter: " . get_class($interceptor)); $interceptor->postHandle($action, $controller); } } return $result; }
php
{ "resource": "" }