getOwnerId example

'comment_count',
      ]);
    foreach ($fields as $field_name => $detail) {
      // Skip fields that entity does not have.       if (!$entity->hasField($field_name)) {
        continue;
      }
      // Get the user ID from the entity if it's set, or default to the       // currently logged in user.       $last_comment_uid = 0;
      if ($entity instanceof EntityOwnerInterface) {
        $last_comment_uid = $entity->getOwnerId();
      }
      if (!isset($last_comment_uid)) {
        // Default to current user when entity does not implement         // EntityOwnerInterface or author is not set.         $last_comment_uid = $this->currentUser->id();
      }
      // Default to REQUEST_TIME when entity does not have a changed property.       $last_comment_timestamp = REQUEST_TIME;
      // @todo Make comment statistics language aware and add some tests. See       // https://www.drupal.org/node/2318875       if ($entity instanceof EntityChangedInterface) {
        
$node = [
      'title' => $title,
      'body' => [['value' => $this->randomMachineName(32)]],
      'uid' => $this->webUser->id(),
      'type' => 'article',
      'nid' => $test_nid,
    ];
    /** @var \Drupal\node\NodeInterface $node */
    $node = Node::create($node);
    $node->enforceIsNew();

    $this->assertEquals($this->webUser->id()$node->getOwnerId());

    $node->save();
    // Test the import.     $node_by_nid = Node::load($test_nid);
    $this->assertNotEmpty($node_by_nid, 'Node load by node ID.');

    $node_by_title = $this->drupalGetNodeByTitle($title);
    $this->assertNotEmpty($node_by_title, 'Node load by node title.');
  }

  /** * Verifies accuracy of the "created" and "changed" timestamp functionality. */
// Valid form state.     $this->assertCount(0, $form_state->getErrors());

    // Test the 'single' element.     $this->assertEquals($this->referencedEntities[0]->id()$form_state->getValue('single'));

    // Test the 'single_autocreate' element.     $value = $form_state->getValue('single_autocreate');
    $this->assertEquals('single - autocreated entity label', $value['entity']->label());
    $this->assertEquals('entity_test', $value['entity']->bundle());
    $this->assertEquals($this->testUser->id()$value['entity']->getOwnerId());

    // Test the 'single_autocreate_specific_uid' element.     $value = $form_state->getValue('single_autocreate_specific_uid');
    $this->assertEquals('single - autocreated entity label with specific uid', $value['entity']->label());
    $this->assertEquals('entity_test', $value['entity']->bundle());
    $this->assertEquals($this->testAutocreateUser->id()$value['entity']->getOwnerId());

    // Test the 'tags' element.     $expected = [
      ['target_id' => $this->referencedEntities[0]->id()],
      ['target_id' => $this->referencedEntities[1]->id()],
    ];
$this->createFileField($field_name, 'node', $type_name);

    $test_file = $this->getTestFile('text');
    $type = 'no-js';
    // Create a temporary file owned by the victim user. This will be as if     // they had uploaded the file, but not saved the node they were editing     // or creating.     $victim_tmp_file = $this->createTemporaryFile('some text', $victim_user);
    $victim_tmp_file = File::load($victim_tmp_file->id());
    $this->assertTrue($victim_tmp_file->isTemporary(), 'New file saved to disk is temporary.');
    $this->assertNotEmpty($victim_tmp_file->id(), 'New file has an fid.');
    $this->assertEquals($victim_user->id()$victim_tmp_file->getOwnerId(), 'New file belongs to the victim.');

    // Have attacker create a new node with a different uploaded file and     // ensure it got uploaded successfully.     $edit = [
      'title[0][value]' => $type . '-title',
    ];

    // Attach a file to a node.     $edit['files[' . $field_name . '_0]'] = $this->container->get('file_system')->realpath($test_file->getFileUri());
    $this->drupalGet(Url::fromRoute('node.add', ['node_type' => $type_name]));
    $this->submitForm($edit, 'Save');
    
return AccessResult::allowedIfHasPermission($account, 'view test entity translations');
        }
      }
      if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
        return AccessResult::neutral('Unpublished entity');
      }
      return AccessResult::allowedIfHasPermission($account, 'view test entity');
    }
    elseif (in_array($operation['update', 'delete'])) {
      $access = AccessResult::allowedIfHasPermission($account, 'administer entity_test content');
      if (!$access->isAllowed() && $operation === 'update' && $account->hasPermission('edit own entity_test content')) {
        $access = $access->orIf(AccessResult::allowedIf($entity->getOwnerId() === $account->id()))->cachePerUser()->addCacheableDependency($entity);
      }
      return $access;
    }

    // Access to revisions is based on labels, so access can vary by individual     // revisions, since the 'name' field can vary by revision.     $labels = explode(',', $entity->label());
    $labels = array_map('trim', $labels);
    if (in_array($operation[
      'view all revisions',
      'view revision',
    ],
->setRevisionCreationTime(123456789)
      ->set('path', '/llama')
      ->save();

    return $node;
  }

  /** * {@inheritdoc} */
  protected function getExpectedNormalizedEntity() {
    $author = User::load($this->entity->getOwnerId());
    return [
      'nid' => [
        ['value' => 1],
      ],
      'uuid' => [
        ['value' => $this->entity->uuid()],
      ],
      'vid' => [
        ['value' => 1],
      ],
      'langcode' => [
        [
return $return_as_object ? $result : $result->isAllowed();
  }

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $node$operation, AccountInterface $account) {
    /** @var \Drupal\node\NodeInterface $node */

    // Fetch information from the node object if possible.     $status = $node->isPublished();
    $uid = $node->getOwnerId();

    // Check if authors can view their own unpublished nodes.     if ($operation === 'view' && !$status && $account->hasPermission('view own unpublished content') && $account->isAuthenticated() && $account->id() == $uid) {
      return AccessResult::allowed()->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
    }

    [$revision_permission_operation$entity_operation] = static::REVISION_OPERATION_MAP[$operation] ?? [
      NULL,
      NULL,
    ];

    
      /** @var \Drupal\Core\TempStore\SharedTempStore[] $stores */
      $stores[$i] = $factory->get($collection$users[$i]);
    }

    $key = $this->randomMachineName();
    // Test that setIfNotExists() succeeds only the first time.     for ($i = 0; $i <= 1; $i++) {
      // setIfNotExists() should be TRUE the first time (when $i is 0) and       // FALSE the second time (when $i is 1).       $this->assertEquals(!$i$stores[0]->setIfNotExists($key$objects[$i]));
      $metadata = $stores[0]->getMetadata($key);
      $this->assertEquals($users[0]$metadata->getOwnerId());
      $this->assertEquals($objects[0]$stores[0]->get($key));
      // Another user should get the same result.       $metadata = $stores[1]->getMetadata($key);
      $this->assertEquals($users[0]$metadata->getOwnerId());
      $this->assertEquals($objects[0]$stores[1]->get($key));
    }

    // Remove the item and try to set it again.     $stores[0]->delete($key);
    $stores[0]->setIfNotExists($key$objects[1]);
    // This time it should succeed.

  public function buildComponents(array &$build, array $entities, array $displays$view_mode) {
    /** @var \Drupal\comment\CommentInterface[] $entities */
    if (empty($entities)) {
      return;
    }

    // Pre-load associated users into cache to leverage multiple loading.     $uids = [];
    foreach ($entities as $entity) {
      $uids[] = $entity->getOwnerId();
    }
    $this->entityTypeManager->getStorage('user')->loadMultiple(array_unique($uids));

    parent::buildComponents($build$entities$displays$view_mode);

    // A counter to track the indentation level.     $current_indent = 0;
    $attach_history = $this->moduleHandler->moduleExists('history') && $this->currentUser->isAuthenticated();

    foreach ($entities as $id => $entity) {
      if ($build[$id]['#comment_threaded']) {
        

  public function testUserPictures() {
    $file_ids = [];
    foreach ($this->migration->getIdMap() as $destination_ids) {
      $file_ids[] = reset($destination_ids);
    }
    $files = File::loadMultiple($file_ids);
    /** @var \Drupal\file\FileInterface $file */
    $file = array_shift($files);
    $this->assertSame('image-test.jpg', $file->getFilename());
    $this->assertSame('public://image-test.jpg', $file->getFileUri());
    $this->assertSame('2', $file->getOwnerId());
    $this->assertSame(1901, $file->getSize());
    $this->assertSame('image/jpeg', $file->getMimeType());

    $file = array_shift($files);
    $this->assertSame('image-test.png', $file->getFilename());
    $this->assertSame('public://image-test.png', $file->getFileUri());
    $this->assertSame('8', $file->getOwnerId());
    $this->assertEmpty($files);

    // Tests the D6 user pictures migration in combination with D6 file.     $this->setUpMigratedFiles();
    
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\media\MediaInterface $entity */
    // Allow admin permission to override all operations.     if ($account->hasPermission($this->entityType->getAdminPermission())) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    $type = $entity->bundle();
    $is_owner = ($account->id() && $account->id() === $entity->getOwnerId());
    switch ($operation) {
      case 'view':
        if ($entity->isPublished()) {
          $access_result = AccessResult::allowedIf($account->hasPermission('view media'))
            ->cachePerPermissions()
            ->addCacheableDependency($entity);
          if (!$access_result->isAllowed()) {
            $access_result->setReason("The 'view media' permission is required when the media item is published.");
          }
        }
        elseif ($account->hasPermission('view own unpublished media')) {
          
$container = \Drupal::getContainer();
    $container->get('current_user')->setAccount($user);

    // Create a test node.     $english = Node::create([
      'type' => 'page',
      'title' => $this->randomMachineName(),
      'language' => 'en',
    ]);
    $english->save();

    $this->assertEquals($user->id()$english->getOwnerId());

    $german = $english->addTranslation('de');
    $german->title = $this->randomString();
    $italian = $english->addTranslation('it');
    $italian->title = $this->randomString();

    // Node::preSave() sets owner to anonymous user if owner is nor set.     $english->set('uid', ['target_id' => NULL]);
    $german->set('uid', ['target_id' => NULL]);
    $italian->set('uid', ['target_id' => NULL]);

    
$tests['[node:nid]'] = $node->id();
    $tests['[node:vid]'] = $node->getRevisionId();
    $tests['[node:type]'] = 'article';
    $tests['[node:type-name]'] = 'Article';
    $tests['[node:title]'] = Html::escape($node->getTitle());
    $tests['[node:body]'] = $node->body->processed;
    $tests['[node:summary]'] = $node->body->summary_processed;
    $tests['[node:langcode]'] = $node->language()->getId();
    $tests['[node:url]'] = $node->toUrl('canonical', $url_options)->toString();
    $tests['[node:edit-url]'] = $node->toUrl('edit-form', $url_options)->toString();
    $tests['[node:author]'] = $account->getAccountName();
    $tests['[node:author:uid]'] = $node->getOwnerId();
    $tests['[node:author:name]'] = $account->getAccountName();
    /** @var \Drupal\Core\Datetime\DateFormatterInterface $date_formatter */
    $date_formatter = $this->container->get('date.formatter');
    $tests['[node:created:since]'] = $date_formatter->formatTimeDiffSince($node->getCreatedTime()['langcode' => $this->interfaceLanguage->getId()]);
    $tests['[node:changed:since]'] = $date_formatter->formatTimeDiffSince($node->getChangedTime()['langcode' => $this->interfaceLanguage->getId()]);

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($node);

    $metadata_tests = [];
    $metadata_tests['[node:nid]'] = $base_bubbleable_metadata;
    $metadata_tests['[node:vid]'] = $base_bubbleable_metadata;
    
// If there is a user object in the current route.     if ($user = $this->routeMatch->getParameter('user')) {
      if ($user instanceof UserInterface) {
        return $user->id();
      }
    }

    // If option to use node author; and node in current route.     if (!empty($this->options['user']) && $node = $this->routeMatch->getParameter('node')) {
      if ($node instanceof NodeInterface) {
        return $node->getOwnerId();
      }
    }
  }

  /** * {@inheritdoc} */
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
  }

  
->setCreatedTime(123456789)
      ->setChangedTime(123456789);
    $comment->save();

    return $comment;
  }

  /** * {@inheritdoc} */
  protected function getExpectedNormalizedEntity() {
    $author = User::load($this->entity->getOwnerId());
    return [
      'cid' => [
        ['value' => 1],
      ],
      'uuid' => [
        ['value' => $this->entity->uuid()],
      ],
      'langcode' => [
        [
          'value' => 'en',
        ],
      ],
Home | Imprint | This part of the site doesn't use cookies.