getPermissions example



        foreach ($refreshableApps->getToBeUpdated() as $app) {
            $this->grantPermissionsForApp($app$io, false);

            $this->appPrinter->checkHosts($app$io);
        }
    }

    private function grantPermissionsForApp(Manifest $app, ShopwareStyle $io, bool $install = true): void
    {
        if ($app->getPermissions()) {
            $this->appPrinter->printPermissions($app$io$install);

            if (!$io->confirm(
                sprintf('Do you want to grant these permissions for app "%s"?', $app->getMetadata()->getName()),
                false
            )) {
                throw new UserAbortedCommandException();
            }
        }
    }
}
$modules = ['module_a', 'module_b', 'module_c'];

    $this->moduleHandler->expects($this->any())
      ->method('getModuleList')
      ->willReturn(array_flip($modules));

    $this->controllerResolver->expects($this->never())
      ->method('getControllerFromDefinition');

    $this->permissionHandler = new PermissionHandler($this->moduleHandler, $this->stringTranslation, $this->controllerResolver);

    $actual_permissions = $this->permissionHandler->getPermissions();
    $this->assertPermissions($actual_permissions);

    $this->assertTrue($this->permissionHandler->moduleProvidesPermissions('module_a'));
    $this->assertTrue($this->permissionHandler->moduleProvidesPermissions('module_b'));
    $this->assertTrue($this->permissionHandler->moduleProvidesPermissions('module_c'));
    $this->assertFalse($this->permissionHandler->moduleProvidesPermissions('module_d'));
  }

  /** * Tests permissions sort inside a module. * * @covers ::__construct * @covers ::getPermissions * @covers ::buildPermissionsYaml * @covers ::sortPermissions */
$all_permissions = $this->buildPermissionsYaml();

    return $this->sortPermissions($all_permissions);
  }

  /** * {@inheritdoc} */
  public function moduleProvidesPermissions($module_name) {
    // @TODO Static cache this information, see     // https://www.drupal.org/node/2339487     $permissions = $this->getPermissions();

    foreach ($permissions as $permission) {
      if ($permission['provider'] == $module_name) {
        return TRUE;
      }
    }
    return FALSE;
  }

  /** * Builds all permissions provided by .permissions.yml files. * * @return array[] * An array with the same structure as * PermissionHandlerInterface::getPermissions(). * * @see \Drupal\user\PermissionHandlerInterface::getPermissions() */

  protected function assertEntity(string $id, string $label, array $permissions): void {
    /** @var \Drupal\user\RoleInterface $entity */
    $entity = Role::load($id);
    $this->assertInstanceOf(RoleInterface::class$entity);
    $this->assertSame($label$entity->label());
    $this->assertSame($permissions$entity->getPermissions());
  }

  /** * Tests user role migration. */
  public function testUserRole() {
    $anonymous_permissions = ['access content'];
    $this->assertEntity('anonymous', 'anonymous user', $anonymous_permissions);
    $this->assertEntity('authenticated', 'authenticated user', $anonymous_permissions);
    $admin_permissions = [
      'access administration pages',
      
/** * {@inheritdoc} */
  protected function setUp(): void {
    // testAdminPages() requires Locale module.     parent::setUp();

    // Create an administrator with all permissions, as well as a regular user     // who can only access administration pages and perform some Locale module     // administrative tasks, but not all of them.     $this->adminUser = $this->drupalCreateUser(array_keys(\Drupal::service('user.permissions')->getPermissions()));
    $this->webUser = $this->drupalCreateUser([
      'access administration pages',
      'translate interface',
    ]);
    $this->drupalLogin($this->adminUser);
  }

  /** * Tests output on administrative listing pages. */
  public function testAdminPages() {
    
->add(self::COUNTRY_ID, new EntityExists(['entity' => 'country', 'context' => $context->getContext()]))
            ->add(self::STATE_ID, new EntityExists(['entity' => 'country_state', 'context' => $context->getContext()]))
        ;

        $this->validator->validate($parameters$definition);

        $customer = $context->getCustomer();
        $this->contextPersister->save(
            $context->getToken(),
            $parameters,
            $context->getSalesChannel()->getId(),
            $customer && empty($context->getPermissions()) ? $customer->getId() : null
        );

        // Language was switched - Check new Domain         $changeUrl = $this->checkNewDomain($parameters$context);

        $event = new SalesChannelContextSwitchEvent($context$data);
        $this->eventDispatcher->dispatch($event);

        return new ContextTokenResponse($context->getToken()$changeUrl);
    }

    
$con->insert('sales_channel_api_context', [
            'token' => Random::getAlphanumericString(32),
            'payload' => \json_encode(['expired' => false, 'customerId' => $this->customerId, 'permissions' => ['foo']], \JSON_THROW_ON_ERROR),
            'sales_channel_id' => Uuid::fromHexToBytes($currentContext->getSalesChannelId()),
            'customer_id' => Uuid::fromHexToBytes($this->customerId),
            'updated_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
        ]);

        $restoreContext = $this->cartRestorer->restore($this->customerId, $currentContext);

        static::assertSame([]$restoreContext->getPermissions());
    }

    private function createProduct(Context $context): string
    {
        $productId = Uuid::randomHex();

        $productNumber = Uuid::randomHex();
        $data = [
            'id' => $productId,
            'productNumber' => $productNumber,
            'stock' => 1,
            
$this->installSchema('node', ['node_access']);
    $this->installSchema('system', ['sequences']);
    $this->installSchema('workspaces', ['workspace_association']);

    $this->createContentType(['type' => 'article']);

    $permissions = array_intersect([
      'administer nodes',
      'create workspace',
      'edit any workspace',
      'view any workspace',
    ]array_keys($this->container->get('user.permissions')->getPermissions()));
    $this->setCurrentUser($this->createUser($permissions));

    $this->workspaces['stage'] = Workspace::create(['id' => 'stage', 'label' => 'Stage']);
    $this->workspaces['stage']->save();
    $this->workspaces['dev'] = Workspace::create(['id' => 'dev', 'parent' => 'stage', 'label' => 'Dev']);
    $this->workspaces['dev']->save();
  }

  /** * Tests the revisions tracked by a workspace. * * @covers ::getTrackedEntities * @covers ::getAssociatedRevisions */

  protected $adminUser;

  /** * {@inheritdoc} */
  protected function setUp(): void {
    parent::setUp();
    // Create an administrator with all permissions.     $this->adminUser = $this->drupalCreateUser(array_keys(\Drupal::service('user.permissions')
      ->getPermissions()));

    // Log in so there are more libraries to test for.     $this->drupalLogin($this->adminUser);
  }

  /** * Default functionality without the param ajax_page_state[libraries]. * * The libraries active-link and drupalSettings are loaded default from core * and available in code as scripts. Do this as the base test. */
  
      // configuration will be sorted by StorableConfigBase.       sort($this->permissions);
    }
  }

  /** * {@inheritdoc} */
  public function calculateDependencies() {
    parent::calculateDependencies();
    // Load all permission definitions.     $permission_definitions = \Drupal::service('user.permissions')->getPermissions();
    $valid_permissions = array_intersect($this->permissions, array_keys($permission_definitions));
    $invalid_permissions = array_diff($this->permissions, $valid_permissions);
    if (!empty($invalid_permissions)) {
      throw new \RuntimeException('Adding non-existent permissions to a role is not allowed. The incorrect permissions are "' . implode('", "', $invalid_permissions) . '".');
    }
    foreach ($valid_permissions as $permission) {
      // Depend on the module that is providing this permissions.       $this->addDependency('module', $permission_definitions[$permission]['provider']);
      // Depend on any other dependencies defined by permissions granted to       // this role.       if (!empty($permission_definitions[$permission]['dependencies'])) {
        
return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('user.permissions'),
      $container->get('module_handler')
    );
  }

  public function getValueOptions() {
    if (!isset($this->valueOptions)) {
      $permissions = $this->permissionHandler->getPermissions();
      foreach ($permissions as $perm => $perm_item) {
        $provider = $perm_item['provider'];
        $display_name = $this->moduleHandler->getName($provider);
        $this->valueOptions[$display_name][$perm] = Html::escape(strip_tags($perm_item['title']));
      }
      return $this->valueOptions;
    }
    else {
      return $this->valueOptions;
    }
  }

  
$assert_session->pageTextContains('Weight');
    $assert_session->fieldNotExists('Weight');
    $assert_session->pageTextContains($no_edit_help_text);

    // Visit vocabulary overview without terms. 'Add term' should not be shown.     $this->drupalGet('admin/structure/taxonomy/manage/' . $vocabulary2_id . '/overview');
    $assert_session->statusCodeEquals(200);
    $assert_session->pageTextContains('No terms available');
    $assert_session->linkExists('Add term');

    // Ensure the dynamic vocabulary permissions have the correct dependencies.     $permissions = \Drupal::service('user.permissions')->getPermissions();
    $this->assertTrue(isset($permissions['create terms in ' . $vocabulary1_id]));
    $this->assertEquals(['config' => [$vocabulary1->getConfigDependencyName()]]$permissions['create terms in ' . $vocabulary1_id]['dependencies']);
  }

  /** * Create, edit and delete a taxonomy term via the user interface. */
  public function testVocabularyPermissionsTaxonomyTerm() {
    // Vocabulary used for creating, removing and editing terms.     $vocabulary = $this->createVocabulary();

    
'label' => 'Test label',
      'description' => 'My test description',
    ])->save();
  }

  /** * Tests that enabling translation via the API triggers schema updates. */
  public function testPermissions() {
    $this->container->get('content_translation.manager')->setEnabled('entity_test_mul', 'entity_test_mul', TRUE);
    $this->container->get('content_translation.manager')->setEnabled('entity_test_mul_with_bundle', 'test', TRUE);
    $permissions = $this->container->get('user.permissions')->getPermissions();
    $this->assertEquals(['entity_test']$permissions['translate entity_test_mul']['dependencies']['module']);
    $this->assertEquals(['entity_test.entity_test_mul_bundle.test']$permissions['translate test entity_test_mul_with_bundle']['dependencies']['config']);

    // Ensure bundle permission granularity works for bundles not based on     // configuration.     $this->container->get('state')->set('entity_test_mul.permission_granularity', 'bundle');
    $this->container->get('entity_type.manager')->clearCachedDefinitions();
    $permissions = $this->container->get('user.permissions')->getPermissions();
    $this->assertEquals(['entity_test']$permissions['translate entity_test_mul entity_test_mul']['dependencies']['module']);
    $this->assertEquals(['entity_test.entity_test_mul_bundle.test']$permissions['translate test entity_test_mul_with_bundle']['dependencies']['config']);
  }

}
if (isset($weight)) {
      $role->set('weight', $weight);
    }
    $result = $role->save();

    $this->assertSame(SAVED_NEW, $resultnew FormattableMarkup('Created role ID @rid with name @name.', ['@name' => var_export($role->label(), TRUE), '@rid' => var_export($role->id(), TRUE)]));

    if ($result === SAVED_NEW) {
      // Grant the specified permissions to the role, if any.       if (!empty($permissions)) {
        $this->grantPermissions($role$permissions);
        $assigned_permissions = Role::load($role->id())->getPermissions();
        $missing_permissions = array_diff($permissions$assigned_permissions);
        $this->assertEmpty($missing_permissions);
      }
      return $role->id();
    }
    else {
      return FALSE;
    }
  }

  /** * Checks whether a given list of permission names is valid. * * @param array $permissions * The permission names to check. * * @return bool * TRUE if the permissions are valid, FALSE otherwise. */
$salesChannelContext->setItemRounding($order->getItemRounding());
        }

        if ($order->getTotalRounding() !== null) {
            $salesChannelContext->setTotalRounding($order->getTotalRounding());
        }

        $cart = $this->orderConverter->convertToCart($order$salesChannelContext->getContext());
        $this->cartRuleLoader->loadByCart(
            $salesChannelContext,
            $cart,
            new CartBehavior($salesChannelContext->getPermissions()),
            true
        );

        return $salesChannelContext;
    }

    /** * @param array<string> $overrideOptions * * @throws Exception */
    
Home | Imprint | This part of the site doesn't use cookies.