public static function getKeyWords(string $text, int $maxLen = 60): string
	{
		$keyWords = [];
		// nalezeni vsech linku v textu
		preg_match_all('/<a[^>]*>[^<]+<\/a>/i', $text, $found);
		if (isset($found[0])) {
			foreach ($found[0] as $kw) {
				$keyWords[] = self::lower(self::trim(strip_tags($kw)));
			}
		}

		// h2 a strong
		preg_match_all('/<(h2|strong)[^>]*>[^<]+<\/(h2|strong)>/i', $text, $found);
		if (isset($found[0])) {
			foreach ($found[0] as $kw) {
				$keyWords[] = self::lower(self::trim(strip_tags($kw)));
			}
		}

		$result = implode(', ', array_unique($keyWords));

		return self::truncate($result, $maxLen, '');
	}

Vrati klicova slova z textu
@param string $text
@param int $maxLen
@return string


public static function findEmails(string $text): array
	{
		$result = [];
		preg_match_all('/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i', $text, $result);
		return isset($result[0]) ? $result[0] : [];
	}

Vrati email z textu
@param string $text
@return string[]


public static function containsArray(string $haystack, array $needle): ?string
	{
		foreach ($needle as $query) {
			if (parent::contains($haystack, $query)) {
				return $query;
			}
		}
		return null;
	}

public static function containsArray ( string $ haystack , array $ needle ) : ? string { foreach ( $ needle as $ query ) { if ( parent :: contains ( $ haystack , $ query ) ) { return $ query ; } } return null ; }

Vrati retezec, ktery se v textu vyskytuje
@param string $haystack
@param string[] $needle
@return string|null

Vrati retezec ktery se v textu vyskytuje


public function redirect( Request $request, $endpoint, $path, $responseType = 'json' ) {
		// Set the Endpoints
		$this->getEndpoints();

		// Get Endpoint config.
		$this->setBaseUri( $this->getEndpointConfig( $endpoint )['endpoint'] );

		// Get Endpoint AUTH
		// $this->setAuthHeaders();

		// Get Required variables for the endpoint.
		// void

		// Add Proxy to request
		$request->attributes->add( [
			                           'proxy' => [
				                           'host'          => $this->getBaseUri(),
				                           'path'          => $path,
				                           'response_type' => $responseType,
			                           ],
		                           ] );

		// Create a call to the endpoint
		$this->prepareCall( null );

		// Prepare headers:
		$headers = $request->headers->all();
		if ( isset( $headers['host'] ) ) {
			unset( $headers['host'] );
		}

		// Set proxy headers
		$headers['bizhost-request-identifier'] = [ $request->get( 'bizhost-request-identifier' , null) ];
		$headers['bizhost-session-identifier'] = [ $request->get( 'bizhost-session-identifier' , null) ];

		// Prepare data
		$data = $request->all();

		// Execute call
		$this->execute( $request->getMethod(), $path, $data, $headers );

		// Catch the results
		return $this->getResponse( $responseType );
	}

Redirect the API call to the micro service

@param Request $request
@param string  $endpoint
@param string  $path
@param string  $responseType

@return mixed
@throws \Exception


public function migrateUp(MigrationConfig $config, $flushDatabase = false): Awaitable
    {
        return new Coroutine(function () use ($config, $flushDatabase) {
            $migrations = $this->instantiateMigrations($config);

            if (empty($migrations)) {
                $skip = false;
            } else {
                $skip = yield $this->platform->hasTable('#__kk_migration');

                if ($skip) {
                    $mtime = clone $this->date;
                    $params = [];

                    foreach (\array_values($migrations) as $i => $migration) {
                        $params[] = $migration->getVersion();
                        $date = new \DateTime('@' . \filemtime((new \ReflectionClass(\get_class($migration)))->getFileName()));

                        if ($date > $mtime) {
                            $mtime = $date;
                        }
                    }

                    $sql = "SELECT COUNT(*) AS cnt, MAX(`migrated`) AS mtime FROM `#__kk_migration` WHERE `version` IN (";
                    $sql .= \implode(', ', \array_fill(0, \count($params), '?')) . ")";

                    $stmt = $this->conn->prepare($sql);
                    $stmt->bindAll($params);

                    try {
                        $result = yield $stmt->execute();

                        // Only skip migrations if all of them are alreay migrated up.
                        try {
                            $row = yield $result->fetch();
                        } finally {
                            $result->closeCursor();
                        }
                    } finally {
                        $stmt->dispose();
                    }

                    $dbcnt = (int) $row['cnt'];
                    $dbmtime = \DateTime::createFromFormat('YmdHis', $row['mtime']);

                    $skip = (\count($params) === $dbcnt) && ($dbmtime > $mtime);
                }
            }

            if (!$skip) {
                if ($flushDatabase) {
                    yield $this->platform->flushDatabase();
                }

                foreach ($migrations as $migration) {
                    yield from $this->executeMigrationUp($migration);
                }
            }

            if ($skip && $flushDatabase) {
                yield $this->platform->flushData();
            }
        });
    }

Execute all up-migrations loaded from the given config.

DB will be flushed if a migration must be applied, will simply flush all data if no migration is needed.

@param MigrationConfig $config All configured migrations to be applied.
@param bool $flushDatabase Flush database before any migration is applied?

Execute all up - migrations loaded from the given config .


public function migrateDirectoryUp($dir, $flushDatabase = false): Awaitable
    {
        $config = new MigrationConfig();
        $config->loadMigrationsFromDirectory($dir);

        return $this->migrateUp($config, $flushDatabase);
    }

public function migrateDirectoryUp ( $ dir , $ flushDatabase = false ) : Awaitable { $ config = new MigrationConfig ( ) ; $ config -> loadMigrationsFromDirectory ( $ dir ) ; return $ this -> migrateUp ( $ config , $ flushDatabase ) ; }

Execute all up-migrations found in the given directory.

DB will be flushed if a migration must be applied, will simply flush all data if no migration is needed.

@param string $dir Directory where migration PHP-files are placed.
@param boolean $flushDatabase Flush database before any migration is applied?

Execute all up - migrations found in the given directory .


public function setId($id = null)
    {
		if ($id != null){
			$this->isNew = false;
			$this->id = $id;
		}else{
			$this->id = SecureKey::generate();
		}
        return $this;
    }

public function setId ( $ id = null ) { if ( $ id != null ) { $ this -> isNew = false ; $ this -> id = $ id ; } else { $ this -> id = SecureKey :: generate ( ) ; } return $ this ; }

Set token ID

@param string $id Token ID

@return self


public function daemon($sleep = 60, $memoryLimit = 128)
    {
        $memoryLimit = $memoryLimit * 1024 * 1024;
        $startTime = time();
        while (true) {
            $ret = $this->runNextJob();

            if (! $ret) { //没有获取到job
                sleep($sleep);
            }

            ($this->memoryExceeded($memoryLimit) || $this->queueShouldRestart($startTime)) &&
                $this->stop();
        }
    }

public function daemon ( $ sleep = 60 , $ memoryLimit = 128 ) { $ memoryLimit = $ memoryLimit * 1024 * 1024 ; $ startTime = time ( ) ; while ( true ) { $ ret = $ this -> runNextJob ( ) ; if ( ! $ ret ) { //没有获取到job sleep ( $ sleep ) ; } ( $ this -> memoryExceeded ( $ memoryLimit ) || $ this -> queueShouldRestart ( $ startTime ) ) && $ this -> stop ( ) ; } }

Listen to the given queue in a loop.

@param int $sleep 没有新的有效任务产生时的休眠时间 (单位: 秒)
@param int $memoryLimit worker 内存限制 (单位: mb)


public function has($key)
    {
        if (isset($this->parameters[$key]) || array_key_exists($key, $this->parameters)) {
            return true;
        }

        return false;
    }

public function has ( $ key ) { if ( isset ( $ this -> parameters [ $ key ] ) || array_key_exists ( $ key , $ this -> parameters ) ) { return true ; } return false ; }

Returns whether the key exists or not.

@param string $key name of key to check

@return bool true, if key exists; false otherwise


public function getOauthRequest(array $params, $httpMethod, $baseUrl, $endPoint) : string
	{
		$signatureParams = array_merge($params, $this->getOauthParams());
		$signatureParams['oauth_signature'] = $this->getOauthSignature($signatureParams, $httpMethod, $baseUrl . $endPoint);

		$contentParams = [];
		foreach ($params as $key => $param) {
			$contentParams[] = $key . '=' . rawurlencode($param);
		}

		$content = implode('&', $contentParams);

		return $httpMethod . " " . $endPoint . " HTTP/1.1\r\n"
		."Accept: */*\r\n"
		."Connection: close\r\n"
		."User-Agent: Callisto API\r\n"
		."Content-Type: application/x-www-form-urlencoded\r\n"
		."Authorization: OAuth realm=\"\",oauth_consumer_key=\"" . $signatureParams['oauth_consumer_key'] . "\","
		."oauth_nonce=\"" . $signatureParams['oauth_nonce'] . "\","
		."oauth_signature_method=\"" . $signatureParams['oauth_signature_method'] . "\","
		."oauth_timestamp=\"" . $signatureParams['oauth_timestamp'] . "\","
		."oauth_version=\"" . $signatureParams['oauth_version'] . "\","
		."oauth_token=\"" . $signatureParams['oauth_token'] . "\","
		."oauth_signature=\"" . rawurlencode($signatureParams['oauth_signature']) . "\"\r\n"
		."Content-Length: " . strlen($content) . "\r\n"
		."Host: stream.twitter.com:443\r\n\r\n"
		.$content;
	}

Generates the HTTP request string.

@param array $params
@param $httpMethod
@param $baseUrl
@param $endPoint
@return string


private function getOauthSignature(array $params, $httpMethod, $url) : string
	{
		$urlParams = [];
		foreach ($params as $key => $value) {
			$params[$key] = rawurlencode($value);
			$urlParams[$key] = $key . '=' . $params[$key];
		}

		ksort($urlParams);
		$parameterString = implode('&', $urlParams);
		$signatureBaseString = strtoupper($httpMethod) .
			'&' . rawurlencode($url) .
			'&' . rawurlencode($parameterString);

		$signingKey = rawurlencode($this->consumerSecret) . '&' . rawurlencode($this->accessTokenSecret);
		$oauthSignature = base64_encode(hash_hmac('sha1', $signatureBaseString, $signingKey, true));

		return $oauthSignature;
	}

private function getOauthSignature ( array $ params , $ httpMethod , $ url ) : string { $ urlParams = [ ] ; foreach ( $ params as $ key => $ value ) { $ params [ $ key ] = rawurlencode ( $ value ) ; $ urlParams [ $ key ] = $ key . '=' . $ params [ $ key ] ; } ksort ( $ urlParams ) ; $ parameterString = implode ( '&' , $ urlParams ) ; $ signatureBaseString = strtoupper ( $ httpMethod ) . '&' . rawurlencode ( $ url ) . '&' . rawurlencode ( $ parameterString ) ; $ signingKey = rawurlencode ( $ this -> consumerSecret ) . '&' . rawurlencode ( $ this -> accessTokenSecret ) ; $ oauthSignature = base64_encode ( hash_hmac ( 'sha1' , $ signatureBaseString , $ signingKey , true ) ) ; return $ oauthSignature ; }

Generates an OAuth signature.

@param array $params
@param $httpMethod
@param $url
@return string


public function node($id)
    {
        if (isset($this->items[$id])) {
            throw new \RuntimeException(sprintf('Duplicate item ID: "%s"', $id));
        }

        return $this->items[$id] = new Node($id);
    }

public
function
node
(
$
id
)
{
if
(
isset
(
$
this
->
items
[
$
id
]
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Duplicate item ID: "%s"'
,
$
id
)
)
;
}
return
$
this
->
items
[
$
id
]
=
new
Node
(
$
id
)
;
}

Add a new node to the process.

@param string $id Unique ID of the node.
@return Node Created node instance.


public function transition($id, $from, $to)
    {
        if (isset($this->items[$id])) {
            throw new \RuntimeException(sprintf('Duplicate item ID: "%s"', $id));
        }

        $transition = $this->items[$id] = new Transition($id, $from);
        $transition->to($to);

        return $transition;
    }

public
function
transition
(
$
id
,
$
from
,
$
to
)
{
if
(
isset
(
$
this
->
items
[
$
id
]
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Duplicate item ID: "%s"'
,
$
id
)
)
;
}
$
transition
=
$
this
->
items
[
$
id
]
=
new
Transition
(
$
id
,
$
from
)
;
$
transition
->
to
(
$
to
)
;
return
$
transition
;
}

Add a new transition between 2 nodes to the process.

@param string $id Unique ID of the transition.
@param string $from ID of the start node.
@param string $to ID of the end node.
@return Transition Created transition instance.

Add a new transition between 2 nodes to the process .


public function addSetting(ISetting $setting, $cachable = true)
    {
        $this->settings[] = $setting;

        if (true === $cachable) {
            $this->cachable_settings[] = $setting;
        }

        return $this;
    }

public function addSetting ( ISetting $ setting , $ cachable = true ) { $ this -> settings [ ] = $ setting ; if ( true === $ cachable ) { $ this -> cachable_settings [ ] = $ setting ; } return $ this ; }

Adds the given setting to the internal lists of settings.

@param ISetting $setting setting to add to internal lists of settings
@param bool $cachable whether or not the setting may be put into a cache for reuse on re-execution of the check

@return Result this instance for fluent API support

Adds the given setting to the internal lists of settings .


public function addSettings(array $settings, $cachable = true)
    {
        foreach ($settings as $setting) {
            if ($setting instanceof ISetting) {
                $this->addSetting($setting);
            }
        }

        return $this;
    }

public function addSettings ( array $ settings , $ cachable = true ) { foreach ( $ settings as $ setting ) { if ( $ setting instanceof ISetting ) { $ this -> addSetting ( $ setting ) ; } } return $ this ; }

Adds the given setting to the internal list of settings.

@param array $settings array with ISetting implementing instances to add
@param bool $cachable whether or not the setting may be put into a cache for reuse on re-execution of the check

@return Result this instance for fluent API support

Adds the given setting to the internal list of settings .


public function getSettings($groups = null, $flag = null)
    {
        return $this->getFiltered($this->settings, $groups, $flag);
    }

public function getSettings ( $ groups = null , $ flag = null ) { return $ this -> getFiltered ( $ this -> settings , $ groups , $ flag ) ; }

Returns the internal list of settings emitted by the processed check.

@param string $groups group names of settings to return
@param integer $flag flag value the settings should belong to

@return array of ISetting implementing instances matching the arguments

Returns the internal list of settings emitted by the processed check .


public function getCachableSettings($groups = null, $flag = null)
    {
        return $this->getFiltered($this->cachable_settings, $groups, $flag);
    }

public function getCachableSettings ( $ groups = null , $ flag = null ) { return $ this -> getFiltered ( $ this -> cachable_settings , $ groups , $ flag ) ; }

Returns the internal list of cachable settings emitted by the processed check.

@param string $groups group names of settings to return
@param integer $flag flag value the settings should belong to

@return array of ISetting implementing instances matching the arguments

Returns the internal list of cachable settings emitted by the processed check .


public function getSettingsAsArray($groups = null, $flag = null)
    {
        return $this->getFilteredAsArray($this->settings, $groups, $flag);
    }

public function getSettingsAsArray ( $ groups = null , $ flag = null ) { return $ this -> getFilteredAsArray ( $ this -> settings , $ groups , $ flag ) ; }

Return all settings or the settings of the specified groups as an array.

@param string $groups group names of settings to return
@param integer $flag flag value the settings should belong to

@return array all settings (for the specified groups); empty array if groups don't exist.

Return all settings or the settings of the specified groups as an array .


public function getCachableSettingsAsArray($groups = null, $flag = null)
    {
        return $this->getFilteredAsArray($this->cachable_settings, $groups, $flag);
    }

public function getCachableSettingsAsArray ( $ groups = null , $ flag = null ) { return $ this -> getFilteredAsArray ( $ this -> cachable_settings , $ groups , $ flag ) ; }

Return all cachable settings or the cachable settings of the specified groups as an array.

@param string $groups group names of cachable settings to return
@param integer $flag flag value the settings should belong to

@return array all cachable settings (for the specified groups); empty array if groups don't exist.

Return all cachable settings or the cachable settings of the specified groups as an array .


protected function getFiltered(array $all_settings = array(), $groups = null, $flag = null)
    {
        $settings = array();

        foreach ($all_settings as $setting) {
            if ($setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                $settings[] = $setting;
            }
        }

        return $settings;
    }

protected function getFiltered ( array $ all_settings = array ( ) , $ groups = null , $ flag = null ) { $ settings = array ( ) ; foreach ( $ all_settings as $ setting ) { if ( $ setting -> matchesGroup ( $ groups ) && $ setting -> matchesFlag ( $ flag ) ) { $ settings [ ] = $ setting ; } } return $ settings ; }

Returns all settings from the given array that match the groups and flag.

@param array $all_settings array of ISetting implementing classes
@param string $groups group names of settings to return
@param integer $flag flag value the settings should belong to

@return array of entries from all_settings that match the given groups and flag

Returns all settings from the given array that match the groups and flag .


protected function getFilteredAsArray(array $all_settings, $groups = null, $flag = null)
    {
        $settings = array();

        foreach ($all_settings as $setting) {
            if ($setting->matchesGroup($groups) && $setting->matchesFlag($flag)) {
                $settings[] = $setting->toArray();
            }
        }

        return $settings;
    }

protected function getFilteredAsArray ( array $ all_settings , $ groups = null , $ flag = null ) { $ settings = array ( ) ; foreach ( $ all_settings as $ setting ) { if ( $ setting -> matchesGroup ( $ groups ) && $ setting -> matchesFlag ( $ flag ) ) { $ settings [ ] = $ setting -> toArray ( ) ; } } return $ settings ; }

Returns all or just the matching settings of the given groups as an associative array.

@param array $all_settings array of ISetting implementing setting instances
@param string $group name of group to filter given settings for
@param integer $flag flag value the setting must be matching

@return array with associative arrays (for each setting)

Returns all or just the matching settings of the given groups as an associative array .


public function render()
    {
        // preload images
        $sHTML = "\n";

        // list all views and highlight the current view
        $sHTML .= "
\n";
        $sHTML .= $this->renderNodeItems($this->nodesXml);
        $sHTML .= "
";
        return $sHTML;
    }

" minus = new Image();\n minus.src = \""

Render HTML Tree

@return string html content of the tree


protected function renderNodeItems(&$nodeItemArray)
    {
        $sHTML = "";
        if (isset($nodeItemArray["ATTRIBUTES"]))
        {
            $sHTML .= $this->renderSingleNodeItem($nodeItemArray);
        }
        else
        {
            foreach ($nodeItemArray as $nodeItem)
            {
                $sHTML .= $this->renderSingleNodeItem($nodeItem);
            }
        }
        return $sHTML;
    }

protected function renderNodeItems ( & $ nodeItemArray ) { $ sHTML = "" ; if ( isset ( $ nodeItemArray [ "ATTRIBUTES" ] ) ) { $ sHTML .= $ this -> renderSingleNodeItem ( $ nodeItemArray ) ; } else { foreach ( $ nodeItemArray as $ nodeItem ) { $ sHTML .= $ this -> renderSingleNodeItem ( $ nodeItem ) ; } } return $ sHTML ; }

Render the html tree

@return string html content of the tree


protected function renderSingleNodeItem(&$nodeItem)
    {
        $url = $nodeItem["ATTRIBUTES"]["URL"];
        $caption = $this->translate($nodeItem["ATTRIBUTES"]["CAPTION"]);
        $target = $nodeItem["ATTRIBUTES"]["TARGET"];
        //$img = $nodeItem["ATTRIBUTES"]["IMAGE"];
        if ($nodeItem["NODE"]) {
            $image = "getImageUrl() . "/plus.gif' class='collapsed' onclick='mouseClickHandler(this)'>";
        } else {
            $image = "getImageUrl() . "/topic.gif'>";
        }

        if ($target) {
            if ($url) {
                $sHTML .= "
$image " . $caption . "";
            } else {
                $sHTML .= "
$image $caption";
            }
        } elseif ($url) {
            $sHTML .= "
$image " . $caption . "";
        } else {
            $sHTML .= "
$image $caption";
        }
        if ($nodeItem["NODE"])
        {
            $sHTML .= "\n
\n";
            $sHTML .= $this->renderNodeItems($nodeItem["NODE"]);
            $sHTML .= "
";
        }
        $sHTML .= "
\n";
        return $sHTML;
    }

Render single node item

@param array $nodeItem
@return <type>


protected function run()
    {
        if (! $this->bootstrapped) {
            $this->autoloaderCollection = new JsonAutoloaderCollection($this->vendorDir, $this->searchFolders);
            $this->retrieveInstalledBundles();
            $this->install();
            $this->uninstall();
            $this->arrangeBundlesForEnvironment();

            $this->bootstrapped = true;
        }
    }

protected function run ( ) { if ( ! $ this -> bootstrapped ) { $ this -> autoloaderCollection = new JsonAutoloaderCollection ( $ this -> vendorDir , $ this -> searchFolders ) ; $ this -> retrieveInstalledBundles ( ) ; $ this -> install ( ) ; $ this -> uninstall ( ) ; $ this -> arrangeBundlesForEnvironment ( ) ; $ this -> bootstrapped = true ; } }


protected function register($environment)
    {
        if (isset($this->environmentsBundles[$environment])) {
            foreach ($this->environmentsBundles[$environment] as $bundle) {
                $bundleClass = $bundle->getClass();
                if (empty($this->instantiatedBundles) || !in_array($bundleClass, $this->instantiatedBundles)) {

                    if ( ! class_exists($bundleClass)) {
                        throw new InvalidAutoloaderException(sprintf("The bundle class %s does not exist. Check the bundle's autoload.json to fix the problem", $bundleClass, get_class($this)));
                    }

                    if ( ! in_array($bundle->getName(), $this->bundles)) {
                        $instantiatedBundle = new $bundleClass;
                        $this->bundles[$bundle->getName()] = $instantiatedBundle;
                        $overridedBundles = $bundle->getOverrides();
                        if ( ! empty($overridedBundles)) {
                            $this->overridedBundles[$bundle->getName()] = $overridedBundles;
                        }
                        $this->instantiatedBundles[] = $bundleClass;
                    }
                }
            }
        }
    }

Registers the bundles for the given environment

@param string $environment


protected function install()
    {
        foreach ($this->autoloaderCollection as $dir => $jsonAutoloader) {
            $bundleName = $jsonAutoloader->getBundleName();
            $this->installPackage($dir, $jsonAutoloader);
            unset($this->installedBundles[$bundleName]);
        }
    }

protected function install ( ) { foreach ( $ this -> autoloaderCollection as $ dir => $ jsonAutoloader ) { $ bundleName = $ jsonAutoloader -> getBundleName ( ) ; $ this -> installPackage ( $ dir , $ jsonAutoloader ) ; unset ( $ this -> installedBundles [ $ bundleName ] ) ; } }

Instantiates the bundles that must be autoconfigured, parsing the autoload_namespaces.php file
generated by composer

Instantiates the bundles that must be autoconfigured parsing the autoload_namespaces . php file generated by composer


protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output);

        $this->input = $input;
        $this->output = $output;

        // prepend include_path if demanded
        $path = $input->getOption('include-path');
        if (!empty($path)) {
            ini_set('include_path', $path . PATH_SEPARATOR . ini_get('include_path'));
        }

        // run given bootstrap file if necessary
        $bootstrap_path = $input->getOption('bootstrap');
        if (!empty($bootstrap_path)) {
            if (!is_readable($bootstrap_path)) {
                throw new \InvalidArgumentException('Bootstrap file "' . $bootstrap_path . '" is not readable.');
            }

            if ($this->input->getOption('verbose')) {
                $output->writeln('<comment>Requiring boostrap file from "' . $bootstrap_path . '".</comment>');
            }
            require $bootstrap_path;
        }

        // we autoload classes from the current working directory or the specified autoload_dir
        $autoload_dir = $input->getOption('autoload-dir');
        if (!empty($autoload_dir)) {
            if (!is_readable($autoload_dir)) {
                throw new \InvalidArgumentException(
                    'Autoload path "' . $autoload_dir . '" is not readable. Please specify an existing directory.'
                );
            }

            if ($this->input->getOption('verbose')) {
                $output->writeln('<comment>Classes will be autoloaded from "' . $autoload_dir . '".</comment>');
            }
        } else {
            if ($this->input->getOption('verbose')) {
                $output->writeln(
                    '<comment>No autoload_dir specified, using "' . $this->getCurrentWorkingDirectory() .
                    '" to autoload classes from.</comment>'
                );
            }
        }

        spl_autoload_register(array($this, 'autoload'));
    }

Handles the default options all commands have in common.

@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output

@throws \InvalidArgumentException in case of configuration errors

Handles the default options all commands have in common .


protected function autoload($class)
    {
        $class = str_replace('\\', DIRECTORY_SEPARATOR, $class);

        $autoload_dir = $this->getInput()->getOption('autoload-dir');
        if (empty($autoload_dir)) {
            $autoload_dir = $this->getCurrentWorkingDirectory();
        }

        $file_path = $autoload_dir . DIRECTORY_SEPARATOR . $class . '.php';

        if ($this->input->getOption('verbose')) {
            $this->output->write('<info>Autoloading</info>: ');
        }

        if (is_readable($file_path)) {
            if ($this->input->getOption('verbose')) {
                $this->output->writeln($file_path);
            }

            include_once($file_path);
        } else {
            $this->output->writeln('<error>Autoload error: "' . $file_path . '" not found!</error>' . PHP_EOL);
            // don't exit here to let other autoloaders get their chance
            //throw new \InvalidArgumentException('Could not include unreadable file: ' . $file_path);
        }
    }

Autoloads the given class if it exists.

@param string $class class name like 'Foo\Bar\Baz'

@throws \InvalidArgumentException in case of errors (file

Autoloads the given class if it exists .


public static function load($id): bool
    {
        $loaded = false;
        if (isset(static::$files[$id])) {
            $loaded = static::$files[$id] === true;

            if (! $loaded) {
                assert(file_exists(static::$files[$id]));

                include static::$files[$id];
                $loaded = static::$files[$id] = true;
            }
        }
        return $loaded;
    }

public static function load ( $ id ) : bool { $ loaded = false ; if ( isset ( static :: $ files [ $ id ] ) ) { $ loaded = static :: $ files [ $ id ] === true ; if ( ! $ loaded ) { assert ( file_exists ( static :: $ files [ $ id ] ) ) ; include static :: $ files [ $ id ] ; $ loaded = static :: $ files [ $ id ] = true ; } } return $ loaded ; }

Load the given collection.

Asserts file existence because it should never be the case that they don't
exist on production.

@param $id
@return bool


public function forward($route, array $attributes = [], array $query = [])
    {
        return $this->getKernel()->forward($route, $attributes, $query);
    }

public function forward ( $ route , array $ attributes = [ ] , array $ query = [ ] ) { return $ this -> getKernel ( ) -> forward ( $ route , $ attributes , $ query ) ; }

Internal redirect without creating an instance of kernel

@param string $route
@param array $attributes
@param array $query

@return Response


public function glyphIcon($glyphIcon)
    {
        if (empty($this->parts['{input}'])) {
            throw new InternalErrorException('Firstly you must set field type!');
        }

        if (empty($glyphIcon) || !$this->_glyphIconAllowed) {
            $this->parts['{glyphIcon}'] = '';
            return $this;
        }

        $this->parts['{glyphIcon}'] = Html::tag('span', '', ['class' => "glyphicon glyphicon-$glyphIcon form-control-feedback"]);

        return $this;
    }

Working only with inputs where type is text or password

You must set field first

@param $glyphIcon string Icon name
@return $this
@throws InternalErrorException


public function setQueryParameters($paramValues)
    {
        foreach ($paramValues as $param => $value)
            $this->queryParams[$param] = $value;
    }

public function setQueryParameters ( $ paramValues ) { foreach ( $ paramValues as $ param => $ value ) $ this -> queryParams [ $ param ] = $ value ; }

Set query parameter for parameter binding in the query

@param array {fieldname:value} list
@return void


public function setLimit($count, $offset = 0)
    {
        if ($count < 0) {
            $count = 0;
        }
        if ($offset < 0) {
            $offset = 0;
        }
        $this->queryLimit['count'] = $count;
        $this->queryLimit['offset'] = $offset;
    }

public function setLimit ( $ count , $ offset = 0 ) { if ( $ count < 0 ) { $ count = 0 ; } if ( $ offset < 0 ) { $ offset = 0 ; } $ this -> queryLimit [ 'count' ] = $ count ; $ this -> queryLimit [ 'offset' ] = $ offset ; }

Set limit of the query.

@param int $count the number of records to return
@param int $offset the starting position of the result records
@return void


public function getDBConnection($type = 'default')
    {
        switch (strtolower($type)) {
            case "default":
            case "read":
                if (isset($this->databaseAliasNameforRead)) {
                    $dbName = $this->databaseAliasNameforRead;
                } else {
                    $dbName = $this->databaseAliasName;
                }
                break;
            case "write":
                if (isset($this->databaseAliasNameforWrite)) {
                    $dbName = $this->databaseAliasNameforWrite;
                } else {
                    $dbName = $this->databaseAliasName;
                }
                break;
        }
        return Openbizx::$app->getDbConnection($dbName);
    }

public function getDBConnection ( $ type = 'default' ) { switch ( strtolower ( $ type ) ) { case "default" : case "read" : if ( isset ( $ this -> databaseAliasNameforRead ) ) { $ dbName = $ this -> databaseAliasNameforRead ; } else { $ dbName = $ this -> databaseAliasName ; } break ; case "write" : if ( isset ( $ this -> databaseAliasNameforWrite ) ) { $ dbName = $ this -> databaseAliasNameforWrite ; } else { $ dbName = $ this -> databaseAliasName ; } break ; } return Openbizx :: $ app -> getDbConnection ( $ dbName ) ; }

Get database connection

@return \Zend_Db_Adapter_Abstract


public function getProperty($propertyName)
    {
        $ret = parent::getProperty($propertyName);
        if ($ret)
            return $ret;
        if ($propertyName == "Table")
            return $this->table;
        if ($propertyName == "SearchRule")
            return $this->searchRule;
        // get control object if propertyName is "Field[fldname]"
        $pos1 = strpos($propertyName, "[");
        $pos2 = strpos($propertyName, "]");
        if ($pos1 > 0 && $pos2 > $pos1) {
            $propType = substr($propertyName, 0, $pos1);
            $fieldName = substr($propertyName, $pos1 + 1, $pos2 - $pos1 - 1);
            if ($propType == "param") {   // get parameter
                return $this->parameters->get($fieldName);
            }
            return $this->getField($fieldName);
        }
    }

Get the property of the object. Used in expression language

@param string $propertyName name of the property
@return BizField|string property value

Get the property of the object . Used in expression language


public function getRefObject($objName)
    {
        // see if there is such object in the ObjReferences
        $objRef = $this->objReferences->get($objName);
        if (!$objRef)
            return null;

        // apply association on the object
        // $assc = $this->EvaluateExpression($objRef->association);
        // get the object instance
        $obj = Openbizx::getObject($objName);
        $obj->setAssociation($objRef, $this);
        return $obj;
    }

Get the object instance defined in the object reference

@param string $objName the object name list in the ObjectReference part
@return BizDataObj object instance


protected function setAssociation($objRef, $asscObj)
    {
        $this->association["AsscObjName"] = $asscObj->objectName;
        $this->association["Relationship"] = $objRef->relationship;
        $this->association["Table"] = $objRef->table;
        $this->association["Column"] = $objRef->column;
        $this->association["FieldRef"] = $objRef->fieldRef;
        $this->association["FieldRefVal"] = $asscObj->getFieldValue($objRef->fieldRef);
        $this->association["CondColumn"] = $objRef->condColumn;
        $this->association["CondValue"] = $objRef->condValue;
        $this->association["Condition"] = $objRef->condition;
        if ($objRef->relationship == "M-M" || $objRef->relationship == "Self-Self") {
            $this->association["XTable"] = $objRef->xTable;
            $this->association["XColumn1"] = $objRef->xColumn1;
            $this->association["XColumn2"] = $objRef->xColumn2;
            $this->association["XKeyColumn"] = $objRef->xKeyColumn;
            $this->association["XDataObj"] = $objRef->xDataObj;
        }
    }

protected function setAssociation ( $ objRef , $ asscObj ) { $ this -> association [ "AsscObjName" ] = $ asscObj -> objectName ; $ this -> association [ "Relationship" ] = $ objRef -> relationship ; $ this -> association [ "Table" ] = $ objRef -> table ; $ this -> association [ "Column" ] = $ objRef -> column ; $ this -> association [ "FieldRef" ] = $ objRef -> fieldRef ; $ this -> association [ "FieldRefVal" ] = $ asscObj -> getFieldValue ( $ objRef -> fieldRef ) ; $ this -> association [ "CondColumn" ] = $ objRef -> condColumn ; $ this -> association [ "CondValue" ] = $ objRef -> condValue ; $ this -> association [ "Condition" ] = $ objRef -> condition ; if ( $ objRef -> relationship == "M-M" || $ objRef -> relationship == "Self-Self" ) { $ this -> association [ "XTable" ] = $ objRef -> xTable ; $ this -> association [ "XColumn1" ] = $ objRef -> xColumn1 ; $ this -> association [ "XColumn2" ] = $ objRef -> xColumn2 ; $ this -> association [ "XKeyColumn" ] = $ objRef -> xKeyColumn ; $ this -> association [ "XDataObj" ] = $ objRef -> xDataObj ; } }

Set the association of the object

@param ObjReference $objRef
@param BizDataObj $asscObj
@return void


protected function fromDocblock($docblock, array $context=array())
    {
        $annotations = $this->getParser()->parse($docblock);

        $col = $this->getCollection();
        $rv = array();
        foreach ($annotations as $annot) {
            list($name, $positional, $named) = $annot;

            if ($obj = $col->create($name, $positional, $named, $context)) {
                $rv[] = $obj;
            }
        }

        return $rv;
    }

protected function fromDocblock ( $ docblock , array $ context = array ( ) ) { $ annotations = $ this -> getParser ( ) -> parse ( $ docblock ) ; $ col = $ this -> getCollection ( ) ; $ rv = array ( ) ; foreach ( $ annotations as $ annot ) { list ( $ name , $ positional , $ named ) = $ annot ; if ( $ obj = $ col -> create ( $ name , $ positional , $ named , $ context ) ) { $ rv [ ] = $ obj ; } } return $ rv ; }

Use the parser to parse a docblock into annotations and create annotation
objects.

@since   0.1
@access  protected
@param   string $docblock The docblock to parse.
@param   array $context This is the place from where the docblock came
This particular reader uses the keys `class`, `method`, `property`,
and `function`. One or more of them will be present. Each would
would be the appropriate Reflection(Class|Method|Property|Function)
object. The array is converted into an AnnotationContextInterface
implentation here, and, in this reader, passed as the second
argument to the constructor.
@return  object[]

Use the parser to parse a docblock into annotations and create annotation objects .


public static function fromMemory(string $prefix = ''): SqliteConnection
    {
        $pdo = new \PDO('sqlite::memory:');
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $pdo->exec("PRAGMA foreign_keys = ON");

        return new static($pdo, $prefix);
    }

public
static
function
fromMemory
(
string
$
prefix
=
''
)
:
SqliteConnection
{
$
pdo
=
new
\
PDO
(
'sqlite::memory:'
)
;
$
pdo
->
setAttribute
(
\
PDO
::
ATTR_ERRMODE
,
\
PDO
::
ERRMODE_EXCEPTION
)
;
$
pdo
->
exec
(
"PRAGMA foreign_keys = ON"
)
;
return
new
static
(
$
pdo
,
$
prefix
)
;
}

Create an in-memory Sqlite database, very fast but not durable!

@param string $prefix DB schema object prefix to be used.

Create an in - memory Sqlite database very fast but not durable!


public static function fromFile(string $file, string $prefix = ''): SqliteConnection
    {
        $pdo = new \PDO('sqlite:' . $file);
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $pdo->exec("PRAGMA foreign_keys = ON");

        return new static($pdo, $prefix);
    }

public
static
function
fromFile
(
string
$
file
,
string
$
prefix
=
''
)
:
SqliteConnection
{
$
pdo
=
new
\
PDO
(
'sqlite:'
.
$
file
)
;
$
pdo
->
setAttribute
(
\
PDO
::
ATTR_ERRMODE
,
\
PDO
::
ERRMODE_EXCEPTION
)
;
$
pdo
->
exec
(
"PRAGMA foreign_keys = ON"
)
;
return
new
static
(
$
pdo
,
$
prefix
)
;
}

Create a Sqlite DB using the given file to store data.

@param string $file Absolute path of the DB file.
@param string $prefix DB schema object prefix to be used.

Create a Sqlite DB using the given file to store data .


protected function getField(string $f) : ?iField
    {
        $r = null;
        if ($this->hasField($f)) {
            $r = $this->fieldsCollection[strtolower($f)];
        }
        return $r;
    }

protected function getField ( string $ f ) : ? iField { $ r = null ; if ( $ this -> hasField ( $ f ) ) { $ r = $ this -> fieldsCollection [ strtolower ( $ f ) ] ; } return $ r ; }

Retorna o objeto "iField" referente ao campo
de nome indicado.

@param       string $f
Nome do campo que será retornado.

@return      ?iField

Retorna o objeto iField referente ao campo de nome indicado .


public function hasField(string $f) : bool
    {
        return (isset($this->fieldsCollection[strtolower($f)]) === true);
    }

public function hasField ( string $ f ) : bool { return ( isset ( $ this -> fieldsCollection [ strtolower ( $ f ) ] ) === true ) ; }

Identifica se o campo com o nome indicado
existe neste modelo de dados.

@param       string $f
Nome do campo que será verificado.

@return      bool

Identifica se o campo com o nome indicado existe neste modelo de dados .


public function getFieldNames() : array
    {
        $r = [];
        foreach ($this->fieldsCollection as $fieldName => $field) {
            $r[] = $field->getName();
        }
        return $r;
    }

public function getFieldNames ( ) : array { $ r = [ ] ; foreach ( $ this -> fieldsCollection as $ fieldName => $ field ) { $ r [ ] = $ field -> getName ( ) ; } return $ r ; }

Retorna um array contendo o nome de cada um dos campos existentes
neste modelo de dados.

@return      array

Retorna um array contendo o nome de cada um dos campos existentes neste modelo de dados .


public function getInitialDataModel() : array
    {
        $r = [];
        foreach ($this->fieldsCollection as $fieldName => $field) {
            $r[$field->getName()] = $field->getDefault();
        }
        return $r;
    }

public function getInitialDataModel ( ) : array { $ r = [ ] ; foreach ( $ this -> fieldsCollection as $ fieldName => $ field ) { $ r [ $ field -> getName ( ) ] = $ field -> getDefault ( ) ; } return $ r ; }

Retorna um array associativo contendo todos os campos definidos
para o modelo atual e seus respectivos valores iniciais.

@return      array

Retorna um array associativo contendo todos os campos definidos para o modelo atual e seus respectivos valores iniciais .


protected function authorizeIndex(Request $request)
    {
        $this->authorizeCrudRequest(Action::INDEX, null, $this->getParent($request));
    }

protected function authorizeIndex ( Request $ request ) { $ this -> authorizeCrudRequest ( Action :: INDEX , null , $ this -> getParent ( $ request ) ) ; }

Checks if user is authorized to watch an index of the entities.
@param Request $request

Checks if user is authorized to watch an index of the entities .


protected function authorizeCreate(Request $request)
    {
        $this->authorizeCrudRequest(Action::CREATE, null, $this->getParent($request));
    }

protected function authorizeCreate ( Request $ request ) { $ this -> authorizeCrudRequest ( Action :: CREATE , null , $ this -> getParent ( $ request ) ) ; }

Checks if user is authorized to create an entity.
@param Request $request

Checks if user is authorized to create an entity .


public function getNestedItem($pattern, $object, $default = null)
    {
        $parts = explode("/", $pattern);
        $lastObject = $object;
        $nr = 0;
        $totalParts = count($parts);
        $item = null;
        foreach ($parts as $part) {
            $item = null;
            $nr++;
            $found = false;
            if ($part == '') {
                return $default;
            }
            try {
                if (is_object($lastObject)) {
                    $mthd = 'get' . ucfirst($part);
                    $mthdIs = 'is' . ucfirst($part);
                    if (substr($part, 0, 2) == '::') {
                        $reflect = new \ReflectionObject($lastObject);
                        $props = $reflect->getStaticProperties();
                        $nm = substr($part, 2);
                        if (isset($props[$nm])) {
                            $prop = $reflect->getProperty($nm);
                            if ($prop->isPublic()) {
                                $item = $lastObject::$$nm;
                            }
                        }
                    } elseif (is_callable([$lastObject, $mthd])) {
                        $item = $lastObject->$mthd();
                    } elseif (is_callable([$lastObject, $mthdIs])) {
                        $item = $lastObject->$mthdIs();
                    } elseif (is_callable([$lastObject, $part])) {
                        $item = $lastObject->$part();
                    } else {
                        $reflect = new \ReflectionObject($lastObject);
                        $prop = $reflect->getProperty($part);
                        if ($prop->isPublic()) {
                            $item = $lastObject->$part;
                        }
                    }
                    $found = true;
                } elseif (is_array($lastObject)) {
                    if (array_key_exists($part, $lastObject)) {
                        $item = $lastObject[$part];
                        $found = true;
                    }
                }
            } catch (\Exception $e) {
                return $default;
            }
            if ((!is_null($item) && !is_object($item) && !is_array($item) && $nr < $totalParts) || !$found) {
                //its a string,boolean or integer , but we're not at the end of the list so we can't find the end
                return $default;
            }
            $lastObject = $item;
        }
        return $item;
    }

Gets a nested value from an object

@param string $pattern
@param mixed  $object
@param mixed  $default
@return mixed|null


public function init()
    {
        $device = '';
        $style = '';
        if (!isset($_SERVER['HTTP_USER_AGENT'])) {
            return;
        }
        if (stristr($_SERVER['HTTP_USER_AGENT'], 'ipad')) {
            $device = "ipad";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'iphone')
                || strstr($_SERVER['HTTP_USER_AGENT'], 'ipod')) {
            $device = "iphone";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'blackberry')) {
            $device = "blackberry";
            $style = "touch";
        } else if (stristr($_SERVER['HTTP_USER_AGENT'], 'android')) {
            $device = "android";
            $style = "touch";
        }

        $this->_userAgent = $device;
        $this->_style = $style;
        if ($device != '' && $style == 'touch') {
            $this->_isTouch = true;
            $this->_device = 'mobile';
        } else {
            $this->_isTouch = false;
            $this->_device = 'desktop';
        }
    }

public function init ( ) { $ device = '' ; $ style = '' ; if ( ! isset ( $ _SERVER [ 'HTTP_USER_AGENT' ] ) ) { return ; } if ( stristr ( $ _SERVER [ 'HTTP_USER_AGENT' ] , 'ipad' ) ) { $ device = "ipad" ; $ style = "touch" ; } else if ( stristr ( $ _SERVER [ 'HTTP_USER_AGENT' ] , 'iphone' ) || strstr ( $ _SERVER [ 'HTTP_USER_AGENT' ] , 'ipod' ) ) { $ device = "iphone" ; $ style = "touch" ; } else if ( stristr ( $ _SERVER [ 'HTTP_USER_AGENT' ] , 'blackberry' ) ) { $ device = "blackberry" ; $ style = "touch" ; } else if ( stristr ( $ _SERVER [ 'HTTP_USER_AGENT' ] , 'android' ) ) { $ device = "android" ; $ style = "touch" ; } $ this -> _userAgent = $ device ; $ this -> _style = $ style ; if ( $ device != '' && $ style == 'touch' ) { $ this -> _isTouch = true ; $ this -> _device = 'mobile' ; } else { $ this -> _isTouch = false ; $ this -> _device = 'desktop' ; } }


public function getExportImplementor()
    {
        $export = new Parameters($this->config->get('export', array()));
        return $export->get(self::PARAM_CLASS, 'Environaut\Export\Export');
    }

public function getExportImplementor ( ) { $ export = new Parameters ( $ this -> config -> get ( 'export' , array ( ) ) ) ; return $ export -> get ( self :: PARAM_CLASS , 'Environaut\Export\Export' ) ; }

Defaults to "Environaut\Export\Export".

@return string (namespaced) class name to use for exporting a report

Defaults to Environaut \ Export \ Export .


public function getReportImplementor()
    {
        $report = new Parameters($this->config->get('report', array()));
        return $report->get(self::PARAM_CLASS, 'Environaut\Report\Report');
    }

public function getReportImplementor ( ) { $ report = new Parameters ( $ this -> config -> get ( 'report' , array ( ) ) ) ; return $ report -> get ( self :: PARAM_CLASS , 'Environaut\Report\Report' ) ; }

Defaults to "Environaut\Report\Report".

@return string (namespaced) class name to use for a report

Defaults to Environaut \ Report \ Report .


public function getRunnerImplementor()
    {
        $runner = new Parameters($this->config->get('runner', array()));
        return $runner->get(self::PARAM_CLASS, 'Environaut\Runner\Runner');
    }

public function getRunnerImplementor ( ) { $ runner = new Parameters ( $ this -> config -> get ( 'runner' , array ( ) ) ) ; return $ runner -> get ( self :: PARAM_CLASS , 'Environaut\Runner\Runner' ) ; }

Defaults to "Environaut\Runner\Runner".

@return string (namespaced) class name to use for running checks read from the config

Defaults to Environaut \ Runner \ Runner .


public function getCacheImplementor()
    {
        $cache = new Parameters($this->config->get('cache', array()));
        return $cache->get(self::PARAM_CLASS, 'Environaut\Cache\Cache');
    }

public function getCacheImplementor ( ) { $ cache = new Parameters ( $ this -> config -> get ( 'cache' , array ( ) ) ) ; return $ cache -> get ( self :: PARAM_CLASS , 'Environaut\Cache\Cache' ) ; }

Defaults to "Environaut\Cache\Cache".

@return string (namespaced) class name to use for writing cachable settings after report generation

Defaults to Environaut \ Cache \ Cache .


public function buildUpdateSQL($dataObj)
    {
        // generate column value pairs. ignore those whose inputValue=fieldValue
        $sqlFlds = $dataObj->bizRecord->getToSaveFields('UPDATE');
        $colval_pairs = null;
        foreach ($sqlFlds as $field) {
            $col = $field->column;

            // ignore empty vallue for Date or Datetime
            if (($field->value == "" && $field->oldValue == "") && ($field->type == "Date" || $field->type == "Datetime"))
                continue;

            if ($field->valueOnUpdate != "") // ignore ValueOnUpdate field first
                continue;

            if ($field->isLobField())  // take care of blob/clob type later
                continue;

            // ignore the column where old value is same as new value; set the column only if new value is diff than the old value
            if ($field->oldValue == $field->value)
                continue;

            $_val = $field->getSqlValue();
            $colval_pairs[$col] = $_val; //($_val===null || $_val === '') ? "''" : $_val;
        }
        if ($colval_pairs == null)
            return false;

        // take care value on update fields only
        foreach ($sqlFlds as $field) {
            $col = $field->column;
            if ($field->valueOnUpdate != "") {
                $_val = $field->getValueOnUpdate();
                $colval_pairs[$col] = $_val; //($_val===null || $_val === '') ? "''" : $_val;
            }
        }

        $db = $dataObj->getDBConnection('WRITE');
        $sql = "";
        foreach ($colval_pairs as $col => $val) {
            //$queryString = QueryStringParam::formatQueryString("`$col`", "=", $val);
            $queryString = "`$col`=" . $db->quote($val);
            if ($sql != "") {
                $sql .= ", $queryString";
            } else {
                $sql .= $queryString;
            }
        }

        $sql = "UPDATE `" . $dataObj->mainTableName . "` SET " . $sql;

        $whereStr = $dataObj->bizRecord->getKeySearchRule(true, true);  // use old value and column name
        $sql .= " WHERE " . $whereStr;

        // append DataPerm in the WHERE clause
        if ($dataObj->dataPermControl == 'Y') {
            $svcObj = Openbizx::getService(OPENBIZ_DATAPERM_SERVICE);
            $hasOwnerField = $this->_hasOwnerField($dataObj);
            $dataPermSQLRule = $svcObj->buildSqlRule($dataObj, 'update', $hasOwnerField);
            $sqlSearchRule = $this->_convertSqlExpressionWithoutPrefix($dataObj, $dataPermSQLRule);
            if ($whereStr != '') {
                $sql .= ' AND ' . $sqlSearchRule;
            } else {
                $sql .= $sqlSearchRule;
            }
        }
        return $sql;
    }

Build update sql
UPDATE table SET col1=val1, col2=val2 ...
WHERE idcol1='id1' AND idcol2='id2'

@param BizDataObj $dataObj
@return mixed
@todo consider the record data on main table as well as join table, this function can return a sql array.


public function buildDeleteSQL($dataObj)
    {
        $sql = "DELETE FROM `" . $dataObj->mainTableName . "`";
        $whereStr = $dataObj->bizRecord->getKeySearchRule(false, true);  // use cur value and column name
        $sql .= " WHERE " . $whereStr;
        // append DataPerm in the WHERE clause
        if ($dataObj->dataPermControl == 'Y') {
            $svcObj = Openbizx::getService(OPENBIZ_DATAPERM_SERVICE);
            $hasOwnerField = $this->_hasOwnerField($dataObj);
            $dataPermSQLRule = $svcObj->buildSqlRule($dataObj, 'delete', $hasOwnerField);
            $sqlSearchRule = $this->_convertSqlExpressionWithoutPrefix($dataObj, $dataPermSQLRule);
            if ($whereStr != '') {
                $sql .= ' AND ' . $sqlSearchRule;
            } else {
                $sql .= $sqlSearchRule;
            }
        }
        return $sql;
    }

public
function
buildDeleteSQL
(
$
dataObj
)
{
$
sql
=
"DELETE FROM `"
.
$
dataObj
->
mainTableName
.
"`"
;
$
whereStr
=
$
dataObj
->
bizRecord
->
getKeySearchRule
(
false
,
true
)
;
// use cur value and column name
$
sql
.=
" WHERE "
.
$
whereStr
;
// append DataPerm in the WHERE clause
if
(
$
dataObj
->
dataPermControl
==
'Y'
)
{
$
svcObj
=
Openbizx
::
getService
(
OPENBIZ_DATAPERM_SERVICE
)
;
$
hasOwnerField
=
$
this
->
_hasOwnerField
(
$
dataObj
)
;
$
dataPermSQLRule
=
$
svcObj
->
buildSqlRule
(
$
dataObj
,
'delete'
,
$
hasOwnerField
)
;
$
sqlSearchRule
=
$
this
->
_convertSqlExpressionWithoutPrefix
(
$
dataObj
,
$
dataPermSQLRule
)
;
if
(
$
whereStr
!=
''
)
{
$
sql
.=
' AND '
.
$
sqlSearchRule
;
}
else
{
$
sql
.=
$
sqlSearchRule
;
}
}
return
$
sql
;
}

Build delete-sql DELETE FROM table WHERE idcol1='id1' AND idcol2='id2'

@param BizDataObj $dataObj
@return string SQL statement

Build delete - sql DELETE FROM table WHERE idcol1 = id1 AND idcol2 = id2


protected function getStyle()
    {
        $htmlClass = $this->cssClass ? "class='" . $this->cssClass . "' " : "class='editcombobox'";
        /*
          $width = $this->width ? $this->width : 146;
          $this->widthInput = ($width-18).'px';
          $this->width = $width.'px';
          $style = "position: absolute; width: $this->width; z-index: 1; clip: rect(auto, auto, auto, $this->widthInput);";
         */
        if ($this->style)
            $style .= $this->style;
        if (!isset($style) && !$htmlClass)
            return null;
        if (isset($style)) {
            $formObj = $this->getFormObj();
            $style = Expression::evaluateExpression($style, $formObj);
            $style = "style='$style'";
        }
        if ($htmlClass) {
            $style = $htmlClass . " " . $style;
        }
        return $style;
    }

Get style of element

@return string style of Element


public function getChildNodes()
    {
        $prefix = $this->ownerDocument->getDefaultNamespacePrefix();

        if ($prefix) {
            return $this->ownerDocument->getXpath()->query(sprintf('child::%s:*', $prefix), $this);
        } else {
            return $this->ownerDocument->getXpath()->query('child::*', $this);
        }
    }

public function getChildNodes ( ) { $ prefix = $ this -> ownerDocument -> getDefaultNamespacePrefix ( ) ; if ( $ prefix ) { return $ this -> ownerDocument -> getXpath ( ) -> query ( sprintf ( 'child::%s:*' , $ prefix ) , $ this ) ; } else { return $ this -> ownerDocument -> getXpath ( ) -> query ( 'child::*' , $ this ) ; } }

Returns a \DOMNodeList of all child elements of the element.

@return \DOMNodeList of all child elements

Returns a \ DOMNodeList of all child elements of the element .


public function getAttributeValue($name, $default_value = null)
    {
        $value = parent::getAttribute($name);

        if ($value === '') {
            $value = $default_value;
        }

        return $value;
    }

public function getAttributeValue ( $ name , $ default_value = null ) { $ value = parent :: getAttribute ( $ name ) ; if ( $ value === '' ) { $ value = $ default_value ; } return $ value ; }

Returns the value of the given attribute or returns the given
default value if the attribute is missing.

@param string $name name of attribute
@param mixed $default_value value to return if attribute is missing

@return mixed string value of attribute or default_value if attribute is not found or empty

Returns the value of the given attribute or returns the given default value if the attribute is missing .


public function getAttributes()
    {
        $attributes = array();

        foreach ($this->ownerDocument->getXpath()->query('@*', $this) as $attribute) {
            $attributes[$attribute->localName] = $attribute->nodeValue;
        }

        return $attributes;
    }

public function getAttributes ( ) { $ attributes = array ( ) ; foreach ( $ this -> ownerDocument -> getXpath ( ) -> query ( '@*' , $ this ) as $ attribute ) { $ attributes [ $ attribute -> localName ] = $ attribute -> nodeValue ; } return $ attributes ; }

Returns all attributes including their values for the element.

@return array of attributes (name => value pairs)

Returns all attributes including their values for the element .


public function getChild($name)
    {
        $query = 'self::node()[count(child::*[local-name() = "%1$s" and namespace-uri() = "%2$s"]) = 1]/*' .
                '[local-name() = "%1$s" and namespace-uri() = "%2$s"]';

        $node = $this->ownerDocument->getXpath()->query(
            sprintf($query, $name, $this->ownerDocument->getDefaultNamespaceUri()),
            $this
        )->item(0);

        return $node;
    }

Returns first child of the element with the given name.

@param string $name name of element to get

@return \DOMNode first child node with the given name

Returns first child of the element with the given name .


protected function getLiteralValue($element)
    {
        $value = $element->getValue();
        $trimmed_value = trim($value);

        $preserve_whitespace = $element->getAttributeValue('space', 'default') === 'preserve';
        $literalize_value = self::literalize($element->getAttributeValue('literalize')) !== false;

        if ($literalize_value) {
            if ($preserve_whitespace && ($trimmed_value === '' || $value !== $trimmed_value)) {
                $value = $value;
            } else {
                $value = self::literalize($trimmed_value);
            }
        } elseif (!$preserve_whitespace) {
            $value = $trimmed_value;
            if ($value === '') {
                $value = null;
            }
        }

        return $value;
    }

protected function getLiteralValue ( $ element ) { $ value = $ element -> getValue ( ) ; $ trimmed_value = trim ( $ value ) ; $ preserve_whitespace = $ element -> getAttributeValue ( 'space' , 'default' ) === 'preserve' ; $ literalize_value = self :: literalize ( $ element -> getAttributeValue ( 'literalize' ) ) !== false ; if ( $ literalize_value ) { if ( $ preserve_whitespace && ( $ trimmed_value === '' || $ value !== $ trimmed_value ) ) { $ value = $ value ; } else { $ value = self :: literalize ( $ trimmed_value ) ; } } elseif ( ! $ preserve_whitespace ) { $ value = $ trimmed_value ; if ( $ value === '' ) { $ value = null ; } } return $ value ; }

Depending on the values of the 'literalize' and 'space' attributes of the element
the transformed or literal value of the value is returned

@param \DOMNode $element element to get a value for

@return mixed literalized and/or whitespace preserved value or null if value is empty

Depending on the values of the literalize and space attributes of the element the transformed or literal value of the value is returned


private function cacheIfConfigured($closure)
    {
        if (config('menu.cache.enable')) {
            $key = config('menu.cache.key');
            $minutes = config('menu.cache.minutes');

            return Cache::remember($key, $minutes, function () use ($closure) {
                return call_user_func($closure);
            });
        }

        return call_user_func($closure);
    }

private function cacheIfConfigured ( $ closure ) { if ( config ( 'menu.cache.enable' ) ) { $ key = config ( 'menu.cache.key' ) ; $ minutes = config ( 'menu.cache.minutes' ) ; return Cache :: remember ( $ key , $ minutes , function ( ) use ( $ closure ) { return call_user_func ( $ closure ) ; } ) ; } return call_user_func ( $ closure ) ; }

uses the cache if it was configured or calculates
the plain output every request otherwise.

@param $closure

@return array

uses the cache if it was configured or calculates the plain output every request otherwise .


public function handle(array &$arguments, string $callType = Caller::TYPE_DEFAULT)
    {
        if ($this->isValid()) {
            $this->callType = $callType;
            $method = $this->getMethod();
            $context = $this->getContext();
            return $context->$method(...$arguments);
        }
    }

public function handle ( array & $ arguments , string $ callType = Caller :: TYPE_DEFAULT ) { if ( $ this -> isValid ( ) ) { $ this -> callType = $ callType ; $ method = $ this -> getMethod ( ) ; $ context = $ this -> getContext ( ) ; return $ context -> $ method ( ... $ arguments ) ; } }

Handle the arguments passed to the middleware and return the new response.
By default, this will automatically try to call a class method that corresponds
to the method named give to the object.

@param array $arguments
@return null

Handle the arguments passed to the middleware and return the new response . By default this will automatically try to call a class method that corresponds to the method named give to the object .


public function isValid(string $method = null): bool
    {
        if ($method === null) {
            $method = $this->getMethod();
        }
        return $this->isEnabled() && $this->methodIsCallable($method);
    }

public function isValid ( string $ method = null ) : bool { if ( $ method === null ) { $ method = $ this -> getMethod ( ) ; } return $ this -> isEnabled ( ) && $ this -> methodIsCallable ( $ method ) ; }

Checks the given method and determines if it passed the black and white lists and can be called.

@param string $method
@return bool

Checks the given method and determines if it passed the black and white lists and can be called .


protected function isGetter(): bool
    {
        $isExternalObject = is_object($this->context) && $this->context instanceof static === false;
        return $this->callType === Caller::TYPE_GETTER && $isExternalObject;
    }

protected function isGetter ( ) : bool { $ isExternalObject = is_object ( $ this -> context ) && $ this -> context instanceof static === false ; return $ this -> callType === Caller :: TYPE_GETTER && $ isExternalObject ; }


protected function isSetter(): bool
    {
        $isExternalObject = is_object($this->context) && $this->context instanceof static === false;
        return $this->callType === Caller::TYPE_SETTER && $isExternalObject;
    }

protected function isSetter ( ) : bool { $ isExternalObject = is_object ( $ this -> context ) && $ this -> context instanceof static === false ; return $ this -> callType === Caller :: TYPE_SETTER && $ isExternalObject ; }


public function prepareCall( Client $client = null ) {
        // Set the default client:
        $this->curlClient = null;
        $client           = null;

        $this->log( 'prepare ' . __CLASS__ . ' GuzzleRequest: base_uri(' . $this->getBaseUri() . '), client(' . ( (bool) is_null( $client ) ) . '), timeout(' . $this->getCurlTimeout() . '), ', 'debug');

        // Check if baseUri is set or that $client is set (make pass trough client available else set the client self)
        if ( $this->getBaseUri() !== null && $client === null ) {
            // Initialize the Client:
            $this->curlClient = new Client( [
                // Base URI is used with relative requests
                'base_uri' => $this->getBaseUri(),

                // You can set any number of default request options.
                'timeout'  => 2.0,
            ] );
        } else if ( $client !== null ) {
            $this->curlClient = $client;
        }
    }

Prepare the Guzzle Client

@param Client|null $client


public function getResponse( $type = self::RESPONSE_TYPE_JSON ) {
        // Check if response is set
        if ( $this->response === null ) {
            return null;
        }

        try {
            // Get the stream from the response getBody() method returns a stream instead of a string.
            $stream = $this->response->getBody();

            // Get the body from the stream.
            $body = $stream->getContents();

            if ( empty( $body ) ) {
                return null;
            }

            switch ( $type ) {
                default:
                case self::RESPONSE_TYPE_JSON:
                    return $this->getResponseJSON( $body );
                    break;
                case self::RESPONSE_TYPE_XML:
                    return (string) $body;
                    break;
                case self::RESPONSE_TYPE_HTML:
                    return (string) $body;
                    break;
                case self::RESPONSE_TYPE_TEXT:
                    return (string) $body;
                    break;
                case self::RESPONSE_ORIGINAL:
                    return $this->response;
                    break;
            }
        }
        catch ( BadResponseException $exception ) {
            return null;
        }
        catch ( \Exception $exception ) {
            return null;
        }
    }

Get the response body from the response and try to parse it to array or object.

@param string $type

@return null|string|BaseResponseInterface

Get the response body from the response and try to parse it to array or object .


private function getResponseJSON( $body ) {
        try {
            return json_decode( (string) $body, true );
        }
        catch ( \Exception $e ) {
            throw new \RuntimeException( 'Invalid JSON ' . $e->getMessage(), 0, $body );
        }
    }

private
function
getResponseJSON
(
$
body
)
{
try
{
return
json_decode
(
(
string
)
$
body
,
true
)
;
}
catch
(
\
Exception
$
e
)
{
throw
new
\
RuntimeException
(
'Invalid JSON '
.
$
e
->
getMessage
(
)
,
0
,
$
body
)
;
}
}

Decode the JSON String

@param string $body JSON encoded string

@return string


public function saveObjVar($objName, $varName, &$value, $stateful = false)
    {
        if (preg_match('/\./si', $objName)) {
            $objName = $this->getNamespace() . '#' . $objName;
        }
        if (!$stateful) {
            $this->_sessObjArr[$objName][$varName] = $value;
        } else {
            $this->_statefulSessObjArr[$objName][$varName] = $value;
        }
    }

public function saveObjVar ( $ objName , $ varName , & $ value , $ stateful = false ) { if ( preg_match ( '/\./si' , $ objName ) ) { $ objName = $ this -> getNamespace ( ) . '#' . $ objName ; } if ( ! $ stateful ) { $ this -> _sessObjArr [ $ objName ] [ $ varName ] = $ value ; } else { $ this -> _statefulSessObjArr [ $ objName ] [ $ varName ] = $ value ; } }

Set single session variable of a stateful object

@param string $objName - object name
@param string $varName - vaiable name
@param mixed $value - reference of the value (in/out)
@param boolean $stateful - is stateful?
@return void


public function loadObjVar($objName, $varName, &$value, $stateful = false)
    {
        //Openbizx::$app->getLog()->log(LOG_ALERT, __METHOD__, ' | name : ' . $varName . ' | value : ' . $value);
        //Openbizx::$app->getClientProxy()->showClientAlert( __METHOD__ . ' | name : ' . $varName . ' | value : ' . $value);

        if (preg_match('/\./si', $objName)) {
            $objName = $this->getNamespace() . '#' . $objName;
        }
        if (!$stateful) {
            if (!$this->_sessObjArr) {
                return null;
            }
            if (isset($this->_sessObjArr[$objName][$varName])) {
                $value = $this->_sessObjArr[$objName][$varName];
            }
        } else {
            if (!$this->_statefulSessObjArr) {
                return null;
            }
            if (isset($this->_statefulSessObjArr[$objName][$varName])) {
                $value = $this->_statefulSessObjArr[$objName][$varName];
            }
        }
    }

Get single session variable of a stateful object

@param string $objName - object name
@param string $varName - vaiable name
@param mixed $value - reference of the value (in/out)
@param boolean $stateful - is stateful?
@return void


public function saveSessionObjects()
    {
        // loop all objects (bizview, bizform, bizdataobj) collect their session vars
        $allobjs = Openbizx::objectFactory()->getAllObjects();
        foreach ($allobjs as $obj) {
            if (method_exists($obj, "saveStatefullVars")) {
                //after calling $obj->saveStatefullVars SessObjArr and StatefulSessObjArr are filled
                $obj->saveStatefullVars($this);
            }
            // if previous view's object is used in current view, don't discard its session data
            if ( isset($obj->objectName) && isset($this->_prevViewObjNames[$obj->objectName]) ) {
                unset( $this->_prevViewObjNames[$obj->objectName] );
                Openbizx::$app->getLog()->log( LOG_ERR, "SESSION", "unset " . $obj->objectName );
            }
        }

        // discard useless previous view's session objects
        //foreach($this->_prevViewObjNames as $objName=>$tmp)
        //    unset($this->_sessObjArr[$objName]);

        $this->_sessObjArr["ViewHist"] = $this->_viewHistory;

        $this->setVar(OB_TRANSIENT_DATA_SESSION_INDEX, $this->_sessObjArr);
        $this->setVar(OB_STATEFUL_DATA_SESSION_INDEX, $this->_statefulSessObjArr);
    }

//    unset($this->_sessObjArr[$objName]);

Save session variables of all stateful objects into sessionid_obj file

@return void


public function clearSessionObjects($keepObjects = false)
    {
        if ($keepObjects == false) {
            unset($this->_sessObjArr);
            $this->_sessObjArr = array();
        } else { // add previous view's session object names in to a map
            if (isset($this->_sessObjArr)) {
                foreach ($this->_sessObjArr as $objName => $sessobj) {
                    //echo "save sess $objName <br/>";
                    $this->_prevViewObjNames[$objName] = 1;
                }
            }
        }
    }

Clear session variables of all stateful objects

@param boolean $keepObjects
@return void


public function saveJSONArray($jsonValue, $jsonName = NULL)
    {
        $jsonArray = json_decode($jsonValue);

        if ((bool) $jsonName) { //If I want save all array in session I send the name of the array in session
            $this->setVar($jsonName, $jsonArray);
        } else {//I save each value in session
            foreach ($jsonArray as $varName => $value) {
                $this->setVar($varName, $value);
            }
        }
    }

Save a JSON array in session

@param string $jsonValue
@param string $jsonName
@return void


public function setViewHistory($formName, $historyInfo)
    {
        $view = Openbizx::$app->getCurrentViewName();
        $view_form = $formName; //$view."_".$formname;
        if (!$historyInfo) {
            unset($this->_viewHistory[$view_form]);
        } else {
            $this->_viewHistory[$view_form] = $historyInfo;
        }
    }

public function setViewHistory ( $ formName , $ historyInfo ) { $ view = Openbizx :: $ app -> getCurrentViewName ( ) ; $ view_form = $ formName ; //$view."_".$formname; if ( ! $ historyInfo ) { unset ( $ this -> _viewHistory [ $ view_form ] ) ; } else { $ this -> _viewHistory [ $ view_form ] = $ historyInfo ; } }

Set view history data of given bizform into session file

@param string $formName - name of bizform
@param array $historyInfo - view history data represented by an associated array
@return void


public function tic($flag = self::RESET_COUNTER)
    {
        $this->start = microtime(true);
        if ($flag) {
            $this->count = 0;
        }
    }

public function tic ( $ flag = self :: RESET_COUNTER ) { $ this -> start = microtime ( true ) ; if ( $ flag ) { $ this -> count = 0 ; } }

Starts timer.
@param  int $flag self::RESET_COUNTER|self::KEEP_COUNTER
@return void


public function toc($message = '')
    {
        $this->stop = microtime(true);
        ++$this->count;
        $this->elapsed = ($this->stop - $this->start ) * 1e6 - $this->calib;
        print $this;
        if ($message) {
            print $message . "\n";
        }
    }

public function toc ( $ message = '' ) { $ this -> stop = microtime ( true ) ; ++ $ this -> count ; $ this -> elapsed = ( $ this -> stop - $ this -> start ) * 1e6 - $ this -> calib ; print $ this ; if ( $ message ) { print $ message . "\n" ; } }

Stops timer and displays elapsed time.
@param  string $message is an optional user message.
@return void


public function tac($flag = self::ADD_LAP)
    {
        $this->stop = microtime(true);
        if ($flag) {
            $this->elapsed = ($this->stop - $this->start) * 1e6
            - $this->calib;
        } else {
            $this->elapsed += ($this->stop - $this->start) * 1e6
            - $this->calib;
        }
        ++$this->count;
    }

public function tac ( $ flag = self :: ADD_LAP ) { $ this -> stop = microtime ( true ) ; if ( $ flag ) { $ this -> elapsed = ( $ this -> stop - $ this -> start ) * 1e6 - $ this -> calib ; } else { $ this -> elapsed += ( $ this -> stop - $ this -> start ) * 1e6 - $ this -> calib ; } ++ $ this -> count ; }

Keeps lap time.
@param  int $flag Takes values self::ADD_LAP|self::RESET_LAP
@return void


public function reset()
    {
        $this->count = 0;
        $this->elapsed = 0;
        $this->start = 0;
        $this->stop = 0;
        return $this;
    }

public function reset ( ) { $ this -> count = 0 ; $ this -> elapsed = 0 ; $ this -> start = 0 ; $ this -> stop = 0 ; return $ this ; }


public function validExecutable($value)
    {
        $val = trim($value);

        if (empty($val)) {
            throw new \InvalidArgumentException(
                'Not a valid executable path. Please specify a command (like "ls") or a path (like "/usr/bin/ls").'
            );
        }

        $executable = trim(shell_exec('which ' . $val));
        if (!$executable) {
            throw new \InvalidArgumentException('Could not find executable: ' . $val);
        }

        $command = $this->parameters->get('command', $this->getName());
        $cli_option = $this->parameters->get('version_parameter', '--version');
        $version_mask = $this->parameters->get('version_mask', '/Version/');

        if ($version_mask) {
            $version_info_raw = trim(shell_exec('cat /dev/null | ' . $executable . ' ' . $cli_option . ' 2>&1'));
            if (!preg_match($version_mask, $version_info_raw, $matches, PREG_OFFSET_CAPTURE)) {
                throw new \InvalidArgumentException(
                    'Could not get version information for "' . $command . '" using "' . $executable . '".'
                );
            }
        }

        return $executable;
    }

Checks whether the given input value leads to an executable that
matches the configured version_mask parameter.

@param string $value path to an executable

@return string absolute path to executable

@throws \InvalidArgumentException in case of non-existing executable at the given path or version mismatch

Checks whether the given input value leads to an executable that matches the configured version_mask parameter .


public function getRedirectPage()
    {
        // get the control that issues the call
        // __this is elementName:eventHandlerName
        list($element, $eventHandler) = $this->getInvokingElement();
        $eventHandlerName = $eventHandler->objectName;
        $redirectPage = $element->getRedirectPage($eventHandlerName); // need to get postaction of eventhandler
        $functionType = $element->getFunctionType($eventHandlerName);
        switch ($functionType)
        {
            case "Popup":
                $target = "Popup";
                break;
            default:
                $target = "";
        }
        return array($redirectPage, $target);
    }

return redirect page and target array

@return array {redirectPage, $target}


public function processDataException($e)
    {
        $errorMsg = $e->getMessage();
        Openbizx::$app->getLog()->log(LOG_ERR, "DATAOBJ", "DataObj error = ".$errorMsg);
        //Openbizx::$app->getClientProxy()->showClientAlert($errorMsg);   //showErrorMessage($errorMsg);
        //Openbizx::$app->getClientProxy()->showErrorMessage($errorMsg);
        $e->no_exit=true;
	    ErrorHandler::exceptionHandler($e);
    }

Handle the exception from DataObj method,
report the error as an alert window

@param int $errCode
@return string

Handle the exception from DataObj method report the error as an alert window


protected function processURL()
    {
        // if url has form=...
        $paramForm = isset($_GET['form']) ? $_GET['form'] : null;
        $paramCForm = isset($_GET['cform']) ? $_GET['cform'] : null;

        if (!$paramForm)
            return;

        // add the form in FormRefs
        if ($paramForm)
        {
        	if($this->isInFormRefLibs($paramForm))
	        	{
	            $xmlArr["ATTRIBUTES"]["NAME"] = $paramForm;
	            $xmlArr["ATTRIBUTES"]["SUBFORMS"] = $paramCForm ? $paramCForm : "";
	            $formRef = new FormReference($xmlArr);
	            $this->formRefs->set($paramForm, $formRef);
	            if ($paramCForm)
	            {
	            	if($this->isInFormRefLibs($paramCForm))
	            	{
		                $xmlArr["ATTRIBUTES"]["NAME"] = $paramCForm;
		                $xmlArr["ATTRIBUTES"]["SUBFORMS"] = "";
		                $cformRef = new FormReference($xmlArr);
		                $this->formRefs->set($paramCForm, $cformRef);
	            	}
	            }
        	}
        }

        // check url arg as fld:name=val
        $getKeys = array_keys($_GET);
        $paramFields = null;
        foreach ($getKeys as $key)
        {
            if (substr($key, 0, 4) == "fld:")
            {
                $fieldName = substr($key, 4);
                $fieldValue = $_GET[$key];
                $paramFields[$fieldName] = $fieldValue;
            }
        }

        if (!$paramFields)
            return;

        $paramForm = $this->prefixPackage($paramForm);
        $formObj = Openbizx::getObject($paramForm);
        $formObj->setRequestParams($paramFields);
    }

protected
function
processURL
(
)
{
// if url has form=...
$
paramForm
=
isset
(
$
_GET
[
'form'
]
)
$
_GET
[
'form'
]
:
;
$
paramCForm
=
isset
(
$
_GET
[
'cform'
]
)
$
_GET
[
'cform'
]
:
;
if
(
!
$
paramForm
)
return
;
// add the form in FormRefs
if
(
$
paramForm
)
{
if
(
$
this
->
isInFormRefLibs
(
$
paramForm
)
)
{
$
xmlArr
[
"ATTRIBUTES"
]
[
"NAME"
]
=
$
paramForm
;
$
xmlArr
[
"ATTRIBUTES"
]
[
"SUBFORMS"
]
=
$
paramCForm
$
paramCForm
:
""
;
$
formRef
=
new
FormReference
(
$
xmlArr
)
;
$
this
->
formRefs
->
set
(
$
paramForm
,
$
formRef
)
;
if
(
$
paramCForm
)
{
if
(
$
this
->
isInFormRefLibs
(
$
paramCForm
)
)
{
$
xmlArr
[
"ATTRIBUTES"
]
[
"NAME"
]
=
$
paramCForm
;
$
xmlArr
[
"ATTRIBUTES"
]
[
"SUBFORMS"
]
=
""
;
$
cformRef
=
new
FormReference
(
$
xmlArr
)
;
$
this
->
formRefs
->
set
(
$
paramCForm
,
$
cformRef
)
;
}
}
}
}
// check url arg as fld:name=val
$
getKeys
=
array_keys
(
$
_GET
)
;
$
paramFields
=
;
foreach
(
$
getKeys
as
$
key
)
{
if
(
substr
(
$
key
,
0
,
4
)
==
"fld:"
)
{
$
fieldName
=
substr
(
$
key
,
4
)
;
$
fieldValue
=
$
_GET
[
$
key
]
;
$
paramFields
[
$
fieldName
]
=
$
fieldValue
;
}
}
if
(
!
$
paramFields
)
return
;
$
paramForm
=
$
this
->
prefixPackage
(
$
paramForm
)
;
$
formObj
=
Openbizx
::
getObject
(
$
paramForm
)
;
$
formObj
->
setRequestParams
(
$
paramFields
)
;
}

Process URL to get the form param and add the form in the FormRefs

@return void


public static function baseURI()
    {
        // Check if uri contains a query.
        $uri = $_SERVER['REQUEST_URI'];
        $qmIsHere  = strpos($uri, '?');
        $uri  = ($qmIsHere === false) ? $uri :
            substr($uri, 0, $qmIsHere);
        // Get file name
        return pathinfo($uri)['filename'];
    }

public
static
function
baseURI
(
)
{
// Check if uri contains a query.
$
uri
=
$
_SERVER
[
'REQUEST_URI'
]
;
$
qmIsHere
=
strpos
(
$
uri
,
'?'
)
;
$
uri
=
(
$
qmIsHere
===
false
)
$
uri
:
substr
(
$
uri
,
0
,
$
qmIsHere
)
;
// Get file name
return
pathinfo
(
$
uri
)
[
'filename'
]
;
}

Returns 'baseURI'.
@method baseURI
@return string  baseUri
Examples:
http:://google.com/ => google
/index.php          => index
user/logout/        => logout
user/post/?msg='...'=> post


protected function validateIdentity($identity)
    {
        $credentialProperty = $this->options->getCredentialProperty();
        $getter             = 'get' . ucfirst($credentialProperty);
        $documentCredential = null;

        if (method_exists($identity, $getter)) {
            $documentCredential = $identity->$getter();
        } elseif (property_exists($identity, $credentialProperty)) {
            $documentCredential = $identity->{$credentialProperty};
        } else {
            throw new Exception\UnexpectedValueException(
                sprintf(
                    'Property (%s) in (%s) is not accessible. You should implement %s::%s()',
                    $credentialProperty,
                    get_class($identity),
                    get_class($identity),
                    $getter
                )
            );
        }

        $credentialValue = $this->credential;
        $callable        = $this->options->getCredentialCallable();

        if ($callable) {
            $credentialValue = call_user_func($callable, $identity, $credentialValue);
        }

        if ($credentialValue !== true && $credentialValue !== $documentCredential) {
            $this->authenticationResultInfo['code']       = AuthenticationResult::FAILURE_CREDENTIAL_INVALID;
            $this->authenticationResultInfo['messages'][] = 'Supplied credential is invalid.';

            return $this->createAuthenticationResult();
        }

        $this->authenticationResultInfo['code']       = AuthenticationResult::SUCCESS;
        $this->authenticationResultInfo['identity']   = $identity;
        $this->authenticationResultInfo['messages'][] = 'Authentication successful.';

        return $this->createAuthenticationResult();
    }

This method attempts to validate that the record in the resultset is indeed a
record that matched the identity provided to this adapter.

@param  object                              $identity
@throws Exception\UnexpectedValueException
@return AuthenticationResult

This method attempts to validate that the record in the resultset is indeed a record that matched the identity provided to this adapter .


protected function setup()
    {
        if (null === $this->identity) {
            throw new Exception\RuntimeException(
                'A value for the identity was not provided prior to authentication with ObjectRepository '
                . 'authentication adapter'
            );
        }

        if (null === $this->credential) {
            throw new Exception\RuntimeException(
                'A credential value was not provided prior to authentication with ObjectRepository'
                . ' authentication adapter'
            );
        }

        $this->authenticationResultInfo = array(
            'code' => AuthenticationResult::FAILURE,
            'identity' => $this->identity,
            'messages' => array()
        );
    }

This method abstracts the steps involved with making sure that this adapter was
indeed setup properly with all required pieces of information.

@throws Exception\RuntimeException - in the event that setup was not done properly

This method abstracts the steps involved with making sure that this adapter was indeed setup properly with all required pieces of information .


protected function setVisibleAttribute(string $name, $value)
    {
        $method = "set" . ucfirst($name);
        if (method_exists($this, $method)) {
            $value = $this->$method($value);

        } elseif (PublicReflection::hasAttribute(get_class($this), $name)) {
            $value = $this->setAttribute($name, $value);

        } elseif ($this->triggerUndefinedAttributeNotice) {
            $className = get_class($this);
            trigger_error("The property {$className}::\${$name} is not accessible.", E_USER_NOTICE);
        }
        return $value;
    }

Checks the visibility of the given attribute before setting it to the given value.

@param string $name
@param $value
@return $this

Checks the visibility of the given attribute before setting it to the given value .


public function firstHumpArray(...$parameters){
        $res = $this->firstHump(...$parameters);
        if ($res instanceof EloquentModel){
            $res = $res->toArray();
        }
        return $res;
    }

public function firstHumpArray ( ... $ parameters ) { $ res = $ this -> firstHump ( ... $ parameters ) ; if ( $ res instanceof EloquentModel ) { $ res = $ res -> toArray ( ) ; } return $ res ; }

Convert the model instance to an array.

@return array

Convert the model instance to an array .


public function getFromList(&$list, $selectFrom = null)
    {
        if (!$selectFrom) {
            $selectFrom = $this->getSelectFrom();
        }
        if (!$selectFrom) {
            return $this->getSQLFromList($list);
        }
        $this->getXMLFromList($list, $selectFrom);
        if ($list != null)
            return;
        $this->getDOFromList($list, $selectFrom);
        if ($list != null)
            return;
        $this->getSimpleFromList($list, $selectFrom);
        if ($list != null)
            return;

        return;
    }

public function getFromList ( & $ list , $ selectFrom = null ) { if ( ! $ selectFrom ) { $ selectFrom = $ this -> getSelectFrom ( ) ; } if ( ! $ selectFrom ) { return $ this -> getSQLFromList ( $ list ) ; } $ this -> getXMLFromList ( $ list , $ selectFrom ) ; if ( $ list != null ) return ; $ this -> getDOFromList ( $ list , $ selectFrom ) ; if ( $ list != null ) return ; $ this -> getSimpleFromList ( $ list , $ selectFrom ) ; if ( $ list != null ) return ; return ; }

Get from list

@param array $list
@return void


public function format(IReport $report)
    {
        $output = '';
        $format = $this->getParameters()->get('format', self::DEFAULT_FORMAT);

        $results = $report->getResults();
        foreach ($results as $result) {
            $messages = $result->getMessages();
            foreach ($messages as $message) {
                switch($message->getSeverity()) {
                    case Message::SEVERITY_FATAL:
                    case Message::SEVERITY_ERROR:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<error>' . $message->getText() . '</error>'
                        );
                        break;
                    case Message::SEVERITY_NOTICE:
                    case Message::SEVERITY_WARN:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<comment>' . $message->getText() . '</comment>'
                        );
                        break;
                    case Message::SEVERITY_INFO:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            '<info>' . $message->getText() . '</info>'
                        );
                        break;
                    case Message::SEVERITY_DEBUG:
                    default:
                        $output .= sprintf(
                            $format,
                            $message->getGroup(),
                            $message->getName(),
                            $message->getText()
                        );
                        break;
                }

                $output .= PHP_EOL;
            }
        }

        return $output;
    }

public function format ( IReport $ report ) { $ output = '' ; $ format = $ this -> getParameters ( ) -> get ( 'format' , self :: DEFAULT_FORMAT ) ; $ results = $ report -> getResults ( ) ; foreach ( $ results as $ result ) { $ messages = $ result -> getMessages ( ) ; foreach ( $ messages as $ message ) { switch ( $ message -> getSeverity ( ) ) { case Message :: SEVERITY_FATAL : case Message :: SEVERITY_ERROR : $ output .= sprintf ( $ format , $ message -> getGroup ( ) , $ message -> getName ( ) , '<error>' . $ message -> getText ( ) . '</error>' ) ; break ; case Message :: SEVERITY_NOTICE : case Message :: SEVERITY_WARN : $ output .= sprintf ( $ format , $ message -> getGroup ( ) , $ message -> getName ( ) , '<comment>' . $ message -> getText ( ) . '</comment>' ) ; break ; case Message :: SEVERITY_INFO : $ output .= sprintf ( $ format , $ message -> getGroup ( ) , $ message -> getName ( ) , '<info>' . $ message -> getText ( ) . '</info>' ) ; break ; case Message :: SEVERITY_DEBUG : default : $ output .= sprintf ( $ format , $ message -> getGroup ( ) , $ message -> getName ( ) , $ message -> getText ( ) ) ; break ; } $ output .= PHP_EOL ; } } return $ output ; }

Returns a formatted string consisting of all
messages from the results of the given report.

@param IReport $report report to take results (and messages) from

@return string messages formatted with the configured format

Returns a formatted string consisting of all messages from the results of the given report .


protected function callMiddleware(
        $middleware,
        string $method = "",
        array &$arguments = [],
        string $type = Caller::TYPE_DEFAULT,
        $result = null
    ) {
        if (! $this->skipMiddleware) {
            $result = $this->middlewareCaller($middleware, $result)
                ->as($type)
                ->catch($this->catchHaltExceptions)
                ->call($method, $arguments);
        }
        return $result;
    }

protected function callMiddleware ( $ middleware , string $ method = "" , array & $ arguments = [ ] , string $ type = Caller :: TYPE_DEFAULT , $ result = null ) { if ( ! $ this -> skipMiddleware ) { $ result = $ this -> middlewareCaller ( $ middleware , $ result ) -> as ( $ type ) -> catch ( $ this -> catchHaltExceptions ) -> call ( $ method , $ arguments ) ; } return $ result ; }

Call middleware pieces.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException if requested

@param mixed $middleware
@param string $method
@param array $arguments
@param $response
@param string $key
@return mixed


protected function callProxyGetters(string $name, $result = null)
    {
        if ($this->getMiddlewareGroup(Caller::TYPE_GETTER)->isNotEmpty()) {
            $middleware = $this->getMiddlewareGroup(Caller::TYPE_GETTER);
            $arguments = [$name];
            $result = $this->callMiddleware($middleware, "get", $arguments, Caller::TYPE_GETTER, $result);

        } elseif ($this->magicMethodsFallbackLocally && property_exists($this, $name)) {
            $result = $this->getAttribute($name);
        }
        return $result;
    }

protected function callProxyGetters ( string $ name , $ result = null ) { if ( $ this -> getMiddlewareGroup ( Caller :: TYPE_GETTER ) -> isNotEmpty ( ) ) { $ middleware = $ this -> getMiddlewareGroup ( Caller :: TYPE_GETTER ) ; $ arguments = [ $ name ] ; $ result = $ this -> callMiddleware ( $ middleware , "get" , $ arguments , Caller :: TYPE_GETTER , $ result ) ; } elseif ( $ this -> magicMethodsFallbackLocally && property_exists ( $ this , $ name ) ) { $ result = $ this -> getAttribute ( $ name ) ; } return $ result ; }

Call the registered middleware getters.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException if requested

@param string $name
@param mixed $result
@return bool

Call the registered middleware getters .


protected function callProxyMethods(string $name, array &$arguments, $result = null)
    {
        if ($this->getMiddlewareGroup(Caller::TYPE_CALLER)->isNotEmpty()) {
            $middleware = $this->getMiddlewareGroup(Caller::TYPE_CALLER);
            $result = $this->callMiddleware($middleware, $name, $arguments, Caller::TYPE_CALLER, $result);

        } elseif ($this->magicMethodsFallbackLocally && is_callable([$this, $name])) {
            $result = $this->$name($arguments);
        }
        return $result;
    }

protected function callProxyMethods ( string $ name , array & $ arguments , $ result = null ) { if ( $ this -> getMiddlewareGroup ( Caller :: TYPE_CALLER ) -> isNotEmpty ( ) ) { $ middleware = $ this -> getMiddlewareGroup ( Caller :: TYPE_CALLER ) ; $ result = $ this -> callMiddleware ( $ middleware , $ name , $ arguments , Caller :: TYPE_CALLER , $ result ) ; } elseif ( $ this -> magicMethodsFallbackLocally && is_callable ( [ $ this , $ name ] ) ) { $ result = $ this -> $ name ( $ arguments ) ; } return $ result ; }

Sends the request to the method MiddleMans and returns the final response.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException if requested

@param string $name
@param array $arguments
@param mixed $result
@return mixed

Sends the request to the method MiddleMans and returns the final response .


protected function callProxySetters(string $name, $value, $result = null)
    {
        $result = null;
        if ($this->getMiddlewareGroup(Caller::TYPE_SETTER)->isNotEmpty()) {
            $middleware = $this->getMiddlewareGroup(Caller::TYPE_SETTER);
            $arguments = [$name, $value];
            $result = $this->callMiddleware($middleware, "set", $arguments, Caller::TYPE_SETTER, $result);

        } elseif ($this->magicMethodsFallbackLocally && property_exists($this, $name)) {
            $this->setAttribute($name, $value);
            $result = [$name, $value];
        }
        return $result;
    }

protected function callProxySetters ( string $ name , $ value , $ result = null ) { $ result = null ; if ( $ this -> getMiddlewareGroup ( Caller :: TYPE_SETTER ) -> isNotEmpty ( ) ) { $ middleware = $ this -> getMiddlewareGroup ( Caller :: TYPE_SETTER ) ; $ arguments = [ $ name , $ value ] ; $ result = $ this -> callMiddleware ( $ middleware , "set" , $ arguments , Caller :: TYPE_SETTER , $ result ) ; } elseif ( $ this -> magicMethodsFallbackLocally && property_exists ( $ this , $ name ) ) { $ this -> setAttribute ( $ name , $ value ) ; $ result = [ $ name , $ value ] ; } return $ result ; }

Sends the request to the setter MiddleMans and returns the final response.

@throws \MichaelRShelton\MiddleMan\Exceptions\HaltPropagationException if requested

@param string $name
@param $value
@param mixed $result
@return array|null

Sends the request to the setter MiddleMans and returns the final response .


protected function catchHaltedMiddleware(bool $setting = null)
    {
        if ($setting === null) {
            return $this->catchHaltExceptions;
        }
        $this->catchHaltExceptions = $setting;
        return $this;
    }

protected function catchHaltedMiddleware ( bool $ setting = null ) { if ( $ setting === null ) { return $ this -> catchHaltExceptions ; } $ this -> catchHaltExceptions = $ setting ; return $ this ; }

Getter and setting for the exception catching property.

@param bool $setting
@return $this|bool

Getter and setting for the exception catching property .


protected function clearMiddleware(string $group = null)
    {
        if ($group === null) {
            $this->middleware = new Group;
        } else {
            unset($this->middleware[$group]);
        }
        return $this;
    }

protected function clearMiddleware ( string $ group = null ) { if ( $ group === null ) { $ this -> middleware = new Group ; } else { unset ( $ this -> middleware [ $ group ] ) ; } return $ this ; }

Clears the given middleware group or all if none given.

@param string|null $group
@return $this

Clears the given middleware group or all if none given .


protected function disableMiddleware(string $key = '', string $group = null)
    {
        $middleware = $this->getMiddleware($key, $group);
        if ($middleware instanceof Disableable) {
            $middleware->disable();
        }
        return $this;
    }

protected function disableMiddleware ( string $ key = '' , string $ group = null ) { $ middleware = $ this -> getMiddleware ( $ key , $ group ) ; if ( $ middleware instanceof Disableable ) { $ middleware -> disable ( ) ; } return $ this ; }

Disable the given middleware.

@param string $key
@param string|null $group
@return $this


protected function enableMiddleware(string $key = '', string $group = null)
    {
        $middleware = $this->getMiddleware($key, $group);
        if ($middleware instanceof Enableable) {
            $middleware->enable();
        }
        return $this;
    }

protected function enableMiddleware ( string $ key = '' , string $ group = null ) { $ middleware = $ this -> getMiddleware ( $ key , $ group ) ; if ( $ middleware instanceof Enableable ) { $ middleware -> enable ( ) ; } return $ this ; }

Enable the given middleware.

@param string $key
@param string|null $group
@return $this


protected function getMiddleware(string $key = "", string $group = null, $default = null)
    {
        return $this->getMiddlewareGroup($group ?: $this->middlewareGroupId)->get($key, $default);
    }

protected function getMiddleware ( string $ key = "" , string $ group = null , $ default = null ) { return $ this -> getMiddlewareGroup ( $ group ? : $ this -> middlewareGroupId ) -> get ( $ key , $ default ) ; }

Retrieves the middleware by key and group with a variable fallback.

@param string $key
@param string|null $group
@param mixed $default
@return mixed

Retrieves the middleware by key and group with a variable fallback .