Processing object before save data

Check if there are other schedules for the same job at the same time and skip saving in this case.

@return Mage_Core_Model_Abstract
517289
protected function _beforeSave()
    {
        if (!$this->getScheduledBy() && php_sapi_name() !== 'cli' && Mage::getSingleton('admin/session')->isLoggedIn()) {
            $this->setScheduledBy(Mage::getSingleton('admin/session')->getUser()->getId());
        }

        $collection = Mage::getModel('cron/schedule')/* @var $collection Mage_Cron_Model_Resource_Schedule_Collection */
            ->getCollection()
            ->addFieldToFilter('status', Aoe_Scheduler_Model_Schedule::STATUS_PENDING)
            ->addFieldToFilter('job_code', $this->getJobCode())
            ->addFieldToFilter('scheduled_at', $this->getScheduledAt());
        if ($this->getId() !== null) {
            $collection->addFieldToFilter('schedule_id', array('neq' => $this->getId()));
        }
        $count = $collection->count();
        if ($count > 0) {
            $this->_dataSaveAllowed = false; // prevents this object from being stored to database
            $this->log(sprintf('Pending schedule for "%s" at "%s" already exists %s times. Skipping.', $this->getJobCode(), $this->getScheduledAt(), $count));
        } else {
            $this->_dataSaveAllowed = true; // allow the next object to save (because it's not reset automatically)
        }
        return parent::_beforeSave();
    }
523919
protected function _beforeSave()
    {
        $value = $this->getValue();
        $value = Mage::helper('adyen/installments')->makeStorableArrayFieldValue($value);
        $this->setValue($value);
    }
1079626
public function beforeSave()
    {
        parent::beforeSave();
        if ($this->isObjectNew() && !$this->getCreatedAt()) {
            $this->setCreatedAt($this->dateTime->formatDate(true));
        }
        $this->setUpdatedAt($this->dateTime->formatDate(true));

        return $this;
    }
423745
public function process()
    {
        if ($this->isProcessed()) {
            throw new MultiProcessException('Already Processed!');
        }

        if ($this->doProcess()) {
            $this->setProcessed(true);
        }

        return $this;
    }
506847
public function save()
    {
        $objectHash = spl_object_hash($this);
        if (array_key_exists($objectHash, self::$saved)) {
            return true;
        }

        self::$saved[$objectHash] = true;

        $data = [];
        $validation = [];
        $one2many = AttributeType::ONE2MANY;
        $many2many = AttributeType::MANY2MANY;
        /* @var $attr AbstractAttribute */
        foreach ($this->getAttributes() as $key => $attr) {
            if ($attr->isRequired() && !$attr->hasValue()) {
                $ex = new ValidationException(ValidationException::VALIDATION_FAILED);
                $ex->addError($key, ValidationException::REQUIRED);
                $validation[$key] = $ex;
                continue;
            }

            if (!count($validation) && !$this->isInstanceOf($attr, $one2many) && !$this->isInstanceOf($attr, $many2many)) {
                if ($attr->getStoreToDb()) {
                    $data[$key] = $attr->getDbValue();
                }
            }
        }

        // Throw EntityException with invalid attributes
        if (count($validation)) {
            $attributes = [];
            foreach ($validation as $attr => $error) {
                foreach ($error as $key => $value) {
                    $attributes[$key] = $value;
                }
            }
            $ex = new EntityException(EntityException::VALIDATION_FAILED, [get_class($this), count($validation)]);
            $ex->setInvalidAttributes($attributes);
            throw $ex;
        }

        /**
         * Insert or update
         */
        $mongo = $this->entity()->getDatabase();
        if (!$this->exists()) {
            $data['_id'] = $mongo->isId($data['id']) ? $mongo->id($data['id']) : $mongo->id();
            $data['id'] = (string)$data['_id'];
            $mongo->insertOne(static::$collection, $data);
            $this->id = $data['id'];
        } else {
            $where = ['_id' => $mongo->id($this->id)];
            $mongo->update(static::$collection, $where, ['$set' => $data], ['upsert' => true]);
        }

        /**
         * Now save One2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr One2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::ONE2MANY) && $attr->isLoaded()) {
                foreach ($attr->getValue() as $item) {
                    $item->getAttribute($attr->getRelatedAttribute())->setValue($this);
                    $item->save();
                }
                /**
                 * The value of one2many attribute must be set to null to trigger data reload on next access.
                 * This is necessary when we have circular references, and parent record does not get it's many2one ID saved
                 * until all child referenced objects are saved. Only then can we get proper links between referenced classes.
                 */
                $attr->setValue(null, true);
            }
        }

        /**
         * Now save Many2Many values
         */
        foreach ($this->getAttributes() as $attr) {
            /* @var $attr Many2ManyAttribute */
            if ($this->isInstanceOf($attr, AttributeType::MANY2MANY)) {
                $attr->save();
            }
        }

        // Now that this entity is saved, remove it from save log
        unset(self::$saved[$objectHash]);

        return true;
    }
355696
public function setData()
    {
        // Process a collection
        if ($this->resource instanceof Collection) {
            $this->data = [];

            foreach ($this->resource->getData() as $resource) {
                $this->parseItem(new Item($resource, $this->resource->getTransformer()));
            }
        }

        // Process an item
        elseif ($this->resource instanceof Item) {
            $this->parseItem($this->resource);
        }

        return $this;
    }
16807
public function preSave()
    {
        if (!isset($this->revisionEnabled) || $this->revisionEnabled) {
            // if there's no revisionEnabled. Or if there is, if it's true

            $this->originalData = $this->original;
            $this->updatedData  = $this->attributes;

            // we can only safely compare basic items,
            // so for now we drop any object based items, like DateTime
            foreach ($this->updatedData as $key => $val) {
                if (gettype($val) == 'object' && ! method_exists($val, '__toString')) {
                    unset($this->originalData[$key]);
                    unset($this->updatedData[$key]);
                }
            }

            // the below is ugly, for sure, but it's required so we can save the standard model
            // then use the keep / dontkeep values for later, in the isRevisionable method
            $this->dontKeep = isset($this->dontKeepRevisionOf) ?
                array_merge($this->dontKeepRevisionOf, $this->dontKeep)
                : $this->dontKeep;

            $this->doKeep = isset($this->keepRevisionOf) ?
                array_merge($this->keepRevisionOf, $this->doKeep)
                : $this->doKeep;

            unset($this->attributes['dontKeepRevisionOf']);
            unset($this->attributes['keepRevisionOf']);

            $this->dirtyData = $this->getDirty();
            $this->updating = $this->exists;
        }
    }
252201
final public function store() {
		
		// hook for tasks to be executed before store
		$this->beforeStore();
		
		// create if object’s keys are populated
		if ($this->areKeysPopulated() and static::exists($this->getId())) {
			$ret = $this->update();
		} else {
			$ret = $this->create();
		}

		// hook for tasks to be executed after store
		$this->afterStore();
		
		return $ret;

	}
746181
public function getNewEmptyItem()
    {
        $model = Mage::getModel($this->model);

        if (!$model instanceof Aoe_Scheduler_Model_Job) {
            Mage::throwException(
                sprintf(
                    'Invalid model class. Expected "%s" and received "%s".',
                    'Aoe_Scheduler_Model_Job',
                    (is_object($model) ? get_class($model) : 'UNKNOWN')
                )
            );
        }

        return $model;
    }
685936
protected function beforeSave() 
	{
		$controller = strtolower(Yii::app()->controller->id);
		$action = strtolower(Yii::app()->controller->action->id);

		$location = $controller;
		
		if(parent::beforeSave()) {
			if($this->isNewRecord || (!$this->isNewRecord && !$this->name)) {
				$name=new SourceMessage;
				$name->message = $this->name_i;
				$name->location = $location.'_title';
				if($name->save())
					$this->name = $name->id;

				$this->slug = $this->urlTitle($this->name_i);
				
			} else {
				$name = SourceMessage::model()->findByPk($this->name);
				$name->message = $this->name_i;
				$name->save();
			}

			$this->sitetype_access = serialize($this->sitetype_access);
			$this->userlevel_access = serialize($this->userlevel_access);
		}
		return true;
	}
1653
public function beforeSave()
    {
        if ($this->file instanceof UploadedFile) {

            if (true !== $this->owner->isNewRecord) {
                /** @var ActiveRecord $oldModel */
                $oldModel = $this->owner->findOne($this->owner->primaryKey);
                $behavior = static::getInstance($oldModel, $this->attribute);
                $behavior->cleanFiles();
            }

            $this->owner->{$this->attribute} = implode('.',
                array_filter([$this->file->baseName, $this->file->extension])
            );
        } else {
            if (true !== $this->owner->isNewRecord && empty($this->owner->{$this->attribute})) {
                $this->owner->{$this->attribute} = ArrayHelper::getValue($this->owner->oldAttributes, $this->attribute,
                    null);
            }
        }
    }
302456
private function needsSchedulingForDirtyCheck()
    {
        return $this->owner && $this->dm && $this->mapping->isOwningSide
            && $this->dm->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify();
    }
587921
public function save()
    {
        if (!$this->activeRecordCriteriaPrototype) {
            throw new Exception\RuntimeException(sprintf(
                'An Active Record Criteria Prototype must be set prior to calling %s',
                __FUNCTION__
            ));
        }

        if (!$this->getModel()) {
            throw new Exception\RuntimeException(sprintf('A Model must be set prior to calling %s', __FUNCTION__));
        }

        $criteria = $this->activeRecordCriteriaPrototype;
        $criteria->setId($this->getId());
        $result = $this->getModel()->save($criteria, $this);
        return $result;
    }
1308908
protected function _prepareMassaction()
    {
        $this->setMassactionIdField('schedule_id');
        $this->getMassactionBlock()->setFormFieldName('schedule_ids');
        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label' => $this->__('Delete'),
                'url'   => $this->getUrl('*/*/delete'),
            )
        );
        $this->getMassactionBlock()->addItem(
            'kill',
            array(
                'label' => $this->__('Kill'),
                'url'   => $this->getUrl('*/*/kill'),
            )
        );
        return $this;
    }
723282
public function scheduleNowAction()
    {
        $code = $this->getArg('code');
        if (empty($code)) {
            echo "\nNo code found!\n\n";
            echo $this->usageHelp();
            exit(1);
        }

        $allowedCodes = Mage::getSingleton('aoe_scheduler/job')->getResource()->getJobCodes();
        if (!in_array($code, $allowedCodes)) {
            echo "\nNo valid job found!\n\n";
            echo $this->usageHelp();
            exit(1);
        }

        $schedule = Mage::getModel('cron/schedule'); /* @var $schedule Aoe_Scheduler_Model_Schedule */
        $schedule->setScheduledReason(Aoe_Scheduler_Model_Schedule::REASON_SCHEDULENOW_CLI);
        $schedule->setJobCode($code);
        $schedule->schedule();
        $schedule->save();
    }
74492
public function beforeModelSave()
    {
        $preferences = UserPreference::forUser();
        list($namespace, $group, $item) = $preferences->parseKey($this->recordCode);
        $this->model->item = $item;
        $this->model->group = $group;
        $this->model->namespace = $namespace;
        $this->model->user_id = $preferences->userContext->id;

        if ($this->fieldValues) {
            $this->model->value = $this->fieldValues;
        }
    }
764545
public function getDataForCache()
    {
        $reflectionClass = new \ReflectionObject($this);
        $array = array();
        $excludes = array_flip($this->excludedPropertiesForCache);
        $excludes['excludedPropertiesForCache'] = true;
        foreach ($reflectionClass->getProperties() as $property) {
            $propertyName = $property->getName();
            if (!isset($excludes[$propertyName])
                && null !== $value = $this->processPropertyForCache($propertyName)) {
                $array[$propertyName] = $value;
            }
        }

        return $this->encodeDataForCache($array);
    }