Add behavior methods to model class

@return string
778418
public function objectMethods($builder)
    {
        $array = $this->getParameters();
        if (empty($array)) {
            throw new InvalidArgumentException('Please, define your rules for validation.');
        }
        $this->cleanupParameters();

        $this->builder = $builder;
        $this->builder->declareClasses(
            'Symfony\\Component\\Validator\\Mapping\\ClassMetadata',
            'Symfony\\Component\\Validator\\DefaultTranslator',
            'Symfony\\Component\\Validator\\Mapping\\Loader\\StaticMethodLoader',
            'Symfony\\Component\\Validator\\ConstraintValidatorFactory',
            'Symfony\\Component\\Validator\\ConstraintViolationList'
        );

        //if SF >= 2.5 use new validator classes
        if(class_exists('Symfony\\Component\\Validator\\Validator\\RecursiveValidator')) {
            $this->builder->declareClasses(
                'Symfony\\Component\\Validator\\Validator\\RecursiveValidator',
                'Symfony\\Component\\Validator\\Context\\ExecutionContextFactory',
                'Symfony\\Component\\Validator\\Mapping\\Factory\LazyLoadingMetadataFactory',
                'Symfony\\Component\\Validator\\Context\\ExecutionContextInterface',
                'Symfony\\Component\\Validator\\Validator\\ValidatorInterface',
                'Symfony\\Component\\Translation\\IdentityTranslator'
            );
        } else {
            $this->builder->declareClasses(
                'Symfony\\Component\\Validator\\Validator',
                'Symfony\\Component\\Validator\\Mapping\ClassMetadataFactory',
                'Symfony\\Component\\Validator\\DefaultTranslator',
                'Symfony\\Component\\Validator\\ExecutionContextInterface',
                'Symfony\\Component\\Validator\\ValidatorInterface'
            );
        }

        $script = $this->addLoadValidatorMetadataMethod();
        $script .= $this->addValidateMethod();
        $script .= $this->addGetValidationFailuresMethod();

        return $script;
    }
949596
protected function performStep()
    {
        $relations = [];

        foreach ($this->reflection()->getMethods() as $method) {

            if (    ! $this->isPotentialRelationMethod($method)
                ||  ! $this->isReflectionMethodEloquentRelation($method)
            ) {
                continue;
            }

            // It's a relationship method; get information from method
            try {
                $relation = $this->model()->{$method->name}();

            } catch (Exception $e) {
                // If an exception occurs, ignore it and ignore the method
                continue;
            }

            if ( ! ($relation instanceof Relation)) {
                continue;
            }

            $type        = camel_case(class_basename($relation));
            $morphModels = [];

            // Determine if the foreign key for this relation is nullable.
            // For now, this only concerns belongsTo relations.
            $nullableKey = false;
            $foreignKeys = [];

            if ($type == RelationType::BELONGS_TO || $type == RelationType::BELONGS_TO_THROUGH) {
                /** @var $relation Relations\BelongsTo */
                $foreignKeys = [ $relation->getForeignKeyName() ];
                $nullableKey = $this->isNullableKey($relation->getForeignKeyName());

            } elseif ($type == RelationType::MORPH_TO) {
                /** @var Relations\MorphTo $relation */
                $foreignKeys = [$relation->getForeignKeyName(), $relation->getMorphType()];
                $nullableKey = $this->isNullableKey($relation->getForeignKeyName());

                $morphModels = $this->getMorphedModelsFromMorphToReflectionMethod($method);

            } elseif ($type == RelationType::HAS_ONE || $type == RelationType::HAS_MANY) {
                /** @var $relation Relations\HasMany */
                $foreignKeys = [ $relation->getQualifiedForeignKeyName() ];

            } elseif ($type == RelationType::BELONGS_TO_MANY) {
                /** @var Relations\BelongsToMany $relation */
                $foreignKeys = [
                    $relation->getQualifiedForeignPivotKeyName(),
                    $relation->getQualifiedRelatedPivotKeyName(),
                ];

            } elseif ($type == RelationType::MORPH_TO_MANY) {
                /** @var Relations\MorphToMany $relation */
                $foreignKeys = [
                    $relation->getQualifiedForeignPivotKeyName(),
                    $relation->getMorphType(),
                    $relation->getQualifiedRelatedPivotKeyName(),
                ];

                // The relation is inverse if the MorphClass is not this model
                if (get_class($this->model()) !== $relation->getMorphClass()) {
                    $type = RelationType::MORPHED_BY_MANY;
                }
            }

            $relations[ $method->name ] = new ModelRelationData([
                'name'          => $method->name,
                'method'        => $method->name,
                'type'          => $type,
                'relationClass' => get_class($relation),
                'relatedModel'  => get_class($relation->getRelated()),
                'foreign_keys'  => $foreignKeys,
                'nullable_key'  => $nullableKey,
                'morphModels'   => $morphModels,
            ]);
        }

        $this->info['relations'] = $relations;
    }
1298084
public function behaviors()
    {
        $behaviors = ArrayHelper::merge(parent::behaviors(), [
            'params-access' => [
                'class' => ParamsAccessBehaviour::className(),
                'defaultRole' => 'roleRoot',
                'readonlyParams' => [
                    'behaviors', // parameters which nobody can edit, will overwrite another rules
                ],
            ],
        ]);
        if (isset($this->params['behaviors'])) {
            $behaviors = ArrayHelper::merge($behaviors, $this->params['behaviors']);
        }
        return $behaviors;
    }
725089
public function getTraits()
    {
        if (!isset($this->traits)) {
            $traitAdaptations = [];
            $this->traits     = ReflectionClass::collectTraitsFromClassNode($this->classLikeNode, $traitAdaptations);
            $this->traitAdaptations = $traitAdaptations;
        }

        return $this->traits;
    }
871085
public function setAllAttributes()
    {
        $methods            = get_class_methods($this);
        $attributeMethods   = array();

        // Get all attribute related getters
        foreach ($methods as $method) {
            if (strpos($method, 'getAttribute') !== false && $method !== 'getAttributes') {
                $attributeMethods[] = $method;
            }
        }

        // Call all attribute related getters
        foreach ($attributeMethods as $attributeMethod) {
            $name   = strtolower(str_replace('getAttribute', '', $attributeMethod));
            $value  = $this->$attributeMethod();

            $this->_setAttributeProperty($name, $value);
        }

        return $this;
    }
101690
public function actionAdd() {

		$model				= new Post();
		$model->siteId		= Yii::$app->core->siteId;
		$model->comments	= false;

		$content			= new ModelContent();

		if( $model->load( Yii::$app->request->post(), $model->getClassName() ) && $model->validate() && $content->load(Yii::$app->request->post(),'ModelContent' ) && $content->getClassName() ) {

			$model->status	= Post::STATUS_BASIC;

			$this->modelService->register( $model, [ 'publish' => $model->isActive(), 'content' => $content ] );

			return $this->checkRefresh( $model );
		}

		$visibilityMap	= Post::$visibilityMap;

		return $this->render( 'reg/basic', [
			'model' => $model, 'content' => $content,
			'visibilityMap' => $visibilityMap
		]);
	}
530977
protected function generateMethodsLines()
    {
        $code = array();
        foreach ($this->methods as $method) {
            $method->setIndentationString($this->getIndentationString());
            $method->setIndentationLevel($this->getIndentationLevel() + 1);
            $code[] = $method->generate();
            $code[] = null;
        }

        return $code;
    }
1074654
private function buildValidation() {
        $validation = new Object\Index($this->getConfiguration());
        $validation->setNamespace(
            $this->getConfiguration()->getRootNamespace()
            . '\Services\Behavior\\' . $this->getConfiguration()->getModelSubNamespace()
            . '\Generated'
        );
        $validation->setName($this->getAbstractClass()->getName());
        $validation->setAbstract(true);
        $validation->setExtends('BehaviorBase');
        $validation->addUse(str_replace('\Generated', '', $this->getAbstractClass()->getNamespace()) . '\\' . $this->getAbstractClass()->getName() . ' as Model');
        $validation->addUse('Phalcon\Mvc\Model\Message');
        $validation->addUse('Bullhorn\FastRest\Api\Services\Behavior\BehaviorBase');


        $method = new Object\Method();
        $method->setAccess('public');
        $method->setName('getEntity');
        $method->setReturnType('Model');
        $method->setContent('return parent::getEntity();');
        $validation->addMethod($method);


        //Before Delete Method
        $content = '';
        foreach($this->getRelationships() as $relationship) {
            if($relationship->isPlural() && !$relationship->isNullable() && $relationship->getAction() != 'ACTION_CASCADE') {
                $content .= 'parent::beforeDelete();
        if($this->isUnitTestingChildren()) {
            return;
        }
        $entity = $this->getEntity();
        if ($entity->count' . ucfirst($relationship->getAlias()) . '()>0) {
			$entity->appendMessage(new Message(\'Multiple ' . ucfirst($relationship->getAlias()) . ' found\'));
		}';
            }
        }
        $method = new Object\Method();
        $method->setAccess('protected');
        $method->setDescription('Validates if the entity can be deleted');
        $method->setReturnType('void');
        $method->setName('beforeDelete');
        $method->setContent($content);
        $validation->addMethod($method);
        //End Before Delete Method


        //Validation Method
        $content = 'parent::validation();
        if($this->isUnitTestingChildren()) {
            return;
        }
        $entity = $this->getEntity();
        //Check to see if it is automatically updated
		$automaticAttributes = $entity->getModelsMetaData()->getAutomaticCreateAttributes($entity);
		$columnMap = $entity->getModelsMetaData()->getColumnMap($entity);
		$automaticFields = array_fill_keys($entity->getAutomaticallyUpdatedFields(), null);
		foreach($automaticAttributes as $fullName=>$null) {
			$automaticFields[$columnMap[$fullName]] = null;
		}
';
        foreach($this->getFields() as $field) {
            if(!is_null($field->getEnumOptions())) {
                $validation->addUse('Phalcon\Mvc\Model\Validator\Inclusionin as ValidateEnum');
                $subMethod = new Object\Method();
                $subMethod->setAccess('private');
                $subMethod->setDescription('Validates ' . $field->getShortName() . ' is in the enum list');
                $subMethod->setReturnType('void');
                $subMethod->setName('validate' . ucfirst($field->getShortName()) . 'Enum');
                $subMethod->setContent(
                    '$this->validate(
			new ValidateEnum(
				array(
					\'field\' => \'' . $field->getShortName() . '\',
					\'domain\' => [\'' . implode('\',\'', $field->getEnumOptions()) . '\']
				)
			)
		);'
                );
                $validation->addMethod($subMethod);
                $content .= '		$this->validate' . ucfirst($field->getShortName()) . 'Enum();
';
            }
            if(!$field->isNullable()) {
                $subMethod = new Object\Method();
                $subMethod->setAccess('private');
                $subMethod->setDescription('Validates ' . $field->getShortName() . ' is not null');
                $subMethod->setReturnType('void');
                $subMethod->setName('validate' . ucfirst($field->getShortName()) . 'NotNull');
                $parameter = new Object\Parameter();
                $parameter->setName('entity');
                $parameter->setType('Model');
                $parameter->setStrictType(true);
                $subMethod->addParameter($parameter);
                $parameter = new Object\Parameter();
                $parameter->setName('automaticFields');
                $parameter->setType('array');
                $parameter->setStrictType(true);
                $subMethod->addParameter($parameter);
                $subMethod->setContent(
                    'if(!array_key_exists(\'' . $field->getShortName() . '\', $automaticFields) && is_null($entity->readAttribute(\'' . $field->getShortName() . '\'))) {
			$entity->appendMessage(new Message(\'Null Error with the field: ' . $field->getShortname() . ', Expected Type: ' . $field->getType() . '\'));
		}'
                );
                $validation->addMethod($subMethod);
                $content .= '		$this->validate' . ucfirst($field->getShortName()) . 'NotNull($entity, $automaticFields);
';
            }
        }

        foreach($this->getIndexes() as $index) {
            if($index->isUnique() && !$index->isPrimary()) {
                $validation->addUse('Bullhorn\FastRest\Api\Services\Validator\Unique as ValidateUnique');
                $fields = array();
                foreach($index->getColumns() as $column) {
                    $fields[] = $this->getField($column)->getShortName();
                }
                $name = 'validate';
                foreach($fields as $field) {
                    $name .= ucfirst($field);
                }
                $name .= 'Unique';
                $subMethod = new Object\Method();
                $subMethod->setAccess('private');
                $subMethod->setDescription('Validates this combination of ' . implode(', ', $fields) . ' is unique in the database');
                $subMethod->setReturnType('void');
                $subMethod->setName($name);
                $subMethod->setContent(
                    '$this->validate(
			$validation = new ValidateUnique(
				[
					\'fields\'  => [\'' . implode('\',\'', $fields) . '\'],
					\'message\' => \'A unique constraint failed on: ' . implode(',', $fields) . '\'
				]
			)
		);'
                );
                $validation->addMethod($subMethod);
                $content .= '		$this->' . $name . '();
';
            }
        }

        foreach($this->getRelationships() as $relationship) {
            $field = $this->getField($relationship->getLocalColumn());
            if(!$relationship->isPlural()) {
                //Ex: Not Required relationship, make sure if the value isn't null, it is valid
                $subMethod = new Object\Method();
                $subMethod->setAccess('private');
                $subMethod->setDescription('Validates the ' . ucfirst($relationship->getAlias()) . ' Relationship');
                $subMethod->setReturnType('void');
                $subMethod->setName('validate' . ucfirst($relationship->getAlias()) . 'Relationship');
                $parameter = new Object\Parameter();
                $parameter->setName('entity');
                $parameter->setType('Model');
                $parameter->setStrictType(true);
                $subMethod->addParameter($parameter);
                $subMethod->setContent(
                    'if ($entity->get' . ucfirst($relationship->getAlias()) . '()===false '
                    . ($field->isNullable() ? '&& !is_null($entity->get' . ucfirst($field->getShortName()) . '())' : '') . ') {
			$entity->appendMessage(new Message(\'No ' . ucfirst($relationship->getAlias()) . ' found with the id \'.$entity->get' . ucfirst($field->getShortName()) . '()));
		}'
                );
                $validation->addMethod($subMethod);
                $content .= '		$this->validate' . ucfirst($relationship->getAlias()) . 'Relationship($entity);
';
            }
        }
        $method = new Object\Method();
        $method->setAccess('protected');
        $method->setDescription('Validates if the entity can be updated or inserted');
        $method->setReturnType('void');
        $method->setName('validation');
        $method->setContent($content);
        $validation->addMethod($method);
        //End Validation Method

        $this->setValidationClass($validation);

        $childValidation = new Object\Index($this->getConfiguration());
        $childValidation->setNamespace(
            $this->getConfiguration()->getRootNamespace()
            . '\Services\Behavior\\' . $this->getConfiguration()->getModelSubNamespace()
        );
        $childValidation->setName($this->getAbstractClass()->getName());
        $childValidation->setExtends('Generated\\' . $this->getAbstractClass()->getName());
        $childValidation->addUse(str_replace('\Generated', '', $this->getAbstractClass()->getNamespace()) . '\\' . $this->getAbstractClass()->getName() . ' as Model');

        $this->setValidationChildClass($childValidation);
        $this->getAbstractClass()->addUse($childValidation->getNamespace() . '\\' . $childValidation->getName() . ' as ModelValidator');
        return '		$this->addBehavior(new ModelValidator());' . "\n";
    }
254795
protected function buildMethodMaps()
    {

        $getterMap = [];
        $setterMap = [];

        $methods = (new ReflectionObject($this))->getMethods(ReflectionMethod::IS_PUBLIC);

        foreach ($methods as $method) {

            if ($this->isGetter($method)) {
                $getterMap[$this->toPropertyName($method->getName())] = $method->getName();
                continue;
            }

            if ($this->isSetter($method)) {
                $setterMap[$this->toPropertyName($method->getName())] = $method->getName();
                continue;
            }


        }

        return [$getterMap, $setterMap];
    }
788848
public function getClassMethods()
    {
        if (empty($this->_methods)) {
            $methods = $this->_getReflection()->getMethods();
            foreach ($methods as $method) {
                $this->_methods[] = $method->getName();
            }
        }
        return $this->_methods;
    }
1329690
public function attachBehavior($name, $behavior)
    {
        $this->_behaviors[$name] = $name;
        unset(self::$_names[get_class($this)]);

        return parent::attachBehavior($name, $behavior);
    }
16020
public static function getAppliedFilters()
    {
        $classMethods = get_class_methods(get_class());
        $calledClassMethods = get_class_methods(get_called_class());

        $filteredMethods = array_filter(
            $calledClassMethods, function ($calledClassMethod) use ($classMethods) {
                return !in_array($calledClassMethod, $classMethods, true);
            }
        );

        return \Illuminate\Support\Facades\Request::only($filteredMethods);
    }
1045806
def _init_and_add_behavior(behavior_hash)
      obj = _load_asset(ASSET_TYPE_BEHAVIOR, behavior_hash[:name])
      unless obj.nil?
        obj.parameters = behavior_hash[:parameters]
        @behavior_objects << obj
      end
    end
953790
private function method(): string
    {
        return isset($this->bt['class'])
            ? sprintf('%s::%s()', $this->bt['class'], $this->bt['function'])
            : $this->bt['function'];
    }
906634
public function getNextTableBehavior()
    {
        // order the behaviors according to Behavior::$tableModificationOrder
        $behaviors = array();
        foreach ($this->getTables() as $table) {
            foreach ($table->getBehaviors() as $behavior) {
                if (!$behavior->isTableModified()) {
                    $behaviors[$behavior->getTableModificationOrder()][] = $behavior;
                }
            }
        }
        ksort($behaviors);
        foreach ($behaviors as $behaviorList) {
            foreach ($behaviorList as $behavior) {
                return $behavior;
            }
        }
    }
925415
private function appendBehaviorNode(Behavior $behavior, \DOMNode $parentNode)
    {
        $behaviorNode = $parentNode->appendChild($this->document->createElement('behavior'));
        $behaviorNode->setAttribute('name', $behavior->getName());

        if ($behavior->allowMultiple()) {
            $behaviorNode->setAttribute('id', $behavior->getId());
        }

        foreach ($behavior->getParameters() as $name => $value) {
            $parameterNode = $behaviorNode->appendChild($this->document->createElement('parameter'));
            $parameterNode->setAttribute('name', $name);
            $parameterNode->setAttribute('value', $value);
        }
    }
314610
public function getEarlyBehaviors()
    {
        $behaviors = array();
        foreach ($this->behaviors as $name => $behavior) {
            if ($behavior->isEarly()) {
                $behaviors[$name] = $behavior;
            }
        }

        return $behaviors;
    }