[TASK] Split DataHandler::copyRecord_procBasedOnFieldType
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Tests / FunctionalTestCaseBootstrapUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Tests;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 /**
18 * Utility class to set up and bootstrap TYPO3 CMS for functional tests
19 */
20 class FunctionalTestCaseBootstrapUtility {
21
22 /**
23 * @var string Identifier calculated from test case class
24 */
25 protected $identifier;
26
27 /**
28 * @var string Absolute path to test instance document root
29 */
30 protected $instancePath;
31
32 /**
33 * @var string Name of test database
34 */
35 protected $databaseName;
36
37 /**
38 * @var string Name of original database
39 */
40 protected $originalDatabaseName;
41
42 /**
43 * @var array These extensions are always loaded
44 */
45 protected $defaultActivatedCoreExtensions = array(
46 'core',
47 'backend',
48 'frontend',
49 'cms',
50 'lang',
51 'extbase',
52 'install',
53 );
54
55 /**
56 * @var array These folder are always created
57 */
58 protected $defaultFoldersToCreate = array(
59 '',
60 '/fileadmin',
61 '/typo3temp',
62 '/typo3conf',
63 '/typo3conf/ext',
64 '/uploads'
65 );
66
67 /**
68 * Set up creates a test instance and database.
69 *
70 * @param string $testCaseClassName Name of test case class
71 * @param array $coreExtensionsToLoad Array of core extensions to load
72 * @param array $testExtensionsToLoad Array of test extensions to load
73 * @param array $pathsToLinkInTestInstance Array of source => destination path pairs to be linked
74 * @param array $configurationToUse Array of TYPO3_CONF_VARS that need to be overridden
75 * @param array $additionalFoldersToCreate Array of folder paths to be created
76 * @return string Path to TYPO3 CMS test installation for this test case
77 */
78 public function setUp(
79 $testCaseClassName,
80 array $coreExtensionsToLoad,
81 array $testExtensionsToLoad,
82 array $pathsToLinkInTestInstance,
83 array $configurationToUse,
84 array $additionalFoldersToCreate
85 ) {
86 $this->setUpIdentifier($testCaseClassName);
87 $this->setUpInstancePath();
88 if ($this->recentTestInstanceExists()) {
89 $this->setUpBasicTypo3Bootstrap();
90 $this->initializeTestDatabase();
91 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(TRUE);
92 } else {
93 $this->removeOldInstanceIfExists();
94 $this->setUpInstanceDirectories($additionalFoldersToCreate);
95 $this->setUpInstanceCoreLinks();
96 $this->linkTestExtensionsToInstance($testExtensionsToLoad);
97 $this->linkPathsInTestInstance($pathsToLinkInTestInstance);
98 $this->setUpLocalConfiguration($configurationToUse);
99 $this->setUpPackageStates($coreExtensionsToLoad, $testExtensionsToLoad);
100 $this->setUpBasicTypo3Bootstrap();
101 $this->setUpTestDatabase();
102 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->loadExtensionTables(TRUE);
103 $this->createDatabaseStructure();
104 }
105
106 return $this->instancePath;
107 }
108
109 /**
110 * Checks whether the current test instance exists and is younger than
111 * some minutes.
112 *
113 * @return bool
114 */
115 protected function recentTestInstanceExists() {
116 if (@file_get_contents($this->instancePath . '/last_run.txt') <= (time() - 300)) {
117 return FALSE;
118 } else {
119 // Test instance exists and is pretty young -> re-use
120 return TRUE;
121 }
122 }
123
124 /**
125 * Calculate a "unique" identifier for the test database and the
126 * instance patch based on the given test case class name.
127 *
128 * As a result, the database name will be identical between different
129 * test runs, but different between each test case.
130 */
131 protected function setUpIdentifier($testCaseClassName) {
132 // 7 characters of sha1 should be enough for a unique identification
133 $this->identifier = substr(sha1($testCaseClassName), 0, 7);
134 }
135
136 /**
137 * Calculates path to TYPO3 CMS test installation for this test case.
138 *
139 * @return void
140 */
141 protected function setUpInstancePath() {
142 $this->instancePath = ORIGINAL_ROOT . 'typo3temp/functional-' . $this->identifier;
143 }
144
145 /**
146 * Remove test instance folder structure in setUp() if it exists.
147 * This may happen if a functional test before threw a fatal.
148 *
149 * @return void
150 */
151 protected function removeOldInstanceIfExists() {
152 if (is_dir($this->instancePath)) {
153 $this->removeInstance();
154 }
155 }
156
157 /**
158 * Create folder structure of test instance.
159 *
160 * @param array $additionalFoldersToCreate Array of additional folders to be created
161 * @throws Exception
162 * @return void
163 */
164 protected function setUpInstanceDirectories(array $additionalFoldersToCreate = array()) {
165 $foldersToCreate = array_merge($this->defaultFoldersToCreate, $additionalFoldersToCreate);
166 foreach ($foldersToCreate as $folder) {
167 $success = mkdir($this->instancePath . $folder);
168 if (!$success) {
169 throw new Exception(
170 'Creating directory failed: ' . $this->instancePath . $folder,
171 1376657189
172 );
173 }
174 }
175
176 // Store the time we created this directory
177 file_put_contents($this->instancePath . '/last_run.txt', time());
178 }
179
180 /**
181 * Link TYPO3 CMS core from "parent" instance.
182 *
183 * @throws Exception
184 * @return void
185 */
186 protected function setUpInstanceCoreLinks() {
187 $linksToSet = array(
188 ORIGINAL_ROOT . 'typo3' => $this->instancePath . '/typo3',
189 ORIGINAL_ROOT . 'index.php' => $this->instancePath . '/index.php'
190 );
191 foreach ($linksToSet as $from => $to) {
192 $success = symlink($from, $to);
193 if (!$success) {
194 throw new Exception(
195 'Creating link failed: from ' . $from . ' to: ' . $to,
196 1376657199
197 );
198 }
199 }
200 }
201
202 /**
203 * Link test extensions to the typo3conf/ext folder of the instance.
204 *
205 * @param array $extensionPaths Contains paths to extensions relative to document root
206 * @throws Exception
207 * @return void
208 */
209 protected function linkTestExtensionsToInstance(array $extensionPaths) {
210 foreach ($extensionPaths as $extensionPath) {
211 $absoluteExtensionPath = ORIGINAL_ROOT . $extensionPath;
212 if (!is_dir($absoluteExtensionPath)) {
213 throw new Exception(
214 'Test extension path ' . $absoluteExtensionPath . ' not found',
215 1376745645
216 );
217 }
218 $destinationPath = $this->instancePath . '/typo3conf/ext/' . basename($absoluteExtensionPath);
219 $success = symlink($absoluteExtensionPath, $destinationPath);
220 if (!$success) {
221 throw new Exception(
222 'Can not link extension folder: ' . $absoluteExtensionPath . ' to ' . $destinationPath,
223 1376657142
224 );
225 }
226 }
227 }
228
229 /**
230 * Link paths inside the test instance, e.g. from a fixture fileadmin subfolder to the
231 * test instance fileadmin folder
232 *
233 * @param array $pathsToLinkInTestInstance Contains paths as array of source => destination in key => value pairs of folders relative to test instance root
234 * @throws \TYPO3\CMS\Core\Tests\Exception if a source path could not be found
235 * @throws \TYPO3\CMS\Core\Tests\Exception on failing creating the symlink
236 * @return void
237 * @see \TYPO3\CMS\Core\Tests\FunctionalTestCase::$pathsToLinkInTestInstance
238 */
239 protected function linkPathsInTestInstance(array $pathsToLinkInTestInstance) {
240 foreach ($pathsToLinkInTestInstance as $sourcePathToLinkInTestInstance => $destinationPathToLinkInTestInstance) {
241 $sourcePath = $this->instancePath . '/' . ltrim($sourcePathToLinkInTestInstance, '/');
242 if (!file_exists($sourcePath)) {
243 throw new Exception(
244 'Path ' . $sourcePath . ' not found',
245 1376745645
246 );
247 }
248 $destinationPath = $this->instancePath . '/' . ltrim($destinationPathToLinkInTestInstance, '/');
249 $success = symlink($sourcePath, $destinationPath);
250 if (!$success) {
251 throw new Exception(
252 'Can not link the path ' . $sourcePath . ' to ' . $destinationPath,
253 1389969623
254 );
255 }
256 }
257 }
258
259 /**
260 * Create LocalConfiguration.php file in the test instance
261 *
262 * @param array $configurationToMerge
263 * @throws Exception
264 * @return void
265 */
266 protected function setUpLocalConfiguration(array $configurationToMerge) {
267 $databaseName = trim(getenv('typo3DatabaseName'));
268 $databaseHost = trim(getenv('typo3DatabaseHost'));
269 $databaseUsername = trim(getenv('typo3DatabaseUsername'));
270 $databasePassword = trim(getenv('typo3DatabasePassword'));
271 $databasePort = trim(getenv('typo3DatabasePort'));
272 $databaseSocket = trim(getenv('typo3DatabaseSocket'));
273 if ($databaseName || $databaseHost || $databaseUsername || $databasePassword || $databasePort || $databaseSocket) {
274 // Try to get database credentials from environment variables first
275 $originalConfigurationArray = array(
276 'DB' => array(),
277 );
278 if ($databaseName) {
279 $originalConfigurationArray['DB']['database'] = $databaseName;
280 }
281 if ($databaseHost) {
282 $originalConfigurationArray['DB']['host'] = $databaseHost;
283 }
284 if ($databaseUsername) {
285 $originalConfigurationArray['DB']['username'] = $databaseUsername;
286 }
287 if ($databasePassword) {
288 $originalConfigurationArray['DB']['password'] = $databasePassword;
289 }
290 if ($databasePort) {
291 $originalConfigurationArray['DB']['port'] = $databasePort;
292 }
293 if ($databaseSocket) {
294 $originalConfigurationArray['DB']['socket'] = $databaseSocket;
295 }
296 } elseif (file_exists(ORIGINAL_ROOT . 'typo3conf/LocalConfiguration.php')) {
297 // See if a LocalConfiguration file exists in "parent" instance to get db credentials from
298 $originalConfigurationArray = require ORIGINAL_ROOT . 'typo3conf/LocalConfiguration.php';
299 } else {
300 throw new Exception(
301 'Database credentials for functional tests are neither set through environment'
302 . ' variables, and can not be found in an existing LocalConfiguration file',
303 1397406356
304 );
305 }
306
307 // Base of final LocalConfiguration is core factory configuration
308 $finalConfigurationArray = require ORIGINAL_ROOT . 'typo3/sysext/core/Configuration/FactoryConfiguration.php';
309
310 $this->mergeRecursiveWithOverrule($finalConfigurationArray, require ORIGINAL_ROOT . 'typo3/sysext/core/Build/Configuration/FunctionalTestsConfiguration.php');
311 $this->mergeRecursiveWithOverrule($finalConfigurationArray, $configurationToMerge);
312 $finalConfigurationArray['DB'] = $originalConfigurationArray['DB'];
313 // Calculate and set new database name
314 $this->originalDatabaseName = $originalConfigurationArray['DB']['database'];
315 $this->databaseName = $this->originalDatabaseName . '_ft' . $this->identifier;
316
317 // Maximum database name length for mysql is 64 characters
318 if (strlen($this->databaseName) > 64) {
319 $maximumOriginalDatabaseName = 64 - strlen('_ft' . $this->identifier);
320 throw new Exception(
321 'The name of the database that is used for the functional test (' . $this->databaseName . ')' .
322 ' exceeds the maximum length of 64 character allowed by MySQL. You have to shorten your' .
323 ' original database name to ' . $maximumOriginalDatabaseName . ' characters',
324 1377600104
325 );
326 }
327
328 $finalConfigurationArray['DB']['database'] = $this->databaseName;
329
330 $result = $this->writeFile(
331 $this->instancePath . '/typo3conf/LocalConfiguration.php',
332 '<?php' . chr(10) .
333 'return ' .
334 $this->arrayExport(
335 $finalConfigurationArray
336 ) .
337 ';' . chr(10) .
338 '?>'
339 );
340 if (!$result) {
341 throw new Exception('Can not write local configuration', 1376657277);
342 }
343 }
344
345 /**
346 * Compile typo3conf/PackageStates.php containing default packages like core,
347 * a functional test specific list of additional core extensions, and a list of
348 * test extensions.
349 *
350 * @param array $coreExtensionsToLoad Additional core extensions to load
351 * @param array $testExtensionPaths Paths to extensions relative to document root
352 * @throws Exception
353 * @TODO Figure out what the intention of the upper arguments is
354 */
355 protected function setUpPackageStates(array $coreExtensionsToLoad, array $testExtensionPaths) {
356 $packageStates = array(
357 'packages' => array(),
358 'version' => 4,
359 );
360
361 // Register default list of extensions and set active
362 foreach ($this->defaultActivatedCoreExtensions as $extensionName) {
363 $packageStates['packages'][$extensionName] = array(
364 'state' => 'active',
365 'packagePath' => 'typo3/sysext/' . $extensionName . '/',
366 'classesPath' => 'Classes/',
367 );
368 }
369
370 // Register additional core extensions and set active
371 foreach ($coreExtensionsToLoad as $extensionName) {
372 if (isset($packageSates['packages'][$extensionName])) {
373 throw new Exception(
374 $extensionName . ' is already registered as default core extension to load, no need to load it explicitly',
375 1390913893
376 );
377 }
378 $packageStates['packages'][$extensionName] = array(
379 'state' => 'active',
380 'packagePath' => 'typo3/sysext/' . $extensionName . '/',
381 'classesPath' => 'Classes/',
382 );
383 }
384
385 // Activate test extensions that have been symlinked before
386 foreach ($testExtensionPaths as $extensionPath) {
387 $extensionName = basename($extensionPath);
388 if (isset($packageSates['packages'][$extensionName])) {
389 throw new Exception(
390 $extensionName . ' is already registered as extension to load, no need to load it explicitly',
391 1390913894
392 );
393 }
394 $packageStates['packages'][$extensionName] = array(
395 'state' => 'active',
396 'packagePath' => 'typo3conf/ext/' . $extensionName . '/',
397 'classesPath' => 'Classes/',
398 );
399 }
400
401 $result = $this->writeFile(
402 $this->instancePath . '/typo3conf/PackageStates.php',
403 '<?php' . chr(10) .
404 'return ' .
405 $this->arrayExport(
406 $packageStates
407 ) .
408 ';' . chr(10) .
409 '?>'
410 );
411 if (!$result) {
412 throw new Exception('Can not write PackageStates', 1381612729);
413 }
414 }
415
416 /**
417 * Bootstrap basic TYPO3
418 *
419 * @return void
420 */
421 protected function setUpBasicTypo3Bootstrap() {
422 $_SERVER['PWD'] = $this->instancePath;
423 $_SERVER['argv'][0] = 'index.php';
424
425 define('TYPO3_MODE', 'BE');
426 define('TYPO3_cliMode', TRUE);
427
428 require_once $this->instancePath . '/typo3/sysext/core/Classes/Core/CliBootstrap.php';
429 \TYPO3\CMS\Core\Core\CliBootstrap::checkEnvironmentOrDie();
430
431 require_once $this->instancePath . '/typo3/sysext/core/Classes/Core/Bootstrap.php';
432 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()
433 ->baseSetup('')
434 ->loadConfigurationAndInitialize(TRUE)
435 ->loadTypo3LoadedExtAndExtLocalconf(TRUE)
436 ->initializeExceptionHandling()
437 ->setFinalCachingFrameworkCacheConfiguration()
438 ->defineLoggingAndExceptionConstants()
439 ->unsetReservedGlobalVariables();
440 }
441
442 /**
443 * Populate $GLOBALS['TYPO3_DB'] and create test database
444 *
445 * @throws \TYPO3\CMS\Core\Tests\Exception
446 * @return void
447 */
448 protected function setUpTestDatabase() {
449 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->initializeTypo3DbGlobal();
450 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
451 $database = $GLOBALS['TYPO3_DB'];
452 if(!$database->sql_pconnect()) {
453 throw new Exception(
454 'TYPO3 Fatal Error: The current username, password or host was not accepted when the'
455 . ' connection to the database was attempted to be established!',
456 1377620117
457 );
458 }
459
460 // Drop database in case a previous test had a fatal and did not clean up properly
461 $database->admin_query('DROP DATABASE IF EXISTS `' . $this->databaseName . '`');
462 $createDatabaseResult = $database->admin_query('CREATE DATABASE `' . $this->databaseName . '`');
463 if (!$createDatabaseResult) {
464 $user = $GLOBALS['TYPO3_CONF_VARS']['DB']['username'];
465 $host = $GLOBALS['TYPO3_CONF_VARS']['DB']['host'];
466 throw new Exception(
467 'Unable to create database with name ' . $this->databaseName . '. This is probably a permission problem.'
468 . ' For this instance this could be fixed executing'
469 . ' "GRANT ALL ON `' . $this->originalDatabaseName . '_ft%`.* TO `' . $user . '`@`' . $host . '`;"',
470 1376579070
471 );
472 }
473 $database->setDatabaseName($this->databaseName);
474 // On windows, this still works, but throws a warning, which we need to discard.
475 @$database->sql_select_db();
476 }
477
478 /**
479 * Populate $GLOBALS['TYPO3_DB'] reusing an existing database with
480 * all tables truncated.
481 *
482 * @throws \TYPO3\CMS\Core\Tests\Exception
483 * @return void
484 */
485 protected function initializeTestDatabase() {
486 \TYPO3\CMS\Core\Core\Bootstrap::getInstance()->initializeTypo3DbGlobal();
487 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
488 $database = $GLOBALS['TYPO3_DB'];
489 if (!$database->sql_pconnect()) {
490 throw new Exception(
491 'TYPO3 Fatal Error: The current username, password or host was not accepted when the'
492 . ' connection to the database was attempted to be established!',
493 1377620117
494 );
495 }
496 $this->databaseName = $GLOBALS['TYPO3_CONF_VARS']['DB']['database'];
497 $database->setDatabaseName($this->databaseName);
498 $database->sql_select_db();
499 foreach ($database->admin_get_tables() as $table) {
500 $database->admin_query('TRUNCATE ' . $table['Name'] . ';');
501 }
502 }
503
504 /**
505 * Create tables and import static rows
506 *
507 * @return void
508 */
509 protected function createDatabaseStructure() {
510 /** @var \TYPO3\CMS\Install\Service\SqlSchemaMigrationService $schemaMigrationService */
511 $schemaMigrationService = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Install\Service\SqlSchemaMigrationService::class);
512 /** @var \TYPO3\CMS\Extbase\Object\ObjectManager $objectManager */
513 $objectManager = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Extbase\Object\ObjectManager::class);
514 /** @var \TYPO3\CMS\Install\Service\SqlExpectedSchemaService $expectedSchemaService */
515 $expectedSchemaService = $objectManager->get(\TYPO3\CMS\Install\Service\SqlExpectedSchemaService::class);
516
517 // Raw concatenated ext_tables.sql and friends string
518 $expectedSchemaString = $expectedSchemaService->getTablesDefinitionString(TRUE);
519 $statements = $schemaMigrationService->getStatementArray($expectedSchemaString, TRUE);
520 list($_, $insertCount) = $schemaMigrationService->getCreateTables($statements, TRUE);
521
522 $fieldDefinitionsFile = $schemaMigrationService->getFieldDefinitions_fileContent($expectedSchemaString);
523 $fieldDefinitionsDatabase = $schemaMigrationService->getFieldDefinitions_database();
524 $difference = $schemaMigrationService->getDatabaseExtra($fieldDefinitionsFile, $fieldDefinitionsDatabase);
525 $updateStatements = $schemaMigrationService->getUpdateSuggestions($difference);
526
527 $schemaMigrationService->performUpdateQueries($updateStatements['add'], $updateStatements['add']);
528 $schemaMigrationService->performUpdateQueries($updateStatements['change'], $updateStatements['change']);
529 $schemaMigrationService->performUpdateQueries($updateStatements['create_table'], $updateStatements['create_table']);
530
531 foreach ($insertCount as $table => $count) {
532 $insertStatements = $schemaMigrationService->getTableInsertStatements($statements, $table);
533 foreach ($insertStatements as $insertQuery) {
534 $insertQuery = rtrim($insertQuery, ';');
535 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
536 $database = $GLOBALS['TYPO3_DB'];
537 $database->admin_query($insertQuery);
538 }
539 }
540 }
541
542 /**
543 * Drop test database.
544 *
545 * @throws \TYPO3\CMS\Core\Tests\Exception
546 * @return void
547 */
548 protected function tearDownTestDatabase() {
549 /** @var \TYPO3\CMS\Core\Database\DatabaseConnection $database */
550 $database = $GLOBALS['TYPO3_DB'];
551 $result = $database->admin_query('DROP DATABASE `' . $this->databaseName . '`');
552 if (!$result) {
553 throw new Exception(
554 'Dropping test database ' . $this->databaseName . ' failed',
555 1376583188
556 );
557 }
558 }
559
560 /**
561 * Removes instance directories and files
562 *
563 * @throws \TYPO3\CMS\Core\Tests\Exception
564 * @return void
565 */
566 protected function removeInstance() {
567 $success = $this->rmdir($this->instancePath, TRUE);
568 if (!$success) {
569 throw new Exception(
570 'Can not remove folder: ' . $this->instancePath,
571 1376657210
572 );
573 }
574 }
575
576 /**
577 * COPIED FROM GeneralUtility
578 *
579 * Wrapper function for rmdir, allowing recursive deletion of folders and files
580 *
581 * @param string $path Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.
582 * @param bool $removeNonEmpty Allow deletion of non-empty directories
583 * @return bool TRUE if @rmdir went well!
584 */
585 protected function rmdir($path, $removeNonEmpty = FALSE) {
586 $OK = FALSE;
587 // Remove trailing slash
588 $path = preg_replace('|/$|', '', $path);
589 if (file_exists($path)) {
590 $OK = TRUE;
591 if (!is_link($path) && is_dir($path)) {
592 if ($removeNonEmpty == TRUE && ($handle = opendir($path))) {
593 while ($OK && FALSE !== ($file = readdir($handle))) {
594 if ($file == '.' || $file == '..') {
595 continue;
596 }
597 $OK = $this->rmdir($path . '/' . $file, $removeNonEmpty);
598 }
599 closedir($handle);
600 }
601 if ($OK) {
602 $OK = @rmdir($path);
603 }
604 } else {
605 // If $path is a symlink to a folder we need rmdir() on Windows systems
606 if (!stristr(PHP_OS, 'darwin') && stristr(PHP_OS, 'win') && is_link($path) && is_dir($path . '/')) {
607 $OK = rmdir($path);
608 } else {
609 $OK = unlink($path);
610 }
611 }
612 clearstatcache();
613 } elseif (is_link($path)) {
614 $OK = unlink($path);
615 clearstatcache();
616 }
617 return $OK;
618 }
619
620 /**
621 * COPIED FROM GeneralUtility
622 *
623 * Writes $content to the file $file
624 *
625 * @param string $file Filepath to write to
626 * @param string $content Content to write
627 * @return bool TRUE if the file was successfully opened and written to.
628 */
629 protected function writeFile($file, $content) {
630 if ($fd = fopen($file, 'wb')) {
631 $res = fwrite($fd, $content);
632 fclose($fd);
633 if ($res === FALSE) {
634 return FALSE;
635 }
636 return TRUE;
637 }
638 return FALSE;
639 }
640
641 /**
642 * COPIED FROM ArrayUtility
643 *
644 * Exports an array as string.
645 * Similar to var_export(), but representation follows the TYPO3 core CGL.
646 *
647 * See unit tests for detailed examples
648 *
649 * @param array $array Array to export
650 * @param int $level Internal level used for recursion, do *not* set from outside!
651 * @return string String representation of array
652 * @throws \RuntimeException
653 */
654 protected function arrayExport(array $array = array(), $level = 0) {
655 $lines = 'array(' . chr(10);
656 $level++;
657 $writeKeyIndex = FALSE;
658 $expectedKeyIndex = 0;
659 foreach ($array as $key => $value) {
660 if ($key === $expectedKeyIndex) {
661 $expectedKeyIndex++;
662 } else {
663 // Found a non integer or non consecutive key, so we can break here
664 $writeKeyIndex = TRUE;
665 break;
666 }
667 }
668 foreach ($array as $key => $value) {
669 // Indention
670 $lines .= str_repeat(chr(9), $level);
671 if ($writeKeyIndex) {
672 // Numeric / string keys
673 $lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => ';
674 }
675 if (is_array($value)) {
676 if (count($value) > 0) {
677 $lines .= $this->arrayExport($value, $level);
678 } else {
679 $lines .= 'array(),' . chr(10);
680 }
681 } elseif (is_int($value) || is_float($value)) {
682 $lines .= $value . ',' . chr(10);
683 } elseif (is_null($value)) {
684 $lines .= 'NULL' . ',' . chr(10);
685 } elseif (is_bool($value)) {
686 $lines .= $value ? 'TRUE' : 'FALSE';
687 $lines .= ',' . chr(10);
688 } elseif (is_string($value)) {
689 // Quote \ to \\
690 $stringContent = str_replace('\\', '\\\\', $value);
691 // Quote ' to \'
692 $stringContent = str_replace('\'', '\\\'', $stringContent);
693 $lines .= '\'' . $stringContent . '\'' . ',' . chr(10);
694 } else {
695 throw new \RuntimeException('Objects are not supported', 1342294986);
696 }
697 }
698 $lines .= str_repeat(chr(9), ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . chr(10));
699 return $lines;
700 }
701
702 /**
703 * COPIED FROM ArrayUtility
704 *
705 * Merges two arrays recursively and "binary safe" (integer keys are
706 * overridden as well), overruling similar values in the original array
707 * with the values of the overrule array.
708 * In case of identical keys, ie. keeping the values of the overrule array.
709 *
710 * This method takes the original array by reference for speed optimization with large arrays
711 *
712 * The differences to the existing PHP function array_merge_recursive() are:
713 * * Keys of the original array can be unset via the overrule array. ($enableUnsetFeature)
714 * * Much more control over what is actually merged. ($addKeys, $includeEmptyValues)
715 * * Elements or the original array get overwritten if the same key is present in the overrule array.
716 *
717 * @param array $original Original array. It will be *modified* by this method and contains the result afterwards!
718 * @param array $overrule Overrule array, overruling the original array
719 * @param bool $addKeys If set to FALSE, keys that are NOT found in $original will not be set. Thus only existing value can/will be overruled from overrule array.
720 * @param bool $includeEmptyValues If set, values from $overrule will overrule if they are empty or zero.
721 * @param bool $enableUnsetFeature If set, special values "__UNSET" can be used in the overrule array in order to unset array keys in the original array.
722 * @return void
723 */
724 protected function mergeRecursiveWithOverrule(array &$original, array $overrule, $addKeys = TRUE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
725 foreach ($overrule as $key => $_) {
726 if ($enableUnsetFeature && $overrule[$key] === '__UNSET') {
727 unset($original[$key]);
728 continue;
729 }
730 if (isset($original[$key]) && is_array($original[$key])) {
731 if (is_array($overrule[$key])) {
732 self::mergeRecursiveWithOverrule($original[$key], $overrule[$key], $addKeys, $includeEmptyValues, $enableUnsetFeature);
733 }
734 } elseif (
735 ($addKeys || isset($original[$key])) &&
736 ($includeEmptyValues || $overrule[$key])
737 ) {
738 $original[$key] = $overrule[$key];
739 }
740 }
741 // This line is kept for backward compatibility reasons.
742 reset($original);
743 }
744
745 }