Saves messages to database

@param array $messages
@param \yii\db\Connection $db
@param string $sourceMessageTable
@param string $messageTable
@param boolean $removeUnused
@param array $languages
773140
public function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages)
    {
        $q = new \yii\db\Query;
        $current = [];

        foreach ($q->select(['id', 'category', 'message'])->from($sourceMessageTable)->all() as $row) {
            $current[$row['category']][$row['id']] = $row['message'];
        }

        $new = [];
        $obsolete = [];

        foreach ($messages as $category => $msgs) {
            $msgs = array_unique($msgs);

            if (isset($current[$category])) {
                $new[$category] = array_diff($msgs, $current[$category]);
                $obsolete += array_diff($current[$category], $msgs);
            } else {
                $new[$category] = $msgs;
            }
        }

        foreach (array_diff(array_keys($current), array_keys($messages)) as $category) {
            $obsolete += $current[$category];
        }

        if (!$removeUnused) {
            foreach ($obsolete as $pk => $m) {
                if (mb_substr($m, 0, 2) === '@@' && mb_substr($m, -2) === '@@') {
                    unset($obsolete[$pk]);
                }
            }
        }

        $obsolete = array_keys($obsolete);
        $this->stdout("Inserting new messages...");
        $savedFlag = false;
        $columnNames = $db->getTableSchema($sourceMessageTable)->columnNames;
        $hasLocationColumn = in_array('location', $columnNames) ?: false;

        foreach ($new as $category => $msgs) {
            foreach ($msgs as $m) {
                $savedFlag  = true;
                $msgHash    = md5($m);
                $sourceMessageData = [
                    'category'  => $category,
                    'message'   => $m,
                ];
                if ( true === $hasLocationColumn ) {
                    $sourceMessageData['location']  = $this->extractLocations($category, $m);
                    $sourceMessageData['hash']      = $msgHash;
                }
                $db->createCommand()
                    ->insert($sourceMessageTable, $sourceMessageData)
                    ->execute()
                ;
                $lastID = ($db->driverName == 'pgsql')
                        ? $db->getLastInsertID($sourceMessageTable . '_id_seq')
                        : $db->getLastInsertID();
                foreach ($languages as $language) {
                    $messageData = [
                        'id'        => $lastID,
                        'language'  => $language,
                    ];
                    if ( true === $hasLocationColumn ) {
                        $messageData['hash'] = $msgHash;
                    }
                    $db->createCommand()
                        ->insert($messageTable, $messageData)
                        ->execute()
                    ;
                }
            }
        }

        $this->stdout($savedFlag ? "saved." . PHP_EOL : "Nothing new...skipped." . PHP_EOL);
        $this->stdout($removeUnused ? "Deleting obsoleted messages..." . PHP_EOL : "Updating obsoleted messages..." . PHP_EOL);

        if (empty($obsolete)) {
            $this->stdout("Nothing obsoleted!...skipped." . PHP_EOL);
        } else {
            if ($removeUnused) {
                $db->createCommand()
                   ->delete($sourceMessageTable, ['in', 'id', $obsolete])->execute();
                $this->stdout("deleted." . PHP_EOL);
            } else {
                $db->createCommand()
                    ->update(
                        $sourceMessageTable,
                        ['message' => new \yii\db\Expression("CONCAT('@@',message,'@@')")],
                        ['in', 'id', $obsolete]
                    )
                    ->execute()
                ;
                $this->stdout("updated." . PHP_EOL);
            }
        }

        // ------------------------------ COUNTER ------------------------------
        $counter = ['new' => 0, 'obsolete' => count($obsolete)];
        foreach ( $new as $msgs ) {
            $counter['new'] += count($msgs);
        }

        return $counter;
    }
1373977
public static function unUsing(IDb $db, string $sql)
    {
        $hashCode = $db->hashCode();
        if(isset(static::$statements[$hashCode][$sql]))
        {
            static::$statements[$hashCode][$sql]['using'] = false;
        }
    }
348990
public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL)
    {
        $this->io->overwrite($messages, $newline, $verbosity);
    }
1100430
protected function sortMessages(&$messages)
    {
        if (is_array($messages)) {
            ksort($messages);

            foreach ($messages as $key => &$value) {
                $this->sortMessages($value);
            }
        }
    }
852160
public function sendMessage(MessageInterface $message, array $recipients)
    {
        $messageProcessor = new MessageProcessor($this->getProcessorStore());
        $message = $messageProcessor->preProcessMessage($message);

        foreach ($recipients as $recipient) {
            foreach ($this->getChannels($message, $recipient) as $channel) {
                $processedMessage = $messageProcessor
                    ->processMessage(clone($message), $recipient);
                if ($channel->isHandling($processedMessage, $recipient)) {
                    $channel->send($processedMessage, $recipient);
                }
            }
        }
    }
806334
public function saveMessages()
    {
        if (!$this->getId()) {
            return $this->save();
        }

        $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
        /* @var $connection Varien_Db_Adapter_Interface */

        $count = $connection
            ->update(
                $this->getResource()->getMainTable(),
                array('messages' => $this->getMessages()),
                array('schedule_id = ?' => $this->getId())
            );

        if (!$count) {
            /**
             * Check if the row was not updated because of data truncation.
             */
            $warning = $this->_getPdoWarning($connection->getConnection());
            if ($warning && $warning->Code = 1265) {
                $maxLength = strlen($this->getMessages()) - 5000;
                $this->setMessages($warning->Level . ': ' .
                    str_replace(' at row 1', '.', $warning->Message) . PHP_EOL . PHP_EOL .
                    '...' . substr($this->getMessages(), -$maxLength));
            }
        }

        return $this;
    }
324397
protected function saveMessage()
    {
        $this->savedMessage = ['headers' => []];
        $this->savedMessage['body'] = $this->getBody();
        $this->savedMessage['children'] = $this->getChildren();
        if (count($this->savedMessage['children']) > 0 && '' != $this->getBody()) {
            $this->setChildren(array_merge([$this->becomeMimePart()], $this->savedMessage['children']));
            $this->setBody('');
        }
    }
932905
public function loadTranslations($languages)
    {
        $languages = (array)$languages;

        foreach ($languages as $language) {
            $this->loadTranslation($language);
        }
    }
1197141
public function initDb(array $connections): void{
        $this->db = new Database();
        foreach ($connections as $name => $settings) {
            $this->db->addConnection($settings, $name);
        }
    }
974033
private static function fromArray(array $messages, Translations $translations)
    {
        foreach ($messages as $original => $translation) {
            if ($original === '') {
                self::extractHeaders($translation, $translations);
                continue;
            }

            $translations->insert(null, $original)->setTranslation($translation);
        }
    }
1083549
public static function create(array $data = [], array $rules = [], array $messages = [])
    {
        $model = new static;
        $model->saveRecursive($data, $rules, $messages);

        return $model;
    }
1079242
public function createLanguageSourceDataProvider($languageSources)
    {
        $data = [];
        foreach ($languageSources as $category => $messages) {
            foreach ($messages as $message => $boolean) {
                $data[] = [
                    'category' => $category,
                    'message' => $message,
                ];
            }
        }

        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => false,
        ]);
    }
193300
public function saveData($database, $language)
    {
        $initData = include('install/core/afterInstall/config.php');
        $siteUrl = $this->getSystemHelper()->getBaseUrl();
        $databaseDefaults = $this->app->getContainer()->get('config')->get('database');

        $data = array(
            'database' => array_merge($databaseDefaults, $database),
            'language' => $language,
            'siteUrl' => $siteUrl,
            'passwordSalt' => $this->getPasswordHash()->generateSalt(),
            'cryptKey' => $this->getContainer()->get('crypt')->generateKey()
        );

        $owner = $this->getFileManager()->getPermissionUtils()->getDefaultOwner(true);
        $group = $this->getFileManager()->getPermissionUtils()->getDefaultGroup(true);

        if (!empty($owner)) {
            $data['defaultPermissions']['user'] = $owner;
        }
        if (!empty($group)) {
            $data['defaultPermissions']['group'] = $group;
        }

        $data = array_merge($data, $initData);
        $result = $this->saveConfig($data);

        return $result;
    }
586457
public function saveTranslation($language, $data, $formName = null) {
        $model = $this->getTranslationModel($language);
        $model->load($data, $formName);
        $dirty = $model->getDirtyAttributes();
       
        if (empty($dirty)) {
            return true; // we do not need to save anything
        }

        /** @var \yii\db\ActiveQuery $relation */
        $relation = $this->owner->getRelation($this->relation);

        $model->{key($relation->link)} = $this->owner->getPrimaryKey();
//        $result = $model->save();
//        if (!$result) {
//            Yii::info(\yii\helpers\VarDumper::dumpAsString($model->getErrors()));
//        }
//        return $result;
        return $model->save();
    }
736072
public static function info(...$messages): void
    {
        static::init();

        if (!static::isTemporaryDisabled('info')) {
            foreach (static::$adapters as $adapter) {
                /* @var $adapter \Koldy\Log\Adapter\AbstractLogAdapter */
                if ($adapter->isLevelEnabled(self::INFO)) {
                    $adapter->info((new Message(self::INFO))->setMessages($messages));
                }
            }
        }
    }
1314932
private function updateMessages(array $messages)
    {
        $this->reset();

        foreach ($messages as $message) {
            $messageSize = strlen($message);

            $this->data['messages_size'] += $messageSize;
            $this->data['messages_count']++;

            $this->data['messages'] []= array(
                'content' => $message,
                'size' => $messageSize,
                'decoded' => unserialize($message),
            );
        }
    }
1325737
public function postMessage($sender, $recipient, $message)
    {
        if (!isset($this->database[$recipient])) {
            $this->database[$recipient] = [];
        } elseif ($this->maxMessages
            && count($this->database[$recipient]) >= $this->maxMessages) {
            return false;
        }

        $this->database[$recipient][] = [
            'timestamp' => date('Y-m-d H:i:s'),
            'sender' => $sender,
            'message' => $message,
        ];

        return true;
    }