Prepopulate the cache of IDs in a locale, to optimise batch calls to isLocalisedInStage.

@param string $locale
@param string $dataObjectClass
@param bool $populateLive
@param bool $populateDraft
977118
public static function prepoulateIdsInLocale($locale, $dataObjectClass, $populateLive = true, $populateDraft = true)
    {
        // Get the table for the given DataObject class
        /** @var DataObject|FluentExtension $dataObject */
        $dataObject = DataObject::singleton($dataObjectClass);
        $table = $dataObject->getLocalisedTable($dataObject->baseTable());

        // If we already have items then we've been here before...
        if (isset(self::$idsInLocaleCache[$locale][$table])) {
            return;
        }

        $tables = [];
        if ($populateDraft) {
            $tables[] = $table;
        }
        if ($populateLive) {
            $tables[] = $table . self::SUFFIX_LIVE;
        }

        // Populate both the draft and live stages
        foreach ($tables as $table) {
            /** @var SQLSelect $select */
            $select = SQLSelect::create(
                ['"RecordID"'],
                '"' . $table . '"',
                ['"Locale"' => $locale]
            );
            $result = $select->execute();
            $ids = $result->column('RecordID');

            // We need to execute ourselves as the param is lost from the subSelect
            self::$idsInLocaleCache[$locale][$table] = array_combine($ids, $ids);
            self::$idsInLocaleCache[$locale][$table]['_complete'] = true;
        }
    }
679327
public function populate(Smarty_Template_Cached $cached, Smarty_Internal_Template $_template)
    {
        $_cache_id = isset($cached->cache_id) ? preg_replace('![^\w\|]+!', '_', $cached->cache_id) : null;
        $_compile_id = isset($cached->compile_id) ? preg_replace('![^\w\|]+!', '_', $cached->compile_id) : null;

        $cached->filepath = sha1($cached->source->filepath . $_cache_id . $_compile_id);
        $this->populateTimestamp($cached);
    }
800855
static function idByLocale( $locale )
    {
        $language = eZContentLanguage::fetchByLocale( $locale );
        if ( $language )
        {
            return (int)$language->attribute( 'id' );
        }
        else
        {
            return false;
        }
    }
1280963
public function createOrUpdateConditions($serializableConditions, $locale)
    {
        $this->setSerializedConditions($serializableConditions);

        // Set object language (i18n)
        if (!\is_null($locale)) {
            $this->setLocale($locale);
        }

        $this->save();
    }
519483
private function _populate_cache()
    {
        if ($this->_use_json) {
            if (is_readable($this->_cache_file) &&
            ($loaded = @json_decode(Common::getContents($this->_cache_file, ''), true)) && is_array($loaded)) {
                $this->_existing_cache_vals = $loaded;
            }
        } else {
            if (is_readable($this->_cache_file) &&
            ($loaded = @unserialize(Common::getContents($this->_cache_file, false))) && is_array($loaded)) {
                $this->_existing_cache_vals = $loaded;
            }
        }
    }
879433
protected void initializeData(ULocale desiredLocale, String type)
    {
        String key = desiredLocale.getBaseName() + '+' + type;
        String ns = desiredLocale.getKeywordValue("numbers");
        if (ns != null && ns.length() > 0) {
            key += '+' + ns;
        }
        DateFormatSymbols dfs = DFSCACHE.getInstance(key, desiredLocale);
        initializeData(dfs);
    }
1105391
public function populateIndex(BulkOperation $bulk, databox $databox)
    {
        $this->logger->info(sprintf('Indexing database %s...', $databox->get_viewname()));

        $submitted_records = [];
        // No delegate, scan all records
        $fetcher = $this->fetcherFactory->createFetcher($databox);

        // post fetch : flag records as "indexing"
        $fetcher->setPostFetch(function(array $records) use ($databox, $fetcher) {
            RecordQueuer::didStartIndexingRecords($records, $databox);
            // do not restart the fetcher since it has no clause on jetons
        });

        // bulk flush : flag records as "indexed"
        $bulk->onFlush(function($operation_identifiers) use ($databox, &$submitted_records) {
            $this->onBulkFlush($databox, $operation_identifiers, $submitted_records);
        });

        // Perform indexing
        $this->indexFromFetcher($bulk, $fetcher, $submitted_records);

        $this->logger->info(sprintf('Finished indexing %s', $databox->get_viewname()));
    }
1247298
private void populateCollectionFromMap(Object entity, PersistenceDelegator delegator, Relation relation,
            Object relObject, Map<String, Object> relationsMap)
    {
        EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        // Map collection to be set into entity
        Map<Object, Object> relationshipEntityMap = new HashMap<Object, Object>();

        if ((relObject == null || ProxyHelper.isProxyCollection(relObject)) && relationsMap != null
                && !relationsMap.isEmpty())
        {
            for (String relationName : relationsMap.keySet())
            {
                Object relationValue = relationsMap.get(relationName);
                if (relationValue instanceof Map)
                {
                    Map<Object, Object> relationValueMap = (Map<Object, Object>) relationValue;

                    // Client for target entity
                    Client targetEntityClient = delegator.getClient(childMetadata);

                    for (Object targetEntityKey : relationValueMap.keySet())
                    {
                        // Find target entity from database
                        Object targetEntity = targetEntityClient.find(childMetadata.getEntityClazz(), targetEntityKey);
                        if (targetEntity != null && targetEntity instanceof EnhanceEntity)
                        {
                            targetEntity = ((EnhanceEntity) targetEntity).getEntity();
                        }

                        // Set source and target entities into Map key entity
                        Object mapKeyEntity = relationValueMap.get(targetEntityKey);
                        Class<?> relationshipClass = relation.getMapKeyJoinClass();
                        for (Field f : relationshipClass.getDeclaredFields())
                        {
                            if (f.getType().equals(entity.getClass()))
                            {
                                PropertyAccessorHelper.set(mapKeyEntity, f, entity);
                            }
                            else if (f.getType().equals(childMetadata.getEntityClazz()))
                            {
                                PropertyAccessorHelper.set(mapKeyEntity, f, targetEntity);
                            }
                        }

                        // Finally, put map key and value into collection
                        relationshipEntityMap.put(mapKeyEntity, targetEntity);
                    }
                }
            }
            relObject = relationshipEntityMap;
        }

        // Set relationship collection into original entity
        PropertyAccessorHelper.set(entity, relation.getProperty(), relObject);

        // Add target entities into persistence cache
        if (relObject != null && !ProxyHelper.isProxyCollection(relObject))
        {
            for (Object child : ((Map) relObject).values())
            {
                if (child != null)
                {
                    Object childId = PropertyAccessorHelper.getId(child, childMetadata);
                    PersistenceCacheManager.addEntityToPersistenceCache(child, delegator, childId);
                }
            }
        }
    }
95934
public static function prepopulate_versionnumber_cache($class, $stage, $idList = null)
    {
        ReadingMode::validateStage($stage);
        if (!Config::inst()->get(static::class, 'prepopulate_versionnumber_cache')) {
            return;
        }

        /** @var Versioned|DataObject $singleton */
        $singleton = DataObject::singleton($class);
        $baseClass = $singleton->baseClass();
        $baseTable = $singleton->baseTable();
        $stageTable = $singleton->stageTable($baseTable, $stage);

        $filter = "";
        $parameters = [];
        if ($idList) {
            // Validate the ID list
            foreach ($idList as $id) {
                if (!is_numeric($id)) {
                    user_error(
                        "Bad ID passed to Versioned::prepopulate_versionnumber_cache() in \$idList: " . $id,
                        E_USER_ERROR
                    );
                }
            }
            $filter = 'WHERE "ID" IN (' . DB::placeholders($idList) . ')';
            $parameters = $idList;

        // If we are caching IDs for _all_ records then we can mark this cache as "complete" and in the case of a cache-miss
        // no subsequent call is necessary
        } else {
            self::$cache_versionnumber[$baseClass][$stage] = [ '_complete' => true ];
        }

        $versions = DB::prepared_query("SELECT \"ID\", \"Version\" FROM \"$stageTable\" $filter", $parameters)->map();

        foreach ($versions as $id => $version) {
            self::$cache_versionnumber[$baseClass][$stage][$id] = $version;
        }
    }
1178824
protected function populateFromRow(Row $row = null, $classname = null, $id_column = null, $row_id = null, $from_resultset = false)
        {
            $item = null;
            if ($row instanceof Row) {
                if (!$from_resultset && Core::isDebugMode()) {
                    $previous_time = Core::getDebugTime();
                }
                if ($classname === null) {
                    $classnames = Core::getCachedTableEntityClasses('\\'.get_class($this));
                    if ($classnames) {
                        $classname = $this->getSubclassNameFromRow($row, $classnames);
                    } else {
                        $classname = Core::getCachedTableEntityClass('\\'.get_class($this));
                    }
                    if (!$classname) {
                        throw new Exception("Classname '{$classname}' or subclasses for table '{$this->getB2DBName()}' is not valid");
                    }
                }

                $id_column = ($id_column) ?? $row->getQuery()->getTable()->getIdColumn();
                $row_id = ($row_id !== null) ? $row_id : $row->get($id_column);
                $is_cached = $classname::getB2DBTable()->hasCachedB2DBObject($row_id);
                $item = $classname::getB2DBCachedObjectIfAvailable($row_id, $classname, $row);
                if (!$from_resultset && !$is_cached && Core::isDebugMode()) {
                    Core::objectPopulationHit(1, array($classname), $previous_time);
                }
            }
            return $item;
        }
928583
public function populate($data = array())
    {
        if (isset($data['name']) && $data['name'] !== null) {
            $this->name = $data['name'];
        }
        if (isset($data['locale']) && $data['locale'] !== null) {
            $this->locale = $data['locale'];
        }
    }
1245965
private void initCapitalizationContextInfo(ULocale locale) {
        ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle.getBundleInstance(ICUData.ICU_BASE_NAME, locale);
        try {
            ICUResourceBundle rdb = rb.getWithFallback("contextTransforms/relative");
            int[] intVector = rdb.getIntVector();
            if (intVector.length >= 2) {
                capitalizationOfRelativeUnitsForListOrMenu = (intVector[0] != 0);
                capitalizationOfRelativeUnitsForStandAlone = (intVector[1] != 0);
            }
        } catch (MissingResourceException e) {
            // use default
        }
    }
773958
private void executeOperation(DbUnitDatabasePopulator populator, DataSource dataSource) throws Exception {

        Connection connection = null;

        try {
            connection = getConnection(dataSource);
            populator.populate(connection);

        } finally {
            if (connection != null && !isConnectionTransactional(connection, dataSource)) {
                // if the connection is transactional, closing it. Otherwise,
                // expects that the framework will do it
                releaseConnection(connection, dataSource);
            }
        }
    }
1073573
public static function createFromLocalId(Connection $dbal, $localId)
    {
        $data = $dbal->fetchAll(
            'SELECT T.*
                                               FROM '.self::PERSIST_TABLE.' AS T
                             INNER JOIN '.self::PERSIST_TABLE.' AS S ON T.shop_order_id = S.shop_order_id
                                  WHERE S.`local_id` = ?
                               ORDER BY T.`cmsident`
                                  ',
            array($localId)
        );
        $manager = self::createFromRecordList($data);

        if (null === $manager) {
            throw new \InvalidArgumentException("unable to find an an id mapper object based on the local reference id [{$localId}]");
        }

        return $manager;
    }
832668
private function putToCache( $locale, $contextName, ezcTranslation $contextData )
    {
        $this->contextCache[$locale][$contextName] = $contextData;
    }
792929
public function doBuild($quiet = false, $populate = true, $testMode = false)
    {
        if ($quiet) {
            DB::quiet();
        } else {
            $conn = DB::get_conn();
            // Assumes database class is like "MySQLDatabase" or "MSSQLDatabase" (suffixed with "Database")
            $dbType = substr(get_class($conn), 0, -8);
            $dbVersion = $conn->getVersion();
            $databaseName = $conn->getSelectedDatabase();

            if (Director::is_cli()) {
                echo sprintf("\n\nBuilding database %s using %s %s\n\n", $databaseName, $dbType, $dbVersion);
            } else {
                echo sprintf("<h2>Building database %s using %s %s</h2>", $databaseName, $dbType, $dbVersion);
            }
        }

        // Set up the initial database
        if (!DB::is_active()) {
            if (!$quiet) {
                echo '<p><b>Creating database</b></p>';
            }

            // Load parameters from existing configuration
            $databaseConfig = DB::getConfig();
            if (empty($databaseConfig) && empty($_REQUEST['db'])) {
                throw new BadMethodCallException("No database configuration available");
            }
            $parameters = (!empty($databaseConfig)) ? $databaseConfig : $_REQUEST['db'];

            // Check database name is given
            if (empty($parameters['database'])) {
                throw new BadMethodCallException(
                    "No database name given; please give a value for SS_DATABASE_NAME or set SS_DATABASE_CHOOSE_NAME"
                );
            }
            $database = $parameters['database'];

            // Establish connection
            unset($parameters['database']);
            DB::connect($parameters);

            // Check to ensure that the re-instated SS_DATABASE_SUFFIX functionality won't unexpectedly
            // rename the database. To be removed for SS5
            if ($suffix = Environment::getEnv('SS_DATABASE_SUFFIX')) {
                $previousName = preg_replace("/{$suffix}$/", '', $database);

                if (!isset($_GET['force_suffix_rename']) && DB::get_conn()->databaseExists($previousName)) {
                    throw new DatabaseException(
                        "SS_DATABASE_SUFFIX was previously broken, but has now been fixed. This will result in your "
                        . "database being named \"{$database}\" instead of \"{$previousName}\" from now on. If this "
                        . "change is intentional, please visit dev/build?force_suffix_rename=1 to continue"
                    );
                }
            }

            // Create database
            DB::create_database($database);
        }

        // Build the database.  Most of the hard work is handled by DataObject
        $dataClasses = ClassInfo::subclassesFor(DataObject::class);
        array_shift($dataClasses);

        if (!$quiet) {
            if (Director::is_cli()) {
                echo "\nCREATING DATABASE TABLES\n\n";
            } else {
                echo "\n<p><b>Creating database tables</b></p><ul>\n\n";
            }
        }

        $showRecordCounts = (boolean)$this->config()->show_record_counts;

        // Initiate schema update
        $dbSchema = DB::get_schema();
        $dbSchema->schemaUpdate(function () use ($dataClasses, $testMode, $quiet, $showRecordCounts) {
            $dataObjectSchema = DataObject::getSchema();

            foreach ($dataClasses as $dataClass) {
                // Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
                if (!class_exists($dataClass)) {
                    continue;
                }

                // Check if this class should be excluded as per testing conventions
                $SNG = singleton($dataClass);
                if (!$testMode && $SNG instanceof TestOnly) {
                    continue;
                }
                $tableName = $dataObjectSchema->tableName($dataClass);

                // Log data
                if (!$quiet) {
                    if ($showRecordCounts && DB::get_schema()->hasTable($tableName)) {
                        try {
                            $count = DB::query("SELECT COUNT(*) FROM \"$tableName\"")->value();
                            $countSuffix = " ($count records)";
                        } catch (Exception $e) {
                            $countSuffix = " (error getting record count)";
                        }
                    } else {
                        $countSuffix = "";
                    }

                    if (Director::is_cli()) {
                        echo " * $tableName$countSuffix\n";
                    } else {
                        echo "<li>$tableName$countSuffix</li>\n";
                    }
                }

                // Instruct the class to apply its schema to the database
                $SNG->requireTable();
            }
        });
        ClassInfo::reset_db_cache();

        if (!$quiet && !Director::is_cli()) {
            echo "</ul>";
        }

        if ($populate) {
            if (!$quiet) {
                if (Director::is_cli()) {
                    echo "\nCREATING DATABASE RECORDS\n\n";
                } else {
                    echo "\n<p><b>Creating database records</b></p><ul>\n\n";
                }
            }

            // Remap obsolete class names
            $remappingConfig = $this->config()->get('classname_value_remapping');
            $remappingFields = $this->getClassNameRemappingFields();
            foreach ($remappingFields as $className => $fieldNames) {
                foreach ($fieldNames as $fieldName) {
                    foreach ($remappingConfig as $oldClassName => $newClassName) {
                        $this->updateLegacyClassNames($className, $fieldName, $oldClassName, $newClassName);
                    }
                }
            }

            // Require all default records
            foreach ($dataClasses as $dataClass) {
                // Check if class exists before trying to instantiate - this sidesteps any manifest weirdness
                // Test_ indicates that it's the data class is part of testing system
                if (strpos($dataClass, 'Test_') === false && class_exists($dataClass)) {
                    if (!$quiet) {
                        if (Director::is_cli()) {
                            echo " * $dataClass\n";
                        } else {
                            echo "<li>$dataClass</li>\n";
                        }
                    }

                    DataObject::singleton($dataClass)->requireDefaultRecords();
                }
            }

            if (!$quiet && !Director::is_cli()) {
                echo "</ul>";
            }
        }

        touch(TEMP_PATH
            . DIRECTORY_SEPARATOR
            . 'database-last-generated-'
            . str_replace(array('\\', '/', ':'), '.', Director::baseFolder()));

        if (isset($_REQUEST['from_installer'])) {
            echo "OK";
        }

        if (!$quiet) {
            echo (Director::is_cli()) ? "\n Database build completed!\n\n" :"<p>Database build completed!</p>";
        }

        ClassInfo::reset_db_cache();
    }
909096
private static void populateCache() {
        if (cache == null) {
            cache = new LinkedHashMap<>();

            logger.info("IDataDecoders found:");

            ServiceLoader<IDataDecoder> loader =
                    ServiceLoader.load(IDataDecoder.class);

            // Logging.
            for (IDataDecoder discoveredDecoder : loader) {
                String name = discoveredDecoder.getClass().getCanonicalName();
                String decoderMimeType = discoveredDecoder.getMimeType();
                logger.info(String.format("    %s -> %s",
                        decoderMimeType, name));
                cache.put(decoderMimeType, discoveredDecoder.getClass());
            }
        }
    }