Init state by request or passed in override values.

@author Benjamin Carl <opensource@clickalicious.de>

@return $this Instance for chaining
512778
public function init()
    {
        // Status
        $processed = false;

        // Receive information from: Store, Request and process it to a valid state representation

        // We can do the following without any side effects ...
        //   a) Load data pool from session - fall back to default one for first call
        //   b) Generate a fresh token used at least for next/first render()
        //   c) Detect if the form was in any kind submitted to here - maybe through a satellite form entry

        $this
            ->initializeDataPool()
            ->submitted($this->isASubmittedFormInRequest())
            ->jumped($this->receiveJumpFieldValueFromRequest());

        // We can now check for submitted data which can either control the flow (e.g. JUMP) or required to correctly bootstrap the form
        if (true === $this->wasSubmitted()) {

            // Collect data from request cause we have one!
            $step   = (int) $this->receiveStepFieldValueFromRequest();
            $steps  = (int) $this->receiveStepsFieldValueFromRequest();
            $token  = $this->receiveTokenFieldValueFromRequest();
            $upload = (int) $this->receiveUploadFieldValueFromRequest();
            $valid  = true;

            // When submitted we must have also this information! So we can use to check this as well
            $stepFromDataPool  = (int) $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_STEP);
            $stepsFromDataPool = (int) $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_STEPS);
            $lastValidStep     = (int) $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_LASTVALIDSTEP);

            // Adjust by following rule:
            // On a switch from one step to the next we need to adjust the step
            $step  = ($stepFromDataPool > $step)   ? $stepFromDataPool  : $step;
            $steps = ($stepsFromDataPool > $steps) ? $stepsFromDataPool : $steps;

            // If validation now fails for basic manipulation protection fallback to default
            if (
                $step                        <=  0                    ||    // ~ e.g. no valid step found
                $steps                       <=  0                    ||    // ~ e.g. no valid steps limit/end found
                null                         === $token               ||    // ~ e.g. no token submitted
                $step                        >   $steps               ||    // ~ e.g. stepped over goal
                ($lastValidStep              === 0      && $step > 1) ||    // ~ e.g. If no last valid step but where in a step > 1
                (abs($lastValidStep - $step) !=  1      && $step > 1)       // ~ e.g. More than 1 step diff is only allowed for jump
            ) {
                $valid = false;
            }

            if (true === $valid) {
                // Store the detected values for further processing
                $this->setStep($step);
                $this->setSteps($steps);
                $this->setToken($token);
                $this->setUpload($upload);

                // Check for form has file upload (in general not on current request limited) - and getMetaComponents it ...
                if (true === $this->hasFileUpload()) {
                    // ... getMetaComponents in this context is to ensure that we can't
                    $fileUploadHandler = $this->getFileUploadHandler();

                    // Retrieve files for this step (either from pool or fresh uploaded)
                    $files = $fileUploadHandler->getUploadedFiles(
                        $step,
                        $this->getDataPool(),
                        $this->getRequest()->getUploadedFiles()
                    );
                } else {
                    $files = [];
                }

                // Store files ...
                $this->setFiles($files);

                // Extract components for validation in this steps
                $validationRules = $this->getDataPool()[Doozr_Form_Service_Constant::IDENTIFIER_COMPONENTS][$step];

                // Manually inject validation for method
                $validationRules[Doozr_Form_Service_Constant::PREFIX.Doozr_Form_Service_Constant::IDENTIFIER_METHOD] = [
                    'validation' => ['value' => [$this->getDataPool()[Doozr_Form_Service_Constant::IDENTIFIER_METHOD]]],
                    'type'       => Doozr_Form_Service_Constant::COMPONENT_TYPE_GENERIC,
                ];

                $submittedValues = $this->buildValueArray(array_keys($validationRules));

                $submittedValues[Doozr_Form_Service_Constant::PREFIX.Doozr_Form_Service_Constant::IDENTIFIER_METHOD] = $this->getRequest()->getMethod();

                // Manually inject validation for token
                $validationRules[Doozr_Form_Service_Constant::PREFIX.Doozr_Form_Service_Constant::IDENTIFIER_TOKEN] = [
                    'validation' => ['value' => [$this->getDataPool()[Doozr_Form_Service_Constant::IDENTIFIER_TOKEN]]],
                    'type'       => Doozr_Form_Service_Constant::COMPONENT_TYPE_GENERIC,
                ];

                $submittedValues[Doozr_Form_Service_Constant::PREFIX.Doozr_Form_Service_Constant::IDENTIFIER_TOKEN] = $this->getToken();

                // Run validation by using validation handler ...
                $this->setValid(
                    $this->getValidationHandler()->validate(
                        $submittedValues,
                        $validationRules
                    )
                );

                /**
                 * Required to handle
                 *
                 * Token-Behavior -> comes from history
                 * $invalidTokenBehavior = $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_TOKENBEHAVIOR)
                 *
                 */
                $invalidTokenBehavior = $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_TOKENBEHAVIOR);
                $tokenValid           = $this->getError(
                    Doozr_Form_Service_Constant::PREFIX.Doozr_Form_Service_Constant::IDENTIFIER_TOKEN,
                    true
                );

                // Handle outsourced to token handler
                $this->getTokenHandler()->handleToken(
                    $invalidTokenBehavior,
                    $tokenValid
                );

                // Transfer valid data ...
                $this->transferValidDataAndFilesToPool($step);

                // If valid we must increase active step to the next one :)
                if (true === $this->isValid()) {
                    // We only accept completion of forms on a submit. This is a condition which prevent us from
                    // running into raise conditions with jumped forms which are valid ... and it makes the rule easy:
                    $this->setComplete($step === $steps);

                    if (true === $this->isComplete()) {
                        $data = $this->getDataHandler()->enrichWithMetaInformation($this->getDataPool());
                        $this->invalidateDataPool();
                        $this->setResult($data);
                    }

                    $this->setActiveStep($step + 1);
                } else {
                    $this->setActiveStep($step);
                }

                $processed = true;
            }

            // We can also check if form was not submitted - maybe it was jumped to this place!!!
            // The we must! have a valid data pool entry for each single element and restore the values from there to emulate a valid request
        } elseif (true === $this->wasJumped()) {

            // Collect data from store ...
            $step   = (int) $this->getDataPoolDataValue($this->getJumped(), $this->getFieldnameStep());
            $steps  = (int) $this->getDataPoolDataValue($this->getJumped(), $this->getFieldnameSteps());
            $token  = $this->getDataPoolDataValue($this->getJumped(), $this->getFieldnameToken());
            $data   = $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_DATA);
            $upload = (int) $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_UPLOAD);
            $valid  = true;
            $jumped = $this->getJumped();

            $lastValidStep = (int) $this->getDataPoolValue(Doozr_Form_Service_Constant::IDENTIFIER_LASTVALIDSTEP);

            // If validation now fails for basic manipulation protection fallback to default
            if (
                $step                        <=  0                    ||    // ~ e.g. no valid step found
                $steps                       <=  0                    ||    // ~ e.g. no valid steps limit/end found
                null                         === $token               ||    // ~ e.g. no token ever stored
                $step                        >   $steps               ||    // ~ e.g. stepped over goal
                ($lastValidStep              === 0      && $step > 1) ||    // ~ e.g. If no last valid step but where in a step > 1
                (abs($lastValidStep - $step) !=  1      && $step > 1)       // ~ e.g. More than 1 step diff is only allowed for jump
            ) {
                $valid = false;
            }

            if (
                (null !== $lastValidStep && 0 !== $lastValidStep) &&
                (abs($jumped - $lastValidStep) <= 1)
            ) {
                $valid = true;
                $step  = $jumped;
                $steps = (int) $this->getDataPoolDataValue($lastValidStep, $this->getFieldnameSteps());
                $token = $this->getDataPoolDataValue($lastValidStep, $this->getFieldnameToken());
            }

            //
            if (true === $valid) {
                // Store the detected values for further processing
                $this->setStep($step);
                $this->setSteps($steps);
                $this->setToken($token);
                $this->setUpload($upload);

                // Check for form has file upload (in general not on current request limited) - and getMetaComponents it ...
                if (true === $this->hasFileUpload()) {
                    // ... getMetaComponents in this context is to ensure that we can't
                    $fileUploadHandler = $this->getFileUploadHandler();

                    // Retrieve files for this step (either from pool or fresh uploaded)
                    $files = $fileUploadHandler->getUploadedFiles(
                        $step,
                        $this->getDataPool()
                    );

                } else {
                    $files = [];
                }

                // Store files ...
                $this->setFiles($files);

                // Validate only if we ...
                if ($jumped <= $lastValidStep) {

                    // Extract components for validation in this steps
                    $validationRules = $this->getDataPool()[Doozr_Form_Service_Constant::IDENTIFIER_COMPONENTS][$step];

                    $submittedValues = $this->buildValueArray(
                        array_keys($validationRules)
                    );

                    // Run validation by using validation handler ...
                    $this->setValid(
                        $this->getValidationHandler()->validate(
                            $submittedValues,
                            $validationRules
                        )
                    );
                }

                // Transfer valid data ...
                $this->transferValidDataAndFilesToPool($step);

                // If valid we must increase active step to the next one :)
                if (true === $this->isValid()) {
                    // We only accept completion of forms on a submit. This is a condition which prevent us from
                    // running into raise conditions with jumped forms which are valid ... and it makes the rule easy:
                    $this->setComplete($step === $steps);

                    if (true === $this->isComplete()) {
                        $data = $this->getDataHandler()->enrichWithMetaInformation($this->getDataPool());
                        $this->invalidateDataPool();
                        $this->setResult($data);
                    }

                    $this->setActiveStep($step);
                } else {
                    $this->setActiveStep($step);
                }

                $processed = true;
            }


            /*
            // At this point the basic validation must be done!
            if (true === $valid) {
                // Store the detected values for further processing
                $this->setStep($step);
                $this->setSteps($steps);
                $this->setToken($token);
                $this->setUpload($upload);

                // We could now call the validation. But why? We validated that the call to here is correct (validation)
                // and the data we would now validation ir already validated. The request method will probably fail cause
                // we jumped via ?...Step=x to here ;) So we do not validation again!
                $this->setValid(true);
                $this->setComplete(false);
                $this->setActiveStep($step);

                $processed = true;
            }*/
        }

        // If neither submit nor successful jump step back to defaults!
        if (false === $processed) {
            $step       = Doozr_Form_Service_Constant::DEFAULT_STEP_FIRST;
            $activeStep = $step;
            $steps      = Doozr_Form_Service_Constant::DEFAULT_STEP_FIRST;
            $upload     = Doozr_Form_Service_Constant::DEFAULT_HAS_FILE_UPLOAD;

            // Store the detected values for further processing
            $this->setStep($step);
            $this->setActiveStep($activeStep);
            $this->setSteps($steps);
            $this->setUpload($upload);
            $this->setFiles([]);
            $this->setValid(false);
            $this->setComplete(false);
        }

        return $this;
    }
1083123
protected function _init() {
		parent::_init();

		foreach (static::_parents() as $parent) {
			$inherit = get_class_vars($parent);

			if (isset($inherit['_render'])) {
				$this->_render += $inherit['_render'];
			}
			if ($parent === __CLASS__) {
				break;
			}
		}

		$this->request = $this->request ?: $this->_config['request'];
		$this->response = $this->_instance('response', $this->_config['response']);

		if (!$this->request || $this->_render['type']) {
			return;
		}
		if ($this->_render['negotiate']) {
			$this->_render['type'] = $this->request->accepts();
			return;
		}
		$this->_render['type'] = $this->request->get('params:type') ?: 'html';
	}
424353
public static function initialize()
    {
        switch($_SERVER['REQUEST_METHOD']) {
            case "POST":
                self::$_method = self::POST;
                break;
            case "GET":
                self::$_method = self::GET;
                break;
            case "PUT":
                self::$_method = self::PUT;
                break;
            case "DELETE":
                self::$_method = self::DELETE;
                break;
            default:
                self::$_method = self::HEAD;
        }
        self::$_data = array();
        self::_parseData($_GET);
        self::_parseData($_POST);
        
        if(
            isset($_SERVER['HTTPS']) &&
            $_SERVER['HTTPS'] !== null &&
            $_SERVER['HTTPS'] !== "off"
        ) {
            self::$_https = true;
        } else {
            self::$_https = false;
        }
        
        self::$_domain = (string) $_SERVER['HTTP_HOST'];
        self::$_file = (string) $_SERVER['SCRIPT_FILENAME'];
        if(isset($_SERVER['PATH_INFO'])) {
            self::$_pathInfo = (string) $_SERVER['PATH_INFO'];
        } else {
            self::$_pathInfo = "";
        }
    }
323844
public function init()
    {
        foreach ($this->dynamic as $key => $data) {
            // Locate field.
            $path = explode('/', $key);
            $current = &$this->items;

            foreach ($path as $field) {
                if (\is_object($current)) {
                    // Handle objects.
                    if (!isset($current->{$field})) {
                        $current->{$field} = [];
                    }

                    $current = &$current->{$field};
                } else {
                    // Handle arrays and scalars.
                    if (!\is_array($current)) {
                        $current = [$field => []];
                    } elseif (!isset($current[$field])) {
                        $current[$field] = [];
                    }

                    $current = &$current[$field];
                }
            }

            // Set dynamic property.
            foreach ($data as $property => $call) {
                $action = 'dynamic' . ucfirst($call['action']);

                if (method_exists($this, $action)) {
                    $this->{$action}($current, $property, $call);
                }
            }
        }

        return $this;
    }
806689
protected function initHandle()
    {
        if ($this->isOpen()) {
            rewind($this->resource);

            return $this->resource;
        }

        return $this->resource();
    }
1148002
public function init()
	{
		// Use Reflection::getProperties(PROTECTED) to get protected properties from the passed model
		$reflection = new ReflectionClass($this->model);
		$this->properties = $reflection->getProperties(ReflectionProperty::IS_PROTECTED);

		return parent::init();
	}
1139025
public function init()
    {
        if ($this->runEvent) {
            $chain = new jsChain();
            $this->app->html->js(true, $chain->atkServerEvent(
                ['uri' => $this->getUrl()]
            ));
            $this->isRunning = true;
        }

        $this->_initialized = true;
    }
699880
protected function Init()
    {
        $this->article = Article::Schema()->ByCleanTitle(Request::GetData('article'));
        if ($this->article && !$this->CheckPublished()) {
            $this->article = null;
        }
        if ($this->article) {
            $this->category = $this->article->GetCategory();
            $this->archive = $this->category->GetArchive();
            $this->InitMetaTitle();
            $this->InitMetaDescription();
        }
        return parent::Init();
    }
492473
protected function Init()
    {
        $this->group = new Membergroup(Request::GetData('membergroup'));
        $this->AddNameField();
        $this->AddSubmit();
        return parent::Init();
    }
1134103
protected function Init()
    {
        $this->repeater = ContentRepeater::Schema()->ByContent($this->content);
        $this->current = $this->tree->FirstChildOf($this->item);
        $this->isEmpty = !$this->current;
        return parent::Init();
    }
1051572
public function initInlineScript()
    {
        $javascripts = $this->orderByPriority($this->options->getJs()->getInline());
        foreach ($javascripts as $js) {
            $this->setJavascript($this->inlineScript, $js);
        }

        return $this;
    }
484906
public function initialize() {
        if (!$this->isEnabled()) {
            return;
        }

        $current = null;

        // Determine via cookie
        if (!empty($_COOKIE['locale']) && isset($this->_locales[$_COOKIE['locale']])) {
            $current = $_COOKIE['locale'];

        // Determine locale based on HTTP headers
        } else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            $header = mb_strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']);

            if (mb_strpos($header, ';') !== false) {
                $header = mb_strstr($header, ';', true);
            }

            $header = explode(',', $header);

            if (count($header) > 0) {
                foreach ($header as $key) {
                    if (isset($this->_locales[$key])) {
                        $current = $key;
                        break;
                    }
                }
            }
        }

        // Set current to the fallback if none found
        if ($current === null) {
            $current = $this->_fallback->getCode();
        }

        // Check for a translator
        if (!$this->_translator) {
            throw new MissingTranslatorException('A translator is required for G11n message parsing');
        }

        $this->emit('g11n.onInit', [$this, &$current]);

        // Apply the locale
        $this->useLocale($current);
    }
699200
protected function Init()
    {        
        $this->user = new User(Request::GetData('user'));
        
        $this->AddNameField();
        $this->AddEmailField();
        $this->AddPasswordField();
        $this->AddPasswordRepeatField();
        $this->AddIsAdminField();
        $this->AddLanguageField();
        $this->AddSubmit();
        return parent::Init();
    }
219153
public function init() {
        $options = $this->getServiceLocator()->get('search.options');
        $this->setOptions($options);
        $this->driverName = $options['driver'];
        $this->setDriverEscaper($this->getServiceLocator()->get($this->driverList[$this->driverName]));
        
        return $this;
    }
934095
public function initializeObject()
    {
        if ($this->request === null) {
            $requestHandler = $this->bootstrap->getActiveRequestHandler();
            if ($requestHandler instanceof HttpRequestHandlerInterface) {
                $this->request = new ActionRequest($requestHandler->getHttpRequest());
            } else {
                $httpRequest = Request::createFromEnvironment();
                $this->request = new ActionRequest($httpRequest);
            }
        }

        $uriBuilder = new UriBuilder();
        $uriBuilder->setRequest($this->request);

        $this->setControllerContext(new ControllerContext(
            $this->request,
            new ActionResponse(),
            new Arguments([]),
            $uriBuilder
        ));
    }
292330
public function init()
    {
        parent::init();

        $this->form->addHook('displayError', function ($form, $fieldName, $str) {
            // default behavior
            $jsError = [$form->js()->form('add prompt', $fieldName, $str)];

            // if field is part of an accordion section, will open that section.
            $section = $form->getClosestOwner($form->getField($fieldName), '\atk4\ui\AccordionSection');
            if ($section) {
                $jsError[] = $section->owner->jsOpen($section);
            }

            return $jsError;
        });
    }
892044
protected function _initItems()
    {
        $data = $this->_getItemsData();
        $items = [];
        foreach ($data as $itemData) {
            $item = $this->_createItem($itemData['label'], $itemData['value'], $itemData['count']);
            $items[] = $item;

            if ($this->useUrlRewrites() === true) {
                $item->setUrlRewrite($itemData['url']);
            }
        }
        $this->_items = $items;

        return $this;
    }