/**
  * Tests file entity denormalization.
  */
 public function testFileDenormalize()
 {
     $file_params = array('filename' => 'test_1.txt', 'uri' => 'public://test_1.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
     // Create a new file entity.
     $file = File::create($file_params);
     file_put_contents($file->getFileUri(), 'hello world');
     $file->save();
     $serializer = \Drupal::service('serializer');
     $normalized_data = $serializer->normalize($file, 'hal_json');
     $denormalized = $serializer->denormalize($normalized_data, 'Drupal\\file\\Entity\\File', 'hal_json');
     $this->assertTrue($denormalized instanceof File, 'A File instance was created.');
     $this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.');
     $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
     $this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found');
     $this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.');
     $this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.');
     $this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.');
     // Try to denormalize with the file uri only.
     $file_name = 'test_2.txt';
     $file_path = 'public://' . $file_name;
     file_put_contents($file_path, 'hello world');
     $file_uri = file_create_url($file_path);
     $data = array('uri' => array(array('value' => $file_uri)));
     $denormalized = $serializer->denormalize($data, 'Drupal\\file\\Entity\\File', 'hal_json');
     $this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.');
     $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.');
     $this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.');
     $this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.');
     $this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.');
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->installEntitySchema('node');
     $this->installSchema('file', ['file_usage']);
     $this->installSchema('node', ['node_access']);
     $id_mappings = array('d6_file' => array());
     // Create new file entities.
     for ($i = 1; $i <= 3; $i++) {
         $file = File::create(array('fid' => $i, 'uid' => 1, 'filename' => 'druplicon.txt', 'uri' => "public://druplicon-{$i}.txt", 'filemime' => 'text/plain', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT));
         $file->enforceIsNew();
         file_put_contents($file->getFileUri(), 'hello world');
         // Save it, inserting a new record.
         $file->save();
         $id_mappings['d6_file'][] = array(array($i), array($i));
     }
     $this->prepareMigrations($id_mappings);
     $this->migrateContent();
     // Since we are only testing a subset of the file migration, do not check
     // that the full file migration has been run.
     $migration = $this->getMigration('d6_upload');
     $migration->set('requirements', []);
     $this->executeMigration($migration);
 }
 /**
  * Tests if public file is always accessible.
  */
 function testFileAccess()
 {
     // Create a new file entity.
     $file = File::create(array('uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'public://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT));
     file_put_contents($file->getFileUri(), 'hello world');
     // Save it, inserting a new record.
     $file->save();
     // Create authenticated user to check file access.
     $account = $this->createUser(array('access site reports'));
     $this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
     $this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
     // Create anonymous user to check file access.
     $account = $this->createUser()->getAnonymousUser();
     $this->assertTrue($file->access('view', $account), 'Public file is viewable to anonymous user');
     $this->assertTrue($file->access('download', $account), 'Public file is downloadable to anonymous user');
     // Create a new file entity.
     $file = File::create(array('uid' => 1, 'filename' => 'drupal.txt', 'uri' => 'private://drupal.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT));
     file_put_contents($file->getFileUri(), 'hello world');
     // Save it, inserting a new record.
     $file->save();
     // Create authenticated user to check file access.
     $account = $this->createUser(array('access site reports'));
     $this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
     $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
     // Create anonymous user to check file access.
     $account = $this->createUser()->getAnonymousUser();
     $this->assertFalse($file->access('view', $account), 'Private file is not viewable to anonymous user');
     $this->assertFalse($file->access('download', $account), 'Private file is not downloadable to anonymous user');
 }
Beispiel #4
0
 /**
  * Creates a file with a given size.
  *
  * @param string $uri
  *   URI of the file to create.
  * @param int $size
  *   Size of the file.
  * @param int $uid
  *   File owner ID.
  * @param int $status
  *   Whether the file should be permanent or temporary.
  *
  * @return \Drupal\Core\Entity\EntityInterface
  *   The file entity.
  */
 protected function createFileWithSize($uri, $size, $uid, $status = FILE_STATUS_PERMANENT)
 {
     file_put_contents($uri, $this->randomMachineName($size));
     $file = File::create(['uri' => $uri, 'uid' => $uid, 'status' => $status]);
     $file->save();
     return $file;
 }
 /**
  * Tests the editor file reference filter.
  */
 function testEditorFileReferenceFilter()
 {
     $filter = $this->filters['editor_file_reference'];
     $test = function ($input) use($filter) {
         return $filter->process($input, 'und');
     };
     file_put_contents('public://llama.jpg', $this->randomMachineName());
     $image = File::create(['uri' => 'public://llama.jpg']);
     $image->save();
     $id = $image->id();
     $uuid = $image->uuid();
     $cache_tag = ['file:' . $id];
     file_put_contents('public://alpaca.jpg', $this->randomMachineName());
     $image_2 = File::create(['uri' => 'public://alpaca.jpg']);
     $image_2->save();
     $id_2 = $image_2->id();
     $uuid_2 = $image_2->uuid();
     $cache_tag_2 = ['file:' . $id_2];
     $this->pass('No data-entity-type and no data-entity-uuid attribute.');
     $input = '<img src="llama.jpg" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->pass('A non-file data-entity-type attribute value.');
     $input = '<img src="llama.jpg" data-entity-type="invalid-entity-type-value" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->pass('One data-entity-uuid attribute.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute with odd capitalization.');
     $input = '<img src="llama.jpg" data-entity-type="file" DATA-entity-UUID =   "' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute on a non-image tag.');
     $input = '<video src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
     $this->pass('One data-entity-uuid attribute with an invalid value.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="invalid-' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual(array(), $output->getCacheTags());
     $this->pass('Two different data-entity-uuid attributes.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $input .= '<img src="alpaca.jpg" data-entity-type="file" data-entity-uuid="' . $uuid_2 . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual(Cache::mergeTags($cache_tag, $cache_tag_2), $output->getCacheTags());
     $this->pass('Two identical  data-entity-uuid attributes.');
     $input = '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $input .= '<img src="llama.jpg" data-entity-type="file" data-entity-uuid="' . $uuid . '" />';
     $output = $test($input);
     $this->assertIdentical($input, $output->getProcessedText());
     $this->assertEqual($cache_tag, $output->getCacheTags());
 }
 /**
  * Retrieves a sample file of the specified type.
  *
  * @return \Drupal\file\FileInterface
  */
 function getTestFile($type_name, $size = NULL)
 {
     // Get a file to upload.
     $file = current($this->drupalGetTestFiles($type_name, $size));
     // Add a filesize property to files as would be read by
     // \Drupal\file\Entity\File::load().
     $file->filesize = filesize($file->uri);
     return File::create((array) $file);
 }
 /**
  * Tests normal formatter display on node display.
  */
 function testNodeDisplay()
 {
     $field_name = strtolower($this->randomMachineName());
     $type_name = 'article';
     $field_storage_settings = array('display_field' => '1', 'display_default' => '1', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
     $field_settings = array('description_field' => '1');
     $widget_settings = array();
     $this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings);
     // Create a new node *without* the file field set, and check that the field
     // is not shown for each node display.
     $node = $this->drupalCreateNode(array('type' => $type_name));
     // Check file_default last as the assertions below assume that this is the
     // case.
     $file_formatters = array('file_table', 'file_url_plain', 'hidden', 'file_default');
     foreach ($file_formatters as $formatter) {
         $edit = array("fields[{$field_name}][type]" => $formatter);
         $this->drupalPostForm("admin/structure/types/manage/{$type_name}/display", $edit, t('Save'));
         $this->drupalGet('node/' . $node->id());
         $this->assertNoText($field_name, format_string('Field label is hidden when no file attached for formatter %formatter', array('%formatter' => $formatter)));
     }
     $test_file = $this->getTestFile('text');
     simpletest_generate_file('escaped-&-text', 64, 10, 'text');
     $test_file = File::create(['uri' => 'public://escaped-&-text.txt', 'name' => 'escaped-&-text', 'filesize' => filesize('public://escaped-&-text.txt')]);
     // Create a new node with the uploaded file.
     $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
     // Check that the default formatter is displaying with the file name.
     $node_storage = $this->container->get('entity.manager')->getStorage('node');
     $node_storage->resetCache(array($nid));
     $node = $node_storage->load($nid);
     $node_file = File::load($node->{$field_name}->target_id);
     $file_link = array('#theme' => 'file_link', '#file' => $node_file);
     $default_output = \Drupal::service('renderer')->renderRoot($file_link);
     $this->assertRaw($default_output, 'Default formatter displaying correctly on full node view.');
     // Turn the "display" option off and check that the file is no longer displayed.
     $edit = array($field_name . '[0][display]' => FALSE);
     $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
     $this->assertNoRaw($default_output, 'Field is hidden when "display" option is unchecked.');
     // Add a description and make sure that it is displayed.
     $description = $this->randomMachineName();
     $edit = array($field_name . '[0][description]' => $description, $field_name . '[0][display]' => TRUE);
     $this->drupalPostForm('node/' . $nid . '/edit', $edit, t('Save and keep published'));
     $this->assertText($description);
     // Ensure the filename in the link's title attribute is escaped.
     $this->assertRaw('title="escaped-&amp;-text.txt"');
     // Test that fields appear as expected after during the preview.
     // Add a second file.
     $name = 'files[' . $field_name . '_1][]';
     $edit[$name] = drupal_realpath($test_file->getFileUri());
     // Uncheck the display checkboxes and go to the preview.
     $edit[$field_name . '[0][display]'] = FALSE;
     $edit[$field_name . '[1][display]'] = FALSE;
     $this->drupalPostForm("node/{$nid}/edit", $edit, t('Preview'));
     $this->clickLink(t('Back to content editing'));
     $this->assertRaw($field_name . '[0][display]', 'First file appears as expected.');
     $this->assertRaw($field_name . '[1][display]', 'Second file appears as expected.');
 }
 protected function setUp()
 {
     parent::setUp();
     FieldStorageConfig::create(array('entity_type' => 'entity_test', 'field_name' => 'image_test', 'type' => 'image', 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED))->save();
     FieldConfig::create(['entity_type' => 'entity_test', 'field_name' => 'image_test', 'bundle' => 'entity_test'])->save();
     file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example.jpg');
     $this->image = File::create(['uri' => 'public://example.jpg']);
     $this->image->save();
     $this->imageFactory = $this->container->get('image.factory');
 }
Beispiel #9
0
 /**
  * Tests the normalize function.
  */
 public function testNormalize()
 {
     $file_params = array('filename' => 'test_1.txt', 'uri' => 'public://test_1.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
     // Create a new file entity.
     $file = File::create($file_params);
     file_put_contents($file->getFileUri(), 'hello world');
     $file->save();
     $expected_array = array('uri' => array(array('value' => file_create_url($file->getFileUri()))));
     $normalized = $this->serializer->normalize($file, $this->format);
     $this->assertEqual($normalized['uri'], $expected_array['uri'], 'URI is normalized.');
 }
 /**
  * {@inheritdoc}
  */
 function setUp()
 {
     parent::setUp();
     $this->addLanguage('de');
     $filtered_html_format = FilterFormat::create(array('format' => 'filtered_html', 'name' => 'Filtered HTML'));
     $filtered_html_format->save();
     $this->drupalCreateContentType(array('type' => 'test_bundle'));
     $this->loginAsAdmin(array('create translation jobs', 'submit translation jobs', 'create test_bundle content', $filtered_html_format->getPermissionName()));
     file_unmanaged_copy(DRUPAL_ROOT . '/core/misc/druplicon.png', 'public://example.jpg');
     $this->image = File::create(array('uri' => 'public://example.jpg'));
     $this->image->save();
 }
 /**
  * Tests using entity fields of the image field type.
  */
 public function testImageItem()
 {
     // Create a test entity with the image field set.
     $entity = EntityTest::create();
     $entity->image_test->target_id = $this->image->id();
     $entity->image_test->alt = $alt = $this->randomMachineName();
     $entity->image_test->title = $title = $this->randomMachineName();
     $entity->name->value = $this->randomMachineName();
     $entity->save();
     $entity = entity_load('entity_test', $entity->id());
     $this->assertTrue($entity->image_test instanceof FieldItemListInterface, 'Field implements interface.');
     $this->assertTrue($entity->image_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     $this->assertEqual($entity->image_test->alt, $alt);
     $this->assertEqual($entity->image_test->title, $title);
     $image = $this->imageFactory->get('public://example.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->entity->id(), $this->image->id());
     $this->assertEqual($entity->image_test->entity->uuid(), $this->image->uuid());
     // Make sure the computed entity reflects updates to the referenced file.
     file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', 'public://example-2.jpg');
     $image2 = File::create(['uri' => 'public://example-2.jpg']);
     $image2->save();
     $entity->image_test->target_id = $image2->id();
     $entity->image_test->alt = $new_alt = $this->randomMachineName();
     // The width and height is only updated when width is not set.
     $entity->image_test->width = NULL;
     $entity->save();
     $this->assertEqual($entity->image_test->entity->id(), $image2->id());
     $this->assertEqual($entity->image_test->entity->getFileUri(), $image2->getFileUri());
     $image = $this->imageFactory->get('public://example-2.jpg');
     $this->assertEqual($entity->image_test->width, $image->getWidth());
     $this->assertEqual($entity->image_test->height, $image->getHeight());
     $this->assertEqual($entity->image_test->alt, $new_alt);
     // Check that the image item can be set to the referenced file directly.
     $entity->image_test = $this->image;
     $this->assertEqual($entity->image_test->target_id, $this->image->id());
     // Delete the image and try to save the entity again.
     $this->image->delete();
     $entity = EntityTest::create(array('mame' => $this->randomMachineName()));
     $entity->save();
     // Test image item properties.
     $expected = array('target_id', 'entity', 'alt', 'title', 'width', 'height');
     $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
     $this->assertEqual(array_keys($properties), $expected);
     // Test the generateSampleValue() method.
     $entity = EntityTest::create();
     $entity->image_test->generateSampleItems();
     $this->entityValidateAndSave($entity);
     $this->assertEqual($entity->image_test->entity->get('filemime')->value, 'image/jpeg');
 }
Beispiel #12
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->installEntitySchema('user');
     $this->installSchema('file', array('file_usage'));
     $this->installSchema('system', 'sequences');
     $this->user1 = User::create(['name' => 'user1', 'status' => 1]);
     $this->user1->save();
     $this->user2 = User::create(['name' => 'user2', 'status' => 1]);
     $this->user2->save();
     $this->file = File::create(array('uid' => $this->user1->id(), 'filename' => 'druplicon.txt', 'filemime' => 'text/plain'));
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     ViewTestData::createTestViews(get_class($this), array('file_test_views'));
     $this->installEntitySchema('file');
     file_put_contents('public://file.png', '');
     File::create(['uri' => 'public://file.png', 'filename' => 'file.png'])->save();
     file_put_contents('public://file.tar', '');
     File::create(['uri' => 'public://file.tar', 'filename' => 'file.tar'])->save();
     file_put_contents('public://file.tar.gz', '');
     File::create(['uri' => 'public://file.tar.gz', 'filename' => 'file.tar.gz'])->save();
     file_put_contents('public://file', '');
     File::create(['uri' => 'public://file', 'filename' => 'file'])->save();
 }
Beispiel #14
0
 /**
  * Saves a file for an entity and returns the file's ID.
  *
  * @param string $filename
  *   The file name given by the user.
  * @param string $files_path
  *   The file path where the file exists in.
  *
  * @return int
  *   The file ID returned by the File::save() method.
  *
  * @throws \Exception
  *   Throws an exception when the file is not found.
  */
 public function createFile($filename, $files_path)
 {
     $path = rtrim(realpath($files_path), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $filename;
     if (!is_file($path)) {
         throw new \Exception("File '{$filename}' was not found in file path '{$files_path}'.");
     }
     // Copy the file into the public files folder and turn it into a File
     // entity before linking it to the collection.
     $uri = 'public://' . $filename;
     $destination = file_unmanaged_copy($path, $uri);
     $file = File::create(['uri' => $destination]);
     $file->save();
     $this->files[$file->id()] = $file;
     return $file->id();
 }
Beispiel #15
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->installSchema('file', ['file_usage']);
     $file = File::create(array('fid' => 2, 'uid' => 2, 'filename' => 'image-test.jpg', 'uri' => "public://image-test.jpg", 'filemime' => 'image/jpeg', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT));
     $file->enforceIsNew();
     file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-1.png'));
     $file->save();
     $file = File::create(array('fid' => 8, 'uid' => 8, 'filename' => 'image-test.png', 'uri' => "public://image-test.png", 'filemime' => 'image/png', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT));
     $file->enforceIsNew();
     file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-2.jpg'));
     $file->save();
     $this->migrateUsers();
 }
  protected function validatePdfUpload(array &$form, FormStateInterface &$form_state, UploadedFile $file_upload, $file_field_name) {
    /**
     * @var $file_upload \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    if ($file_upload && $file_upload->isValid()) {
      // Move it to somewhere we know.
      $uploaded_filename = $file_upload->getClientOriginalName();

      // Ensure the destination is unique; we deliberately use managed files,
      // but they are keyed on file URI, so we can't save the same one twice.
      $scheme = $this->config('fillpdf.settings')->get('scheme');
      $destination = file_destination(FillPdf::buildFileUri($scheme, 'fillpdf/' . $uploaded_filename), FILE_EXISTS_RENAME);

      // Ensure our directory exists.
      $fillpdf_directory = FillPdf::buildFileUri($scheme, 'fillpdf');
      $directory_exists = file_prepare_directory($fillpdf_directory, FILE_CREATE_DIRECTORY + FILE_MODIFY_PERMISSIONS);

      if ($directory_exists) {
        $file_moved = $this->fileSystem->moveUploadedFile($file_upload->getRealPath(), $destination);

        if ($file_moved) {
          // Create a File object from the uploaded file.
          $new_file = File::create([
            'uri' => $destination,
            'uid' => $this->currentUser()->id(),
          ]);

          $errors = file_validate_extensions($new_file, 'pdf');

          if (count($errors)) {
            $form_state->setErrorByName('upload_pdf', $this->t('Only PDF files are supported, and they must end in .pdf.'));
          }
          else {
            $form_state->setValue('upload_pdf', $new_file);
          }
        }
        else {
          $form_state->setErrorByName('upload_pdf', $this->t("Could not move your uploaded file from PHP's temporary location to Drupal file storage."));
        }
      }
      else {
        $form_state->setErrorByName('upload_pdf', $this->t('Could not automatically create the <em>fillpdf</em> subdirectory. Please create this manually before uploading your PDF form.'));
      }
    }
    else {
      $form_state->setErrorByName('upload_pdf', $this->t('Your PDF could not be uploaded. Did you select one?'));
    }
  }
 function testFileSave()
 {
     // Create a new file entity.
     $file = File::create(array('uid' => 1, 'filename' => 'druplicon.txt', 'uri' => 'public://druplicon.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT));
     file_put_contents($file->getFileUri(), 'hello world');
     // Save it, inserting a new record.
     $file->save();
     // Check that the correct hooks were called.
     $this->assertFileHooksCalled(array('insert'));
     $this->assertTrue($file->id() > 0, 'A new file ID is set when saving a new file to the database.', 'File');
     $loaded_file = file_load($file->id());
     $this->assertNotNull($loaded_file, 'Record exists in the database.');
     $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.');
     $this->assertEqual($file->getSize(), filesize($file->getFileUri()), 'File size was set correctly.', 'File');
     $this->assertTrue($file->getChangedTime() > 1, 'File size was set correctly.', 'File');
     $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was defaulted correctly.');
     // Resave the file, updating the existing record.
     file_test_reset();
     $file->status->value = 7;
     $file->save();
     // Check that the correct hooks were called.
     $this->assertFileHooksCalled(array('load', 'update'));
     $this->assertEqual($file->id(), $file->id(), 'The file ID of an existing file is not changed when updating the database.', 'File');
     $this->assertTrue($file->getChangedTime() >= $file->getChangedTime(), "Timestamp didn't go backwards.", 'File');
     $loaded_file = file_load($file->id());
     $this->assertNotNull($loaded_file, 'Record still exists in the database.', 'File');
     $this->assertEqual($loaded_file->isPermanent(), $file->isPermanent(), 'Status was saved correctly.');
     $this->assertEqual($loaded_file->langcode->value, 'en', 'Langcode was saved correctly.');
     // Try to insert a second file with the same name apart from case insensitivity
     // to ensure the 'uri' index allows for filenames with different cases.
     $uppercase_values = array('uid' => 1, 'filename' => 'DRUPLICON.txt', 'uri' => 'public://DRUPLICON.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT);
     $uppercase_file = File::create($uppercase_values);
     file_put_contents($uppercase_file->getFileUri(), 'hello world');
     $violations = $uppercase_file->validate();
     $this->assertEqual(count($violations), 0, 'No violations when adding an URI with an existing filename in upper case.');
     $uppercase_file->save();
     // Ensure the database URI uniqueness constraint is triggered.
     $uppercase_file_duplicate = File::create($uppercase_values);
     file_put_contents($uppercase_file_duplicate->getFileUri(), 'hello world');
     $violations = $uppercase_file_duplicate->validate();
     $this->assertEqual(count($violations), 1);
     $this->assertEqual($violations[0]->getMessage(), t('The file %value already exists. Enter a unique file URI.', ['%value' => $uppercase_file_duplicate->getFileUri()]));
     // Ensure that file URI entity queries are case sensitive.
     $fids = \Drupal::entityQuery('file')->condition('uri', $uppercase_file->getFileUri())->execute();
     $this->assertEqual(1, count($fids));
     $this->assertEqual(array($uppercase_file->id() => $uppercase_file->id()), $fids);
 }
 /**
  * Tests using the views image relationship.
  */
 public function testViewsHandlerRelationshipUserImageData()
 {
     $file = File::create(['fid' => 2, 'uid' => 2, 'filename' => 'image-test.jpg', 'uri' => "public://image-test.jpg", 'filemime' => 'image/jpeg', 'created' => 1, 'changed' => 1, 'status' => FILE_STATUS_PERMANENT]);
     $file->enforceIsNew();
     file_put_contents($file->getFileUri(), file_get_contents('core/modules/simpletest/files/image-1.png'));
     $file->save();
     $account = $this->drupalCreateUser();
     $account->user_picture->target_id = 2;
     $account->save();
     $view = Views::getView('test_image_user_image_data');
     // Tests \Drupal\taxonomy\Plugin\views\relationship\NodeTermData::calculateDependencies().
     $expected = ['module' => ['file', 'user']];
     $this->assertIdentical($expected, $view->getDependencies());
     $this->executeView($view);
     $expected_result = array(array('file_managed_user__user_picture_fid' => '2'));
     $column_map = array('file_managed_user__user_picture_fid' => 'file_managed_user__user_picture_fid');
     $this->assertIdenticalResultset($view, $expected_result, $column_map);
 }
 /**
  * Tests the editor file reference filter with private files.
  */
 function testEditorPrivateFileReferenceFilter()
 {
     $author = $this->drupalCreateUser();
     $this->drupalLogin($author);
     // Create a content type with a body field.
     $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
     // Create a file in the 'private:// ' stream.
     $filename = 'test.png';
     $src = '/system/files/' . $filename;
     /** @var \Drupal\file\FileInterface $file */
     $file = File::create(['uri' => 'private://' . $filename]);
     $file->setTemporary();
     $file->setOwner($author);
     // Create the file itself.
     file_put_contents($file->getFileUri(), $this->randomString());
     $file->save();
     // The image should be visible for its author.
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(200);
     // The not-yet-permanent image should NOT be visible for anonymous.
     $this->drupalLogout();
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(403);
     // Resave the file to be permanent.
     $file->setPermanent();
     $file->save();
     // Create a node with its body field properly pointing to the just-created
     // file.
     $node = $this->drupalCreateNode(['type' => 'page', 'body' => ['value' => '<img alt="alt" data-entity-type="file" data-entity-uuid="' . $file->uuid() . '" src="' . $src . '" />', 'format' => 'private_images'], 'uid' => $author->id()]);
     // Do the actual test. The image should be visible for anonymous users,
     // because they can view the referencing entity.
     $this->drupalGet($node->toUrl());
     $this->assertSession()->statusCodeEquals(200);
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(200);
     // Disallow anonymous users to view the entity, which then should also
     // disallow them to view the image.
     Role::load(RoleInterface::ANONYMOUS_ID)->revokePermission('access content')->save();
     $this->drupalGet($node->toUrl());
     $this->assertSession()->statusCodeEquals(403);
     $this->drupalGet($src);
     $this->assertSession()->statusCodeEquals(403);
 }
 /**
  * @covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraint
  * @covers \Drupal\file\Plugin\Validation\Constraint\FileValidationConstraintValidator
  * @dataProvider getFileTypes
  */
 public function testFileValidationConstraint($file_type)
 {
     $field_storage = FieldStorageConfig::create(['field_name' => 'field_test_file', 'entity_type' => 'entity_test', 'type' => $file_type]);
     $field_storage->save();
     $field = FieldConfig::create(['field_name' => 'field_test_file', 'entity_type' => 'entity_test', 'bundle' => 'entity_test', 'settings' => ['max_filesize' => '2k', 'file_extensions' => 'jpg|png']]);
     $field->save();
     vfsStream::setup('drupal_root');
     vfsStream::create(['sites' => ['default' => ['files' => ['test.txt' => str_repeat('a', 3000)]]]]);
     // Test for max filesize.
     $file = File::create(['uri' => 'vfs://drupal_root/sites/default/files/test.txt']);
     $file->save();
     $entity_test = EntityTest::create(['uid' => $this->user->id(), 'field_test_file' => ['target_id' => $file->id()]]);
     $result = $entity_test->validate();
     $this->assertCount(2, $result);
     $this->assertEquals('field_test_file.0', $result->get(0)->getPropertyPath());
     $this->assertEquals('The file is <em class="placeholder">2.93 KB</em> exceeding the maximum file size of <em class="placeholder">2 KB</em>.', (string) $result->get(0)->getMessage());
     $this->assertEquals('field_test_file.0', $result->get(1)->getPropertyPath());
     $this->assertEquals('Only files with the following extensions are allowed: <em class="placeholder">jpg|png</em>.', (string) $result->get(1)->getMessage());
 }
 /**
  * Test the resize feature.
  */
 public function testResizeImages()
 {
     global $base_url;
     $druplicon = 'core/misc/druplicon.png';
     $uri = file_unmanaged_copy($druplicon, 'public://druplicon.png', FILE_EXISTS_REPLACE);
     $file = File::create(['uri' => $uri, 'uuid' => 'thisisauuid']);
     $file->save();
     $relative_path = str_replace($base_url, '', file_create_url($uri));
     $images['inline-image'] = '<img alt="This is a description" data-entity-type="file" data-entity-uuid="' . $file->uuid() . '" height="50" src="' . $relative_path . '" width="44">';
     $comment = [];
     foreach ($images as $key => $image) {
         $comment[$key] = $image;
     }
     $edit = array('comment_body[0][value]' => implode("\n", $comment));
     $this->drupalPostForm('node/' . $this->node->id(), $edit, t('Save'));
     $expected = 'public://resize/druplicon-44x50.png';
     $expected_relative_path = str_replace($base_url, '', file_create_url($expected));
     $this->assertNoRaw($relative_path, 'The original image is gone.');
     $this->assertRaw($expected_relative_path, 'The resize version was found.');
     $this->assertTrue(file_exists($expected), 'The resize file exists.');
 }
Beispiel #22
0
 /**
  * Tests moving a randomly generated image.
  */
 function testNormal()
 {
     // Pick a file for testing.
     $file = File::create((array) current($this->drupalGetTestFiles('image')));
     // Create derivative image.
     $styles = ImageStyle::loadMultiple();
     $style = reset($styles);
     $original_uri = $file->getFileUri();
     $derivative_uri = $style->buildUri($original_uri);
     $style->createDerivative($original_uri, $derivative_uri);
     // Check if derivative image exists.
     $this->assertTrue(file_exists($derivative_uri), 'Make sure derivative image is generated successfully.');
     // Clone the object so we don't have to worry about the function changing
     // our reference copy.
     $desired_filepath = 'public://' . $this->randomMachineName();
     $result = file_move(clone $file, $desired_filepath, FILE_EXISTS_ERROR);
     // Check if image has been moved.
     $this->assertTrue(file_exists($result->getFileUri()), 'Make sure image is moved successfully.');
     // Check if derivative image has been flushed.
     $this->assertFalse(file_exists($derivative_uri), 'Make sure derivative image has been flushed.');
 }
 /**
  * Check access for file fields.
  */
 public function testFileFields()
 {
     ConfigurableLanguage::create(['id' => 'fr', 'name' => 'French'])->save();
     $user = User::create(['name' => 'test user']);
     $user->save();
     file_put_contents('public://test.txt', 'test');
     $file = File::create(['filename' => 'test.txt', 'uri' => 'public://test.txt', 'status' => TRUE, 'langcode' => 'fr', 'uid' => $user->id()]);
     $file->save();
     // @todo Expand the test coverage in https://www.drupal.org/node/2464635
     $this->assertFieldAccess('file', 'fid', $file->id());
     $this->assertFieldAccess('file', 'uuid', $file->uuid());
     $this->assertFieldAccess('file', 'langcode', $file->language()->getName());
     $this->assertFieldAccess('file', 'uid', 'test user');
     $this->assertFieldAccess('file', 'filename', $file->getFilename());
     $this->assertFieldAccess('file', 'uri', $file->getFileUri());
     $this->assertFieldAccess('file', 'filemime', $file->filemime->value);
     $this->assertFieldAccess('file', 'filesize', '4 bytes');
     $this->assertFieldAccess('file', 'status', t('Permanent'));
     // $this->assertFieldAccess('file', 'created', \Drupal::service('date.formatter')->format(123456));
     // $this->assertFieldAccess('file', 'changed', \Drupal::service('date.formatter')->format(REQUEST_TIME));
 }
 /**
  * Tests devel silent.
  */
 public function testDevelSilent()
 {
     // TODO Quickfix for dynamic_page_cache, enabled by default in the testing
     // profile.
     $this->container->get('module_installer')->uninstall(['dynamic_page_cache']);
     $web_user = $this->drupalCreateUser(['administer site configuration', 'access devel information', 'administer software updates']);
     $this->drupalLogin($web_user);
     // Ensure that devel is disabled if response come from routes that are
     // declared with '_devel_silent' requirement.
     $this->drupalGet('devel-silent/route-requirement');
     $this->assertText(t('"_devel_silent" route requirement forces devel to be inactive.'));
     // Ensure that devel doesn't interfere with non html response (e.g JsonResponse).
     $response = $this->drupalGet('devel-silent/json');
     $this->assertResponse(200);
     $expected = ['data' => 'Devel is active only on HtmlResponse.'];
     $this->assertIdentical(Json::decode($response), $expected);
     // Ensure that devel doesn't interfere with private image style creation
     // and with BinaryFileResponse response.
     $style = ImageStyle::create(['name' => 'zyx', 'label' => $this->randomString()]);
     $style->save();
     $image = current($this->drupalGetTestFiles('image'));
     $image_uri = file_unmanaged_copy($image->uri, 'private://');
     // Let the devel_test module know about this file, so it can claim
     // ownership in hook_file_download().
     \Drupal::state()->set('devel.test_file_download', $image_uri);
     $this->drupalGet($style->buildUrl($image_uri));
     $this->assertResponse(200);
     $this->assertRaw(file_get_contents($style->buildUri($image_uri)), 'URL returns expected file.');
     // Ensure that devel doesn't interfere with private files and with
     // BinaryFileResponse response.
     $file = File::create(['uid' => $web_user->id(), 'filename' => 'drupal.txt', 'uri' => 'private://devel.txt', 'filemime' => 'text/plain', 'status' => FILE_STATUS_PERMANENT]);
     file_put_contents($file->getFileUri(), 'Hello world!');
     $file->save();
     // Let the image_module_test module know about this file, so it can claim
     // ownership in hook_file_download().
     \Drupal::state()->set('devel.test_file_download', $file->getFileUri());
     $this->drupalGet($file->url());
     $this->assertResponse(200);
     $this->assertRaw(file_get_contents($file->getFileUri()), 'URL returns expected file.');
 }
Beispiel #25
0
 protected function setUp()
 {
     parent::setUp();
     $account = $this->drupalCreateUser(array('access site reports'));
     $this->drupalLogin($account);
     $image_files = $this->drupalGetTestFiles('image');
     $this->image = File::create((array) current($image_files));
     list(, $this->imageExtension) = explode('.', $this->image->getFilename());
     $this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
     $this->phpfile = current($this->drupalGetTestFiles('php'));
     $this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
     $this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
     // Upload with replace to guarantee there's something there.
     $edit = array('file_test_replace' => FILE_EXISTS_REPLACE, 'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()));
     $this->drupalPostForm('file-test/upload', $edit, t('Submit'));
     $this->assertResponse(200, 'Received a 200 response for posted test file.');
     $this->assertRaw(t('You WIN!'), 'Found the success message.');
     // Check that the correct hooks were called then clean out the hook
     // counters.
     $this->assertFileHooksCalled(array('validate', 'insert'));
     file_test_reset();
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->installEntitySchema('file');
     $this->files = [];
     file_put_contents('public://file.png', str_repeat('t', 10));
     $file = File::create(['uri' => 'public://file.png', 'filename' => 'file.png']);
     $file->save();
     $this->files[] = $file;
     file_put_contents('public://file.tar', str_repeat('t', 200));
     $file = File::create(['uri' => 'public://file.tar', 'filename' => 'file.tar']);
     $file->save();
     $this->files[] = $file;
     file_put_contents('public://file.tar.gz', str_repeat('t', 40000));
     $file = File::create(['uri' => 'public://file.tar.gz', 'filename' => 'file.tar.gz']);
     $file->save();
     $this->files[] = $file;
     file_put_contents('public://file', str_repeat('t', 8000000));
     $file = File::create(['uri' => 'public://file', 'filename' => 'file']);
     $file->save();
     $this->files[] = $file;
 }
  public function testFileEntityClone() {
    /** @var \Drupal\file\FileInterface $file */
    $file = File::create(array(
      'uid' => 1,
      'filename' => 'druplicon.txt',
      'uri' => 'public://druplicon.txt',
      'filemime' => 'text/plain',
      'status' => FILE_STATUS_PERMANENT,
    ));
    file_put_contents($file->getFileUri(), 'hello world');
    $file->save();

    $this->drupalPostForm('entity_clone/file/' . $file->id(), [], t('Clone'));

    $files = \Drupal::entityTypeManager()
      ->getStorage('file')
      ->loadByProperties([
        'filename' => 'druplicon.txt - Cloned',
      ]);
    $file = reset($files);
    $this->assertTrue($file, 'Test file cloned found in database.');

    $this->assertEqual($file->getFileUri(), 'public://druplicon_0.txt', 'The stored file is also cloned.');
  }
 /**
  * Tests image field field synchronization.
  */
 function testImageFieldSync()
 {
     // Check that the alt and title fields are enabled for the image field.
     $this->drupalLogin($this->editor);
     $this->drupalGet('entity_test_mul/structure/' . $this->entityTypeId . '/fields/' . $this->entityTypeId . '.' . $this->entityTypeId . '.' . $this->fieldName);
     $this->assertFieldChecked('edit-third-party-settings-content-translation-translation-sync-alt');
     $this->assertFieldChecked('edit-third-party-settings-content-translation-translation-sync-title');
     $edit = array('third_party_settings[content_translation][translation_sync][alt]' => FALSE, 'third_party_settings[content_translation][translation_sync][title]' => FALSE);
     $this->drupalPostForm(NULL, $edit, t('Save settings'));
     // Check that the content translation settings page reflects the changes
     // performed in the field edit page.
     $this->drupalGet('admin/config/regional/content-language');
     $this->assertNoFieldChecked('edit-settings-entity-test-mul-entity-test-mul-columns-field-test-et-ui-image-alt');
     $this->assertNoFieldChecked('edit-settings-entity-test-mul-entity-test-mul-columns-field-test-et-ui-image-title');
     $edit = array('settings[entity_test_mul][entity_test_mul][fields][field_test_et_ui_image]' => TRUE, 'settings[entity_test_mul][entity_test_mul][columns][field_test_et_ui_image][alt]' => TRUE, 'settings[entity_test_mul][entity_test_mul][columns][field_test_et_ui_image][title]' => TRUE);
     $this->drupalPostForm('admin/config/regional/content-language', $edit, t('Save configuration'));
     $errors = $this->xpath('//div[contains(@class, "messages--error")]');
     $this->assertFalse($errors, 'Settings correctly stored.');
     $this->assertFieldChecked('edit-settings-entity-test-mul-entity-test-mul-columns-field-test-et-ui-image-alt');
     $this->assertFieldChecked('edit-settings-entity-test-mul-entity-test-mul-columns-field-test-et-ui-image-title');
     $this->drupalLogin($this->translator);
     $default_langcode = $this->langcodes[0];
     $langcode = $this->langcodes[1];
     // Populate the test entity with some random initial values.
     $values = array('name' => $this->randomMachineName(), 'user_id' => mt_rand(1, 128), 'langcode' => $default_langcode);
     $entity = entity_create($this->entityTypeId, $values);
     // Create some file entities from the generated test files and store them.
     $values = array();
     for ($delta = 0; $delta < $this->cardinality; $delta++) {
         // For the default language use the same order for files and field items.
         $index = $delta;
         // Create the file entity for the image being processed and record its
         // identifier.
         $field_values = array('uri' => $this->files[$index]->uri, 'uid' => \Drupal::currentUser()->id(), 'status' => FILE_STATUS_PERMANENT);
         $file = File::create($field_values);
         $file->save();
         $fid = $file->id();
         $this->files[$index]->fid = $fid;
         // Generate the item for the current image file entity and attach it to
         // the entity.
         $item = array('target_id' => $fid, 'alt' => $default_langcode . '_' . $fid . '_' . $this->randomMachineName(), 'title' => $default_langcode . '_' . $fid . '_' . $this->randomMachineName());
         $entity->{$this->fieldName}[] = $item;
         // Store the generated values keying them by fid for easier lookup.
         $values[$default_langcode][$fid] = $item;
     }
     $entity = $this->saveEntity($entity);
     // Create some field translations for the test image field. The translated
     // items will be one less than the original values to check that only the
     // translated ones will be preserved. In fact we want the same fids and
     // items order for both languages.
     $translation = $entity->addTranslation($langcode);
     for ($delta = 0; $delta < $this->cardinality - 1; $delta++) {
         // Simulate a field reordering: items are shifted of one position ahead.
         // The modulo operator ensures we start from the beginning after reaching
         // the maximum allowed delta.
         $index = ($delta + 1) % $this->cardinality;
         // Generate the item for the current image file entity and attach it to
         // the entity.
         $fid = $this->files[$index]->fid;
         $item = array('target_id' => $fid, 'alt' => $langcode . '_' . $fid . '_' . $this->randomMachineName(), 'title' => $langcode . '_' . $fid . '_' . $this->randomMachineName());
         $translation->{$this->fieldName}[] = $item;
         // Again store the generated values keying them by fid for easier lookup.
         $values[$langcode][$fid] = $item;
     }
     // Perform synchronization: the translation language is used as source,
     // while the default language is used as target.
     $this->manager->getTranslationMetadata($translation)->setSource($default_langcode);
     $entity = $this->saveEntity($translation);
     $translation = $entity->getTranslation($langcode);
     // Check that one value has been dropped from the original values.
     $assert = count($entity->{$this->fieldName}) == 2;
     $this->assertTrue($assert, 'One item correctly removed from the synchronized field values.');
     // Check that fids have been synchronized and translatable column values
     // have been retained.
     $fids = array();
     foreach ($entity->{$this->fieldName} as $delta => $item) {
         $value = $values[$default_langcode][$item->target_id];
         $source_item = $translation->{$this->fieldName}->get($delta);
         $assert = $item->target_id == $source_item->target_id && $item->alt == $value['alt'] && $item->title == $value['title'];
         $this->assertTrue($assert, format_string('Field item @fid has been successfully synchronized.', array('@fid' => $item->target_id)));
         $fids[$item->target_id] = TRUE;
     }
     // Check that the dropped value is the right one.
     $removed_fid = $this->files[0]->fid;
     $this->assertTrue(!isset($fids[$removed_fid]), format_string('Field item @fid has been correctly removed.', array('@fid' => $removed_fid)));
     // Add back an item for the dropped value and perform synchronization again.
     $values[$langcode][$removed_fid] = array('target_id' => $removed_fid, 'alt' => $langcode . '_' . $removed_fid . '_' . $this->randomMachineName(), 'title' => $langcode . '_' . $removed_fid . '_' . $this->randomMachineName());
     $translation->{$this->fieldName}->setValue(array_values($values[$langcode]));
     $entity = $this->saveEntity($translation);
     $translation = $entity->getTranslation($langcode);
     // Check that the value has been added to the default language.
     $assert = count($entity->{$this->fieldName}->getValue()) == 3;
     $this->assertTrue($assert, 'One item correctly added to the synchronized field values.');
     foreach ($entity->{$this->fieldName} as $delta => $item) {
         // When adding an item its value is copied over all the target languages,
         // thus in this case the source language needs to be used to check the
         // values instead of the target one.
         $fid_langcode = $item->target_id != $removed_fid ? $default_langcode : $langcode;
         $value = $values[$fid_langcode][$item->target_id];
         $source_item = $translation->{$this->fieldName}->get($delta);
         $assert = $item->target_id == $source_item->target_id && $item->alt == $value['alt'] && $item->title == $value['title'];
         $this->assertTrue($assert, format_string('Field item @fid has been successfully synchronized.', array('@fid' => $item->target_id)));
     }
 }
 /**
  * Tests ValidReferenceConstraint with newly created and unsaved entities.
  */
 public function testAutocreateValidation()
 {
     // The term entity is unsaved here.
     $term = Term::create(array('name' => $this->randomMachineName(), 'vid' => $this->term->bundle(), 'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED));
     $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]);
     $errors = $entity->validate();
     // Using target_id of NULL is valid with an unsaved entity.
     $this->assertEqual(0, count($errors));
     // Using target_id of NULL is not valid with a saved entity.
     $term->save();
     $entity = EntityTest::create(['field_test_taxonomy_term' => ['entity' => $term, 'target_id' => NULL]]);
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), 'This value should not be null.');
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_taxonomy_term.0');
     // This should rectify the issue, favoring the entity over the target_id.
     $entity->save();
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
     // Test with an unpublished and unsaved node.
     $title = $this->randomString();
     $node = Node::create(['title' => $title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]);
     $entity = EntityTest::create(['field_test_node' => ['entity' => $node]]);
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $title]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
     // Publish the node and try again.
     $node->setPublished(TRUE);
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
     // Test with a mix of valid and invalid nodes.
     $unsaved_unpublished_node_title = $this->randomString();
     $unsaved_unpublished_node = Node::create(['title' => $unsaved_unpublished_node_title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]);
     $saved_unpublished_node_title = $this->randomString();
     $saved_unpublished_node = Node::create(['title' => $saved_unpublished_node_title, 'type' => 'node', 'status' => NODE_NOT_PUBLISHED]);
     $saved_unpublished_node->save();
     $saved_published_node_title = $this->randomString();
     $saved_published_node = Node::create(['title' => $saved_published_node_title, 'type' => 'node', 'status' => NODE_PUBLISHED]);
     $saved_published_node->save();
     $entity = EntityTest::create(['field_test_node' => [['entity' => $unsaved_unpublished_node], ['target_id' => $saved_unpublished_node->id()], ['target_id' => $saved_published_node->id()]]]);
     $errors = $entity->validate();
     $this->assertEqual(2, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
     $this->assertEqual($errors[1]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $saved_unpublished_node->id()]));
     $this->assertEqual($errors[1]->getPropertyPath(), 'field_test_node.1.target_id');
     // Publish one of the nodes and try again.
     $saved_unpublished_node->setPublished(TRUE);
     $saved_unpublished_node->save();
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'node', '%label' => $unsaved_unpublished_node_title]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_node.0.entity');
     // Publish the last invalid node and try again.
     $unsaved_unpublished_node->setPublished(TRUE);
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
     // Test with an unpublished and unsaved comment.
     $title = $this->randomString();
     $comment = Comment::create(['subject' => $title, 'comment_type' => 'comment', 'status' => 0]);
     $entity = EntityTest::create(['field_test_comment' => ['entity' => $comment]]);
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'comment', '%label' => $title]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_comment.0.entity');
     // Publish the comment and try again.
     $comment->setPublished(TRUE);
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
     // Test with an inactive and unsaved user.
     $name = $this->randomString();
     $user = User::create(['name' => $name, 'status' => 0]);
     $entity = EntityTest::create(['field_test_user' => ['entity' => $user]]);
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'user', '%label' => $name]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_user.0.entity');
     // Activate the user and try again.
     $user->activate();
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
     // Test with a temporary and unsaved file.
     $filename = $this->randomMachineName() . '.txt';
     $file = File::create(['filename' => $filename, 'status' => 0]);
     $entity = EntityTest::create(['field_test_file' => ['entity' => $file]]);
     $errors = $entity->validate();
     $this->assertEqual(1, count($errors));
     $this->assertEqual($errors[0]->getMessage(), new FormattableMarkup('This entity (%type: %label) cannot be referenced.', ['%type' => 'file', '%label' => $filename]));
     $this->assertEqual($errors[0]->getPropertyPath(), 'field_test_file.0.entity');
     // Set the file as permanent and try again.
     $file->setPermanent();
     $errors = $entity->validate();
     $this->assertEqual(0, count($errors));
 }
Beispiel #30
0
 /**
  * Tests the basics around constructing and working with typed data objects.
  */
 public function testGetAndSet()
 {
     // Boolean type.
     $typed_data = $this->createTypedData(array('type' => 'boolean'), TRUE);
     $this->assertTrue($typed_data instanceof BooleanInterface, 'Typed data object is an instance of BooleanInterface.');
     $this->assertTrue($typed_data->getValue() === TRUE, 'Boolean value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(FALSE);
     $this->assertTrue($typed_data->getValue() === FALSE, 'Boolean value was changed.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $this->assertTrue(is_string($typed_data->getString()), 'Boolean value was converted to string');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Boolean wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // String type.
     $value = $this->randomString();
     $typed_data = $this->createTypedData(array('type' => 'string'), $value);
     $this->assertTrue($typed_data instanceof StringInterface, 'Typed data object is an instance of StringInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'String value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = $this->randomString();
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'String value was changed.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Funky test.
     $this->assertTrue(is_string($typed_data->getString()), 'String value was converted to string');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'String wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(array('no string'));
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Integer type.
     $value = rand();
     $typed_data = $this->createTypedData(array('type' => 'integer'), $value);
     $this->assertTrue($typed_data instanceof IntegerInterface, 'Typed data object is an instance of IntegerInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'Integer value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = rand();
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Integer value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Integer value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Integer wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Float type.
     $value = 123.45;
     $typed_data = $this->createTypedData(array('type' => 'float'), $value);
     $this->assertTrue($typed_data instanceof FloatInterface, 'Typed data object is an instance of FloatInterface.');
     $this->assertTrue($typed_data->getValue() === $value, 'Float value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = 678.9;
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Float value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Float value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Float wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Date Time type.
     $value = '2014-01-01T20:00:00+00:00';
     $typed_data = $this->createTypedData(array('type' => 'datetime_iso8601'), $value);
     $this->assertTrue($typed_data instanceof DateTimeInterface, 'Typed data object is an instance of DateTimeInterface.');
     $this->assertTrue($typed_data->getValue() == $value, 'Date value was fetched.');
     $this->assertEqual($typed_data->getValue(), $typed_data->getDateTime()->format('c'), 'Value representation of a date is ISO 8601');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = '2014-01-02T20:00:00+00:00';
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getDateTime()->format('c') === $new_value, 'Date value was changed and set by an ISO8601 date.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $this->assertTrue($typed_data->getDateTime()->format('Y-m-d') == '2014-01-02', 'Date value was changed and set by date string.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime(), 'Date wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DateTimeInterface.
     $typed_data = $this->createTypedData(array('type' => 'datetime_iso8601'), '2014-01-01T20:00:00+00:00');
     $this->assertTrue($typed_data->getDateTime() instanceof DrupalDateTime);
     $typed_data->setDateTime(new DrupalDateTime('2014-01-02T20:00:00+00:00'));
     $this->assertEqual($typed_data->getValue(), '2014-01-02T20:00:00+00:00');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime());
     // Timestamp type.
     $value = REQUEST_TIME;
     $typed_data = $this->createTypedData(array('type' => 'timestamp'), $value);
     $this->assertTrue($typed_data instanceof DateTimeInterface, 'Typed data object is an instance of DateTimeInterface.');
     $this->assertTrue($typed_data->getValue() == $value, 'Timestamp value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $new_value = REQUEST_TIME + 1;
     $typed_data->setValue($new_value);
     $this->assertTrue($typed_data->getValue() === $new_value, 'Timestamp value was changed and set.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime(), 'Timestamp wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DateTimeInterface.
     $typed_data = $this->createTypedData(array('type' => 'timestamp'), REQUEST_TIME);
     $this->assertTrue($typed_data->getDateTime() instanceof DrupalDateTime);
     $typed_data->setDateTime(DrupalDateTime::createFromTimestamp(REQUEST_TIME + 1));
     $this->assertEqual($typed_data->getValue(), REQUEST_TIME + 1);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDateTime());
     // DurationIso8601 type.
     $value = 'PT20S';
     $typed_data = $this->createTypedData(array('type' => 'duration_iso8601'), $value);
     $this->assertTrue($typed_data instanceof DurationInterface, 'Typed data object is an instance of DurationInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'DurationIso8601 value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('P40D');
     $this->assertEqual($typed_data->getDuration()->d, 40, 'DurationIso8601 value was changed and set by duration string.');
     $this->assertTrue(is_string($typed_data->getString()), 'DurationIso8601 value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'DurationIso8601 wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DurationInterface.
     $typed_data = $this->createTypedData(array('type' => 'duration_iso8601'), 'PT20S');
     $this->assertTrue($typed_data->getDuration() instanceof \DateInterval);
     $typed_data->setDuration(new \DateInterval('P40D'));
     // @todo: Should we make this "nicer"?
     $this->assertEqual($typed_data->getValue(), 'P0Y0M40DT0H0M0S');
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDuration());
     // Time span type.
     $value = 20;
     $typed_data = $this->createTypedData(array('type' => 'timespan'), $value);
     $this->assertTrue($typed_data instanceof DurationInterface, 'Typed data object is an instance of DurationInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'Time span value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(60 * 60 * 4);
     $this->assertEqual($typed_data->getDuration()->s, 14400, 'Time span was changed');
     $this->assertTrue(is_string($typed_data->getString()), 'Time span value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Time span wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Check implementation of DurationInterface.
     $typed_data = $this->createTypedData(array('type' => 'timespan'), 20);
     $this->assertTrue($typed_data->getDuration() instanceof \DateInterval);
     $typed_data->setDuration(new \DateInterval('PT4H'));
     $this->assertEqual($typed_data->getValue(), 60 * 60 * 4);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getDuration());
     // URI type.
     $uri = 'http://example.com/foo/';
     $typed_data = $this->createTypedData(array('type' => 'uri'), $uri);
     $this->assertTrue($typed_data instanceof UriInterface, 'Typed data object is an instance of UriInterface.');
     $this->assertTrue($typed_data->getValue() === $uri, 'URI value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue($uri . 'bar.txt');
     $this->assertTrue($typed_data->getValue() === $uri . 'bar.txt', 'URI value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'URI value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'URI wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     $typed_data->setValue('public://field/image/Photo on 4-28-14 at 12.01 PM.jpg');
     $this->assertEqual($typed_data->validate()->count(), 0, 'Filename with spaces is valid.');
     // Generate some files that will be used to test the binary data type.
     $files = array();
     for ($i = 0; $i < 3; $i++) {
         $path = "public://example_{$i}.png";
         file_unmanaged_copy(\Drupal::root() . '/core/misc/druplicon.png', $path);
         $image = File::create(['uri' => $path]);
         $image->save();
         $files[] = $image;
     }
     // Email type.
     $value = $this->randomString();
     $typed_data = $this->createTypedData(array('type' => 'email'), $value);
     $this->assertTrue($typed_data instanceof StringInterface, 'Typed data object is an instance of StringInterface.');
     $this->assertIdentical($typed_data->getValue(), $value, 'Email value was fetched.');
     $new_value = '*****@*****.**';
     $typed_data->setValue($new_value);
     $this->assertIdentical($typed_data->getValue(), $new_value, 'Email value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Email value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Email wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalidATexample.com');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Binary type.
     $typed_data = $this->createTypedData(array('type' => 'binary'), $files[0]->getFileUri());
     $this->assertTrue($typed_data instanceof BinaryInterface, 'Typed data object is an instance of BinaryInterface.');
     $this->assertTrue(is_resource($typed_data->getValue()), 'Binary value was fetched.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Try setting by URI.
     $typed_data->setValue($files[1]->getFileUri());
     $this->assertEqual(fgets($typed_data->getValue()), fgets(fopen($files[1]->getFileUri(), 'r')), 'Binary value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Binary value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // Try setting by resource.
     $typed_data->setValue(fopen($files[2]->getFileUri(), 'r'));
     $this->assertEqual(fgets($typed_data->getValue()), fgets(fopen($files[2]->getFileUri(), 'r')), 'Binary value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Binary value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Binary wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue('invalid');
     $this->assertEqual($typed_data->validate()->count(), 1, 'Validation detected invalid value.');
     // Any type.
     $value = array('foo');
     $typed_data = $this->createTypedData(array('type' => 'any'), $value);
     $this->assertIdentical($typed_data->getValue(), $value, 'Any value was fetched.');
     $new_value = '*****@*****.**';
     $typed_data->setValue($new_value);
     $this->assertIdentical($typed_data->getValue(), $new_value, 'Any value was changed.');
     $this->assertTrue(is_string($typed_data->getString()), 'Any value was converted to string');
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue(NULL);
     $this->assertNull($typed_data->getValue(), 'Any wrapper is null-able.');
     $this->assertEqual($typed_data->validate()->count(), 0);
     // We cannot test invalid values as everything is valid for the any type,
     // but make sure an array or object value passes validation also.
     $typed_data->setValue(array('entry'));
     $this->assertEqual($typed_data->validate()->count(), 0);
     $typed_data->setValue((object) array('entry'));
     $this->assertEqual($typed_data->validate()->count(), 0);
 }