Update core 8.3.0
This commit is contained in:
parent
da7a7918f8
commit
cd7a898e66
6144 changed files with 132297 additions and 87747 deletions
|
|
@ -107,10 +107,10 @@ class SafeMarkupKernelTest extends KernelTestBase {
|
|||
|
||||
/**
|
||||
* @dataProvider providerTestSafeMarkupUriWithException
|
||||
* @expectedException \InvalidArgumentException
|
||||
*/
|
||||
public function testSafeMarkupUriWithExceptionUri($string, $uri) {
|
||||
// Should throw an \InvalidArgumentException, due to Uri::toString().
|
||||
$this->setExpectedException(\InvalidArgumentException::class);
|
||||
$args = self::getSafeMarkupUriArgs($uri);
|
||||
|
||||
SafeMarkup::format($string, $args);
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use Drupal\Core\Config\FileStorage;
|
|||
use Drupal\Core\Config\InstallStorage;
|
||||
use Drupal\Core\Config\StorageInterface;
|
||||
use Drupal\KernelTests\AssertConfigTrait;
|
||||
use Drupal\KernelTests\FileSystemModuleDiscoveryDataProviderTrait;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
|
|
@ -16,6 +17,7 @@ use Drupal\KernelTests\KernelTestBase;
|
|||
class DefaultConfigTest extends KernelTestBase {
|
||||
|
||||
use AssertConfigTrait;
|
||||
use FileSystemModuleDiscoveryDataProviderTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
|
|
@ -30,7 +32,7 @@ class DefaultConfigTest extends KernelTestBase {
|
|||
/**
|
||||
* The following config entries are changed on module install.
|
||||
*
|
||||
* Compare them does not make sense.
|
||||
* Comparing them does not make sense.
|
||||
*
|
||||
* @todo Figure out why simpletest.settings is not installed.
|
||||
*
|
||||
|
|
@ -61,7 +63,7 @@ class DefaultConfigTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests if installed config is equal to the exported config.
|
||||
*
|
||||
* @dataProvider providerTestModuleConfig
|
||||
* @dataProvider coreModuleListDataProvider
|
||||
*/
|
||||
public function testModuleConfig($module) {
|
||||
// System and user are required in order to be able to install some of the
|
||||
|
|
@ -86,7 +88,7 @@ class DefaultConfigTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Work out any additional modules and themes that need installing to create
|
||||
// and optional config.
|
||||
// an optional config.
|
||||
$optional_config_storage = new FileStorage($module_path . InstallStorage::CONFIG_OPTIONAL_DIRECTORY, StorageInterface::DEFAULT_COLLECTION);
|
||||
$modules_to_install = [$module];
|
||||
$themes_to_install = [];
|
||||
|
|
@ -142,24 +144,4 @@ class DefaultConfigTest extends KernelTestBase {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test data provider for ::testModuleConfig().
|
||||
*
|
||||
* @return array
|
||||
* An array of module names to test.
|
||||
*/
|
||||
public function providerTestModuleConfig() {
|
||||
$module_dirs = array_keys(iterator_to_array(new \FilesystemIterator(__DIR__ . '/../../../../modules/')));
|
||||
$module_names = array_map(function($path) {
|
||||
return str_replace(__DIR__ . '/../../../../modules/', '', $path);
|
||||
}, $module_dirs);
|
||||
$modules_keyed = array_combine($module_names, $module_names);
|
||||
|
||||
$data = array_map(function ($module) {
|
||||
return [$module];
|
||||
}, $modules_keyed);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('language', 'simpletest', 'common_test', 'system');
|
||||
public static $modules = ['language', 'simpletest', 'common_test', 'system'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
|
|
@ -55,18 +55,18 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that default CSS and JavaScript is empty.
|
||||
*/
|
||||
function testDefault() {
|
||||
public function testDefault() {
|
||||
$assets = new AttachedAssets();
|
||||
$this->assertEqual(array(), $this->assetResolver->getCssAssets($assets, FALSE), 'Default CSS is empty.');
|
||||
$this->assertEqual([], $this->assetResolver->getCssAssets($assets, FALSE), 'Default CSS is empty.');
|
||||
list($js_assets_header, $js_assets_footer) = $this->assetResolver->getJsAssets($assets, FALSE);
|
||||
$this->assertEqual(array(), $js_assets_header, 'Default header JavaScript is empty.');
|
||||
$this->assertEqual(array(), $js_assets_footer, 'Default footer JavaScript is empty.');
|
||||
$this->assertEqual([], $js_assets_header, 'Default header JavaScript is empty.');
|
||||
$this->assertEqual([], $js_assets_footer, 'Default footer JavaScript is empty.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests non-existing libraries.
|
||||
*/
|
||||
function testLibraryUnknown() {
|
||||
public function testLibraryUnknown() {
|
||||
$build['#attached']['library'][] = 'core/unknown';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -76,7 +76,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests adding a CSS and a JavaScript file.
|
||||
*/
|
||||
function testAddFiles() {
|
||||
public function testAddFiles() {
|
||||
$build['#attached']['library'][] = 'common_test/files';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -97,7 +97,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests adding JavaScript settings.
|
||||
*/
|
||||
function testAddJsSettings() {
|
||||
public function testAddJsSettings() {
|
||||
// Add a file in order to test default settings.
|
||||
$build['#attached']['library'][] = 'core/drupalSettings';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
|
@ -116,7 +116,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests adding external CSS and JavaScript files.
|
||||
*/
|
||||
function testAddExternalFiles() {
|
||||
public function testAddExternalFiles() {
|
||||
$build['#attached']['library'][] = 'common_test/external';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -136,7 +136,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests adding JavaScript files with additional attributes.
|
||||
*/
|
||||
function testAttributes() {
|
||||
public function testAttributes() {
|
||||
$build['#attached']['library'][] = 'common_test/js-attributes';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -152,7 +152,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that attributes are maintained when JS aggregation is enabled.
|
||||
*/
|
||||
function testAggregatedAttributes() {
|
||||
public function testAggregatedAttributes() {
|
||||
$build['#attached']['library'][] = 'common_test/js-attributes';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -168,7 +168,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Integration test for CSS/JS aggregation.
|
||||
*/
|
||||
function testAggregation() {
|
||||
public function testAggregation() {
|
||||
$build['#attached']['library'][] = 'core/drupal.timezone';
|
||||
$build['#attached']['library'][] = 'core/drupal.vertical-tabs';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
|
@ -186,8 +186,8 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests JavaScript settings.
|
||||
*/
|
||||
function testSettings() {
|
||||
$build = array();
|
||||
public function testSettings() {
|
||||
$build = [];
|
||||
$build['#attached']['library'][] = 'core/drupalSettings';
|
||||
// Nonsensical value to verify if it's possible to override path settings.
|
||||
$build['#attached']['drupalSettings']['path']['pathPrefix'] = 'yarhar';
|
||||
|
|
@ -226,7 +226,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests JS assets depending on the 'core/<head>' virtual library.
|
||||
*/
|
||||
function testHeaderHTML() {
|
||||
public function testHeaderHTML() {
|
||||
$build['#attached']['library'][] = 'common_test/js-header';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -242,7 +242,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that for assets with cache = FALSE, Drupal sets preprocess = FALSE.
|
||||
*/
|
||||
function testNoCache() {
|
||||
public function testNoCache() {
|
||||
$build['#attached']['library'][] = 'common_test/no-cache';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -255,7 +255,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
*
|
||||
* @see \Drupal\Core\Render\Element\HtmlTag::preRenderConditionalComments()
|
||||
*/
|
||||
function testBrowserConditionalComments() {
|
||||
public function testBrowserConditionalComments() {
|
||||
$default_query_string = $this->container->get('state')->get('system.css_js_query_string') ?: '0';
|
||||
|
||||
$build['#attached']['library'][] = 'common_test/browsers';
|
||||
|
|
@ -274,7 +274,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests JavaScript versioning.
|
||||
*/
|
||||
function testVersionQueryString() {
|
||||
public function testVersionQueryString() {
|
||||
$build['#attached']['library'][] = 'core/backbone';
|
||||
$build['#attached']['library'][] = 'core/domready';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
|
@ -289,7 +289,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests JavaScript and CSS asset ordering.
|
||||
*/
|
||||
function testRenderOrder() {
|
||||
public function testRenderOrder() {
|
||||
$build['#attached']['library'][] = 'common_test/order';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
@ -311,12 +311,12 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
$js = $this->assetResolver->getJsAssets($assets, FALSE)[1];
|
||||
$js_render_array = \Drupal::service('asset.js.collection_renderer')->render($js);
|
||||
$rendered_js = $this->renderer->renderPlain($js_render_array);
|
||||
$matches = array();
|
||||
$matches = [];
|
||||
if (preg_match_all('/weight_([-0-9]+_[0-9]+)/', $rendered_js, $matches)) {
|
||||
$result = $matches[1];
|
||||
}
|
||||
else {
|
||||
$result = array();
|
||||
$result = [];
|
||||
}
|
||||
$this->assertIdentical($result, $expected_order_js, 'JavaScript is added in the expected weight order.');
|
||||
|
||||
|
|
@ -353,12 +353,12 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
$css = $this->assetResolver->getCssAssets($assets, FALSE);
|
||||
$css_render_array = \Drupal::service('asset.css.collection_renderer')->render($css);
|
||||
$rendered_css = $this->renderer->renderPlain($css_render_array);
|
||||
$matches = array();
|
||||
$matches = [];
|
||||
if (preg_match_all('/([a-z]+)_weight_([-0-9]+_[0-9]+)/', $rendered_css, $matches)) {
|
||||
$result = $matches[0];
|
||||
}
|
||||
else {
|
||||
$result = array();
|
||||
$result = [];
|
||||
}
|
||||
$this->assertIdentical($result, $expected_order_css, 'CSS is added in the expected weight order.');
|
||||
}
|
||||
|
|
@ -366,7 +366,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests rendering the JavaScript with a file's weight above jQuery's.
|
||||
*/
|
||||
function testRenderDifferentWeight() {
|
||||
public function testRenderDifferentWeight() {
|
||||
// If a library contains assets A and B, and A is listed first, then B can
|
||||
// still make itself appear first by defining a lower weight.
|
||||
$build['#attached']['library'][] = 'core/jquery';
|
||||
|
|
@ -386,7 +386,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
*
|
||||
* @see simpletest_js_alter()
|
||||
*/
|
||||
function testAlter() {
|
||||
public function testAlter() {
|
||||
// Add both tableselect.js and simpletest.js.
|
||||
$build['#attached']['library'][] = 'core/drupal.tableselect';
|
||||
$build['#attached']['library'][] = 'simpletest/drupal.simpletest';
|
||||
|
|
@ -406,7 +406,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
*
|
||||
* @see common_test_library_info_alter()
|
||||
*/
|
||||
function testLibraryAlter() {
|
||||
public function testLibraryAlter() {
|
||||
// Verify that common_test altered the title of Farbtastic.
|
||||
/** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
|
||||
$library_discovery = \Drupal::service('library.discovery');
|
||||
|
|
@ -425,7 +425,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Dynamically defines an asset library and alters it.
|
||||
*/
|
||||
function testDynamicLibrary() {
|
||||
public function testDynamicLibrary() {
|
||||
/** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
|
||||
$library_discovery = \Drupal::service('library.discovery');
|
||||
// Retrieve a dynamic library definition.
|
||||
|
|
@ -449,7 +449,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
*
|
||||
* @see common_test.library.yml
|
||||
*/
|
||||
function testLibraryNameConflicts() {
|
||||
public function testLibraryNameConflicts() {
|
||||
/** @var \Drupal\Core\Asset\LibraryDiscoveryInterface $library_discovery */
|
||||
$library_discovery = \Drupal::service('library.discovery');
|
||||
$farbtastic = $library_discovery->getLibraryByName('common_test', 'jquery.farbtastic');
|
||||
|
|
@ -459,7 +459,7 @@ class AttachedAssetsTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests JavaScript files that have querystrings attached get added right.
|
||||
*/
|
||||
function testAddJsFileWithQueryString() {
|
||||
public function testAddJsFileWithQueryString() {
|
||||
$build['#attached']['library'][] = 'common_test/querystring';
|
||||
$assets = AttachedAssets::createFromRenderArray($build);
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
namespace Drupal\KernelTests\Core\Bootstrap;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
|
|
@ -16,15 +17,19 @@ class GetFilenameTest extends KernelTestBase {
|
|||
*/
|
||||
public static $modules = ['system'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function register(ContainerBuilder $container) {
|
||||
parent::register($container);
|
||||
// Use the testing install profile.
|
||||
$container->setParameter('install_profile', 'testing');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that drupal_get_filename() works when the file is not in database.
|
||||
*/
|
||||
function testDrupalGetFilename() {
|
||||
// drupal_get_profile() is using obtaining the profile from state if the
|
||||
// install_state global is not set.
|
||||
global $install_state;
|
||||
$install_state['parameters']['profile'] = 'testing';
|
||||
|
||||
public function testDrupalGetFilename() {
|
||||
// Rebuild system.module.files state data.
|
||||
// @todo Remove as part of https://www.drupal.org/node/2186491
|
||||
drupal_static_reset('system_rebuild_module_data');
|
||||
|
|
@ -34,7 +39,7 @@ class GetFilenameTest extends KernelTestBase {
|
|||
$this->assertIdentical(drupal_get_filename('module', 'system'), 'core/modules/system/system.info.yml');
|
||||
|
||||
// Retrieving the location of a theme.
|
||||
\Drupal::service('theme_handler')->install(array('stark'));
|
||||
\Drupal::service('theme_handler')->install(['stark']);
|
||||
$this->assertIdentical(drupal_get_filename('theme', 'stark'), 'core/themes/stark/stark.info.yml');
|
||||
|
||||
// Retrieving the location of a theme engine.
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class ResettableStaticTest extends KernelTestBase {
|
|||
* Tests that a variable reference returned by drupal_static() gets reset when
|
||||
* drupal_static_reset() is called.
|
||||
*/
|
||||
function testDrupalStatic() {
|
||||
public function testDrupalStatic() {
|
||||
$name = __CLASS__ . '_' . __METHOD__;
|
||||
$var = &drupal_static($name, 'foo');
|
||||
$this->assertEqual($var, 'foo', 'Variable returned by drupal_static() was set to its default.');
|
||||
|
|
|
|||
|
|
@ -17,9 +17,9 @@ class BackendChainTest extends GenericCacheBackendUnitTestBase {
|
|||
|
||||
// We need to create some various backends in the chain.
|
||||
$chain
|
||||
->appendBackend(new MemoryBackend('foo'))
|
||||
->prependBackend(new MemoryBackend('bar'))
|
||||
->appendBackend(new MemoryBackend('baz'));
|
||||
->appendBackend(new MemoryBackend())
|
||||
->prependBackend(new MemoryBackend())
|
||||
->appendBackend(new MemoryBackend());
|
||||
|
||||
\Drupal::service('cache_tags.invalidator')->addInvalidator($chain);
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ class DatabaseBackendTagTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system');
|
||||
public static $modules = ['system'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
|
|
@ -30,21 +30,21 @@ class DatabaseBackendTagTest extends KernelTestBase {
|
|||
$container
|
||||
->register('cache_factory', 'Drupal\Core\Cache\CacheFactory')
|
||||
->addArgument(new Reference('settings'))
|
||||
->addMethodCall('setContainer', array(new Reference('service_container')));
|
||||
->addMethodCall('setContainer', [new Reference('service_container')]);
|
||||
}
|
||||
|
||||
public function testTagInvalidations() {
|
||||
// Create cache entry in multiple bins.
|
||||
$tags = array('test_tag:1', 'test_tag:2', 'test_tag:3');
|
||||
$bins = array('data', 'bootstrap', 'render');
|
||||
$tags = ['test_tag:1', 'test_tag:2', 'test_tag:3'];
|
||||
$bins = ['data', 'bootstrap', 'render'];
|
||||
foreach ($bins as $bin) {
|
||||
$bin = \Drupal::cache($bin);
|
||||
$bin->set('test', 'value', Cache::PERMANENT, $tags);
|
||||
$this->assertTrue($bin->get('test'), 'Cache item was set in bin.');
|
||||
}
|
||||
|
||||
$invalidations_before = intval(db_select('cachetags')->fields('cachetags', array('invalidations'))->condition('tag', 'test_tag:2')->execute()->fetchField());
|
||||
Cache::invalidateTags(array('test_tag:2'));
|
||||
$invalidations_before = intval(db_select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
|
||||
Cache::invalidateTags(['test_tag:2']);
|
||||
|
||||
// Test that cache entry has been invalidated in multiple bins.
|
||||
foreach ($bins as $bin) {
|
||||
|
|
@ -53,7 +53,7 @@ class DatabaseBackendTagTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Test that only one tag invalidation has occurred.
|
||||
$invalidations_after = intval(db_select('cachetags')->fields('cachetags', array('invalidations'))->condition('tag', 'test_tag:2')->execute()->fetchField());
|
||||
$invalidations_after = intval(db_select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
|
||||
$this->assertEqual($invalidations_after, $invalidations_before + 1, 'Only one addition cache tag invalidation has occurred after invalidating a tag used in multiple bins.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class DatabaseBackendTest extends GenericCacheBackendUnitTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system');
|
||||
public static $modules = ['system'];
|
||||
|
||||
/**
|
||||
* Creates a new instance of DatabaseBackend.
|
||||
|
|
|
|||
|
|
@ -102,7 +102,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
}
|
||||
|
||||
protected function setUp() {
|
||||
$this->cachebackends = array();
|
||||
$this->cachebackends = [];
|
||||
$this->defaultValue = $this->randomMachineName(10);
|
||||
|
||||
parent::setUp();
|
||||
|
|
@ -131,7 +131,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$backend = $this->getCacheBackend();
|
||||
|
||||
$this->assertIdentical(FALSE, $backend->get('test1'), "Backend does not contain data for cache id test1.");
|
||||
$with_backslash = array('foo' => '\Drupal\foo\Bar');
|
||||
$with_backslash = ['foo' => '\Drupal\foo\Bar'];
|
||||
$backend->set('test1', $with_backslash);
|
||||
$cached = $backend->get('test1');
|
||||
$this->assert(is_object($cached), "Backend returned an object for cache id test1.");
|
||||
|
|
@ -142,10 +142,10 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.');
|
||||
|
||||
$this->assertIdentical(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2.");
|
||||
$backend->set('test2', array('value' => 3), REQUEST_TIME + 3);
|
||||
$backend->set('test2', ['value' => 3], REQUEST_TIME + 3);
|
||||
$cached = $backend->get('test2');
|
||||
$this->assert(is_object($cached), "Backend returned an object for cache id test2.");
|
||||
$this->assertIdentical(array('value' => 3), $cached->data);
|
||||
$this->assertIdentical(['value' => 3], $cached->data);
|
||||
$this->assertTrue($cached->valid, 'Item is marked as valid.');
|
||||
$this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.');
|
||||
$this->assertEqual($cached->expire, REQUEST_TIME + 3, 'Expire time is correct.');
|
||||
|
|
@ -159,7 +159,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertEqual($cached->expire, REQUEST_TIME - 3, 'Expire time is correct.');
|
||||
|
||||
$this->assertIdentical(FALSE, $backend->get('test4'), "Backend does not contain data for cache id test4.");
|
||||
$with_eof = array('foo' => "\nEOF\ndata");
|
||||
$with_eof = ['foo' => "\nEOF\ndata"];
|
||||
$backend->set('test4', $with_eof);
|
||||
$cached = $backend->get('test4');
|
||||
$this->assert(is_object($cached), "Backend returned an object for cache id test4.");
|
||||
|
|
@ -169,7 +169,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.');
|
||||
|
||||
$this->assertIdentical(FALSE, $backend->get('test5'), "Backend does not contain data for cache id test5.");
|
||||
$with_eof_and_semicolon = array('foo' => "\nEOF;\ndata");
|
||||
$with_eof_and_semicolon = ['foo' => "\nEOF;\ndata"];
|
||||
$backend->set('test5', $with_eof_and_semicolon);
|
||||
$cached = $backend->get('test5');
|
||||
$this->assert(is_object($cached), "Backend returned an object for cache id test5.");
|
||||
|
|
@ -178,7 +178,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertTrue($cached->created >= REQUEST_TIME && $cached->created <= round(microtime(TRUE), 3), 'Created time is correct.');
|
||||
$this->assertEqual($cached->expire, Cache::PERMANENT, 'Expire time is correct.');
|
||||
|
||||
$with_variable = array('foo' => '$bar');
|
||||
$with_variable = ['foo' => '$bar'];
|
||||
$backend->set('test6', $with_variable);
|
||||
$cached = $backend->get('test6');
|
||||
$this->assert(is_object($cached), "Backend returned an object for cache id test6.");
|
||||
|
|
@ -257,14 +257,14 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
public function testValueTypeIsKept() {
|
||||
$backend = $this->getCacheBackend();
|
||||
|
||||
$variables = array(
|
||||
$variables = [
|
||||
'test1' => 1,
|
||||
'test2' => '0',
|
||||
'test3' => '',
|
||||
'test4' => 12.64,
|
||||
'test5' => FALSE,
|
||||
'test6' => array(1, 2, 3),
|
||||
);
|
||||
'test6' => [1, 2, 3],
|
||||
];
|
||||
|
||||
// Create cache entries.
|
||||
foreach ($variables as $cid => $data) {
|
||||
|
|
@ -297,14 +297,14 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$backend->set($long_cid, 300);
|
||||
|
||||
// Mismatch order for harder testing.
|
||||
$reference = array(
|
||||
$reference = [
|
||||
'test3',
|
||||
'test7',
|
||||
'test21', // Cid does not exist.
|
||||
'test6',
|
||||
'test19', // Cid does not exist until added before second getMultiple().
|
||||
'test2',
|
||||
);
|
||||
];
|
||||
|
||||
$cids = $reference;
|
||||
$ret = $backend->getMultiple($cids);
|
||||
|
|
@ -364,7 +364,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertFalse(in_array('test19', $cids), "Added cache id test19 is not in cids array.");
|
||||
|
||||
// Test with a long $cid and non-numeric array key.
|
||||
$cids = array('key:key' => $long_cid);
|
||||
$cids = ['key:key' => $long_cid];
|
||||
$return = $backend->getMultiple($cids);
|
||||
$this->assertEqual(300, $return[$long_cid]->data);
|
||||
$this->assertTrue(empty($cids));
|
||||
|
|
@ -380,13 +380,13 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
|
||||
// Set multiple testing keys.
|
||||
$backend->set('cid_1', 'Some other value');
|
||||
$items = array(
|
||||
'cid_1' => array('data' => 1),
|
||||
'cid_2' => array('data' => 2),
|
||||
'cid_3' => array('data' => array(1, 2)),
|
||||
'cid_4' => array('data' => 1, 'expire' => $future_expiration),
|
||||
'cid_5' => array('data' => 1, 'tags' => array('test:a', 'test:b')),
|
||||
);
|
||||
$items = [
|
||||
'cid_1' => ['data' => 1],
|
||||
'cid_2' => ['data' => 2],
|
||||
'cid_3' => ['data' => [1, 2]],
|
||||
'cid_4' => ['data' => 1, 'expire' => $future_expiration],
|
||||
'cid_5' => ['data' => 1, 'tags' => ['test:a', 'test:b']],
|
||||
];
|
||||
$backend->setMultiple($items);
|
||||
$cids = array_keys($items);
|
||||
$cached = $backend->getMultiple($cids);
|
||||
|
|
@ -411,9 +411,9 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
// assertion.
|
||||
try {
|
||||
$items = [
|
||||
'exception_test_1' => array('data' => 1, 'tags' => []),
|
||||
'exception_test_2' => array('data' => 2, 'tags' => ['valid']),
|
||||
'exception_test_3' => array('data' => 3, 'tags' => ['node' => [3, 5, 7]]),
|
||||
'exception_test_1' => ['data' => 1, 'tags' => []],
|
||||
'exception_test_2' => ['data' => 2, 'tags' => ['valid']],
|
||||
'exception_test_3' => ['data' => 3, 'tags' => ['node' => [3, 5, 7]]],
|
||||
];
|
||||
$backend->setMultiple($items);
|
||||
$this->fail('::setMultiple() was called with invalid cache tags, runtime assertion did not fail.');
|
||||
|
|
@ -441,13 +441,13 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
|
||||
$backend->delete('test1');
|
||||
$backend->delete('test23'); // Nonexistent key should not cause an error.
|
||||
$backend->deleteMultiple(array(
|
||||
$backend->deleteMultiple([
|
||||
'test3',
|
||||
'test5',
|
||||
'test7',
|
||||
'test19', // Nonexistent key should not cause an error.
|
||||
'test21', // Nonexistent key should not cause an error.
|
||||
));
|
||||
]);
|
||||
|
||||
// Test if expected keys have been deleted.
|
||||
$this->assertIdentical(FALSE, $backend->get('test1'), "Cache id test1 deleted.");
|
||||
|
|
@ -465,7 +465,7 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
$this->assertIdentical(FALSE, $backend->get('test21'), "Cache id test21 does not exist.");
|
||||
|
||||
// Calling deleteMultiple() with an empty array should not cause an error.
|
||||
$this->assertFalse($backend->deleteMultiple(array()));
|
||||
$this->assertFalse($backend->deleteMultiple([]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -491,21 +491,21 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
* Test Drupal\Core\Cache\CacheBackendInterface::invalidate() and
|
||||
* Drupal\Core\Cache\CacheBackendInterface::invalidateMultiple().
|
||||
*/
|
||||
function testInvalidate() {
|
||||
public function testInvalidate() {
|
||||
$backend = $this->getCacheBackend();
|
||||
$backend->set('test1', 1);
|
||||
$backend->set('test2', 2);
|
||||
$backend->set('test3', 2);
|
||||
$backend->set('test4', 2);
|
||||
|
||||
$reference = array('test1', 'test2', 'test3', 'test4');
|
||||
$reference = ['test1', 'test2', 'test3', 'test4'];
|
||||
|
||||
$cids = $reference;
|
||||
$ret = $backend->getMultiple($cids);
|
||||
$this->assertEqual(count($ret), 4, 'Four items returned.');
|
||||
|
||||
$backend->invalidate('test1');
|
||||
$backend->invalidateMultiple(array('test2', 'test3'));
|
||||
$backend->invalidateMultiple(['test2', 'test3']);
|
||||
|
||||
$cids = $reference;
|
||||
$ret = $backend->getMultiple($cids);
|
||||
|
|
@ -517,55 +517,55 @@ abstract class GenericCacheBackendUnitTestBase extends KernelTestBase {
|
|||
|
||||
// Calling invalidateMultiple() with an empty array should not cause an
|
||||
// error.
|
||||
$this->assertFalse($backend->invalidateMultiple(array()));
|
||||
$this->assertFalse($backend->invalidateMultiple([]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests Drupal\Core\Cache\CacheBackendInterface::invalidateTags().
|
||||
*/
|
||||
function testInvalidateTags() {
|
||||
public function testInvalidateTags() {
|
||||
$backend = $this->getCacheBackend();
|
||||
|
||||
// Create two cache entries with the same tag and tag value.
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, array('test_tag:2'));
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, array('test_tag:2'));
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, ['test_tag:2']);
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, ['test_tag:2']);
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1') && $backend->get('test_cid_invalidate2'), 'Two cache items were created.');
|
||||
|
||||
// Invalidate test_tag of value 1. This should invalidate both entries.
|
||||
Cache::invalidateTags(array('test_tag:2'));
|
||||
Cache::invalidateTags(['test_tag:2']);
|
||||
$this->assertFalse($backend->get('test_cid_invalidate1') || $backend->get('test_cid_invalidate2'), 'Two cache items invalidated after invalidating a cache tag.');
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1', TRUE) && $backend->get('test_cid_invalidate2', TRUE), 'Cache items not deleted after invalidating a cache tag.');
|
||||
|
||||
// Create two cache entries with the same tag and an array tag value.
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, array('test_tag:1'));
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, array('test_tag:1'));
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, ['test_tag:1']);
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, ['test_tag:1']);
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1') && $backend->get('test_cid_invalidate2'), 'Two cache items were created.');
|
||||
|
||||
// Invalidate test_tag of value 1. This should invalidate both entries.
|
||||
Cache::invalidateTags(array('test_tag:1'));
|
||||
Cache::invalidateTags(['test_tag:1']);
|
||||
$this->assertFalse($backend->get('test_cid_invalidate1') || $backend->get('test_cid_invalidate2'), 'Two caches removed after invalidating a cache tag.');
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1', TRUE) && $backend->get('test_cid_invalidate2', TRUE), 'Cache items not deleted after invalidating a cache tag.');
|
||||
|
||||
// Create three cache entries with a mix of tags and tag values.
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, array('test_tag:1'));
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, array('test_tag:2'));
|
||||
$backend->set('test_cid_invalidate3', $this->defaultValue, Cache::PERMANENT, array('test_tag_foo:3'));
|
||||
$backend->set('test_cid_invalidate1', $this->defaultValue, Cache::PERMANENT, ['test_tag:1']);
|
||||
$backend->set('test_cid_invalidate2', $this->defaultValue, Cache::PERMANENT, ['test_tag:2']);
|
||||
$backend->set('test_cid_invalidate3', $this->defaultValue, Cache::PERMANENT, ['test_tag_foo:3']);
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1') && $backend->get('test_cid_invalidate2') && $backend->get('test_cid_invalidate3'), 'Three cached items were created.');
|
||||
Cache::invalidateTags(array('test_tag_foo:3'));
|
||||
Cache::invalidateTags(['test_tag_foo:3']);
|
||||
$this->assertTrue($backend->get('test_cid_invalidate1') && $backend->get('test_cid_invalidate2'), 'Cache items not matching the tag were not invalidated.');
|
||||
$this->assertFalse($backend->get('test_cid_invalidated3'), 'Cached item matching the tag was removed.');
|
||||
|
||||
// Create cache entry in multiple bins. Two cache entries
|
||||
// (test_cid_invalidate1 and test_cid_invalidate2) still exist from previous
|
||||
// tests.
|
||||
$tags = array('test_tag:1', 'test_tag:2', 'test_tag:3');
|
||||
$bins = array('path', 'bootstrap', 'page');
|
||||
$tags = ['test_tag:1', 'test_tag:2', 'test_tag:3'];
|
||||
$bins = ['path', 'bootstrap', 'page'];
|
||||
foreach ($bins as $bin) {
|
||||
$this->getCacheBackend($bin)->set('test', $this->defaultValue, Cache::PERMANENT, $tags);
|
||||
$this->assertTrue($this->getCacheBackend($bin)->get('test'), 'Cache item was set in bin.');
|
||||
}
|
||||
|
||||
Cache::invalidateTags(array('test_tag:2'));
|
||||
Cache::invalidateTags(['test_tag:2']);
|
||||
|
||||
// Test that the cache entry has been invalidated in multiple bins.
|
||||
foreach ($bins as $bin) {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class MemoryBackendTest extends GenericCacheBackendUnitTestBase {
|
|||
* A new MemoryBackend object.
|
||||
*/
|
||||
protected function createCacheBackend($bin) {
|
||||
$backend = new MemoryBackend($bin);
|
||||
$backend = new MemoryBackend();
|
||||
\Drupal::service('cache_tags.invalidator')->addInvalidator($backend);
|
||||
return $backend;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class SizeTest extends KernelTestBase {
|
|||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$kb = Bytes::KILOBYTE;
|
||||
$this->exactTestCases = array(
|
||||
$this->exactTestCases = [
|
||||
'1 byte' => 1,
|
||||
'1 KB' => $kb,
|
||||
'1 MB' => $kb * $kb,
|
||||
|
|
@ -28,21 +28,21 @@ class SizeTest extends KernelTestBase {
|
|||
'1 EB' => $kb * $kb * $kb * $kb * $kb * $kb,
|
||||
'1 ZB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb,
|
||||
'1 YB' => $kb * $kb * $kb * $kb * $kb * $kb * $kb * $kb,
|
||||
);
|
||||
$this->roundedTestCases = array(
|
||||
];
|
||||
$this->roundedTestCases = [
|
||||
'2 bytes' => 2,
|
||||
'1 MB' => ($kb * $kb) - 1, // rounded to 1 MB (not 1000 or 1024 kilobyte!)
|
||||
round(3623651 / ($this->exactTestCases['1 MB']), 2) . ' MB' => 3623651, // megabytes
|
||||
round(67234178751368124 / ($this->exactTestCases['1 PB']), 2) . ' PB' => 67234178751368124, // petabytes
|
||||
round(235346823821125814962843827 / ($this->exactTestCases['1 YB']), 2) . ' YB' => 235346823821125814962843827, // yottabytes
|
||||
);
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that format_size() returns the expected string.
|
||||
*/
|
||||
function testCommonFormatSize() {
|
||||
foreach (array($this->exactTestCases, $this->roundedTestCases) as $test_cases) {
|
||||
public function testCommonFormatSize() {
|
||||
foreach ([$this->exactTestCases, $this->roundedTestCases] as $test_cases) {
|
||||
foreach ($test_cases as $expected => $input) {
|
||||
$this->assertEqual(
|
||||
($result = format_size($input, NULL)),
|
||||
|
|
@ -56,7 +56,7 @@ class SizeTest extends KernelTestBase {
|
|||
/**
|
||||
* Cross-tests Bytes::toInt() and format_size().
|
||||
*/
|
||||
function testCommonParseSizeFormatSize() {
|
||||
public function testCommonParseSizeFormatSize() {
|
||||
foreach ($this->exactTestCases as $size) {
|
||||
$this->assertEqual(
|
||||
$size,
|
||||
|
|
|
|||
|
|
@ -18,29 +18,29 @@ class XssUnitTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('filter', 'system');
|
||||
public static $modules = ['filter', 'system'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(array('system'));
|
||||
$this->installConfig(['system']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests t() functionality.
|
||||
*/
|
||||
function testT() {
|
||||
public function testT() {
|
||||
$text = t('Simple text');
|
||||
$this->assertEqual($text, 'Simple text', 't leaves simple text alone.');
|
||||
$text = t('Escaped text: @value', array('@value' => '<script>'));
|
||||
$text = t('Escaped text: @value', ['@value' => '<script>']);
|
||||
$this->assertEqual($text, 'Escaped text: <script>', 't replaces and escapes string.');
|
||||
$text = t('Placeholder text: %value', array('%value' => '<script>'));
|
||||
$text = t('Placeholder text: %value', ['%value' => '<script>']);
|
||||
$this->assertEqual($text, 'Placeholder text: <em class="placeholder"><script></em>', 't replaces, escapes and themes string.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that harmful protocols are stripped.
|
||||
*/
|
||||
function testBadProtocolStripping() {
|
||||
public function testBadProtocolStripping() {
|
||||
// Ensure that check_url() strips out harmful protocols, and encodes for
|
||||
// HTML.
|
||||
// Ensure \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() can
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
/**
|
||||
* Exempt from strict schema checking.
|
||||
*
|
||||
* @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
|
||||
* @see \Drupal\Core\Config\Development\ConfigSchemaChecker
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
|
|
@ -32,12 +32,12 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system');
|
||||
public static $modules = ['system'];
|
||||
|
||||
/**
|
||||
* Tests CRUD operations.
|
||||
*/
|
||||
function testCRUD() {
|
||||
public function testCRUD() {
|
||||
$storage = $this->container->get('config.storage');
|
||||
$config_factory = $this->container->get('config.factory');
|
||||
$name = 'config_test.crud';
|
||||
|
|
@ -52,7 +52,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
|
||||
// Verify the active configuration contains the saved value.
|
||||
$actual_data = $storage->read($name);
|
||||
$this->assertIdentical($actual_data, array('value' => 'initial'));
|
||||
$this->assertIdentical($actual_data, ['value' => 'initial']);
|
||||
|
||||
// Update the configuration object instance.
|
||||
$config->set('value', 'instance-update');
|
||||
|
|
@ -61,7 +61,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
|
||||
// Verify the active configuration contains the updated value.
|
||||
$actual_data = $storage->read($name);
|
||||
$this->assertIdentical($actual_data, array('value' => 'instance-update'));
|
||||
$this->assertIdentical($actual_data, ['value' => 'instance-update']);
|
||||
|
||||
// Verify a call to $this->config() immediately returns the updated value.
|
||||
$new_config = $this->config($name);
|
||||
|
|
@ -75,7 +75,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
$config->delete();
|
||||
|
||||
// Verify the configuration object is empty.
|
||||
$this->assertIdentical($config->get(), array());
|
||||
$this->assertIdentical($config->get(), []);
|
||||
$this->assertIdentical($config->isNew(), TRUE);
|
||||
|
||||
// Verify that all copies of the configuration has been removed from the
|
||||
|
|
@ -98,7 +98,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
|
||||
// Verify the active configuration contains the updated value.
|
||||
$actual_data = $storage->read($name);
|
||||
$this->assertIdentical($actual_data, array('value' => 're-created'));
|
||||
$this->assertIdentical($actual_data, ['value' => 're-created']);
|
||||
|
||||
// Verify a call to $this->config() immediately returns the updated value.
|
||||
$new_config = $this->config($name);
|
||||
|
|
@ -115,7 +115,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
// Ensure that the old configuration object is removed from both the cache
|
||||
// and the configuration storage.
|
||||
$config = $this->config($name);
|
||||
$this->assertIdentical($config->get(), array());
|
||||
$this->assertIdentical($config->get(), []);
|
||||
$this->assertIdentical($config->isNew(), TRUE);
|
||||
|
||||
// Test renaming when config.factory does not have the object in its static
|
||||
|
|
@ -138,10 +138,10 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
|
||||
// Merge data into the configuration object.
|
||||
$new_config = $this->config($new_name);
|
||||
$expected_values = array(
|
||||
$expected_values = [
|
||||
'value' => 'herp',
|
||||
'404' => 'derp',
|
||||
);
|
||||
];
|
||||
$new_config->merge($expected_values);
|
||||
$new_config->save();
|
||||
$this->assertIdentical($new_config->get('value'), $expected_values['value']);
|
||||
|
|
@ -157,7 +157,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests the validation of configuration object names.
|
||||
*/
|
||||
function testNameValidation() {
|
||||
public function testNameValidation() {
|
||||
// Verify that an object name without namespace causes an exception.
|
||||
$name = 'nonamespace';
|
||||
$message = 'Expected ConfigNameException was thrown for a name without a namespace.';
|
||||
|
|
@ -181,7 +181,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Verify that disallowed characters in the name cause an exception.
|
||||
$characters = $test_characters = array(':', '?', '*', '<', '>', '"', '\'', '/', '\\');
|
||||
$characters = $test_characters = [':', '?', '*', '<', '>', '"', '\'', '/', '\\'];
|
||||
foreach ($test_characters as $i => $c) {
|
||||
try {
|
||||
$name = 'namespace.object' . $c;
|
||||
|
|
@ -192,9 +192,9 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
unset($test_characters[$i]);
|
||||
}
|
||||
}
|
||||
$this->assertTrue(empty($test_characters), format_string('Expected ConfigNameException was thrown for all invalid name characters: @characters', array(
|
||||
$this->assertTrue(empty($test_characters), format_string('Expected ConfigNameException was thrown for all invalid name characters: @characters', [
|
||||
'@characters' => implode(' ', $characters),
|
||||
)));
|
||||
]));
|
||||
|
||||
// Verify that a valid config object name can be saved.
|
||||
$name = 'namespace.object';
|
||||
|
|
@ -213,11 +213,11 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests the validation of configuration object values.
|
||||
*/
|
||||
function testValueValidation() {
|
||||
public function testValueValidation() {
|
||||
// Verify that setData() will catch dotted keys.
|
||||
$message = 'Expected ConfigValueException was thrown from setData() for value with dotted keys.';
|
||||
try {
|
||||
$this->config('namespace.object')->setData(array('key.value' => 12))->save();
|
||||
$this->config('namespace.object')->setData(['key.value' => 12])->save();
|
||||
$this->fail($message);
|
||||
}
|
||||
catch (ConfigValueException $e) {
|
||||
|
|
@ -227,7 +227,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
// Verify that set() will catch dotted keys.
|
||||
$message = 'Expected ConfigValueException was thrown from set() for value with dotted keys.';
|
||||
try {
|
||||
$this->config('namespace.object')->set('foo', array('key.value' => 12))->save();
|
||||
$this->config('namespace.object')->set('foo', ['key.value' => 12])->save();
|
||||
$this->fail($message);
|
||||
}
|
||||
catch (ConfigValueException $e) {
|
||||
|
|
@ -239,7 +239,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
* Tests data type handling.
|
||||
*/
|
||||
public function testDataTypes() {
|
||||
\Drupal::service('module_installer')->install(array('config_test'));
|
||||
\Drupal::service('module_installer')->install(['config_test']);
|
||||
$storage = new DatabaseStorage($this->container->get('database'), 'config');
|
||||
$name = 'config_test.types';
|
||||
$config = $this->config($name);
|
||||
|
|
@ -247,8 +247,8 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
$this->verbose('<pre>' . $original_content . "\n" . var_export($storage->read($name), TRUE));
|
||||
|
||||
// Verify variable data types are intact.
|
||||
$data = array(
|
||||
'array' => array(),
|
||||
$data = [
|
||||
'array' => [],
|
||||
'boolean' => TRUE,
|
||||
'exp' => 1.2e+34,
|
||||
'float' => 3.14159,
|
||||
|
|
@ -258,7 +258,7 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
'octal' => 0775,
|
||||
'string' => 'string',
|
||||
'string_int' => '1',
|
||||
);
|
||||
];
|
||||
$data['_core']['default_config_hash'] = Crypt::hashBase64(serialize($data));
|
||||
$this->assertIdentical($config->get(), $data);
|
||||
|
||||
|
|
@ -292,9 +292,9 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
$this->fail('No Exception thrown upon saving invalid data type.');
|
||||
}
|
||||
catch (UnsupportedDataTypeConfigException $e) {
|
||||
$this->pass(SafeMarkup::format('%class thrown upon saving invalid data type.', array(
|
||||
$this->pass(SafeMarkup::format('%class thrown upon saving invalid data type.', [
|
||||
'%class' => get_class($e),
|
||||
)));
|
||||
]));
|
||||
}
|
||||
|
||||
// Test that setting an unsupported type for a config object with no schema
|
||||
|
|
@ -309,9 +309,9 @@ class ConfigCRUDTest extends KernelTestBase {
|
|||
$this->fail('No Exception thrown upon saving invalid data type.');
|
||||
}
|
||||
catch (UnsupportedDataTypeConfigException $e) {
|
||||
$this->pass(SafeMarkup::format('%class thrown upon saving invalid data type.', array(
|
||||
$this->pass(SafeMarkup::format('%class thrown upon saving invalid data type.', [
|
||||
'%class' => get_class($e),
|
||||
)));
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -21,20 +21,20 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'entity_test', 'user');
|
||||
public static $modules = ['config_test', 'entity_test', 'user'];
|
||||
|
||||
/**
|
||||
* Tests that calculating dependencies for system module.
|
||||
*/
|
||||
public function testNonEntity() {
|
||||
$this->installConfig(array('system'));
|
||||
$this->installConfig(['system']);
|
||||
$config_manager = \Drupal::service('config.manager');
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('system'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['system']);
|
||||
$this->assertTrue(isset($dependents['system.site']), 'Simple configuration system.site has a UUID key even though it is not a configuration entity and therefore is found when looking for dependencies of the System module.');
|
||||
// Ensure that calling
|
||||
// \Drupal\Core\Config\ConfigManager::findConfigEntityDependentsAsEntities()
|
||||
// does not try to load system.site as an entity.
|
||||
$config_manager->findConfigEntityDependentsAsEntities('module', array('system'));
|
||||
$config_manager->findConfigEntityDependentsAsEntities('module', ['system']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -46,22 +46,22 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$storage = $this->container->get('entity.manager')->getStorage('config_test');
|
||||
// Test dependencies between modules.
|
||||
$entity1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity1',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'module' => array('node')
|
||||
)
|
||||
)
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'module' => ['node']
|
||||
]
|
||||
]
|
||||
]
|
||||
);
|
||||
$entity1->save();
|
||||
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('node'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['node']);
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 has a dependency on the Node module.');
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('config_test'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['config_test']);
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 has a dependency on the config_test module.');
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('views'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['views']);
|
||||
$this->assertFalse(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 does not have a dependency on the Views module.');
|
||||
// Ensure that the provider of the config entity is not actually written to
|
||||
// the dependencies array.
|
||||
|
|
@ -70,22 +70,22 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertTrue(empty($root_module_dependencies), 'Node module is not written to the root dependencies array as it is enforced.');
|
||||
|
||||
// Create additional entities to test dependencies on config entities.
|
||||
$entity2 = $storage->create(array('id' => 'entity2', 'dependencies' => array('enforced' => array('config' => array($entity1->getConfigDependencyName())))));
|
||||
$entity2 = $storage->create(['id' => 'entity2', 'dependencies' => ['enforced' => ['config' => [$entity1->getConfigDependencyName()]]]]);
|
||||
$entity2->save();
|
||||
$entity3 = $storage->create(array('id' => 'entity3', 'dependencies' => array('enforced' => array('config' => array($entity2->getConfigDependencyName())))));
|
||||
$entity3 = $storage->create(['id' => 'entity3', 'dependencies' => ['enforced' => ['config' => [$entity2->getConfigDependencyName()]]]]);
|
||||
$entity3->save();
|
||||
$entity4 = $storage->create(array('id' => 'entity4', 'dependencies' => array('enforced' => array('config' => array($entity3->getConfigDependencyName())))));
|
||||
$entity4 = $storage->create(['id' => 'entity4', 'dependencies' => ['enforced' => ['config' => [$entity3->getConfigDependencyName()]]]]);
|
||||
$entity4->save();
|
||||
|
||||
// Test getting $entity1's dependencies as configuration dependency objects.
|
||||
$dependents = $config_manager->findConfigEntityDependents('config', array($entity1->getConfigDependencyName()));
|
||||
$dependents = $config_manager->findConfigEntityDependents('config', [$entity1->getConfigDependencyName()]);
|
||||
$this->assertFalse(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 does not have a dependency on itself.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity2']), 'config_test.dynamic.entity2 has a dependency on config_test.dynamic.entity1.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity3']), 'config_test.dynamic.entity3 has a dependency on config_test.dynamic.entity1.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity4']), 'config_test.dynamic.entity4 has a dependency on config_test.dynamic.entity1.');
|
||||
|
||||
// Test getting $entity2's dependencies as entities.
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('config', array($entity2->getConfigDependencyName()));
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('config', [$entity2->getConfigDependencyName()]);
|
||||
$dependent_ids = $this->getDependentIds($dependents);
|
||||
$this->assertFalse(in_array('config_test:entity1', $dependent_ids), 'config_test.dynamic.entity1 does not have a dependency on config_test.dynamic.entity1.');
|
||||
$this->assertFalse(in_array('config_test:entity2', $dependent_ids), 'config_test.dynamic.entity2 does not have a dependency on itself.');
|
||||
|
|
@ -94,7 +94,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
|
||||
// Test getting node module's dependencies as configuration dependency
|
||||
// objects.
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('node'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['node']);
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 has a dependency on the Node module.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity2']), 'config_test.dynamic.entity2 has a dependency on the Node module.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity3']), 'config_test.dynamic.entity3 has a dependency on the Node module.');
|
||||
|
|
@ -105,20 +105,20 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
// no longer depend on node module.
|
||||
$entity1->setEnforcedDependencies([])->save();
|
||||
$entity3->setEnforcedDependencies(['module' => ['node'], 'config' => [$entity2->getConfigDependencyName()]])->save();
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', array('node'));
|
||||
$dependents = $config_manager->findConfigEntityDependents('module', ['node']);
|
||||
$this->assertFalse(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 does not have a dependency on the Node module.');
|
||||
$this->assertFalse(isset($dependents['config_test.dynamic.entity2']), 'config_test.dynamic.entity2 does not have a dependency on the Node module.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity3']), 'config_test.dynamic.entity3 has a dependency on the Node module.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity4']), 'config_test.dynamic.entity4 has a dependency on the Node module.');
|
||||
|
||||
// Test dependency on a content entity.
|
||||
$entity_test = EntityTest::create(array(
|
||||
$entity_test = EntityTest::create([
|
||||
'name' => $this->randomString(),
|
||||
'type' => 'entity_test',
|
||||
));
|
||||
]);
|
||||
$entity_test->save();
|
||||
$entity2->setEnforcedDependencies(['config' => [$entity1->getConfigDependencyName()], 'content' => [$entity_test->getConfigDependencyName()]])->save();;
|
||||
$dependents = $config_manager->findConfigEntityDependents('content', array($entity_test->getConfigDependencyName()));
|
||||
$dependents = $config_manager->findConfigEntityDependents('content', [$entity_test->getConfigDependencyName()]);
|
||||
$this->assertFalse(isset($dependents['config_test.dynamic.entity1']), 'config_test.dynamic.entity1 does not have a dependency on the content entity.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity2']), 'config_test.dynamic.entity2 has a dependency on the content entity.');
|
||||
$this->assertTrue(isset($dependents['config_test.dynamic.entity3']), 'config_test.dynamic.entity3 has a dependency on the content entity (via entity2).');
|
||||
|
|
@ -127,10 +127,10 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
// Create a configuration entity of a different type with the same ID as one
|
||||
// of the entities already created.
|
||||
$alt_storage = $this->container->get('entity.manager')->getStorage('config_query_test');
|
||||
$alt_storage->create(array('id' => 'entity1', 'dependencies' => array('enforced' => array('config' => array($entity1->getConfigDependencyName())))))->save();
|
||||
$alt_storage->create(array('id' => 'entity2', 'dependencies' => array('enforced' => array('module' => array('views')))))->save();
|
||||
$alt_storage->create(['id' => 'entity1', 'dependencies' => ['enforced' => ['config' => [$entity1->getConfigDependencyName()]]]])->save();
|
||||
$alt_storage->create(['id' => 'entity2', 'dependencies' => ['enforced' => ['module' => ['views']]]])->save();
|
||||
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('config', array($entity1->getConfigDependencyName()));
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('config', [$entity1->getConfigDependencyName()]);
|
||||
$dependent_ids = $this->getDependentIds($dependents);
|
||||
$this->assertFalse(in_array('config_test:entity1', $dependent_ids), 'config_test.dynamic.entity1 does not have a dependency on itself.');
|
||||
$this->assertTrue(in_array('config_test:entity2', $dependent_ids), 'config_test.dynamic.entity2 has a dependency on config_test.dynamic.entity1.');
|
||||
|
|
@ -139,7 +139,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertTrue(in_array('config_query_test:entity1', $dependent_ids), 'config_query_test.dynamic.entity1 has a dependency on config_test.dynamic.entity1.');
|
||||
$this->assertFalse(in_array('config_query_test:entity2', $dependent_ids), 'config_query_test.dynamic.entity2 does not have a dependency on config_test.dynamic.entity1.');
|
||||
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('module', array('node', 'views'));
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('module', ['node', 'views']);
|
||||
$dependent_ids = $this->getDependentIds($dependents);
|
||||
$this->assertFalse(in_array('config_test:entity1', $dependent_ids), 'config_test.dynamic.entity1 does not have a dependency on Views or Node.');
|
||||
$this->assertFalse(in_array('config_test:entity2', $dependent_ids), 'config_test.dynamic.entity2 does not have a dependency on Views or Node.');
|
||||
|
|
@ -148,7 +148,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertFalse(in_array('config_query_test:entity1', $dependent_ids), 'config_test.query.entity1 does not have a dependency on Views or Node.');
|
||||
$this->assertTrue(in_array('config_query_test:entity2', $dependent_ids), 'config_test.query.entity2 has a dependency on Views or Node.');
|
||||
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('module', array('config_test'));
|
||||
$dependents = $config_manager->findConfigEntityDependentsAsEntities('module', ['config_test']);
|
||||
$dependent_ids = $this->getDependentIds($dependents);
|
||||
$this->assertTrue(in_array('config_test:entity1', $dependent_ids), 'config_test.dynamic.entity1 has a dependency on config_test module.');
|
||||
$this->assertTrue(in_array('config_test:entity2', $dependent_ids), 'config_test.dynamic.entity2 has a dependency on config_test module.');
|
||||
|
|
@ -194,25 +194,25 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
->getStorage('config_test');
|
||||
// Test dependencies between modules.
|
||||
$entity1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity1',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'module' => array('node', 'config_test')
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'module' => ['node', 'config_test']
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity1->save();
|
||||
$entity2 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity2',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity1->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity1->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity2->save();
|
||||
// Perform a module rebuild so we can know where the node module is located
|
||||
|
|
@ -258,14 +258,14 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
->getStorage('config_test');
|
||||
// Entity 1 will be deleted because it depends on node.
|
||||
$entity_1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity_' . $entity_id_suffixes[0],
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'module' => array('node', 'config_test')
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'module' => ['node', 'config_test']
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity_1->save();
|
||||
|
||||
|
|
@ -273,14 +273,14 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
// \Drupal\config_test\Entity::onDependencyRemoval() will remove the
|
||||
// dependency before config entities are deleted.
|
||||
$entity_2 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity_' . $entity_id_suffixes[1],
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity_1->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity_1->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity_2->save();
|
||||
|
||||
|
|
@ -288,34 +288,34 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
// be fixed. The ConfigEntityInterface::onDependencyRemoval() method will
|
||||
// not be called for this entity.
|
||||
$entity_3 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity_' . $entity_id_suffixes[2],
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity_2->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity_2->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity_3->save();
|
||||
|
||||
// Entity 4's config dependency will be fixed but it will still be deleted
|
||||
// because it also depends on the node module.
|
||||
$entity_4 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity_' . $entity_id_suffixes[3],
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity_1->getConfigDependencyName()),
|
||||
'module' => array('node', 'config_test')
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity_1->getConfigDependencyName()],
|
||||
'module' => ['node', 'config_test']
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity_4->save();
|
||||
|
||||
// Set a more complicated test where dependencies will be fixed.
|
||||
\Drupal::state()->set('config_test.fix_dependencies', array($entity_1->getConfigDependencyName()));
|
||||
\Drupal::state()->set('config_test.fix_dependencies', [$entity_1->getConfigDependencyName()]);
|
||||
\Drupal::state()->set('config_test.on_dependency_removal_called', []);
|
||||
|
||||
// Do a dry run using
|
||||
|
|
@ -341,7 +341,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertFalse($storage->load($entity_1->id()), 'Entity 1 deleted');
|
||||
$entity_2 = $storage->load($entity_2->id());
|
||||
$this->assertTrue($entity_2, 'Entity 2 not deleted');
|
||||
$this->assertEqual($entity_2->calculateDependencies()->getDependencies()['config'], array(), 'Entity 2 dependencies updated to remove dependency on entity 1.');
|
||||
$this->assertEqual($entity_2->calculateDependencies()->getDependencies()['config'], [], 'Entity 2 dependencies updated to remove dependency on entity 1.');
|
||||
$entity_3 = $storage->load($entity_3->id());
|
||||
$this->assertTrue($entity_3, 'Entity 3 not deleted');
|
||||
$this->assertEqual($entity_3->calculateDependencies()->getDependencies()['config'], [$entity_2->getConfigDependencyName()], 'Entity 3 still depends on entity 2.');
|
||||
|
|
@ -475,20 +475,20 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$storage = $this->container->get('entity.manager')->getStorage('config_test');
|
||||
// Test dependencies between configuration entities.
|
||||
$entity1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity1'
|
||||
)
|
||||
]
|
||||
);
|
||||
$entity1->save();
|
||||
$entity2 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity2',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity1->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity1->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity2->save();
|
||||
|
||||
|
|
@ -506,13 +506,13 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertFalse($storage->load('entity2'), 'Entity 2 deleted');
|
||||
|
||||
// Set a more complicated test where dependencies will be fixed.
|
||||
\Drupal::state()->set('config_test.fix_dependencies', array($entity1->getConfigDependencyName()));
|
||||
\Drupal::state()->set('config_test.fix_dependencies', [$entity1->getConfigDependencyName()]);
|
||||
|
||||
// Entity1 will be deleted by the test.
|
||||
$entity1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity1',
|
||||
)
|
||||
]
|
||||
);
|
||||
$entity1->save();
|
||||
|
||||
|
|
@ -520,28 +520,28 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
// \Drupal\config_test\Entity::onDependencyRemoval() will remove the
|
||||
// dependency before config entities are deleted.
|
||||
$entity2 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity2',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity1->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity1->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity2->save();
|
||||
|
||||
// Entity3 will be unchanged because it is dependent on Entity2 which can
|
||||
// be fixed.
|
||||
$entity3 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity3',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity2->getConfigDependencyName()),
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity2->getConfigDependencyName()],
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity3->save();
|
||||
|
||||
|
|
@ -559,7 +559,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
$this->assertFalse($storage->load('entity1'), 'Entity 1 deleted');
|
||||
$entity2 = $storage->load('entity2');
|
||||
$this->assertTrue($entity2, 'Entity 2 not deleted');
|
||||
$this->assertEqual($entity2->calculateDependencies()->getDependencies()['config'], array(), 'Entity 2 dependencies updated to remove dependency on Entity1.');
|
||||
$this->assertEqual($entity2->calculateDependencies()->getDependencies()['config'], [], 'Entity 2 dependencies updated to remove dependency on Entity1.');
|
||||
$entity3 = $storage->load('entity3');
|
||||
$this->assertTrue($entity3, 'Entity 3 not deleted');
|
||||
$this->assertEqual($entity3->calculateDependencies()->getDependencies()['config'], [$entity2->getConfigDependencyName()], 'Entity 3 still depends on Entity 2.');
|
||||
|
|
@ -585,30 +585,30 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
/** @var \Drupal\Core\Config\Entity\ConfigEntityStorage $storage */
|
||||
$storage = $this->container->get('entity.manager')->getStorage('config_test');
|
||||
$entity1 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity1',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'content' => array($content_entity->getConfigDependencyName())
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'content' => [$content_entity->getConfigDependencyName()]
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity1->save();
|
||||
$entity2 = $storage->create(
|
||||
array(
|
||||
[
|
||||
'id' => 'entity2',
|
||||
'dependencies' => array(
|
||||
'enforced' => array(
|
||||
'config' => array($entity1->getConfigDependencyName())
|
||||
),
|
||||
),
|
||||
)
|
||||
'dependencies' => [
|
||||
'enforced' => [
|
||||
'config' => [$entity1->getConfigDependencyName()]
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$entity2->save();
|
||||
|
||||
// Create a configuration entity that is not in the dependency chain.
|
||||
$entity3 = $storage->create(array('id' => 'entity3'));
|
||||
$entity3 = $storage->create(['id' => 'entity3']);
|
||||
$entity3->save();
|
||||
|
||||
$config_entities = $config_manager->getConfigEntitiesToChangeOnDependencyRemoval('content', [$content_entity->getConfigDependencyName()]);
|
||||
|
|
@ -628,7 +628,7 @@ class ConfigDependencyTest extends EntityKernelTestBase {
|
|||
* An array with values of entity_type_id:ID
|
||||
*/
|
||||
protected function getDependentIds(array $dependents) {
|
||||
$dependent_ids = array();
|
||||
$dependent_ids = [];
|
||||
foreach ($dependents as $dependent) {
|
||||
$dependent_ids[] = $dependent->getEntityTypeId() . ':' . $dependent->id();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -16,12 +16,12 @@ class ConfigDiffTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'system');
|
||||
public static $modules = ['config_test', 'system'];
|
||||
|
||||
/**
|
||||
* Tests calculating the difference between two sets of configuration.
|
||||
*/
|
||||
function testDiff() {
|
||||
public function testDiff() {
|
||||
$active = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$config_name = 'config_test.system';
|
||||
|
|
@ -32,7 +32,7 @@ class ConfigDiffTest extends KernelTestBase {
|
|||
$change_data = 'foobar';
|
||||
|
||||
// Install the default config.
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
$original_data = \Drupal::config($config_name)->get();
|
||||
|
||||
// Change a configuration value in sync.
|
||||
|
|
@ -75,10 +75,10 @@ class ConfigDiffTest extends KernelTestBase {
|
|||
|
||||
// Test diffing a renamed config entity.
|
||||
$test_entity_id = $this->randomMachineName();
|
||||
$test_entity = entity_create('config_test', array(
|
||||
$test_entity = entity_create('config_test', [
|
||||
'id' => $test_entity_id,
|
||||
'label' => $this->randomMachineName(),
|
||||
));
|
||||
]);
|
||||
$test_entity->save();
|
||||
$data = $active->read('config_test.dynamic.' . $test_entity_id);
|
||||
$sync->write('config_test.dynamic.' . $test_entity_id, $data);
|
||||
|
|
@ -108,7 +108,7 @@ class ConfigDiffTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests calculating the difference between two sets of config collections.
|
||||
*/
|
||||
function testCollectionDiff() {
|
||||
public function testCollectionDiff() {
|
||||
/** @var \Drupal\Core\Config\StorageInterface $active */
|
||||
$active = $this->container->get('config.storage');
|
||||
/** @var \Drupal\Core\Config\StorageInterface $sync */
|
||||
|
|
@ -117,12 +117,12 @@ class ConfigDiffTest extends KernelTestBase {
|
|||
$sync_test_collection = $sync->createCollection('test');
|
||||
|
||||
$config_name = 'config_test.test';
|
||||
$data = array('foo' => 'bar');
|
||||
$data = ['foo' => 'bar'];
|
||||
|
||||
$active->write($config_name, $data);
|
||||
$sync->write($config_name, $data);
|
||||
$active_test_collection->write($config_name, $data);
|
||||
$sync_test_collection->write($config_name, array('foo' => 'baz'));
|
||||
$sync_test_collection->write($config_name, ['foo' => 'baz']);
|
||||
|
||||
// Test the fields match in the default collection diff.
|
||||
$diff = \Drupal::service('config.manager')->diff($active, $sync, $config_name);
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class ConfigEntityNormalizeTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
|
@ -24,15 +24,15 @@ class ConfigEntityNormalizeTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
public function testNormalize() {
|
||||
$config_entity = entity_create('config_test', array('id' => 'system', 'label' => 'foobar', 'weight' => 1));
|
||||
$config_entity = entity_create('config_test', ['id' => 'system', 'label' => 'foobar', 'weight' => 1]);
|
||||
$config_entity->save();
|
||||
|
||||
// Modify stored config entity, this is comparable with a schema change.
|
||||
$config = $this->config('config_test.dynamic.system');
|
||||
$data = array(
|
||||
$data = [
|
||||
'label' => 'foobar',
|
||||
'additional_key' => TRUE
|
||||
) + $config->getRawData();
|
||||
] + $config->getRawData();
|
||||
$config->setData($data)->save();
|
||||
$this->assertNotIdentical($config_entity->toArray(), $config->getRawData(), 'Stored config entity is not is equivalent to config schema.');
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class ConfigEntityStaticCacheTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'config_entity_static_cache_test');
|
||||
public static $modules = ['config_test', 'config_entity_static_cache_test'];
|
||||
|
||||
/**
|
||||
* The type ID of the entity under test.
|
||||
|
|
@ -42,7 +42,7 @@ class ConfigEntityStaticCacheTest extends KernelTestBase {
|
|||
$this->entityId = 'test_1';
|
||||
$this->container->get('entity_type.manager')
|
||||
->getStorage($this->entityTypeId)
|
||||
->create(array('id' => $this->entityId, 'label' => 'Original label'))
|
||||
->create(['id' => $this->entityId, 'label' => 'Original label'])
|
||||
->save();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -16,15 +16,15 @@ class ConfigEntityStatusTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
/**
|
||||
* Tests the enabling/disabling of entities.
|
||||
*/
|
||||
function testCRUD() {
|
||||
$entity = entity_create('config_test', array(
|
||||
public function testCRUD() {
|
||||
$entity = entity_create('config_test', [
|
||||
'id' => strtolower($this->randomMachineName()),
|
||||
));
|
||||
]);
|
||||
$this->assertTrue($entity->status(), 'Default status is enabled.');
|
||||
$entity->save();
|
||||
$this->assertTrue($entity->status(), 'Status is enabled after saving.');
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class ConfigEntityStorageTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
/**
|
||||
* Tests creating configuration entities with changed UUIDs.
|
||||
|
|
@ -43,7 +43,7 @@ class ConfigEntityStorageTest extends KernelTestBase {
|
|||
$this->fail('Exception thrown when attempting to save a configuration entity with a UUID that does not match the existing UUID.');
|
||||
}
|
||||
catch (ConfigDuplicateUUIDException $e) {
|
||||
$this->pass(format_string('Exception thrown when attempting to save a configuration entity with a UUID that does not match existing data: %e.', array('%e' => $e)));
|
||||
$this->pass(format_string('Exception thrown when attempting to save a configuration entity with a UUID that does not match existing data: %e.', ['%e' => $e]));
|
||||
}
|
||||
|
||||
// Ensure that the config entity was not corrupted.
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ class ConfigEntityUnitTest extends KernelTestBase {
|
|||
/**
|
||||
* Exempt from strict schema checking.
|
||||
*
|
||||
* @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
|
||||
* @see \Drupal\Core\Config\Development\ConfigSchemaChecker
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
|
|
@ -25,7 +25,7 @@ class ConfigEntityUnitTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
/**
|
||||
* The config_test entity storage.
|
||||
|
|
@ -57,19 +57,19 @@ class ConfigEntityUnitTest extends KernelTestBase {
|
|||
// Create three entities, two with the same style.
|
||||
$style = $this->randomMachineName(8);
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
$entity = $this->storage->create(array(
|
||||
$entity = $this->storage->create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => $this->randomString(),
|
||||
'style' => $style,
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
}
|
||||
$entity = $this->storage->create(array(
|
||||
$entity = $this->storage->create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => $this->randomString(),
|
||||
// Use a different length for the entity to ensure uniqueness.
|
||||
'style' => $this->randomMachineName(9),
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
// Ensure that the configuration entity can be loaded by UUID.
|
||||
|
|
@ -85,7 +85,7 @@ class ConfigEntityUnitTest extends KernelTestBase {
|
|||
$entities = $this->storage->loadByProperties();
|
||||
$this->assertEqual(count($entities), 3, 'Three entities are loaded when no properties are specified.');
|
||||
|
||||
$entities = $this->storage->loadByProperties(array('style' => $style));
|
||||
$entities = $this->storage->loadByProperties(['style' => $style]);
|
||||
$this->assertEqual(count($entities), 2, 'Two entities are loaded when the style property is specified.');
|
||||
|
||||
// Assert that both returned entities have a matching style property.
|
||||
|
|
@ -94,11 +94,11 @@ class ConfigEntityUnitTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Test that schema type enforcement can be overridden by trusting the data.
|
||||
$entity = $this->storage->create(array(
|
||||
$entity = $this->storage->create([
|
||||
'id' => $this->randomMachineName(),
|
||||
'label' => $this->randomString(),
|
||||
'style' => 999
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
$this->assertIdentical('999', $entity->style);
|
||||
$entity->style = 999;
|
||||
|
|
|
|||
|
|
@ -18,64 +18,64 @@ class ConfigEventsTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_events_test');
|
||||
public static $modules = ['config_events_test'];
|
||||
|
||||
/**
|
||||
* Tests configuration events.
|
||||
*/
|
||||
function testConfigEvents() {
|
||||
public function testConfigEvents() {
|
||||
$name = 'config_events_test.test';
|
||||
|
||||
$config = new Config($name, \Drupal::service('config.storage'), \Drupal::service('event_dispatcher'), \Drupal::service('config.typed'));
|
||||
$config->set('key', 'initial');
|
||||
$this->assertIdentical(\Drupal::state()->get('config_events_test.event', array()), array(), 'No events fired by creating a new configuration object');
|
||||
$this->assertIdentical(\Drupal::state()->get('config_events_test.event', []), [], 'No events fired by creating a new configuration object');
|
||||
$config->save();
|
||||
|
||||
$event = \Drupal::state()->get('config_events_test.event', array());
|
||||
$event = \Drupal::state()->get('config_events_test.event', []);
|
||||
$this->assertIdentical($event['event_name'], ConfigEvents::SAVE);
|
||||
$this->assertIdentical($event['current_config_data'], array('key' => 'initial'));
|
||||
$this->assertIdentical($event['raw_config_data'], array('key' => 'initial'));
|
||||
$this->assertIdentical($event['original_config_data'], array());
|
||||
$this->assertIdentical($event['current_config_data'], ['key' => 'initial']);
|
||||
$this->assertIdentical($event['raw_config_data'], ['key' => 'initial']);
|
||||
$this->assertIdentical($event['original_config_data'], []);
|
||||
|
||||
$config->set('key', 'updated')->save();
|
||||
$event = \Drupal::state()->get('config_events_test.event', array());
|
||||
$event = \Drupal::state()->get('config_events_test.event', []);
|
||||
$this->assertIdentical($event['event_name'], ConfigEvents::SAVE);
|
||||
$this->assertIdentical($event['current_config_data'], array('key' => 'updated'));
|
||||
$this->assertIdentical($event['raw_config_data'], array('key' => 'updated'));
|
||||
$this->assertIdentical($event['original_config_data'], array('key' => 'initial'));
|
||||
$this->assertIdentical($event['current_config_data'], ['key' => 'updated']);
|
||||
$this->assertIdentical($event['raw_config_data'], ['key' => 'updated']);
|
||||
$this->assertIdentical($event['original_config_data'], ['key' => 'initial']);
|
||||
|
||||
$config->delete();
|
||||
$event = \Drupal::state()->get('config_events_test.event', array());
|
||||
$event = \Drupal::state()->get('config_events_test.event', []);
|
||||
$this->assertIdentical($event['event_name'], ConfigEvents::DELETE);
|
||||
$this->assertIdentical($event['current_config_data'], array());
|
||||
$this->assertIdentical($event['raw_config_data'], array());
|
||||
$this->assertIdentical($event['original_config_data'], array('key' => 'updated'));
|
||||
$this->assertIdentical($event['current_config_data'], []);
|
||||
$this->assertIdentical($event['raw_config_data'], []);
|
||||
$this->assertIdentical($event['original_config_data'], ['key' => 'updated']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests configuration rename event that is fired from the ConfigFactory.
|
||||
*/
|
||||
function testConfigRenameEvent() {
|
||||
public function testConfigRenameEvent() {
|
||||
$name = 'config_events_test.test';
|
||||
$new_name = 'config_events_test.test_rename';
|
||||
$GLOBALS['config'][$name] = array('key' => 'overridden');
|
||||
$GLOBALS['config'][$new_name] = array('key' => 'new overridden');
|
||||
$GLOBALS['config'][$name] = ['key' => 'overridden'];
|
||||
$GLOBALS['config'][$new_name] = ['key' => 'new overridden'];
|
||||
|
||||
$config = $this->config($name);
|
||||
$config->set('key', 'initial')->save();
|
||||
$event = \Drupal::state()->get('config_events_test.event', array());
|
||||
$event = \Drupal::state()->get('config_events_test.event', []);
|
||||
$this->assertIdentical($event['event_name'], ConfigEvents::SAVE);
|
||||
$this->assertIdentical($event['current_config_data'], array('key' => 'initial'));
|
||||
$this->assertIdentical($event['current_config_data'], ['key' => 'initial']);
|
||||
|
||||
// Override applies when getting runtime config.
|
||||
$this->assertEqual($GLOBALS['config'][$name], \Drupal::config($name)->get());
|
||||
|
||||
\Drupal::configFactory()->rename($name, $new_name);
|
||||
$event = \Drupal::state()->get('config_events_test.event', array());
|
||||
$event = \Drupal::state()->get('config_events_test.event', []);
|
||||
$this->assertIdentical($event['event_name'], ConfigEvents::RENAME);
|
||||
$this->assertIdentical($event['current_config_data'], array('key' => 'new overridden'));
|
||||
$this->assertIdentical($event['raw_config_data'], array('key' => 'initial'));
|
||||
$this->assertIdentical($event['original_config_data'], array('key' => 'new overridden'));
|
||||
$this->assertIdentical($event['current_config_data'], ['key' => 'new overridden']);
|
||||
$this->assertIdentical($event['raw_config_data'], ['key' => 'initial']);
|
||||
$this->assertIdentical($event['original_config_data'], ['key' => 'new overridden']);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
/**
|
||||
* Exempt from strict schema checking.
|
||||
*
|
||||
* @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
|
||||
* @see \Drupal\Core\Config\Development\ConfigSchemaChecker
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
|
|
@ -24,7 +24,7 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests setting, writing, and reading of a configuration setting.
|
||||
*/
|
||||
function testReadWriteConfig() {
|
||||
public function testReadWriteConfig() {
|
||||
$storage = $this->container->get('config.storage');
|
||||
|
||||
$name = 'foo.bar';
|
||||
|
|
@ -33,19 +33,19 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
$nested_key = 'biff.bang';
|
||||
$nested_value = 'pow';
|
||||
$array_key = 'array';
|
||||
$array_value = array(
|
||||
$array_value = [
|
||||
'foo' => 'bar',
|
||||
'biff' => array(
|
||||
'biff' => [
|
||||
'bang' => 'pow',
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$casting_array_key = 'casting_array';
|
||||
$casting_array_false_value_key = 'casting_array.cast.false';
|
||||
$casting_array_value = array(
|
||||
'cast' => array(
|
||||
$casting_array_value = [
|
||||
'cast' => [
|
||||
'false' => FALSE,
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$nested_array_key = 'nested.array';
|
||||
$true_key = 'true';
|
||||
$false_key = 'false';
|
||||
|
|
@ -58,7 +58,7 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
$this->assertTrue($config, 'Config object created.');
|
||||
|
||||
// Verify the configuration object is empty.
|
||||
$this->assertEqual($config->get(), array(), 'New config object is empty.');
|
||||
$this->assertEqual($config->get(), [], 'New config object is empty.');
|
||||
|
||||
// Verify nothing was saved.
|
||||
$data = $storage->read($name);
|
||||
|
|
@ -173,7 +173,7 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
// Get file listing for all files starting with 'bar'. Should return
|
||||
// an empty array.
|
||||
$files = $storage->listAll('bar');
|
||||
$this->assertEqual($files, array(), 'No files listed with the prefix \'bar\'.');
|
||||
$this->assertEqual($files, [], 'No files listed with the prefix \'bar\'.');
|
||||
|
||||
// Delete the configuration.
|
||||
$config = $this->config($name);
|
||||
|
|
@ -187,22 +187,22 @@ class ConfigFileContentTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests serialization of configuration to file.
|
||||
*/
|
||||
function testSerialization() {
|
||||
public function testSerialization() {
|
||||
$name = $this->randomMachineName(10) . '.' . $this->randomMachineName(10);
|
||||
$config_data = array(
|
||||
$config_data = [
|
||||
// Indexed arrays; the order of elements is essential.
|
||||
'numeric keys' => array('i', 'n', 'd', 'e', 'x', 'e', 'd'),
|
||||
'numeric keys' => ['i', 'n', 'd', 'e', 'x', 'e', 'd'],
|
||||
// Infinitely nested keys using arbitrary element names.
|
||||
'nested keys' => array(
|
||||
'nested keys' => [
|
||||
// HTML/XML in values.
|
||||
'HTML' => '<strong> <bold> <em> <blockquote>',
|
||||
// UTF-8 in values.
|
||||
'UTF-8' => 'FrançAIS is ÜBER-åwesome',
|
||||
// Unicode in keys and values.
|
||||
'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ' => 'αβγδεζηθικλμνξοσὠ',
|
||||
),
|
||||
],
|
||||
'invalid xml' => '</title><script type="text/javascript">alert("Title XSS!");</script> & < > " \' ',
|
||||
);
|
||||
];
|
||||
|
||||
// Encode and write, and reload and decode the configuration data.
|
||||
$filestorage = new FileStorage(config_get_config_directory(CONFIG_SYNC_DIRECTORY));
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class ConfigImportRecreateTest extends KernelTestBase {
|
|||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('node');
|
||||
$this->installConfig(array('field', 'node'));
|
||||
$this->installConfig(['field', 'node']);
|
||||
|
||||
$this->copyConfig($this->container->get('config.storage'), $this->container->get('config.storage.sync'));
|
||||
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
|
||||
$this->installEntitySchema('user');
|
||||
$this->installEntitySchema('node');
|
||||
$this->installConfig(array('field'));
|
||||
$this->installConfig(['field']);
|
||||
|
||||
// Set up the ConfigImporter object for testing.
|
||||
$storage_comparer = new StorageComparer(
|
||||
|
|
@ -67,10 +67,10 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
public function testRenameValidation() {
|
||||
// Create a test entity.
|
||||
$test_entity_id = $this->randomMachineName();
|
||||
$test_entity = entity_create('config_test', array(
|
||||
$test_entity = entity_create('config_test', [
|
||||
'id' => $test_entity_id,
|
||||
'label' => $this->randomMachineName(),
|
||||
));
|
||||
]);
|
||||
$test_entity->save();
|
||||
$uuid = $test_entity->uuid();
|
||||
|
||||
|
|
@ -91,9 +91,9 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
// Confirm that the staged configuration is detected as a rename since the
|
||||
// UUIDs match.
|
||||
$this->configImporter->reset();
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'node.type.' . $content_type->id() . '::config_test.dynamic.' . $test_entity_id,
|
||||
);
|
||||
];
|
||||
$renames = $this->configImporter->getUnprocessedConfiguration('rename');
|
||||
$this->assertIdentical($expected, $renames);
|
||||
|
||||
|
|
@ -105,9 +105,9 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
}
|
||||
catch (ConfigImporterException $e) {
|
||||
$this->pass('Expected ConfigImporterException thrown when a renamed configuration entity does not match the existing entity type.');
|
||||
$expected = array(
|
||||
SafeMarkup::format('Entity type mismatch on rename. @old_type not equal to @new_type for existing configuration @old_name and staged configuration @new_name.', array('@old_type' => 'node_type', '@new_type' => 'config_test', '@old_name' => 'node.type.' . $content_type->id(), '@new_name' => 'config_test.dynamic.' . $test_entity_id))
|
||||
);
|
||||
$expected = [
|
||||
SafeMarkup::format('Entity type mismatch on rename. @old_type not equal to @new_type for existing configuration @old_name and staged configuration @new_name.', ['@old_type' => 'node_type', '@new_type' => 'config_test', '@old_name' => 'node.type.' . $content_type->id(), '@new_name' => 'config_test.dynamic.' . $test_entity_id])
|
||||
];
|
||||
$this->assertEqual($expected, $this->configImporter->getErrors());
|
||||
}
|
||||
}
|
||||
|
|
@ -134,9 +134,9 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
// Confirm that the staged configuration is detected as a rename since the
|
||||
// UUIDs match.
|
||||
$this->configImporter->reset();
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'config_test.old::config_test.new'
|
||||
);
|
||||
];
|
||||
$renames = $this->configImporter->getUnprocessedConfiguration('rename');
|
||||
$this->assertIdentical($expected, $renames);
|
||||
|
||||
|
|
@ -148,9 +148,9 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
|
|||
}
|
||||
catch (ConfigImporterException $e) {
|
||||
$this->pass('Expected ConfigImporterException thrown when simple configuration is renamed.');
|
||||
$expected = array(
|
||||
SafeMarkup::format('Rename operation for simple configuration. Existing configuration @old_name and staged configuration @new_name.', array('@old_name' => 'config_test.old', '@new_name' => 'config_test.new'))
|
||||
);
|
||||
$expected = [
|
||||
SafeMarkup::format('Rename operation for simple configuration. Existing configuration @old_name and staged configuration @new_name.', ['@old_name' => 'config_test.old', '@new_name' => 'config_test.new'])
|
||||
];
|
||||
$this->assertEqual($expected, $this->configImporter->getErrors());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -26,14 +26,14 @@ class ConfigImporterMissingContentTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'user', 'entity_test', 'config_test', 'config_import_test');
|
||||
public static $modules = ['system', 'user', 'entity_test', 'config_test', 'config_import_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installSchema('system', 'sequences');
|
||||
$this->installEntitySchema('entity_test');
|
||||
$this->installEntitySchema('user');
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
// Installing config_test's default configuration pollutes the global
|
||||
// variable being used for recording hook invocations by this test already,
|
||||
// so it has to be cleared out manually.
|
||||
|
|
@ -66,16 +66,16 @@ class ConfigImporterMissingContentTest extends KernelTestBase {
|
|||
* @see \Drupal\Core\Config\ConfigImporter::processMissingContent()
|
||||
* @see \Drupal\config_import_test\EventSubscriber
|
||||
*/
|
||||
function testMissingContent() {
|
||||
public function testMissingContent() {
|
||||
\Drupal::state()->set('config_import_test.config_import_missing_content', TRUE);
|
||||
|
||||
// Update a configuration entity in the sync directory to have a dependency
|
||||
// on two content entities that do not exist.
|
||||
$storage = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$entity_one = EntityTest::create(array('name' => 'one'));
|
||||
$entity_two = EntityTest::create(array('name' => 'two'));
|
||||
$entity_three = EntityTest::create(array('name' => 'three'));
|
||||
$entity_one = EntityTest::create(['name' => 'one']);
|
||||
$entity_two = EntityTest::create(['name' => 'two']);
|
||||
$entity_three = EntityTest::create(['name' => 'three']);
|
||||
$dynamic_name = 'config_test.dynamic.dotted.default';
|
||||
$original_dynamic_data = $storage->read($dynamic_name);
|
||||
// Entity one will be resolved by
|
||||
|
|
|
|||
|
|
@ -28,12 +28,12 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'system', 'config_import_test');
|
||||
public static $modules = ['config_test', 'system', 'config_import_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
// Installing config_test's default configuration pollutes the global
|
||||
// variable being used for recording hook invocations by this test already,
|
||||
// so it has to be cleared out manually.
|
||||
|
|
@ -63,7 +63,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests omission of module APIs for bare configuration operations.
|
||||
*/
|
||||
function testNoImport() {
|
||||
public function testNoImport() {
|
||||
$dynamic_name = 'config_test.dynamic.dotted.default';
|
||||
|
||||
// Verify the default configuration values exist.
|
||||
|
|
@ -78,7 +78,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
* Tests that trying to import from an empty sync configuration directory
|
||||
* fails.
|
||||
*/
|
||||
function testEmptyImportFails() {
|
||||
public function testEmptyImportFails() {
|
||||
try {
|
||||
$this->container->get('config.storage.sync')->deleteAll();
|
||||
$this->configImporter->reset()->import();
|
||||
|
|
@ -92,7 +92,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests verification of site UUID before importing configuration.
|
||||
*/
|
||||
function testSiteUuidValidate() {
|
||||
public function testSiteUuidValidate() {
|
||||
$sync = \Drupal::service('config.storage.sync');
|
||||
// Create updated configuration object.
|
||||
$config_data = $this->config('system.site')->get();
|
||||
|
|
@ -106,7 +106,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
catch (ConfigImporterException $e) {
|
||||
$this->assertEqual($e->getMessage(), 'There were errors validating the config synchronization.');
|
||||
$error_log = $this->configImporter->getErrors();
|
||||
$expected = array('Site UUID in source storage does not match the target storage.');
|
||||
$expected = ['Site UUID in source storage does not match the target storage.'];
|
||||
$this->assertEqual($expected, $error_log);
|
||||
}
|
||||
}
|
||||
|
|
@ -114,7 +114,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests deletion of configuration during import.
|
||||
*/
|
||||
function testDeleted() {
|
||||
public function testDeleted() {
|
||||
$dynamic_name = 'config_test.dynamic.dotted.default';
|
||||
$storage = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
|
|
@ -151,7 +151,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests creation of configuration during import.
|
||||
*/
|
||||
function testNew() {
|
||||
public function testNew() {
|
||||
$dynamic_name = 'config_test.dynamic.new';
|
||||
$storage = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
|
|
@ -160,11 +160,11 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
$this->assertIdentical($storage->exists($dynamic_name), FALSE, $dynamic_name . ' not found.');
|
||||
|
||||
// Create new config entity.
|
||||
$original_dynamic_data = array(
|
||||
$original_dynamic_data = [
|
||||
'uuid' => '30df59bd-7b03-4cf7-bb35-d42fc49f0651',
|
||||
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(),
|
||||
'status' => TRUE,
|
||||
'dependencies' => array(),
|
||||
'dependencies' => [],
|
||||
'id' => 'new',
|
||||
'label' => 'New',
|
||||
'weight' => 0,
|
||||
|
|
@ -172,7 +172,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
'size' => '',
|
||||
'size_value' => '',
|
||||
'protected_property' => '',
|
||||
);
|
||||
];
|
||||
$sync->write($dynamic_name, $original_dynamic_data);
|
||||
|
||||
$this->assertIdentical($sync->exists($dynamic_name), TRUE, $dynamic_name . ' found.');
|
||||
|
|
@ -205,29 +205,29 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that secondary writes are overwritten.
|
||||
*/
|
||||
function testSecondaryWritePrimaryFirst() {
|
||||
public function testSecondaryWritePrimaryFirst() {
|
||||
$name_primary = 'config_test.dynamic.primary';
|
||||
$name_secondary = 'config_test.dynamic.secondary';
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$uuid = $this->container->get('uuid');
|
||||
|
||||
$values_primary = array(
|
||||
$values_primary = [
|
||||
'id' => 'primary',
|
||||
'label' => 'Primary',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
);
|
||||
];
|
||||
$sync->write($name_primary, $values_primary);
|
||||
$values_secondary = array(
|
||||
$values_secondary = [
|
||||
'id' => 'secondary',
|
||||
'label' => 'Secondary Sync',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on primary, to ensure that is synced first.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_primary),
|
||||
)
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_primary],
|
||||
]
|
||||
];
|
||||
$sync->write($name_secondary, $values_secondary);
|
||||
|
||||
// Import.
|
||||
|
|
@ -245,35 +245,35 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
|
||||
$logs = $this->configImporter->getErrors();
|
||||
$this->assertEqual(count($logs), 1);
|
||||
$this->assertEqual($logs[0], SafeMarkup::format('Deleted and replaced configuration entity "@name"', array('@name' => $name_secondary)));
|
||||
$this->assertEqual($logs[0], SafeMarkup::format('Deleted and replaced configuration entity "@name"', ['@name' => $name_secondary]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that secondary writes are overwritten.
|
||||
*/
|
||||
function testSecondaryWriteSecondaryFirst() {
|
||||
public function testSecondaryWriteSecondaryFirst() {
|
||||
$name_primary = 'config_test.dynamic.primary';
|
||||
$name_secondary = 'config_test.dynamic.secondary';
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$uuid = $this->container->get('uuid');
|
||||
|
||||
$values_primary = array(
|
||||
$values_primary = [
|
||||
'id' => 'primary',
|
||||
'label' => 'Primary',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on secondary, so that is synced first.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_secondary),
|
||||
)
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_secondary],
|
||||
]
|
||||
];
|
||||
$sync->write($name_primary, $values_primary);
|
||||
$values_secondary = array(
|
||||
$values_secondary = [
|
||||
'id' => 'secondary',
|
||||
'label' => 'Secondary Sync',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
);
|
||||
];
|
||||
$sync->write($name_secondary, $values_secondary);
|
||||
|
||||
// Import.
|
||||
|
|
@ -297,7 +297,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that secondary updates for deleted files work as expected.
|
||||
*/
|
||||
function testSecondaryUpdateDeletedDeleterFirst() {
|
||||
public function testSecondaryUpdateDeletedDeleterFirst() {
|
||||
$name_deleter = 'config_test.dynamic.deleter';
|
||||
$name_deletee = 'config_test.dynamic.deletee';
|
||||
$name_other = 'config_test.dynamic.other';
|
||||
|
|
@ -305,52 +305,52 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
$sync = $this->container->get('config.storage.sync');
|
||||
$uuid = $this->container->get('uuid');
|
||||
|
||||
$values_deleter = array(
|
||||
$values_deleter = [
|
||||
'id' => 'deleter',
|
||||
'label' => 'Deleter',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
);
|
||||
];
|
||||
$storage->write($name_deleter, $values_deleter);
|
||||
$values_deleter['label'] = 'Updated Deleter';
|
||||
$sync->write($name_deleter, $values_deleter);
|
||||
$values_deletee = array(
|
||||
$values_deletee = [
|
||||
'id' => 'deletee',
|
||||
'label' => 'Deletee',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on deleter, to make sure that is synced first.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_deleter),
|
||||
)
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_deleter],
|
||||
]
|
||||
];
|
||||
$storage->write($name_deletee, $values_deletee);
|
||||
$values_deletee['label'] = 'Updated Deletee';
|
||||
$sync->write($name_deletee, $values_deletee);
|
||||
|
||||
// Ensure that import will continue after the error.
|
||||
$values_other = array(
|
||||
$values_other = [
|
||||
'id' => 'other',
|
||||
'label' => 'Other',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on deleter, to make sure that is synced first. This
|
||||
// will also be synced after the deletee due to alphabetical ordering.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_deleter),
|
||||
)
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_deleter],
|
||||
]
|
||||
];
|
||||
$storage->write($name_other, $values_other);
|
||||
$values_other['label'] = 'Updated other';
|
||||
$sync->write($name_other, $values_other);
|
||||
|
||||
// Check update changelist order.
|
||||
$updates = $this->configImporter->reset()->getStorageComparer()->getChangelist('update');
|
||||
$expected = array(
|
||||
$expected = [
|
||||
$name_deleter,
|
||||
$name_deletee,
|
||||
$name_other,
|
||||
);
|
||||
];
|
||||
$this->assertIdentical($expected, $updates);
|
||||
|
||||
// Import.
|
||||
|
|
@ -373,7 +373,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
|
||||
$logs = $this->configImporter->getErrors();
|
||||
$this->assertEqual(count($logs), 1);
|
||||
$this->assertEqual($logs[0], SafeMarkup::format('Update target "@name" is missing.', array('@name' => $name_deletee)));
|
||||
$this->assertEqual($logs[0], SafeMarkup::format('Update target "@name" is missing.', ['@name' => $name_deletee]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -383,32 +383,32 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
* configuration tree imports. Therefore, any configuration updates that cause
|
||||
* secondary deletes should be reflected already in the staged configuration.
|
||||
*/
|
||||
function testSecondaryUpdateDeletedDeleteeFirst() {
|
||||
public function testSecondaryUpdateDeletedDeleteeFirst() {
|
||||
$name_deleter = 'config_test.dynamic.deleter';
|
||||
$name_deletee = 'config_test.dynamic.deletee';
|
||||
$storage = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$uuid = $this->container->get('uuid');
|
||||
|
||||
$values_deleter = array(
|
||||
$values_deleter = [
|
||||
'id' => 'deleter',
|
||||
'label' => 'Deleter',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on deletee, to make sure that is synced first.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_deletee),
|
||||
),
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_deletee],
|
||||
],
|
||||
];
|
||||
$storage->write($name_deleter, $values_deleter);
|
||||
$values_deleter['label'] = 'Updated Deleter';
|
||||
$sync->write($name_deleter, $values_deleter);
|
||||
$values_deletee = array(
|
||||
$values_deletee = [
|
||||
'id' => 'deletee',
|
||||
'label' => 'Deletee',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
);
|
||||
];
|
||||
$storage->write($name_deletee, $values_deletee);
|
||||
$values_deletee['label'] = 'Updated Deletee';
|
||||
$sync->write($name_deletee, $values_deletee);
|
||||
|
|
@ -429,30 +429,30 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that secondary deletes for deleted files work as expected.
|
||||
*/
|
||||
function testSecondaryDeletedDeleteeSecond() {
|
||||
public function testSecondaryDeletedDeleteeSecond() {
|
||||
$name_deleter = 'config_test.dynamic.deleter';
|
||||
$name_deletee = 'config_test.dynamic.deletee';
|
||||
$storage = $this->container->get('config.storage');
|
||||
|
||||
$uuid = $this->container->get('uuid');
|
||||
|
||||
$values_deleter = array(
|
||||
$values_deleter = [
|
||||
'id' => 'deleter',
|
||||
'label' => 'Deleter',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
// Add a dependency on deletee, to make sure this delete is synced first.
|
||||
'dependencies' => array(
|
||||
'config' => array($name_deletee),
|
||||
),
|
||||
);
|
||||
'dependencies' => [
|
||||
'config' => [$name_deletee],
|
||||
],
|
||||
];
|
||||
$storage->write($name_deleter, $values_deleter);
|
||||
$values_deletee = array(
|
||||
$values_deletee = [
|
||||
'id' => 'deletee',
|
||||
'label' => 'Deletee',
|
||||
'weight' => 0,
|
||||
'uuid' => $uuid->generate(),
|
||||
);
|
||||
];
|
||||
$storage->write($name_deletee, $values_deletee);
|
||||
|
||||
// Import.
|
||||
|
|
@ -471,7 +471,7 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests updating of configuration during import.
|
||||
*/
|
||||
function testUpdated() {
|
||||
public function testUpdated() {
|
||||
$name = 'config_test.system';
|
||||
$dynamic_name = 'config_test.dynamic.dotted.default';
|
||||
$storage = $this->container->get('config.storage');
|
||||
|
|
@ -483,9 +483,9 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
|
||||
// Replace the file content of the existing configuration objects in the
|
||||
// sync directory.
|
||||
$original_name_data = array(
|
||||
$original_name_data = [
|
||||
'foo' => 'beer',
|
||||
);
|
||||
];
|
||||
$sync->write($name, $original_name_data);
|
||||
$original_dynamic_data = $storage->read($dynamic_name);
|
||||
$original_dynamic_data['label'] = 'Updated';
|
||||
|
|
@ -528,11 +528,11 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests the isInstallable method()
|
||||
*/
|
||||
function testIsInstallable() {
|
||||
public function testIsInstallable() {
|
||||
$config_name = 'config_test.dynamic.isinstallable';
|
||||
$this->assertFalse($this->container->get('config.storage')->exists($config_name));
|
||||
\Drupal::state()->set('config_test.isinstallable', TRUE);
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
$this->assertTrue($this->container->get('config.storage')->exists($config_name));
|
||||
}
|
||||
|
||||
|
|
@ -668,6 +668,34 @@ class ConfigImporterTest extends KernelTestBase {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests install profile validation during configuration import.
|
||||
*
|
||||
* @see \Drupal\Core\EventSubscriber\ConfigImportSubscriber
|
||||
*/
|
||||
public function testInstallProfileMisMatch() {
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
|
||||
$extensions = $sync->read('core.extension');
|
||||
// Change the install profile.
|
||||
$extensions['profile'] = 'this_will_not_work';
|
||||
$sync->write('core.extension', $extensions);
|
||||
|
||||
try {
|
||||
$this->configImporter->reset()->import();
|
||||
$this->fail('ConfigImporterException not thrown; an invalid import was not stopped due to missing dependencies.');
|
||||
}
|
||||
catch (ConfigImporterException $e) {
|
||||
$this->assertEqual($e->getMessage(), 'There were errors validating the config synchronization.');
|
||||
$error_log = $this->configImporter->getErrors();
|
||||
// Install profiles can not be changed. Note that KernelTestBase currently
|
||||
// does not use an install profile. This situation should be impossible
|
||||
// to get in but site's can removed the install profile setting from
|
||||
// settings.php so the test is valid.
|
||||
$this->assertEqual(['Cannot change the install profile from <em class="placeholder">this_will_not_work</em> to <em class="placeholder"></em> once Drupal is installed.'], $error_log);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests config_get_config_directory().
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests module installation.
|
||||
*/
|
||||
function testModuleInstallation() {
|
||||
public function testModuleInstallation() {
|
||||
$default_config = 'config_test.system';
|
||||
$default_configuration_entity = 'config_test.dynamic.dotted.default';
|
||||
|
||||
|
|
@ -49,7 +49,7 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
$this->assertFalse(\Drupal::service('config.typed')->hasConfigSchema('config_schema_test.someschema'), 'Configuration schema for config_schema_test.someschema does not exist.');
|
||||
|
||||
// Install the test module.
|
||||
$this->installModules(array('config_test'));
|
||||
$this->installModules(['config_test']);
|
||||
|
||||
// Verify that default module config exists.
|
||||
\Drupal::configFactory()->reset($default_config);
|
||||
|
|
@ -69,14 +69,14 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
$this->assertFalse(isset($GLOBALS['hook_config_test']['delete']));
|
||||
|
||||
// Install the schema test module.
|
||||
$this->enableModules(array('config_schema_test'));
|
||||
$this->installConfig(array('config_schema_test'));
|
||||
$this->enableModules(['config_schema_test']);
|
||||
$this->installConfig(['config_schema_test']);
|
||||
|
||||
// After module installation the new schema should exist.
|
||||
$this->assertTrue(\Drupal::service('config.typed')->hasConfigSchema('config_schema_test.someschema'), 'Configuration schema for config_schema_test.someschema exists.');
|
||||
|
||||
// Test that uninstalling configuration removes configuration schema.
|
||||
$this->config('core.extension')->set('module', array())->save();
|
||||
$this->config('core.extension')->set('module', [])->save();
|
||||
\Drupal::service('config.manager')->uninstall('module', 'config_test');
|
||||
$this->assertFalse(\Drupal::service('config.typed')->hasConfigSchema('config_schema_test.someschema'), 'Configuration schema for config_schema_test.someschema does not exist.');
|
||||
}
|
||||
|
|
@ -86,28 +86,28 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
*/
|
||||
public function testCollectionInstallationNoCollections() {
|
||||
// Install the test module.
|
||||
$this->enableModules(array('config_collection_install_test'));
|
||||
$this->installConfig(array('config_collection_install_test'));
|
||||
$this->enableModules(['config_collection_install_test']);
|
||||
$this->installConfig(['config_collection_install_test']);
|
||||
/** @var \Drupal\Core\Config\StorageInterface $active_storage */
|
||||
$active_storage = \Drupal::service('config.storage');
|
||||
$this->assertEqual(array(), $active_storage->getAllCollectionNames());
|
||||
$this->assertEqual([], $active_storage->getAllCollectionNames());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests config objects in collections are installed as expected.
|
||||
*/
|
||||
public function testCollectionInstallationCollections() {
|
||||
$collections = array(
|
||||
$collections = [
|
||||
'another_collection',
|
||||
'collection.test1',
|
||||
'collection.test2',
|
||||
);
|
||||
];
|
||||
// Set the event listener to return three possible collections.
|
||||
// @see \Drupal\config_collection_install_test\EventSubscriber
|
||||
\Drupal::state()->set('config_collection_install_test.collection_names', $collections);
|
||||
// Install the test module.
|
||||
$this->enableModules(array('config_collection_install_test'));
|
||||
$this->installConfig(array('config_collection_install_test'));
|
||||
$this->enableModules(['config_collection_install_test']);
|
||||
$this->installConfig(['config_collection_install_test']);
|
||||
/** @var \Drupal\Core\Config\StorageInterface $active_storage */
|
||||
$active_storage = \Drupal::service('config.storage');
|
||||
$this->assertEqual($collections, $active_storage->getAllCollectionNames());
|
||||
|
|
@ -140,20 +140,20 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
// is not enabled.
|
||||
$this->assertEqual($collections, $active_storage->getAllCollectionNames());
|
||||
// Enable the 'config_test' module and try again.
|
||||
$this->enableModules(array('config_test'));
|
||||
$this->enableModules(['config_test']);
|
||||
\Drupal::service('config.installer')->installCollectionDefaultConfig('entity');
|
||||
$collections[] = 'entity';
|
||||
$this->assertEqual($collections, $active_storage->getAllCollectionNames());
|
||||
$collection_storage = $active_storage->createCollection('entity');
|
||||
$data = $collection_storage->read('config_test.dynamic.dotted.default');
|
||||
$this->assertIdentical(array('label' => 'entity'), $data);
|
||||
$this->assertIdentical(['label' => 'entity'], $data);
|
||||
|
||||
// Test that the config manager uninstalls configuration from collections
|
||||
// as expected.
|
||||
\Drupal::service('config.manager')->uninstall('module', 'config_collection_install_test');
|
||||
$this->assertEqual(array('entity'), $active_storage->getAllCollectionNames());
|
||||
$this->assertEqual(['entity'], $active_storage->getAllCollectionNames());
|
||||
\Drupal::service('config.manager')->uninstall('module', 'config_test');
|
||||
$this->assertEqual(array(), $active_storage->getAllCollectionNames());
|
||||
$this->assertEqual([], $active_storage->getAllCollectionNames());
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -165,12 +165,12 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
* using simple configuration.
|
||||
*/
|
||||
public function testCollectionInstallationCollectionConfigEntity() {
|
||||
$collections = array(
|
||||
$collections = [
|
||||
'entity',
|
||||
);
|
||||
];
|
||||
\Drupal::state()->set('config_collection_install_test.collection_names', $collections);
|
||||
// Install the test module.
|
||||
$this->installModules(array('config_test', 'config_collection_install_test'));
|
||||
$this->installModules(['config_test', 'config_collection_install_test']);
|
||||
/** @var \Drupal\Core\Config\StorageInterface $active_storage */
|
||||
$active_storage = \Drupal::service('config.storage');
|
||||
$this->assertEqual($collections, $active_storage->getAllCollectionNames());
|
||||
|
|
@ -185,7 +185,7 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
$data = $active_storage->read($name);
|
||||
$this->assertTrue(isset($data['uuid']));
|
||||
$data = $collection_storage->read($name);
|
||||
$this->assertIdentical(array('label' => 'entity'), $data);
|
||||
$this->assertIdentical(['label' => 'entity'], $data);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -199,8 +199,18 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
}
|
||||
catch (UnmetDependenciesException $e) {
|
||||
$this->assertEqual($e->getExtension(), 'config_install_dependency_test');
|
||||
$this->assertEqual($e->getConfigObjects(), ['config_other_module_config_test.weird_simple_config', 'config_test.dynamic.other_module_test_with_dependency']);
|
||||
$this->assertEqual($e->getMessage(), 'Configuration objects (config_other_module_config_test.weird_simple_config, config_test.dynamic.other_module_test_with_dependency) provided by config_install_dependency_test have unmet dependencies');
|
||||
$this->assertEqual($e->getConfigObjects(), ['config_test.dynamic.other_module_test_with_dependency' => ['config_other_module_config_test', 'config_test.dynamic.dotted.english']]);
|
||||
$this->assertEqual($e->getMessage(), 'Configuration objects provided by <em class="placeholder">config_install_dependency_test</em> have unmet dependencies: <em class="placeholder">config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test, config_test.dynamic.dotted.english)</em>');
|
||||
}
|
||||
$this->installModules(['config_test_language']);
|
||||
try {
|
||||
$this->installModules(['config_install_dependency_test']);
|
||||
$this->fail('Expected UnmetDependenciesException not thrown.');
|
||||
}
|
||||
catch (UnmetDependenciesException $e) {
|
||||
$this->assertEqual($e->getExtension(), 'config_install_dependency_test');
|
||||
$this->assertEqual($e->getConfigObjects(), ['config_test.dynamic.other_module_test_with_dependency' => ['config_other_module_config_test']]);
|
||||
$this->assertEqual($e->getMessage(), 'Configuration objects provided by <em class="placeholder">config_install_dependency_test</em> have unmet dependencies: <em class="placeholder">config_test.dynamic.other_module_test_with_dependency (config_other_module_config_test)</em>');
|
||||
}
|
||||
$this->installModules(['config_other_module_config_test']);
|
||||
$this->installModules(['config_install_dependency_test']);
|
||||
|
|
@ -214,7 +224,7 @@ class ConfigInstallTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests imported configuration entities with and without language information.
|
||||
*/
|
||||
function testLanguage() {
|
||||
public function testLanguage() {
|
||||
$this->installModules(['config_test_language']);
|
||||
// Test imported configuration with implicit language code.
|
||||
$storage = new InstallStorage();
|
||||
|
|
|
|||
|
|
@ -17,20 +17,20 @@ class ConfigLanguageOverrideTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('user', 'language', 'config_test', 'system', 'field');
|
||||
public static $modules = ['user', 'language', 'config_test', 'system', 'field'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests locale override based on language.
|
||||
*/
|
||||
function testConfigLanguageOverride() {
|
||||
public function testConfigLanguageOverride() {
|
||||
// The language module implements a config factory override object that
|
||||
// overrides configuration when the Language module is enabled. This test ensures that
|
||||
// English overrides work.
|
||||
|
|
@ -68,40 +68,40 @@ class ConfigLanguageOverrideTest extends KernelTestBase {
|
|||
// Test how overrides react to base configuration changes. Set up some base
|
||||
// values.
|
||||
\Drupal::configFactory()->getEditable('config_test.foo')
|
||||
->set('value', array('key' => 'original'))
|
||||
->set('value', ['key' => 'original'])
|
||||
->set('label', 'Original')
|
||||
->save();
|
||||
\Drupal::languageManager()
|
||||
->getLanguageConfigOverride('de', 'config_test.foo')
|
||||
->set('value', array('key' => 'override'))
|
||||
->set('value', ['key' => 'override'])
|
||||
->set('label', 'Override')
|
||||
->save();
|
||||
\Drupal::languageManager()
|
||||
->getLanguageConfigOverride('fr', 'config_test.foo')
|
||||
->set('value', array('key' => 'override'))
|
||||
->set('value', ['key' => 'override'])
|
||||
->save();
|
||||
\Drupal::configFactory()->clearStaticCache();
|
||||
$config = \Drupal::config('config_test.foo');
|
||||
$this->assertIdentical($config->get('value'), array('key' => 'override'));
|
||||
$this->assertIdentical($config->get('value'), ['key' => 'override']);
|
||||
|
||||
// Ensure renaming the config will rename the override.
|
||||
\Drupal::languageManager()->setConfigOverrideLanguage(\Drupal::languageManager()->getLanguage('en'));
|
||||
\Drupal::configFactory()->rename('config_test.foo', 'config_test.bar');
|
||||
$config = \Drupal::config('config_test.bar');
|
||||
$this->assertEqual($config->get('value'), array('key' => 'original'));
|
||||
$this->assertEqual($config->get('value'), ['key' => 'original']);
|
||||
$override = \Drupal::languageManager()->getLanguageConfigOverride('de', 'config_test.foo');
|
||||
$this->assertTrue($override->isNew());
|
||||
$this->assertEqual($override->get('value'), NULL);
|
||||
$override = \Drupal::languageManager()->getLanguageConfigOverride('de', 'config_test.bar');
|
||||
$this->assertFalse($override->isNew());
|
||||
$this->assertEqual($override->get('value'), array('key' => 'override'));
|
||||
$this->assertEqual($override->get('value'), ['key' => 'override']);
|
||||
$override = \Drupal::languageManager()->getLanguageConfigOverride('fr', 'config_test.bar');
|
||||
$this->assertFalse($override->isNew());
|
||||
$this->assertEqual($override->get('value'), array('key' => 'override'));
|
||||
$this->assertEqual($override->get('value'), ['key' => 'override']);
|
||||
|
||||
// Ensure changing data in the config will update the overrides.
|
||||
$config = \Drupal::configFactory()->getEditable('config_test.bar')->clear('value.key')->save();
|
||||
$this->assertEqual($config->get('value'), array());
|
||||
$this->assertEqual($config->get('value'), []);
|
||||
$override = \Drupal::languageManager()->getLanguageConfigOverride('de', 'config_test.bar');
|
||||
$this->assertFalse($override->isNew());
|
||||
$this->assertEqual($override->get('value'), NULL);
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class ConfigModuleOverridesTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'config', 'config_override_test');
|
||||
public static $modules = ['system', 'config', 'config_override_test'];
|
||||
|
||||
public function testSimpleModuleOverrides() {
|
||||
$GLOBALS['config_test_run_module_overrides'] = TRUE;
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class ConfigOverrideTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'config_test');
|
||||
public static $modules = ['system', 'config_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
|
@ -26,12 +26,12 @@ class ConfigOverrideTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests configuration override.
|
||||
*/
|
||||
function testConfOverride() {
|
||||
$expected_original_data = array(
|
||||
public function testConfOverride() {
|
||||
$expected_original_data = [
|
||||
'foo' => 'bar',
|
||||
'baz' => NULL,
|
||||
'404' => 'herp',
|
||||
);
|
||||
];
|
||||
|
||||
// Set globals before installing to prove that the installed file does not
|
||||
// contain these values.
|
||||
|
|
@ -40,7 +40,7 @@ class ConfigOverrideTest extends KernelTestBase {
|
|||
$overrides['config_test.system']['404'] = 'derp';
|
||||
$GLOBALS['config'] = $overrides;
|
||||
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
|
||||
// Verify that the original configuration data exists. Have to read storage
|
||||
// directly otherwise overrides will apply.
|
||||
|
|
@ -90,10 +90,10 @@ class ConfigOverrideTest extends KernelTestBase {
|
|||
|
||||
// Write file to sync.
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$expected_new_data = array(
|
||||
$expected_new_data = [
|
||||
'foo' => 'barbar',
|
||||
'404' => 'herpderp',
|
||||
);
|
||||
];
|
||||
$sync->write('config_test.system', $expected_new_data);
|
||||
|
||||
// Import changed data from sync to active.
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ class ConfigOverridesPriorityTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'config', 'config_override_test', 'language');
|
||||
public static $modules = ['system', 'config', 'config_override_test', 'language'];
|
||||
|
||||
public function testOverridePriorities() {
|
||||
$GLOBALS['config_test_run_module_overrides'] = FALSE;
|
||||
|
|
@ -50,10 +50,10 @@ class ConfigOverridesPriorityTest extends KernelTestBase {
|
|||
$this->assertEqual(50, $config_factory->get('system.site')->get('weight_select_max'));
|
||||
|
||||
// Override using language.
|
||||
$language = new Language(array(
|
||||
$language = new Language([
|
||||
'name' => 'French',
|
||||
'id' => 'fr',
|
||||
));
|
||||
]);
|
||||
\Drupal::languageManager()->setConfigOverrideLanguage($language);
|
||||
\Drupal::languageManager()
|
||||
->getLanguageConfigOverride($language->getId(), 'system.site')
|
||||
|
|
|
|||
|
|
@ -5,6 +5,10 @@ namespace Drupal\KernelTests\Core\Config;
|
|||
use Drupal\Core\Config\FileStorage;
|
||||
use Drupal\Core\Config\InstallStorage;
|
||||
use Drupal\Core\Config\Schema\ConfigSchemaAlterException;
|
||||
use Drupal\Core\Config\Schema\Ignore;
|
||||
use Drupal\Core\Config\Schema\Mapping;
|
||||
use Drupal\Core\Config\Schema\Undefined;
|
||||
use Drupal\Core\TypedData\Plugin\DataType\StringData;
|
||||
use Drupal\Core\TypedData\Type\IntegerInterface;
|
||||
use Drupal\Core\TypedData\Type\StringInterface;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
|
@ -21,26 +25,26 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'language', 'field', 'image', 'config_test', 'config_schema_test');
|
||||
public static $modules = ['system', 'language', 'field', 'image', 'config_test', 'config_schema_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(array('system', 'image', 'config_schema_test'));
|
||||
$this->installConfig(['system', 'image', 'config_schema_test']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the basic metadata retrieval layer.
|
||||
*/
|
||||
function testSchemaMapping() {
|
||||
public function testSchemaMapping() {
|
||||
// Nonexistent configuration key will have Undefined as metadata.
|
||||
$this->assertIdentical(FALSE, \Drupal::service('config.typed')->hasConfigSchema('config_schema_test.no_such_key'));
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('config_schema_test.no_such_key');
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Undefined';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Undefined';
|
||||
$expected['class'] = Undefined::class;
|
||||
$expected['type'] = 'undefined';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
|
||||
$this->assertEqual($definition, $expected, 'Retrieved the right metadata for nonexistent configuration.');
|
||||
|
|
@ -53,14 +57,14 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
// Configuration file with only some schema.
|
||||
$this->assertIdentical(TRUE, \Drupal::service('config.typed')->hasConfigSchema('config_schema_test.someschema'));
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('config_schema_test.someschema');
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Schema test data';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['mapping']['langcode']['type'] = 'string';
|
||||
$expected['mapping']['langcode']['label'] = 'Language code';
|
||||
$expected['mapping']['_core']['type'] = '_core_config_info';
|
||||
$expected['mapping']['testitem'] = array('label' => 'Test item');
|
||||
$expected['mapping']['testlist'] = array('label' => 'Test list');
|
||||
$expected['mapping']['testitem'] = ['label' => 'Test item'];
|
||||
$expected['mapping']['testlist'] = ['label' => 'Test list'];
|
||||
$expected['type'] = 'config_schema_test.someschema';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$this->assertEqual($definition, $expected, 'Retrieved the right metadata for configuration with only some schema.');
|
||||
|
|
@ -68,40 +72,40 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
// Check type detection on elements with undefined types.
|
||||
$config = \Drupal::service('config.typed')->get('config_schema_test.someschema');
|
||||
$definition = $config->get('testitem')->getDataDefinition()->toArray();
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Test item';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Undefined';
|
||||
$expected['class'] = Undefined::class;
|
||||
$expected['type'] = 'undefined';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
|
||||
$this->assertEqual($definition, $expected, 'Automatic type detected for a scalar is undefined.');
|
||||
$definition = $config->get('testlist')->getDataDefinition()->toArray();
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Test list';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Undefined';
|
||||
$expected['class'] = Undefined::class;
|
||||
$expected['type'] = 'undefined';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
|
||||
$this->assertEqual($definition, $expected, 'Automatic type detected for a list is undefined.');
|
||||
$definition = $config->get('testnoschema')->getDataDefinition()->toArray();
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Undefined';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Undefined';
|
||||
$expected['class'] = Undefined::class;
|
||||
$expected['type'] = 'undefined';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
|
||||
$this->assertEqual($definition, $expected, 'Automatic type detected for an undefined integer is undefined.');
|
||||
|
||||
// Simple case, straight metadata.
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('system.maintenance');
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Maintenance mode';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['mapping']['message'] = array(
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['mapping']['message'] = [
|
||||
'label' => 'Message to display when in maintenance mode',
|
||||
'type' => 'text',
|
||||
);
|
||||
$expected['mapping']['langcode'] = array(
|
||||
];
|
||||
$expected['mapping']['langcode'] = [
|
||||
'label' => 'Language code',
|
||||
'type' => 'string',
|
||||
);
|
||||
];
|
||||
$expected['mapping']['_core']['type'] = '_core_config_info';
|
||||
$expected['type'] = 'system.maintenance';
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
|
|
@ -109,41 +113,41 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
|
||||
// Mixed schema with ignore elements.
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('config_schema_test.ignore');
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Ignore test';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$expected['mapping']['langcode'] = array(
|
||||
$expected['mapping']['langcode'] = [
|
||||
'type' => 'string',
|
||||
'label' => 'Language code',
|
||||
);
|
||||
];
|
||||
$expected['mapping']['_core']['type'] = '_core_config_info';
|
||||
$expected['mapping']['label'] = array(
|
||||
$expected['mapping']['label'] = [
|
||||
'label' => 'Label',
|
||||
'type' => 'label',
|
||||
);
|
||||
$expected['mapping']['irrelevant'] = array(
|
||||
];
|
||||
$expected['mapping']['irrelevant'] = [
|
||||
'label' => 'Irrelevant',
|
||||
'type' => 'ignore',
|
||||
);
|
||||
$expected['mapping']['indescribable'] = array(
|
||||
];
|
||||
$expected['mapping']['indescribable'] = [
|
||||
'label' => 'Indescribable',
|
||||
'type' => 'ignore',
|
||||
);
|
||||
$expected['mapping']['weight'] = array(
|
||||
];
|
||||
$expected['mapping']['weight'] = [
|
||||
'label' => 'Weight',
|
||||
'type' => 'integer',
|
||||
);
|
||||
];
|
||||
$expected['type'] = 'config_schema_test.ignore';
|
||||
|
||||
$this->assertEqual($definition, $expected);
|
||||
|
||||
// The ignore elements themselves.
|
||||
$definition = \Drupal::service('config.typed')->get('config_schema_test.ignore')->get('irrelevant')->getDataDefinition()->toArray();
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['type'] = 'ignore';
|
||||
$expected['label'] = 'Irrelevant';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Ignore';
|
||||
$expected['class'] = Ignore::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
|
||||
$this->assertEqual($definition, $expected);
|
||||
$definition = \Drupal::service('config.typed')->get('config_schema_test.ignore')->get('indescribable')->getDataDefinition()->toArray();
|
||||
|
|
@ -152,9 +156,9 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
|
||||
// More complex case, generic type. Metadata for image style.
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('image.style.large');
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Image style';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$expected['mapping']['name']['type'] = 'string';
|
||||
$expected['mapping']['uuid']['type'] = 'string';
|
||||
|
|
@ -185,9 +189,9 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
// More complex, type based on a complex one.
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('image.effect.image_scale');
|
||||
// This should be the schema for image.effect.image_scale.
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Image scale';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$expected['mapping']['width']['type'] = 'integer';
|
||||
$expected['mapping']['width']['label'] = 'Width';
|
||||
|
|
@ -211,10 +215,10 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
$a = \Drupal::config('config_test.dynamic.third_party');
|
||||
$test = \Drupal::service('config.typed')->get('config_test.dynamic.third_party')->get('third_party_settings.config_schema_test');
|
||||
$definition = $test->getDataDefinition()->toArray();
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['type'] = 'config_test.dynamic.*.third_party.config_schema_test';
|
||||
$expected['label'] = 'Mapping';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$expected['mapping'] = [
|
||||
'integer' => ['type' => 'integer'],
|
||||
|
|
@ -225,9 +229,9 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
// More complex, several level deep test.
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('config_schema_test.someschema.somemodule.section_one.subsection');
|
||||
// This should be the schema of config_schema_test.someschema.somemodule.*.*.
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Schema multiple filesystem marker test';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['mapping']['langcode']['type'] = 'string';
|
||||
$expected['mapping']['langcode']['label'] = 'Language code';
|
||||
$expected['mapping']['_core']['type'] = '_core_config_info';
|
||||
|
|
@ -248,47 +252,47 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests metadata retrieval with several levels of %parent indirection.
|
||||
*/
|
||||
function testSchemaMappingWithParents() {
|
||||
public function testSchemaMappingWithParents() {
|
||||
$config_data = \Drupal::service('config.typed')->get('config_schema_test.someschema.with_parents');
|
||||
|
||||
// Test fetching parent one level up.
|
||||
$entry = $config_data->get('one_level');
|
||||
$definition = $entry->get('testitem')->getDataDefinition()->toArray();
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'type' => 'config_schema_test.someschema.with_parents.key_1',
|
||||
'label' => 'Test item nested one level',
|
||||
'class' => '\Drupal\Core\TypedData\Plugin\DataType\StringData',
|
||||
'class' => StringData::class,
|
||||
'definition_class' => '\Drupal\Core\TypedData\DataDefinition',
|
||||
);
|
||||
];
|
||||
$this->assertEqual($definition, $expected);
|
||||
|
||||
// Test fetching parent two levels up.
|
||||
$entry = $config_data->get('two_levels');
|
||||
$definition = $entry->get('wrapper')->get('testitem')->getDataDefinition()->toArray();
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'type' => 'config_schema_test.someschema.with_parents.key_2',
|
||||
'label' => 'Test item nested two levels',
|
||||
'class' => '\Drupal\Core\TypedData\Plugin\DataType\StringData',
|
||||
'class' => StringData::class,
|
||||
'definition_class' => '\Drupal\Core\TypedData\DataDefinition',
|
||||
);
|
||||
];
|
||||
$this->assertEqual($definition, $expected);
|
||||
|
||||
// Test fetching parent three levels up.
|
||||
$entry = $config_data->get('three_levels');
|
||||
$definition = $entry->get('wrapper_1')->get('wrapper_2')->get('testitem')->getDataDefinition()->toArray();
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'type' => 'config_schema_test.someschema.with_parents.key_3',
|
||||
'label' => 'Test item nested three levels',
|
||||
'class' => '\Drupal\Core\TypedData\Plugin\DataType\StringData',
|
||||
'class' => StringData::class,
|
||||
'definition_class' => '\Drupal\Core\TypedData\DataDefinition',
|
||||
);
|
||||
];
|
||||
$this->assertEqual($definition, $expected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests metadata applied to configuration objects.
|
||||
*/
|
||||
function testSchemaData() {
|
||||
public function testSchemaData() {
|
||||
// Try a simple property.
|
||||
$meta = \Drupal::service('config.typed')->get('system.site');
|
||||
$property = $meta->get('page')->get('front');
|
||||
|
|
@ -324,7 +328,7 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
* Test configuration value data type enforcement using schemas.
|
||||
*/
|
||||
public function testConfigSaveWithSchema() {
|
||||
$untyped_values = array(
|
||||
$untyped_values = [
|
||||
'string' => 1,
|
||||
'empty_string' => '',
|
||||
'null_string' => NULL,
|
||||
|
|
@ -333,22 +337,22 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
'boolean' => 1,
|
||||
// If the config schema doesn't have a type it shouldn't be casted.
|
||||
'no_type' => 1,
|
||||
'mapping' => array(
|
||||
'mapping' => [
|
||||
'string' => 1
|
||||
),
|
||||
],
|
||||
'float' => '3.14',
|
||||
'null_float' => '',
|
||||
'sequence' => array (1, 0, 1),
|
||||
'sequence_bc' => array(1, 0, 1),
|
||||
'sequence' => [1, 0, 1],
|
||||
'sequence_bc' => [1, 0, 1],
|
||||
// Not in schema and therefore should be left untouched.
|
||||
'not_present_in_schema' => TRUE,
|
||||
// Test a custom type.
|
||||
'config_schema_test_integer' => '1',
|
||||
'config_schema_test_integer_empty_string' => '',
|
||||
);
|
||||
];
|
||||
$untyped_to_typed = $untyped_values;
|
||||
|
||||
$typed_values = array(
|
||||
$typed_values = [
|
||||
'string' => '1',
|
||||
'empty_string' => '',
|
||||
'null_string' => NULL,
|
||||
|
|
@ -356,17 +360,17 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
'null_integer' => NULL,
|
||||
'boolean' => TRUE,
|
||||
'no_type' => 1,
|
||||
'mapping' => array(
|
||||
'mapping' => [
|
||||
'string' => '1'
|
||||
),
|
||||
],
|
||||
'float' => 3.14,
|
||||
'null_float' => NULL,
|
||||
'sequence' => array (TRUE, FALSE, TRUE),
|
||||
'sequence_bc' => array(TRUE, FALSE, TRUE),
|
||||
'sequence' => [TRUE, FALSE, TRUE],
|
||||
'sequence_bc' => [TRUE, FALSE, TRUE],
|
||||
'not_present_in_schema' => TRUE,
|
||||
'config_schema_test_integer' => 1,
|
||||
'config_schema_test_integer_empty_string' => NULL,
|
||||
);
|
||||
];
|
||||
|
||||
// Save config which has a schema that enforces types.
|
||||
$this->config('config_schema_test.schema_data_types')
|
||||
|
|
@ -394,12 +398,12 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests fallback to a greedy wildcard.
|
||||
*/
|
||||
function testSchemaFallback() {
|
||||
public function testSchemaFallback() {
|
||||
$definition = \Drupal::service('config.typed')->getDefinition('config_schema_test.wildcard_fallback.something');
|
||||
// This should be the schema of config_schema_test.wildcard_fallback.*.
|
||||
$expected = array();
|
||||
$expected = [];
|
||||
$expected['label'] = 'Schema wildcard fallback test';
|
||||
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
|
||||
$expected['class'] = Mapping::class;
|
||||
$expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
|
||||
$expected['mapping']['langcode']['type'] = 'string';
|
||||
$expected['mapping']['langcode']['label'] = 'Language code';
|
||||
|
|
@ -423,7 +427,7 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
*
|
||||
* @see \Drupal\Core\Config\TypedConfigManager::getFallbackName()
|
||||
*/
|
||||
function testColonsInSchemaTypeDetermination() {
|
||||
public function testColonsInSchemaTypeDetermination() {
|
||||
$tests = \Drupal::service('config.typed')->get('config_schema_test.plugin_types')->get('tests')->getElements();
|
||||
$definition = $tests[0]->getDataDefinition()->toArray();
|
||||
$this->assertEqual($definition['type'], 'test.plugin_types.boolean');
|
||||
|
|
@ -631,6 +635,27 @@ class ConfigSchemaTest extends KernelTestBase {
|
|||
$this->assertEqual($definition['type'], 'wrapping.test.double_brackets.*||test.double_brackets.cat.dog');
|
||||
$definition = $tests[1]->getDataDefinition()->toArray();
|
||||
$this->assertEqual($definition['type'], 'wrapping.test.double_brackets.*||test.double_brackets.turtle.horse');
|
||||
|
||||
$typed_values = [
|
||||
'tests' => [
|
||||
[
|
||||
'id' => 'cat:persion.dog',
|
||||
'foo' => 'cat',
|
||||
'bar' => 'dog',
|
||||
'breed' => 'persion',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
\Drupal::configFactory()->getEditable('wrapping.config_schema_test.other_double_brackets')
|
||||
->setData($typed_values)
|
||||
->save();
|
||||
$tests = \Drupal::service('config.typed')->get('wrapping.config_schema_test.other_double_brackets')->get('tests')->getElements();
|
||||
$definition = $tests[0]->getDataDefinition()->toArray();
|
||||
// Check that definition type is a merge of the expected types.
|
||||
$this->assertEqual($definition['type'], 'wrapping.test.other_double_brackets.*||test.double_brackets.cat:*.*');
|
||||
// Check that breed was inherited from parent definition.
|
||||
$this->assertEqual($definition['mapping']['breed'], ['type' => 'string']);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class ConfigSnapshotTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'system');
|
||||
public static $modules = ['config_test', 'system'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
|
|
@ -33,7 +33,7 @@ class ConfigSnapshotTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests config snapshot creation and updating.
|
||||
*/
|
||||
function testSnapshot() {
|
||||
public function testSnapshot() {
|
||||
$active = $this->container->get('config.storage');
|
||||
$sync = $this->container->get('config.storage.sync');
|
||||
$snapshot = $this->container->get('config.storage.snapshot');
|
||||
|
|
@ -50,7 +50,7 @@ class ConfigSnapshotTest extends KernelTestBase {
|
|||
$this->assertFalse($active_snapshot_comparer->createChangelist()->hasChanges());
|
||||
|
||||
// Install the default config.
|
||||
$this->installConfig(array('config_test'));
|
||||
$this->installConfig(['config_test']);
|
||||
// Although we have imported config this has not affected the snapshot.
|
||||
$this->assertTrue($active_snapshot_comparer->reset()->hasChanges());
|
||||
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
namespace Drupal\KernelTests\Core\Config;
|
||||
|
||||
use Drupal\config\Tests\SchemaCheckTestTrait;
|
||||
use Drupal\Tests\SchemaCheckTestTrait;
|
||||
use Drupal\config_test\TestInstallStorage;
|
||||
use Drupal\Core\Config\InstallStorage;
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
|
|
@ -23,7 +23,7 @@ class DefaultConfigTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'config_test');
|
||||
public static $modules = ['system', 'config_test'];
|
||||
|
||||
/**
|
||||
* Themes which provide default configuration and need enabling.
|
||||
|
|
|
|||
|
|
@ -27,14 +27,14 @@ class SchemaCheckTraitTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test', 'config_schema_test');
|
||||
public static $modules = ['config_test', 'config_schema_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(array('config_test', 'config_schema_test'));
|
||||
$this->installConfig(['config_test', 'config_schema_test']);
|
||||
$this->typedConfig = \Drupal::service('config.typed');
|
||||
}
|
||||
|
||||
|
|
@ -53,14 +53,14 @@ class SchemaCheckTraitTest extends KernelTestBase {
|
|||
|
||||
// Add a new key, a new array and overwrite boolean with array to test the
|
||||
// error messages.
|
||||
$config_data = array('new_key' => 'new_value', 'new_array' => array()) + $config_data;
|
||||
$config_data['boolean'] = array();
|
||||
$config_data = ['new_key' => 'new_value', 'new_array' => []] + $config_data;
|
||||
$config_data['boolean'] = [];
|
||||
$ret = $this->checkConfigSchema($this->typedConfig, 'config_test.types', $config_data);
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'config_test.types:new_key' => 'missing schema',
|
||||
'config_test.types:new_array' => 'missing schema',
|
||||
'config_test.types:boolean' => 'non-scalar value but not defined as an array (such as mapping or sequence)',
|
||||
);
|
||||
];
|
||||
$this->assertEqual($ret, $expected);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class SchemaConfigListenerTest extends KernelTestBase {
|
|||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ class CachedStorageTest extends ConfigStorageTestBase {
|
|||
$this->storage = new CachedStorage($this->fileStorage, \Drupal::service('cache.config'));
|
||||
$this->cache = \Drupal::service('cache_factory')->get('config');
|
||||
// ::listAll() verifications require other configuration data to exist.
|
||||
$this->storage->write('system.performance', array());
|
||||
$this->storage->write('system.performance', []);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
*
|
||||
* @todo Coverage: Trigger PDOExceptions / Database exceptions.
|
||||
*/
|
||||
function testCRUD() {
|
||||
public function testCRUD() {
|
||||
$name = 'config_test.storage';
|
||||
|
||||
// Checking whether a non-existing name exists returns FALSE.
|
||||
|
|
@ -44,7 +44,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
$this->assertIdentical($data, FALSE);
|
||||
|
||||
// Writing data returns TRUE and the data has been written.
|
||||
$data = array('foo' => 'bar');
|
||||
$data = ['foo' => 'bar'];
|
||||
$result = $this->storage->write($name, $data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
|
||||
|
|
@ -86,11 +86,11 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
|
||||
// Deleting all names with prefix deletes the appropriate data and returns
|
||||
// TRUE.
|
||||
$files = array(
|
||||
$files = [
|
||||
'config_test.test.biff',
|
||||
'config_test.test.bang',
|
||||
'config_test.test.pow',
|
||||
);
|
||||
];
|
||||
foreach ($files as $name) {
|
||||
$this->storage->write($name, $data);
|
||||
}
|
||||
|
|
@ -98,7 +98,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
$result = $this->storage->deleteAll('config_test.');
|
||||
$names = $this->storage->listAll('config_test.');
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($names, array());
|
||||
$this->assertIdentical($names, []);
|
||||
|
||||
// Test renaming an object that does not exist throws an exception.
|
||||
try {
|
||||
|
|
@ -127,7 +127,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
|
||||
// Write something to the valid storage to prove that the storages do not
|
||||
// pollute one another.
|
||||
$data = array('foo' => 'bar');
|
||||
$data = ['foo' => 'bar'];
|
||||
$result = $this->storage->write($name, $data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
|
||||
|
|
@ -150,20 +150,20 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
|
||||
// Listing on a non-existing storage bin returns an empty array.
|
||||
$result = $this->invalidStorage->listAll();
|
||||
$this->assertIdentical($result, array());
|
||||
$this->assertIdentical($result, []);
|
||||
// Writing to a non-existing storage bin creates the bin.
|
||||
$this->invalidStorage->write($name, array('foo' => 'bar'));
|
||||
$this->invalidStorage->write($name, ['foo' => 'bar']);
|
||||
$result = $this->invalidStorage->read($name);
|
||||
$this->assertIdentical($result, array('foo' => 'bar'));
|
||||
$this->assertIdentical($result, ['foo' => 'bar']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests storage writing and reading data preserving data type.
|
||||
*/
|
||||
function testDataTypes() {
|
||||
public function testDataTypes() {
|
||||
$name = 'config_test.types';
|
||||
$data = array(
|
||||
'array' => array(),
|
||||
$data = [
|
||||
'array' => [],
|
||||
'boolean' => TRUE,
|
||||
'exp' => 1.2e+34,
|
||||
'float' => 3.14159,
|
||||
|
|
@ -172,7 +172,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
'octal' => 0775,
|
||||
'string' => 'string',
|
||||
'string_int' => '1',
|
||||
);
|
||||
];
|
||||
|
||||
$result = $this->storage->write($name, $data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
|
|
@ -186,7 +186,7 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
*/
|
||||
public function testCollection() {
|
||||
$name = 'config_test.storage';
|
||||
$data = array('foo' => 'bar');
|
||||
$data = ['foo' => 'bar'];
|
||||
$result = $this->storage->write($name, $data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($data, $this->storage->read($name));
|
||||
|
|
@ -194,13 +194,13 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
// Create configuration in a new collection.
|
||||
$new_storage = $this->storage->createCollection('collection.sub.new');
|
||||
$this->assertFalse($new_storage->exists($name));
|
||||
$this->assertEqual(array(), $new_storage->listAll());
|
||||
$this->assertEqual([], $new_storage->listAll());
|
||||
$new_storage->write($name, $data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($data, $new_storage->read($name));
|
||||
$this->assertEqual(array($name), $new_storage->listAll());
|
||||
$this->assertEqual([$name], $new_storage->listAll());
|
||||
$this->assertTrue($new_storage->exists($name));
|
||||
$new_data = array('foo' => 'baz');
|
||||
$new_data = ['foo' => 'baz'];
|
||||
$new_storage->write($name, $new_data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($new_data, $new_storage->read($name));
|
||||
|
|
@ -208,11 +208,11 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
// Create configuration in another collection.
|
||||
$another_storage = $this->storage->createCollection('collection.sub.another');
|
||||
$this->assertFalse($another_storage->exists($name));
|
||||
$this->assertEqual(array(), $another_storage->listAll());
|
||||
$this->assertEqual([], $another_storage->listAll());
|
||||
$another_storage->write($name, $new_data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($new_data, $another_storage->read($name));
|
||||
$this->assertEqual(array($name), $another_storage->listAll());
|
||||
$this->assertEqual([$name], $another_storage->listAll());
|
||||
$this->assertTrue($another_storage->exists($name));
|
||||
|
||||
// Create configuration in yet another collection.
|
||||
|
|
@ -226,33 +226,33 @@ abstract class ConfigStorageTestBase extends KernelTestBase {
|
|||
$this->assertIdentical($data, $this->storage->read($name));
|
||||
|
||||
// Check that the getAllCollectionNames() method works.
|
||||
$this->assertIdentical(array('alternate', 'collection.sub.another', 'collection.sub.new'), $this->storage->getAllCollectionNames());
|
||||
$this->assertIdentical(['alternate', 'collection.sub.another', 'collection.sub.new'], $this->storage->getAllCollectionNames());
|
||||
|
||||
// Check that the collections are removed when they are empty.
|
||||
$alt_storage->delete($name);
|
||||
$this->assertIdentical(array('collection.sub.another', 'collection.sub.new'), $this->storage->getAllCollectionNames());
|
||||
$this->assertIdentical(['collection.sub.another', 'collection.sub.new'], $this->storage->getAllCollectionNames());
|
||||
|
||||
// Create configuration in collection called 'collection'. This ensures that
|
||||
// FileStorage's collection storage works regardless of its use of
|
||||
// subdirectories.
|
||||
$parent_storage = $this->storage->createCollection('collection');
|
||||
$this->assertFalse($parent_storage->exists($name));
|
||||
$this->assertEqual(array(), $parent_storage->listAll());
|
||||
$this->assertEqual([], $parent_storage->listAll());
|
||||
$parent_storage->write($name, $new_data);
|
||||
$this->assertIdentical($result, TRUE);
|
||||
$this->assertIdentical($new_data, $parent_storage->read($name));
|
||||
$this->assertEqual(array($name), $parent_storage->listAll());
|
||||
$this->assertEqual([$name], $parent_storage->listAll());
|
||||
$this->assertTrue($parent_storage->exists($name));
|
||||
$this->assertIdentical(array('collection', 'collection.sub.another', 'collection.sub.new'), $this->storage->getAllCollectionNames());
|
||||
$this->assertIdentical(['collection', 'collection.sub.another', 'collection.sub.new'], $this->storage->getAllCollectionNames());
|
||||
$parent_storage->deleteAll();
|
||||
$this->assertIdentical(array('collection.sub.another', 'collection.sub.new'), $this->storage->getAllCollectionNames());
|
||||
$this->assertIdentical(['collection.sub.another', 'collection.sub.new'], $this->storage->getAllCollectionNames());
|
||||
|
||||
// Check that the having an empty collection-less storage does not break
|
||||
// anything. Before deleting check that the previous delete did not affect
|
||||
// data in another collection.
|
||||
$this->assertIdentical($data, $this->storage->read($name));
|
||||
$this->storage->delete($name);
|
||||
$this->assertIdentical(array('collection.sub.another', 'collection.sub.new'), $this->storage->getAllCollectionNames());
|
||||
$this->assertIdentical(['collection.sub.another', 'collection.sub.new'], $this->storage->getAllCollectionNames());
|
||||
}
|
||||
|
||||
abstract protected function read($name);
|
||||
|
|
|
|||
|
|
@ -21,20 +21,20 @@ class DatabaseStorageTest extends ConfigStorageTestBase {
|
|||
$this->invalidStorage = new DatabaseStorage($this->container->get('database'), 'invalid');
|
||||
|
||||
// ::listAll() verifications require other configuration data to exist.
|
||||
$this->storage->write('system.performance', array());
|
||||
$this->storage->write('system.performance', []);
|
||||
}
|
||||
|
||||
protected function read($name) {
|
||||
$data = db_query('SELECT data FROM {config} WHERE name = :name', array(':name' => $name))->fetchField();
|
||||
$data = db_query('SELECT data FROM {config} WHERE name = :name', [':name' => $name])->fetchField();
|
||||
return unserialize($data);
|
||||
}
|
||||
|
||||
protected function insert($name, $data) {
|
||||
db_insert('config')->fields(array('name' => $name, 'data' => $data))->execute();
|
||||
db_insert('config')->fields(['name' => $name, 'data' => $data])->execute();
|
||||
}
|
||||
|
||||
protected function update($name, $data) {
|
||||
db_update('config')->fields(array('data' => $data))->condition('name', $name)->execute();
|
||||
db_update('config')->fields(['data' => $data])->condition('name', $name)->execute();
|
||||
}
|
||||
|
||||
protected function delete($name) {
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ class FileStorageTest extends ConfigStorageTestBase {
|
|||
|
||||
// FileStorage::listAll() requires other configuration data to exist.
|
||||
$this->storage->write('system.performance', $this->config('system.performance')->get());
|
||||
$this->storage->write('core.extension', array('module' => array()));
|
||||
$this->storage->write('core.extension', ['module' => []]);
|
||||
}
|
||||
|
||||
protected function read($name) {
|
||||
|
|
@ -57,10 +57,10 @@ class FileStorageTest extends ConfigStorageTestBase {
|
|||
* Tests the FileStorage::listAll method with a relative and absolute path.
|
||||
*/
|
||||
public function testlistAll() {
|
||||
$expected_files = array(
|
||||
$expected_files = [
|
||||
'core.extension',
|
||||
'system.performance',
|
||||
);
|
||||
];
|
||||
|
||||
$config_files = $this->storage->listAll();
|
||||
$this->assertIdentical($config_files, $expected_files, 'Relative path, two config files found.');
|
||||
|
|
|
|||
|
|
@ -19,8 +19,8 @@ class StorageReplaceDataWrapperTest extends ConfigStorageTestBase {
|
|||
parent::setUp();
|
||||
$this->storage = new StorageReplaceDataWrapper($this->container->get('config.storage'));
|
||||
// ::listAll() verifications require other configuration data to exist.
|
||||
$this->storage->write('system.performance', array());
|
||||
$this->storage->replaceData('system.performance', array('foo' => 'bar'));
|
||||
$this->storage->write('system.performance', []);
|
||||
$this->storage->replaceData('system.performance', ['foo' => 'bar']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can do basic alters.
|
||||
*/
|
||||
function testSimpleAlter() {
|
||||
public function testSimpleAlter() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -27,7 +27,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can alter the joins on a query.
|
||||
*/
|
||||
function testAlterWithJoin() {
|
||||
public function testAlterWithJoin() {
|
||||
$query = db_select('test_task');
|
||||
$tid_field = $query->addField('test_task', 'tid');
|
||||
$task_field = $query->addField('test_task', 'task');
|
||||
|
|
@ -51,7 +51,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can alter a query's conditionals.
|
||||
*/
|
||||
function testAlterChangeConditional() {
|
||||
public function testAlterChangeConditional() {
|
||||
$query = db_select('test_task');
|
||||
$tid_field = $query->addField('test_task', 'tid');
|
||||
$pid_field = $query->addField('test_task', 'pid');
|
||||
|
|
@ -76,7 +76,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can alter the fields of a query.
|
||||
*/
|
||||
function testAlterChangeFields() {
|
||||
public function testAlterChangeFields() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -91,7 +91,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can alter expressions in the query.
|
||||
*/
|
||||
function testAlterExpression() {
|
||||
public function testAlterExpression() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addExpression("age*2", 'double_age');
|
||||
|
|
@ -111,7 +111,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
*
|
||||
* This also tests hook_query_TAG_alter().
|
||||
*/
|
||||
function testAlterRemoveRange() {
|
||||
public function testAlterRemoveRange() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -126,7 +126,7 @@ class AlterTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can do basic alters on subqueries.
|
||||
*/
|
||||
function testSimpleAlterSubquery() {
|
||||
public function testSimpleAlterSubquery() {
|
||||
// Create a sub-query with an alter tag.
|
||||
$subquery = db_select('test', 'p');
|
||||
$subquery->addField('p', 'name');
|
||||
|
|
|
|||
|
|
@ -15,63 +15,63 @@ class BasicSyntaxTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests string concatenation.
|
||||
*/
|
||||
function testConcatLiterals() {
|
||||
$result = db_query('SELECT CONCAT(:a1, CONCAT(:a2, CONCAT(:a3, CONCAT(:a4, :a5))))', array(
|
||||
public function testConcatLiterals() {
|
||||
$result = db_query('SELECT CONCAT(:a1, CONCAT(:a2, CONCAT(:a3, CONCAT(:a4, :a5))))', [
|
||||
':a1' => 'This',
|
||||
':a2' => ' ',
|
||||
':a3' => 'is',
|
||||
':a4' => ' a ',
|
||||
':a5' => 'test.',
|
||||
));
|
||||
]);
|
||||
$this->assertIdentical($result->fetchField(), 'This is a test.', 'Basic CONCAT works.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests string concatenation with field values.
|
||||
*/
|
||||
function testConcatFields() {
|
||||
$result = db_query('SELECT CONCAT(:a1, CONCAT(name, CONCAT(:a2, CONCAT(age, :a3)))) FROM {test} WHERE age = :age', array(
|
||||
public function testConcatFields() {
|
||||
$result = db_query('SELECT CONCAT(:a1, CONCAT(name, CONCAT(:a2, CONCAT(age, :a3)))) FROM {test} WHERE age = :age', [
|
||||
':a1' => 'The age of ',
|
||||
':a2' => ' is ',
|
||||
':a3' => '.',
|
||||
':age' => 25,
|
||||
));
|
||||
]);
|
||||
$this->assertIdentical($result->fetchField(), 'The age of John is 25.', 'Field CONCAT works.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests string concatenation with separator.
|
||||
*/
|
||||
function testConcatWsLiterals() {
|
||||
$result = db_query("SELECT CONCAT_WS(', ', :a1, NULL, :a2, :a3, :a4)", array(
|
||||
public function testConcatWsLiterals() {
|
||||
$result = db_query("SELECT CONCAT_WS(', ', :a1, NULL, :a2, :a3, :a4)", [
|
||||
':a1' => 'Hello',
|
||||
':a2' => NULL,
|
||||
':a3' => '',
|
||||
':a4' => 'world.',
|
||||
));
|
||||
]);
|
||||
$this->assertIdentical($result->fetchField(), 'Hello, , world.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests string concatenation with separator, with field values.
|
||||
*/
|
||||
function testConcatWsFields() {
|
||||
$result = db_query("SELECT CONCAT_WS('-', :a1, name, :a2, age) FROM {test} WHERE age = :age", array(
|
||||
public function testConcatWsFields() {
|
||||
$result = db_query("SELECT CONCAT_WS('-', :a1, name, :a2, age) FROM {test} WHERE age = :age", [
|
||||
':a1' => 'name',
|
||||
':a2' => 'age',
|
||||
':age' => 25,
|
||||
));
|
||||
]);
|
||||
$this->assertIdentical($result->fetchField(), 'name-John-age-25');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests escaping of LIKE wildcards.
|
||||
*/
|
||||
function testLikeEscape() {
|
||||
public function testLikeEscape() {
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Ring_',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
// Match both "Ringo" and "Ring_".
|
||||
|
|
@ -93,15 +93,15 @@ class BasicSyntaxTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests a LIKE query containing a backslash.
|
||||
*/
|
||||
function testLikeBackslash() {
|
||||
public function testLikeBackslash() {
|
||||
db_insert('test')
|
||||
->fields(array('name'))
|
||||
->values(array(
|
||||
->fields(['name'])
|
||||
->values([
|
||||
'name' => 'abcde\f',
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'name' => 'abc%\_',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
// Match both rows using a LIKE expression with two wildcards and a verbatim
|
||||
|
|
|
|||
|
|
@ -11,20 +11,20 @@ class CaseSensitivityTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests BINARY collation in MySQL.
|
||||
*/
|
||||
function testCaseSensitiveInsert() {
|
||||
public function testCaseSensitiveInsert() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'john', // <- A record already exists with name 'John'.
|
||||
'age' => 2,
|
||||
'job' => 'Baby',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
$this->assertIdentical($num_records_before + 1, (int) $num_records_after, 'Record inserts correctly.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'john'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'john'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '2', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class ConnectionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that connections return appropriate connection objects.
|
||||
*/
|
||||
function testConnectionRouting() {
|
||||
public function testConnectionRouting() {
|
||||
// Clone the primary credentials to a replica connection.
|
||||
// Note this will result in two independent connection objects that happen
|
||||
// to point to the same place.
|
||||
|
|
@ -49,7 +49,7 @@ class ConnectionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that connections return appropriate connection objects.
|
||||
*/
|
||||
function testConnectionRoutingOverride() {
|
||||
public function testConnectionRoutingOverride() {
|
||||
// Clone the primary credentials to a replica connection.
|
||||
// Note this will result in two independent connection objects that happen
|
||||
// to point to the same place.
|
||||
|
|
@ -67,7 +67,7 @@ class ConnectionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests the closing of a database connection.
|
||||
*/
|
||||
function testConnectionClosing() {
|
||||
public function testConnectionClosing() {
|
||||
// Open the default target so we have an object to compare.
|
||||
$db1 = Database::getConnection('default', 'default');
|
||||
|
||||
|
|
@ -82,7 +82,7 @@ class ConnectionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests the connection options of the active database.
|
||||
*/
|
||||
function testConnectionOptions() {
|
||||
public function testConnectionOptions() {
|
||||
$connection_info = Database::getConnectionInfo('default');
|
||||
|
||||
// Be sure we're connected to the default database.
|
||||
|
|
@ -168,9 +168,9 @@ class ConnectionTest extends DatabaseTestBase {
|
|||
$stmt->execute();
|
||||
foreach ($stmt->fetchAllAssoc('word') as $word => $row) {
|
||||
$expected = '"' . $word . '"';
|
||||
$this->assertIdentical($db->escapeTable($word), $expected, format_string('The reserved word %word was correctly escaped when used as a table name.', array('%word' => $word)));
|
||||
$this->assertIdentical($db->escapeField($word), $expected, format_string('The reserved word %word was correctly escaped when used as a column name.', array('%word' => $word)));
|
||||
$this->assertIdentical($db->escapeAlias($word), $expected, format_string('The reserved word %word was correctly escaped when used as an alias.', array('%word' => $word)));
|
||||
$this->assertIdentical($db->escapeTable($word), $expected, format_string('The reserved word %word was correctly escaped when used as a table name.', ['%word' => $word]));
|
||||
$this->assertIdentical($db->escapeField($word), $expected, format_string('The reserved word %word was correctly escaped when used as a column name.', ['%word' => $word]));
|
||||
$this->assertIdentical($db->escapeAlias($word), $expected, format_string('The reserved word %word was correctly escaped when used as an alias.', ['%word' => $word]));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
*/
|
||||
protected function assertConnection($id) {
|
||||
$list = $this->monitor->query('SHOW PROCESSLIST')->fetchAllKeyed(0, 0);
|
||||
return $this->assertTrue(isset($list[$id]), format_string('Connection ID @id found.', array('@id' => $id)));
|
||||
return $this->assertTrue(isset($list[$id]), format_string('Connection ID @id found.', ['@id' => $id]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -86,7 +86,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
*/
|
||||
protected function assertNoConnection($id) {
|
||||
$list = $this->monitor->query('SHOW PROCESSLIST')->fetchAllKeyed(0, 0);
|
||||
return $this->assertFalse(isset($list[$id]), format_string('Connection ID @id not found.', array('@id' => $id)));
|
||||
return $this->assertFalse(isset($list[$id]), format_string('Connection ID @id not found.', ['@id' => $id]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -94,7 +94,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
*
|
||||
* @todo getConnectionID() executes a query.
|
||||
*/
|
||||
function testOpenClose() {
|
||||
public function testOpenClose() {
|
||||
if ($this->skipTest) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -118,7 +118,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests Database::closeConnection() with a query.
|
||||
*/
|
||||
function testOpenQueryClose() {
|
||||
public function testOpenQueryClose() {
|
||||
if ($this->skipTest) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -145,7 +145,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests Database::closeConnection() with a query and custom prefetch method.
|
||||
*/
|
||||
function testOpenQueryPrefetchClose() {
|
||||
public function testOpenQueryPrefetchClose() {
|
||||
if ($this->skipTest) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -172,7 +172,7 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests Database::closeConnection() with a select query.
|
||||
*/
|
||||
function testOpenSelectQueryClose() {
|
||||
public function testOpenSelectQueryClose() {
|
||||
if ($this->skipTest) {
|
||||
return;
|
||||
}
|
||||
|
|
@ -186,18 +186,18 @@ class ConnectionUnitTest extends KernelTestBase {
|
|||
|
||||
// Create a table.
|
||||
$name = 'foo';
|
||||
Database::getConnection($this->target, $this->key)->schema()->createTable($name, array(
|
||||
'fields' => array(
|
||||
'name' => array(
|
||||
Database::getConnection($this->target, $this->key)->schema()->createTable($name, [
|
||||
'fields' => [
|
||||
'name' => [
|
||||
'type' => 'varchar',
|
||||
'length' => 255,
|
||||
),
|
||||
),
|
||||
));
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
// Execute a query.
|
||||
Database::getConnection($this->target, $this->key)->select('foo', 'f')
|
||||
->fields('f', array('name'))
|
||||
->fields('f', ['name'])
|
||||
->execute()
|
||||
->fetchAll();
|
||||
|
||||
|
|
|
|||
|
|
@ -12,11 +12,11 @@ use Drupal\KernelTests\KernelTestBase;
|
|||
*/
|
||||
abstract class DatabaseTestBase extends KernelTestBase {
|
||||
|
||||
public static $modules = array('database_test');
|
||||
public static $modules = ['database_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installSchema('database_test', array(
|
||||
$this->installSchema('database_test', [
|
||||
'test',
|
||||
'test_people',
|
||||
'test_people_copy',
|
||||
|
|
@ -27,120 +27,120 @@ abstract class DatabaseTestBase extends KernelTestBase {
|
|||
'test_serialized',
|
||||
'test_special_columns',
|
||||
'TEST_UPPERCASE',
|
||||
));
|
||||
]);
|
||||
self::addSampleData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up tables for NULL handling.
|
||||
*/
|
||||
function ensureSampleDataNull() {
|
||||
public function ensureSampleDataNull() {
|
||||
db_insert('test_null')
|
||||
->fields(array('name', 'age'))
|
||||
->values(array(
|
||||
->fields(['name', 'age'])
|
||||
->values([
|
||||
'name' => 'Kermit',
|
||||
'age' => 25,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'name' => 'Fozzie',
|
||||
'age' => NULL,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'name' => 'Gonzo',
|
||||
'age' => 27,
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up our sample data.
|
||||
*/
|
||||
static function addSampleData() {
|
||||
public static function addSampleData() {
|
||||
// We need the IDs, so we can't use a multi-insert here.
|
||||
$john = db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'John',
|
||||
'age' => 25,
|
||||
'job' => 'Singer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$george = db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'George',
|
||||
'age' => 27,
|
||||
'job' => 'Singer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Ringo',
|
||||
'age' => 28,
|
||||
'job' => 'Drummer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$paul = db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Paul',
|
||||
'age' => 26,
|
||||
'job' => 'Songwriter',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
db_insert('test_people')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Meredith',
|
||||
'age' => 30,
|
||||
'job' => 'Speaker',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
db_insert('test_task')
|
||||
->fields(array('pid', 'task', 'priority'))
|
||||
->values(array(
|
||||
->fields(['pid', 'task', 'priority'])
|
||||
->values([
|
||||
'pid' => $john,
|
||||
'task' => 'eat',
|
||||
'priority' => 3,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $john,
|
||||
'task' => 'sleep',
|
||||
'priority' => 4,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $john,
|
||||
'task' => 'code',
|
||||
'priority' => 1,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $george,
|
||||
'task' => 'sing',
|
||||
'priority' => 2,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $george,
|
||||
'task' => 'sleep',
|
||||
'priority' => 2,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $paul,
|
||||
'task' => 'found new band',
|
||||
'priority' => 1,
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'pid' => $paul,
|
||||
'task' => 'perform at superbowl',
|
||||
'priority' => 3,
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
db_insert('test_special_columns')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'id' => 1,
|
||||
'offset' => 'Offset value 1',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,13 +20,13 @@ class DeleteTruncateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can use a subselect in a delete successfully.
|
||||
*/
|
||||
function testSubselectDelete() {
|
||||
public function testSubselectDelete() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
|
||||
$pid_to_delete = db_query("SELECT * FROM {test_task} WHERE task = 'sleep'")->fetchField();
|
||||
|
||||
$subquery = db_select('test', 't')
|
||||
->fields('t', array('id'))
|
||||
->condition('t.id', array($pid_to_delete), 'IN');
|
||||
->fields('t', ['id'])
|
||||
->condition('t.id', [$pid_to_delete], 'IN');
|
||||
$delete = db_delete('test_task')
|
||||
->condition('task', 'sleep')
|
||||
->condition('pid', $subquery, 'IN');
|
||||
|
|
@ -41,7 +41,7 @@ class DeleteTruncateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can delete a single record successfully.
|
||||
*/
|
||||
function testSimpleDelete() {
|
||||
public function testSimpleDelete() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
$num_deleted = db_delete('test')
|
||||
|
|
@ -56,7 +56,7 @@ class DeleteTruncateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can truncate a whole table successfully.
|
||||
*/
|
||||
function testTruncate() {
|
||||
public function testTruncate() {
|
||||
$num_records_before = db_query("SELECT COUNT(*) FROM {test}")->fetchField();
|
||||
$this->assertTrue($num_records_before > 0, 'The table is not empty.');
|
||||
|
||||
|
|
@ -69,7 +69,7 @@ class DeleteTruncateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can delete a single special column name record successfully.
|
||||
*/
|
||||
function testSpecialColumnDelete() {
|
||||
public function testSpecialColumnDelete() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_special_columns}')->fetchField();
|
||||
|
||||
$num_deleted = db_delete('test_special_columns')
|
||||
|
|
|
|||
|
|
@ -18,9 +18,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch a record properly in default object mode.
|
||||
*/
|
||||
function testQueryFetchDefault() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25));
|
||||
public function testQueryFetchDefault() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25]);
|
||||
$this->assertTrue($result instanceof StatementInterface, 'Result set is a Drupal statement object.');
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
|
|
@ -34,9 +34,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch a record to an object explicitly.
|
||||
*/
|
||||
function testQueryFetchObject() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => \PDO::FETCH_OBJ));
|
||||
public function testQueryFetchObject() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25], ['fetch' => \PDO::FETCH_OBJ]);
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
$this->assertTrue(is_object($record), 'Record is an object.');
|
||||
|
|
@ -49,9 +49,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch a record to an associative array explicitly.
|
||||
*/
|
||||
function testQueryFetchArray() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => \PDO::FETCH_ASSOC));
|
||||
public function testQueryFetchArray() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25], ['fetch' => \PDO::FETCH_ASSOC]);
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
if ($this->assertTrue(is_array($record), 'Record is an array.')) {
|
||||
|
|
@ -67,9 +67,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
*
|
||||
* @see \Drupal\system\Tests\Database\FakeRecord
|
||||
*/
|
||||
function testQueryFetchClass() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => 'Drupal\system\Tests\Database\FakeRecord'));
|
||||
public function testQueryFetchClass() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25], ['fetch' => 'Drupal\system\Tests\Database\FakeRecord']);
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
if ($this->assertTrue($record instanceof FakeRecord, 'Record is an object of class FakeRecord.')) {
|
||||
|
|
@ -83,9 +83,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch a record into an indexed array explicitly.
|
||||
*/
|
||||
function testQueryFetchNum() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => \PDO::FETCH_NUM));
|
||||
public function testQueryFetchNum() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25], ['fetch' => \PDO::FETCH_NUM]);
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
if ($this->assertTrue(is_array($record), 'Record is an array.')) {
|
||||
|
|
@ -99,9 +99,9 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch a record into a doubly-keyed array explicitly.
|
||||
*/
|
||||
function testQueryFetchBoth() {
|
||||
$records = array();
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 25), array('fetch' => \PDO::FETCH_BOTH));
|
||||
public function testQueryFetchBoth() {
|
||||
$records = [];
|
||||
$result = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 25], ['fetch' => \PDO::FETCH_BOTH]);
|
||||
foreach ($result as $record) {
|
||||
$records[] = $record;
|
||||
if ($this->assertTrue(is_array($record), 'Record is an array.')) {
|
||||
|
|
@ -129,12 +129,12 @@ class FetchTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can fetch an entire column of a result set at once.
|
||||
*/
|
||||
function testQueryFetchCol() {
|
||||
$result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
|
||||
public function testQueryFetchCol() {
|
||||
$result = db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25]);
|
||||
$column = $result->fetchCol();
|
||||
$this->assertIdentical(count($column), 3, 'fetchCol() returns the right number of records.');
|
||||
|
||||
$result = db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25));
|
||||
$result = db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25]);
|
||||
$i = 0;
|
||||
foreach ($result as $record) {
|
||||
$this->assertIdentical($record->name, $column[$i++], 'Column matches direct access.');
|
||||
|
|
|
|||
|
|
@ -14,20 +14,20 @@ class InsertDefaultsTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can run a query that uses default values for everything.
|
||||
*/
|
||||
function testDefaultInsert() {
|
||||
$query = db_insert('test')->useDefaults(array('job'));
|
||||
public function testDefaultInsert() {
|
||||
$query = db_insert('test')->useDefaults(['job']);
|
||||
$id = $query->execute();
|
||||
|
||||
$schema = drupal_get_module_schema('database_test', 'test');
|
||||
|
||||
$job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
|
||||
$job = db_query('SELECT job FROM {test} WHERE id = :id', [':id' => $id])->fetchField();
|
||||
$this->assertEqual($job, $schema['fields']['job']['default'], 'Default field value is set.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that no action will be preformed if no fields are specified.
|
||||
*/
|
||||
function testDefaultEmptyInsert() {
|
||||
public function testDefaultEmptyInsert() {
|
||||
$num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
try {
|
||||
|
|
@ -46,15 +46,15 @@ class InsertDefaultsTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can insert fields with values and defaults in the same query.
|
||||
*/
|
||||
function testDefaultInsertWithFields() {
|
||||
public function testDefaultInsertWithFields() {
|
||||
$query = db_insert('test')
|
||||
->fields(array('name' => 'Bob'))
|
||||
->useDefaults(array('job'));
|
||||
->fields(['name' => 'Bob'])
|
||||
->useDefaults(['job']);
|
||||
$id = $query->execute();
|
||||
|
||||
$schema = drupal_get_module_schema('database_test', 'test');
|
||||
|
||||
$job = db_query('SELECT job FROM {test} WHERE id = :id', array(':id' => $id))->fetchField();
|
||||
$job = db_query('SELECT job FROM {test} WHERE id = :id', [':id' => $id])->fetchField();
|
||||
$this->assertEqual($job, $schema['fields']['job']['default'], 'Default field value is set.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,27 +12,27 @@ class InsertLobTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can insert a single blob field successfully.
|
||||
*/
|
||||
function testInsertOneBlob() {
|
||||
public function testInsertOneBlob() {
|
||||
$data = "This is\000a test.";
|
||||
$this->assertTrue(strlen($data) === 15, 'Test data contains a NULL.');
|
||||
$id = db_insert('test_one_blob')
|
||||
->fields(array('blob1' => $data))
|
||||
->fields(['blob1' => $data])
|
||||
->execute();
|
||||
$r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === $data, format_string('Can insert a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
|
||||
$r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', [':id' => $id])->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === $data, format_string('Can insert a blob: id @id, @data.', ['@id' => $id, '@data' => serialize($r)]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can insert multiple blob fields in the same query.
|
||||
*/
|
||||
function testInsertMultipleBlob() {
|
||||
public function testInsertMultipleBlob() {
|
||||
$id = db_insert('test_two_blobs')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'blob1' => 'This is',
|
||||
'blob2' => 'a test',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
$r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
|
||||
$r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', [':id' => $id])->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === 'This is' && $r['blob2'] === 'a test', 'Can insert multiple blobs per row.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,14 +12,14 @@ class InsertTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests very basic insert functionality.
|
||||
*/
|
||||
function testSimpleInsert() {
|
||||
public function testSimpleInsert() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
$query = db_insert('test');
|
||||
$query->fields(array(
|
||||
$query->fields([
|
||||
'name' => 'Yoko',
|
||||
'age' => '29',
|
||||
));
|
||||
]);
|
||||
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 1, 'One record is queued for insertion.');
|
||||
|
|
@ -27,34 +27,34 @@ class InsertTest extends DatabaseTestBase {
|
|||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
$this->assertIdentical($num_records_before + 1, (int) $num_records_after, 'Record inserts correctly.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Yoko'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Yoko'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '29', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can insert multiple records in one query object.
|
||||
*/
|
||||
function testMultiInsert() {
|
||||
public function testMultiInsert() {
|
||||
$num_records_before = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
$query = db_insert('test');
|
||||
$query->fields(array(
|
||||
$query->fields([
|
||||
'name' => 'Larry',
|
||||
'age' => '30',
|
||||
));
|
||||
]);
|
||||
|
||||
// We should be able to specify values in any order if named.
|
||||
$query->values(array(
|
||||
$query->values([
|
||||
'age' => '31',
|
||||
'name' => 'Curly',
|
||||
));
|
||||
]);
|
||||
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 2, 'Two records are queued for insertion.');
|
||||
|
||||
// We should be able to say "use the field order".
|
||||
// This is not the recommended mechanism for most cases, but it should work.
|
||||
$query->values(array('Moe', '32'));
|
||||
$query->values(['Moe', '32']);
|
||||
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 3, 'Three records are queued for insertion.');
|
||||
|
|
@ -62,41 +62,41 @@ class InsertTest extends DatabaseTestBase {
|
|||
|
||||
$num_records_after = (int) db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
$this->assertIdentical($num_records_before + 3, $num_records_after, 'Record inserts correctly.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Larry'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Curly'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Moe'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that an insert object can be reused with new data after it executes.
|
||||
*/
|
||||
function testRepeatedInsert() {
|
||||
public function testRepeatedInsert() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
|
||||
$query = db_insert('test');
|
||||
|
||||
$query->fields(array(
|
||||
$query->fields([
|
||||
'name' => 'Larry',
|
||||
'age' => '30',
|
||||
));
|
||||
]);
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 1, 'One record is queued for insertion.');
|
||||
$query->execute(); // This should run the insert, but leave the fields intact.
|
||||
|
||||
// We should be able to specify values in any order if named.
|
||||
$query->values(array(
|
||||
$query->values([
|
||||
'age' => '31',
|
||||
'name' => 'Curly',
|
||||
));
|
||||
]);
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 1, 'One record is queued for insertion.');
|
||||
$query->execute();
|
||||
|
||||
// We should be able to say "use the field order".
|
||||
$query->values(array('Moe', '32'));
|
||||
$query->values(['Moe', '32']);
|
||||
|
||||
// Check how many records are queued for insertion.
|
||||
$this->assertIdentical($query->count(), 1, 'One record is queued for insertion.');
|
||||
|
|
@ -104,43 +104,43 @@ class InsertTest extends DatabaseTestBase {
|
|||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
|
||||
$this->assertIdentical((int) $num_records_before + 3, (int) $num_records_after, 'Record inserts correctly.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Larry'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Curly'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Moe'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can specify fields without values and specify values later.
|
||||
*/
|
||||
function testInsertFieldOnlyDefinition() {
|
||||
public function testInsertFieldOnlyDefinition() {
|
||||
// This is useful for importers, when we want to create a query and define
|
||||
// its fields once, then loop over a multi-insert execution.
|
||||
db_insert('test')
|
||||
->fields(array('name', 'age'))
|
||||
->values(array('Larry', '30'))
|
||||
->values(array('Curly', '31'))
|
||||
->values(array('Moe', '32'))
|
||||
->fields(['name', 'age'])
|
||||
->values(['Larry', '30'])
|
||||
->values(['Curly', '31'])
|
||||
->values(['Moe', '32'])
|
||||
->execute();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Larry'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Larry'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Curly'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Curly'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '31', 'Can retrieve after inserting.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Moe'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Moe'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '32', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that inserts return the proper auto-increment ID.
|
||||
*/
|
||||
function testInsertLastInsertID() {
|
||||
public function testInsertLastInsertID() {
|
||||
$id = db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Larry',
|
||||
'age' => '30',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$this->assertIdentical($id, '5', 'Auto-increment ID returned successfully.');
|
||||
|
|
@ -149,14 +149,14 @@ class InsertTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that the INSERT INTO ... SELECT (fields) ... syntax works.
|
||||
*/
|
||||
function testInsertSelectFields() {
|
||||
public function testInsertSelectFields() {
|
||||
$query = db_select('test_people', 'tp');
|
||||
// The query builder will always append expressions after fields.
|
||||
// Add the expression first to test that the insert fields are correctly
|
||||
// re-ordered.
|
||||
$query->addExpression('tp.age', 'age');
|
||||
$query
|
||||
->fields('tp', array('name', 'job'))
|
||||
->fields('tp', ['name', 'job'])
|
||||
->condition('tp.name', 'Meredith');
|
||||
|
||||
// The resulting query should be equivalent to:
|
||||
|
|
@ -168,14 +168,14 @@ class InsertTest extends DatabaseTestBase {
|
|||
->from($query)
|
||||
->execute();
|
||||
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Meredith'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the INSERT INTO ... SELECT * ... syntax works.
|
||||
*/
|
||||
function testInsertSelectAll() {
|
||||
public function testInsertSelectAll() {
|
||||
$query = db_select('test_people', 'tp')
|
||||
->fields('tp')
|
||||
->condition('tp.name', 'Meredith');
|
||||
|
|
@ -189,21 +189,21 @@ class InsertTest extends DatabaseTestBase {
|
|||
->from($query)
|
||||
->execute();
|
||||
|
||||
$saved_age = db_query('SELECT age FROM {test_people_copy} WHERE name = :name', array(':name' => 'Meredith'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test_people_copy} WHERE name = :name', [':name' => 'Meredith'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '30', 'Can retrieve after inserting.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can INSERT INTO a special named column.
|
||||
*/
|
||||
function testSpecialColumnInsert() {
|
||||
public function testSpecialColumnInsert() {
|
||||
$id = db_insert('test_special_columns')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'id' => 2,
|
||||
'offset' => 'Offset value 2',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
$saved_value = db_query('SELECT "offset" FROM {test_special_columns} WHERE id = :id', array(':id' => 2))->fetchField();
|
||||
$saved_value = db_query('SELECT "offset" FROM {test_special_columns} WHERE id = :id', [':id' => 2])->fetchField();
|
||||
$this->assertIdentical($saved_value, 'Offset value 2', 'Can retrieve special column name value after inserting.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,31 +14,31 @@ class InvalidDataTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests aborting of traditional SQL database systems with invalid data.
|
||||
*/
|
||||
function testInsertDuplicateData() {
|
||||
public function testInsertDuplicateData() {
|
||||
// Try to insert multiple records where at least one has bad data.
|
||||
try {
|
||||
db_insert('test')
|
||||
->fields(array('name', 'age', 'job'))
|
||||
->values(array(
|
||||
->fields(['name', 'age', 'job'])
|
||||
->values([
|
||||
'name' => 'Elvis',
|
||||
'age' => 63,
|
||||
'job' => 'Singer',
|
||||
))->values(array(
|
||||
])->values([
|
||||
'name' => 'John', // <-- Duplicate value on unique field.
|
||||
'age' => 17,
|
||||
'job' => 'Consultant',
|
||||
))
|
||||
->values(array(
|
||||
])
|
||||
->values([
|
||||
'name' => 'Frank',
|
||||
'age' => 75,
|
||||
'job' => 'Singer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
$this->fail('Insert succeeded when it should not have.');
|
||||
}
|
||||
catch (IntegrityConstraintViolationException $e) {
|
||||
// Check if the first record was inserted.
|
||||
$name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => 63))->fetchField();
|
||||
$name = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => 63])->fetchField();
|
||||
|
||||
if ($name == 'Elvis') {
|
||||
if (!Database::getConnection()->supportsTransactions()) {
|
||||
|
|
@ -58,8 +58,8 @@ class InvalidDataTest extends DatabaseTestBase {
|
|||
|
||||
// Ensure the other values were not inserted.
|
||||
$record = db_select('test')
|
||||
->fields('test', array('name', 'age'))
|
||||
->condition('age', array(17, 75), 'IN')
|
||||
->fields('test', ['name', 'age'])
|
||||
->condition('age', [17, 75], 'IN')
|
||||
->execute()->fetchObject();
|
||||
|
||||
$this->assertFalse($record, 'The rest of the insert aborted as expected.');
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ class LargeQueryTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests truncation of messages when max_allowed_packet exception occurs.
|
||||
*/
|
||||
function testMaxAllowedPacketQueryTruncating() {
|
||||
public function testMaxAllowedPacketQueryTruncating() {
|
||||
// This test only makes sense if we are running on a MySQL database.
|
||||
// Test if we are.
|
||||
$database = Database::getConnectionInfo('default');
|
||||
|
|
@ -29,7 +29,7 @@ class LargeQueryTest extends DatabaseTestBase {
|
|||
if (Environment::checkMemoryLimit($max_allowed_packet + (16 * 1024 * 1024))) {
|
||||
$long_name = str_repeat('a', $max_allowed_packet + 1);
|
||||
try {
|
||||
db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $long_name));
|
||||
db_query('SELECT name FROM {test} WHERE name = :name', [':name' => $long_name]);
|
||||
$this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'");
|
||||
}
|
||||
catch (DatabaseException $e) {
|
||||
|
|
|
|||
|
|
@ -14,14 +14,14 @@ class LoggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can log the existence of a query.
|
||||
*/
|
||||
function testEnableLogging() {
|
||||
public function testEnableLogging() {
|
||||
Database::startLog('testing');
|
||||
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchCol();
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25])->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchCol();
|
||||
|
||||
// Trigger a call that does not have file in the backtrace.
|
||||
call_user_func_array('db_query', array('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo')))->fetchCol();
|
||||
call_user_func_array('db_query', ['SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo']])->fetchCol();
|
||||
|
||||
$queries = Database::getLog('testing', 'default');
|
||||
|
||||
|
|
@ -35,14 +35,14 @@ class LoggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can run two logs in parallel.
|
||||
*/
|
||||
function testEnableMultiLogging() {
|
||||
public function testEnableMultiLogging() {
|
||||
Database::startLog('testing1');
|
||||
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25])->fetchCol();
|
||||
|
||||
Database::startLog('testing2');
|
||||
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchCol();
|
||||
|
||||
$queries1 = Database::getLog('testing1');
|
||||
$queries2 = Database::getLog('testing2');
|
||||
|
|
@ -54,7 +54,7 @@ class LoggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests logging queries against multiple targets on the same connection.
|
||||
*/
|
||||
function testEnableTargetLogging() {
|
||||
public function testEnableTargetLogging() {
|
||||
// Clone the primary credentials to a replica connection and to another fake
|
||||
// connection.
|
||||
$connection_info = Database::getConnectionInfo('default');
|
||||
|
|
@ -62,9 +62,9 @@ class LoggingTest extends DatabaseTestBase {
|
|||
|
||||
Database::startLog('testing1');
|
||||
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25])->fetchCol();
|
||||
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'replica'));//->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'], ['target' => 'replica']);//->fetchCol();
|
||||
|
||||
$queries1 = Database::getLog('testing1');
|
||||
|
||||
|
|
@ -80,17 +80,17 @@ class LoggingTest extends DatabaseTestBase {
|
|||
* a fake target so the query should fall back to running on the default
|
||||
* target.
|
||||
*/
|
||||
function testEnableTargetLoggingNoTarget() {
|
||||
public function testEnableTargetLoggingNoTarget() {
|
||||
Database::startLog('testing1');
|
||||
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25])->fetchCol();
|
||||
|
||||
// We use "fake" here as a target because any non-existent target will do.
|
||||
// However, because all of the tests in this class share a single page
|
||||
// request there is likely to be a target of "replica" from one of the other
|
||||
// unit tests, so we use a target here that we know with absolute certainty
|
||||
// does not exist.
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'fake'))->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'], ['target' => 'fake'])->fetchCol();
|
||||
|
||||
$queries1 = Database::getLog('testing1');
|
||||
|
||||
|
|
@ -102,7 +102,7 @@ class LoggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can log queries separately on different connections.
|
||||
*/
|
||||
function testEnableMultiConnectionLogging() {
|
||||
public function testEnableMultiConnectionLogging() {
|
||||
// Clone the primary credentials to a fake connection.
|
||||
// That both connections point to the same physical database is irrelevant.
|
||||
$connection_info = Database::getConnectionInfo('default');
|
||||
|
|
@ -111,11 +111,11 @@ class LoggingTest extends DatabaseTestBase {
|
|||
Database::startLog('testing1');
|
||||
Database::startLog('testing1', 'test2');
|
||||
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', array(':age' => 25))->fetchCol();
|
||||
db_query('SELECT name FROM {test} WHERE age > :age', [':age' => 25])->fetchCol();
|
||||
|
||||
$old_key = db_set_active('test2');
|
||||
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'), array('target' => 'replica'))->fetchCol();
|
||||
db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'], ['target' => 'replica'])->fetchCol();
|
||||
|
||||
db_set_active($old_key);
|
||||
|
||||
|
|
@ -129,7 +129,7 @@ class LoggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that getLog with a wrong key return an empty array.
|
||||
*/
|
||||
function testGetLoggingWrongKey() {
|
||||
public function testGetLoggingWrongKey() {
|
||||
$result = Database::getLog('wrong');
|
||||
|
||||
$this->assertEqual($result, [], 'The function getLog with a wrong key returns an empty array.');
|
||||
|
|
|
|||
|
|
@ -15,15 +15,15 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can merge-insert a record successfully.
|
||||
*/
|
||||
function testMergeInsert() {
|
||||
public function testMergeInsert() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
$result = db_merge('test_people')
|
||||
->key('job', 'Presenter')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'age' => 31,
|
||||
'name' => 'Tiffany',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$this->assertEqual($result, Merge::STATUS_INSERT, 'Insert status returned.');
|
||||
|
|
@ -31,7 +31,7 @@ class MergeTest extends DatabaseTestBase {
|
|||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Presenter'])->fetch();
|
||||
$this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, 31, 'Age set correctly.');
|
||||
$this->assertEqual($person->job, 'Presenter', 'Job set correctly.');
|
||||
|
|
@ -40,15 +40,15 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can merge-update a record successfully.
|
||||
*/
|
||||
function testMergeUpdate() {
|
||||
public function testMergeUpdate() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
$result = db_merge('test_people')
|
||||
->key('job', 'Speaker')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'age' => 31,
|
||||
'name' => 'Tiffany',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$this->assertEqual($result, Merge::STATUS_UPDATE, 'Update status returned.');
|
||||
|
|
@ -56,7 +56,7 @@ class MergeTest extends DatabaseTestBase {
|
|||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, 31, 'Age set correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
|
||||
|
|
@ -68,19 +68,19 @@ class MergeTest extends DatabaseTestBase {
|
|||
* This test varies from the previous test because it manually defines which
|
||||
* fields are inserted, and which fields are updated.
|
||||
*/
|
||||
function testMergeUpdateExcept() {
|
||||
public function testMergeUpdateExcept() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
db_merge('test_people')
|
||||
->key('job', 'Speaker')
|
||||
->insertFields(array('age' => 31))
|
||||
->updateFields(array('name' => 'Tiffany'))
|
||||
->insertFields(['age' => 31])
|
||||
->updateFields(['name' => 'Tiffany'])
|
||||
->execute();
|
||||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, 30, 'Age skipped correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
|
||||
|
|
@ -89,24 +89,24 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can merge-update a record, with alternate replacement.
|
||||
*/
|
||||
function testMergeUpdateExplicit() {
|
||||
public function testMergeUpdateExplicit() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
db_merge('test_people')
|
||||
->key('job', 'Speaker')
|
||||
->insertFields(array(
|
||||
->insertFields([
|
||||
'age' => 31,
|
||||
'name' => 'Tiffany',
|
||||
))
|
||||
->updateFields(array(
|
||||
])
|
||||
->updateFields([
|
||||
'name' => 'Joe',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Joe', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, 30, 'Age skipped correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
|
||||
|
|
@ -115,10 +115,10 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can merge-update a record successfully, with expressions.
|
||||
*/
|
||||
function testMergeUpdateExpression() {
|
||||
public function testMergeUpdateExpression() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
$age_before = db_query('SELECT age FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetchField();
|
||||
$age_before = db_query('SELECT age FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetchField();
|
||||
|
||||
// This is a very contrived example, as I have no idea why you'd want to
|
||||
// change age this way, but that's beside the point.
|
||||
|
|
@ -127,15 +127,15 @@ class MergeTest extends DatabaseTestBase {
|
|||
// which is what is supposed to happen.
|
||||
db_merge('test_people')
|
||||
->key('job', 'Speaker')
|
||||
->fields(array('name' => 'Tiffany'))
|
||||
->insertFields(array('age' => 31))
|
||||
->expression('age', 'age + :age', array(':age' => 4))
|
||||
->fields(['name' => 'Tiffany'])
|
||||
->insertFields(['age' => 31])
|
||||
->expression('age', 'age + :age', [':age' => 4])
|
||||
->execute();
|
||||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge updated properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, $age_before + 4, 'Age updated correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job set correctly.');
|
||||
|
|
@ -144,7 +144,7 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can merge-insert without any update fields.
|
||||
*/
|
||||
function testMergeInsertWithoutUpdate() {
|
||||
public function testMergeInsertWithoutUpdate() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
db_merge('test_people')
|
||||
|
|
@ -154,7 +154,7 @@ class MergeTest extends DatabaseTestBase {
|
|||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before + 1, $num_records_after, 'Merge inserted properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Presenter'])->fetch();
|
||||
$this->assertEqual($person->name, '', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, 0, 'Age set correctly.');
|
||||
$this->assertEqual($person->job, 'Presenter', 'Job set correctly.');
|
||||
|
|
@ -163,7 +163,7 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can merge-update without any update fields.
|
||||
*/
|
||||
function testMergeUpdateWithoutUpdate() {
|
||||
public function testMergeUpdateWithoutUpdate() {
|
||||
$num_records_before = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
|
||||
db_merge('test_people')
|
||||
|
|
@ -173,20 +173,20 @@ class MergeTest extends DatabaseTestBase {
|
|||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge skipped properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Meredith', 'Name skipped correctly.');
|
||||
$this->assertEqual($person->age, 30, 'Age skipped correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job skipped correctly.');
|
||||
|
||||
db_merge('test_people')
|
||||
->key('job', 'Speaker')
|
||||
->insertFields(array('age' => 31))
|
||||
->insertFields(['age' => 31])
|
||||
->execute();
|
||||
|
||||
$num_records_after = db_query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before, $num_records_after, 'Merge skipped properly.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->name, 'Meredith', 'Name skipped correctly.');
|
||||
$this->assertEqual($person->age, 30, 'Age skipped correctly.');
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job skipped correctly.');
|
||||
|
|
@ -195,17 +195,17 @@ class MergeTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that an invalid merge query throws an exception.
|
||||
*/
|
||||
function testInvalidMerge() {
|
||||
public function testInvalidMerge() {
|
||||
try {
|
||||
// This query will fail because there is no key field specified.
|
||||
// Normally it would throw an exception but we are suppressing it with
|
||||
// the throw_exception option.
|
||||
$options['throw_exception'] = FALSE;
|
||||
db_merge('test_people', $options)
|
||||
->fields(array(
|
||||
->fields([
|
||||
'age' => 31,
|
||||
'name' => 'Tiffany',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
$this->pass('$options[\'throw_exception\'] is FALSE, no InvalidMergeQueryException thrown.');
|
||||
}
|
||||
|
|
@ -217,10 +217,10 @@ class MergeTest extends DatabaseTestBase {
|
|||
try {
|
||||
// This query will fail because there is no key field specified.
|
||||
db_merge('test_people')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'age' => 31,
|
||||
'name' => 'Tiffany',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
catch (InvalidMergeQueryException $e) {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class NextIdTest extends KernelTestBase {
|
|||
* The modules to enable.
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system');
|
||||
public static $modules = ['system'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
|
@ -25,7 +25,7 @@ class NextIdTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests that the sequences API works.
|
||||
*/
|
||||
function testDbNextId() {
|
||||
public function testDbNextId() {
|
||||
$first = db_next_id();
|
||||
$second = db_next_id();
|
||||
// We can test for exact increase in here because we know there is no
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ class PrefixInfoTest extends DatabaseTestBase {
|
|||
* The other two by Drupal core supported databases do not have this variable
|
||||
* set in the return array.
|
||||
*/
|
||||
function testGetPrefixInfo() {
|
||||
public function testGetPrefixInfo() {
|
||||
$connection_info = Database::getConnectionInfo('default');
|
||||
if ($connection_info['default']['driver'] == 'mysql') {
|
||||
// Copy the default connection info to the 'extra' key.
|
||||
|
|
|
|||
|
|
@ -12,20 +12,20 @@ class QueryTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can pass an array of values directly in the query.
|
||||
*/
|
||||
function testArraySubstitution() {
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', array(':ages[]' => array(25, 26, 27)))->fetchAll();
|
||||
public function testArraySubstitution() {
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', [':ages[]' => [25, 26, 27]])->fetchAll();
|
||||
$this->assertEqual(count($names), 3, 'Correct number of names returned');
|
||||
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', array(':ages[]' => array(25)))->fetchAll();
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', [':ages[]' => [25]])->fetchAll();
|
||||
$this->assertEqual(count($names), 1, 'Correct number of names returned');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can not pass a scalar value when an array is expected.
|
||||
*/
|
||||
function testScalarSubstitution() {
|
||||
public function testScalarSubstitution() {
|
||||
try {
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', array(':ages[]' => 25))->fetchAll();
|
||||
$names = db_query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', [':ages[]' => 25])->fetchAll();
|
||||
$this->fail('Array placeholder with scalar argument should result in an exception.');
|
||||
}
|
||||
catch (\InvalidArgumentException $e) {
|
||||
|
|
@ -39,12 +39,12 @@ class QueryTest extends DatabaseTestBase {
|
|||
*/
|
||||
public function testArrayArgumentsSQLInjection() {
|
||||
// Attempt SQL injection and verify that it does not work.
|
||||
$condition = array(
|
||||
$condition = [
|
||||
"1 ;INSERT INTO {test} (name) VALUES ('test12345678'); -- " => '',
|
||||
'1' => '',
|
||||
);
|
||||
];
|
||||
try {
|
||||
db_query("SELECT * FROM {test} WHERE name = :name", array(':name' => $condition))->fetchObject();
|
||||
db_query("SELECT * FROM {test} WHERE name = :name", [':name' => $condition])->fetchObject();
|
||||
$this->fail('SQL injection attempt via array arguments should result in a database exception.');
|
||||
}
|
||||
catch (\InvalidArgumentException $e) {
|
||||
|
|
@ -101,7 +101,7 @@ class QueryTest extends DatabaseTestBase {
|
|||
|
||||
try {
|
||||
$result = db_select('test', 't')
|
||||
->fields('t', array('name', 'name'))
|
||||
->fields('t', ['name', 'name'])
|
||||
->condition('name', 1, $injection)
|
||||
->execute();
|
||||
$this->fail('Should not be able to attempt SQL injection via operator.');
|
||||
|
|
@ -118,7 +118,7 @@ class QueryTest extends DatabaseTestBase {
|
|||
|
||||
try {
|
||||
$result = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->fields('t', ['name'])
|
||||
->condition('name', 1, $injection)
|
||||
->execute();
|
||||
$this->fail('Should not be able to attempt SQL injection via operator.');
|
||||
|
|
@ -139,9 +139,9 @@ class QueryTest extends DatabaseTestBase {
|
|||
$count = db_query('SELECT COUNT(*) >= 3 FROM {test}')->fetchField();
|
||||
$this->assertEqual((bool) $count, TRUE);
|
||||
|
||||
$count = db_query('SELECT COUNT(*) >= :count FROM {test}', array(
|
||||
$count = db_query('SELECT COUNT(*) >= :count FROM {test}', [
|
||||
':count' => 3,
|
||||
))->fetchField();
|
||||
])->fetchField();
|
||||
$this->assertEqual((bool) $count, TRUE);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -9,17 +9,10 @@ namespace Drupal\KernelTests\Core\Database;
|
|||
*/
|
||||
class RangeQueryTest extends DatabaseTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('database_test');
|
||||
|
||||
/**
|
||||
* Confirms that range queries work and return the correct result.
|
||||
*/
|
||||
function testRangeQuery() {
|
||||
public function testRangeQuery() {
|
||||
// Test if return correct number of rows.
|
||||
$range_rows = db_query_range("SELECT name FROM {test} ORDER BY name", 1, 3)->fetchAll();
|
||||
$this->assertEqual(count($range_rows), 3, 'Range query work and return correct number of rows.');
|
||||
|
|
|
|||
|
|
@ -14,29 +14,29 @@ class RegressionTest extends DatabaseTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('node', 'user');
|
||||
public static $modules = ['node', 'user'];
|
||||
|
||||
/**
|
||||
* Ensures that non-ASCII UTF-8 data is stored in the database properly.
|
||||
*/
|
||||
function testRegression_310447() {
|
||||
public function testRegression_310447() {
|
||||
// That's a 255 character UTF-8 string.
|
||||
$job = str_repeat("é", 255);
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => $this->randomMachineName(),
|
||||
'age' => 20,
|
||||
'job' => $job,
|
||||
))->execute();
|
||||
])->execute();
|
||||
|
||||
$from_database = db_query('SELECT job FROM {test} WHERE job = :job', array(':job' => $job))->fetchField();
|
||||
$from_database = db_query('SELECT job FROM {test} WHERE job = :job', [':job' => $job])->fetchField();
|
||||
$this->assertIdentical($job, $from_database, 'The database handles UTF-8 characters cleanly.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the db_table_exists() function.
|
||||
*/
|
||||
function testDBTableExists() {
|
||||
public function testDBTableExists() {
|
||||
$this->assertIdentical(TRUE, db_table_exists('test'), 'Returns true for existent table.');
|
||||
$this->assertIdentical(FALSE, db_table_exists('nosuchtable'), 'Returns false for nonexistent table.');
|
||||
}
|
||||
|
|
@ -44,7 +44,7 @@ class RegressionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests the db_field_exists() function.
|
||||
*/
|
||||
function testDBFieldExists() {
|
||||
public function testDBFieldExists() {
|
||||
$this->assertIdentical(TRUE, db_field_exists('test', 'name'), 'Returns true for existent column.');
|
||||
$this->assertIdentical(FALSE, db_field_exists('test', 'nosuchcolumn'), 'Returns false for nonexistent column.');
|
||||
}
|
||||
|
|
@ -52,7 +52,7 @@ class RegressionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests the db_index_exists() function.
|
||||
*/
|
||||
function testDBIndexExists() {
|
||||
public function testDBIndexExists() {
|
||||
$this->assertIdentical(TRUE, db_index_exists('test', 'ages'), 'Returns true for existent index.');
|
||||
$this->assertIdentical(FALSE, db_index_exists('test', 'nosuchindex'), 'Returns false for nonexistent index.');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,34 +24,34 @@ class SchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests database interactions.
|
||||
*/
|
||||
function testSchema() {
|
||||
public function testSchema() {
|
||||
// Try creating a table.
|
||||
$table_specification = array(
|
||||
$table_specification = [
|
||||
'description' => 'Schema table description may contain "quotes" and could be long—very long indeed.',
|
||||
'fields' => array(
|
||||
'id' => array(
|
||||
'fields' => [
|
||||
'id' => [
|
||||
'type' => 'int',
|
||||
'default' => NULL,
|
||||
),
|
||||
'test_field' => array(
|
||||
],
|
||||
'test_field' => [
|
||||
'type' => 'int',
|
||||
'not null' => TRUE,
|
||||
'description' => 'Schema table description may contain "quotes" and could be long—very long indeed. There could be "multiple quoted regions".',
|
||||
),
|
||||
'test_field_string' => array(
|
||||
],
|
||||
'test_field_string' => [
|
||||
'type' => 'varchar',
|
||||
'length' => 20,
|
||||
'not null' => TRUE,
|
||||
'default' => "'\"funky default'\"",
|
||||
'description' => 'Schema column description for string.',
|
||||
),
|
||||
'test_field_string_ascii' => array(
|
||||
],
|
||||
'test_field_string_ascii' => [
|
||||
'type' => 'varchar_ascii',
|
||||
'length' => 255,
|
||||
'description' => 'Schema column description for ASCII string.',
|
||||
),
|
||||
),
|
||||
);
|
||||
],
|
||||
],
|
||||
];
|
||||
db_create_table('test_table', $table_specification);
|
||||
|
||||
// Assert that the table exists.
|
||||
|
|
@ -95,7 +95,7 @@ class SchemaTest extends KernelTestBase {
|
|||
$index_exists = Database::getConnection()->schema()->indexExists('test_table', 'test_field');
|
||||
$this->assertIdentical($index_exists, FALSE, 'Fake index does not exists');
|
||||
// Add index.
|
||||
db_add_index('test_table', 'test_field', array('test_field'), $table_specification);
|
||||
db_add_index('test_table', 'test_field', ['test_field'], $table_specification);
|
||||
// Test for created index and test for the boolean result of indexExists().
|
||||
$index_exists = Database::getConnection()->schema()->indexExists('test_table', 'test_field');
|
||||
$this->assertIdentical($index_exists, TRUE, 'Index created.');
|
||||
|
|
@ -123,13 +123,13 @@ class SchemaTest extends KernelTestBase {
|
|||
// Recreate the table.
|
||||
db_create_table('test_table', $table_specification);
|
||||
db_field_set_default('test_table', 'test_field', 0);
|
||||
db_add_field('test_table', 'test_serial', array('type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'Added column description.'));
|
||||
db_add_field('test_table', 'test_serial', ['type' => 'int', 'not null' => TRUE, 'default' => 0, 'description' => 'Added column description.']);
|
||||
|
||||
// Assert that the column comment has been set.
|
||||
$this->checkSchemaComment('Added column description.', 'test_table', 'test_serial');
|
||||
|
||||
// Change the new field to a serial column.
|
||||
db_change_field('test_table', 'test_serial', 'test_serial', array('type' => 'serial', 'not null' => TRUE, 'description' => 'Changed column description.'), array('primary key' => array('test_serial')));
|
||||
db_change_field('test_table', 'test_serial', 'test_serial', ['type' => 'serial', 'not null' => TRUE, 'description' => 'Changed column description.'], ['primary key' => ['test_serial']]);
|
||||
|
||||
// Assert that the column comment has been set.
|
||||
$this->checkSchemaComment('Changed column description.', 'test_table', 'test_serial');
|
||||
|
|
@ -143,24 +143,46 @@ class SchemaTest extends KernelTestBase {
|
|||
$count = db_query('SELECT COUNT(*) FROM {test_table}')->fetchField();
|
||||
$this->assertEqual($count, 2, 'There were two rows.');
|
||||
|
||||
// Test adding a serial field to an existing table.
|
||||
db_drop_table('test_table');
|
||||
db_create_table('test_table', $table_specification);
|
||||
db_field_set_default('test_table', 'test_field', 0);
|
||||
db_add_field('test_table', 'test_serial', ['type' => 'serial', 'not null' => TRUE], ['primary key' => ['test_serial']]);
|
||||
|
||||
$this->assertPrimaryKeyColumns('test_table', ['test_serial']);
|
||||
|
||||
$this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
|
||||
$max1 = db_query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
|
||||
$this->assertTrue($this->tryInsert(), 'Insert with a serial succeeded.');
|
||||
$max2 = db_query('SELECT MAX(test_serial) FROM {test_table}')->fetchField();
|
||||
$this->assertTrue($max2 > $max1, 'The serial is monotone.');
|
||||
|
||||
$count = db_query('SELECT COUNT(*) FROM {test_table}')->fetchField();
|
||||
$this->assertEqual($count, 2, 'There were two rows.');
|
||||
|
||||
// Test adding a new column and form a composite primary key with it.
|
||||
db_add_field('test_table', 'test_composite_primary_key', ['type' => 'int', 'not null' => TRUE, 'default' => 0], ['primary key' => ['test_serial', 'test_composite_primary_key']]);
|
||||
|
||||
$this->assertPrimaryKeyColumns('test_table', ['test_serial', 'test_composite_primary_key']);
|
||||
|
||||
// Test renaming of keys and constraints.
|
||||
db_drop_table('test_table');
|
||||
$table_specification = array(
|
||||
'fields' => array(
|
||||
'id' => array(
|
||||
$table_specification = [
|
||||
'fields' => [
|
||||
'id' => [
|
||||
'type' => 'serial',
|
||||
'not null' => TRUE,
|
||||
),
|
||||
'test_field' => array(
|
||||
],
|
||||
'test_field' => [
|
||||
'type' => 'int',
|
||||
'default' => 0,
|
||||
),
|
||||
),
|
||||
'primary key' => array('id'),
|
||||
'unique keys' => array(
|
||||
'test_field' => array('test_field'),
|
||||
),
|
||||
);
|
||||
],
|
||||
],
|
||||
'primary key' => ['id'],
|
||||
'unique keys' => [
|
||||
'test_field' => ['test_field'],
|
||||
],
|
||||
];
|
||||
db_create_table('test_table', $table_specification);
|
||||
|
||||
// Tests for indexes are Database specific.
|
||||
|
|
@ -215,18 +237,18 @@ class SchemaTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Use database specific data type and ensure that table is created.
|
||||
$table_specification = array(
|
||||
$table_specification = [
|
||||
'description' => 'Schema table description.',
|
||||
'fields' => array(
|
||||
'timestamp' => array(
|
||||
'fields' => [
|
||||
'timestamp' => [
|
||||
'mysql_type' => 'timestamp',
|
||||
'pgsql_type' => 'timestamp',
|
||||
'sqlite_type' => 'datetime',
|
||||
'not null' => FALSE,
|
||||
'default' => NULL,
|
||||
),
|
||||
),
|
||||
);
|
||||
],
|
||||
],
|
||||
];
|
||||
try {
|
||||
db_create_table('test_timestamp', $table_specification);
|
||||
}
|
||||
|
|
@ -240,56 +262,56 @@ class SchemaTest extends KernelTestBase {
|
|||
*
|
||||
* @see \Drupal\Core\Database\Driver\mysql\Schema::getNormalizedIndexes()
|
||||
*/
|
||||
function testIndexLength() {
|
||||
public function testIndexLength() {
|
||||
if (Database::getConnection()->databaseType() != 'mysql') {
|
||||
return;
|
||||
}
|
||||
$table_specification = array(
|
||||
'fields' => array(
|
||||
'id' => array(
|
||||
$table_specification = [
|
||||
'fields' => [
|
||||
'id' => [
|
||||
'type' => 'int',
|
||||
'default' => NULL,
|
||||
),
|
||||
'test_field_text' => array(
|
||||
],
|
||||
'test_field_text' => [
|
||||
'type' => 'text',
|
||||
'not null' => TRUE,
|
||||
),
|
||||
'test_field_string_long' => array(
|
||||
],
|
||||
'test_field_string_long' => [
|
||||
'type' => 'varchar',
|
||||
'length' => 255,
|
||||
'not null' => TRUE,
|
||||
),
|
||||
'test_field_string_ascii_long' => array(
|
||||
],
|
||||
'test_field_string_ascii_long' => [
|
||||
'type' => 'varchar_ascii',
|
||||
'length' => 255,
|
||||
),
|
||||
'test_field_string_short' => array(
|
||||
],
|
||||
'test_field_string_short' => [
|
||||
'type' => 'varchar',
|
||||
'length' => 128,
|
||||
'not null' => TRUE,
|
||||
),
|
||||
),
|
||||
'indexes' => array(
|
||||
'test_regular' => array(
|
||||
],
|
||||
],
|
||||
'indexes' => [
|
||||
'test_regular' => [
|
||||
'test_field_text',
|
||||
'test_field_string_long',
|
||||
'test_field_string_ascii_long',
|
||||
'test_field_string_short',
|
||||
),
|
||||
'test_length' => array(
|
||||
array('test_field_text', 128),
|
||||
array('test_field_string_long', 128),
|
||||
array('test_field_string_ascii_long', 128),
|
||||
array('test_field_string_short', 128),
|
||||
),
|
||||
'test_mixed' => array(
|
||||
array('test_field_text', 200),
|
||||
],
|
||||
'test_length' => [
|
||||
['test_field_text', 128],
|
||||
['test_field_string_long', 128],
|
||||
['test_field_string_ascii_long', 128],
|
||||
['test_field_string_short', 128],
|
||||
],
|
||||
'test_mixed' => [
|
||||
['test_field_text', 200],
|
||||
'test_field_string_long',
|
||||
array('test_field_string_ascii_long', 200),
|
||||
['test_field_string_ascii_long', 200],
|
||||
'test_field_string_short',
|
||||
),
|
||||
),
|
||||
);
|
||||
],
|
||||
],
|
||||
];
|
||||
db_create_table('test_table_index_length', $table_specification);
|
||||
|
||||
$schema_object = Database::getConnection()->schema();
|
||||
|
|
@ -331,29 +353,29 @@ class SchemaTest extends KernelTestBase {
|
|||
|
||||
// Get index information.
|
||||
$results = db_query('SHOW INDEX FROM {test_table_index_length}');
|
||||
$expected_lengths = array(
|
||||
'test_regular' => array(
|
||||
$expected_lengths = [
|
||||
'test_regular' => [
|
||||
'test_field_text' => 191,
|
||||
'test_field_string_long' => 191,
|
||||
'test_field_string_ascii_long' => NULL,
|
||||
'test_field_string_short' => NULL,
|
||||
),
|
||||
'test_length' => array(
|
||||
],
|
||||
'test_length' => [
|
||||
'test_field_text' => 128,
|
||||
'test_field_string_long' => 128,
|
||||
'test_field_string_ascii_long' => 128,
|
||||
'test_field_string_short' => NULL,
|
||||
),
|
||||
'test_mixed' => array(
|
||||
],
|
||||
'test_mixed' => [
|
||||
'test_field_text' => 191,
|
||||
'test_field_string_long' => 191,
|
||||
'test_field_string_ascii_long' => 200,
|
||||
'test_field_string_short' => NULL,
|
||||
),
|
||||
'test_separate' => array(
|
||||
],
|
||||
'test_separate' => [
|
||||
'test_field_text' => 191,
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
// Count the number of columns defined in the indexes.
|
||||
$column_count = 0;
|
||||
|
|
@ -379,10 +401,10 @@ class SchemaTest extends KernelTestBase {
|
|||
* @return
|
||||
* TRUE if the insert succeeded, FALSE otherwise.
|
||||
*/
|
||||
function tryInsert($table = 'test_table') {
|
||||
public function tryInsert($table = 'test_table') {
|
||||
try {
|
||||
db_insert($table)
|
||||
->fields(array('id' => mt_rand(10, 20)))
|
||||
->fields(['id' => mt_rand(10, 20)])
|
||||
->execute();
|
||||
return TRUE;
|
||||
}
|
||||
|
|
@ -401,7 +423,7 @@ class SchemaTest extends KernelTestBase {
|
|||
* @param $column
|
||||
* Optional column to test.
|
||||
*/
|
||||
function checkSchemaComment($description, $table, $column = NULL) {
|
||||
public function checkSchemaComment($description, $table, $column = NULL) {
|
||||
if (method_exists(Database::getConnection()->schema(), 'getComment')) {
|
||||
$comment = Database::getConnection()->schema()->getComment($table, $column);
|
||||
// The schema comment truncation for mysql is different.
|
||||
|
|
@ -416,21 +438,21 @@ class SchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests creating unsigned columns and data integrity thereof.
|
||||
*/
|
||||
function testUnsignedColumns() {
|
||||
public function testUnsignedColumns() {
|
||||
// First create the table with just a serial column.
|
||||
$table_name = 'unsigned_table';
|
||||
$table_spec = array(
|
||||
'fields' => array('serial_column' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE)),
|
||||
'primary key' => array('serial_column'),
|
||||
);
|
||||
$table_spec = [
|
||||
'fields' => ['serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE]],
|
||||
'primary key' => ['serial_column'],
|
||||
];
|
||||
db_create_table($table_name, $table_spec);
|
||||
|
||||
// Now set up columns for the other types.
|
||||
$types = array('int', 'float', 'numeric');
|
||||
$types = ['int', 'float', 'numeric'];
|
||||
foreach ($types as $type) {
|
||||
$column_spec = array('type' => $type, 'unsigned' => TRUE);
|
||||
$column_spec = ['type' => $type, 'unsigned' => TRUE];
|
||||
if ($type == 'numeric') {
|
||||
$column_spec += array('precision' => 10, 'scale' => 0);
|
||||
$column_spec += ['precision' => 10, 'scale' => 0];
|
||||
}
|
||||
$column_name = $type . '_column';
|
||||
$table_spec['fields'][$column_name] = $column_spec;
|
||||
|
|
@ -439,8 +461,8 @@ class SchemaTest extends KernelTestBase {
|
|||
|
||||
// Finally, check each column and try to insert invalid values into them.
|
||||
foreach ($table_spec['fields'] as $column_name => $column_spec) {
|
||||
$this->assertTrue(db_field_exists($table_name, $column_name), format_string('Unsigned @type column was created.', array('@type' => $column_spec['type'])));
|
||||
$this->assertFalse($this->tryUnsignedInsert($table_name, $column_name), format_string('Unsigned @type column rejected a negative value.', array('@type' => $column_spec['type'])));
|
||||
$this->assertTrue(db_field_exists($table_name, $column_name), format_string('Unsigned @type column was created.', ['@type' => $column_spec['type']]));
|
||||
$this->assertFalse($this->tryUnsignedInsert($table_name, $column_name), format_string('Unsigned @type column rejected a negative value.', ['@type' => $column_spec['type']]));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -455,10 +477,10 @@ class SchemaTest extends KernelTestBase {
|
|||
* @return
|
||||
* TRUE if the insert succeeded, FALSE otherwise.
|
||||
*/
|
||||
function tryUnsignedInsert($table_name, $column_name) {
|
||||
public function tryUnsignedInsert($table_name, $column_name) {
|
||||
try {
|
||||
db_insert($table_name)
|
||||
->fields(array($column_name => -1))
|
||||
->fields([$column_name => -1])
|
||||
->execute();
|
||||
return TRUE;
|
||||
}
|
||||
|
|
@ -470,22 +492,22 @@ class SchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests adding columns to an existing table.
|
||||
*/
|
||||
function testSchemaAddField() {
|
||||
public function testSchemaAddField() {
|
||||
// Test varchar types.
|
||||
foreach (array(1, 32, 128, 256, 512) as $length) {
|
||||
$base_field_spec = array(
|
||||
foreach ([1, 32, 128, 256, 512] as $length) {
|
||||
$base_field_spec = [
|
||||
'type' => 'varchar',
|
||||
'length' => $length,
|
||||
);
|
||||
$variations = array(
|
||||
array('not null' => FALSE),
|
||||
array('not null' => FALSE, 'default' => '7'),
|
||||
array('not null' => FALSE, 'default' => substr('"thing"', 0, $length)),
|
||||
array('not null' => FALSE, 'default' => substr("\"'hing", 0, $length)),
|
||||
array('not null' => TRUE, 'initial' => 'd'),
|
||||
array('not null' => FALSE, 'default' => NULL),
|
||||
array('not null' => TRUE, 'initial' => 'd', 'default' => '7'),
|
||||
);
|
||||
];
|
||||
$variations = [
|
||||
['not null' => FALSE],
|
||||
['not null' => FALSE, 'default' => '7'],
|
||||
['not null' => FALSE, 'default' => substr('"thing"', 0, $length)],
|
||||
['not null' => FALSE, 'default' => substr("\"'hing", 0, $length)],
|
||||
['not null' => TRUE, 'initial' => 'd'],
|
||||
['not null' => FALSE, 'default' => NULL],
|
||||
['not null' => TRUE, 'initial' => 'd', 'default' => '7'],
|
||||
];
|
||||
|
||||
foreach ($variations as $variation) {
|
||||
$field_spec = $variation + $base_field_spec;
|
||||
|
|
@ -494,19 +516,19 @@ class SchemaTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Test int and float types.
|
||||
foreach (array('int', 'float') as $type) {
|
||||
foreach (array('tiny', 'small', 'medium', 'normal', 'big') as $size) {
|
||||
$base_field_spec = array(
|
||||
foreach (['int', 'float'] as $type) {
|
||||
foreach (['tiny', 'small', 'medium', 'normal', 'big'] as $size) {
|
||||
$base_field_spec = [
|
||||
'type' => $type,
|
||||
'size' => $size,
|
||||
);
|
||||
$variations = array(
|
||||
array('not null' => FALSE),
|
||||
array('not null' => FALSE, 'default' => 7),
|
||||
array('not null' => TRUE, 'initial' => 1),
|
||||
array('not null' => TRUE, 'initial' => 1, 'default' => 7),
|
||||
array('not null' => TRUE, 'initial_from_field' => 'serial_column'),
|
||||
);
|
||||
];
|
||||
$variations = [
|
||||
['not null' => FALSE],
|
||||
['not null' => FALSE, 'default' => 7],
|
||||
['not null' => TRUE, 'initial' => 1],
|
||||
['not null' => TRUE, 'initial' => 1, 'default' => 7],
|
||||
['not null' => TRUE, 'initial_from_field' => 'serial_column'],
|
||||
];
|
||||
|
||||
foreach ($variations as $variation) {
|
||||
$field_spec = $variation + $base_field_spec;
|
||||
|
|
@ -516,25 +538,25 @@ class SchemaTest extends KernelTestBase {
|
|||
}
|
||||
|
||||
// Test numeric types.
|
||||
foreach (array(1, 5, 10, 40, 65) as $precision) {
|
||||
foreach (array(0, 2, 10, 30) as $scale) {
|
||||
foreach ([1, 5, 10, 40, 65] as $precision) {
|
||||
foreach ([0, 2, 10, 30] as $scale) {
|
||||
// Skip combinations where precision is smaller than scale.
|
||||
if ($precision <= $scale) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$base_field_spec = array(
|
||||
$base_field_spec = [
|
||||
'type' => 'numeric',
|
||||
'scale' => $scale,
|
||||
'precision' => $precision,
|
||||
);
|
||||
$variations = array(
|
||||
array('not null' => FALSE),
|
||||
array('not null' => FALSE, 'default' => 7),
|
||||
array('not null' => TRUE, 'initial' => 1),
|
||||
array('not null' => TRUE, 'initial' => 1, 'default' => 7),
|
||||
array('not null' => TRUE, 'initial_from_field' => 'serial_column'),
|
||||
);
|
||||
];
|
||||
$variations = [
|
||||
['not null' => FALSE],
|
||||
['not null' => FALSE, 'default' => 7],
|
||||
['not null' => TRUE, 'initial' => 1],
|
||||
['not null' => TRUE, 'initial' => 1, 'default' => 7],
|
||||
['not null' => TRUE, 'initial_from_field' => 'serial_column'],
|
||||
];
|
||||
|
||||
foreach ($variations as $variation) {
|
||||
$field_spec = $variation + $base_field_spec;
|
||||
|
|
@ -556,15 +578,15 @@ class SchemaTest extends KernelTestBase {
|
|||
protected function assertFieldAdditionRemoval($field_spec) {
|
||||
// Try creating the field on a new table.
|
||||
$table_name = 'test_table_' . ($this->counter++);
|
||||
$table_spec = array(
|
||||
'fields' => array(
|
||||
'serial_column' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
|
||||
$table_spec = [
|
||||
'fields' => [
|
||||
'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
|
||||
'test_field' => $field_spec,
|
||||
),
|
||||
'primary key' => array('serial_column'),
|
||||
);
|
||||
],
|
||||
'primary key' => ['serial_column'],
|
||||
];
|
||||
db_create_table($table_name, $table_spec);
|
||||
$this->pass(format_string('Table %table created.', array('%table' => $table_name)));
|
||||
$this->pass(format_string('Table %table created.', ['%table' => $table_name]));
|
||||
|
||||
// Check the characteristics of the field.
|
||||
$this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
|
||||
|
|
@ -574,24 +596,24 @@ class SchemaTest extends KernelTestBase {
|
|||
|
||||
// Try adding a field to an existing table.
|
||||
$table_name = 'test_table_' . ($this->counter++);
|
||||
$table_spec = array(
|
||||
'fields' => array(
|
||||
'serial_column' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
|
||||
),
|
||||
'primary key' => array('serial_column'),
|
||||
);
|
||||
$table_spec = [
|
||||
'fields' => [
|
||||
'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
|
||||
],
|
||||
'primary key' => ['serial_column'],
|
||||
];
|
||||
db_create_table($table_name, $table_spec);
|
||||
$this->pass(format_string('Table %table created.', array('%table' => $table_name)));
|
||||
$this->pass(format_string('Table %table created.', ['%table' => $table_name]));
|
||||
|
||||
// Insert some rows to the table to test the handling of initial values.
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
db_insert($table_name)
|
||||
->useDefaults(array('serial_column'))
|
||||
->useDefaults(['serial_column'])
|
||||
->execute();
|
||||
}
|
||||
|
||||
db_add_field($table_name, 'test_field', $field_spec);
|
||||
$this->pass(format_string('Column %column created.', array('%column' => 'test_field')));
|
||||
$this->pass(format_string('Column %column created.', ['%column' => 'test_field']));
|
||||
|
||||
// Check the characteristics of the field.
|
||||
$this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
|
||||
|
|
@ -614,7 +636,7 @@ class SchemaTest extends KernelTestBase {
|
|||
if (isset($field_spec['initial'])) {
|
||||
// There should be no row with a value different then $field_spec['initial'].
|
||||
$count = db_select($table_name)
|
||||
->fields($table_name, array('serial_column'))
|
||||
->fields($table_name, ['serial_column'])
|
||||
->condition($field_name, $field_spec['initial'], '<>')
|
||||
->countQuery()
|
||||
->execute()
|
||||
|
|
@ -627,7 +649,7 @@ class SchemaTest extends KernelTestBase {
|
|||
// There should be no row with a value different than
|
||||
// $field_spec['initial_from_field'].
|
||||
$count = db_select($table_name)
|
||||
->fields($table_name, array('serial_column'))
|
||||
->fields($table_name, ['serial_column'])
|
||||
->where($table_name . '.' . $field_spec['initial_from_field'] . ' <> ' . $table_name . '.' . $field_name)
|
||||
->countQuery()
|
||||
->execute()
|
||||
|
|
@ -639,10 +661,10 @@ class SchemaTest extends KernelTestBase {
|
|||
if (isset($field_spec['default'])) {
|
||||
// Try inserting a row, and check the resulting value of the new column.
|
||||
$id = db_insert($table_name)
|
||||
->useDefaults(array('serial_column'))
|
||||
->useDefaults(['serial_column'])
|
||||
->execute();
|
||||
$field_value = db_select($table_name)
|
||||
->fields($table_name, array($field_name))
|
||||
->fields($table_name, [$field_name])
|
||||
->condition('serial_column', $id)
|
||||
->execute()
|
||||
->fetchField();
|
||||
|
|
@ -653,15 +675,15 @@ class SchemaTest extends KernelTestBase {
|
|||
/**
|
||||
* Tests changing columns between types.
|
||||
*/
|
||||
function testSchemaChangeField() {
|
||||
$field_specs = array(
|
||||
array('type' => 'int', 'size' => 'normal', 'not null' => FALSE),
|
||||
array('type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 17),
|
||||
array('type' => 'float', 'size' => 'normal', 'not null' => FALSE),
|
||||
array('type' => 'float', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 7.3),
|
||||
array('type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => FALSE),
|
||||
array('type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => TRUE, 'initial' => 1, 'default' => 7),
|
||||
);
|
||||
public function testSchemaChangeField() {
|
||||
$field_specs = [
|
||||
['type' => 'int', 'size' => 'normal', 'not null' => FALSE],
|
||||
['type' => 'int', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 17],
|
||||
['type' => 'float', 'size' => 'normal', 'not null' => FALSE],
|
||||
['type' => 'float', 'size' => 'normal', 'not null' => TRUE, 'initial' => 1, 'default' => 7.3],
|
||||
['type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => FALSE],
|
||||
['type' => 'numeric', 'scale' => 2, 'precision' => 10, 'not null' => TRUE, 'initial' => 1, 'default' => 7],
|
||||
];
|
||||
|
||||
foreach ($field_specs as $i => $old_spec) {
|
||||
foreach ($field_specs as $j => $new_spec) {
|
||||
|
|
@ -673,12 +695,12 @@ class SchemaTest extends KernelTestBase {
|
|||
}
|
||||
}
|
||||
|
||||
$field_specs = array(
|
||||
array('type' => 'varchar_ascii', 'length' => '255'),
|
||||
array('type' => 'varchar', 'length' => '255'),
|
||||
array('type' => 'text'),
|
||||
array('type' => 'blob', 'size' => 'big'),
|
||||
);
|
||||
$field_specs = [
|
||||
['type' => 'varchar_ascii', 'length' => '255'],
|
||||
['type' => 'varchar', 'length' => '255'],
|
||||
['type' => 'text'],
|
||||
['type' => 'blob', 'size' => 'big'],
|
||||
];
|
||||
|
||||
foreach ($field_specs as $i => $old_spec) {
|
||||
foreach ($field_specs as $j => $new_spec) {
|
||||
|
|
@ -705,15 +727,15 @@ class SchemaTest extends KernelTestBase {
|
|||
*/
|
||||
protected function assertFieldChange($old_spec, $new_spec, $test_data = NULL) {
|
||||
$table_name = 'test_table_' . ($this->counter++);
|
||||
$table_spec = array(
|
||||
'fields' => array(
|
||||
'serial_column' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
|
||||
$table_spec = [
|
||||
'fields' => [
|
||||
'serial_column' => ['type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE],
|
||||
'test_field' => $old_spec,
|
||||
),
|
||||
'primary key' => array('serial_column'),
|
||||
);
|
||||
],
|
||||
'primary key' => ['serial_column'],
|
||||
];
|
||||
db_create_table($table_name, $table_spec);
|
||||
$this->pass(format_string('Table %table created.', array('%table' => $table_name)));
|
||||
$this->pass(format_string('Table %table created.', ['%table' => $table_name]));
|
||||
|
||||
// Check the characteristics of the field.
|
||||
$this->assertFieldCharacteristics($table_name, 'test_field', $old_spec);
|
||||
|
|
@ -804,4 +826,46 @@ class SchemaTest extends KernelTestBase {
|
|||
Database::setActiveConnection('default');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the primary keys of a table.
|
||||
*
|
||||
* @param string $table_name
|
||||
* The name of the table to check.
|
||||
* @param array $primary_key
|
||||
* The expected key column specifier for a table's primary key.
|
||||
*/
|
||||
protected function assertPrimaryKeyColumns($table_name, array $primary_key = []) {
|
||||
$db_type = Database::getConnection()->databaseType();
|
||||
|
||||
switch ($db_type) {
|
||||
case 'mysql':
|
||||
$result = Database::getConnection()->query("SHOW KEYS FROM {" . $table_name . "} WHERE Key_name = 'PRIMARY'")->fetchAllAssoc('Column_name');
|
||||
$this->assertSame($primary_key, array_keys($result));
|
||||
|
||||
break;
|
||||
case 'pgsql':
|
||||
$result = Database::getConnection()->query("SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
|
||||
FROM pg_index i
|
||||
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
|
||||
WHERE i.indrelid = '{" . $table_name . "}'::regclass AND i.indisprimary")
|
||||
->fetchAllAssoc('attname');
|
||||
$this->assertSame($primary_key, array_keys($result));
|
||||
|
||||
break;
|
||||
case 'sqlite':
|
||||
// For SQLite we need access to the protected
|
||||
// \Drupal\Core\Database\Driver\sqlite\Schema::introspectSchema() method
|
||||
// because we have no other way of getting the table prefixes needed for
|
||||
// running a straight PRAGMA query.
|
||||
$schema_object = Database::getConnection()->schema();
|
||||
$reflection = new \ReflectionMethod($schema_object, 'introspectSchema');
|
||||
$reflection->setAccessible(TRUE);
|
||||
|
||||
$table_info = $reflection->invoke($schema_object, $table_name);
|
||||
$this->assertSame($primary_key, $table_info['primary key']);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ class SelectCloneTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Test that subqueries as value within conditions are cloned properly.
|
||||
*/
|
||||
function testSelectConditionSubQueryCloning() {
|
||||
public function testSelectConditionSubQueryCloning() {
|
||||
$subquery = db_select('test', 't');
|
||||
$subquery->addField('t', 'id', 'id');
|
||||
$subquery->condition('age', 28, '<');
|
||||
|
|
|
|||
|
|
@ -18,12 +18,12 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'user', 'node_access_test', 'field');
|
||||
public static $modules = ['system', 'user', 'node_access_test', 'field'];
|
||||
|
||||
/**
|
||||
* Tests simple JOIN statements.
|
||||
*/
|
||||
function testDefaultJoin() {
|
||||
public function testDefaultJoin() {
|
||||
$query = db_select('test_task', 't');
|
||||
$people_alias = $query->join('test', 'p', 't.pid = p.id');
|
||||
$name_field = $query->addField($people_alias, 'name', 'name');
|
||||
|
|
@ -48,7 +48,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests LEFT OUTER joins.
|
||||
*/
|
||||
function testLeftOuterJoin() {
|
||||
public function testLeftOuterJoin() {
|
||||
$query = db_select('test', 'p');
|
||||
$people_alias = $query->leftJoin('test_task', 't', 't.pid = p.id');
|
||||
$name_field = $query->addField('p', 'name', 'name');
|
||||
|
|
@ -72,7 +72,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests GROUP BY clauses.
|
||||
*/
|
||||
function testGroupBy() {
|
||||
public function testGroupBy() {
|
||||
$query = db_select('test_task', 't');
|
||||
$count_field = $query->addExpression('COUNT(task)', 'num');
|
||||
$task_field = $query->addField('t', 'task');
|
||||
|
|
@ -82,7 +82,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
|
||||
$num_records = 0;
|
||||
$last_count = 0;
|
||||
$records = array();
|
||||
$records = [];
|
||||
foreach ($result as $record) {
|
||||
$num_records++;
|
||||
$this->assertTrue($record->$count_field >= $last_count, 'Results returned in correct order.');
|
||||
|
|
@ -90,16 +90,16 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
$records[$record->$task_field] = $record->$count_field;
|
||||
}
|
||||
|
||||
$correct_results = array(
|
||||
$correct_results = [
|
||||
'eat' => 1,
|
||||
'sleep' => 2,
|
||||
'code' => 1,
|
||||
'found new band' => 1,
|
||||
'perform at superbowl' => 1,
|
||||
);
|
||||
];
|
||||
|
||||
foreach ($correct_results as $task => $count) {
|
||||
$this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", array('@task' => $task)));
|
||||
$this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
|
||||
}
|
||||
|
||||
$this->assertEqual($num_records, 6, 'Returned the correct number of total rows.');
|
||||
|
|
@ -108,7 +108,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests GROUP BY and HAVING clauses together.
|
||||
*/
|
||||
function testGroupByAndHaving() {
|
||||
public function testGroupByAndHaving() {
|
||||
$query = db_select('test_task', 't');
|
||||
$count_field = $query->addExpression('COUNT(task)', 'num');
|
||||
$task_field = $query->addField('t', 'task');
|
||||
|
|
@ -119,7 +119,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
|
||||
$num_records = 0;
|
||||
$last_count = 0;
|
||||
$records = array();
|
||||
$records = [];
|
||||
foreach ($result as $record) {
|
||||
$num_records++;
|
||||
$this->assertTrue($record->$count_field >= 2, 'Record has the minimum count.');
|
||||
|
|
@ -128,12 +128,12 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
$records[$record->$task_field] = $record->$count_field;
|
||||
}
|
||||
|
||||
$correct_results = array(
|
||||
$correct_results = [
|
||||
'sleep' => 2,
|
||||
);
|
||||
];
|
||||
|
||||
foreach ($correct_results as $task => $count) {
|
||||
$this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", array('@task' => $task)));
|
||||
$this->assertEqual($records[$task], $count, format_string("Correct number of '@task' records found.", ['@task' => $task]));
|
||||
}
|
||||
|
||||
$this->assertEqual($num_records, 1, 'Returned the correct number of total rows.');
|
||||
|
|
@ -144,7 +144,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
*
|
||||
* The SQL clause varies with the database.
|
||||
*/
|
||||
function testRange() {
|
||||
public function testRange() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -157,7 +157,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Test whether the range property of a select clause can be undone.
|
||||
*/
|
||||
function testRangeUndo() {
|
||||
public function testRangeUndo() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -171,7 +171,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests distinct queries.
|
||||
*/
|
||||
function testDistinct() {
|
||||
public function testDistinct() {
|
||||
$query = db_select('test_task');
|
||||
$query->addField('test_task', 'task');
|
||||
$query->distinct();
|
||||
|
|
@ -183,7 +183,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can generate a count query from a built query.
|
||||
*/
|
||||
function testCountQuery() {
|
||||
public function testCountQuery() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -203,7 +203,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests having queries.
|
||||
*/
|
||||
function testHavingCountQuery() {
|
||||
public function testHavingCountQuery() {
|
||||
$query = db_select('test')
|
||||
->extend('Drupal\Core\Database\Query\PagerSelectExtender')
|
||||
->groupBy('age')
|
||||
|
|
@ -217,7 +217,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that countQuery removes 'all_fields' statements and ordering clauses.
|
||||
*/
|
||||
function testCountQueryRemovals() {
|
||||
public function testCountQueryRemovals() {
|
||||
$query = db_select('test');
|
||||
$query->fields('test');
|
||||
$query->orderBy('name');
|
||||
|
|
@ -248,14 +248,14 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that countQuery properly removes fields and expressions.
|
||||
*/
|
||||
function testCountQueryFieldRemovals() {
|
||||
public function testCountQueryFieldRemovals() {
|
||||
// countQuery should remove all fields and expressions, so this can be
|
||||
// tested by adding a non-existent field and expression: if it ends
|
||||
// up in the query, an error will be thrown. If not, it will return the
|
||||
// number of records, which in this case happens to be 4 (there are four
|
||||
// records in the {test} table).
|
||||
$query = db_select('test');
|
||||
$query->fields('test', array('fail'));
|
||||
$query->fields('test', ['fail']);
|
||||
$this->assertEqual(4, $query->countQuery()->execute()->fetchField(), 'Count Query removed fields');
|
||||
|
||||
$query = db_select('test');
|
||||
|
|
@ -266,7 +266,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can generate a count query from a query with distinct.
|
||||
*/
|
||||
function testCountQueryDistinct() {
|
||||
public function testCountQueryDistinct() {
|
||||
$query = db_select('test_task');
|
||||
$query->addField('test_task', 'task');
|
||||
$query->distinct();
|
||||
|
|
@ -279,7 +279,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can generate a count query from a query with GROUP BY.
|
||||
*/
|
||||
function testCountQueryGroupBy() {
|
||||
public function testCountQueryGroupBy() {
|
||||
$query = db_select('test_task');
|
||||
$query->addField('test_task', 'pid');
|
||||
$query->groupBy('pid');
|
||||
|
|
@ -304,7 +304,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can properly nest conditional clauses.
|
||||
*/
|
||||
function testNestedConditions() {
|
||||
public function testNestedConditions() {
|
||||
// This query should translate to:
|
||||
// "SELECT job FROM {test} WHERE name = 'Paul' AND (age = 26 OR age = 27)"
|
||||
// That should find only one record. Yes it's a non-optimal way of writing
|
||||
|
|
@ -321,7 +321,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms we can join on a single table twice with a dynamic alias.
|
||||
*/
|
||||
function testJoinTwice() {
|
||||
public function testJoinTwice() {
|
||||
$query = db_select('test')->fields('test');
|
||||
$alias = $query->join('test', 'test', 'test.job = %alias.job');
|
||||
$query->addField($alias, 'name', 'othername');
|
||||
|
|
@ -335,7 +335,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can join on a query.
|
||||
*/
|
||||
function testJoinSubquery() {
|
||||
public function testJoinSubquery() {
|
||||
$this->installSchema('system', 'sequences');
|
||||
|
||||
$account = User::create([
|
||||
|
|
@ -343,7 +343,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
'mail' => $this->randomMachineName() . '@example.com',
|
||||
]);
|
||||
|
||||
$query = db_select('test_task', 'tt', array('target' => 'replica'));
|
||||
$query = db_select('test_task', 'tt', ['target' => 'replica']);
|
||||
$query->addExpression('tt.pid + 1', 'abc');
|
||||
$query->condition('priority', 1, '>');
|
||||
$query->condition('priority', 100, '<');
|
||||
|
|
@ -375,7 +375,7 @@ class SelectComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that rowCount() throws exception on SELECT query.
|
||||
*/
|
||||
function testSelectWithRowCount() {
|
||||
public function testSelectWithRowCount() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$result = $query->execute();
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ class SelectOrderedTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests basic ORDER BY.
|
||||
*/
|
||||
function testSimpleSelectOrdered() {
|
||||
public function testSimpleSelectOrdered() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -33,7 +33,7 @@ class SelectOrderedTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests multiple ORDER BY.
|
||||
*/
|
||||
function testSimpleSelectMultiOrdered() {
|
||||
public function testSimpleSelectMultiOrdered() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -43,12 +43,12 @@ class SelectOrderedTest extends DatabaseTestBase {
|
|||
$result = $query->execute();
|
||||
|
||||
$num_records = 0;
|
||||
$expected = array(
|
||||
array('Ringo', 28, 'Drummer'),
|
||||
array('John', 25, 'Singer'),
|
||||
array('George', 27, 'Singer'),
|
||||
array('Paul', 26, 'Songwriter'),
|
||||
);
|
||||
$expected = [
|
||||
['Ringo', 28, 'Drummer'],
|
||||
['John', 25, 'Singer'],
|
||||
['George', 27, 'Singer'],
|
||||
['Paul', 26, 'Songwriter'],
|
||||
];
|
||||
$results = $result->fetchAll(\PDO::FETCH_NUM);
|
||||
foreach ($expected as $k => $record) {
|
||||
$num_records++;
|
||||
|
|
@ -64,7 +64,7 @@ class SelectOrderedTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests ORDER BY descending.
|
||||
*/
|
||||
function testSimpleSelectOrderedDesc() {
|
||||
public function testSimpleSelectOrderedDesc() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can use a subquery in a FROM clause.
|
||||
*/
|
||||
function testFromSubquerySelect() {
|
||||
public function testFromSubquerySelect() {
|
||||
// Create a subquery, which is just a normal query object.
|
||||
$subquery = db_select('test_task', 'tt');
|
||||
$subquery->addField('tt', 'pid', 'pid');
|
||||
|
|
@ -39,14 +39,14 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
// WHERE tt.task = 'code'
|
||||
$people = $select->execute()->fetchCol();
|
||||
|
||||
$this->assertEqual(count($people), 1, 'Returned the correct number of rows.');
|
||||
$this->assertCount(1, $people, 'Returned the correct number of rows.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can use a subquery in a FROM clause with a LIMIT.
|
||||
*/
|
||||
function testFromSubquerySelectWithLimit() {
|
||||
public function testFromSubquerySelectWithLimit() {
|
||||
// Create a subquery, which is just a normal query object.
|
||||
$subquery = db_select('test_task', 'tt');
|
||||
$subquery->addField('tt', 'pid', 'pid');
|
||||
|
|
@ -66,13 +66,13 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
// INNER JOIN test t ON t.id=tt.pid
|
||||
$people = $select->execute()->fetchCol();
|
||||
|
||||
$this->assertEqual(count($people), 1, 'Returned the correct number of rows.');
|
||||
$this->assertCount(1, $people, 'Returned the correct number of rows.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can use a subquery in a WHERE clause.
|
||||
* Tests that we can use a subquery with an IN operator in a WHERE clause.
|
||||
*/
|
||||
function testConditionSubquerySelect() {
|
||||
public function testConditionSubquerySelect() {
|
||||
// Create a subquery, which is just a normal query object.
|
||||
$subquery = db_select('test_task', 'tt');
|
||||
$subquery->addField('tt', 'pid', 'pid');
|
||||
|
|
@ -89,13 +89,98 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
// FROM test tt2
|
||||
// WHERE tt2.pid IN (SELECT tt.pid AS pid FROM test_task tt WHERE tt.priority=1)
|
||||
$people = $select->execute()->fetchCol();
|
||||
$this->assertEqual(count($people), 5, 'Returned the correct number of rows.');
|
||||
$this->assertCount(5, $people, 'Returned the correct number of rows.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that we can use a subquery with a relational operator in a WHERE clause.
|
||||
*/
|
||||
public function testConditionSubquerySelect2() {
|
||||
// Create a subquery, which is just a normal query object.
|
||||
$subquery = db_select('test', 't2');
|
||||
$subquery->addExpression('AVG(t2.age)');
|
||||
|
||||
// Create another query that adds a clause using the subquery.
|
||||
$select = db_select('test', 't');
|
||||
$select->addField('t', 'name');
|
||||
$select->condition('t.age', $subquery, '<');
|
||||
|
||||
// The resulting query should be equivalent to:
|
||||
// SELECT t.name
|
||||
// FROM test t
|
||||
// WHERE t.age < (SELECT AVG(t2.age) FROM test t2)
|
||||
$people = $select->execute()->fetchCol();
|
||||
$this->assertEquals(['John', 'Paul'], $people, 'Returned Paul and John.', 0.0, 10, TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that we can use 2 subqueries with a relational operator in a WHERE clause.
|
||||
*/
|
||||
public function testConditionSubquerySelect3() {
|
||||
// Create subquery 1, which is just a normal query object.
|
||||
$subquery1 = db_select('test_task', 'tt');
|
||||
$subquery1->addExpression('AVG(tt.priority)');
|
||||
$subquery1->where('tt.pid = t.id');
|
||||
|
||||
// Create subquery 2, which is just a normal query object.
|
||||
$subquery2 = db_select('test_task', 'tt2');
|
||||
$subquery2->addExpression('AVG(tt2.priority)');
|
||||
|
||||
// Create another query that adds a clause using the subqueries.
|
||||
$select = db_select('test', 't');
|
||||
$select->addField('t', 'name');
|
||||
$select->condition($subquery1, $subquery2, '>');
|
||||
|
||||
// The resulting query should be equivalent to:
|
||||
// SELECT t.name
|
||||
// FROM test t
|
||||
// WHERE (SELECT AVG(tt.priority) FROM test_task tt WHERE tt.pid = t.id) > (SELECT AVG(tt2.priority) FROM test_task tt2)
|
||||
$people = $select->execute()->fetchCol();
|
||||
$this->assertEquals(['John'], $people, 'Returned John.', 0.0, 10, TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that we can use multiple subqueries.
|
||||
*
|
||||
* This test uses a subquery at the left hand side and multiple subqueries at
|
||||
* the right hand side. The test query may not be that logical but that's due
|
||||
* to the limited amount of data and tables. 'Valid' use cases do exist :)
|
||||
*/
|
||||
public function testConditionSubquerySelect4() {
|
||||
// Create subquery 1, which is just a normal query object.
|
||||
$subquery1 = db_select('test_task', 'tt');
|
||||
$subquery1->addExpression('AVG(tt.priority)');
|
||||
$subquery1->where('tt.pid = t.id');
|
||||
|
||||
// Create subquery 2, which is just a normal query object.
|
||||
$subquery2 = db_select('test_task', 'tt2');
|
||||
$subquery2->addExpression('MIN(tt2.priority)');
|
||||
$subquery2->where('tt2.pid <> t.id');
|
||||
|
||||
// Create subquery 3, which is just a normal query object.
|
||||
$subquery3 = db_select('test_task', 'tt3');
|
||||
$subquery3->addExpression('AVG(tt3.priority)');
|
||||
$subquery3->where('tt3.pid <> t.id');
|
||||
|
||||
// Create another query that adds a clause using the subqueries.
|
||||
$select = db_select('test', 't');
|
||||
$select->addField('t', 'name');
|
||||
$select->condition($subquery1, [$subquery2, $subquery3], 'BETWEEN');
|
||||
|
||||
// The resulting query should be equivalent to:
|
||||
// SELECT t.name AS name
|
||||
// FROM {test} t
|
||||
// WHERE (SELECT AVG(tt.priority) AS expression FROM {test_task} tt WHERE (tt.pid = t.id))
|
||||
// BETWEEN (SELECT MIN(tt2.priority) AS expression FROM {test_task} tt2 WHERE (tt2.pid <> t.id))
|
||||
// AND (SELECT AVG(tt3.priority) AS expression FROM {test_task} tt3 WHERE (tt3.pid <> t.id));
|
||||
$people = $select->execute()->fetchCol();
|
||||
$this->assertEquals(['George', 'Paul'], $people, 'Returned George and Paul.', 0.0, 10, TRUE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that we can use a subquery in a JOIN clause.
|
||||
*/
|
||||
function testJoinSubquerySelect() {
|
||||
public function testJoinSubquerySelect() {
|
||||
// Create a subquery, which is just a normal query object.
|
||||
$subquery = db_select('test_task', 'tt');
|
||||
$subquery->addField('tt', 'pid', 'pid');
|
||||
|
|
@ -113,7 +198,7 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
// INNER JOIN (SELECT tt.pid AS pid FROM test_task tt WHERE priority=1) tt ON t.id=tt.pid
|
||||
$people = $select->execute()->fetchCol();
|
||||
|
||||
$this->assertEqual(count($people), 2, 'Returned the correct number of rows.');
|
||||
$this->assertCount(2, $people, 'Returned the correct number of rows.');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -122,28 +207,28 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
* We essentially select all rows from the {test} table that have matching
|
||||
* rows in the {test_people} table based on the shared name column.
|
||||
*/
|
||||
function testExistsSubquerySelect() {
|
||||
public function testExistsSubquerySelect() {
|
||||
// Put George into {test_people}.
|
||||
db_insert('test_people')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'George',
|
||||
'age' => 27,
|
||||
'job' => 'Singer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
// Base query to {test}.
|
||||
$query = db_select('test', 't')
|
||||
->fields('t', array('name'));
|
||||
->fields('t', ['name']);
|
||||
// Subquery to {test_people}.
|
||||
$subquery = db_select('test_people', 'tp')
|
||||
->fields('tp', array('name'))
|
||||
->fields('tp', ['name'])
|
||||
->where('tp.name = t.name');
|
||||
$query->exists($subquery);
|
||||
$result = $query->execute();
|
||||
|
||||
// Ensure that we got the right record.
|
||||
$record = $result->fetch();
|
||||
$this->assertEqual($record->name, 'George', 'Fetched name is correct using EXISTS query.');
|
||||
$this->assertEquals('George', $record->name, 'Fetched name is correct using EXISTS query.');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -152,28 +237,28 @@ class SelectSubqueryTest extends DatabaseTestBase {
|
|||
* We essentially select all rows from the {test} table that don't have
|
||||
* matching rows in the {test_people} table based on the shared name column.
|
||||
*/
|
||||
function testNotExistsSubquerySelect() {
|
||||
public function testNotExistsSubquerySelect() {
|
||||
// Put George into {test_people}.
|
||||
db_insert('test_people')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'George',
|
||||
'age' => 27,
|
||||
'job' => 'Singer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
// Base query to {test}.
|
||||
$query = db_select('test', 't')
|
||||
->fields('t', array('name'));
|
||||
->fields('t', ['name']);
|
||||
// Subquery to {test_people}.
|
||||
$subquery = db_select('test_people', 'tp')
|
||||
->fields('tp', array('name'))
|
||||
->fields('tp', ['name'])
|
||||
->where('tp.name = t.name');
|
||||
$query->notExists($subquery);
|
||||
|
||||
// Ensure that we got the right number of records.
|
||||
$people = $query->execute()->fetchCol();
|
||||
$this->assertEqual(count($people), 3, 'NOT EXISTS query returned the correct results.');
|
||||
$this->assertCount(3, $people, 'NOT EXISTS query returned the correct results.');
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests rudimentary SELECT statements.
|
||||
*/
|
||||
function testSimpleSelect() {
|
||||
public function testSimpleSelect() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -26,7 +26,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests rudimentary SELECT statement with a COMMENT.
|
||||
*/
|
||||
function testSimpleComment() {
|
||||
public function testSimpleComment() {
|
||||
$query = db_select('test')->comment('Testing query comments');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -44,7 +44,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests query COMMENT system against vulnerabilities.
|
||||
*/
|
||||
function testVulnerableComment() {
|
||||
public function testVulnerableComment() {
|
||||
$query = db_select('test')->comment('Testing query comments */ SELECT nid FROM {node}; --');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -68,7 +68,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Provides expected and input values for testVulnerableComment().
|
||||
*/
|
||||
function makeCommentsProvider() {
|
||||
public function makeCommentsProvider() {
|
||||
return [
|
||||
[
|
||||
'/* */ ',
|
||||
|
|
@ -99,7 +99,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests basic conditionals on SELECT statements.
|
||||
*/
|
||||
function testSimpleSelectConditional() {
|
||||
public function testSimpleSelectConditional() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addField('test', 'age', 'age');
|
||||
|
|
@ -119,7 +119,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests SELECT statements with expressions.
|
||||
*/
|
||||
function testSimpleSelectExpression() {
|
||||
public function testSimpleSelectExpression() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_field = $query->addExpression("age*2", 'double_age');
|
||||
|
|
@ -139,7 +139,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests SELECT statements with multiple expressions.
|
||||
*/
|
||||
function testSimpleSelectExpressionMultiple() {
|
||||
public function testSimpleSelectExpressionMultiple() {
|
||||
$query = db_select('test');
|
||||
$name_field = $query->addField('test', 'name');
|
||||
$age_double_field = $query->addExpression("age*2");
|
||||
|
|
@ -161,9 +161,9 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests adding multiple fields to a SELECT statement at the same time.
|
||||
*/
|
||||
function testSimpleSelectMultipleFields() {
|
||||
public function testSimpleSelectMultipleFields() {
|
||||
$record = db_select('test')
|
||||
->fields('test', array('id', 'name', 'age', 'job'))
|
||||
->fields('test', ['id', 'name', 'age', 'job'])
|
||||
->condition('age', 27)
|
||||
->execute()->fetchObject();
|
||||
|
||||
|
|
@ -184,7 +184,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests adding all fields from a given table to a SELECT statement.
|
||||
*/
|
||||
function testSimpleSelectAllFields() {
|
||||
public function testSimpleSelectAllFields() {
|
||||
$record = db_select('test')
|
||||
->fields('test')
|
||||
->condition('age', 27)
|
||||
|
|
@ -207,11 +207,11 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that a comparison with NULL is always FALSE.
|
||||
*/
|
||||
function testNullCondition() {
|
||||
public function testNullCondition() {
|
||||
$this->ensureSampleDataNull();
|
||||
|
||||
$names = db_select('test_null', 'tn')
|
||||
->fields('tn', array('name'))
|
||||
->fields('tn', ['name'])
|
||||
->condition('age', NULL)
|
||||
->execute()->fetchCol();
|
||||
|
||||
|
|
@ -221,11 +221,11 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can find a record with a NULL value.
|
||||
*/
|
||||
function testIsNullCondition() {
|
||||
public function testIsNullCondition() {
|
||||
$this->ensureSampleDataNull();
|
||||
|
||||
$names = db_select('test_null', 'tn')
|
||||
->fields('tn', array('name'))
|
||||
->fields('tn', ['name'])
|
||||
->isNull('age')
|
||||
->execute()->fetchCol();
|
||||
|
||||
|
|
@ -236,11 +236,11 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can find a record without a NULL value.
|
||||
*/
|
||||
function testIsNotNullCondition() {
|
||||
public function testIsNotNullCondition() {
|
||||
$this->ensureSampleDataNull();
|
||||
|
||||
$names = db_select('test_null', 'tn')
|
||||
->fields('tn', array('name'))
|
||||
->fields('tn', ['name'])
|
||||
->isNotNull('tn.age')
|
||||
->orderBy('name')
|
||||
->execute()->fetchCol();
|
||||
|
|
@ -256,13 +256,13 @@ class SelectTest extends DatabaseTestBase {
|
|||
* This is semantically equal to UNION DISTINCT, so we don't explicitly test
|
||||
* that.
|
||||
*/
|
||||
function testUnion() {
|
||||
public function testUnion() {
|
||||
$query_1 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->condition('age', array(27, 28), 'IN');
|
||||
->fields('t', ['name'])
|
||||
->condition('age', [27, 28], 'IN');
|
||||
|
||||
$query_2 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->fields('t', ['name'])
|
||||
->condition('age', 28);
|
||||
|
||||
$query_1->union($query_2);
|
||||
|
|
@ -279,13 +279,13 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can UNION ALL multiple SELECT queries together.
|
||||
*/
|
||||
function testUnionAll() {
|
||||
public function testUnionAll() {
|
||||
$query_1 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->condition('age', array(27, 28), 'IN');
|
||||
->fields('t', ['name'])
|
||||
->condition('age', [27, 28], 'IN');
|
||||
|
||||
$query_2 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->fields('t', ['name'])
|
||||
->condition('age', 28);
|
||||
|
||||
$query_1->union($query_2, 'ALL');
|
||||
|
|
@ -303,13 +303,13 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can get a count query for a UNION Select query.
|
||||
*/
|
||||
function testUnionCount() {
|
||||
public function testUnionCount() {
|
||||
$query_1 = db_select('test', 't')
|
||||
->fields('t', array('name', 'age'))
|
||||
->condition('age', array(27, 28), 'IN');
|
||||
->fields('t', ['name', 'age'])
|
||||
->condition('age', [27, 28], 'IN');
|
||||
|
||||
$query_2 = db_select('test', 't')
|
||||
->fields('t', array('name', 'age'))
|
||||
->fields('t', ['name', 'age'])
|
||||
->condition('age', 28);
|
||||
|
||||
$query_1->union($query_2, 'ALL');
|
||||
|
|
@ -325,15 +325,15 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can UNION multiple Select queries together and set the ORDER.
|
||||
*/
|
||||
function testUnionOrder() {
|
||||
public function testUnionOrder() {
|
||||
// This gives George and Ringo.
|
||||
$query_1 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->condition('age', array(27, 28), 'IN');
|
||||
->fields('t', ['name'])
|
||||
->condition('age', [27, 28], 'IN');
|
||||
|
||||
// This gives Paul.
|
||||
$query_2 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->fields('t', ['name'])
|
||||
->condition('age', 26);
|
||||
|
||||
$query_1->union($query_2);
|
||||
|
|
@ -354,15 +354,15 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that we can UNION multiple Select queries together with and a LIMIT.
|
||||
*/
|
||||
function testUnionOrderLimit() {
|
||||
public function testUnionOrderLimit() {
|
||||
// This gives George and Ringo.
|
||||
$query_1 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->condition('age', array(27, 28), 'IN');
|
||||
->fields('t', ['name'])
|
||||
->condition('age', [27, 28], 'IN');
|
||||
|
||||
// This gives Paul.
|
||||
$query_2 = db_select('test', 't')
|
||||
->fields('t', array('name'))
|
||||
->fields('t', ['name'])
|
||||
->condition('age', 26);
|
||||
|
||||
$query_1->union($query_2);
|
||||
|
|
@ -395,19 +395,19 @@ class SelectTest extends DatabaseTestBase {
|
|||
* order each time, the only way this could happen is if we have successfully
|
||||
* triggered the database's random ordering functionality.
|
||||
*/
|
||||
function testRandomOrder() {
|
||||
public function testRandomOrder() {
|
||||
// Use 52 items, so the chance that this test fails by accident will be the
|
||||
// same as the chance that a deck of cards will come out in the same order
|
||||
// after shuffling it (in other words, nearly impossible).
|
||||
$number_of_items = 52;
|
||||
while (db_query("SELECT MAX(id) FROM {test}")->fetchField() < $number_of_items) {
|
||||
db_insert('test')->fields(array('name' => $this->randomMachineName()))->execute();
|
||||
db_insert('test')->fields(['name' => $this->randomMachineName()])->execute();
|
||||
}
|
||||
|
||||
// First select the items in order and make sure we get an ordered list.
|
||||
$expected_ids = range(1, $number_of_items);
|
||||
$ordered_ids = db_select('test', 't')
|
||||
->fields('t', array('id'))
|
||||
->fields('t', ['id'])
|
||||
->range(0, $number_of_items)
|
||||
->orderBy('id')
|
||||
->execute()
|
||||
|
|
@ -418,7 +418,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
// expect this to contain a differently ordered version of the original
|
||||
// result.
|
||||
$randomized_ids = db_select('test', 't')
|
||||
->fields('t', array('id'))
|
||||
->fields('t', ['id'])
|
||||
->range(0, $number_of_items)
|
||||
->orderRandom()
|
||||
->execute()
|
||||
|
|
@ -431,7 +431,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
// Now perform the exact same query again, and make sure the order is
|
||||
// different.
|
||||
$randomized_ids_second_set = db_select('test', 't')
|
||||
->fields('t', array('id'))
|
||||
->fields('t', ['id'])
|
||||
->range(0, $number_of_items)
|
||||
->orderRandom()
|
||||
->execute()
|
||||
|
|
@ -447,24 +447,24 @@ class SelectTest extends DatabaseTestBase {
|
|||
*/
|
||||
public function testRegexCondition() {
|
||||
|
||||
$test_groups[] = array(
|
||||
$test_groups[] = [
|
||||
'regex' => 'hn$',
|
||||
'expected' => array(
|
||||
'expected' => [
|
||||
'John',
|
||||
),
|
||||
);
|
||||
$test_groups[] = array(
|
||||
],
|
||||
];
|
||||
$test_groups[] = [
|
||||
'regex' => '^Pau',
|
||||
'expected' => array(
|
||||
'expected' => [
|
||||
'Paul',
|
||||
),
|
||||
);
|
||||
$test_groups[] = array(
|
||||
],
|
||||
];
|
||||
$test_groups[] = [
|
||||
'regex' => 'Ringo|George',
|
||||
'expected' => array(
|
||||
'expected' => [
|
||||
'Ringo', 'George',
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
|
||||
$database = $this->container->get('database');
|
||||
|
|
@ -480,25 +480,25 @@ class SelectTest extends DatabaseTestBase {
|
|||
|
||||
// Ensure that filter by "#" still works due to the quoting.
|
||||
$database->insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Pete',
|
||||
'age' => 26,
|
||||
'job' => '#Drummer',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$test_groups = array();
|
||||
$test_groups[] = array(
|
||||
$test_groups = [];
|
||||
$test_groups[] = [
|
||||
'regex' => '#Drummer',
|
||||
'expected' => array(
|
||||
'expected' => [
|
||||
'Pete',
|
||||
),
|
||||
);
|
||||
$test_groups[] = array(
|
||||
],
|
||||
];
|
||||
$test_groups[] = [
|
||||
'regex' => '#Singer',
|
||||
'expected' => array(
|
||||
),
|
||||
);
|
||||
'expected' => [
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($test_groups as $test_group) {
|
||||
$query = $database->select('test', 't');
|
||||
|
|
@ -509,12 +509,19 @@ class SelectTest extends DatabaseTestBase {
|
|||
$this->assertEqual(count($result), count($test_group['expected']), 'Returns the expected number of rows.');
|
||||
$this->assertEqual(sort($result), sort($test_group['expected']), 'Returns the expected rows.');
|
||||
}
|
||||
|
||||
// Ensure that REGEXP filter still works with no-string type field.
|
||||
$query = $database->select('test', 't');
|
||||
$query->addField('t', 'age');
|
||||
$query->condition('t.age', '2[6]', 'REGEXP');
|
||||
$result = $query->execute()->fetchField();
|
||||
$this->assertEquals($result, '26', 'Regexp with number type.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that aliases are renamed when they are duplicates.
|
||||
*/
|
||||
function testSelectDuplicateAlias() {
|
||||
public function testSelectDuplicateAlias() {
|
||||
$query = db_select('test', 't');
|
||||
$alias1 = $query->addField('t', 'name', 'the_alias');
|
||||
$alias2 = $query->addField('t', 'age', 'the_alias');
|
||||
|
|
@ -524,7 +531,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests that an invalid merge query throws an exception.
|
||||
*/
|
||||
function testInvalidSelectCount() {
|
||||
public function testInvalidSelectCount() {
|
||||
try {
|
||||
// This query will fail because the table does not exist.
|
||||
// Normally it would throw an exception but we are suppressing
|
||||
|
|
@ -559,11 +566,11 @@ class SelectTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests thrown exception for IN query conditions with an empty array.
|
||||
*/
|
||||
function testEmptyInCondition() {
|
||||
public function testEmptyInCondition() {
|
||||
try {
|
||||
db_select('test', 't')
|
||||
->fields('t')
|
||||
->condition('age', array(), 'IN')
|
||||
->condition('age', [], 'IN')
|
||||
->execute();
|
||||
|
||||
$this->fail('Expected exception not thrown');
|
||||
|
|
@ -575,7 +582,7 @@ class SelectTest extends DatabaseTestBase {
|
|||
try {
|
||||
db_select('test', 't')
|
||||
->fields('t')
|
||||
->condition('age', array(), 'NOT IN')
|
||||
->condition('age', [], 'NOT IN')
|
||||
->execute();
|
||||
|
||||
$this->fail('Expected exception not thrown');
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ class SerializeQueryTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that a query can be serialized and unserialized.
|
||||
*/
|
||||
function testSerializeQuery() {
|
||||
public function testSerializeQuery() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'age');
|
||||
$query->condition('name', 'Ringo');
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that a query has a tag added to it.
|
||||
*/
|
||||
function testHasTag() {
|
||||
public function testHasTag() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -29,7 +29,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests query tagging "has all of these tags" functionality.
|
||||
*/
|
||||
function testHasAllTags() {
|
||||
public function testHasAllTags() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -44,7 +44,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests query tagging "has at least one of these tags" functionality.
|
||||
*/
|
||||
function testHasAnyTag() {
|
||||
public function testHasAnyTag() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
|
@ -58,7 +58,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that an extended query has a tag added to it.
|
||||
*/
|
||||
function testExtenderHasTag() {
|
||||
public function testExtenderHasTag() {
|
||||
$query = db_select('test')
|
||||
->extend('Drupal\Core\Database\Query\SelectExtender');
|
||||
$query->addField('test', 'name');
|
||||
|
|
@ -73,7 +73,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests extended query tagging "has all of these tags" functionality.
|
||||
*/
|
||||
function testExtenderHasAllTags() {
|
||||
public function testExtenderHasAllTags() {
|
||||
$query = db_select('test')
|
||||
->extend('Drupal\Core\Database\Query\SelectExtender');
|
||||
$query->addField('test', 'name');
|
||||
|
|
@ -89,7 +89,7 @@ class TaggingTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests extended query tagging "has at least one of these tags" functionality.
|
||||
*/
|
||||
function testExtenderHasAnyTag() {
|
||||
public function testExtenderHasAnyTag() {
|
||||
$query = db_select('test')
|
||||
->extend('Drupal\Core\Database\Query\SelectExtender');
|
||||
$query->addField('test', 'name');
|
||||
|
|
@ -106,15 +106,15 @@ class TaggingTest extends DatabaseTestBase {
|
|||
*
|
||||
* This is how we pass additional context to alter hooks.
|
||||
*/
|
||||
function testMetaData() {
|
||||
public function testMetaData() {
|
||||
$query = db_select('test');
|
||||
$query->addField('test', 'name');
|
||||
$query->addField('test', 'age', 'age');
|
||||
|
||||
$data = array(
|
||||
$data = [
|
||||
'a' => 'A',
|
||||
'b' => 'B',
|
||||
);
|
||||
];
|
||||
|
||||
$query->addMetaData('test', $data);
|
||||
|
||||
|
|
|
|||
|
|
@ -58,10 +58,10 @@ class TransactionTest extends DatabaseTestBase {
|
|||
|
||||
// Insert a single row into the testing table.
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'David' . $suffix,
|
||||
'age' => '24',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$this->assertTrue($connection->inTransaction(), 'In transaction before calling nested transaction.');
|
||||
|
|
@ -75,8 +75,8 @@ class TransactionTest extends DatabaseTestBase {
|
|||
if ($rollback) {
|
||||
// Roll back the transaction, if requested.
|
||||
// This rollback should propagate to the last savepoint.
|
||||
$txn->rollback();
|
||||
$this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollback().');
|
||||
$txn->rollBack();
|
||||
$this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollBack().');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -108,25 +108,25 @@ class TransactionTest extends DatabaseTestBase {
|
|||
|
||||
// Insert a single row into the testing table.
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'Daniel' . $suffix,
|
||||
'age' => '19',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
$this->assertTrue($connection->inTransaction(), 'In transaction inside nested transaction.');
|
||||
|
||||
if ($ddl_statement) {
|
||||
$table = array(
|
||||
'fields' => array(
|
||||
'id' => array(
|
||||
$table = [
|
||||
'fields' => [
|
||||
'id' => [
|
||||
'type' => 'serial',
|
||||
'unsigned' => TRUE,
|
||||
'not null' => TRUE,
|
||||
),
|
||||
),
|
||||
'primary key' => array('id'),
|
||||
);
|
||||
],
|
||||
],
|
||||
'primary key' => ['id'],
|
||||
];
|
||||
db_create_table('database_test_1', $table);
|
||||
|
||||
$this->assertTrue($connection->inTransaction(), 'In transaction inside nested transaction.');
|
||||
|
|
@ -135,8 +135,8 @@ class TransactionTest extends DatabaseTestBase {
|
|||
if ($rollback) {
|
||||
// Roll back the transaction, if requested.
|
||||
// This rollback should propagate to the last savepoint.
|
||||
$txn->rollback();
|
||||
$this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollback().');
|
||||
$txn->rollBack();
|
||||
$this->assertTrue(($connection->transactionDepth() == $depth), 'Transaction has rolled back to the last savepoint after calling rollBack().');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -146,7 +146,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
* If the active connection does not support transactions, this test does
|
||||
* nothing.
|
||||
*/
|
||||
function testTransactionRollBackSupported() {
|
||||
public function testTransactionRollBackSupported() {
|
||||
// This test won't work right if transactions are not supported.
|
||||
if (!Database::getConnection()->supportsTransactions()) {
|
||||
return;
|
||||
|
|
@ -157,9 +157,9 @@ class TransactionTest extends DatabaseTestBase {
|
|||
|
||||
// Neither of the rows we inserted in the two transaction layers
|
||||
// should be present in the tables post-rollback.
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidB'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DavidB'])->fetchField();
|
||||
$this->assertNotIdentical($saved_age, '24', 'Cannot retrieve DavidB row after commit.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielB'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DanielB'])->fetchField();
|
||||
$this->assertNotIdentical($saved_age, '19', 'Cannot retrieve DanielB row after commit.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
|
|
@ -172,7 +172,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
*
|
||||
* If the active driver supports transactions, this test does nothing.
|
||||
*/
|
||||
function testTransactionRollBackNotSupported() {
|
||||
public function testTransactionRollBackNotSupported() {
|
||||
// This test won't work right if transactions are supported.
|
||||
if (Database::getConnection()->supportsTransactions()) {
|
||||
return;
|
||||
|
|
@ -183,9 +183,9 @@ class TransactionTest extends DatabaseTestBase {
|
|||
|
||||
// Because our current database claims to not support transactions,
|
||||
// the inserted rows should be present despite the attempt to roll back.
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidB'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DavidB'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '24', 'DavidB not rolled back, since transactions are not supported.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielB'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DanielB'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '19', 'DanielB not rolled back, since transactions are not supported.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
|
|
@ -199,15 +199,15 @@ class TransactionTest extends DatabaseTestBase {
|
|||
* The behavior of this test should be identical for connections that support
|
||||
* transactions and those that do not.
|
||||
*/
|
||||
function testCommittedTransaction() {
|
||||
public function testCommittedTransaction() {
|
||||
try {
|
||||
// Create two nested transactions. The changes should be committed.
|
||||
$this->transactionOuterLayer('A');
|
||||
|
||||
// Because we committed, both of the inserted rows should be present.
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DavidA'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DavidA'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '24', 'Can retrieve DavidA row after commit.');
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'DanielA'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'DanielA'])->fetchField();
|
||||
$this->assertIdentical($saved_age, '19', 'Can retrieve DanielA row after commit.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
|
|
@ -218,7 +218,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests the compatibility of transactions with DDL statements.
|
||||
*/
|
||||
function testTransactionWithDdlStatement() {
|
||||
public function testTransactionWithDdlStatement() {
|
||||
// First, test that a commit works normally, even with DDL statements.
|
||||
$transaction = db_transaction();
|
||||
$this->insertRow('row');
|
||||
|
|
@ -254,7 +254,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
unset($transaction2);
|
||||
$transaction3 = db_transaction();
|
||||
$this->insertRow('row');
|
||||
$transaction3->rollback();
|
||||
$transaction3->rollBack();
|
||||
unset($transaction3);
|
||||
unset($transaction);
|
||||
$this->assertRowAbsent('row');
|
||||
|
|
@ -267,7 +267,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$transaction = db_transaction();
|
||||
$this->insertRow('row');
|
||||
$this->executeDDLStatement();
|
||||
$transaction->rollback();
|
||||
$transaction->rollBack();
|
||||
unset($transaction);
|
||||
$this->assertRowAbsent('row');
|
||||
|
||||
|
|
@ -280,7 +280,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$transaction3 = db_transaction();
|
||||
$this->insertRow('row');
|
||||
unset($transaction3);
|
||||
$transaction->rollback();
|
||||
$transaction->rollBack();
|
||||
unset($transaction);
|
||||
$this->assertRowAbsent('row');
|
||||
}
|
||||
|
|
@ -293,7 +293,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$this->executeDDLStatement();
|
||||
// Rollback the outer transaction.
|
||||
try {
|
||||
$transaction->rollback();
|
||||
$transaction->rollBack();
|
||||
unset($transaction);
|
||||
// @TODO: an exception should be triggered here, but is not, because
|
||||
// "ROLLBACK" fails silently in MySQL if there is no transaction active.
|
||||
|
|
@ -311,9 +311,9 @@ class TransactionTest extends DatabaseTestBase {
|
|||
*/
|
||||
protected function insertRow($name) {
|
||||
db_insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => $name,
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
}
|
||||
|
||||
|
|
@ -322,16 +322,16 @@ class TransactionTest extends DatabaseTestBase {
|
|||
*/
|
||||
protected function executeDDLStatement() {
|
||||
static $count = 0;
|
||||
$table = array(
|
||||
'fields' => array(
|
||||
'id' => array(
|
||||
$table = [
|
||||
'fields' => [
|
||||
'id' => [
|
||||
'type' => 'serial',
|
||||
'unsigned' => TRUE,
|
||||
'not null' => TRUE,
|
||||
),
|
||||
),
|
||||
'primary key' => array('id'),
|
||||
);
|
||||
],
|
||||
],
|
||||
'primary key' => ['id'],
|
||||
];
|
||||
db_create_table('database_test_' . ++$count, $table);
|
||||
}
|
||||
|
||||
|
|
@ -351,11 +351,11 @@ class TransactionTest extends DatabaseTestBase {
|
|||
* @param $message
|
||||
* The message to log for the assertion.
|
||||
*/
|
||||
function assertRowPresent($name, $message = NULL) {
|
||||
public function assertRowPresent($name, $message = NULL) {
|
||||
if (!isset($message)) {
|
||||
$message = format_string('Row %name is present.', array('%name' => $name));
|
||||
$message = format_string('Row %name is present.', ['%name' => $name]);
|
||||
}
|
||||
$present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
|
||||
$present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', [':name' => $name])->fetchField();
|
||||
return $this->assertTrue($present, $message);
|
||||
}
|
||||
|
||||
|
|
@ -367,18 +367,18 @@ class TransactionTest extends DatabaseTestBase {
|
|||
* @param $message
|
||||
* The message to log for the assertion.
|
||||
*/
|
||||
function assertRowAbsent($name, $message = NULL) {
|
||||
public function assertRowAbsent($name, $message = NULL) {
|
||||
if (!isset($message)) {
|
||||
$message = format_string('Row %name is absent.', array('%name' => $name));
|
||||
$message = format_string('Row %name is absent.', ['%name' => $name]);
|
||||
}
|
||||
$present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', array(':name' => $name))->fetchField();
|
||||
$present = (boolean) db_query('SELECT 1 FROM {test} WHERE name = :name', [':name' => $name])->fetchField();
|
||||
return $this->assertFalse($present, $message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests transaction stacking, commit, and rollback.
|
||||
*/
|
||||
function testTransactionStacking() {
|
||||
public function testTransactionStacking() {
|
||||
// This test won't work right if transactions are not supported.
|
||||
if (!Database::getConnection()->supportsTransactions()) {
|
||||
return;
|
||||
|
|
@ -424,7 +424,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$transaction2 = db_transaction();
|
||||
$this->insertRow('inner');
|
||||
// Now rollback the inner transaction.
|
||||
$transaction2->rollback();
|
||||
$transaction2->rollBack();
|
||||
unset($transaction2);
|
||||
$this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction');
|
||||
// Pop the outer transaction, it should commit.
|
||||
|
|
@ -445,7 +445,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
unset($transaction);
|
||||
$this->assertTrue($database->inTransaction(), 'Still in a transaction after popping the outer transaction');
|
||||
// Now rollback the inner transaction, it should rollback.
|
||||
$transaction2->rollback();
|
||||
$transaction2->rollBack();
|
||||
unset($transaction2);
|
||||
$this->assertFalse($database->inTransaction(), 'Transaction closed after popping the inner transaction');
|
||||
$this->assertRowPresent('outer');
|
||||
|
|
@ -463,7 +463,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$this->insertRow('inner2');
|
||||
// Rollback the outer transaction.
|
||||
try {
|
||||
$transaction->rollback();
|
||||
$transaction->rollBack();
|
||||
unset($transaction);
|
||||
$this->fail('Rolling back the outer transaction while the inner transaction is active resulted in an exception.');
|
||||
}
|
||||
|
|
@ -476,7 +476,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
$this->pass('Trying to commit an inner transaction resulted in an exception.');
|
||||
// Try to rollback one inner transaction.
|
||||
try {
|
||||
$transaction->rollback();
|
||||
$transaction->rollBack();
|
||||
unset($transaction2);
|
||||
$this->fail('Trying to commit an inner transaction resulted in an exception.');
|
||||
}
|
||||
|
|
@ -498,7 +498,7 @@ class TransactionTest extends DatabaseTestBase {
|
|||
|
||||
// Test a failed query using the query() method.
|
||||
try {
|
||||
$connection->query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'David'))->fetchField();
|
||||
$connection->query('SELECT age FROM {test} WHERE name = :name', [':name' => 'David'])->fetchField();
|
||||
$this->fail('Using the query method failed.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
|
|
@ -594,16 +594,16 @@ class TransactionTest extends DatabaseTestBase {
|
|||
// Create the missing schema and insert a row.
|
||||
$this->installSchema('database_test', ['test']);
|
||||
$connection->insert('test')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'name' => 'David',
|
||||
'age' => '24',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
// Commit the transaction.
|
||||
unset($transaction);
|
||||
|
||||
$saved_age = $connection->query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'David'))->fetchField();
|
||||
$saved_age = $connection->query('SELECT age FROM {test} WHERE name = :name', [':name' => 'David'])->fetchField();
|
||||
$this->assertEqual('24', $saved_age);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,9 +12,9 @@ class UpdateComplexTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Tests updates with OR conditionals.
|
||||
*/
|
||||
function testOrConditionUpdate() {
|
||||
public function testOrConditionUpdate() {
|
||||
$update = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition(db_or()
|
||||
->condition('name', 'John')
|
||||
->condition('name', 'Paul')
|
||||
|
|
@ -22,112 +22,110 @@ class UpdateComplexTest extends DatabaseTestBase {
|
|||
$num_updated = $update->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests WHERE IN clauses.
|
||||
*/
|
||||
function testInConditionUpdate() {
|
||||
public function testInConditionUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->condition('name', array('John', 'Paul'), 'IN')
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('name', ['John', 'Paul'], 'IN')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests WHERE NOT IN clauses.
|
||||
*/
|
||||
function testNotInConditionUpdate() {
|
||||
public function testNotInConditionUpdate() {
|
||||
// The o is lowercase in the 'NoT IN' operator, to make sure the operators
|
||||
// work in mixed case.
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->condition('name', array('John', 'Paul', 'George'), 'NoT IN')
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('name', ['John', 'Paul', 'George'], 'NoT IN')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests BETWEEN conditional clauses.
|
||||
*/
|
||||
function testBetweenConditionUpdate() {
|
||||
public function testBetweenConditionUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->condition('age', array(25, 26), 'BETWEEN')
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('age', [25, 26], 'BETWEEN')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests LIKE conditionals.
|
||||
*/
|
||||
function testLikeConditionUpdate() {
|
||||
public function testLikeConditionUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('name', '%ge%', 'LIKE')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests UPDATE with expression values.
|
||||
*/
|
||||
function testUpdateExpression() {
|
||||
$before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
|
||||
$GLOBALS['larry_test'] = 1;
|
||||
public function testUpdateExpression() {
|
||||
$before_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchField();
|
||||
$num_updated = db_update('test')
|
||||
->condition('name', 'Ringo')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->expression('age', 'age + :age', array(':age' => 4))
|
||||
->fields(['job' => 'Musician'])
|
||||
->expression('age', 'age + :age', [':age' => 4])
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
|
||||
|
||||
$person = db_query('SELECT * FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetch();
|
||||
$person = db_query('SELECT * FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetch();
|
||||
$this->assertEqual($person->name, 'Ringo', 'Name set correctly.');
|
||||
$this->assertEqual($person->age, $before_age + 4, 'Age set correctly.');
|
||||
$this->assertEqual($person->job, 'Musician', 'Job set correctly.');
|
||||
$GLOBALS['larry_test'] = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests UPDATE with only expression values.
|
||||
*/
|
||||
function testUpdateOnlyExpression() {
|
||||
$before_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
|
||||
public function testUpdateOnlyExpression() {
|
||||
$before_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchField();
|
||||
$num_updated = db_update('test')
|
||||
->condition('name', 'Ringo')
|
||||
->expression('age', 'age + :age', array(':age' => 4))
|
||||
->expression('age', 'age + :age', [':age' => 4])
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
|
||||
$after_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchField();
|
||||
$this->assertEqual($before_age + 4, $after_age, 'Age updated correctly');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test UPDATE with a subselect value.
|
||||
*/
|
||||
function testSubSelectUpdate() {
|
||||
public function testSubSelectUpdate() {
|
||||
$subselect = db_select('test_task', 't');
|
||||
$subselect->addExpression('MAX(priority) + :increment', 'max_priority', array(':increment' => 30));
|
||||
$subselect->addExpression('MAX(priority) + :increment', 'max_priority', [':increment' => 30]);
|
||||
// Clone this to make sure we are running a different query when
|
||||
// asserting.
|
||||
$select = clone $subselect;
|
||||
|
|
@ -136,7 +134,7 @@ class UpdateComplexTest extends DatabaseTestBase {
|
|||
->condition('name', 'Ringo');
|
||||
// Save the number of rows that updated for assertion later.
|
||||
$num_updated = $query->execute();
|
||||
$after_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'Ringo'))->fetchField();
|
||||
$after_age = db_query('SELECT age FROM {test} WHERE name = :name', [':name' => 'Ringo'])->fetchField();
|
||||
$expected_age = $select->execute()->fetchField();
|
||||
$this->assertEqual($after_age, $expected_age);
|
||||
$this->assertEqual(1, $num_updated, t('Expected 1 row to be updated in subselect update query.'));
|
||||
|
|
|
|||
|
|
@ -12,40 +12,40 @@ class UpdateLobTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can update a blob column.
|
||||
*/
|
||||
function testUpdateOneBlob() {
|
||||
public function testUpdateOneBlob() {
|
||||
$data = "This is\000a test.";
|
||||
$this->assertTrue(strlen($data) === 15, 'Test data contains a NULL.');
|
||||
$id = db_insert('test_one_blob')
|
||||
->fields(array('blob1' => $data))
|
||||
->fields(['blob1' => $data])
|
||||
->execute();
|
||||
|
||||
$data .= $data;
|
||||
db_update('test_one_blob')
|
||||
->condition('id', $id)
|
||||
->fields(array('blob1' => $data))
|
||||
->fields(['blob1' => $data])
|
||||
->execute();
|
||||
|
||||
$r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', array(':id' => $id))->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === $data, format_string('Can update a blob: id @id, @data.', array('@id' => $id, '@data' => serialize($r))));
|
||||
$r = db_query('SELECT * FROM {test_one_blob} WHERE id = :id', [':id' => $id])->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === $data, format_string('Can update a blob: id @id, @data.', ['@id' => $id, '@data' => serialize($r)]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms that we can update two blob columns in the same table.
|
||||
*/
|
||||
function testUpdateMultipleBlob() {
|
||||
public function testUpdateMultipleBlob() {
|
||||
$id = db_insert('test_two_blobs')
|
||||
->fields(array(
|
||||
->fields([
|
||||
'blob1' => 'This is',
|
||||
'blob2' => 'a test',
|
||||
))
|
||||
])
|
||||
->execute();
|
||||
|
||||
db_update('test_two_blobs')
|
||||
->condition('id', $id)
|
||||
->fields(array('blob1' => 'and so', 'blob2' => 'is this'))
|
||||
->fields(['blob1' => 'and so', 'blob2' => 'is this'])
|
||||
->execute();
|
||||
|
||||
$r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', array(':id' => $id))->fetchAssoc();
|
||||
$r = db_query('SELECT * FROM {test_two_blobs} WHERE id = :id', [':id' => $id])->fetchAssoc();
|
||||
$this->assertTrue($r['blob1'] === 'and so' && $r['blob2'] === 'is this', 'Can update multiple blobs per row.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -12,93 +12,93 @@ class UpdateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirms that we can update a single record successfully.
|
||||
*/
|
||||
function testSimpleUpdate() {
|
||||
public function testSimpleUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('name' => 'Tiffany'))
|
||||
->fields(['name' => 'Tiffany'])
|
||||
->condition('id', 1)
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 1))->fetchField();
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE id = :id', [':id' => 1])->fetchField();
|
||||
$this->assertIdentical($saved_name, 'Tiffany', 'Updated name successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms updating to NULL.
|
||||
*/
|
||||
function testSimpleNullUpdate() {
|
||||
public function testSimpleNullUpdate() {
|
||||
$this->ensureSampleDataNull();
|
||||
$num_updated = db_update('test_null')
|
||||
->fields(array('age' => NULL))
|
||||
->fields(['age' => NULL])
|
||||
->condition('name', 'Kermit')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$saved_age = db_query('SELECT age FROM {test_null} WHERE name = :name', array(':name' => 'Kermit'))->fetchField();
|
||||
$saved_age = db_query('SELECT age FROM {test_null} WHERE name = :name', [':name' => 'Kermit'])->fetchField();
|
||||
$this->assertNull($saved_age, 'Updated name successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms that we can update multiple records successfully.
|
||||
*/
|
||||
function testMultiUpdate() {
|
||||
public function testMultiUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('job', 'Singer')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms that we can update multiple records with a non-equality condition.
|
||||
*/
|
||||
function testMultiGTUpdate() {
|
||||
public function testMultiGTUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->fields(['job' => 'Musician'])
|
||||
->condition('age', 26, '>')
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms that we can update multiple records with a where call.
|
||||
*/
|
||||
function testWhereUpdate() {
|
||||
public function testWhereUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->where('age > :age', array(':age' => 26))
|
||||
->fields(['job' => 'Musician'])
|
||||
->where('age > :age', [':age' => 26])
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 2, 'Updated 2 records.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '2', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms that we can stack condition and where calls.
|
||||
*/
|
||||
function testWhereAndConditionUpdate() {
|
||||
public function testWhereAndConditionUpdate() {
|
||||
$update = db_update('test')
|
||||
->fields(array('job' => 'Musician'))
|
||||
->where('age > :age', array(':age' => 26))
|
||||
->fields(['job' => 'Musician'])
|
||||
->where('age > :age', [':age' => 26])
|
||||
->condition('name', 'Ringo');
|
||||
$num_updated = $update->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', array(':job' => 'Musician'))->fetchField();
|
||||
$num_matches = db_query('SELECT COUNT(*) FROM {test} WHERE job = :job', [':job' => 'Musician'])->fetchField();
|
||||
$this->assertIdentical($num_matches, '1', 'Updated fields successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests updating with expressions.
|
||||
*/
|
||||
function testExpressionUpdate() {
|
||||
public function testExpressionUpdate() {
|
||||
// Ensure that expressions are handled properly. This should set every
|
||||
// record's age to a square of itself.
|
||||
$num_rows = db_update('test')
|
||||
|
|
@ -106,14 +106,14 @@ class UpdateTest extends DatabaseTestBase {
|
|||
->execute();
|
||||
$this->assertIdentical($num_rows, 4, 'Updated 4 records.');
|
||||
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE age = :age', array(':age' => pow(26, 2)))->fetchField();
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE age = :age', [':age' => pow(26, 2)])->fetchField();
|
||||
$this->assertIdentical($saved_name, 'Paul', 'Successfully updated values using an algebraic expression.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests return value on update.
|
||||
*/
|
||||
function testUpdateAffectedRows() {
|
||||
public function testUpdateAffectedRows() {
|
||||
// At 5am in the morning, all band members but those with a priority 1 task
|
||||
// are sleeping. So we set their tasks to 'sleep'. 5 records match the
|
||||
// condition and therefore are affected by the query, even though two of
|
||||
|
|
@ -122,7 +122,7 @@ class UpdateTest extends DatabaseTestBase {
|
|||
// because that's cross-db expected behavior.
|
||||
$num_rows = db_update('test_task')
|
||||
->condition('priority', 1, '<>')
|
||||
->fields(array('task' => 'sleep'))
|
||||
->fields(['task' => 'sleep'])
|
||||
->execute();
|
||||
$this->assertIdentical($num_rows, 5, 'Correctly returned 5 affected rows.');
|
||||
}
|
||||
|
|
@ -130,28 +130,28 @@ class UpdateTest extends DatabaseTestBase {
|
|||
/**
|
||||
* Confirm that we can update the primary key of a record successfully.
|
||||
*/
|
||||
function testPrimaryKeyUpdate() {
|
||||
public function testPrimaryKeyUpdate() {
|
||||
$num_updated = db_update('test')
|
||||
->fields(array('id' => 42, 'name' => 'John'))
|
||||
->fields(['id' => 42, 'name' => 'John'])
|
||||
->condition('id', 1)
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
|
||||
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 42))->fetchField();
|
||||
$saved_name = db_query('SELECT name FROM {test} WHERE id = :id', [':id' => 42])->fetchField();
|
||||
$this->assertIdentical($saved_name, 'John', 'Updated primary key successfully.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that we can update values in a column with special name.
|
||||
*/
|
||||
function testSpecialColumnUpdate() {
|
||||
public function testSpecialColumnUpdate() {
|
||||
$num_updated = db_update('test_special_columns')
|
||||
->fields(array('offset' => 'New offset value'))
|
||||
->fields(['offset' => 'New offset value'])
|
||||
->condition('id', 1)
|
||||
->execute();
|
||||
$this->assertIdentical($num_updated, 1, 'Updated 1 special column record.');
|
||||
|
||||
$saved_value = db_query('SELECT "offset" FROM {test_special_columns} WHERE id = :id', array(':id' => 1))->fetchField();
|
||||
$saved_value = db_query('SELECT "offset" FROM {test_special_columns} WHERE id = :id', [':id' => 1])->fetchField();
|
||||
$this->assertIdentical($saved_value, 'New offset value', 'Updated special column name value successfully.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -42,12 +42,12 @@ class UpsertTest extends DatabaseTestBase {
|
|||
$num_records_after = $connection->query('SELECT COUNT(*) FROM {test_people}')->fetchField();
|
||||
$this->assertEqual($num_records_before + 1, $num_records_after, 'Rows were inserted and updated properly.');
|
||||
|
||||
$person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Presenter'))->fetch();
|
||||
$person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Presenter'])->fetch();
|
||||
$this->assertEqual($person->job, 'Presenter', 'Job set correctly.');
|
||||
$this->assertEqual($person->age, 31, 'Age set correctly.');
|
||||
$this->assertEqual($person->name, 'Tiffany', 'Name set correctly.');
|
||||
|
||||
$person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', array(':job' => 'Speaker'))->fetch();
|
||||
$person = $connection->query('SELECT * FROM {test_people} WHERE job = :job', [':job' => 'Speaker'])->fetch();
|
||||
$this->assertEqual($person->job, 'Speaker', 'Job was not changed.');
|
||||
$this->assertEqual($person->age, 32, 'Age updated correctly.');
|
||||
$this->assertEqual($person->name, 'Meredith', 'Name was not changed.');
|
||||
|
|
|
|||
|
|
@ -51,6 +51,8 @@ class FormatDateTest extends KernelTestBase {
|
|||
public function testFormatDate() {
|
||||
/** @var \Drupal\Core\Datetime\DateFormatterInterface $formatter */
|
||||
$formatter = $this->container->get('date.formatter');
|
||||
/** @var \Drupal\Core\Language\LanguageManagerInterface $language_manager */
|
||||
$language_manager = $this->container->get('language_manager');
|
||||
|
||||
$timestamp = strtotime('2007-03-26T00:00:00+00:00');
|
||||
$this->assertSame('Sunday, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Test all parameters.');
|
||||
|
|
@ -59,6 +61,14 @@ class FormatDateTest extends KernelTestBase {
|
|||
$this->assertSame('\\domingo, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', '\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test format containing backslash character.');
|
||||
$this->assertSame('\\l, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', '\\\\\\l, d-M-y H:i:s T', 'America/Los_Angeles', self::LANGCODE), 'Test format containing backslash followed by escaped format string.');
|
||||
$this->assertSame('Monday, 26-Mar-07 01:00:00 BST', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London', 'en'), 'Test a different time zone.');
|
||||
$this->assertSame('Thu, 01/01/1970 - 00:00', $formatter->format(0, 'custom', '', 'UTC', 'en'), 'Test custom format with empty string.');
|
||||
|
||||
// Make sure we didn't change the configuration override language.
|
||||
$this->assertSame('en', $language_manager->getConfigOverrideLanguage()->getId(), 'Configuration override language not disturbed,');
|
||||
|
||||
// Test bad format string will use the fallback format.
|
||||
$this->assertSame($formatter->format($timestamp, 'fallback'), $formatter->format($timestamp, 'bad_format_string'), 'Test fallback format.');
|
||||
$this->assertSame('en', $language_manager->getConfigOverrideLanguage()->getId(), 'Configuration override language not disturbed,');
|
||||
|
||||
// Change the default language and timezone.
|
||||
$this->config('system.site')->set('default_langcode', static::LANGCODE)->save();
|
||||
|
|
@ -66,7 +76,8 @@ class FormatDateTest extends KernelTestBase {
|
|||
|
||||
// Reset the language manager so new negotiations attempts will fall back on
|
||||
// on the new language.
|
||||
$this->container->get('language_manager')->reset();
|
||||
$language_manager->reset();
|
||||
$this->assertSame('en', $language_manager->getConfigOverrideLanguage()->getId(), 'Configuration override language not disturbed,');
|
||||
|
||||
$this->assertSame('Sunday, 25-Mar-07 17:00:00 PDT', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'America/Los_Angeles', 'en'), 'Test a different language.');
|
||||
$this->assertSame('Monday, 26-Mar-07 01:00:00 BST', $formatter->format($timestamp, 'custom', 'l, d-M-y H:i:s T', 'Europe/London'), 'Test a different time zone.');
|
||||
|
|
@ -84,6 +95,13 @@ class FormatDateTest extends KernelTestBase {
|
|||
$this->assertSame('2007-03', $formatter->format($timestamp, 'html_month'), 'Test html_month date format.');
|
||||
$this->assertSame('2007', $formatter->format($timestamp, 'html_year'), 'Test html_year date format.');
|
||||
|
||||
// Make sure we didn't change the configuration override language.
|
||||
$this->assertSame('en', $language_manager->getConfigOverrideLanguage()->getId(), 'Configuration override language not disturbed,');
|
||||
|
||||
// Test bad format string will use the fallback format.
|
||||
$this->assertSame($formatter->format($timestamp, 'fallback'), $formatter->format($timestamp, 'bad_format_string'), 'Test fallback format.');
|
||||
$this->assertSame('en', $language_manager->getConfigOverrideLanguage()->getId(), 'Configuration override language not disturbed,');
|
||||
|
||||
// HTML is not escaped by the date formatter, it must be escaped later.
|
||||
$this->assertSame("<script>alert('2007');</script>", $formatter->format($timestamp, 'custom', '\<\s\c\r\i\p\t\>\a\l\e\r\t\(\'Y\'\)\;\<\/\s\c\r\i\p\t\>'), 'Script tags not removed from dates.');
|
||||
$this->assertSame('<em>2007</em>', $formatter->format($timestamp, 'custom', '\<\e\m\>Y\<\/\e\m\>'), 'Em tags are not removed from dates.');
|
||||
|
|
|
|||
|
|
@ -60,10 +60,10 @@ class DrupalKernelTest extends KernelTestBase {
|
|||
*/
|
||||
public function testCompileDIC() {
|
||||
// @todo: write a memory based storage backend for testing.
|
||||
$modules_enabled = array(
|
||||
$modules_enabled = [
|
||||
'system' => 'system',
|
||||
'user' => 'user',
|
||||
);
|
||||
];
|
||||
|
||||
$request = Request::createFromGlobals();
|
||||
$this->getTestKernel($request, $modules_enabled);
|
||||
|
|
@ -128,11 +128,11 @@ class DrupalKernelTest extends KernelTestBase {
|
|||
|
||||
// Check that the location of the new module is registered.
|
||||
$modules = $container->getParameter('container.modules');
|
||||
$this->assertEqual($modules['service_provider_test'], array(
|
||||
$this->assertEqual($modules['service_provider_test'], [
|
||||
'type' => 'module',
|
||||
'pathname' => drupal_get_filename('module', 'service_provider_test'),
|
||||
'filename' => NULL,
|
||||
));
|
||||
]);
|
||||
|
||||
// Check that the container itself is not among the persist IDs because it
|
||||
// does not make sense to persist the container itself.
|
||||
|
|
@ -169,10 +169,10 @@ class DrupalKernelTest extends KernelTestBase {
|
|||
*/
|
||||
public function testPreventChangeOfSitePath() {
|
||||
// @todo: write a memory based storage backend for testing.
|
||||
$modules_enabled = array(
|
||||
$modules_enabled = [
|
||||
'system' => 'system',
|
||||
'user' => 'user',
|
||||
);
|
||||
];
|
||||
|
||||
$request = Request::createFromGlobals();
|
||||
$kernel = $this->getTestKernel($request, $modules_enabled);
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ class ServiceDestructionTest extends KernelTestBase {
|
|||
*/
|
||||
public function testDestructionUsed() {
|
||||
// Enable the test module to add it to the container.
|
||||
$this->enableModules(array('service_provider_test'));
|
||||
$this->enableModules(['service_provider_test']);
|
||||
|
||||
$request = $this->container->get('request_stack')->getCurrentRequest();
|
||||
$kernel = $this->container->get('kernel');
|
||||
|
|
@ -39,7 +39,7 @@ class ServiceDestructionTest extends KernelTestBase {
|
|||
*/
|
||||
public function testDestructionUnused() {
|
||||
// Enable the test module to add it to the container.
|
||||
$this->enableModules(array('service_provider_test'));
|
||||
$this->enableModules(['service_provider_test']);
|
||||
|
||||
$request = $this->container->get('request_stack')->getCurrentRequest();
|
||||
$kernel = $this->container->get('kernel');
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'user');
|
||||
public static $modules = ['system', 'user'];
|
||||
|
||||
/**
|
||||
* Sets up the test.
|
||||
|
|
@ -41,16 +41,16 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
$this->installEntitySchema('user');
|
||||
\Drupal::service('router.builder')->rebuild();
|
||||
/** @var \Drupal\user\RoleInterface $role */
|
||||
$role = Role::create(array(
|
||||
$role = Role::create([
|
||||
'id' => 'admin',
|
||||
'label' => 'admin',
|
||||
));
|
||||
]);
|
||||
$role->grantPermission('link to any page');
|
||||
$role->save();
|
||||
$this->testUser = User::create(array(
|
||||
$this->testUser = User::create([
|
||||
'name' => 'foobar',
|
||||
'mail' => 'foobar@example.com',
|
||||
));
|
||||
]);
|
||||
$this->testUser->addRole($role->id());
|
||||
$this->testUser->save();
|
||||
\Drupal::service('current_user')->setAccount($this->testUser);
|
||||
|
|
@ -68,57 +68,57 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
// A required validated path.
|
||||
$form['required_validate'] = array(
|
||||
$form['required_validate'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => TRUE,
|
||||
'#title' => 'required_validate',
|
||||
'#convert_path' => PathElement::CONVERT_NONE,
|
||||
);
|
||||
];
|
||||
|
||||
// A non validated required path.
|
||||
$form['required_non_validate'] = array(
|
||||
$form['required_non_validate'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => TRUE,
|
||||
'#title' => 'required_non_validate',
|
||||
'#convert_path' => PathElement::CONVERT_NONE,
|
||||
'#validate_path' => FALSE,
|
||||
);
|
||||
];
|
||||
|
||||
// A non required validated path.
|
||||
$form['optional_validate'] = array(
|
||||
$form['optional_validate'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => FALSE,
|
||||
'#title' => 'optional_validate',
|
||||
'#convert_path' => PathElement::CONVERT_NONE,
|
||||
);
|
||||
];
|
||||
|
||||
// A non required converted path.
|
||||
$form['optional_validate'] = array(
|
||||
$form['optional_validate'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => FALSE,
|
||||
'#title' => 'optional_validate',
|
||||
'#convert_path' => PathElement::CONVERT_ROUTE,
|
||||
);
|
||||
];
|
||||
|
||||
// A converted required validated path.
|
||||
$form['required_validate_route'] = array(
|
||||
$form['required_validate_route'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => TRUE,
|
||||
'#title' => 'required_validate_route',
|
||||
);
|
||||
];
|
||||
|
||||
// A converted required validated path.
|
||||
$form['required_validate_url'] = array(
|
||||
$form['required_validate_url'] = [
|
||||
'#type' => 'path',
|
||||
'#required' => TRUE,
|
||||
'#title' => 'required_validate_url',
|
||||
'#convert_path' => PathElement::CONVERT_URL,
|
||||
);
|
||||
];
|
||||
|
||||
$form['submit'] = array(
|
||||
$form['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => t('Submit'),
|
||||
);
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
|
@ -154,19 +154,19 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
|
||||
// Valid form state.
|
||||
$this->assertEqual(count($form_state->getErrors()), 0);
|
||||
$this->assertEqual($form_state->getValue('required_validate_route'), array(
|
||||
$this->assertEqual($form_state->getValue('required_validate_route'), [
|
||||
'route_name' => 'entity.user.canonical',
|
||||
'route_parameters' => array(
|
||||
'route_parameters' => [
|
||||
'user' => $this->testUser->id(),
|
||||
),
|
||||
));
|
||||
],
|
||||
]);
|
||||
/** @var \Drupal\Core\Url $url */
|
||||
$url = $form_state->getValue('required_validate_url');
|
||||
$this->assertTrue($url instanceof Url);
|
||||
$this->assertEqual($url->getRouteName(), 'entity.user.canonical');
|
||||
$this->assertEqual($url->getRouteParameters(), array(
|
||||
$this->assertEqual($url->getRouteParameters(), [
|
||||
'user' => $this->testUser->id(),
|
||||
));
|
||||
]);
|
||||
|
||||
// Test #required.
|
||||
$form_state = (new FormState())
|
||||
|
|
@ -179,7 +179,7 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
$errors = $form_state->getErrors();
|
||||
// Should be missing 'required_validate' field.
|
||||
$this->assertEqual(count($errors), 1);
|
||||
$this->assertEqual($errors, array('required_validate' => t('@name field is required.', array('@name' => 'required_validate'))));
|
||||
$this->assertEqual($errors, ['required_validate' => t('@name field is required.', ['@name' => 'required_validate'])]);
|
||||
|
||||
// Test invalid parameters.
|
||||
$form_state = (new FormState())
|
||||
|
|
@ -195,11 +195,11 @@ class PathElementFormTest extends KernelTestBase implements FormInterface {
|
|||
// Valid form state.
|
||||
$errors = $form_state->getErrors();
|
||||
$this->assertEqual(count($errors), 3);
|
||||
$this->assertEqual($errors, array(
|
||||
'required_validate' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')),
|
||||
'required_validate_route' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')),
|
||||
'required_validate_url' => t('This path does not exist or you do not have permission to link to %path.', array('%path' => 'user/74')),
|
||||
));
|
||||
$this->assertEqual($errors, [
|
||||
'required_validate' => t('This path does not exist or you do not have permission to link to %path.', ['%path' => 'user/74']),
|
||||
'required_validate_route' => t('This path does not exist or you do not have permission to link to %path.', ['%path' => 'user/74']),
|
||||
'required_validate_url' => t('This path does not exist or you do not have permission to link to %path.', ['%path' => 'user/74']),
|
||||
]);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ class BundleConstraintValidatorTest extends KernelTestBase {
|
|||
*/
|
||||
protected $typedData;
|
||||
|
||||
public static $modules = array('node', 'field', 'text', 'user');
|
||||
public static $modules = ['node', 'field', 'text', 'user'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
|
@ -32,7 +32,7 @@ class BundleConstraintValidatorTest extends KernelTestBase {
|
|||
*/
|
||||
public function testValidation() {
|
||||
// Test with multiple values.
|
||||
$this->assertValidation(array('foo', 'bar'));
|
||||
$this->assertValidation(['foo', 'bar']);
|
||||
// Test with a single string value as well.
|
||||
$this->assertValidation('foo');
|
||||
}
|
||||
|
|
@ -49,14 +49,14 @@ class BundleConstraintValidatorTest extends KernelTestBase {
|
|||
->addConstraint('Bundle', $bundle);
|
||||
|
||||
// Test the validation.
|
||||
$node = $this->container->get('entity.manager')->getStorage('node')->create(array('type' => 'foo'));
|
||||
$node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'foo']);
|
||||
|
||||
$typed_data = $this->typedData->create($definition, $node);
|
||||
$violations = $typed_data->validate();
|
||||
$this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
|
||||
|
||||
// Test the validation when an invalid value is passed.
|
||||
$page_node = $this->container->get('entity.manager')->getStorage('node')->create(array('type' => 'baz'));
|
||||
$page_node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'baz']);
|
||||
|
||||
$typed_data = $this->typedData->create($definition, $page_node);
|
||||
$violations = $typed_data->validate();
|
||||
|
|
@ -64,7 +64,7 @@ class BundleConstraintValidatorTest extends KernelTestBase {
|
|||
|
||||
// Make sure the information provided by a violation is correct.
|
||||
$violation = $violations[0];
|
||||
$this->assertEqual($violation->getMessage(), t('The entity must be of bundle %bundle.', array('%bundle' => implode(', ', (array) $bundle))), 'The message for invalid value is correct.');
|
||||
$this->assertEqual($violation->getMessage(), t('The entity must be of bundle %bundle.', ['%bundle' => implode(', ', (array) $bundle)]), 'The message for invalid value is correct.');
|
||||
$this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
|
||||
$this->assertEqual($violation->getInvalidValue(), $page_node, 'The invalid value is set correctly in the violation.');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('config_test');
|
||||
public static $modules = ['config_test'];
|
||||
|
||||
/**
|
||||
* Stores the search results for alter comparison.
|
||||
|
|
@ -45,7 +45,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->entities = array();
|
||||
$this->entities = [];
|
||||
$this->factory = $this->container->get('entity.query');
|
||||
|
||||
// These two are here to make sure that matchArray needs to go over several
|
||||
|
|
@ -54,56 +54,56 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$array['level1a']['level2'] = 9;
|
||||
// The tests match array.level1.level2.
|
||||
$array['level1']['level2'] = 1;
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => '1',
|
||||
'number' => 31,
|
||||
'array' => $array,
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
||||
$array['level1']['level2'] = 2;
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => '2',
|
||||
'number' => 41,
|
||||
'array' => $array,
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
||||
$array['level1']['level2'] = 1;
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => 'test_prefix_' . $this->randomMachineName(),
|
||||
'id' => '3',
|
||||
'number' => 59,
|
||||
'array' => $array,
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
||||
$array['level1']['level2'] = 2;
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => $this->randomMachineName() . '_test_suffix',
|
||||
'id' => '4',
|
||||
'number' => 26,
|
||||
'array' => $array,
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
||||
$array['level1']['level2'] = 3;
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => $this->randomMachineName() . '_TEST_contains_' . $this->randomMachineName(),
|
||||
'id' => '5',
|
||||
'number' => 53,
|
||||
'array' => $array,
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
|
@ -116,84 +116,84 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
// Run a test without any condition.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '3', '4', '5'));
|
||||
$this->assertResults(['1', '2', '3', '4', '5']);
|
||||
// No conditions, OR.
|
||||
$this->queryResults = $this->factory->get('config_query_test', 'OR')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '3', '4', '5'));
|
||||
$this->assertResults(['1', '2', '3', '4', '5']);
|
||||
|
||||
// Filter by ID with equality.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3')
|
||||
->execute();
|
||||
$this->assertResults(array('3'));
|
||||
$this->assertResults(['3']);
|
||||
|
||||
// Filter by label with a known prefix.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'test_prefix', 'STARTS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('3'));
|
||||
$this->assertResults(['3']);
|
||||
|
||||
// Filter by label with a known suffix.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'test_suffix', 'ENDS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('4'));
|
||||
$this->assertResults(['4']);
|
||||
|
||||
// Filter by label with a known containing word.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'test_contains', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array('5'));
|
||||
$this->assertResults(['5']);
|
||||
|
||||
// Filter by ID with the IN operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', array('2', '3'), 'IN')
|
||||
->condition('id', ['2', '3'], 'IN')
|
||||
->execute();
|
||||
$this->assertResults(array('2', '3'));
|
||||
$this->assertResults(['2', '3']);
|
||||
|
||||
// Filter by ID with the implicit IN operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', array('2', '3'))
|
||||
->condition('id', ['2', '3'])
|
||||
->execute();
|
||||
$this->assertResults(array('2', '3'));
|
||||
$this->assertResults(['2', '3']);
|
||||
|
||||
// Filter by ID with the > operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '>')
|
||||
->execute();
|
||||
$this->assertResults(array('4', '5'));
|
||||
$this->assertResults(['4', '5']);
|
||||
|
||||
// Filter by ID with the >= operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '>=')
|
||||
->execute();
|
||||
$this->assertResults(array('3', '4', '5'));
|
||||
$this->assertResults(['3', '4', '5']);
|
||||
|
||||
// Filter by ID with the <> operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '<>')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '4', '5'));
|
||||
$this->assertResults(['1', '2', '4', '5']);
|
||||
|
||||
// Filter by ID with the < operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '<')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
|
||||
// Filter by ID with the <= operator.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '<=')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '3'));
|
||||
$this->assertResults(['1', '2', '3']);
|
||||
|
||||
// Filter by two conditions on the same field.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'test_pref', 'STARTS_WITH')
|
||||
->condition('label', 'test_prefix', 'STARTS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('3'));
|
||||
$this->assertResults(['3']);
|
||||
|
||||
// Filter by two conditions on different fields. The first query matches for
|
||||
// a different ID, so the result is empty.
|
||||
|
|
@ -201,7 +201,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition('label', 'test_prefix', 'STARTS_WITH')
|
||||
->condition('id', '5')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
|
||||
// Filter by two different conditions on different fields. This time the
|
||||
// first condition matches on one item, but the second one does as well.
|
||||
|
|
@ -209,7 +209,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition('label', 'test_prefix', 'STARTS_WITH')
|
||||
->condition('id', '3')
|
||||
->execute();
|
||||
$this->assertResults(array('3'));
|
||||
$this->assertResults(['3']);
|
||||
|
||||
// Filter by two different conditions, of which the first one matches for
|
||||
// every entry, the second one as well, but just the third one filters so
|
||||
|
|
@ -219,37 +219,37 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition('number', 10, '>=')
|
||||
->condition('number', 50, '>=')
|
||||
->execute();
|
||||
$this->assertResults(array('3', '5'));
|
||||
$this->assertResults(['3', '5']);
|
||||
|
||||
// Filter with an OR condition group.
|
||||
$this->queryResults = $this->factory->get('config_query_test', 'OR')
|
||||
->condition('id', 1)
|
||||
->condition('id', '2')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
|
||||
// Simplify it with IN.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', array('1', '2'))
|
||||
->condition('id', ['1', '2'])
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
// Try explicit IN.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', array('1', '2'), 'IN')
|
||||
->condition('id', ['1', '2'], 'IN')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
// Try not IN.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', array('1', '2'), 'NOT IN')
|
||||
->condition('id', ['1', '2'], 'NOT IN')
|
||||
->execute();
|
||||
$this->assertResults(array('3', '4', '5'));
|
||||
$this->assertResults(['3', '4', '5']);
|
||||
|
||||
// Filter with an OR condition group on different fields.
|
||||
$this->queryResults = $this->factory->get('config_query_test', 'OR')
|
||||
->condition('id', 1)
|
||||
->condition('number', 41)
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
|
||||
// Filter with an OR condition group on different fields but matching on the
|
||||
// same entity.
|
||||
|
|
@ -257,7 +257,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition('id', 1)
|
||||
->condition('number', 31)
|
||||
->execute();
|
||||
$this->assertResults(array('1'));
|
||||
$this->assertResults(['1']);
|
||||
|
||||
// NO simple conditions, YES complex conditions, 'AND'.
|
||||
$query = $this->factory->get('config_query_test', 'AND');
|
||||
|
|
@ -271,7 +271,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition($and_condition_1)
|
||||
->condition($and_condition_2)
|
||||
->execute();
|
||||
$this->assertResults(array('1'));
|
||||
$this->assertResults(['1']);
|
||||
|
||||
// NO simple conditions, YES complex conditions, 'OR'.
|
||||
$query = $this->factory->get('config_query_test', 'OR');
|
||||
|
|
@ -285,7 +285,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition($and_condition_1)
|
||||
->condition($and_condition_2)
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2'));
|
||||
$this->assertResults(['1', '2']);
|
||||
|
||||
// YES simple conditions, YES complex conditions, 'AND'.
|
||||
$query = $this->factory->get('config_query_test', 'AND');
|
||||
|
|
@ -300,7 +300,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition($and_condition_1)
|
||||
->condition($and_condition_2)
|
||||
->execute();
|
||||
$this->assertResults(array('1'));
|
||||
$this->assertResults(['1']);
|
||||
|
||||
// YES simple conditions, YES complex conditions, 'OR'.
|
||||
$query = $this->factory->get('config_query_test', 'OR');
|
||||
|
|
@ -315,28 +315,28 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->condition($and_condition_1)
|
||||
->condition($and_condition_2)
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '4', '5'));
|
||||
$this->assertResults(['1', '2', '4', '5']);
|
||||
|
||||
// Test the exists and notExists conditions.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->exists('id')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '3', '4', '5'));
|
||||
$this->assertResults(['1', '2', '3', '4', '5']);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->exists('non-existent')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->notExists('id')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->notExists('non-existent')
|
||||
->execute();
|
||||
$this->assertResults(array('1', '2', '3', '4', '5'));
|
||||
$this->assertResults(['1', '2', '3', '4', '5']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -344,10 +344,10 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
*/
|
||||
public function testStringIdConditions() {
|
||||
// We need an entity with a non-numeric ID.
|
||||
$entity = ConfigQueryTest::create(array(
|
||||
$entity = ConfigQueryTest::create([
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => 'foo.bar',
|
||||
));
|
||||
]);
|
||||
$this->entities[] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
|
@ -356,43 +356,43 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'foo.bar', 'STARTS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'f', 'STARTS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'miss', 'STARTS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
|
||||
// Test 'CONTAINS' condition.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'foo.bar', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'oo.ba', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'miss', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
|
||||
// Test 'ENDS_WITH' condition.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'foo.bar', 'ENDS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'r', 'ENDS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array('foo.bar'));
|
||||
$this->assertResults(['foo.bar']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', 'miss', 'ENDS_WITH')
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -429,62 +429,62 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->sort('number', 'DESC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('3', '5', '2', '1', '4'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->sort('number', 'ASC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('4', '1', '2', '5', '3'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
|
||||
|
||||
// Apply some filters and sort.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '>')
|
||||
->sort('number', 'DESC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('5', '4'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['5', '4']);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('id', '3', '>')
|
||||
->sort('number', 'ASC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('4', '5'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['4', '5']);
|
||||
|
||||
// Apply a pager and sort.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->sort('number', 'DESC')
|
||||
->range('2', '2')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('2', '1'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['2', '1']);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->sort('number', 'ASC')
|
||||
->range('2', '2')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('2', '5'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['2', '5']);
|
||||
|
||||
// Add a range to a query without a start parameter.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->range(0, '3')
|
||||
->sort('id', 'ASC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('1', '2', '3'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3']);
|
||||
|
||||
// Apply a pager with limit 4.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->pager('4', 0)
|
||||
->sort('id', 'ASC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('1', '2', '3', '4'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests sorting with tableSort on config entity queries.
|
||||
*/
|
||||
public function testTableSort() {
|
||||
$header = array(
|
||||
array('data' => t('ID'), 'specifier' => 'id'),
|
||||
array('data' => t('Number'), 'specifier' => 'number'),
|
||||
);
|
||||
$header = [
|
||||
['data' => t('ID'), 'specifier' => 'id'],
|
||||
['data' => t('Number'), 'specifier' => 'number'],
|
||||
];
|
||||
|
||||
// Sort key: id
|
||||
// Sorting with 'DESC' upper case
|
||||
|
|
@ -492,28 +492,28 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->tableSort($header)
|
||||
->sort('id', 'DESC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('5', '4', '3', '2', '1'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['5', '4', '3', '2', '1']);
|
||||
|
||||
// Sorting with 'ASC' upper case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('id', 'ASC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('1', '2', '3', '4', '5'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5']);
|
||||
|
||||
// Sorting with 'desc' lower case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('id', 'desc')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('5', '4', '3', '2', '1'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['5', '4', '3', '2', '1']);
|
||||
|
||||
// Sorting with 'asc' lower case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('id', 'asc')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('1', '2', '3', '4', '5'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5']);
|
||||
|
||||
// Sort key: number
|
||||
// Sorting with 'DeSc' mixed upper and lower case
|
||||
|
|
@ -521,28 +521,28 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
->tableSort($header)
|
||||
->sort('number', 'DeSc')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('3', '5', '2', '1', '4'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
|
||||
|
||||
// Sorting with 'AsC' mixed upper and lower case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('number', 'AsC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('4', '1', '2', '5', '3'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
|
||||
|
||||
// Sorting with 'dEsC' mixed upper and lower case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('number', 'dEsC')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('3', '5', '2', '1', '4'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
|
||||
|
||||
// Sorting with 'aSc' mixed upper and lower case
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->tableSort($header)
|
||||
->sort('number', 'aSc')
|
||||
->execute();
|
||||
$this->assertIdentical(array_values($this->queryResults), array('4', '1', '2', '5', '3'));
|
||||
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -552,26 +552,26 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('array.level1.*', 1)
|
||||
->execute();
|
||||
$this->assertResults(array('1', '3'));
|
||||
$this->assertResults(['1', '3']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('*.level1.level2', 2)
|
||||
->execute();
|
||||
$this->assertResults(array('2', '4'));
|
||||
$this->assertResults(['2', '4']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('array.level1.*', 3)
|
||||
->execute();
|
||||
$this->assertResults(array('5'));
|
||||
$this->assertResults(['5']);
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('array.level1.level2', 3)
|
||||
->execute();
|
||||
$this->assertResults(array('5'));
|
||||
$this->assertResults(['5']);
|
||||
// Make sure that values on the wildcard level do not match if there are
|
||||
// sub-keys defined. This must not find anything even if entity 2 has a
|
||||
// top-level key number with value 41.
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('*.level1.level2', 41)
|
||||
->execute();
|
||||
$this->assertResults(array());
|
||||
$this->assertResults([]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -582,12 +582,12 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'TEST', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array('3', '4', '5'));
|
||||
$this->assertResults(['3', '4', '5']);
|
||||
|
||||
$this->queryResults = $this->factory->get('config_query_test')
|
||||
->condition('label', 'test', 'CONTAINS')
|
||||
->execute();
|
||||
$this->assertResults(array('3', '4', '5'));
|
||||
$this->assertResults(['3', '4', '5']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -599,11 +599,11 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$key_value = $this->container->get('keyvalue')->get(QueryFactory::CONFIG_LOOKUP_PREFIX . 'config_test');
|
||||
|
||||
$test_entities = [];
|
||||
$entity = entity_create('config_test', array(
|
||||
$entity = entity_create('config_test', [
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => '1',
|
||||
'style' => 'test',
|
||||
));
|
||||
]);
|
||||
$test_entities[$entity->getConfigDependencyName()] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
|
|
@ -612,22 +612,22 @@ class ConfigEntityQueryTest extends KernelTestBase {
|
|||
$expected[] = $entity->getConfigDependencyName();
|
||||
$this->assertEqual($expected, $key_value->get('style:test'));
|
||||
|
||||
$entity = entity_create('config_test', array(
|
||||
$entity = entity_create('config_test', [
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => '2',
|
||||
'style' => 'test',
|
||||
));
|
||||
]);
|
||||
$test_entities[$entity->getConfigDependencyName()] = $entity;
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
$expected[] = $entity->getConfigDependencyName();
|
||||
$this->assertEqual($expected, $key_value->get('style:test'));
|
||||
|
||||
$entity = entity_create('config_test', array(
|
||||
$entity = entity_create('config_test', [
|
||||
'label' => $this->randomMachineName(),
|
||||
'id' => '3',
|
||||
'style' => 'blah',
|
||||
));
|
||||
]);
|
||||
$entity->enforceIsNew();
|
||||
$entity->save();
|
||||
// Do not add this entity to the list of expected result as it has a
|
||||
|
|
|
|||
|
|
@ -59,11 +59,12 @@ class ContentEntityChangedTest extends EntityKernelTestBase {
|
|||
$user2 = $this->createUser();
|
||||
|
||||
// Create a test entity.
|
||||
$entity = EntityTestMulChanged::create(array(
|
||||
$entity = EntityTestMulChanged::create([
|
||||
'name' => $this->randomString(),
|
||||
'not_translatable' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'language' => 'en',
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
$this->assertTrue(
|
||||
|
|
@ -122,6 +123,25 @@ class ContentEntityChangedTest extends EntityKernelTestBase {
|
|||
'Changed time of the German translation did not change.'
|
||||
);
|
||||
|
||||
// Update a non-translatable field to make sure that the changed timestamp
|
||||
// is updated for all translations.
|
||||
$entity->set('not_translatable', $this->randomString())->save();
|
||||
|
||||
$this->assertTrue(
|
||||
$entity->getChangedTime() > $changed_en,
|
||||
'Changed time of original language did change.'
|
||||
);
|
||||
|
||||
$this->assertTrue(
|
||||
$german->getChangedTime() > $changed_de,
|
||||
'Changed time of the German translation did change.'
|
||||
);
|
||||
|
||||
$this->assertEquals($entity->getChangedTime(), $german->getChangedTime(), 'When editing a non-translatable field the updated changed time is equal across all translations.');
|
||||
|
||||
$changed_en = $entity->getChangedTime();
|
||||
$changed_de = $german->getChangedTime();
|
||||
|
||||
$entity->setOwner($user2);
|
||||
|
||||
$entity->save();
|
||||
|
|
@ -269,11 +289,11 @@ class ContentEntityChangedTest extends EntityKernelTestBase {
|
|||
$user2 = $this->createUser();
|
||||
|
||||
// Create a test entity.
|
||||
$entity = EntityTestMulRevChanged::create(array(
|
||||
$entity = EntityTestMulRevChanged::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'language' => 'en',
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
$this->assertTrue(
|
||||
|
|
@ -491,6 +511,10 @@ class ContentEntityChangedTest extends EntityKernelTestBase {
|
|||
'Changed flag of French translation is set when adding the translation and a new revision.'
|
||||
);
|
||||
|
||||
// Since above a clone of the entity was saved and then this entity is saved
|
||||
// again, we have to update the revision ID to the current one.
|
||||
$german->set('revision_id', $form_entity_builder_clone->getRevisionId());
|
||||
$german->updateLoadedRevisionId();
|
||||
$german->setOwner($user1);
|
||||
$german->setRevisionTranslationAffected(FALSE);
|
||||
$entity->save();
|
||||
|
|
|
|||
|
|
@ -2,7 +2,9 @@
|
|||
|
||||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
use Drupal\entity_test\Entity\EntityTestMul;
|
||||
use Drupal\entity_test\Entity\EntityTestMulRev;
|
||||
use Drupal\language\Entity\ConfigurableLanguage;
|
||||
|
||||
/**
|
||||
|
|
@ -27,6 +29,7 @@ class ContentEntityCloneTest extends EntityKernelTestBase {
|
|||
ConfigurableLanguage::createFromLangcode('de')->save();
|
||||
|
||||
$this->installEntitySchema('entity_test_mul');
|
||||
$this->installEntitySchema('entity_test_mulrev');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -41,8 +44,15 @@ class ContentEntityCloneTest extends EntityKernelTestBase {
|
|||
'user_id' => $user->id(),
|
||||
'language' => 'en',
|
||||
]);
|
||||
$translation = $entity->addTranslation('de');
|
||||
|
||||
$clone = clone $entity->addTranslation('de');
|
||||
// Initialize the fields on the translation objects in order to check that
|
||||
// they are properly cloned and have a reference to the cloned entity
|
||||
// object and not to the original one.
|
||||
$entity->getFields();
|
||||
$translation->getFields();
|
||||
|
||||
$clone = clone $translation;
|
||||
|
||||
$this->assertEqual($entity->getTranslationLanguages(), $clone->getTranslationLanguages(), 'The entity and its clone have the same translation languages.');
|
||||
|
||||
|
|
@ -53,10 +63,12 @@ class ContentEntityCloneTest extends EntityKernelTestBase {
|
|||
if ($field->getFieldDefinition()->isTranslatable()) {
|
||||
$args = ['%field_name' => $field_name, '%langcode' => $langcode];
|
||||
$this->assertEqual($langcode, $field->getEntity()->language()->getId(), format_string('Translatable field %field_name on translation %langcode has correct entity reference in translation %langcode after cloning.', $args));
|
||||
$this->assertSame($translation, $field->getEntity(), new FormattableMarkup('Translatable field %field_name on translation %langcode has correct reference to the cloned entity object.', $args));
|
||||
}
|
||||
else {
|
||||
$args = ['%field_name' => $field_name, '%langcode' => $langcode, '%default_langcode' => $default_langcode];
|
||||
$this->assertEqual($default_langcode, $field->getEntity()->language()->getId(), format_string('Non translatable field %field_name on translation %langcode has correct entity reference in the default translation %default_langcode after cloning.', $args));
|
||||
$this->assertSame($translation->getUntranslated(), $field->getEntity(), new FormattableMarkup('Non translatable field %field_name on translation %langcode has correct reference to the cloned entity object in the default translation %default_langcode.', $args));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -78,15 +90,165 @@ class ContentEntityCloneTest extends EntityKernelTestBase {
|
|||
// The entity is not new anymore.
|
||||
$this->assertFalse($entity_translation->isNew());
|
||||
|
||||
// The clone should not be new as well.
|
||||
// The clone should not be new either.
|
||||
$clone = clone $entity_translation;
|
||||
$this->assertFalse($clone->isNew());
|
||||
|
||||
// After enforcing the clone to be new only it should be flagged as new,
|
||||
// but the original entity should not be flagged as new.
|
||||
// After forcing the clone to be new only it should be flagged as new, but
|
||||
// the original entity should not.
|
||||
$clone->enforceIsNew();
|
||||
$this->assertTrue($clone->isNew());
|
||||
$this->assertFalse($entity_translation->isNew());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests if the entity fields are properly cloned.
|
||||
*/
|
||||
public function testClonedEntityFields() {
|
||||
$user = $this->createUser();
|
||||
|
||||
// Create a test entity.
|
||||
$entity = EntityTestMul::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user->id(),
|
||||
'language' => 'en',
|
||||
]);
|
||||
|
||||
$entity->addTranslation('de');
|
||||
$entity->save();
|
||||
$fields = array_keys($entity->getFieldDefinitions());
|
||||
|
||||
// Reload the entity, clone it and check that both entity objects reference
|
||||
// different field instances.
|
||||
$entity = $this->reloadEntity($entity);
|
||||
$clone = clone $entity;
|
||||
|
||||
$different_references = TRUE;
|
||||
foreach ($fields as $field_name) {
|
||||
if ($entity->get($field_name) === $clone->get($field_name)) {
|
||||
$different_references = FALSE;
|
||||
}
|
||||
}
|
||||
$this->assertTrue($different_references, 'The entity object and the cloned entity object reference different field item list objects.');
|
||||
|
||||
|
||||
// Reload the entity, initialize one translation, clone it and check that
|
||||
// both entity objects reference different field instances.
|
||||
$entity = $this->reloadEntity($entity);
|
||||
$entity->getTranslation('de');
|
||||
$clone = clone $entity;
|
||||
|
||||
$different_references = TRUE;
|
||||
foreach ($fields as $field_name) {
|
||||
if ($entity->get($field_name) === $clone->get($field_name)) {
|
||||
$different_references = FALSE;
|
||||
}
|
||||
}
|
||||
$this->assertTrue($different_references, 'The entity object and the cloned entity object reference different field item list objects if the entity is cloned after an entity translation has been initialized.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the flag for enforcing a new revision is not shared.
|
||||
*/
|
||||
public function testNewRevisionOnCloneEntityTranslation() {
|
||||
// Create a test entity.
|
||||
$entity = EntityTestMulRev::create([
|
||||
'name' => $this->randomString(),
|
||||
'language' => 'en',
|
||||
]);
|
||||
$entity->save();
|
||||
$entity->addTranslation('de');
|
||||
$entity->save();
|
||||
|
||||
// Reload the entity as ContentEntityBase::postCreate() forces the entity to
|
||||
// be a new revision.
|
||||
$entity = EntityTestMulRev::load($entity->id());
|
||||
$entity_translation = $entity->getTranslation('de');
|
||||
|
||||
// The entity is not set to be a new revision.
|
||||
$this->assertFalse($entity_translation->isNewRevision());
|
||||
|
||||
// The clone should not be set to be a new revision either.
|
||||
$clone = clone $entity_translation;
|
||||
$this->assertFalse($clone->isNewRevision());
|
||||
|
||||
// After forcing the clone to be a new revision only it should be flagged
|
||||
// as a new revision, but the original entity should not.
|
||||
$clone->setNewRevision();
|
||||
$this->assertTrue($clone->isNewRevision());
|
||||
$this->assertFalse($entity_translation->isNewRevision());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests modifications on entity keys of a cloned entity object.
|
||||
*/
|
||||
public function testEntityKeysModifications() {
|
||||
// Create a test entity with a translation, which will internally trigger
|
||||
// entity cloning for the new translation and create references for some of
|
||||
// the entity properties.
|
||||
$entity = EntityTestMulRev::create([
|
||||
'name' => 'original-name',
|
||||
'uuid' => 'original-uuid',
|
||||
'language' => 'en',
|
||||
]);
|
||||
$entity->addTranslation('de');
|
||||
$entity->save();
|
||||
|
||||
// Clone the entity.
|
||||
$clone = clone $entity;
|
||||
|
||||
// Alter a non-translatable and a translatable entity key fields of the
|
||||
// cloned entity and assert that retrieving the value through the entity
|
||||
// keys local cache will be different for the cloned and the original
|
||||
// entity.
|
||||
// We first have to call the ::uuid() and ::label() method on the original
|
||||
// entity as it is going to cache the field values into the $entityKeys and
|
||||
// $translatableEntityKeys properties of the entity object and we want to
|
||||
// check that the cloned and the original entity aren't sharing the same
|
||||
// reference to those local cache properties.
|
||||
$uuid_field_name = $entity->getEntityType()->getKey('uuid');
|
||||
$this->assertFalse($entity->getFieldDefinition($uuid_field_name)->isTranslatable());
|
||||
$clone->$uuid_field_name->value = 'clone-uuid';
|
||||
$this->assertEquals('original-uuid', $entity->uuid());
|
||||
$this->assertEquals('clone-uuid', $clone->uuid());
|
||||
|
||||
$label_field_name = $entity->getEntityType()->getKey('label');
|
||||
$this->assertTrue($entity->getFieldDefinition($label_field_name)->isTranslatable());
|
||||
$clone->$label_field_name->value = 'clone-name';
|
||||
$this->assertEquals('original-name', $entity->label());
|
||||
$this->assertEquals('clone-name', $clone->label());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the field values after serializing an entity and its clone.
|
||||
*/
|
||||
public function testFieldValuesAfterSerialize() {
|
||||
// Create a test entity with a translation, which will internally trigger
|
||||
// entity cloning for the new translation and create references for some of
|
||||
// the entity properties.
|
||||
$entity = EntityTestMulRev::create([
|
||||
'name' => 'original',
|
||||
'language' => 'en',
|
||||
]);
|
||||
$entity->addTranslation('de');
|
||||
$entity->save();
|
||||
|
||||
// Clone the entity.
|
||||
$clone = clone $entity;
|
||||
|
||||
// Alter the name field value of the cloned entity object.
|
||||
$clone->setName('clone');
|
||||
|
||||
// Serialize the entity and the cloned object in order to destroy the field
|
||||
// objects and put the field values into the entity property $values, so
|
||||
// that on accessing a field again it will be newly created with the value
|
||||
// from the $values property.
|
||||
serialize($entity);
|
||||
serialize($clone);
|
||||
|
||||
// Assert that the original and the cloned entity both have different names.
|
||||
$this->assertEquals('original', $entity->getName());
|
||||
$this->assertEquals('clone', $clone->getName());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,101 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\user\Entity\User;
|
||||
|
||||
/**
|
||||
* Tests ContentEntityBase::hasTranslationChanges().
|
||||
*
|
||||
* @group Entity
|
||||
*/
|
||||
class ContentEntityHasChangesTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* Bundle of entity.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $bundle = 'test';
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['system', 'user', 'entity_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('user');
|
||||
$this->installEntitySchema('entity_test_mulrev_chnged_revlog');
|
||||
$this->installSchema('system', 'sequences');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the correct functionality of the hasTranslationChanges() function.
|
||||
*/
|
||||
public function testHasTranslationChanges() {
|
||||
$user1 = User::create([
|
||||
'name' => 'username1',
|
||||
'status' => 1,
|
||||
]);
|
||||
$user1->save();
|
||||
|
||||
$user2 = User::create([
|
||||
'name' => 'username2',
|
||||
'status' => 1,
|
||||
]);
|
||||
$user2->save();
|
||||
|
||||
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
|
||||
$storage = $this->container->get('entity_type.manager')
|
||||
->getStorage('entity_test_mulrev_chnged_revlog');
|
||||
/** @var \Drupal\entity_test\Entity\EntityTestMulRevChangedWithRevisionLog $entity */
|
||||
$entity = $storage->create([
|
||||
'name' => $this->randomString(),
|
||||
]);
|
||||
$entity->setRevisionUserId($user1->id());
|
||||
$entity->save();
|
||||
|
||||
$this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes after the entity has been saved.');
|
||||
|
||||
// Update the revision metadata fields and the changed field, which should
|
||||
// be skipped from checking for changes in
|
||||
// ContentEntityBase::hasTranslationChanges().
|
||||
$entity_previous_rev_id = $entity->getRevisionId();
|
||||
// Revision metadata field revision_timestamp.
|
||||
$entity->setRevisionCreationTime(time() + 1);
|
||||
// Revision metadata field revision_uid.
|
||||
$entity->setRevisionUserId($user2->id());
|
||||
// Revision metadata field revision_log.
|
||||
$entity->setRevisionLogMessage('test');
|
||||
// Revision metadata field revision_translation_affected.
|
||||
$entity->setRevisionTranslationAffected(TRUE);
|
||||
// Changed field.
|
||||
$entity->setChangedTime(time() + 1);
|
||||
|
||||
// Check that the revision metadata fields and the changed field have been
|
||||
// skipped when comparing same revisions.
|
||||
$this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes when comparing different revisions.');
|
||||
|
||||
// Check that the revision metadata fields and the changed field have been
|
||||
// skipped when comparing same revisions with enforced new revision to be
|
||||
// created on save.
|
||||
$entity->setNewRevision(TRUE);
|
||||
$this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes when comparing different revisions.');
|
||||
|
||||
// Save the entity in new revision with changes on the revision metadata
|
||||
// fields.
|
||||
$entity->save();
|
||||
|
||||
// Check that the revision metadata fields and the changed field have been
|
||||
// skipped when comparing different revisions.
|
||||
$entity = $storage->loadRevision($entity_previous_rev_id);
|
||||
$this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes when comparing different revisions.');
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -57,21 +57,21 @@ class ContentEntityNonRevisionableFieldTest extends EntityKernelTestBase {
|
|||
$user2 = $this->createUser();
|
||||
|
||||
// Create a test entity.
|
||||
$entity = EntityTestMulRev::create(array(
|
||||
$entity = EntityTestMulRev::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'language' => 'en',
|
||||
'non_rev_field' => 'Huron',
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
// Create a test entity.
|
||||
$entity2 = EntityTestMulRev::create(array(
|
||||
$entity2 = EntityTestMulRev::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'language' => 'en',
|
||||
'non_rev_field' => 'Michigan',
|
||||
));
|
||||
]);
|
||||
$entity2->save();
|
||||
|
||||
$this->assertEquals('Huron', $entity->get('non_rev_field')->value, 'Huron found on entity 1');
|
||||
|
|
@ -123,19 +123,19 @@ class ContentEntityNonRevisionableFieldTest extends EntityKernelTestBase {
|
|||
$user2 = $this->createUser();
|
||||
|
||||
// Create a test entity.
|
||||
$entity = EntityTestRev::create(array(
|
||||
$entity = EntityTestRev::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'non_rev_field' => 'Superior',
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
// Create a test entity.
|
||||
$entity2 = EntityTestRev::create(array(
|
||||
$entity2 = EntityTestRev::create([
|
||||
'name' => $this->randomString(),
|
||||
'user_id' => $user1->id(),
|
||||
'non_rev_field' => 'Ontario',
|
||||
));
|
||||
]);
|
||||
$entity2->save();
|
||||
|
||||
$this->assertEquals('Superior', $entity->get('non_rev_field')->value, 'Superior found on entity 1');
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class ContentEntityNullStorageTest extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('system', 'contact', 'user');
|
||||
public static $modules = ['system', 'contact', 'user'];
|
||||
|
||||
/**
|
||||
* Tests using entity query with ContentEntityNullStorage.
|
||||
|
|
|
|||
|
|
@ -50,23 +50,23 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
$this->installEntitySchema('entity_test_string_id');
|
||||
\Drupal::service('router.builder')->rebuild();
|
||||
|
||||
$this->testUser = User::create(array(
|
||||
$this->testUser = User::create([
|
||||
'name' => 'foobar1',
|
||||
'mail' => 'foobar1@example.com',
|
||||
));
|
||||
]);
|
||||
$this->testUser->save();
|
||||
\Drupal::service('current_user')->setAccount($this->testUser);
|
||||
|
||||
$this->testAutocreateUser = User::create(array(
|
||||
$this->testAutocreateUser = User::create([
|
||||
'name' => 'foobar2',
|
||||
'mail' => 'foobar2@example.com',
|
||||
));
|
||||
]);
|
||||
$this->testAutocreateUser->save();
|
||||
|
||||
for ($i = 1; $i < 3; $i++) {
|
||||
$entity = EntityTest::create(array(
|
||||
$entity = EntityTest::create([
|
||||
'name' => $this->randomMachineName()
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
$this->referencedEntities[] = $entity;
|
||||
}
|
||||
|
|
@ -94,84 +94,84 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$form['single'] = array(
|
||||
$form['single'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
);
|
||||
$form['single_autocreate'] = array(
|
||||
];
|
||||
$form['single_autocreate'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#autocreate' => array(
|
||||
'#autocreate' => [
|
||||
'bundle' => 'entity_test',
|
||||
),
|
||||
);
|
||||
$form['single_autocreate_specific_uid'] = array(
|
||||
],
|
||||
];
|
||||
$form['single_autocreate_specific_uid'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#autocreate' => array(
|
||||
'#autocreate' => [
|
||||
'bundle' => 'entity_test',
|
||||
'uid' => $this->testAutocreateUser->id(),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
$form['tags'] = array(
|
||||
$form['tags'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#tags' => TRUE,
|
||||
);
|
||||
$form['tags_autocreate'] = array(
|
||||
];
|
||||
$form['tags_autocreate'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#tags' => TRUE,
|
||||
'#autocreate' => array(
|
||||
'#autocreate' => [
|
||||
'bundle' => 'entity_test',
|
||||
),
|
||||
);
|
||||
$form['tags_autocreate_specific_uid'] = array(
|
||||
],
|
||||
];
|
||||
$form['tags_autocreate_specific_uid'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#tags' => TRUE,
|
||||
'#autocreate' => array(
|
||||
'#autocreate' => [
|
||||
'bundle' => 'entity_test',
|
||||
'uid' => $this->testAutocreateUser->id(),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
$form['single_no_validate'] = array(
|
||||
$form['single_no_validate'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#validate_reference' => FALSE,
|
||||
);
|
||||
$form['single_autocreate_no_validate'] = array(
|
||||
];
|
||||
$form['single_autocreate_no_validate'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#validate_reference' => FALSE,
|
||||
'#autocreate' => array(
|
||||
'#autocreate' => [
|
||||
'bundle' => 'entity_test',
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
|
||||
$form['single_access'] = array(
|
||||
$form['single_access'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#default_value' => $this->referencedEntities[0],
|
||||
);
|
||||
$form['tags_access'] = array(
|
||||
];
|
||||
$form['tags_access'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test',
|
||||
'#tags' => TRUE,
|
||||
'#default_value' => array($this->referencedEntities[0], $this->referencedEntities[1]),
|
||||
);
|
||||
'#default_value' => [$this->referencedEntities[0], $this->referencedEntities[1]],
|
||||
];
|
||||
|
||||
$form['single_string_id'] = array(
|
||||
$form['single_string_id'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test_string_id',
|
||||
);
|
||||
$form['tags_string_id'] = array(
|
||||
];
|
||||
$form['tags_string_id'] = [
|
||||
'#type' => 'entity_autocomplete',
|
||||
'#target_type' => 'entity_test_string_id',
|
||||
'#tags' => TRUE,
|
||||
);
|
||||
];
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
|
@ -229,10 +229,10 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
$this->assertEqual($value['entity']->getOwnerId(), $this->testAutocreateUser->id());
|
||||
|
||||
// Test the 'tags' element.
|
||||
$expected = array(
|
||||
array('target_id' => $this->referencedEntities[0]->id()),
|
||||
array('target_id' => $this->referencedEntities[1]->id()),
|
||||
);
|
||||
$expected = [
|
||||
['target_id' => $this->referencedEntities[0]->id()],
|
||||
['target_id' => $this->referencedEntities[1]->id()],
|
||||
];
|
||||
$this->assertEqual($form_state->getValue('tags'), $expected);
|
||||
|
||||
// Test the 'single_autocreate' element.
|
||||
|
|
@ -281,7 +281,7 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
]);
|
||||
$form_builder->submitForm($this, $form_state);
|
||||
$this->assertEqual(count($form_state->getErrors()), 1);
|
||||
$this->assertEqual($form_state->getErrors()['single'], t('There are no entities matching "%value".', array('%value' => 'single - non-existent label')));
|
||||
$this->assertEqual($form_state->getErrors()['single'], t('There are no entities matching "%value".', ['%value' => 'single - non-existent label']));
|
||||
|
||||
// Test 'single' with a entity ID that doesn't exist.
|
||||
$form_state = (new FormState())
|
||||
|
|
@ -290,7 +290,7 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
]);
|
||||
$form_builder->submitForm($this, $form_state);
|
||||
$this->assertEqual(count($form_state->getErrors()), 1);
|
||||
$this->assertEqual($form_state->getErrors()['single'], t('The referenced entity (%type: %id) does not exist.', array('%type' => 'entity_test', '%id' => 42)));
|
||||
$this->assertEqual($form_state->getErrors()['single'], t('The referenced entity (%type: %id) does not exist.', ['%type' => 'entity_test', '%id' => 42]));
|
||||
|
||||
// Do the same tests as above but on an element with '#validate_reference'
|
||||
// set to FALSE.
|
||||
|
|
@ -304,7 +304,7 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
// The element without 'autocreate' support still has to emit a warning when
|
||||
// the input doesn't end with an entity ID enclosed in parentheses.
|
||||
$this->assertEqual(count($form_state->getErrors()), 1);
|
||||
$this->assertEqual($form_state->getErrors()['single_no_validate'], t('There are no entities matching "%value".', array('%value' => 'single - non-existent label')));
|
||||
$this->assertEqual($form_state->getErrors()['single_no_validate'], t('There are no entities matching "%value".', ['%value' => 'single - non-existent label']));
|
||||
|
||||
$form_state = (new FormState())
|
||||
->setValues([
|
||||
|
|
@ -333,7 +333,7 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
$this->assertEqual($form['tags_access']['#value'], $expected);
|
||||
|
||||
// Set up a non-admin user that is *not* allowed to view test entities.
|
||||
\Drupal::currentUser()->setAccount($this->createUser(array(), array()));
|
||||
\Drupal::currentUser()->setAccount($this->createUser([], []));
|
||||
|
||||
// Rebuild the form.
|
||||
$form = $form_builder->getForm($this);
|
||||
|
|
@ -381,7 +381,7 @@ class EntityAutocompleteElementFormTest extends EntityKernelTestBase implements
|
|||
* A string that can be used as a value for EntityAutocomplete elements.
|
||||
*/
|
||||
protected function getAutocompleteInput(EntityInterface $entity) {
|
||||
return EntityAutocomplete::getEntityLabels(array($entity));
|
||||
return EntityAutocomplete::getEntityLabels([$entity]);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,12 +23,12 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
/**
|
||||
* Asserts entity access correctly grants or denies access.
|
||||
*/
|
||||
function assertEntityAccess($ops, AccessibleInterface $object, AccountInterface $account = NULL) {
|
||||
public function assertEntityAccess($ops, AccessibleInterface $object, AccountInterface $account = NULL) {
|
||||
foreach ($ops as $op => $result) {
|
||||
$message = format_string("Entity access returns @result with operation '@op'.", array(
|
||||
$message = format_string("Entity access returns @result with operation '@op'.", [
|
||||
'@result' => !isset($result) ? 'null' : ($result ? 'true' : 'false'),
|
||||
'@op' => $op,
|
||||
));
|
||||
]);
|
||||
|
||||
$this->assertEqual($result, $object->access($op, $account), $message);
|
||||
}
|
||||
|
|
@ -45,44 +45,44 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
$user = $this->createUser();
|
||||
|
||||
// The current user is allowed to view the anonymous user label.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
'view label' => TRUE,
|
||||
), $anonymous_user);
|
||||
], $anonymous_user);
|
||||
|
||||
// The current user is allowed to view user labels.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
'view label' => TRUE,
|
||||
), $user);
|
||||
], $user);
|
||||
|
||||
// Switch to a anonymous user account.
|
||||
$account_switcher = \Drupal::service('account_switcher');
|
||||
$account_switcher->switchTo(new AnonymousUserSession());
|
||||
|
||||
// The anonymous user is allowed to view the anonymous user label.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
'view label' => TRUE,
|
||||
), $anonymous_user);
|
||||
], $anonymous_user);
|
||||
|
||||
// The anonymous user is allowed to view user labels.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
'view label' => TRUE,
|
||||
), $user);
|
||||
], $user);
|
||||
|
||||
// Restore user account.
|
||||
$account_switcher->switchBack();
|
||||
|
|
@ -91,35 +91,35 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
/**
|
||||
* Ensures entity access is properly working.
|
||||
*/
|
||||
function testEntityAccess() {
|
||||
public function testEntityAccess() {
|
||||
// Set up a non-admin user that is allowed to view test entities.
|
||||
\Drupal::currentUser()->setAccount($this->createUser(array('uid' => 2), array('view test entity')));
|
||||
\Drupal::currentUser()->setAccount($this->createUser(['uid' => 2], ['view test entity']));
|
||||
|
||||
// Use the 'entity_test_label' entity type in order to test the 'view label'
|
||||
// access operation.
|
||||
$entity = EntityTestLabel::create(array(
|
||||
$entity = EntityTestLabel::create([
|
||||
'name' => 'test',
|
||||
));
|
||||
]);
|
||||
|
||||
// The current user is allowed to view entities.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => TRUE,
|
||||
'view label' => TRUE,
|
||||
), $entity);
|
||||
], $entity);
|
||||
|
||||
// The custom user is not allowed to perform any operation on test entities,
|
||||
// except for viewing their label.
|
||||
$custom_user = $this->createUser();
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
'view label' => TRUE,
|
||||
), $entity, $custom_user);
|
||||
], $entity, $custom_user);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -134,28 +134,28 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
* @see \Drupal\entity_test\EntityTestAccessControlHandler::checkAccess()
|
||||
* @see entity_test_entity_access()
|
||||
*/
|
||||
function testDefaultEntityAccess() {
|
||||
public function testDefaultEntityAccess() {
|
||||
// Set up a non-admin user that is allowed to view test entities.
|
||||
\Drupal::currentUser()->setAccount($this->createUser(array('uid' => 2), array('view test entity')));
|
||||
$entity = EntityTest::create(array(
|
||||
\Drupal::currentUser()->setAccount($this->createUser(['uid' => 2], ['view test entity']));
|
||||
$entity = EntityTest::create([
|
||||
'name' => 'forbid_access',
|
||||
));
|
||||
]);
|
||||
|
||||
// The user is denied access to the entity.
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
), $entity);
|
||||
], $entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the default handler is used as a fallback.
|
||||
*/
|
||||
function testEntityAccessDefaultController() {
|
||||
public function testEntityAccessDefaultController() {
|
||||
// The implementation requires that the global user id can be loaded.
|
||||
\Drupal::currentUser()->setAccount($this->createUser(array('uid' => 2)));
|
||||
\Drupal::currentUser()->setAccount($this->createUser(['uid' => 2]));
|
||||
|
||||
// Check that the default access control handler is used for entities that don't
|
||||
// have a specific access control handler defined.
|
||||
|
|
@ -163,40 +163,40 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
$this->assertTrue($handler instanceof EntityAccessControlHandler, 'The default entity handler is used for the entity_test_default_access entity type.');
|
||||
|
||||
$entity = EntityTestDefaultAccess::create();
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'create' => FALSE,
|
||||
'update' => FALSE,
|
||||
'delete' => FALSE,
|
||||
'view' => FALSE,
|
||||
), $entity);
|
||||
], $entity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures entity access for entity translations is properly working.
|
||||
*/
|
||||
function testEntityTranslationAccess() {
|
||||
public function testEntityTranslationAccess() {
|
||||
|
||||
// Set up a non-admin user that is allowed to view test entity translations.
|
||||
\Drupal::currentUser()->setAccount($this->createUser(array('uid' => 2), array('view test entity translations')));
|
||||
\Drupal::currentUser()->setAccount($this->createUser(['uid' => 2], ['view test entity translations']));
|
||||
|
||||
// Create two test languages.
|
||||
foreach (array('foo', 'bar') as $langcode) {
|
||||
ConfigurableLanguage::create(array(
|
||||
foreach (['foo', 'bar'] as $langcode) {
|
||||
ConfigurableLanguage::create([
|
||||
'id' => $langcode,
|
||||
'label' => $this->randomString(),
|
||||
))->save();
|
||||
])->save();
|
||||
}
|
||||
|
||||
$entity = EntityTest::create(array(
|
||||
$entity = EntityTest::create([
|
||||
'name' => 'test',
|
||||
'langcode' => 'foo',
|
||||
));
|
||||
]);
|
||||
$entity->save();
|
||||
|
||||
$translation = $entity->addTranslation('bar');
|
||||
$this->assertEntityAccess(array(
|
||||
$this->assertEntityAccess([
|
||||
'view' => TRUE,
|
||||
), $translation);
|
||||
], $translation);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -204,9 +204,9 @@ class EntityAccessControlHandlerTest extends EntityLanguageTestBase {
|
|||
*/
|
||||
public function testHooks() {
|
||||
$state = $this->container->get('state');
|
||||
$entity = EntityTest::create(array(
|
||||
$entity = EntityTest::create([
|
||||
'name' => 'test',
|
||||
));
|
||||
]);
|
||||
|
||||
// Test hook_entity_create_access() and hook_ENTITY_TYPE_create_access().
|
||||
$entity->access('create');
|
||||
|
|
|
|||
|
|
@ -49,15 +49,15 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
// Create some test entities.
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array('name' => 'test', 'user_id' => $user1->id()));
|
||||
->create(['name' => 'test', 'user_id' => $user1->id()]);
|
||||
$entity->save();
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array('name' => 'test2', 'user_id' => $user1->id()));
|
||||
->create(['name' => 'test2', 'user_id' => $user1->id()]);
|
||||
$entity->save();
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array('name' => 'test', 'user_id' => NULL));
|
||||
->create(['name' => 'test', 'user_id' => NULL]);
|
||||
$entity->save();
|
||||
|
||||
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
|
||||
|
|
@ -65,32 +65,32 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
->getStorage($entity_type);
|
||||
|
||||
$entities = array_values($storage->loadByProperties(['name' => 'test']));
|
||||
$this->assertEqual($entities[0]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entities[1]->name->value, 'test', format_string('%entity_type: Created and loaded entity', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entities[0]->name->value, 'test', format_string('%entity_type: Created and loaded entity', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entities[1]->name->value, 'test', format_string('%entity_type: Created and loaded entity', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test loading a single entity.
|
||||
$loaded_entity = $storage->load($entity->id());
|
||||
$this->assertEqual($loaded_entity->id(), $entity->id(), format_string('%entity_type: Loaded a single entity by id.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($loaded_entity->id(), $entity->id(), format_string('%entity_type: Loaded a single entity by id.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test deleting an entity.
|
||||
$entities = array_values($storage->loadByProperties(['name' => 'test2']));
|
||||
$entities[0]->delete();
|
||||
$entities = array_values($storage->loadByProperties(['name' => 'test2']));
|
||||
$this->assertEqual($entities, array(), format_string('%entity_type: Entity deleted.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entities, [], format_string('%entity_type: Entity deleted.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test updating an entity.
|
||||
$entities = array_values($storage->loadByProperties(['name' => 'test']));
|
||||
$entities[0]->name->value = 'test3';
|
||||
$entities[0]->save();
|
||||
$entity = $storage->load($entities[0]->id());
|
||||
$this->assertEqual($entity->name->value, 'test3', format_string('%entity_type: Entity updated.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name->value, 'test3', format_string('%entity_type: Entity updated.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Try deleting multiple test entities by deleting all.
|
||||
$ids = array_keys($storage->loadMultiple());
|
||||
entity_delete_multiple($entity_type, $ids);
|
||||
|
||||
$all = $storage->loadMultiple();
|
||||
$this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Verify that all data got deleted.
|
||||
$definition = \Drupal::entityManager()->getDefinition($entity_type);
|
||||
|
|
@ -103,11 +103,11 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
}
|
||||
|
||||
// Test deleting a list of entities not indexed by entity id.
|
||||
$entities = array();
|
||||
$entity = entity_create($entity_type, array('name' => 'test', 'user_id' => $user1->id()));
|
||||
$entities = [];
|
||||
$entity = entity_create($entity_type, ['name' => 'test', 'user_id' => $user1->id()]);
|
||||
$entity->save();
|
||||
$entities['test'] = $entity;
|
||||
$entity = entity_create($entity_type, array('name' => 'test2', 'user_id' => $user1->id()));
|
||||
$entity = entity_create($entity_type, ['name' => 'test2', 'user_id' => $user1->id()]);
|
||||
$entity->save();
|
||||
$entities['test2'] = $entity;
|
||||
$controller = \Drupal::entityManager()->getStorage($entity_type);
|
||||
|
|
@ -115,7 +115,7 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
|
||||
// Verify that entities got deleted.
|
||||
$all = $storage->loadMultiple();
|
||||
$this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(empty($all), format_string('%entity_type: Deleted all entities.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Verify that all data got deleted from the tables.
|
||||
$definition = \Drupal::entityManager()->getDefinition($entity_type);
|
||||
|
|
@ -132,7 +132,7 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
* Tests that exceptions are thrown when saving or deleting an entity.
|
||||
*/
|
||||
public function testEntityStorageExceptionHandling() {
|
||||
$entity = EntityTest::create(array('name' => 'test'));
|
||||
$entity = EntityTest::create(['name' => 'test']);
|
||||
try {
|
||||
$GLOBALS['entity_test_throw_exception'] = TRUE;
|
||||
$entity->save();
|
||||
|
|
@ -142,7 +142,7 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
$this->assertEqual($e->getcode(), 1, 'Entity presave EntityStorageException caught.');
|
||||
}
|
||||
|
||||
$entity = EntityTest::create(array('name' => 'test2'));
|
||||
$entity = EntityTest::create(['name' => 'test2']);
|
||||
try {
|
||||
unset($GLOBALS['entity_test_throw_exception']);
|
||||
$entity->save();
|
||||
|
|
@ -152,7 +152,7 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
$this->assertNotEqual($e->getCode(), 1, 'Entity presave EntityStorageException caught.');
|
||||
}
|
||||
|
||||
$entity = EntityTest::create(array('name' => 'test3'));
|
||||
$entity = EntityTest::create(['name' => 'test3']);
|
||||
$entity->save();
|
||||
try {
|
||||
$GLOBALS['entity_test_throw_exception'] = TRUE;
|
||||
|
|
@ -164,7 +164,7 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
}
|
||||
|
||||
unset($GLOBALS['entity_test_throw_exception']);
|
||||
$entity = EntityTest::create(array('name' => 'test4'));
|
||||
$entity = EntityTest::create(['name' => 'test4']);
|
||||
$entity->save();
|
||||
try {
|
||||
$entity->delete();
|
||||
|
|
@ -175,4 +175,38 @@ class EntityApiTest extends EntityKernelTestBase {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that resaving a revision with a different revision ID throws an exception.
|
||||
*/
|
||||
public function testUpdateWithRevisionId() {
|
||||
$storage = \Drupal::entityTypeManager()->getStorage('entity_test_mulrev');
|
||||
|
||||
// Create a new entity.
|
||||
/** @var \Drupal\entity_test\Entity\EntityTestMulRev $entity */
|
||||
$entity = $storage->create(['name' => 'revision_test']);
|
||||
$entity->save();
|
||||
|
||||
$this->setExpectedException(EntityStorageException::class, "Update existing 'entity_test_mulrev' entity revision while changing the revision ID is not supported.");
|
||||
|
||||
$entity->revision_id = 60;
|
||||
$entity->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that resaving an entity with a different entity ID throws an exception.
|
||||
*/
|
||||
public function testUpdateWithId() {
|
||||
$storage = \Drupal::entityTypeManager()->getStorage('entity_test_mulrev');
|
||||
|
||||
// Create a new entity.
|
||||
/** @var \Drupal\entity_test\Entity\EntityTestMulRev $entity */
|
||||
$entity = $storage->create(['name' => 'revision_test']);
|
||||
$entity->save();
|
||||
|
||||
$this->setExpectedException(EntityStorageException::class, "Update existing 'entity_test_mulrev' entity while changing the ID is not supported.");
|
||||
|
||||
$entity->id = 60;
|
||||
$entity->save();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,23 +43,23 @@ class EntityAutocompleteTest extends EntityKernelTestBase {
|
|||
/**
|
||||
* Tests autocompletion edge cases with slashes in the names.
|
||||
*/
|
||||
function testEntityReferenceAutocompletion() {
|
||||
public function testEntityReferenceAutocompletion() {
|
||||
// Add an entity with a slash in its name.
|
||||
$entity_1 = $this->container->get('entity_type.manager')
|
||||
->getStorage($this->entityType)
|
||||
->create(array('name' => '10/16/2011'));
|
||||
->create(['name' => '10/16/2011']);
|
||||
$entity_1->save();
|
||||
|
||||
// Add another entity that differs after the slash character.
|
||||
$entity_2 = $this->container->get('entity_type.manager')
|
||||
->getStorage($this->entityType)
|
||||
->create(array('name' => '10/17/2011'));
|
||||
->create(['name' => '10/17/2011']);
|
||||
$entity_2->save();
|
||||
|
||||
// Add another entity that has both a comma, a slash and markup.
|
||||
$entity_3 = $this->container->get('entity_type.manager')
|
||||
->getStorage($this->entityType)
|
||||
->create(array('name' => 'label with, and / test'));
|
||||
->create(['name' => 'label with, and / test']);
|
||||
$entity_3->save();
|
||||
|
||||
// Try to autocomplete a entity label that matches both entities.
|
||||
|
|
@ -73,10 +73,10 @@ class EntityAutocompleteTest extends EntityKernelTestBase {
|
|||
// We should only get the first entity in a JSON encoded string.
|
||||
$input = '10/16';
|
||||
$data = $this->getAutocompleteResult($input);
|
||||
$target = array(
|
||||
$target = [
|
||||
'value' => $entity_1->name->value . ' (1)',
|
||||
'label' => Html::escape($entity_1->name->value),
|
||||
);
|
||||
];
|
||||
$this->assertIdentical(reset($data), $target, 'Autocomplete returns only the expected matching entity.');
|
||||
|
||||
// Try to autocomplete a entity label that matches the second entity, and
|
||||
|
|
@ -91,10 +91,10 @@ class EntityAutocompleteTest extends EntityKernelTestBase {
|
|||
$n = $entity_3->name->value . ' (3)';
|
||||
// Entity labels containing commas or quotes must be wrapped in quotes.
|
||||
$n = Tags::encode($n);
|
||||
$target = array(
|
||||
$target = [
|
||||
'value' => $n,
|
||||
'label' => Html::escape($entity_3->name->value),
|
||||
);
|
||||
];
|
||||
$this->assertIdentical(reset($data), $target, 'Autocomplete returns an entity label containing a comma and a slash.');
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ class EntityBundleFieldTest extends EntityKernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('entity_schema_test');
|
||||
public static $modules = ['entity_schema_test'];
|
||||
|
||||
/**
|
||||
* The module handler.
|
||||
|
|
@ -35,7 +35,7 @@ class EntityBundleFieldTest extends EntityKernelTestBase {
|
|||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installSchema('user', array('users_data'));
|
||||
$this->installSchema('user', ['users_data']);
|
||||
$this->moduleHandler = $this->container->get('module_handler');
|
||||
$this->database = $this->container->get('database');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,17 +40,17 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('block', 'block_test', 'entity_crud_hook_test', 'file', 'taxonomy', 'node', 'comment');
|
||||
public static $modules = ['block', 'block_test', 'entity_crud_hook_test', 'file', 'taxonomy', 'node', 'comment'];
|
||||
|
||||
protected $ids = array();
|
||||
protected $ids = [];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installSchema('user', array('users_data'));
|
||||
$this->installSchema('file', array('file_usage'));
|
||||
$this->installSchema('node', array('node_access'));
|
||||
$this->installSchema('comment', array('comment_entity_statistics'));
|
||||
$this->installSchema('user', ['users_data']);
|
||||
$this->installSchema('file', ['file_usage']);
|
||||
$this->installSchema('node', ['node_access']);
|
||||
$this->installSchema('comment', ['comment_entity_statistics']);
|
||||
$this->installConfig(['node', 'comment']);
|
||||
}
|
||||
|
||||
|
|
@ -64,7 +64,7 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
* An array of plain-text messages in the order they should appear.
|
||||
*/
|
||||
protected function assertHookMessageOrder($messages) {
|
||||
$positions = array();
|
||||
$positions = [];
|
||||
foreach ($messages as $message) {
|
||||
// Verify that each message is found and record its position.
|
||||
$position = array_search($message, $GLOBALS['entity_crud_hook_test']);
|
||||
|
|
@ -83,55 +83,55 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
* Tests hook invocations for CRUD operations on blocks.
|
||||
*/
|
||||
public function testBlockHooks() {
|
||||
$entity = Block::create(array(
|
||||
$entity = Block::create([
|
||||
'id' => 'stark_test_html',
|
||||
'plugin' => 'test_html',
|
||||
'theme' => 'stark',
|
||||
));
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_block_create called',
|
||||
'entity_crud_hook_test_entity_create called for type block',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$entity->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_block_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type block',
|
||||
'entity_crud_hook_test_block_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type block',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$entity = Block::load($entity->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type block',
|
||||
'entity_crud_hook_test_block_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$entity->label = 'New label';
|
||||
$entity->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_block_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type block',
|
||||
'entity_crud_hook_test_block_update called',
|
||||
'entity_crud_hook_test_entity_update called for type block',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$entity->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_block_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type block',
|
||||
'entity_crud_hook_test_block_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type block',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -158,9 +158,9 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
]);
|
||||
$node->save();
|
||||
$nid = $node->id();
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
|
||||
$comment = Comment::create(array(
|
||||
$comment = Comment::create([
|
||||
'cid' => NULL,
|
||||
'pid' => 0,
|
||||
'entity_id' => $nid,
|
||||
|
|
@ -172,51 +172,51 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'changed' => REQUEST_TIME,
|
||||
'status' => 1,
|
||||
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
|
||||
));
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_comment_create called',
|
||||
'entity_crud_hook_test_entity_create called for type comment',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$comment->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_comment_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type comment',
|
||||
'entity_crud_hook_test_comment_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type comment',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$comment = Comment::load($comment->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type comment',
|
||||
'entity_crud_hook_test_comment_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$comment->setSubject('New subject');
|
||||
$comment->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_comment_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type comment',
|
||||
'entity_crud_hook_test_comment_update called',
|
||||
'entity_crud_hook_test_entity_update called for type comment',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$comment->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_comment_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type comment',
|
||||
'entity_crud_hook_test_comment_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type comment',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -239,49 +239,49 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'changed' => REQUEST_TIME,
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_file_create called',
|
||||
'entity_crud_hook_test_entity_create called for type file',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$file->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_file_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type file',
|
||||
'entity_crud_hook_test_file_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type file',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$file = File::load($file->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type file',
|
||||
'entity_crud_hook_test_file_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$file->setFilename('new.entity_crud_hook_test.file');
|
||||
$file->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_file_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type file',
|
||||
'entity_crud_hook_test_file_update called',
|
||||
'entity_crud_hook_test_entity_update called for type file',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$file->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_file_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type file',
|
||||
'entity_crud_hook_test_file_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type file',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -302,49 +302,49 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'changed' => REQUEST_TIME,
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_node_create called',
|
||||
'entity_crud_hook_test_entity_create called for type node',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$node->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_node_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type node',
|
||||
'entity_crud_hook_test_node_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type node',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$node = Node::load($node->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type node',
|
||||
'entity_crud_hook_test_node_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$node->title = 'New title';
|
||||
$node->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_node_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type node',
|
||||
'entity_crud_hook_test_node_update called',
|
||||
'entity_crud_hook_test_entity_update called for type node',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$node->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_node_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type node',
|
||||
'entity_crud_hook_test_node_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type node',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -361,7 +361,7 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'module' => 'entity_crud_hook_test',
|
||||
]);
|
||||
$vocabulary->save();
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
|
||||
$term = Term::create([
|
||||
'vid' => $vocabulary->id(),
|
||||
|
|
@ -371,49 +371,49 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'format' => 1,
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_term_create called',
|
||||
'entity_crud_hook_test_entity_create called for type taxonomy_term',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$term->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_term_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type taxonomy_term',
|
||||
'entity_crud_hook_test_taxonomy_term_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type taxonomy_term',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$term = Term::load($term->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type taxonomy_term',
|
||||
'entity_crud_hook_test_taxonomy_term_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$term->setName('New name');
|
||||
$term->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_term_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type taxonomy_term',
|
||||
'entity_crud_hook_test_taxonomy_term_update called',
|
||||
'entity_crud_hook_test_entity_update called for type taxonomy_term',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$term->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_term_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type taxonomy_term',
|
||||
'entity_crud_hook_test_taxonomy_term_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type taxonomy_term',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -430,49 +430,49 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'module' => 'entity_crud_hook_test',
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_create called',
|
||||
'entity_crud_hook_test_entity_create called for type taxonomy_vocabulary',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$vocabulary->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type taxonomy_vocabulary',
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type taxonomy_vocabulary',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$vocabulary = Vocabulary::load($vocabulary->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type taxonomy_vocabulary',
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$vocabulary->set('name', 'New name');
|
||||
$vocabulary->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type taxonomy_vocabulary',
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_update called',
|
||||
'entity_crud_hook_test_entity_update called for type taxonomy_vocabulary',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$vocabulary->delete();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type taxonomy_vocabulary',
|
||||
'entity_crud_hook_test_taxonomy_vocabulary_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type taxonomy_vocabulary',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -487,58 +487,58 @@ class EntityCrudHookTest extends EntityKernelTestBase {
|
|||
'language' => 'en',
|
||||
]);
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_user_create called',
|
||||
'entity_crud_hook_test_entity_create called for type user',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$account->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_user_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type user',
|
||||
'entity_crud_hook_test_user_insert called',
|
||||
'entity_crud_hook_test_entity_insert called for type user',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
User::load($account->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_entity_load called for type user',
|
||||
'entity_crud_hook_test_user_load called',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
$account->name = 'New name';
|
||||
$account->save();
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_user_presave called',
|
||||
'entity_crud_hook_test_entity_presave called for type user',
|
||||
'entity_crud_hook_test_user_update called',
|
||||
'entity_crud_hook_test_entity_update called for type user',
|
||||
));
|
||||
]);
|
||||
|
||||
$GLOBALS['entity_crud_hook_test'] = array();
|
||||
$GLOBALS['entity_crud_hook_test'] = [];
|
||||
user_delete($account->id());
|
||||
|
||||
$this->assertHookMessageOrder(array(
|
||||
$this->assertHookMessageOrder([
|
||||
'entity_crud_hook_test_user_predelete called',
|
||||
'entity_crud_hook_test_entity_predelete called for type user',
|
||||
'entity_crud_hook_test_user_delete called',
|
||||
'entity_crud_hook_test_entity_delete called for type user',
|
||||
));
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests rollback from failed entity save.
|
||||
*/
|
||||
function testEntityRollback() {
|
||||
public function testEntityRollback() {
|
||||
// Create a block.
|
||||
try {
|
||||
EntityTest::create(array('name' => 'fail_insert'))->save();
|
||||
EntityTest::create(['name' => 'fail_insert'])->save();
|
||||
$this->fail('Expected exception has not been thrown.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ use Drupal\Core\Entity\Exception\FieldStorageDefinitionUpdateForbiddenException;
|
|||
use Drupal\Core\Field\BaseFieldDefinition;
|
||||
use Drupal\Core\Field\FieldStorageDefinitionEvents;
|
||||
use Drupal\Core\Language\LanguageInterface;
|
||||
use Drupal\entity_test\Entity\EntityTestUpdate;
|
||||
use Drupal\entity_test_update\Entity\EntityTestUpdate;
|
||||
use Drupal\system\Tests\Entity\EntityDefinitionTestTrait;
|
||||
|
||||
/**
|
||||
|
|
@ -39,6 +39,13 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['entity_test_update'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
|
@ -49,7 +56,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
|
||||
// Install every entity type's schema that wasn't installed in the parent
|
||||
// method.
|
||||
foreach (array_diff_key($this->entityManager->getDefinitions(), array_flip(array('user', 'entity_test'))) as $entity_type_id => $entity_type) {
|
||||
foreach (array_diff_key($this->entityManager->getDefinitions(), array_flip(['user', 'entity_test'])) as $entity_type_id => $entity_type) {
|
||||
$this->installEntitySchema($entity_type_id);
|
||||
}
|
||||
}
|
||||
|
|
@ -80,7 +87,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
public function testNoUpdates() {
|
||||
// Ensure that the definition update manager reports no updates.
|
||||
$this->assertFalse($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that no updates are needed.');
|
||||
$this->assertIdentical($this->entityDefinitionUpdateManager->getChangeSummary(), array(), 'EntityDefinitionUpdateManager reports an empty change summary.');
|
||||
$this->assertIdentical($this->entityDefinitionUpdateManager->getChangeSummary(), [], 'EntityDefinitionUpdateManager reports an empty change summary.');
|
||||
|
||||
// Ensure that applyUpdates() runs without error (it's not expected to do
|
||||
// anything when there aren't updates).
|
||||
|
|
@ -99,11 +106,14 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// reports that an update is needed.
|
||||
$this->updateEntityTypeToRevisionable();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %entity_type entity type needs to be updated.', ['%entity_type' => $this->entityManager->getDefinition('entity_test_update')->getLabel()]),
|
||||
),
|
||||
);
|
||||
// The revision key is now defined, so the revision field needs to be
|
||||
// created.
|
||||
t('The %field_name field needs to be installed.', ['%field_name' => 'Revision ID']),
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected); //, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
|
||||
// Run the update and ensure the revision table is created.
|
||||
|
|
@ -138,11 +148,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// creates its schema.
|
||||
$this->addBaseField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be installed.', ['%field_name' => t('A new base field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertTrue($this->database->schema()->fieldExists('entity_test_update', 'new_base_field'), 'Column created in shared table for new_base_field.');
|
||||
|
|
@ -151,11 +161,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// and the update creates it.
|
||||
$this->addBaseFieldIndex();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be updated.', ['%field_name' => t('A new base field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertTrue($this->database->schema()->indexExists('entity_test_update', 'entity_test_update_field__new_base_field'), 'Index created.');
|
||||
|
|
@ -164,11 +174,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// update deletes it.
|
||||
$this->removeBaseFieldIndex();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be updated.', ['%field_name' => t('A new base field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertFalse($this->database->schema()->indexExists('entity_test_update', 'entity_test_update_field__new_base_field'), 'Index deleted.');
|
||||
|
|
@ -178,11 +188,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// accordingly.
|
||||
$this->modifyBaseField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be updated.', ['%field_name' => t('A new base field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertFalse($this->database->schema()->fieldExists('entity_test_update', 'new_base_field'), 'Original column deleted in shared table for new_base_field.');
|
||||
|
|
@ -193,11 +203,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// update deletes the schema.
|
||||
$this->removeBaseField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be uninstalled.', ['%field_name' => t('A new base field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertFalse($this->database->schema()->fieldExists('entity_test_update', 'new_base_field_value'), 'Value column deleted from shared table for new_base_field.');
|
||||
|
|
@ -212,11 +222,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// creates its schema.
|
||||
$this->addBundleField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be installed.', ['%field_name' => t('A new bundle field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertTrue($this->database->schema()->tableExists('entity_test_update__new_bundle_field'), 'Dedicated table created for new_bundle_field.');
|
||||
|
|
@ -226,11 +236,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// accordingly.
|
||||
$this->modifyBundleField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be updated.', ['%field_name' => t('A new bundle field')]),
|
||||
],
|
||||
);
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertTrue($this->database->schema()->fieldExists('entity_test_update__new_bundle_field', 'new_bundle_field_format'), 'Format column created in dedicated table for new_base_field.');
|
||||
|
|
@ -239,11 +249,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// update deletes the schema.
|
||||
$this->removeBundleField();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %field_name field needs to be uninstalled.', ['%field_name' => t('A new bundle field')]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertFalse($this->database->schema()->tableExists('entity_test_update__new_bundle_field'), 'Dedicated table deleted for new_bundle_field.');
|
||||
|
|
@ -261,7 +271,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// Save an entity.
|
||||
$name = $this->randomString();
|
||||
$storage = $this->entityManager->getStorage('entity_test_update');
|
||||
$entity = $storage->create(array('name' => $name));
|
||||
$entity = $storage->create(['name' => $name]);
|
||||
$entity->save();
|
||||
|
||||
// Add a base field and run the update. Ensure the base field's column is
|
||||
|
|
@ -301,7 +311,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$assert = $schema_handler->fieldExists('entity_test_update', 'new_base_field__shape') && $schema_handler->fieldExists('entity_test_update', 'new_base_field__color');
|
||||
$this->assertTrue($assert, 'Columns created again in shared table for new_base_field.');
|
||||
$entity = $storage->create(array('name' => $name));
|
||||
$entity = $storage->create(['name' => $name]);
|
||||
$entity->save();
|
||||
$this->pass('The new_base_field columns are still nullable');
|
||||
}
|
||||
|
|
@ -318,7 +328,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// Save an entity.
|
||||
$name = $this->randomString();
|
||||
$storage = $this->entityManager->getStorage('entity_test_update');
|
||||
$entity = $storage->create(array('name' => $name));
|
||||
$entity = $storage->create(['name' => $name]);
|
||||
$entity->save();
|
||||
|
||||
// Add a bundle field and run the update. Ensure the bundle field's table
|
||||
|
|
@ -342,7 +352,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
$this->addBundleField('shape_required');
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$message = 'The new_bundle_field_shape column is not nullable.';
|
||||
$values = array(
|
||||
$values = [
|
||||
'bundle' => $entity->bundle(),
|
||||
'deleted' => 0,
|
||||
'entity_id' => $entity->id(),
|
||||
|
|
@ -350,7 +360,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
|
||||
'delta' => 0,
|
||||
'new_bundle_field_color' => $this->randomString(),
|
||||
);
|
||||
];
|
||||
try {
|
||||
// Try to insert a record without providing a value for the 'not null'
|
||||
// column. This should fail.
|
||||
|
|
@ -385,7 +395,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
|
||||
// Save an entity with the base field populated.
|
||||
$this->entityManager->getStorage('entity_test_update')->create(array('new_base_field' => 'foo'))->save();
|
||||
$this->entityManager->getStorage('entity_test_update')->create(['new_base_field' => 'foo'])->save();
|
||||
|
||||
// Remove the base field and apply updates. It's expected to throw an
|
||||
// exception.
|
||||
|
|
@ -411,7 +421,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
|
||||
// Save an entity with the bundle field populated.
|
||||
entity_test_create_bundle('custom');
|
||||
$this->entityManager->getStorage('entity_test_update')->create(array('type' => 'test_bundle', 'new_bundle_field' => 'foo'))->save();
|
||||
$this->entityManager->getStorage('entity_test_update')->create(['type' => 'test_bundle', 'new_bundle_field' => 'foo'])->save();
|
||||
|
||||
// Remove the bundle field and apply updates. It's expected to throw an
|
||||
// exception.
|
||||
|
|
@ -436,7 +446,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
|
||||
// Save an entity with the base field populated.
|
||||
$this->entityManager->getStorage('entity_test_update')->create(array('new_base_field' => 'foo'))->save();
|
||||
$this->entityManager->getStorage('entity_test_update')->create(['new_base_field' => 'foo'])->save();
|
||||
|
||||
// Change the field's field type and apply updates. It's expected to
|
||||
// throw an exception.
|
||||
|
|
@ -460,7 +470,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
|
||||
// Save an entity with the bundle field populated.
|
||||
entity_test_create_bundle('custom');
|
||||
$this->entityManager->getStorage('entity_test_update')->create(array('type' => 'test_bundle', 'new_bundle_field' => 'foo'))->save();
|
||||
$this->entityManager->getStorage('entity_test_update')->create(['type' => 'test_bundle', 'new_bundle_field' => 'foo'])->save();
|
||||
|
||||
// Change the field's field type and apply updates. It's expected to
|
||||
// throw an exception.
|
||||
|
|
@ -482,11 +492,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// update to the entity type.
|
||||
$this->addEntityIndex();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %entity_type entity type needs to be updated.', ['%entity_type' => $this->entityManager->getDefinition('entity_test_update')->getLabel()]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
|
||||
// Run the update and ensure the new index is created.
|
||||
|
|
@ -497,11 +507,11 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// update to the entity type.
|
||||
$this->removeEntityIndex();
|
||||
$this->assertTrue($this->entityDefinitionUpdateManager->needsUpdates(), 'EntityDefinitionUpdateManager reports that updates are needed.');
|
||||
$expected = array(
|
||||
'entity_test_update' => array(
|
||||
$expected = [
|
||||
'entity_test_update' => [
|
||||
t('The %entity_type entity type needs to be updated.', ['%entity_type' => $this->entityManager->getDefinition('entity_test_update')->getLabel()]),
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($this->entityDefinitionUpdateManager->getChangeSummary(), $expected, 'EntityDefinitionUpdateManager reports the expected change summary.');
|
||||
|
||||
// Run the update and ensure the index is deleted.
|
||||
|
|
@ -527,7 +537,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
public function testEntityIndexCreateWithData() {
|
||||
// Save an entity.
|
||||
$name = $this->randomString();
|
||||
$entity = $this->entityManager->getStorage('entity_test_update')->create(array('name' => $name));
|
||||
$entity = $this->entityManager->getStorage('entity_test_update')->create(['name' => $name]);
|
||||
$entity->save();
|
||||
|
||||
// Add an entity index, run the update. Ensure that the index is created
|
||||
|
|
@ -729,13 +739,13 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
// Save an entity.
|
||||
$name = $this->randomString();
|
||||
$storage = $this->entityManager->getStorage('entity_test_update');
|
||||
$entity = $storage->create(array('name' => $name));
|
||||
$entity = $storage->create(['name' => $name]);
|
||||
$entity->save();
|
||||
|
||||
// Create an index.
|
||||
$indexes = array(
|
||||
'entity_test_update__type_index' => array('type'),
|
||||
);
|
||||
$indexes = [
|
||||
'entity_test_update__type_index' => ['type'],
|
||||
];
|
||||
$this->state->set('entity_test_update.additional_entity_indexes', $indexes);
|
||||
$this->entityDefinitionUpdateManager->applyUpdates();
|
||||
$this->assertTrue($this->database->schema()->indexExists('entity_test_update', 'entity_test_update__type_index'), "New index 'entity_test_update__type_index' has been created on the 'entity_test_update' table.");
|
||||
|
|
@ -797,7 +807,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
|
|||
/**
|
||||
* Check that field schema is correctly handled with long-named fields.
|
||||
*/
|
||||
function testLongNameFieldIndexes() {
|
||||
public function testLongNameFieldIndexes() {
|
||||
$this->addLongNameBaseField();
|
||||
$entity_type_id = 'entity_test_update';
|
||||
$entity_type = $this->entityManager->getDefinition($entity_type_id);
|
||||
|
|
|
|||
|
|
@ -20,6 +20,43 @@ class EntityDisplayBaseTest extends KernelTestBase {
|
|||
*/
|
||||
public static $modules = ['entity_test', 'entity_test_third_party', 'field', 'system', 'comment'];
|
||||
|
||||
/**
|
||||
* @covers ::preSave
|
||||
*/
|
||||
public function testPreSave() {
|
||||
$entity_display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'entity_test',
|
||||
'bundle' => 'entity_test',
|
||||
'mode' => 'default',
|
||||
'status' => TRUE,
|
||||
'content' => [
|
||||
'foo' => ['type' => 'visible'],
|
||||
'bar' => ['type' => 'hidden'],
|
||||
'name' => ['type' => 'hidden', 'region' => 'content'],
|
||||
],
|
||||
]);
|
||||
|
||||
// Ensure that no region is set on the component.
|
||||
$this->assertArrayNotHasKey('region', $entity_display->getComponent('foo'));
|
||||
$this->assertArrayNotHasKey('region', $entity_display->getComponent('bar'));
|
||||
|
||||
// Ensure that a region is set on the component after saving.
|
||||
$entity_display->save();
|
||||
|
||||
// The component with a visible type has been assigned a region.
|
||||
$component = $entity_display->getComponent('foo');
|
||||
$this->assertArrayHasKey('region', $component);
|
||||
$this->assertSame('content', $component['region']);
|
||||
|
||||
// The component with a hidden type has been removed.
|
||||
$this->assertNull($entity_display->getComponent('bar'));
|
||||
|
||||
// The component with a valid region and hidden type is unchanged.
|
||||
$component = $entity_display->getComponent('name');
|
||||
$this->assertArrayHasKey('region', $component);
|
||||
$this->assertSame('content', $component['region']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::onDependencyRemoval
|
||||
*/
|
||||
|
|
@ -67,7 +104,7 @@ class EntityDisplayBaseTest extends KernelTestBase {
|
|||
'mode' => 'default',
|
||||
'status' => TRUE,
|
||||
'content' => [
|
||||
'test_field' => ['type' => 'comment_default', 'settings' => ['view_mode' => 'default'], 'label' => 'hidden', 'third_party_settings' => []],
|
||||
'test_field' => ['type' => 'comment_default', 'region' => 'content', 'settings' => ['view_mode' => 'default'], 'label' => 'hidden', 'third_party_settings' => []],
|
||||
],
|
||||
'third_party_settings' => [
|
||||
'entity_test_third_party' => [
|
||||
|
|
@ -79,6 +116,7 @@ class EntityDisplayBaseTest extends KernelTestBase {
|
|||
|
||||
$expected_component = [
|
||||
'type' => 'comment_default',
|
||||
'region' => 'content',
|
||||
'settings' => ['view_mode' => 'default'],
|
||||
'label' => 'hidden',
|
||||
'third_party_settings' => [],
|
||||
|
|
|
|||
|
|
@ -0,0 +1,144 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\Core\Entity\Display\EntityDisplayInterface;
|
||||
use Drupal\Core\Form\FormState;
|
||||
use Drupal\field_ui\Form\EntityViewDisplayEditForm;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\field_ui\Form\EntityDisplayFormBase
|
||||
*
|
||||
* @group Entity
|
||||
*/
|
||||
class EntityDisplayFormBaseTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['entity_test'];
|
||||
|
||||
/**
|
||||
* @covers ::copyFormValuesToEntity
|
||||
*/
|
||||
public function testCopyFormValuesToEntity() {
|
||||
$field_values = [];
|
||||
$entity = $this->prophesize(EntityDisplayInterface::class);
|
||||
$entity->getPluginCollections()->willReturn([]);
|
||||
$entity->getTargetEntityTypeId()->willReturn('entity_test_with_bundle');
|
||||
$entity->getTargetBundle()->willReturn('target_bundle');
|
||||
|
||||
// An initially hidden field, with a submitted region change.
|
||||
$entity->getComponent('new_field_mismatch_type_visible')->willReturn([]);
|
||||
$field_values['new_field_mismatch_type_visible'] = [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'hidden',
|
||||
];
|
||||
$entity->removeComponent('new_field_mismatch_type_visible')
|
||||
->will(function ($args) {
|
||||
// On subsequent calls, getComponent() will return an empty array.
|
||||
$this->getComponent($args[0])->willReturn([]);
|
||||
})
|
||||
->shouldBeCalled();
|
||||
|
||||
// An initially visible field, with identical submitted values.
|
||||
$entity->getComponent('field_visible_no_changes')
|
||||
->willReturn([
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
]);
|
||||
$field_values['field_visible_no_changes'] = [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
];
|
||||
$entity
|
||||
->setComponent('field_visible_no_changes', [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
])
|
||||
->shouldBeCalled();
|
||||
|
||||
|
||||
// An initially visible field, with a submitted region change.
|
||||
$entity->getComponent('field_start_visible_change_region')
|
||||
->willReturn([
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
]);
|
||||
$field_values['field_start_visible_change_region'] = [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'hidden',
|
||||
];
|
||||
$entity->removeComponent('field_start_visible_change_region')
|
||||
->will(function ($args) {
|
||||
// On subsequent calls, getComponent() will return an empty array.
|
||||
$this->getComponent($args[0])->willReturn([]);
|
||||
})
|
||||
->shouldBeCalled();
|
||||
|
||||
// A field that is flagged for plugin settings update on the second build.
|
||||
$entity->getComponent('field_plugin_settings_update')
|
||||
->willReturn([
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
]);
|
||||
$field_values['field_plugin_settings_update'] = [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
'settings_edit_form' => [
|
||||
'third_party_settings' => [
|
||||
'foo' => 'bar',
|
||||
],
|
||||
],
|
||||
];
|
||||
$entity
|
||||
->setComponent('field_plugin_settings_update', [
|
||||
'weight' => 0,
|
||||
'type' => 'textfield',
|
||||
'region' => 'content',
|
||||
])
|
||||
->will(function ($args) {
|
||||
// On subsequent calls, getComponent() will return the newly set values.
|
||||
$this->getComponent($args[0])->willReturn($args[1]);
|
||||
$args[1] += [
|
||||
'settings' => [],
|
||||
'third_party_settings' => [
|
||||
'foo' => 'bar',
|
||||
],
|
||||
];
|
||||
$this->setComponent($args[0], $args[1])->shouldBeCalled();
|
||||
})
|
||||
->shouldBeCalled();
|
||||
|
||||
$form_object = new EntityViewDisplayEditForm($this->container->get('plugin.manager.field.field_type'), $this->container->get('plugin.manager.field.formatter'));
|
||||
$form_object->setEntityManager($this->container->get('entity.manager'));
|
||||
$form_object->setEntity($entity->reveal());
|
||||
|
||||
$form = [
|
||||
'#fields' => array_keys($field_values),
|
||||
'#extra' => [],
|
||||
];
|
||||
$form_state = new FormState();
|
||||
$form_state->setValues(['fields' => $field_values]);
|
||||
$form_state->setProcessInput();
|
||||
|
||||
$form_object->buildEntity($form, $form_state);
|
||||
$form_state->setSubmitted();
|
||||
|
||||
// Flag one field for updating plugin settings.
|
||||
$form_state->set('plugin_settings_update', 'field_plugin_settings_update');
|
||||
// During form submission, buildEntity() will be called twice. Simulate that
|
||||
// here to prove copyFormValuesToEntity() is idempotent.
|
||||
$form_object->buildEntity($form, $form_state);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTestRev;
|
||||
|
||||
/**
|
||||
* Test entity duplication.
|
||||
*
|
||||
* @group Entity
|
||||
*/
|
||||
class EntityDuplicateTest extends EntityKernelTestBase {
|
||||
|
||||
/**
|
||||
* @var \Drupal\Core\Entity\ContentEntityStorageInterface
|
||||
*/
|
||||
protected $entityTestRevStorage;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installEntitySchema('entity_test_rev');
|
||||
$this->entityTestRevStorage = $this->container->get('entity_type.manager')->getStorage('entity_test_rev');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test duplicating a non-default revision.
|
||||
*/
|
||||
public function testDuplicateNonDefaultRevision() {
|
||||
$entity = EntityTestRev::create([
|
||||
'name' => 'First Revision',
|
||||
]);
|
||||
$entity->save();
|
||||
$first_revision_id = $entity->getRevisionId();
|
||||
|
||||
$entity->setNewRevision(TRUE);
|
||||
$entity->name = 'Second Revision';
|
||||
$entity->save();
|
||||
|
||||
$duplicate_first_revision = $this->entityTestRevStorage->loadRevision($first_revision_id)->createDuplicate();
|
||||
$this->assertTrue($duplicate_first_revision->isDefaultRevision(), 'Duplicating a non-default revision creates a default revision.');
|
||||
$this->assertEquals($duplicate_first_revision->label(), 'First Revision');
|
||||
$duplicate_first_revision->save();
|
||||
|
||||
$duplicate_first_revision->name = 'Updated name';
|
||||
$duplicate_first_revision->save();
|
||||
|
||||
$this->entityTestRevStorage->resetCache();
|
||||
$duplicate_first_revision = EntityTestRev::load($duplicate_first_revision->id());
|
||||
$this->assertEquals('Updated name', $duplicate_first_revision->label());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -47,9 +47,9 @@ class EntityFieldDefaultValueTest extends EntityKernelTestBase {
|
|||
->create();
|
||||
$definition = $this->entityManager->getDefinition($entity_type_id);
|
||||
$langcode_key = $definition->getKey('langcode');
|
||||
$this->assertEqual($entity->{$langcode_key}->value, 'en', SafeMarkup::format('%entity_type: Default language', array('%entity_type' => $entity_type_id)));
|
||||
$this->assertTrue(Uuid::isValid($entity->uuid->value), SafeMarkup::format('%entity_type: Default UUID', array('%entity_type' => $entity_type_id)));
|
||||
$this->assertEqual($entity->name->getValue(), array(), 'Field has one empty value by default.');
|
||||
$this->assertEqual($entity->{$langcode_key}->value, 'en', SafeMarkup::format('%entity_type: Default language', ['%entity_type' => $entity_type_id]));
|
||||
$this->assertTrue(Uuid::isValid($entity->uuid->value), SafeMarkup::format('%entity_type: Default UUID', ['%entity_type' => $entity_type_id]));
|
||||
$this->assertEqual($entity->name->getValue(), [], 'Field has one empty value by default.');
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -60,16 +60,16 @@ class EntityFieldDefaultValueTest extends EntityKernelTestBase {
|
|||
// The description field has a default value callback for testing, see
|
||||
// entity_test_field_default_value().
|
||||
$string = 'description_' . $entity->language()->getId();
|
||||
$expected = array(
|
||||
array(
|
||||
$expected = [
|
||||
[
|
||||
'shape' => "shape:0:$string",
|
||||
'color' => "color:0:$string",
|
||||
),
|
||||
array(
|
||||
],
|
||||
[
|
||||
'shape' => "shape:1:$string",
|
||||
'color' => "color:1:$string",
|
||||
),
|
||||
);
|
||||
],
|
||||
];
|
||||
$this->assertEqual($entity->description->getValue(), $expected);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\Core\Entity\EntityInterface;
|
||||
use Drupal\Core\Entity\RevisionLogInterface;
|
||||
use Drupal\Core\Entity\TypedData\EntityDataDefinition;
|
||||
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
|
||||
use Drupal\Core\Field\BaseFieldDefinition;
|
||||
|
|
@ -30,7 +31,7 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = array('filter', 'text', 'node', 'user', 'field_test');
|
||||
public static $modules = ['filter', 'text', 'node', 'user', 'field_test'];
|
||||
|
||||
/**
|
||||
* @var string
|
||||
|
|
@ -62,7 +63,7 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
entity_test_install();
|
||||
|
||||
// Install required default configuration for filter module.
|
||||
$this->installConfig(array('system', 'filter'));
|
||||
$this->installConfig(['system', 'filter']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -111,108 +112,108 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
$langcode = 'en';
|
||||
|
||||
// Access the name field.
|
||||
$this->assertTrue($entity->name instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->name[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', ['%entity_type' => $entity_type]));
|
||||
|
||||
$this->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityName, $entity->name[0]->value, format_string('%entity_type: Name value can be read through list access.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name->getValue(), array(0 => array('value' => $this->entityName)), format_string('%entity_type: Plain field value returned.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityName, $entity->name[0]->value, format_string('%entity_type: Name value can be read through list access.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name->getValue(), [0 => ['value' => $this->entityName]], format_string('%entity_type: Plain field value returned.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Change the name.
|
||||
$new_name = $this->randomMachineName();
|
||||
$entity->name->value = $new_name;
|
||||
$this->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name->getValue(), array(0 => array('value' => $new_name)), format_string('%entity_type: Plain field value reflects the update.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name->getValue(), [0 => ['value' => $new_name]], format_string('%entity_type: Plain field value reflects the update.', ['%entity_type' => $entity_type]));
|
||||
|
||||
$new_name = $this->randomMachineName();
|
||||
$entity->name[0]->value = $new_name;
|
||||
$this->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read through list access.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read through list access.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Access the user field.
|
||||
$this->assertTrue($entity->user_id instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->user_id[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->user_id instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->user_id[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', ['%entity_type' => $entity_type]));
|
||||
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Change the assigned user by entity.
|
||||
$new_user1 = $this->createUser();
|
||||
$entity->user_id->entity = $new_user1;
|
||||
$this->assertEqual($new_user1->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user1->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user1->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($new_user1->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Change the assigned user by id.
|
||||
$new_user2 = $this->createUser();
|
||||
$entity->user_id->target_id = $new_user2->id();
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Try unsetting a field property.
|
||||
$entity->name->value = NULL;
|
||||
$entity->user_id->target_id = NULL;
|
||||
$this->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test setting the values via the typed data API works as well.
|
||||
// Change the assigned user by entity.
|
||||
$entity->user_id->first()->get('entity')->setValue($new_user2);
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Change the assigned user by id.
|
||||
$entity->user_id->first()->get('target_id')->setValue($new_user2->id());
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($new_user2->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Try unsetting a field.
|
||||
$entity->name->first()->get('value')->setValue(NULL);
|
||||
$entity->user_id->first()->get('target_id')->setValue(NULL);
|
||||
$this->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Create a fresh entity so target_id does not get its property object
|
||||
// instantiated, then verify setting a new value via typed data API works.
|
||||
$entity2 = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array(
|
||||
'user_id' => array('target_id' => $new_user1->id()),
|
||||
));
|
||||
->create([
|
||||
'user_id' => ['target_id' => $new_user1->id()],
|
||||
]);
|
||||
// Access the property object, and set a value.
|
||||
$entity2->user_id->first()->get('target_id')->setValue($new_user2->id());
|
||||
$this->assertEqual($new_user2->id(), $entity2->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->name->value, $entity2->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($new_user2->id(), $entity2->user_id->target_id, format_string('%entity_type: Updated user id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($new_user2->name->value, $entity2->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test using isset(), empty() and unset().
|
||||
$entity->name->value = 'test unset';
|
||||
unset($entity->name->value);
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(empty($entity->name->value), format_string('%entity_type: Name is empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(empty($entity->name[0]->value), format_string('%entity_type: Name is empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(empty($entity->name->value), format_string('%entity_type: Name is empty.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(empty($entity->name[0]->value), format_string('%entity_type: Name is empty.', ['%entity_type' => $entity_type]));
|
||||
|
||||
$entity->name->value = 'a value';
|
||||
$this->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name[0]->value), format_string('%entity_type: Name is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(empty($entity->name->value), format_string('%entity_type: Name is not empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(empty($entity->name[0]->value), format_string('%entity_type: Name is not empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name[0]), format_string('%entity_type: Name string item is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[1]), format_string('%entity_type: Second name string item is not set as it does not exist', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->nameInvalid), format_string('%entity_type: Not existing field is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(isset($entity->name[0]->value), format_string('%entity_type: Name is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(empty($entity->name->value), format_string('%entity_type: Name is not empty.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(empty($entity->name[0]->value), format_string('%entity_type: Name is not empty.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(isset($entity->name[0]), format_string('%entity_type: Name string item is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name[1]), format_string('%entity_type: Second name string item is not set as it does not exist', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->nameInvalid), format_string('%entity_type: Not existing field is not set.', ['%entity_type' => $entity_type]));
|
||||
|
||||
unset($entity->name[0]);
|
||||
$this->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test emptying a field by assigning an empty value. NULL and array()
|
||||
// behave the same.
|
||||
foreach ([NULL, array(), 'unset'] as $empty) {
|
||||
foreach ([NULL, [], 'unset'] as $empty) {
|
||||
// Make sure a value is present
|
||||
$entity->name->value = 'a value';
|
||||
$this->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', ['%entity_type' => $entity_type]));
|
||||
// Now, empty the field.
|
||||
if ($empty === 'unset') {
|
||||
unset($entity->name);
|
||||
|
|
@ -220,36 +221,36 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
else {
|
||||
$entity->name = $empty;
|
||||
}
|
||||
$this->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name->isEmpty(), format_string('%entity_type: Name field is set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertIdentical(count($entity->name), 0, format_string('%entity_type: Name field contains no items.', array('%entity_type' => $entity_type)));
|
||||
$this->assertIdentical($entity->name->getValue(), array(), format_string('%entity_type: Name field value is an empty array.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: First name item value is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name value is not set.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->name->isEmpty(), format_string('%entity_type: Name field is set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertIdentical(count($entity->name), 0, format_string('%entity_type: Name field contains no items.', ['%entity_type' => $entity_type]));
|
||||
$this->assertIdentical($entity->name->getValue(), [], format_string('%entity_type: Name field value is an empty array.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: First name item value is not set.', ['%entity_type' => $entity_type]));
|
||||
$this->assertFalse(isset($entity->name->value), format_string('%entity_type: Name value is not set.', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
// Access the language field.
|
||||
$langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
|
||||
$this->assertEqual($langcode, $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getLanguage($langcode), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($langcode, $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(\Drupal::languageManager()->getLanguage($langcode), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Change the language by code.
|
||||
$entity->{$langcode_key}->value = \Drupal::languageManager()->getDefaultLanguage()->getId();
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage()->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage()->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Revert language by code then try setting it by language object.
|
||||
$entity->{$langcode_key}->value = $langcode;
|
||||
$entity->{$langcode_key}->language = \Drupal::languageManager()->getDefaultLanguage();
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage()->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage()->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(\Drupal::languageManager()->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Access the text field and test updating.
|
||||
$this->assertEqual($entity->field_test_text->value, $this->entityFieldText, format_string('%entity_type: Text field can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->field_test_text->value, $this->entityFieldText, format_string('%entity_type: Text field can be read.', ['%entity_type' => $entity_type]));
|
||||
$new_text = $this->randomMachineName();
|
||||
$entity->field_test_text->value = $new_text;
|
||||
$this->assertEqual($entity->field_test_text->value, $new_text, format_string('%entity_type: Updated text field can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->field_test_text->value, $new_text, format_string('%entity_type: Updated text field can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test creating the entity by passing in plain values.
|
||||
$this->entityName = $this->randomMachineName();
|
||||
|
|
@ -261,98 +262,98 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array(
|
||||
->create([
|
||||
'name' => $name_item,
|
||||
'user_id' => $user_item,
|
||||
'field_test_text' => $text_item,
|
||||
));
|
||||
$this->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array('%entity_type' => $entity_type)));
|
||||
]);
|
||||
$this->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Tests copying field values by assigning the TypedData objects.
|
||||
$entity2 = $this->createTestEntity($entity_type);
|
||||
$entity2->name = $entity->name;
|
||||
$entity2->user_id = $entity->user_id;
|
||||
$entity2->field_test_text = $entity->field_test_text;
|
||||
$this->assertFalse($entity->name === $entity2->name, format_string('%entity_type: Copying properties results in a different field object.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name->value, $entity2->name->value, format_string('%entity_type: Name field copied.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, format_string('%entity_type: User id field copied.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, format_string('%entity_type: Text field copied.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse($entity->name === $entity2->name, format_string('%entity_type: Copying properties results in a different field object.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name->value, $entity2->name->value, format_string('%entity_type: Name field copied.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, format_string('%entity_type: User id field copied.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, format_string('%entity_type: Text field copied.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Tests that assigning TypedData objects to non-field properties keeps the
|
||||
// assigned value as is.
|
||||
$entity2 = $this->createTestEntity($entity_type);
|
||||
$entity2->_not_a_field = $entity->name;
|
||||
$this->assertTrue($entity2->_not_a_field === $entity->name, format_string('%entity_type: Typed data objects can be copied to non-field properties as is.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity2->_not_a_field === $entity->name, format_string('%entity_type: Typed data objects can be copied to non-field properties as is.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Tests adding a value to a field item list.
|
||||
$entity->name[] = 'Another name';
|
||||
$this->assertEqual($entity->name[1]->value, 'Another name', format_string('%entity_type: List item added via [] and the first property.', array('%entity_type' => $entity_type)));
|
||||
$entity->name[] = array('value' => 'Third name');
|
||||
$this->assertEqual($entity->name[2]->value, 'Third name', format_string('%entity_type: List item added via [] and an array of properties.', array('%entity_type' => $entity_type)));
|
||||
$entity->name[3] = array('value' => 'Fourth name');
|
||||
$this->assertEqual($entity->name[3]->value, 'Fourth name', format_string('%entity_type: List item added via offset and an array of properties.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[1]->value, 'Another name', format_string('%entity_type: List item added via [] and the first property.', ['%entity_type' => $entity_type]));
|
||||
$entity->name[] = ['value' => 'Third name'];
|
||||
$this->assertEqual($entity->name[2]->value, 'Third name', format_string('%entity_type: List item added via [] and an array of properties.', ['%entity_type' => $entity_type]));
|
||||
$entity->name[3] = ['value' => 'Fourth name'];
|
||||
$this->assertEqual($entity->name[3]->value, 'Fourth name', format_string('%entity_type: List item added via offset and an array of properties.', ['%entity_type' => $entity_type]));
|
||||
unset($entity->name[3]);
|
||||
|
||||
// Test removing and empty-ing list items.
|
||||
$this->assertEqual(count($entity->name), 3, format_string('%entity_type: List has 3 items.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count($entity->name), 3, format_string('%entity_type: List has 3 items.', ['%entity_type' => $entity_type]));
|
||||
unset($entity->name[1]);
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: Second list item has been removed.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[1]->value, 'Third name', format_string('%entity_type: The subsequent items have been shifted up.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[1]->getName(), 1, format_string('%entity_type: The items names have been updated to their new delta.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: Second list item has been removed.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name[1]->value, 'Third name', format_string('%entity_type: The subsequent items have been shifted up.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name[1]->getName(), 1, format_string('%entity_type: The items names have been updated to their new delta.', ['%entity_type' => $entity_type]));
|
||||
$entity->name[1] = NULL;
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: Assigning NULL does not reduce array count.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name[1]->isEmpty(), format_string('%entity_type: Assigning NULL empties the item.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: Assigning NULL does not reduce array count.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->name[1]->isEmpty(), format_string('%entity_type: Assigning NULL empties the item.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test using isEmpty().
|
||||
unset($entity->name[1]);
|
||||
$this->assertFalse($entity->name[0]->isEmpty(), format_string('%entity_type: Name item is not empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertFalse($entity->name[0]->isEmpty(), format_string('%entity_type: Name item is not empty.', ['%entity_type' => $entity_type]));
|
||||
$entity->name->value = NULL;
|
||||
$this->assertTrue($entity->name[0]->isEmpty(), format_string('%entity_type: Name item is empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name->isEmpty(), format_string('%entity_type: Name field is empty.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count($entity->name), 1, format_string('%entity_type: Empty item is considered when counting.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count(iterator_to_array($entity->name->getIterator())), count($entity->name), format_string('%entity_type: Count matches iterator count.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name->getValue() === array(0 => array('value' => NULL)), format_string('%entity_type: Name field value contains a NULL value.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue($entity->name[0]->isEmpty(), format_string('%entity_type: Name item is empty.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->name->isEmpty(), format_string('%entity_type: Name field is empty.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(count($entity->name), 1, format_string('%entity_type: Empty item is considered when counting.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(count(iterator_to_array($entity->name->getIterator())), count($entity->name), format_string('%entity_type: Count matches iterator count.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue($entity->name->getValue() === [0 => ['value' => NULL]], format_string('%entity_type: Name field value contains a NULL value.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test using filterEmptyItems().
|
||||
$entity->name = array(NULL, 'foo');
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: List has 2 items.', array('%entity_type' => $entity_type)));
|
||||
$entity->name = [NULL, 'foo'];
|
||||
$this->assertEqual(count($entity->name), 2, format_string('%entity_type: List has 2 items.', ['%entity_type' => $entity_type]));
|
||||
$entity->name->filterEmptyItems();
|
||||
$this->assertEqual(count($entity->name), 1, format_string('%entity_type: The empty item was removed.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[0]->value, 'foo', format_string('%entity_type: The items were renumbered.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[0]->getName(), 0, format_string('%entity_type: The deltas were updated in the items.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(count($entity->name), 1, format_string('%entity_type: The empty item was removed.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name[0]->value, 'foo', format_string('%entity_type: The items were renumbered.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($entity->name[0]->getName(), 0, format_string('%entity_type: The deltas were updated in the items.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test get and set field values.
|
||||
$entity->name = 'foo';
|
||||
$this->assertEqual($entity->name[0]->toArray(), array('value' => 'foo'), format_string('%entity_type: Field value has been retrieved via toArray()', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->name[0]->toArray(), ['value' => 'foo'], format_string('%entity_type: Field value has been retrieved via toArray()', ['%entity_type' => $entity_type]));
|
||||
|
||||
$values = $entity->toArray();
|
||||
$this->assertEqual($values['name'], array(0 => array('value' => 'foo')), format_string('%entity_type: Field value has been retrieved via toArray() from an entity.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($values['name'], [0 => ['value' => 'foo']], format_string('%entity_type: Field value has been retrieved via toArray() from an entity.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Make sure the user id can be set to zero.
|
||||
$user_item[0]['target_id'] = 0;
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array(
|
||||
->create([
|
||||
'name' => $name_item,
|
||||
'user_id' => $user_item,
|
||||
'field_test_text' => $text_item,
|
||||
));
|
||||
$this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
|
||||
$this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
|
||||
]);
|
||||
$this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', ['%entity_type' => $entity_type]));
|
||||
$this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Test setting the ID with the value only.
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->create(array(
|
||||
->create([
|
||||
'name' => $name_item,
|
||||
'user_id' => 0,
|
||||
'field_test_text' => $text_item,
|
||||
));
|
||||
$this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array('%entity_type' => $entity_type)));
|
||||
$this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array('%entity_type' => $entity_type)));
|
||||
]);
|
||||
$this->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', ['%entity_type' => $entity_type]));
|
||||
$this->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -375,21 +376,21 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
$langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
|
||||
$entity = $this->createTestEntity($entity_type);
|
||||
$entity->save();
|
||||
$this->assertTrue((bool) $entity->id(), format_string('%entity_type: Entity has received an id.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue((bool) $entity->id(), format_string('%entity_type: Entity has received an id.', ['%entity_type' => $entity_type]));
|
||||
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->load($entity->id());
|
||||
$this->assertTrue((bool) $entity->id(), format_string('%entity_type: Entity loaded.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue((bool) $entity->id(), format_string('%entity_type: Entity loaded.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Access the name field.
|
||||
$this->assertEqual(1, $entity->id->value, format_string('%entity_type: ID value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertTrue(is_string($entity->uuid->value), format_string('%entity_type: UUID value can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual('en', $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(\Drupal::languageManager()->getLanguage('en'), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(1, $entity->id->value, format_string('%entity_type: ID value can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertTrue(is_string($entity->uuid->value), format_string('%entity_type: UUID value can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual('en', $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual(\Drupal::languageManager()->getLanguage('en'), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityUser->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityUser->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -531,8 +532,8 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
}
|
||||
|
||||
$fields = $entity->getFields();
|
||||
$this->assertEqual(array_keys($fields), array_keys($entity->getTypedData()->getDataDefinition()->getPropertyDefinitions()), format_string('%entity_type: All fields returned.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($fields, iterator_to_array($entity->getIterator()), format_string('%entity_type: Entity iterator iterates over all fields.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(array_keys($fields), array_keys($entity->getTypedData()->getDataDefinition()->getPropertyDefinitions()), format_string('%entity_type: All fields returned.', ['%entity_type' => $entity_type]));
|
||||
$this->assertEqual($fields, iterator_to_array($entity->getIterator()), format_string('%entity_type: Entity iterator iterates over all fields.', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -557,12 +558,12 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
// Test using the whole tree of typed data by navigating through the tree of
|
||||
// contained properties and getting all contained strings, limited by a
|
||||
// certain depth.
|
||||
$strings = array();
|
||||
$strings = [];
|
||||
$this->getContainedStrings($entity->getTypedData(), 0, $strings);
|
||||
|
||||
// @todo: Once the user entity has defined properties this should contain
|
||||
// the user name and other user entity strings as well.
|
||||
$target_strings = array(
|
||||
$target_strings = [
|
||||
$entity->uuid->value,
|
||||
'en',
|
||||
$this->entityName,
|
||||
|
|
@ -571,10 +572,16 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
$this->entityFieldText,
|
||||
// Field format.
|
||||
NULL,
|
||||
);
|
||||
];
|
||||
|
||||
if ($entity instanceof RevisionLogInterface) {
|
||||
// Adding empty string for revision message.
|
||||
$target_strings[] = '';
|
||||
}
|
||||
|
||||
asort($strings);
|
||||
asort($target_strings);
|
||||
$this->assertEqual(array_values($strings), array_values($target_strings), format_string('%entity_type: All contained strings found.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual(array_values($strings), array_values($target_strings), format_string('%entity_type: All contained strings found.', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -622,10 +629,10 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
* @see entity_test_entity_base_field_info_alter()
|
||||
*/
|
||||
public function testBaseFieldNonExistingBaseField() {
|
||||
$this->entityManager->getStorage('node_type')->create(array(
|
||||
$this->entityManager->getStorage('node_type')->create([
|
||||
'type' => 'page',
|
||||
'name' => 'page',
|
||||
))->save();
|
||||
])->save();
|
||||
$this->entityManager->clearCachedFieldDefinitions();
|
||||
$fields = $this->entityManager->getFieldDefinitions('node', 'page');
|
||||
$override = $fields['status']->getConfig('page');
|
||||
|
|
@ -679,7 +686,7 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
->setLabel('Test entity')
|
||||
->setSetting('target_type', 'entity_test');
|
||||
$reference_field = \Drupal::typedDataManager()->create($definition);
|
||||
$reference = $reference_field->appendItem(array('entity' => $entity))->get('entity');
|
||||
$reference = $reference_field->appendItem(['entity' => $entity])->get('entity');
|
||||
|
||||
// Test validation the typed data object.
|
||||
$violations = $reference->validate();
|
||||
|
|
@ -698,14 +705,14 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
$this->assertEqual($violations->count(), 1);
|
||||
|
||||
// Test bundle validation.
|
||||
NodeType::create(array('type' => 'article'))
|
||||
NodeType::create(['type' => 'article'])
|
||||
->save();
|
||||
$definition = BaseFieldDefinition::create('entity_reference')
|
||||
->setLabel('Test entity')
|
||||
->setSetting('target_type', 'node')
|
||||
->setSetting('handler_settings', ['target_bundles' => ['article' => 'article']]);
|
||||
$reference_field = \Drupal::TypedDataManager()->create($definition);
|
||||
$reference_field->appendItem(array('entity' => $node));
|
||||
$reference_field->appendItem(['entity' => $node]);
|
||||
$violations = $reference_field->validate();
|
||||
$this->assertEqual($violations->count(), 1);
|
||||
|
||||
|
|
@ -742,14 +749,14 @@ class EntityFieldTest extends EntityKernelTestBase {
|
|||
$entity->field_test_text->format = filter_default_format();
|
||||
|
||||
$target = "<p>The <strong>text</strong> text to filter.</p>\n";
|
||||
$this->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', ['%entity_type' => $entity_type]));
|
||||
|
||||
// Save and load entity and make sure it still works.
|
||||
$entity->save();
|
||||
$entity = $this->container->get('entity_type.manager')
|
||||
->getStorage($entity_type)
|
||||
->load($entity->id());
|
||||
$this->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', array('%entity_type' => $entity_type)));
|
||||
$this->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', ['%entity_type' => $entity_type]));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $generatedIds = array();
|
||||
protected $generatedIds = [];
|
||||
|
||||
/**
|
||||
* The state service.
|
||||
|
|
@ -62,7 +62,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
// Only check the modules, if the $modules property was not inherited.
|
||||
$rp = new \ReflectionProperty($class, 'modules');
|
||||
if ($rp->class == $class) {
|
||||
foreach (array_intersect(array('node', 'comment'), $class::$modules) as $module) {
|
||||
foreach (array_intersect(['node', 'comment'], $class::$modules) as $module) {
|
||||
$this->installEntitySchema($module);
|
||||
}
|
||||
if (in_array('forum', $class::$modules, TRUE)) {
|
||||
|
|
@ -79,7 +79,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
$class = get_parent_class($class);
|
||||
}
|
||||
|
||||
$this->installConfig(array('field'));
|
||||
$this->installConfig(['field']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -93,22 +93,22 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
* @return \Drupal\user\Entity\User
|
||||
* The created user entity.
|
||||
*/
|
||||
protected function createUser($values = array(), $permissions = array()) {
|
||||
protected function createUser($values = [], $permissions = []) {
|
||||
if ($permissions) {
|
||||
// Create a new role and apply permissions to it.
|
||||
$role = Role::create(array(
|
||||
$role = Role::create([
|
||||
'id' => strtolower($this->randomMachineName(8)),
|
||||
'label' => $this->randomMachineName(8),
|
||||
));
|
||||
]);
|
||||
$role->save();
|
||||
user_role_grant_permissions($role->id(), $permissions);
|
||||
$values['roles'][] = $role->id();
|
||||
}
|
||||
|
||||
$account = User::create($values + array(
|
||||
$account = User::create($values + [
|
||||
'name' => $this->randomMachineName(),
|
||||
'status' => 1,
|
||||
));
|
||||
]);
|
||||
$account->enforceIsNew();
|
||||
$account->save();
|
||||
return $account;
|
||||
|
|
@ -125,7 +125,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
*/
|
||||
protected function reloadEntity(EntityInterface $entity) {
|
||||
$controller = $this->entityManager->getStorage($entity->getEntityTypeId());
|
||||
$controller->resetCache(array($entity->id()));
|
||||
$controller->resetCache([$entity->id()]);
|
||||
return $controller->load($entity->id());
|
||||
}
|
||||
|
||||
|
|
@ -138,7 +138,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
protected function getHooksInfo() {
|
||||
$key = 'entity_test.hooks';
|
||||
$hooks = $this->state->get($key);
|
||||
$this->state->set($key, array());
|
||||
$this->state->set($key, []);
|
||||
return $hooks;
|
||||
}
|
||||
|
||||
|
|
@ -149,7 +149,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
* The module to install.
|
||||
*/
|
||||
protected function installModule($module) {
|
||||
$this->enableModules(array($module));
|
||||
$this->enableModules([$module]);
|
||||
$this->refreshServices();
|
||||
}
|
||||
|
||||
|
|
@ -160,7 +160,7 @@ abstract class EntityKernelTestBase extends KernelTestBase {
|
|||
* The module to uninstall.
|
||||
*/
|
||||
protected function uninstallModule($module) {
|
||||
$this->disableModules(array($module));
|
||||
$this->disableModules([$module]);
|
||||
$this->refreshServices();
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
*/
|
||||
protected $untranslatableFieldName;
|
||||
|
||||
public static $modules = array('language', 'entity_test');
|
||||
public static $modules = ['language', 'entity_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
|
@ -54,7 +54,7 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
}
|
||||
}
|
||||
|
||||
$this->installConfig(array('language'));
|
||||
$this->installConfig(['language']);
|
||||
|
||||
// Create the test field.
|
||||
module_load_install('entity_test');
|
||||
|
|
@ -71,12 +71,12 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
|
||||
// Create field fields in all entity variations.
|
||||
foreach (entity_test_entity_types() as $entity_type) {
|
||||
FieldStorageConfig::create(array(
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'entity_type' => $entity_type,
|
||||
'type' => 'text',
|
||||
'cardinality' => 4,
|
||||
))->save();
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'field_name' => $this->fieldName,
|
||||
'entity_type' => $entity_type,
|
||||
|
|
@ -84,12 +84,12 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
'translatable' => TRUE,
|
||||
])->save();
|
||||
|
||||
FieldStorageConfig::create(array(
|
||||
FieldStorageConfig::create([
|
||||
'field_name' => $this->untranslatableFieldName,
|
||||
'entity_type' => $entity_type,
|
||||
'type' => 'text',
|
||||
'cardinality' => 4,
|
||||
))->save();
|
||||
])->save();
|
||||
FieldConfig::create([
|
||||
'field_name' => $this->untranslatableFieldName,
|
||||
'entity_type' => $entity_type,
|
||||
|
|
@ -99,16 +99,16 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
}
|
||||
|
||||
// Create the default languages.
|
||||
$this->installConfig(array('language'));
|
||||
$this->installConfig(['language']);
|
||||
|
||||
// Create test languages.
|
||||
$this->langcodes = array();
|
||||
$this->langcodes = [];
|
||||
for ($i = 0; $i < 3; ++$i) {
|
||||
$language = ConfigurableLanguage::create(array(
|
||||
$language = ConfigurableLanguage::create([
|
||||
'id' => 'l' . $i,
|
||||
'label' => $this->randomString(),
|
||||
'weight' => $i,
|
||||
));
|
||||
]);
|
||||
$this->langcodes[$i] = $language->getId();
|
||||
$language->save();
|
||||
}
|
||||
|
|
@ -121,7 +121,7 @@ abstract class EntityLanguageTestBase extends EntityKernelTestBase {
|
|||
* The type of the entity fields are attached to.
|
||||
*/
|
||||
protected function toggleFieldTranslatability($entity_type, $bundle) {
|
||||
$fields = array($this->fieldName, $this->untranslatableFieldName);
|
||||
$fields = [$this->fieldName, $this->untranslatableFieldName];
|
||||
foreach ($fields as $field_name) {
|
||||
$field = FieldConfig::loadByName($entity_type, $bundle, $field_name);
|
||||
$translatable = !$field->isTranslatable();
|
||||
|
|
|
|||
|
|
@ -0,0 +1,170 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\KernelTests\Core\Entity;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTestMulRev;
|
||||
use Drupal\language\Entity\ConfigurableLanguage;
|
||||
|
||||
/**
|
||||
* Tests the loaded Revision of an entity.
|
||||
*
|
||||
* @group entity
|
||||
*/
|
||||
class EntityLoadedRevisionTest extends EntityKernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = [
|
||||
'system',
|
||||
'entity_test',
|
||||
'language',
|
||||
'content_translation',
|
||||
];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->installEntitySchema('entity_test_mulrev');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test getLoadedRevisionId() returns the correct ID throughout the process.
|
||||
*/
|
||||
public function testLoadedRevisionId() {
|
||||
// Create a basic EntityTestMulRev entity and save it.
|
||||
$entity = EntityTestMulRev::create();
|
||||
$entity->save();
|
||||
|
||||
// Load the created entity and create a new revision.
|
||||
$loaded = EntityTestMulRev::load($entity->id());
|
||||
$loaded->setNewRevision(TRUE);
|
||||
|
||||
// Before saving, the loaded Revision ID should be the same as the created
|
||||
// entity, not the same as the loaded entity (which does not have a revision
|
||||
// ID yet).
|
||||
$this->assertEquals($entity->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$this->assertNotEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$this->assertSame(NULL, $loaded->getRevisionId());
|
||||
|
||||
// After updating the loaded Revision ID the result should be the same.
|
||||
$loaded->updateLoadedRevisionId();
|
||||
$this->assertEquals($entity->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$this->assertNotEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$this->assertSame(NULL, $loaded->getRevisionId());
|
||||
|
||||
$loaded->save();
|
||||
|
||||
// In entity_test_entity_update() the loaded Revision ID was stored in
|
||||
// state. This should be the same as we had before calling $loaded->save().
|
||||
/** @var \Drupal\Core\Entity\ContentEntityInterface $loaded_original */
|
||||
$loadedRevisionId = \Drupal::state()->get('entity_test.loadedRevisionId');
|
||||
$this->assertEquals($entity->getRevisionId(), $loadedRevisionId);
|
||||
$this->assertNotEquals($loaded->getRevisionId(), $loadedRevisionId);
|
||||
|
||||
// The revision ID and loaded Revision ID should be different for the two
|
||||
// versions of the entity, but the same for a saved entity.
|
||||
$this->assertNotEquals($loaded->getRevisionId(), $entity->getRevisionId());
|
||||
$this->assertNotEquals($loaded->getLoadedRevisionId(), $entity->getLoadedRevisionId());
|
||||
$this->assertEquals($entity->getRevisionId(), $entity->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the loaded revision ID after an entity re-save, clone and duplicate.
|
||||
*/
|
||||
public function testLoadedRevisionIdWithNoNewRevision() {
|
||||
// Create a basic EntityTestMulRev entity and save it.
|
||||
$entity = EntityTestMulRev::create();
|
||||
$entity->save();
|
||||
|
||||
// Load the created entity and create a new revision.
|
||||
$loaded = EntityTestMulRev::load($entity->id());
|
||||
$loaded->setNewRevision(TRUE);
|
||||
$loaded->save();
|
||||
|
||||
// Make a change to the loaded entity.
|
||||
$loaded->set('name', 'dublin');
|
||||
|
||||
// The revision id and loaded Revision id should still be the same.
|
||||
$this->assertEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
|
||||
$loaded->save();
|
||||
|
||||
// After saving, the loaded Revision id set in entity_test_entity_update()
|
||||
// and returned from the entity should be the same as the entity's revision
|
||||
// id because a new revision wasn't created, the existing revision was
|
||||
// updated.
|
||||
$loadedRevisionId = \Drupal::state()->get('entity_test.loadedRevisionId');
|
||||
$this->assertEquals($loaded->getRevisionId(), $loadedRevisionId);
|
||||
$this->assertEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
|
||||
// Creating a clone should keep the loaded Revision ID.
|
||||
$clone = clone $loaded;
|
||||
$this->assertSame($loaded->getLoadedRevisionId(), $clone->getLoadedRevisionId());
|
||||
|
||||
// Creating a duplicate should set a NULL loaded Revision ID.
|
||||
$duplicate = $loaded->createDuplicate();
|
||||
$this->assertSame(NULL, $duplicate->getLoadedRevisionId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the loaded revision ID for translatable entities.
|
||||
*/
|
||||
public function testTranslatedLoadedRevisionId() {
|
||||
ConfigurableLanguage::createFromLangcode('fr')->save();
|
||||
|
||||
// Create a basic EntityTestMulRev entity and save it.
|
||||
$entity = EntityTestMulRev::create();
|
||||
$entity->save();
|
||||
|
||||
// Load the created entity and create a new revision.
|
||||
$loaded = EntityTestMulRev::load($entity->id());
|
||||
$loaded->setNewRevision(TRUE);
|
||||
$loaded->save();
|
||||
|
||||
// Check it all works with translations.
|
||||
$french = $loaded->addTranslation('fr');
|
||||
// Adding a revision should return the same for each language.
|
||||
$this->assertEquals($french->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getLoadedRevisionId(), $french->getLoadedRevisionId());
|
||||
$french->save();
|
||||
// After saving nothing should change.
|
||||
$this->assertEquals($french->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getLoadedRevisionId(), $french->getLoadedRevisionId());
|
||||
$first_revision_id = $french->getRevisionId();
|
||||
$french->setNewRevision();
|
||||
// Setting a new revision will reset the loaded Revision ID.
|
||||
$this->assertEquals($first_revision_id, $french->getLoadedRevisionId());
|
||||
$this->assertEquals($first_revision_id, $loaded->getLoadedRevisionId());
|
||||
$this->assertNotEquals($french->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertGreaterThan($french->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertNotEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$this->assertGreaterThan($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
$french->save();
|
||||
// Saving the new revision will reset the origin revision ID again.
|
||||
$this->assertEquals($french->getRevisionId(), $french->getLoadedRevisionId());
|
||||
$this->assertEquals($loaded->getRevisionId(), $loaded->getLoadedRevisionId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests re-saving the entity in entity_test_entity_insert().
|
||||
*/
|
||||
public function testSaveInHookEntityInsert() {
|
||||
// Create an entity which will be saved again in entity_test_entity_insert().
|
||||
$entity = EntityTestMulRev::create(['name' => 'EntityLoadedRevisionTest']);
|
||||
$entity->save();
|
||||
$loadedRevisionId = \Drupal::state()->get('entity_test.loadedRevisionId');
|
||||
$this->assertEquals($entity->getLoadedRevisionId(), $loadedRevisionId);
|
||||
$this->assertEquals($entity->getRevisionId(), $entity->getLoadedRevisionId());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Reference in a new issue