rsce_data field save callback

Returns the JSON encoded $this->saveData

@param  string         $value Current field value
@param  \DataContainer $dc    Data container
@return string                JSON encoded $this->saveData
973520
public function saveDataCallback($value, $dc)
	{
		$this->prepareSaveData('rsce_field_', $this->fieldsConfig);

		$data = json_encode($this->saveData);

		if ($data === '[]') {
			$data = '{}';
		}

		return $data;
	}
956528
public function setMultiSrcFlags($value, DataContainer $dataContainer)
    {
        if ($dataContainer->activeRecord && $dataContainer->activeRecord->type === 'bs_grid_gallery') {
            $fieldsDca =& $GLOBALS['TL_DCA'][$dataContainer->table]['fields'][$dataContainer->field]['eval'];

            $fieldsDca['isGallery']  = true;
            $fieldsDca['extensions'] = Config::get('validImageTypes');
        }

        return $value;
    }
688868
public function serialize($value)
    {
        if ($this->getDataType() === 'json') {
            return json_encode($value);
        } elseif ($this->getDataType() === 'array') {
            return json_encode($value);
        } elseif ($this->getDataType() === 'list') {
            return implode(',', $value);
        }

        return trim($value);
    }
763831
protected function processSaveValue($value)
    {
        if (!is_array($value) || !$value) {
            return $value;
        }

        if ($this->useGroups) {
            foreach ($value as $index => &$data) {
                $data['_group'] = $this->getGroupCodeFromIndex($index);
            }
        }

        if ($this->minItems && count($value) < $this->minItems) {
            throw new ApplicationException(Lang::get('backend::lang.repeater.min_items_failed', ['name' => $this->fieldName, 'min' => $this->minItems, 'items' => count($value)]));
        }
        if ($this->maxItems && count($value) > $this->maxItems) {
            throw new ApplicationException(Lang::get('backend::lang.repeater.max_items_failed', ['name' => $this->fieldName, 'max' => $this->maxItems, 'items' => count($value)]));
        }

        return array_values($value);
    }
373443
public function serialize($value): string
    {
        if ($value instanceof Carbon) {
            return $value->toDateTimeString();
        }

        return $this
            ->tryParsingDateTime($value, InvariantViolation::class)
            ->toDateTimeString();
    }
345414
protected function getSerializeValue($value, $event)
    {
        switch ($event) {
            case ActiveRecord::EVENT_BEFORE_INSERT:
            case ActiveRecord::EVENT_BEFORE_UPDATE:
                if (is_array($value)) {
                    $value = serialize($value);
                }
                break;
            case ActiveRecord::EVENT_AFTER_FIND:
                $value = @unserialize($value) ?: $value;
                break;
        }
        return $value;
    }
392525
private function phpEncodeValue($value)
    {
        if (is_array($value)) {
            return $this->phpEncodeArray($value);
        }

        if (is_string($value)) {
            return json_encode($value);
        }

        return var_export($value, true);
    }
792811
public function defaultSizes($value, $dc)
	{
		if ($value == '')
		{			
			return \System::getContainer()->get('contao.image.image_sizes')->getAllOptions()['image_sizes'];
		}

		$intNeededSize = \StringUtil::deserialize($dc->activeRecord->size)[2];
		$arrSelectedSizes = \StringUtil::deserialize($value);
		
		if (!in_array($neededSize, $arrSelectedSizes))
		{
			$arrSelectedSizes[] = $intNeededSize;
			return serialize($arrSelectedSizes);
		}

		return $value;
	}
972445
public static function jsonEncode($value): string
	{
		return Nette\Utils\Json::encode($value, self::jsonEncodeOptions());
	}
478285
public function convert_external_data($value) {
        if (isset($this->options[$value])) {
            $retval = $value;
        } else {
            $retval = array_search($value, $this->options);
        }

        // If value is not found in options then return null, so that it can be handled
        // later by edit_save_data_preprocess.
        if ($retval === false) {
            $retval = null;
        }
        return $retval;
    }
784700
public function save($value, $dc)
	{
		// shortcuts
		$start  = ContentWrapper\Model::TYPE_START;
		$stop   = ContentWrapper\Model::TYPE_STOP;
		$sep    = ContentWrapper\Model::TYPE_SEPARATOR;

		// handle issues with contao models
		if(version_compare(VERSION, '3.2', '>=')) {
			try {
				$model = new \ContentModel($dc->activeRecord);
			}
			catch(\Exception $e) {
				$model = \ContentModel::findByPk($dc->id);
			}
		}
		else {
			$model = new \ContentModel($dc->activeRecord);
		}

		$model->type = $value;

		$this->objModel = new ContentWrapper\Model($model);
		$sorting = $this->objModel->sorting;

		// getType will throw an exception if type is not found. use it to detect non content wrapper elements
		try {
			$type = $this->objModel->getType();
		}
		catch(\Exception $e)
		{
			return $value;
		}

		// check for existing parent element and try to create it if not existing
		if($type != $start) {
			if($this->objModel->bootstrap_parentId == '') {
				$parent = ContentWrapper\Repository::findPreviousElement($this->objModel, $start);

				if($parent) {
					// set relation to parent element
					$this->objModel->bootstrap_parentId = $parent->id;

					$end = ContentWrapper\Repository::findRelatedElement($this->objModel, $stop);

					if($end === null) {
						$this->objModel->sorting = $parent->sorting + 2;
					}
					elseif($parent !== null && $parent->sorting > $end->sorting) {
						$this->objModel->sorting = $end->sorting - 2;
					}

					// set relation to parent element
					if($this->objModel->getType() != $start) {
						$this->objModel->bootstrap_parentId = $parent->id;
					}

					$this->objModel->getModel()->save();
				}

				// create parent if possible
				elseif($this->isTrigger($type, $start)) {
					$sorting = $sorting-2;
					$this->createElement($sorting, $start);
				}

				// no parent element exists, throw error
				else
				{
					throw new \Exception(sprintf(
						$GLOBALS['TL_LANG']['ERR']['wrapperStartNotExists'],
						$GLOBALS['TL_LANG']['CTE'][$value][0] ?: $value
					));
				}
			}
		}

		// create separators if possible
		if($type != $sep && ($this->isTrigger($type, $sep) || $this->isTrigger($type, $sep, static::TRIGGER_DELETE)))
		{
			$config   = $GLOBALS['BOOTSTRAP']['wrappers'][$this->objModel->getGroup()][$sep];
			$callback = $config['countExisting'];
			$this->import($callback[0]);
			$existing = $this->$callback[0]->$callback[1]($this->objModel);

			$callback = $config['countRequired'];
			$this->import($callback[0]);
			$required = $this->$callback[0]->$callback[1]($this->objModel);

			if($existing < $required)
			{
				if($this->isTrigger($type, $sep))
				{
					$count = $required - $existing;

					for($i = 0; $i < $count; $i++)
					{
						$this->createElement($sorting, $sep);
					}

					$end = ContentWrapper\Repository::findRelatedElement($this->objModel, $stop);

					if($end && $end->sorting <= $sorting) {
						$sorting = $sorting + 2;
						$end->sorting = $sorting;
						$end->save();
					}
				}
			}
			elseif($required < $existing)
			{
				if($this->isTrigger($type, $sep, static::TRIGGER_DELETE))
				{
					$count = $existing - $required;

					$parentId = $this->objModel->getType() == ContentWrapper\Model::TYPE_START
						? $this->objModel->id
						: $this->objModel->bootstrap_parentId;

					$this->Database
						->prepare('DELETE FROM tl_content WHERE bootstrap_parentId=? AND type=? ORDER BY sorting DESC')
						->limit($count)
						->execute($parentId, $this->objModel->getTypeName($sep));
				}
			}
		}

		// cereate end element
		if($type == $start && $this->isTrigger($type, $stop))
		{
			$end = ContentWrapper\Repository::countRelatedElements($this->objModel, $stop);

			if(!$end) {
				$end = $this->createElement($sorting, $stop);
			}
		}

		return $value;
	}
90372
public function serialize($value)
    {
        $this->reset();
        $serializedData = $this->serializeData($value);
        $encoded = json_encode($serializedData, $this->calculateEncodeOptions());
        if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
            if (json_last_error() != JSON_ERROR_UTF8) {
                throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
            }

            $serializedData = $this->encodeNonUtf8ToUtf8($serializedData);
            $encoded = json_encode($serializedData, $this->calculateEncodeOptions());

            if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
                throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
            }
        }
        return $this->processEncodedValue($encoded);
    }
560282
public static function encode($value, $options = 0)
    {
        $result = json_encode($value, (int) $options);
        // @codeCoverageIgnoreStart
        if ($result === false) {
            throw new \RuntimeException(static::$errorMessages[json_last_error()]);
        }
        // @codeCoverageIgnoreEnd

        return $result;
    }
565165
public function save($key = '', $value = '')
    {
        try {
            if ($this->cacheInstance !== NULL && is_object($this->cacheInstance)) {
                /**
                 * @var $cache object
                 */
                $cache = $this->cacheInstance->getItem($key);
                if (!$cache->isHit()) {
                    $cache->set($value)->expiresAfter($this->cacheTtl);//in seconds, also accepts Datetime
                    $this->cacheInstance->save($cache); // Save the cache item just like you do with doctrine and entities
                    $result = $cache->get();
                    $this->debug->debug(__FUNCTION__, 'Save Cache Key: ' . $key . ' with Value: ' . json_encode($value));
                } else {
                    $result = $cache->get();
                    $this->debug->debug(__FUNCTION__, 'Get Cache from Key: ' . $key . ', result: ' . json_encode($result));
                }
                $message = 'Final get Content from Key: ' . $key . ' => Output result: ' . json_encode($result);
                $this->debug->info(__FUNCTION__, $message);

                return $result;
            } else {
                $this->debug->error(__FUNCTION__, 'Unavailable cacheInstance');

                return NULL;
            }
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return $message;
        }
    }
921681
public static function jsonDecode($value)
    {
        if (defined('JSON_PARSER_NOTSTRICT')) { // pecl-json-c ext
            $decoded = json_decode($value, false, 512, JSON_PARSER_NOTSTRICT);
        } else { // json-ext
            $decoded = json_decode($value);
        }

        return $decoded;
    }
1357218
public function setPickerOptions($value, $dc)
	{
		$db = Database::getInstance();
		
		switch ($value)
		{
			case 'datetime':
				if (!in_array($dc->activeRecord->rgxp, array('date', 'time', 'datim')))
				{
					// Change rgxp in database
					$db->prepare("UPDATE " . $this->table . " SET rgxp=? WHERE id=?")
					   ->execute('date', $dc->activeRecord->id);
				}
				if ($dc->activeRecord->multiple)
				{
					// Reset multiple in database
					$db->prepare("UPDATE " . $this->table . " SET multiple=? WHERE id=?")
					   ->execute('', $dc->activeRecord->id);
				}
				break;
	
			case 'color':
				if (!in_array($dc->activeRecord->rgxp, array('alnum', 'extnd')))
				{
					// Change rgxp in database
					$db->prepare("UPDATE " . $this->table . " SET rgxp=? WHERE id=?")
					   ->execute('', $dc->activeRecord->id);
				}
				break;
				
			case 'link':
				if ($dc->activeRecord->rgxp != 'url')
				{
					// Change rgxp in database
					$db->prepare("UPDATE " . $this->table . " SET rgxp=? WHERE id=?")
					   ->execute('url', $dc->activeRecord->id);
				}
				if ($dc->activeRecord->multiple)
				{
					// Reset multiple in database
					$db->prepare("UPDATE " . $this->table . " SET multiple=? WHERE id=?")
					   ->execute('', $dc->activeRecord->id);
				}
				break;
				
			case 'unit':
				if ($dc->activeRecord->maxLength > 200)
				{
					// Change maxLength in database
					$db->prepare("UPDATE " . $this->table . " SET maxLength=? WHERE id=?")
					   ->execute(200, $dc->activeRecord->id);
				}
				if ($dc->activeRecord->multiple)
				{
					// Change multiple in database
					$db->prepare("UPDATE " . $this->table . " SET multiple=? WHERE id=?")
					   ->execute('', $dc->activeRecord->id);
				}
				break;

		}
		
		return $value;
	}
699322
public function onSaveType($value, $dc)
    {
        if ('root' !== $value && 'folder' !== $value && $dc->activeRecord->pid === 0) {
            throw new \Exception($GLOBALS['TL_LANG']['ERR']['topLevelRoot']);
        }

        return $value;
    }