Create proper argument value

@param mixed $object
@param array $arguments

@throws ServiceManagerException

@return mixed|object
8208
private function createValue($object, $arguments = [])
    {

        if ($this->isInstanceOf($arguments, ConfigObject::class)) {
            $arguments = $arguments->toArray();
        }

        if (!$this->isArray($arguments)) {
            throw new ServiceManagerException(ServiceManagerException::INVALID_SERVICE_ARGUMENTS_TYPE, [$object]);
        }

        if (!$this->isString($object)) {
            return $object;
        }

        $object = $this->str($object);

        if ($object->startsWith('@')) {
            return ServiceManager::getInstance()->getService($object->trimLeft('@')->val());
        } else {
            $value = $object->val();
            if (class_exists($value)) {
                $reflection = new \ReflectionClass($value);

                return $reflection->newInstanceArgs($arguments);
            }

            return $value;
        }
    }
849171
protected function prepareArguments(/*# string */ $id, array $arguments)
    {
        $args  = isset($arguments[1]) ? (array) $arguments[1] : [];
        $scope = isset($arguments[2]) ? (string) $arguments[2] :
            $this->getScope($id);

        // scope === '@serviceId@' ?
        if (isset($this->circular[$scope])) {
            $scope .= '#' . $this->circular[$scope];
        }

        return [ $args, $scope, $scope . '::' . $id ];
    }
101161
public static function reset($object)
	{
		if (!($object instanceof FieldDescriptorProto)) {
			throw new \InvalidArgumentException('You have to pass object of class Google\Protobuf\FieldDescriptorProto.');
		}
		$object->name = NULL;
		$object->number = NULL;
		$object->label = NULL;
		$object->type = NULL;
		$object->typeName = NULL;
		$object->extendee = NULL;
		$object->defaultValue = NULL;
		$object->oneofIndex = NULL;
		$object->jsonName = NULL;
		$object->options = NULL;
	}
167234
public function create($object)
    {
        $db = new DatabaseManager();
        $connection = $db->getDbh();

        $objectAsArrayForSqlInsert = DatatbaseUtility::objectToArrayLessId($object);
        $fields = array_keys($objectAsArrayForSqlInsert);
        $insertFieldList = DatatbaseUtility::fieldListToInsertString($fields);
        $valuesFieldList = DatatbaseUtility::fieldListToValuesString($fields);

        $sql = 'INSERT into :table :insertFieldList :valuesFieldList';
        $sql = str_replace(':table', $this->tableName, $sql);
        $sql = str_replace(':insertFieldList', $insertFieldList, $sql);
        $sql = str_replace(':valuesFieldList', $valuesFieldList, $sql);

        $statement = $connection->prepare($sql);
        $statement->execute($objectAsArrayForSqlInsert);

        $queryWasSuccessful = ($statement->rowCount() > 0);
        if($queryWasSuccessful) {
            return $connection->lastInsertId();
        } else {
            return -1;
        }
    }
1263521
public static function call($object, string $method, array $parameters)
    {
        $reflectionClass = new \ReflectionClass($object);
        $reflectionMethod = $reflectionClass->getMethod($method);
        $arguments = [];

        foreach ($reflectionMethod->getParameters() as $i => $reflectionParameter) {
            $argument = null;

            if (array_key_exists($reflectionParameter->name, $parameters) || array_key_exists($i, $parameters)) {
                $argument = $parameters[$reflectionParameter->name] ?? $parameters[$i] ?? null;
            } elseif ($reflectionParameter->isDefaultValueAvailable()) {
                $argument = $reflectionParameter->getDefaultValue();
            }

            if ($reflectionType = $reflectionParameter->getType()) {
                if ($reflectionType->isBuiltin()) {
                    if ($argument !== null || !$reflectionType->allowsNull()) {
                        settype($argument, $reflectionType->getName());
                    }
                } elseif ($argument === null && !$reflectionType->allowsNull()) {
                    return null;
                }
            }

            $arguments[] = $argument;
        }

        if ($reflectionMethod->isConstructor()) {
            return $reflectionClass->newInstanceArgs($arguments);
        }

        $reflectionMethod->setAccessible(true);

        return $reflectionMethod->invokeArgs($reflectionMethod->isStatic() ? null : $object, $arguments);
    }
777804
public static function instance($object)
    {
        if (!is_object($object)) {
            throw new \InvalidArgumentException('Only objects are allowed to be passed to the helper.');
        }

        $response = new self();
        $response->origin = $object;
        $response->target = new ReflectionClass($object);
        return $response;
    }
558074
public static function createObject(array $fields) {
        $service = Manager::createObject($fields);
        if (!($service instanceof Base)) {
            throw new InvalidArgumentException(
                sprintf(
                    'Error creating delivery service object.'
                )
            );
        }

        return $service;
    }
95015
protected function processArguments($arguments) {
		$processedArgs = [];
		
		foreach ($arguments as $key => $argument) {
			if (! isset($argument->type)) {
				throw new Exceptions\InvalidConfig('Argument definition must contain a "type" property"');
			}
			
			$type = strtolower(trim($argument->type));
			
			if ($type === 'value') {
				$processedArgs[$key] = $this->processArgumentValue($argument);
				continue;
			}
			
			if ($type === 'service') {
				$processedArgs[$key] = $this->processArgumentService($argument);
				continue;
			}
			
			if ($type === 'parameter') {
				$processedArgs[$key] = $this->processArgumentParameter($argument);
				continue;
			}
			
			throw new Exceptions\InvalidConfig('Unknown type of argument: "' . $type . '"');
		}
		
		return $processedArgs;
	}
18726
public static function createFromObject($object)
    {
        $isFromBase = (static::class === self::class);

        if (!is_object($object)) {
            throw new \Exception('Expecting an object');
        }

        //Test type if it's set
        if (property_exists($object, 'type') && !empty($object->type)) {
            if (array_key_exists($object->type, self::$validatorRegistry)) {
                if (is_object($object->type) || is_array($object->type) || $object->type === null) {
                    throw new \Exception('Expecting string for type');
                }
                $className = self::$validatorRegistry[$object->type];
                $validator = new $className();
            /*} elseif (class_exists(__NAMESPACE__ . '\\' . $object->type)) {
                //if already loaded
                $className = __NAMESPACE__ . '\\' . $object->type;
                $validator = new $className();
            } elseif (class_exists(__NAMESPACE__ . '\\' . $object->type . 'Validator')) {
                //if already loaded
                $className = __NAMESPACE__ . '\\' . $object->type . 'Validator';
                $validator = new $className();*/
            } else {
                $className = $object->type . 'Validator';

                try {
                    //prevent fatal error
                    new \ReflectionClass($className);
                    //attempt to create class
                    $validator = new $className();
                } catch (\Exception $e) {
                    //Wont catch the fatal error
                    throw new \Exception(sprintf(
                        'Incorrect type "%s" from "%s"',
                        $object->type,
                        static::class
                    ));
                }
            }
        } elseif (($validator = static::createFromObjectForAdditional($object)) !== null) {
            return $validator;
        } elseif (!$isFromBase
            || (isset($object->type) && !empty($object->type) && $object->type == static::$type)
        ) {
            $validator = new static();
        } else {
            throw new \Exception(sprintf(
                'Type is required when creating from "%s"',
                self::class
            ));
        }

        //For each Validator's attribute
        foreach (array_merge(
            $validator::getTypeAttributes(),
            $validator::$commonAttributes
        ) as $attribute) {
            //Check if provided object contains this attribute
            if (property_exists($object, $attribute)) {
                if ($attribute == 'properties') {
                    //get properties as array
                    $properties = $object->{$attribute};

                    $createdProperties = new \stdClass();

                    foreach ($properties as $key => $property) {
                        //TODO remove
                        //if (!is_object($property)) {
                        //    throw new \Exception(sprintf(
                        //        'Expected object for property value "%s"',
                        //        $key
                        //    ));
                        //}

                        $createdProperties->{$key} =
                        BaseValidator::createFromObject($property);
                    }
                    //push to class
                    $validator->{$attribute} = $createdProperties;
                } elseif ($attribute == 'items' || $attribute == 'not') {
                    $validator->{$attribute} = BaseValidator::createFromObject(
                        $object->{$attribute}
                    );
                } else {
                    //Use attributes value in Validator object
                    $validator->{$attribute} = $object->{$attribute};
                }
            }
        }

        return $validator;
    }
735016
public static function createObject( $className, $arguments = array() )
	{
		if( !class_exists( $className ) )
			throw new RuntimeException( 'Class "'.$className.'" has not been loaded' );
		$class	= new ReflectionClass( $className );
		if( $arguments )
			$object	= $class->newInstanceArgs( $arguments );
		else
			$object	= $class->newInstance();
		return $object;
	}
921028
public function preparePersistChangeSet($object) : array
    {
        if (! $object instanceof PersistableInterface) {
            throw new InvalidArgumentException(
                sprintf('%s must implement PersistableInterface.', get_class($object))
            );
        }

        return $object->preparePersistChangeSet();
    }
505138
public function object($object, array $rules, string $group = null, array $messages = [], $default = null): self
    {
        if (!is_object($object)) {
            throw new InvalidArgumentException('The first argument should be an object');
        }

        foreach ($rules as $property => $options) {
            $this->validateInput(
                $this->getPropertyValue($object, $property, $default),
                new Configuration($options, $property, $group, $default),
                $messages
            );
        }

        return $this;
    }
1055608
private function doCreateProxy($object)
    {
        $proxy = $this->factory->createProxy($object);
        /* $this in closures does not work with PHP 5.3
         * so we have to pass the object explicitely
         * with its private properties */
        $_this = $this;
        $securityContext = $this->services['security.context'];

        foreach($this->protected_classes[ClassUtils::getRealClass($object)]['methods'] as $method => $options) {
            $attribute = isset($options['attribute']) ? $options['attribute'] : false;
            $expression = isset($options['expression']) ? $options['expression'] : false;
            $returnProxy = isset($options['return_proxy']) ? $options['return_proxy'] : false;
            $denyValue = isset($options['deny_value']) ? $options['deny_value'] : null;

            if($attribute != false && $expression != false) {
                $proxy->setMethodPrefixInterceptor($method,
                    function($proxy, $instance, $methodName, $params, & $returnEarly) use ($expression, $attribute, $denyValue, $securityContext)
                    {
                        if (!($securityContext->isGranted(new Expression($expression), $instance) && $securityContext->isGranted($attribute, $instance)))  {
                            $returnEarly = true;
                            return $denyValue;
                        } else {
                            $returnEarly = false;
                            return;
                        }
                    }
                );
                continue;
            }

            if($attribute != false) {
                $proxy->setMethodPrefixInterceptor($method,
                    function($proxy, $instance, $methodName, $params, & $returnEarly) use ($attribute, $denyValue, $securityContext)
                    {
                        if (!$securityContext->isGranted($attribute, $instance)) {
                            $returnEarly = true;
                            return $denyValue;
                        } else {
                            $returnEarly = false;
                            return;
                        }
                    }
                );
                continue;
            }

            if($expression != false) {
                $proxy->setMethodPrefixInterceptor($method,
                    function($proxy, $instance, $methodName, $params, & $returnEarly) use ($expression, $denyValue, $securityContext)
                    {
                        if (!$securityContext->isGranted(new Expression($expression), $instance)) {
                            $returnEarly = true;
                            return $denyValue;
                        } else {
                            $returnEarly = false;
                            return;
                        }
                    }
                );
            }

            if($returnProxy) {
                $proxy->setMethodSuffixInterceptor($method,
                    function ($proxy, $instance, $methodName, $params, $returnValue, & $returnEarly) use ($_this)
                    {
                        if(is_object($returnValue) && $returnValue === $proxy) {
                            $returnEarly = false;
                            return;
                        } else if ($_this->isProtected($returnValue)) {
                            $returnEarly = true;
                            return $_this->getProxy($returnValue);
                        } else if (is_array($returnValue)
                            || $returnValue instanceof \Traversable
                            || $returnValue instanceof \ArrayAccess
                        ) {
                            $return = array();
                            foreach($returnValue as $element) {
                                if($_this->isProtected($element)) {
                                    $return[] = $_this->getProxy($element);
                                } else {
                                    $return[] = $element;
                                }
                            }
                            $returnEarly = true;
                            return $return;
                        }
                    }
                );
            }
        } // end foreach

        return $proxy;
    }
312630
public function translate($object)
    {
        $commandBaseNamespace = app()->getNamespace() . "Commands";
        $handlerBaseNamespace = app()->getNamespace(). "Handlers";

        $reflectionObject = new ReflectionClass($object);

        $commandNamespace = $this->getCommandNamespace($commandBaseNamespace, $reflectionObject);
        $command = $this->getCommandName($reflectionObject);

        $handler = str_replace('Command', 'CommandHandler', $command);


        if($commandNamespace !== $commandBaseNamespace) {
            $handlerNamespace = $handlerBaseNamespace . $commandNamespace . "\\" . $handler;

            $commandNamespace = $commandBaseNamespace .  $commandNamespace . "\\" . $command;
        }


        if(! class_exists($commandNamespace)) {
            throw new CommandNotFoundException("Command [ $command ] does not exist.");
        }

        if(! class_exists($handlerNamespace)) {
            throw new HandlerNotFoundException("Handler [ $handler ] does nto exist.");
        }

        return $handlerNamespace;
    }
974732
public function assign($obj, ...$args)
    {
        if(is_object($obj)){
            foreach($args as &$source){
                if (!isset($source)) continue;

                if ( !is_object($source) ) {
                    throw new \Exception($source . 'must be object');
                }
                foreach($source as $key=>&$val){
                    $obj->{$key} = $source->{$key};
                }
            }
        }else{
            throw new \Exception("Utlis::assign() parameter 1 by not object");
        }

        return $obj;
    }
79150
public function createArray($object)
    {
        if (!is_object($object)) {
            throw new \InvalidArgumentException('The first param should be a object.');
        }

        $array = [];
        if ($object instanceof Object2ArrayInterface) {
            $array = $object->__toArray();
            array_walk_recursive(
                $array,
                function (&$item) {
                    if (is_object($item)) {
                        $item = $this->createArray($item);
                    }
                }
            );
        } else {
            foreach (Utils::getClassProperties(get_class($object)) as $property) {
                if ($this->context->getReader()->isReadable($object, $property->getName())) {
                    $value = $this->context->getReader()->getValue($object, $property->getName());
                    $types = $types = Utils::getPropertyTypes($property);
                    $value = $this->parseValue($value, $types, $property, $object);

                    if ($value === null && $this->context->isIgnoreNulls()) {
                        continue;
                    }

                    $transformedName = $this->context->getNamingStrategy()->transformName($property->getName());
                    $array[$transformedName] = $value;
                }
            }
        }

        return $array;
    }
238077
public function create($class, array $arguments = [])
    {
        $instanceType = $this->getInstanceType($class);
        $instanceArguments = $this->getInstanceArguments($class, $arguments);
        $reflection = new \ReflectionClass($instanceType);
        $constructor = $reflection->getConstructor();

        if (null === $constructor) {
            $instance = new $instanceType();
        } else {
            $args = $this->resolveArguments($constructor, $instanceArguments);
            $instance = $reflection->newInstanceArgs($args);
        }

        return $instance;
    }