本文整理汇总了PHP中Drupal\Core\Session\AccountInterface类的典型用法代码示例。如果您正苦于以下问题:PHP AccountInterface类的具体用法?PHP AccountInterface怎么用?PHP AccountInterface使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AccountInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: blockAccess
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account)
{
if ($account->hasPermission('search content')) {
return AccessResult::allowed();
}
return AccessResult::forbidden();
}
示例2: access
public function access(AccountInterface $account)
{
if (!$account->id() == 1) {
return AccessResult::forbidden();
}
return AccessResult::allowed();
}
示例3: defaultAccess
/**
* {@inheritdoc}
*/
public function defaultAccess($operation = 'view', AccountInterface $account = NULL)
{
if ($operation == 'view') {
return TRUE;
}
return $account->hasPermission('create url aliases') || $account->hasPermission('administer url aliases');
}
示例4: access
/**
* Checks access to the translation overview for the entity and bundle.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parametrized route.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
* @param string $entity_type_id
* The entity type ID.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(RouteMatchInterface $route_match, AccountInterface $account, $entity_type_id)
{
/* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $route_match->getParameter($entity_type_id);
if ($entity && $entity->isTranslatable()) {
// Get entity base info.
$bundle = $entity->bundle();
// Get entity access callback.
$definition = $this->entityManager->getDefinition($entity_type_id);
$translation = $definition->get('translation');
$access_callback = $translation['content_translation']['access_callback'];
$access = call_user_func($access_callback, $entity);
if ($access->isAllowed()) {
return $access;
}
// Check "translate any entity" permission.
if ($account->hasPermission('translate any entity')) {
return AccessResult::allowed()->cachePerPermissions()->inheritCacheability($access);
}
// Check per entity permission.
$permission = "translate {$entity_type_id}";
if ($definition->getPermissionGranularity() == 'bundle') {
$permission = "translate {$bundle} {$entity_type_id}";
}
return AccessResult::allowedIfHasPermission($account, $permission)->inheritCacheability($access);
}
// No opinion.
return AccessResult::neutral();
}
示例5: setUp
/**
* {@inheritdoc}
*/
public function setUp()
{
parent::setUp();
$cache_contexts_manager = $this->prophesize(CacheContextsManager::class);
$cache_contexts_manager->assertValidTokens()->willReturn(TRUE);
$cache_contexts_manager->reveal();
$container = new Container();
$container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($container);
$this->viewer = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->viewer->expects($this->any())->method('hasPermission')->will($this->returnValue(FALSE));
$this->viewer->expects($this->any())->method('id')->will($this->returnValue(1));
$this->owner = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->owner->expects($this->any())->method('hasPermission')->will($this->returnValueMap(array(array('administer users', FALSE), array('change own username', TRUE))));
$this->owner->expects($this->any())->method('id')->will($this->returnValue(2));
$this->admin = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->admin->expects($this->any())->method('hasPermission')->will($this->returnValue(TRUE));
$entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface');
$this->accessControlHandler = new UserAccessControlHandler($entity_type);
$module_handler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface');
$module_handler->expects($this->any())->method('getImplementations')->will($this->returnValue(array()));
$this->accessControlHandler->setModuleHandler($module_handler);
$this->items = $this->getMockBuilder('Drupal\\Core\\Field\\FieldItemList')->disableOriginalConstructor()->getMock();
$this->items->expects($this->any())->method('defaultAccess')->will($this->returnValue(AccessResult::allowed()));
}
示例6: access
/**
* Grants access only to UID 1.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(AccountInterface $account)
{
if ($account->id() == 1) {
return AccessResult::allowed()->addCacheContexts(['user']);
}
return AccessResult::forbidden()->addCacheContexts(['user']);
}
示例7: generate
/**
* {@inheritdoc}
*
* Cached by role, invalidated whenever permissions change.
*/
public function generate(AccountInterface $account)
{
// User 1 is the super user, and can always access all permissions. Use a
// different, unique identifier for the hash.
if ($account->id() == 1) {
return $this->hash('is-super-user');
}
$sorted_roles = $account->getRoles();
sort($sorted_roles);
$role_list = implode(',', $sorted_roles);
$cid = "user_permissions_hash:{$role_list}";
if ($static_cache = $this->static->get($cid)) {
return $static_cache->data;
} else {
$tags = Cache::buildTags('config:user.role', $sorted_roles, '.');
if ($cache = $this->cache->get($cid)) {
$permissions_hash = $cache->data;
} else {
$permissions_hash = $this->doGenerate($sorted_roles);
$this->cache->set($cid, $permissions_hash, Cache::PERMANENT, $tags);
}
$this->static->set($cid, $permissions_hash, Cache::PERMANENT, $tags);
}
return $permissions_hash;
}
示例8: access
/**
* Checks translation access for the entity and operation on the given route.
*
* @param \Symfony\Component\Routing\Route $route
* The route to check against.
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* The parametrized route.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
* @param string $source
* (optional) For a create operation, the language code of the source.
* @param string $target
* (optional) For a create operation, the language code of the translation.
* @param string $language
* (optional) For an update or delete operation, the language code of the
* translation being updated or deleted.
* @param string $entity_type_id
* (optional) The entity type ID.
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account, $source = NULL, $target = NULL, $language = NULL, $entity_type_id = NULL)
{
/* @var \Drupal\Core\Entity\ContentEntityInterface $entity */
if ($entity = $route_match->getParameter($entity_type_id)) {
if ($account->hasPermission('translate any entity')) {
return AccessResult::allowed()->cachePerRole();
}
$operation = $route->getRequirement('_access_content_translation_manage');
/* @var \Drupal\content_translation\ContentTranslationHandlerInterface $handler */
$handler = $this->entityManager->getHandler($entity->getEntityTypeId(), 'translation');
// Load translation.
$translations = $entity->getTranslationLanguages();
$languages = $this->languageManager->getLanguages();
switch ($operation) {
case 'create':
$source_language = $this->languageManager->getLanguage($source) ?: $entity->language();
$target_language = $this->languageManager->getLanguage($target) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
$is_new_translation = $source_language->getId() != $target_language->getId() && isset($languages[$source_language->getId()]) && isset($languages[$target_language->getId()]) && !isset($translations[$target_language->getId()]);
return AccessResult::allowedIf($is_new_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation));
case 'update':
case 'delete':
$language = $this->languageManager->getLanguage($language) ?: $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
$has_translation = isset($languages[$language->getId()]) && $language->getId() != $entity->getUntranslated()->language()->getId() && isset($translations[$language->getId()]);
return AccessResult::allowedIf($has_translation)->cachePerRole()->cacheUntilEntityChanges($entity)->andIf($handler->getTranslationAccess($entity, $operation));
}
}
// No opinion.
return AccessResult::neutral();
}
示例9: access
/**
* Checks access to the given user's contact page.
*
* @param \Drupal\user\UserInterface $user
* The user being contacted.
* @param \Drupal\Core\Session\AccountInterface $account
* The currently logged in account.
*
* @return string
* A \Drupal\Core\Access\AccessInterface constant value.
*/
public function access(UserInterface $user, AccountInterface $account)
{
$contact_account = $user;
// Anonymous users cannot have contact forms.
if ($contact_account->isAnonymous()) {
return static::DENY;
}
// Users may not contact themselves.
if ($account->id() == $contact_account->id()) {
return static::DENY;
}
// User administrators should always have access to personal contact forms.
if ($account->hasPermission('administer users')) {
return static::ALLOW;
}
// If requested user has been blocked, do not allow users to contact them.
if ($contact_account->isBlocked()) {
return static::DENY;
}
// If the requested user has disabled their contact form, do not allow users
// to contact them.
$account_data = $this->userData->get('contact', $contact_account->id(), 'enabled');
if (isset($account_data) && empty($account_data)) {
return static::DENY;
} else {
if (!$this->configFactory->get('contact.settings')->get('user_default_enabled')) {
return static::DENY;
}
}
return $account->hasPermission('access user contact forms') ? static::ALLOW : static::DENY;
}
示例10: onRespond
/**
* Redirects login attempts on already-logged-in session to the destination.
*/
public function onRespond(FilterResponseEvent $event)
{
// Return early in most cases.
if ($event->getRequest()->getMethod() !== 'POST') {
return;
}
if (!$this->currentUser->isAuthenticated()) {
return;
}
if (!$event->isMasterRequest()) {
return;
}
if (!$event->getRequest()->query->has('destination')) {
return;
}
if ($event->getResponse() instanceof RedirectResponse) {
return;
}
// There has to be a better way to figure out if we landed on the 403/404 page.
$page_403 = $this->configFactory->get('system.site')->get('page.403');
$page_404 = $this->configFactory->get('system.site')->get('page.404');
$path = $this->currentPath->getPath();
$route = $this->currentRouteMatch->getRouteName();
if ($route == 'system.403' || $page_403 && $path == $page_403 || $route == 'system.404' || $page_404 && $path == $page_404) {
// RedirectResponseSubscriber will convert to absolute URL for us.
$event->setResponse(new RedirectResponse($this->redirectDestination->get(), RedirectResponse::HTTP_SEE_OTHER));
}
}
示例11: onKernelRequestMaintenance
/**
* Determine whether the page is configured to be offline.
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
* The event to process.
*/
public function onKernelRequestMaintenance(GetResponseEvent $event)
{
$request = $event->getRequest();
$route_match = RouteMatch::createFromRequest($request);
$path = $request->attributes->get('_system_path');
if ($this->maintenanceMode->applies($route_match)) {
// If the site is offline, log out unprivileged users.
if ($this->account->isAuthenticated() && !$this->maintenanceMode->exempt($this->account)) {
user_logout();
// Redirect to homepage.
$event->setResponse(new RedirectResponse($this->url('<front>', [], ['absolute' => TRUE])));
return;
}
}
if ($this->account->isAuthenticated()) {
if ($path == 'user/login') {
// If the user is already logged in, redirect to their profile page.
$event->setResponse($this->redirect('entity.user.canonical', ['user' => $this->account->id()]));
return;
}
if ($path == 'user/register') {
// If the user is already registered, redirect to their edit page.
$event->setResponse(new RedirectResponse($this->url('entity.user.edit_form', ['user' => $this->account->id()], ['absolute' => TRUE])));
return;
}
}
}
示例12: testMetatag
/**
* Tests adding and editing values using metatag.
*/
public function testMetatag()
{
// Create a test entity.
$edit = ['name[0][value]' => 'Barfoo', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')'];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
$entities = entity_load_multiple_by_properties('entity_test', ['name' => 'Barfoo']);
$this->assertEqual(1, count($entities), 'Entity was saved');
$entity = reset($entities);
// Update the Global defaults and test them.
$values = array('keywords' => 'Purple monkey dishwasher');
$this->drupalPostForm('admin/structure/metatag_defaults/global', $values, 'Save');
$this->assertText('Saved the Global Metatag defaults.');
$this->drupalGet('entity_test/' . $entity->id());
$elements = $this->cssSelect('meta[name=keywords]');
$this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults');
$this->assertEqual((string) $elements[0]['content'], $values['keywords'], 'Default keywords applied');
// Tests metatags with urls work.
$edit = ['name[0][value]' => 'UrlTags', 'user_id[0][target_id]' => 'foo (' . $this->adminUser->id() . ')', 'field_metatag[0][open_graph][og_url]' => 'http://example.com/foo.html'];
$this->drupalPostForm('entity_test/add', $edit, t('Save'));
$entities = entity_load_multiple_by_properties('entity_test', ['name' => 'UrlTags']);
$this->assertEqual(1, count($entities), 'Entity was saved');
$entity = reset($entities);
$this->drupalGet('entity_test/' . $entity->id());
$elements = $this->cssSelect("meta[property='og:url']");
$this->assertTrue(count($elements) === 1, 'Found keywords metatag from defaults');
$this->assertEqual((string) $elements[0]['content'], $edit['field_metatag[0][open_graph][og_url]']);
}
示例13: log
/**
* {@inheritdoc}
*/
public function log($level, $message, array $context = array())
{
// Merge in defaults.
$context += array('channel' => $this->channel, 'link' => '', 'user' => NULL, 'uid' => 0, 'request_uri' => '', 'referer' => '', 'ip' => '', 'timestamp' => time());
// Some context values are only available when in a request context.
if ($this->requestStack && ($request = $this->requestStack->getCurrentRequest())) {
$context['request_uri'] = $request->getUri();
$context['referer'] = $request->headers->get('Referer', '');
$context['ip'] = $request->getClientIP();
try {
if ($this->currentUser) {
$context['user'] = $this->currentUser;
$context['uid'] = $this->currentUser->id();
}
} catch (\Exception $e) {
// An exception might be thrown if the database connection is not
// available or due to another unexpected reason. It is more important
// to log the error that we already have so any additional exceptions
// are ignored.
}
}
if (is_string($level)) {
// Convert to integer equivalent for consistency with RFC 5424.
$level = $this->levelTranslation[$level];
}
// Call all available loggers.
foreach ($this->sortLoggers() as $logger) {
$logger->log($level, $message, $context);
}
}
示例14: onRespond
/**
* Adds a cache tag if the 'user.permissions' cache context is present.
*
* @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
* The event to process.
*/
public function onRespond(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if (!$this->currentUser->isAnonymous()) {
return;
}
$response = $event->getResponse();
if (!$response instanceof CacheableResponseInterface) {
return;
}
// The 'user.permissions' cache context ensures that if the permissions for
// a role are modified, users are not served stale render cache content.
// But, when entire responses are cached in reverse proxies, the value for
// the cache context is never calculated, causing the stale response to not
// be invalidated. Therefore, when varying by permissions and the current
// user is the anonymous user, also add the cache tag for the 'anonymous'
// role.
if (in_array('user.permissions', $response->getCacheableMetadata()->getCacheContexts())) {
$per_permissions_response_for_anon = new CacheableMetadata();
$per_permissions_response_for_anon->setCacheTags(['config:user.role.anonymous']);
$response->addCacheableDependency($per_permissions_response_for_anon);
}
}
示例15: user
/**
* User object.
*
* @return \Drupal\moodle\Sql\User
*/
public function user()
{
// Static cache of already retrieved user data.
$data =& drupal_static(__METHOD__, array());
$user_cid = "moodle-user:{$this->user->id()}";
// If we do not have this user id in the static cache, check {cache_data}.
if (!isset($data[$user_cid])) {
$cache = $this->cacheBackend->get($user_cid);
if ($cache && $cache->data && isset($cache->data[$user_cid])) {
$data[$user_cid] = $cache->data[$user_cid];
}
}
// If nothing in the cache then retrieve it from the database.
if (!isset($data[$user_cid])) {
$user = new User();
$this->query();
$this->addFields();
$statement = $this->query->execute();
$statement->setFetchMode(\PDO::FETCH_INTO, $user);
$data[$user_cid] = $statement->fetch();
// Store the results for a day.
$this->cacheBackend->set($user_cid, $data, REQUEST_TIME + 86400);
}
return $data[$user_cid];
}