_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13700 | User.getAvatarUrlAttribute | train | public function getAvatarUrlAttribute(string $value = null)
{
if ($value && strpos($value, '://') === false) {
return app(UrlGenerator::class)->to('forum')->path('assets/avatars/'.$value);
}
return $value;
} | php | {
"resource": ""
} |
q13701 | User.checkPassword | train | public function checkPassword($password)
{
$valid = static::$dispatcher->until(new CheckingPassword($this, $password));
if ($valid !== null) {
return $valid;
}
return static::$hasher->check($password, $this->password);
} | php | {
"resource": ""
} |
q13702 | User.activate | train | public function activate()
{
if ($this->is_email_confirmed !== true) {
$this->is_email_confirmed = true;
$this->raise(new Activated($this));
}
return $this;
} | php | {
"resource": ""
} |
q13703 | User.hasPermission | train | public function hasPermission($permission)
{
if ($this->isAdmin()) {
return true;
}
if (is_null($this->permissions)) {
$this->permissions = $this->getPermissions();
}
return in_array($permission, $this->permissions);
} | php | {
"resource": ""
} |
q13704 | User.hasPermissionLike | train | public function hasPermissionLike($match)
{
if ($this->isAdmin()) {
return true;
}
if (is_null($this->permissions)) {
$this->permissions = $this->getPermissions();
}
foreach ($this->permissions as $permission) {
if (substr($permission, -strlen($match)) === $match) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q13705 | User.getUnreadNotifications | train | protected function getUnreadNotifications()
{
static $cached = null;
if (is_null($cached)) {
$cached = $this->notifications()
->whereIn('type', $this->getAlertableNotificationTypes())
->whereNull('read_at')
->where('is_deleted', false)
->whereSubjectVisibleTo($this)
->get();
}
return $cached;
} | php | {
"resource": ""
} |
q13706 | User.getNewNotificationCount | train | public function getNewNotificationCount()
{
return $this->getUnreadNotifications()->filter(function ($notification) {
return $notification->created_at > $this->read_notifications_at ?: 0;
})->count();
} | php | {
"resource": ""
} |
q13707 | User.getPreferencesAttribute | train | public function getPreferencesAttribute($value)
{
$defaults = array_map(function ($value) {
return $value['default'];
}, static::$preferences);
$user = array_only((array) json_decode($value, true), array_keys(static::$preferences));
return array_merge($defaults, $user);
} | php | {
"resource": ""
} |
q13708 | User.setPreference | train | public function setPreference($key, $value)
{
if (isset(static::$preferences[$key])) {
$preferences = $this->preferences;
if (! is_null($transformer = static::$preferences[$key]['transformer'])) {
$preferences[$key] = call_user_func($transformer, $value);
} else {
$preferences[$key] = $value;
}
$this->preferences = $preferences;
}
return $this;
} | php | {
"resource": ""
} |
q13709 | User.permissions | train | public function permissions()
{
$groupIds = [Group::GUEST_ID];
// If a user's account hasn't been activated, they are essentially no
// more than a guest. If they are activated, we can give them the
// standard 'member' group, as well as any other groups they've been
// assigned to.
if ($this->is_email_confirmed) {
$groupIds = array_merge($groupIds, [Group::MEMBER_ID], $this->groups->pluck('id')->all());
}
event(new PrepareUserGroups($this, $groupIds));
return Permission::whereIn('group_id', $groupIds);
} | php | {
"resource": ""
} |
q13710 | CookieFactory.make | train | public function make($name, $value = null, $maxAge = null)
{
$cookie = SetCookie::create($this->getName($name), $value);
// Make sure we send both the MaxAge and Expires parameters (the former
// is not supported by all browser versions)
if ($maxAge) {
$cookie = $cookie
->withMaxAge($maxAge)
->withExpires(time() + $maxAge);
}
if ($this->domain != null) {
$cookie = $cookie->withDomain($this->domain);
}
return $cookie
->withPath($this->path)
->withSecure($this->secure)
->withHttpOnly(true);
} | php | {
"resource": ""
} |
q13711 | UserRepository.getIdForUsername | train | public function getIdForUsername($username, User $actor = null)
{
$query = User::where('username', 'like', $username);
return $this->scopeVisibleTo($query, $actor)->value('id');
} | php | {
"resource": ""
} |
q13712 | UserRepository.getIdsForUsername | train | public function getIdsForUsername($string, User $actor = null)
{
$string = $this->escapeLikeString($string);
$query = User::where('username', 'like', '%'.$string.'%')
->orderByRaw('username = ? desc', [$string])
->orderByRaw('username like ? desc', [$string.'%']);
return $this->scopeVisibleTo($query, $actor)->pluck('id')->all();
} | php | {
"resource": ""
} |
q13713 | Group.rename | train | public function rename($nameSingular, $namePlural)
{
$this->name_singular = $nameSingular;
$this->name_plural = $namePlural;
$this->raise(new Renamed($this));
return $this;
} | php | {
"resource": ""
} |
q13714 | Group.hasPermission | train | public function hasPermission($permission)
{
if ($this->id == self::ADMINISTRATOR_ID) {
return true;
}
return $this->permissions->contains('permission', $permission);
} | php | {
"resource": ""
} |
q13715 | RegistrationToken.generate | train | public static function generate(string $provider, string $identifier, array $attributes, array $payload)
{
$token = new static;
$token->token = str_random(40);
$token->provider = $provider;
$token->identifier = $identifier;
$token->user_attributes = $attributes;
$token->payload = $payload;
$token->created_at = Carbon::now();
return $token;
} | php | {
"resource": ""
} |
q13716 | DispatchRoute.process | train | public function process(Request $request, Handler $handler): Response
{
$method = $request->getMethod();
$uri = $request->getUri()->getPath() ?: '/';
$routeInfo = $this->getDispatcher()->dispatch($method, $uri);
switch ($routeInfo[0]) {
case Dispatcher::NOT_FOUND:
throw new RouteNotFoundException($uri);
case Dispatcher::METHOD_NOT_ALLOWED:
throw new MethodNotAllowedException($method);
case Dispatcher::FOUND:
$handler = $routeInfo[1];
$parameters = $routeInfo[2];
return $handler($request, $parameters);
}
} | php | {
"resource": ""
} |
q13717 | PostRepository.findOrFail | train | public function findOrFail($id, User $actor = null)
{
return $this->queryVisibleTo($actor)->findOrFail($id);
} | php | {
"resource": ""
} |
q13718 | PostRepository.findByIds | train | public function findByIds(array $ids, User $actor = null)
{
$posts = $this->queryIds($ids, $actor)->get();
$posts = $posts->sort(function ($a, $b) use ($ids) {
$aPos = array_search($a->id, $ids);
$bPos = array_search($b->id, $ids);
if ($aPos === $bPos) {
return 0;
}
return $aPos < $bPos ? -1 : 1;
});
return $posts;
} | php | {
"resource": ""
} |
q13719 | PostRepository.filterVisibleIds | train | public function filterVisibleIds(array $ids, User $actor)
{
return $this->queryIds($ids, $actor)->pluck('posts.id')->all();
} | php | {
"resource": ""
} |
q13720 | PostRepository.getIndexForNumber | train | public function getIndexForNumber($discussionId, $number, User $actor = null)
{
$query = Discussion::find($discussionId)
->posts()
->whereVisibleTo($actor)
->where('created_at', '<', function ($query) use ($discussionId, $number) {
$query->select('created_at')
->from('posts')
->where('discussion_id', $discussionId)
->whereNotNull('number')
->take(1)
// We don't add $number as a binding because for some
// reason doing so makes the bindings go out of order.
->orderByRaw('ABS(CAST(number AS SIGNED) - '.(int) $number.')');
});
return $query->count();
} | php | {
"resource": ""
} |
q13721 | SelfDemotionGuard.handle | train | public function handle(Saving $event)
{
// Non-admin users pose no problem
if (! $event->actor->isAdmin()) {
return;
}
// Only admins can demote users, which means demoting other users is
// fine, because we still have at least one admin (the actor) left
if ($event->actor->id !== $event->user->id) {
return;
}
$groups = array_get($event->data, 'relationships.groups.data');
// If there is no group data (not even an empty array), this means
// groups were not changed (and thus not removed) - we're fine!
if (! isset($groups)) {
return;
}
$adminGroups = array_filter($groups, function ($group) {
return $group['id'] == Group::ADMINISTRATOR_ID;
});
// As long as the user is still part of the admin group, all is good
if ($adminGroups) {
return;
}
// If we get to this point, we have to prohibit the edit
throw new PermissionDeniedException;
} | php | {
"resource": ""
} |
q13722 | GambitManager.apply | train | public function apply(AbstractSearch $search, $query)
{
$query = $this->applyGambits($search, $query);
if ($query) {
$this->applyFulltext($search, $query);
}
} | php | {
"resource": ""
} |
q13723 | Guest.getGroupsAttribute | train | public function getGroupsAttribute()
{
if (! isset($this->attributes['groups'])) {
$this->attributes['groups'] = $this->relations['groups'] = Group::where('id', Group::GUEST_ID)->get();
}
return $this->attributes['groups'];
} | php | {
"resource": ""
} |
q13724 | InfoCommand.findPackageVersion | train | private function findPackageVersion($path, $fallback = null)
{
if (file_exists("$path/.git")) {
$cwd = getcwd();
chdir($path);
$output = [];
$status = null;
exec('git rev-parse HEAD 2>&1', $output, $status);
chdir($cwd);
if ($status == 0) {
return isset($fallback) ? "$fallback ($output[0])" : $output[0];
}
}
return $fallback;
} | php | {
"resource": ""
} |
q13725 | UserState.read | train | public function read($number)
{
if ($number > $this->last_read_post_number) {
$this->last_read_post_number = $number;
$this->last_read_at = Carbon::now();
$this->raise(new UserRead($this));
}
return $this;
} | php | {
"resource": ""
} |
q13726 | DiscussionRepository.findOrFail | train | public function findOrFail($id, User $user = null)
{
$query = Discussion::where('id', $id);
return $this->scopeVisibleTo($query, $user)->firstOrFail();
} | php | {
"resource": ""
} |
q13727 | DiscussionRepository.getReadIds | train | public function getReadIds(User $user)
{
return Discussion::leftJoin('discussion_user', 'discussion_user.discussion_id', '=', 'discussions.id')
->where('discussion_user.user_id', $user->id)
->whereColumn('last_read_post_number', '>=', 'last_post_number')
->pluck('id')
->all();
} | php | {
"resource": ""
} |
q13728 | UrlGenerator.addCollection | train | public function addCollection($key, RouteCollection $routes, $prefix = null)
{
$this->routes[$key] = new RouteCollectionUrlGenerator(
$this->app->url($prefix),
$routes
);
return $this;
} | php | {
"resource": ""
} |
q13729 | DispatchEventsTrait.dispatchEventsFor | train | public function dispatchEventsFor($entity, User $actor = null)
{
foreach ($entity->releaseEvents() as $event) {
$event->actor = $actor;
$this->events->dispatch($event);
}
} | php | {
"resource": ""
} |
q13730 | NotificationSyncer.sync | train | public function sync(Blueprint\BlueprintInterface $blueprint, array $users)
{
$attributes = $this->getAttributes($blueprint);
// Find all existing notification records in the database matching this
// blueprint. We will begin by assuming that they all need to be
// deleted in order to match the provided list of users.
$toDelete = Notification::where($attributes)->get();
$toUndelete = [];
$newRecipients = [];
// For each of the provided users, check to see if they already have
// a notification record in the database. If they do, we will make sure
// it isn't marked as deleted. If they don't, we will want to create a
// new record for them.
foreach ($users as $user) {
if (! ($user instanceof User)) {
continue;
}
$existing = $toDelete->first(function ($notification, $i) use ($user) {
return $notification->user_id === $user->id;
});
if ($existing) {
$toUndelete[] = $existing->id;
$toDelete->forget($toDelete->search($existing));
} elseif (! static::$onePerUser || ! in_array($user->id, static::$sentTo)) {
$newRecipients[] = $user;
static::$sentTo[] = $user->id;
}
}
// Delete all of the remaining notification records which weren't
// removed from this collection by the above loop. Un-delete the
// existing records that we want to keep.
if (count($toDelete)) {
$this->setDeleted($toDelete->pluck('id')->all(), true);
}
if (count($toUndelete)) {
$this->setDeleted($toUndelete, false);
}
// Create a notification record, and send an email, for all users
// receiving this notification for the first time (we know because they
// didn't have a record in the database).
if (count($newRecipients)) {
$this->sendNotifications($blueprint, $newRecipients);
}
} | php | {
"resource": ""
} |
q13731 | NotificationSyncer.delete | train | public function delete(BlueprintInterface $blueprint)
{
Notification::where($this->getAttributes($blueprint))->update(['is_deleted' => true]);
} | php | {
"resource": ""
} |
q13732 | NotificationSyncer.restore | train | public function restore(BlueprintInterface $blueprint)
{
Notification::where($this->getAttributes($blueprint))->update(['is_deleted' => false]);
} | php | {
"resource": ""
} |
q13733 | NotificationSyncer.mailNotifications | train | protected function mailNotifications(MailableInterface $blueprint, array $recipients)
{
foreach ($recipients as $user) {
if ($user->shouldEmail($blueprint::getType())) {
$this->mailer->send($blueprint, $user);
}
}
} | php | {
"resource": ""
} |
q13734 | NotificationSyncer.getAttributes | train | protected function getAttributes(Blueprint\BlueprintInterface $blueprint)
{
return [
'type' => $blueprint::getType(),
'from_user_id' => ($fromUser = $blueprint->getFromUser()) ? $fromUser->id : null,
'subject_id' => ($subject = $blueprint->getSubject()) ? $subject->id : null,
'data' => ($data = $blueprint->getData()) ? json_encode($data) : null
];
} | php | {
"resource": ""
} |
q13735 | ExtensionManager.enable | train | public function enable($name)
{
if ($this->isEnabled($name)) {
return;
}
$extension = $this->getExtension($name);
$this->dispatcher->dispatch(new Enabling($extension));
$enabled = $this->getEnabled();
$enabled[] = $name;
$this->migrate($extension);
$this->publishAssets($extension);
$this->setEnabled($enabled);
$extension->enable($this->app);
$this->dispatcher->dispatch(new Enabled($extension));
} | php | {
"resource": ""
} |
q13736 | ExtensionManager.disable | train | public function disable($name)
{
$enabled = $this->getEnabled();
if (($k = array_search($name, $enabled)) === false) {
return;
}
$extension = $this->getExtension($name);
$this->dispatcher->dispatch(new Disabling($extension));
unset($enabled[$k]);
$this->setEnabled($enabled);
$extension->disable($this->app);
$this->dispatcher->dispatch(new Disabled($extension));
} | php | {
"resource": ""
} |
q13737 | ExtensionManager.uninstall | train | public function uninstall($name)
{
$extension = $this->getExtension($name);
$this->disable($name);
$this->migrateDown($extension);
$this->unpublishAssets($extension);
$extension->setInstalled(false);
$this->dispatcher->dispatch(new Uninstalled($extension));
} | php | {
"resource": ""
} |
q13738 | ExtensionManager.publishAssets | train | protected function publishAssets(Extension $extension)
{
if ($extension->hasAssets()) {
$this->filesystem->copyDirectory(
$extension->getPath().'/assets',
$this->app->publicPath().'/assets/extensions/'.$extension->getId()
);
}
} | php | {
"resource": ""
} |
q13739 | ExtensionManager.unpublishAssets | train | protected function unpublishAssets(Extension $extension)
{
$this->filesystem->deleteDirectory($this->app->publicPath().'/assets/extensions/'.$extension->getId());
} | php | {
"resource": ""
} |
q13740 | ExtensionManager.getAsset | train | public function getAsset(Extension $extension, $path)
{
return $this->app->publicPath().'/assets/extensions/'.$extension->getId().$path;
} | php | {
"resource": ""
} |
q13741 | ExtensionManager.migrate | train | public function migrate(Extension $extension, $direction = 'up')
{
$this->app->bind('Illuminate\Database\Schema\Builder', function ($container) {
return $container->make('Illuminate\Database\ConnectionInterface')->getSchemaBuilder();
});
$extension->migrate($this->migrator, $direction);
} | php | {
"resource": ""
} |
q13742 | ExtensionManager.getEnabledExtensions | train | public function getEnabledExtensions()
{
$enabled = [];
$extensions = $this->getExtensions();
foreach ($this->getEnabled() as $id) {
if (isset($extensions[$id])) {
$enabled[$id] = $extensions[$id];
}
}
return $enabled;
} | php | {
"resource": ""
} |
q13743 | ExtensionManager.extend | train | public function extend(Container $app)
{
foreach ($this->getEnabledExtensions() as $extension) {
$extension->extend($app);
}
} | php | {
"resource": ""
} |
q13744 | ExtensionManager.setEnabled | train | protected function setEnabled(array $enabled)
{
$enabled = array_values(array_unique($enabled));
$this->config->set('extensions_enabled', json_encode($enabled));
} | php | {
"resource": ""
} |
q13745 | ConfigureLocales.loadLanguagePackFrom | train | public function loadLanguagePackFrom($directory)
{
$name = $title = basename($directory);
if (file_exists($manifest = $directory.'/composer.json')) {
$json = json_decode(file_get_contents($manifest), true);
if (empty($json)) {
throw new RuntimeException("Error parsing composer.json in $name: ".json_last_error_msg());
}
$locale = array_get($json, 'extra.flarum-locale.code');
$title = array_get($json, 'extra.flarum-locale.title', $title);
}
if (! isset($locale)) {
throw new RuntimeException("Language pack $name must define \"extra.flarum-locale.code\" in composer.json.");
}
$this->locales->addLocale($locale, $title);
if (! is_dir($localeDir = $directory.'/locale')) {
throw new RuntimeException("Language pack $name must have a \"locale\" subdirectory.");
}
if (file_exists($file = $localeDir.'/config.js')) {
$this->locales->addJsFile($locale, $file);
}
if (file_exists($file = $localeDir.'/config.css')) {
$this->locales->addCssFile($locale, $file);
}
foreach (new DirectoryIterator($localeDir) as $file) {
if ($file->isFile() && in_array($file->getExtension(), ['yml', 'yaml'])) {
$this->locales->addTranslations($locale, $file->getPathname());
}
}
} | php | {
"resource": ""
} |
q13746 | Configuring.addCommand | train | public function addCommand($command)
{
if (is_string($command)) {
$command = $this->app->make($command);
}
if ($command instanceof Command) {
$command->setLaravel($this->app);
}
$this->console->add($command);
} | php | {
"resource": ""
} |
q13747 | Discussion.start | train | public static function start($title, User $user)
{
$discussion = new static;
$discussion->title = $title;
$discussion->created_at = Carbon::now();
$discussion->user_id = $user->id;
$discussion->setRelation('user', $user);
$discussion->raise(new Started($discussion));
return $discussion;
} | php | {
"resource": ""
} |
q13748 | Discussion.rename | train | public function rename($title)
{
if ($this->title !== $title) {
$oldTitle = $this->title;
$this->title = $title;
$this->raise(new Renamed($this, $oldTitle));
}
return $this;
} | php | {
"resource": ""
} |
q13749 | Discussion.hide | train | public function hide(User $actor = null)
{
if (! $this->hidden_at) {
$this->hidden_at = Carbon::now();
$this->hidden_user_id = $actor ? $actor->id : null;
$this->raise(new Hidden($this));
}
return $this;
} | php | {
"resource": ""
} |
q13750 | Discussion.restore | train | public function restore()
{
if ($this->hidden_at !== null) {
$this->hidden_at = null;
$this->hidden_user_id = null;
$this->raise(new Restored($this));
}
return $this;
} | php | {
"resource": ""
} |
q13751 | Discussion.setFirstPost | train | public function setFirstPost(Post $post)
{
$this->created_at = $post->created_at;
$this->user_id = $post->user_id;
$this->first_post_id = $post->id;
return $this;
} | php | {
"resource": ""
} |
q13752 | Discussion.setLastPost | train | public function setLastPost(Post $post)
{
$this->last_posted_at = $post->created_at;
$this->last_posted_user_id = $post->user_id;
$this->last_post_id = $post->id;
$this->last_post_number = $post->number;
return $this;
} | php | {
"resource": ""
} |
q13753 | Discussion.refreshLastPost | train | public function refreshLastPost()
{
/** @var Post $lastPost */
if ($lastPost = $this->comments()->latest()->first()) {
$this->setLastPost($lastPost);
}
return $this;
} | php | {
"resource": ""
} |
q13754 | Discussion.mergePost | train | public function mergePost(MergeableInterface $post)
{
$lastPost = $this->posts()->latest()->first();
$post = $post->saveAfter($lastPost);
return $this->modifiedPosts[] = $post;
} | php | {
"resource": ""
} |
q13755 | Discussion.state | train | public function state(User $user = null)
{
$user = $user ?: static::$stateUser;
return $this->hasOne(UserState::class)->where('user_id', $user ? $user->id : null);
} | php | {
"resource": ""
} |
q13756 | Discussion.setTitleAttribute | train | protected function setTitleAttribute($title)
{
$this->attributes['title'] = $title;
$this->slug = Str::slug($title);
} | php | {
"resource": ""
} |
q13757 | AbstractModel.getAttribute | train | public function getAttribute($key)
{
if (! is_null($value = parent::getAttribute($key))) {
return $value;
}
// If a custom relation with this key has been set up, then we will load
// and return results from the query and hydrate the relationship's
// value on the "relationships" array.
if (! $this->relationLoaded($key) && ($relation = $this->getCustomRelation($key))) {
if (! $relation instanceof Relation) {
throw new LogicException(
'Relationship method must return an object of type '.Relation::class
);
}
return $this->relations[$key] = $relation->getResults();
}
} | php | {
"resource": ""
} |
q13758 | MigrationCreator.create | train | public function create($name, $extension = null, $table = null, $create = false)
{
$migrationPath = $this->getMigrationPath($extension);
$path = $this->getPath($name, $migrationPath);
$stub = $this->getStub($table, $create);
$this->files->put($path, $this->populateStub($stub, $table));
return $path;
} | php | {
"resource": ""
} |
q13759 | AbstractCommand.error | train | protected function error($message)
{
if ($this->output instanceof ConsoleOutputInterface) {
$this->output->getErrorOutput()->writeln("<error>$message</error>");
} else {
$this->output->writeln("<error>$message</error>");
}
} | php | {
"resource": ""
} |
q13760 | Post.isVisibleTo | train | public function isVisibleTo(User $user)
{
return (bool) $this->newQuery()->whereVisibleTo($user)->find($this->id);
} | php | {
"resource": ""
} |
q13761 | Post.newFromBuilder | train | public function newFromBuilder($attributes = [], $connection = null)
{
$attributes = (array) $attributes;
if (! empty($attributes['type'])
&& isset(static::$models[$attributes['type']])
&& class_exists($class = static::$models[$attributes['type']])
) {
/** @var Post $instance */
$instance = new $class;
$instance->exists = true;
$instance->setRawAttributes($attributes, true);
$instance->setConnection($connection ?: $this->connection);
return $instance;
}
return parent::newFromBuilder($attributes, $connection);
} | php | {
"resource": ""
} |
q13762 | Extension.assignId | train | protected function assignId()
{
list($vendor, $package) = explode('/', $this->name);
$package = str_replace(['flarum-ext-', 'flarum-'], '', $package);
$this->id = "$vendor-$package";
} | php | {
"resource": ""
} |
q13763 | Extension.getIcon | train | public function getIcon()
{
$icon = $this->composerJsonAttribute('extra.flarum-extension.icon');
$file = Arr::get($icon, 'image');
if (is_null($icon) || is_null($file)) {
return $icon;
}
$file = $this->path.'/'.$file;
if (file_exists($file)) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (! array_key_exists($extension, self::LOGO_MIMETYPES)) {
throw new \RuntimeException('Invalid image type');
}
$mimetype = self::LOGO_MIMETYPES[$extension];
$data = base64_encode(file_get_contents($file));
$icon['backgroundImage'] = "url('data:$mimetype;base64,$data')";
}
return $icon;
} | php | {
"resource": ""
} |
q13764 | Extension.toArray | train | public function toArray()
{
return (array) array_merge([
'id' => $this->getId(),
'version' => $this->getVersion(),
'path' => $this->path,
'icon' => $this->getIcon(),
'hasAssets' => $this->hasAssets(),
'hasMigrations' => $this->hasMigrations(),
], $this->composerJson);
} | php | {
"resource": ""
} |
q13765 | EmailConfirmationMailer.getEmailData | train | protected function getEmailData(User $user, $email)
{
$token = $this->generateToken($user, $email);
return [
'{username}' => $user->display_name,
'{url}' => $this->url->to('forum')->route('confirmEmail', ['token' => $token->token]),
'{forum}' => $this->settings->get('forum_title')
];
} | php | {
"resource": ""
} |
q13766 | Permission.map | train | public static function map()
{
$permissions = [];
foreach (static::get() as $permission) {
$permissions[$permission->permission][] = (string) $permission->group_id;
}
return $permissions;
} | php | {
"resource": ""
} |
q13767 | ForumServiceProvider.populateRoutes | train | protected function populateRoutes(RouteCollection $routes)
{
$factory = $this->app->make(RouteHandlerFactory::class);
$callback = include __DIR__.'/routes.php';
$callback($routes, $factory);
$this->app->make('events')->fire(
new ConfigureForumRoutes($routes, $factory)
);
$defaultRoute = $this->app->make('flarum.settings')->get('default_route');
if (isset($routes->getRouteData()[0]['GET'][$defaultRoute])) {
$toDefaultController = $routes->getRouteData()[0]['GET'][$defaultRoute];
} else {
$toDefaultController = $factory->toForum(Content\Index::class);
}
$routes->get(
'/',
'default',
$toDefaultController
);
} | php | {
"resource": ""
} |
q13768 | Notification.scopeWhereSubjectVisibleTo | train | public function scopeWhereSubjectVisibleTo(Builder $query, User $actor)
{
$query->where(function ($query) use ($actor) {
$classes = [];
foreach (static::$subjectModels as $type => $class) {
$classes[$class][] = $type;
}
foreach ($classes as $class => $types) {
$query->orWhere(function ($query) use ($types, $class, $actor) {
$query->whereIn('type', $types)
->whereExists(function ($query) use ($class, $actor) {
$query->selectRaw(1)
->from((new $class)->getTable())
->whereColumn('id', 'subject_id');
static::$dispatcher->dispatch(
new ScopeModelVisibility($class::query()->setQuery($query), $actor, 'view')
);
});
});
}
});
} | php | {
"resource": ""
} |
q13769 | Notification.scopeWhereSubject | train | public function scopeWhereSubject(Builder $query, $model)
{
$query->whereSubjectModel(get_class($model))
->where('subject_id', $model->id);
} | php | {
"resource": ""
} |
q13770 | Notification.scopeWhereSubjectModel | train | public function scopeWhereSubjectModel(Builder $query, string $class)
{
$notificationTypes = array_filter(self::getSubjectModels(), function ($modelClass) use ($class) {
return $modelClass === $class or is_subclass_of($class, $modelClass);
});
$query->whereIn('type', array_keys($notificationTypes));
} | php | {
"resource": ""
} |
q13771 | EmailToken.generate | train | public static function generate($email, $userId)
{
$token = new static;
$token->token = str_random(40);
$token->user_id = $userId;
$token->email = $email;
$token->created_at = Carbon::now();
return $token;
} | php | {
"resource": ""
} |
q13772 | Migration.addColumns | train | public static function addColumns($tableName, array $columnDefinitions)
{
return [
'up' => function (Builder $schema) use ($tableName, $columnDefinitions) {
$schema->table($tableName, function (Blueprint $table) use ($schema, $columnDefinitions) {
foreach ($columnDefinitions as $columnName => $options) {
$type = array_shift($options);
$table->addColumn($type, $columnName, $options);
}
});
},
'down' => function (Builder $schema) use ($tableName, $columnDefinitions) {
$schema->table($tableName, function (Blueprint $table) use ($columnDefinitions) {
$table->dropColumn(array_keys($columnDefinitions));
});
}
];
} | php | {
"resource": ""
} |
q13773 | Migration.renameColumns | train | public static function renameColumns($tableName, array $columnNames)
{
return [
'up' => function (Builder $schema) use ($tableName, $columnNames) {
$schema->table($tableName, function (Blueprint $table) use ($columnNames) {
foreach ($columnNames as $from => $to) {
$table->renameColumn($from, $to);
}
});
},
'down' => function (Builder $schema) use ($tableName, $columnNames) {
$schema->table($tableName, function (Blueprint $table) use ($columnNames) {
foreach ($columnNames as $to => $from) {
$table->renameColumn($from, $to);
}
});
}
];
} | php | {
"resource": ""
} |
q13774 | Migration.addSettings | train | public static function addSettings(array $defaults)
{
return [
'up' => function (Builder $schema) use ($defaults) {
$settings = new DatabaseSettingsRepository(
$schema->getConnection()
);
foreach ($defaults as $key => $value) {
$settings->set($key, $value);
}
},
'down' => function (Builder $schema) use ($defaults) {
$settings = new DatabaseSettingsRepository(
$schema->getConnection()
);
foreach (array_keys($defaults) as $key) {
$settings->delete($key);
}
}
];
} | php | {
"resource": ""
} |
q13775 | Migration.addPermissions | train | public static function addPermissions(array $permissions)
{
$rows = [];
foreach ($permissions as $permission => $groups) {
foreach ((array) $groups as $group) {
$rows[] = [
'group_id' => $group,
'permission' => $permission,
];
}
}
return [
'up' => function (Builder $schema) use ($rows) {
$db = $schema->getConnection();
foreach ($rows as $row) {
if ($db->table('group_permission')->where($row)->exists()) {
continue;
}
if ($db->table('groups')->where('id', $row['group_id'])->doesntExist()) {
continue;
}
$db->table('group_permission')->insert($row);
}
},
'down' => function (Builder $schema) use ($rows) {
$db = $schema->getConnection();
foreach ($rows as $row) {
$db->table('group_permission')->where($row)->delete();
}
}
];
} | php | {
"resource": ""
} |
q13776 | Formatter.parse | train | public function parse($text, $context = null)
{
$parser = $this->getParser($context);
$this->events->dispatch(new Parsing($parser, $context, $text));
return $parser->parse($text);
} | php | {
"resource": ""
} |
q13777 | Formatter.render | train | public function render($xml, $context = null, ServerRequestInterface $request = null)
{
$renderer = $this->getRenderer();
$this->events->dispatch(new Rendering($renderer, $context, $xml, $request));
return $renderer->render($xml);
} | php | {
"resource": ""
} |
q13778 | Formatter.getComponent | train | protected function getComponent($name)
{
$formatter = $this->cache->rememberForever('flarum.formatter', function () {
return $this->getConfigurator()->finalize();
});
return $formatter[$name];
} | php | {
"resource": ""
} |
q13779 | AbstractSerializer.getCustomRelationship | train | protected function getCustomRelationship($model, $name)
{
$relationship = static::$dispatcher->until(
new GetApiRelationship($this, $name, $model)
);
if ($relationship && ! ($relationship instanceof Relationship)) {
throw new LogicException(
'GetApiRelationship handler must return an instance of '.Relationship::class
);
}
return $relationship;
} | php | {
"resource": ""
} |
q13780 | AbstractSerializer.hasOne | train | public function hasOne($model, $serializer, $relation = null)
{
return $this->buildRelationship($model, $serializer, $relation);
} | php | {
"resource": ""
} |
q13781 | AbstractSerializer.hasMany | train | public function hasMany($model, $serializer, $relation = null)
{
return $this->buildRelationship($model, $serializer, $relation, true);
} | php | {
"resource": ""
} |
q13782 | ApplySearchParametersTrait.applySort | train | protected function applySort(AbstractSearch $search, array $sort = null)
{
$sort = $sort ?: $search->getDefaultSort();
if (is_callable($sort)) {
$sort($search->getQuery());
} else {
foreach ($sort as $field => $order) {
if (is_array($order)) {
foreach ($order as $value) {
$search->getQuery()->orderByRaw(snake_case($field).' != ?', [$value]);
}
} else {
$search->getQuery()->orderBy(snake_case($field), $order);
}
}
}
} | php | {
"resource": ""
} |
q13783 | CommentPost.revise | train | public function revise($content, User $actor)
{
if ($this->content !== $content) {
$this->content = $content;
$this->edited_at = Carbon::now();
$this->edited_user_id = $actor->id;
$this->raise(new Revised($this));
}
return $this;
} | php | {
"resource": ""
} |
q13784 | CommentPost.setContentAttribute | train | public function setContentAttribute($value)
{
$this->attributes['content'] = $value ? static::$formatter->parse($value, $this) : null;
} | php | {
"resource": ""
} |
q13785 | Migrator.runClosureMigration | train | protected function runClosureMigration($migration, $direction = 'up')
{
if (is_array($migration) && array_key_exists($direction, $migration)) {
call_user_func($migration[$direction], $this->schemaBuilder);
} else {
throw new Exception('Migration file should contain an array with up/down.');
}
} | php | {
"resource": ""
} |
q13786 | LoginProvider.logIn | train | public static function logIn(string $provider, string $identifier): ?User
{
if ($provider = static::where(compact('provider', 'identifier'))->first()) {
$provider->touch();
return $provider->user;
}
return null;
} | php | {
"resource": ""
} |
q13787 | Client.send | train | public function send($controller, User $actor = null, array $queryParams = [], array $body = []): ResponseInterface
{
$request = ServerRequestFactory::fromGlobals(null, $queryParams, $body);
$request = $request->withAttribute('actor', $actor);
if (is_string($controller)) {
$controller = $this->container->make($controller);
}
if (! ($controller instanceof RequestHandlerInterface)) {
throw new InvalidArgumentException(
'Endpoint must be an instance of '.RequestHandlerInterface::class
);
}
try {
return $controller->handle($request);
} catch (Exception $e) {
if (! $this->errorHandler) {
throw $e;
}
return $this->errorHandler->handle($e);
}
} | php | {
"resource": ""
} |
q13788 | GroupRepository.findOrFail | train | public function findOrFail($id, User $actor = null)
{
$query = Group::where('id', $id);
return $this->scopeVisibleTo($query, $actor)->firstOrFail();
} | php | {
"resource": ""
} |
q13789 | GroupRepository.findByName | train | public function findByName($name, User $actor = null)
{
$query = Group::where('name_singular', $name)->orWhere('name_plural', $name);
return $this->scopeVisibleTo($query, $actor)->first();
} | php | {
"resource": ""
} |
q13790 | Str.slug | train | public static function slug($str)
{
$str = strtolower($str);
$str = preg_replace('/[^a-z0-9]/i', '-', $str);
$str = preg_replace('/-+/', '-', $str);
$str = preg_replace('/-$|^-/', '', $str);
return $str;
} | php | {
"resource": ""
} |
q13791 | Date.autoDetectTimeZone | train | protected function autoDetectTimeZone($object, $originalObject = null)
{
/** @var CarbonTimeZone $timezone */
$timezone = CarbonTimeZone::instance($object);
if ($timezone && is_int($originalObject ?: $object)) {
$timezone = $timezone->toRegionTimeZone($this);
}
return $timezone;
} | php | {
"resource": ""
} |
q13792 | Date.resolveCarbon | train | protected function resolveCarbon($date = null)
{
if (!$date) {
return $this->nowWithSameTz();
}
if (is_string($date)) {
return static::parse($date, $this->getTimezone());
}
static::expectDateTime($date, ['null', 'string']);
return $date instanceof self ? $date : static::instance($date);
} | php | {
"resource": ""
} |
q13793 | Date.addUnitNoOverflow | train | public function addUnitNoOverflow($valueUnit, $value, $overflowUnit)
{
return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit + $value, $overflowUnit);
} | php | {
"resource": ""
} |
q13794 | Date.subUnitNoOverflow | train | public function subUnitNoOverflow($valueUnit, $value, $overflowUnit)
{
return $this->setUnitNoOverflow($valueUnit, $this->$valueUnit - $value, $overflowUnit);
} | php | {
"resource": ""
} |
q13795 | Date.utcOffset | train | public function utcOffset(int $offset = null)
{
if (func_num_args() < 1) {
return $this->offsetMinutes;
}
return $this->setTimezone(static::safeCreateDateTimeZone($offset / static::MINUTES_PER_HOUR));
} | php | {
"resource": ""
} |
q13796 | Date.setTimezone | train | public function setTimezone($value)
{
/** @var static $date */
$date = parent::setTimezone(static::safeCreateDateTimeZone($value));
// https://bugs.php.net/bug.php?id=72338
// just workaround on this bug
$date->getTimestamp();
return $date;
} | php | {
"resource": ""
} |
q13797 | Date.setTimeFrom | train | public function setTimeFrom($date = null)
{
$date = $this->resolveCarbon($date);
return $this->setTime($date->hour, $date->minute, $date->second, $date->microsecond);
} | php | {
"resource": ""
} |
q13798 | Date.setDateTimeFrom | train | public function setDateTimeFrom($date = null)
{
$date = $this->resolveCarbon($date);
return $this->modify($date->rawFormat('Y-m-d H:i:s.u'));
} | php | {
"resource": ""
} |
q13799 | Date.hasRelativeKeywords | train | public static function hasRelativeKeywords($time)
{
if (strtotime($time) === false) {
return false;
}
$date1 = new DateTime('2000-01-01T00:00:00Z');
$date1->modify($time);
$date2 = new DateTime('2001-12-25T00:00:00Z');
$date2->modify($time);
return $date1 != $date2;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.