Converting the property value before saving to database

@return $this
428549
public function beforeSaveValue($value)
    {
        try
        {
            $value      = Json::encode($value);
        } catch (\Exception $e)
        {
            $value      = "{}";
        }

        return $value;
    }
254157
public function unsetValue() {
		if ($this->isOrphan()) {
			if ($this->orphanType == "publicproperty") {
				return $this->moufManager->unsetParameter($this->instanceDescriptor->getIdentifierName(), $this->name);
			} elseif ($this->orphanType == "setter") {
				return $this->moufManager->unsetParameterForSetter($this->instanceDescriptor->getIdentifierName(), $this->name);
			} elseif ($this->orphanType == "constructorargument") {
				return $this->moufManager->unsetParameterForConstructor($this->instanceDescriptor->getIdentifierName(), $this->name);
			} else {
				throw new MoufException("Unsupported orphan type: it is not a public field nor a setter nor a constructor...");
			}
		}
		
		if ($this->propertyDescriptor->isPublicFieldProperty()) {
			return $this->moufManager->unsetParameter($this->instanceDescriptor->getIdentifierName(), $this->name);
		} elseif ($this->propertyDescriptor->isSetterProperty()) {
			return $this->moufManager->unsetParameterForSetter($this->instanceDescriptor->getIdentifierName(), $this->name);
		} elseif ($this->propertyDescriptor->isConstructor()) {
			return $this->moufManager->unsetParameterForConstructor($this->instanceDescriptor->getIdentifierName(), $this->propertyDescriptor->getParameterIndex());
		} else {
			throw new MoufException("Unsupported property type: it is not a public field nor a setter nor a constructor...");
		}
	}
835155
public function save() {
        global $DB;
        if (empty($this->id)) {
            $r = (object)array(
                'data' => base64_encode(serialize($this)),
                'expirytime' => time() + (60*60*24),
                'userid' => $this->user->id,
                'instance' => (empty($this->instance)) ? null : $this->instance->get('id'),
            );
            $this->id = $DB->insert_record('portfolio_tempdata', $r);
            $this->expirytime = $r->expirytime;
            $this->save(); // call again so that id gets added to the save data.
        } else {
            if (!$r = $DB->get_record('portfolio_tempdata', array('id' => $this->id))) {
                if (!$this->deleted) {
                    //debugging("tried to save current object, but failed - see MDL-20872");
                }
                return;
            }
            $r->data = base64_encode(serialize($this));
            $r->instance = (empty($this->instance)) ? null : $this->instance->get('id');
            $DB->update_record('portfolio_tempdata', $r);
        }
    }
1079019
protected function setupObject()
    {
        $schemaType = strtoupper($this->getAttribute("type"));
        $this->copy($this->getDatabase()->getPlatform()->getDomainForType($schemaType));

        //Name
        $this->name = $this->getAttribute("name");

        // Default value
        $defval = $this->getAttribute("defaultValue", $this->getAttribute("default"));
        if ($defval !== null) {
            $this->setDefaultValue(new ColumnDefaultValue($defval, ColumnDefaultValue::TYPE_VALUE));
        } elseif ($this->getAttribute("defaultExpr") !== null) {
            $this->setDefaultValue(new ColumnDefaultValue($this->getAttribute("defaultExpr"), ColumnDefaultValue::TYPE_EXPR));
        }

        $this->size = $this->getAttribute("size");
        $this->scale = $this->getAttribute("scale");
        $this->description = $this->getAttribute("description");
    }
1172323
public function save() {
        $this->invoke(self::BEFORE_SAVE, [$this]);
        if ($this->isNewRecord) {
            $row = $this->insert();
        } else {
            $row = $this->update();
        }
        $this->invoke(self::BEFORE_SAVE, [$this]);
        return $row;
    }
1298530
protected function configureDataProperties(){
        if (isset($this->properties[self::PROPERTY_DATA])){
            $this->data->setProperties($this->properties['data']);
        }
        return $this;
    }
165830
protected function before() {
		if($this->connection->getDatabasePlatform() instanceof SQLServerPlatform) {
			$this->connection->executeUpdate('EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"');
		} else if($this->connection->getDatabasePlatform() instanceof MySqlPlatform) {
			$this->connection->executeUpdate('SET FOREIGN_KEY_CHECKS=0');
		} else if($this->connection->getDatabasePlatform() instanceof SqlitePlatform) {
			$this->connection->executeUpdate('PRAGMA foreign_keys = OFF');
		}
	}
352285
protected function _convertAdditionalData()
    {
        $details = @unserialize($this->getInfo()->getAdditionalData());

        if (is_array($details)) {
            $this->_billerCode = isset($details['biller_code']) ? (string) $details['biller_code'] : '';
            $this->_ref = isset($details['ref']) ? (string) $details['ref'] : '';
        } else {
            $this->_billerCode = '';
            $this->_ref = '';
        }

        return $this;
    }
45933
public function save()
    {
        $data = $this->getData();
        if (!$this->currentId)
        {
            $config = $this->getConfig();
            $config->last_id++;
            $this->tableFields->{$this->databaseConfig->getIdentifier()} = $config->last_id;
            array_push($data,$this->tableFields);
            $this->databaseConfig->put($config);
        }
        else
        {
            $this->tableFields->{$this->databaseConfig->getIdentifier()} = $this->currentId;
            $data[$this->currentKey]    = $this->tableFields;
        }
        $this->databaseDocument->put($data);
        return (!$this->currentId) ? $this->setFields() : $this;
    }
965884
protected function convertation()
    {
        if ($this->executionTime instanceof DateTime) {
            $this->executionTime = $this->executionTime->toString();
        } elseif ($this->executionTime === null) {
            $time = new DateTime();
            $this->executionTime = $time->toString();
        }

        foreach (['periodically', 'active'] as $property) {
            if ($this->$property === true) {
                $this->$property = 'Y';
            } else {
                $this->$property = 'N';
            }
        }
    }
1132738
protected function bindExpectedToObject()
    {
        $accessor = PropertyAccess::createPropertyAccessor();

        $values = array_merge($this->expectedValues, $this->expectedMocks, $this->expectedMocksCollections);

        foreach ($values as $property => $value) {
            if (is_array($value)) {
                $addMethod = 'add'.ucfirst($property);
                foreach ($value as $mock) {
                    $this->getObjectToTest()->$addMethod($mock);
                }
            } else {
                if ($accessor->isWritable($this->getObjectToTest(), $property)) {
                    // Use direct access to property to avoid "only variables should be passed by reference"
                    $accessor->setValue($this->objectToTest, $property, $value);
                }
            }
        }

        // Tear down
        unset($values);
        unset($accessor);

        return $this;
    }
268101
public function savePropertiesAction()
	{
		$idPage = $this->params()->fromRoute('idPage', $this->params()->fromQuery('idPage', ''));
		$isNew = $this->params()->fromRoute('isNew', $this->params()->fromQuery('isNew', ''));
		$translator = $this->serviceLocator->get('translator');
		
		$eventDatas = array('idPage' => $idPage, 'isNew' => $isNew);
		$this->getEventManager()->trigger('meliscms_page_saveproperties_start', null, $eventDatas);
		
		// Get the form properly loaded
		$propertyForm = $this->getPropertyPageForm($idPage, $isNew);
	
		$melisPageSavedTable = $this->getServiceLocator()->get('MelisEngineTablePageSaved');
    	$melisPagePublishedTable = $this->getServiceLocator()->get('MelisEngineTablePagePublished');
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');
		// Check if post
		$request = $this->getRequest();
		if ($request->isPost())
		{
		    // Get the current page id from platform table
		    $melisModuleName = getenv('MELIS_PLATFORM');
		    $melisEngineTablePlatformIds = $this->getServiceLocator()->get('MelisEngineTablePlatformIds');
		    $datasPlatformIds = $melisEngineTablePlatformIds->getPlatformIdsByPlatformName($melisModuleName);
		    $datasPlatformIds = $datasPlatformIds->current();
		    
		    if (!empty($datasPlatformIds))
		    {
        		// Get values posted and set them in form
                $postValues = $this->params()->fromRoute();
                if(!isset($postValues['page_duplicate_event_flag'])) {
                    $postValues = get_object_vars($request->getPost());
                    $postValues = $melisTool->sanitizePost($postValues);
                }

        		$propertyForm->setData($postValues);
               
                if (!$isNew)
                {
                    // Set Page lang id not required
                    $propertyForm->getInputFilter()->get('plang_lang_id')->setRequired(false);
                }
        		
        		// Validate the form 
        		if ($propertyForm->isValid())
        		{
        			// Get datas validated
        			$datas = $propertyForm->getData();
        
        			/**
        			 * First, let's copy the published table entry
        			 * inside the saved table if there's no entry in it.
        			 * Kind of special case, the page is not new, it's being edited after being published
        			 */
        			if (!$isNew)
        			{
        				$dataSaved = $melisPageSavedTable->getEntryById($idPage);
        				$dataSaved = $dataSaved->toArray();
        				if (count($dataSaved) == 0)
        				{
        					$dataPublished = $melisPagePublishedTable->getEntryById($idPage);
        					$dataPublished = $dataPublished->toArray();
        					if (count($dataPublished) > 0)
        					{
        						$dataPublished = $dataPublished[0];
        						$melisPageSavedTable->save($dataPublished, $idPage);
        					}
        				}
        			}
        			else
        			{
        				// New page, create an empty content
        				$newXmlContent = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        				$newXmlContent .= '<document type="MelisCMS" author="MelisTechnology" version="2.0">' . "\n";
        				$newXmlContent .= '</document>';
        				$datas['page_content'] = $newXmlContent;
        			}
        			
        			
        			/**
        			 * Datas are all saved in PageSave once validated.
        			 * This allow to add fields in the app.form and fields in the db.
        			 * It will then works with the new field as long as it's in the same table.
        			 * 
        			 * Useless fields from the form must be unset
        			 * Special fields must be set
        			 */
        
        			
        			$errors = array();
        			$success = 0;
        			$language = $datas['plang_lang_id'];
        			$template = $datas['page_tpl_id'];
        			
        			unset($datas['page_submit']);
        			unset($datas['page_creation_date']);
        			unset($datas['plang_lang_id']);
        			unset($datas['style_id']);
        			
        			$datas['page_id'] = $idPage;
        			
        			if(empty($template)) {
        			    $errors = array(
        			        'page_tpl_id' => array(
        			            'errorMessage' => $translator->translate('tr_meliscms_page_form_page_tpl_id_invalid'),
        			            'label' => $translator->translate('tr_meliscms_page_tab_properties_form_Template'),
        			        ),
        			    );
        			}
        			
        			if ($isNew) 
        			{
        			    $datas['page_creation_date'] = date('Y-m-d H:i:s');
        			    
        			    if(empty($language)) {
        			        $errors = array(
        			            'plang_lang_id' => array(
        			                'errorMessage' => $translator->translate('tr_meliscms_page_form_page_p_lang_id_invalid'),
        			                'label' => $translator->translate('tr_meliscms_page_tab_properties_form_Language'),
        			            ),
        			        );
        			    }
        			}
        			else 
        			{
        			    $datas['page_edit_date'] = date('Y-m-d H:i:s');
        			    
        			    $melisCoreAuth = $this->getServiceLocator()->get('MelisCoreAuth');
        			    $user = $melisCoreAuth->getIdentity();
        			    if (!empty($user))
        			    	$datas['page_last_user_id'] = $user->usr_id;
        			}
        				
        			
        				
        			if(empty($errors))	{
        			    $success = 1;
        			    $res = $melisPageSavedTable->save($datas, $idPage);
        			}
        			    
        
        			$result = array(
        					'success' => $success,
        					'errors' => array($errors),
        			);
        
        		}
        		else
        		{
        			// Get validation errors
        			$result = array(
        					'success' => 0,
        					'errors' => array($propertyForm->getMessages()),
        			);
        		}
		    }
		    else 
		    {
		        $errors = array(
		            'platform_ids' => array(
		                'noPlatformIds' => $translator->translate('tr_meliscms_no_available_platform_ids'),
		                'label' => $translator->translate('tr_meliscms_tool_platform_ids'),
		            ),
		        );
		        
		        $result = array(
		            'success' => 0,
		            'errors' => array($errors),
		        );
            }
		}
		else
		{
			$result = array(
					'success' => 0,
					'errors' => array(array('empty' => $translator->translate('tr_meliscms_form_common_errors_Empty datas'))),
			);
		}

		$this->getEventManager()->trigger('meliscms_page_saveproperties_end', null, $result);
		
		return new JsonModel($result);
	}
100744
public function beforeSave()
    {
        $handler = $this->get('handler');
        if (class_exists($handler)) {
            $handler = new $handler();

            return $handler->beforeSave($this);
        }
    }
925349
public function sanitizeValue()
    {
        $strColNameId    = $this->objAttribute->get('tag_id') ?: 'id';
        $strColNameAlias = $this->objAttribute->get('tag_alias');
        $arrValues       = \is_array($this->value) ? $this->value : \explode(',', $this->value);

        if (!$this->isMetaModel()) {
            if ($strColNameAlias) {
                $builder = $this->connection->createQueryBuilder()
                    ->select($strColNameId)
                    ->from($this->objAttribute->get('tag_table'));
                foreach ($arrValues as $index => $value) {
                    $builder
                        ->orWhere($strColNameAlias . ' LIKE :value_' . $index)
                        ->setParameter('value_' . $index, $value);
                }
                $arrValues = $builder->execute()->fetchAll(\PDO::FETCH_COLUMN);
            } else {
                $arrValues = \array_map('intval', $arrValues);
            }
        } else {
            if ($strColNameAlias == 'id') {
                $values = $arrValues;
            } else {
                $values = [];
                foreach ($arrValues as $value) {
                    $values[] = \array_values(
                        $this->getTagMetaModel()->getAttribute($strColNameAlias)->searchFor($value)
                    );
                }
            }

            $arrValues = $this->flatten($values);
        }

        return $arrValues;
    }
1090687
protected function setupValue()
    {
        $value = $this->getOption($this->valueProperty);
        $isChild = $this->getOption('is_child');

        if ($value instanceof \Closure) {
            $this->valueClosure = $value;
        }

        if (($value === null || $value instanceof \Closure) && !$isChild) {
            $this->setValue($this->getModelValueAttribute($this->parent->getModel(), $this->name));
        } elseif (!$isChild) {
            $this->hasDefault = true;
        }
    }
910204
public function afterSave()
    {
        /** @var \yii\db\ActiveRecord|\DevGroup\DataStructure\traits\PropertiesTrait $owner */
        $owner = $this->owner;
        $event = new HasPropertiesEvent();
        $event->model = $owner;
        HasPropertiesEvent::trigger(self::class, self::EVENT_AFTER_UPDATE, $event);
        if ($this->autoSaveProperties === true) {
            $models = [&$owner];
            PropertiesHelper::storeValues($models);
        }
        $owner->changedProperties = [];
        $owner->propertiesValuesChanged = false;

        // check for auto added property groups
        $owner->ensurePropertyGroupIds();
        $autoAddedGroups = PropertyGroup::getAutoAddedGroupsIds(
            PropertiesHelper::applicablePropertyModelId($owner)
        );

        foreach ($autoAddedGroups as $id) {
            if (!in_array($id, $owner->propertyGroupIds)) {
                /** @var PropertyGroup $propertyGroup */
                $propertyGroup = PropertyGroup::loadModel(
                    $id,
                    false,
                    true,
                    86400,
                    new ServerErrorHttpException("Property group with id $id not found"),
                    true
                );
                $owner->addPropertyGroup($propertyGroup);
            }
        }
    }
1318630
public function save()
    {
        $result;
        if (! self::$id) {
            // new record so we insert
            $query = "INSERT INTO $this->tableName (".implode(", ", array_keys($this->props)).") VALUES(";

            for ($i = 0; $i < count($this->props); $i++) {
                $query .= "?";

                if ($i != count($this->props) - 1) {
                    $query .= ",";
                }
            }

            $query .= ");";

            $insert = Connection::db()->prepare($query);
            $result = $insert->execute(array_values($this->props));
        } else {
            // existing record, se we update
            $query = "UPDATE $this->tableName SET ";

            $count = 0;
            foreach ($this->props as $key => $value) {
                $query .= "$key = '$value'";

                if ($count != count($this->props) - 1) {
                    $query .= ",";
                }
                $count++;
            }

            $query .= " WHERE id = ".self::$id;
            $result = Connection::db()->query($query);
        }

        if (! $result) {
            return false;
        } else {
            return true;
        }
    }