Assembles results data for the report

Establish report data for the widgetHandler.

@param mixed[] $options with entity and view data.
@throws \RuntimeException
@return mixed[] $result containing $_data.
968524
public function getResults(array $options = []) : array
    {
        $this->_instance = $this->getReportInstance($options);
        if (null === $this->_instance) {
            return [];
        }

        $config = $this->getReport($options);
        if (empty($config)) {
            return [];
        }

        $this->setConfig($config);
        $this->setContainerId($config);

        $validated = $this->validate($config);

        if (! $validated['status']) {
            throw new RuntimeException("Report validation failed");
        }

        $result = $this->getQueryData($config);

        if (!empty($result)) {
            $this->_instance->getChartData($result);
            $this->setOptions(['scripts' => $this->_instance->getScripts()]);
        }

        return $result;
    }
683878
public function fetch($view, array $data = [])
    {
        $file = $this->getViewFile($view);

        if (!is_file($file)) {
            throw new \RuntimeException("cannot render '$view' because the view file does not exist. File: $file");
        }

        /*
        foreach ($data as $k=>$val) {
            if (in_array($k, array_keys($this->attributes))) {
                throw new \InvalidArgumentException("Duplicate key found in data and renderer attributes. " . $k);
            }
        }
        */
        $data = array_merge($this->attributes, $data);

        try {
            ob_start();
            $this->protectedIncludeScope($file, $data);
            $output = ob_get_clean();
        } catch (\Throwable $e) { // PHP 7+
            ob_end_clean();
            throw $e;
        }

        return $output;
    }
533521
public function save(array $options = array())
    {
        $result = false;
        
        if ($this->pricelistId) {
            $result = parent::save($options);
            $order = Order::find($this->id);
            $order->pricelists()->attach($this->pricelistId);
        } else {
            throw new Exception('pricelist_id not set.');
        }
        
        return $result;
    }
924767
public function getDetails(array $data)
    {
        $result = call_user_func($this->callback, $data);

        if (false === $result) {
            throw new RuntimeException('Occurred error.');
        }

        return $result;
    }
536764
public function getData(Options $options = null)
    {
        if ($options === null) {
            // Take store global/default options
            $options = $this->store->getOptions();
            // By default formatters are disabled in JSON format
            $options->getHydrationOptions()->disableFormatters();
        }

        // Get unformatted data when using json
        $options->getHydrationOptions()->disableFormatters();

        $data = $this->store->getData($options);
        $now = new DateTime();

        $d = [
            'success' => true,
            'timestamp' => $now->format(DateTime::W3C),
            'total' => $data->getTotalRows(),
            'request_id' => $this->request_id,
            'start' => $data->getSource()->getOptions()->getOffset(),
            'limit' => $data->getSource()->getOptions()->getLimit(),
            'data' => $data->toArray()
        ];

        if ($this->options['debug']) {
            $source = $data->getSource();
            if ($source instanceof QueryableSourceInterface) {
                $d['query'] = $source->getQueryString();
            }
        }

        return json_encode($d);
    }
997680
public function execute(array $args = [], array $options = [])
    {
        $argv = $_SERVER['argv'];
        array_shift($argv);
        array_shift($argv);

        $argvString = '';
        foreach ($argv as $arg) {
            $argvString .= ($argvString ? ' ' : '').'"'.str_replace('"', '\\"', $arg).'"';
        }
        $found = null;
        foreach ($this->getConfig()->get('_shell_scripts_dirs', []) as $dir) {
            $path = sprintf('%s/%s', $dir, $this->script);
            if (!is_file($path)) {
                continue;
            }
            $found = $path;
        }
        if (null === $found) {
            throw new \RuntimeException(sprintf("Unknown shell script '%s'", $this->script), 412);
        }

        $this->executeShellCommand(sprintf('%s %s', $found, $argvString), $options);
    }
101738
protected function options(array $options = null)
    {
        $dataOptions = $this->options;

        if ($options)
        {
            $dataOptions = $this->merge($dataOptions, $options);
        }

        return $dataOptions;
    }
1202419
public function createGroup(array $options)
    {
        if ($this->prepared) {
            throw new \RuntimeException('MenuPool has been prepared and can\'t receive new groups.');
        }

        $group = new MenuGroup($this->groupOptionsResolver->resolve($options));

        $this->addGroup($group);
    }
799356
public function make($data, $options=array())
	{
		// Options
		$this->options = array_merge($this->options, $options);
		$options       = $this->options;

		// Capture output
		$out  = [];

		// @todo - Raise an exception instead ?
		// Would make more send and could be handled more gracefully
		//
		// Have any records actually been passed through ?
		if (empty($data)) {
			return $this->hasNoData($options);
		}

		// If a 'id' key has been specified use that as the table#id
		$tableId = null;

		if (!empty($options['id'])) {
			$tableId = "id='{$options['id']}'";
		}

		$out[] = "<div class=\"{$options['wrapperClass']}\">";
		$out[] = "\t<table class='{$options['containerClass']}' {$tableId}>";

		// Render headers
		if (true == $options['showHeaders']) {
			$headers = $this->extractHeaders($data);

			$out[] = "\t\t<thead>\r\t\t\t<tr class=\"{$options['headerClass']}\">";
			$count = 1;

			/**
			 * Create the <th> tag
			 */
			foreach ($headers as $index => $header)
			{
				$class = $this->getHeaderClass($header, $count);
				$count++;

				// Apply sort links to header
				if (isset($options['sort'][$header])) {

					$sortBy = $options['sort'][$header];
					$label  = $header;

					$header = $this->applyHeaderSort($label, $sortBy);
				}

				$out[] = "\t\t\t\t<th class=\"{$class}\">{$header}</th>";
			}

			$out[] = "\t\t\t</tr>\r\t\t</thead>";
		}

		$out[] = "\t\t<tbody>";

		// Render rows
		foreach ($data as $index => $row)
		{
			$rowClass = ($index % 2 == 0) ? $options['rowClass'] : $options['rowClassAlt'];

			if (isset($row['id'])) {
				$out[] = "\t\t\t<tr class='{$rowClass}' id='{$row['id']}-{$row['id']}'>";
			} else {
				$out[] = "\t\t\t<tr class='{$rowClass}'>";
			}

			foreach ($row as $field => $value) {
				$indent = "";
				if ($field == 'Title' && isset($options['type']) && $options['type'] == 'table-tree') {
					if (!empty($row['parent_id'])) {
						$indent = str_repeat($options['indent_style'], $row['depth']);
					}
				}

				if (in_array($field, $options['hiddenFields'], true)) {
					continue;
				}

				$fieldClass = $options['fieldClass'];

				if (is_array($value)) {
					//Log::info('@todo - Replace with logging interface');
					//$value = implode(',' $value);
					$value = 'Array';
				}

				$out[] = "\t\t\t\t<td class=\"{$fieldClass}\">{$value}</td>";

			}

			$out[] = "\t\t\t</tr>";
		}

		$out[] = "\t\t</tbody>";
		$out[] = "\t</table>";
		$out[] = "</div>";

		$this->output['table'] = implode(PHP_EOL, $out);

		return $this;
	}
928465
public function getData(Options $options = null)
    {
        if ($options === null) {
            $options = $this->getOptions();
        }

        $select = $this->assignOptions(clone $this->getSelect(), $options);

        $sql = new Sql($this->adapter);

        $sql_string = $sql->buildSqlString($select);
        //echo $this->select->getSqlString($this->adapter->getPlatform());
        //echo "----" . var_dump($sql_string) . "----\n";
        // In ZF 2.3.0 an empty query will return SELECT .*
        // In ZF 2.4.0 and empty query will return SELECT *
        if (in_array($sql_string, ['', 'SELECT .*', 'SELECT *'], true)) {
            throw new Exception\EmptyQueryException(__METHOD__ . ': Cannot return data of an empty query');
        }
        $this->query_string = $sql_string;

        try {
            $results = $this->adapter->query($sql_string, Adapter::QUERY_MODE_EXECUTE);
            //$stmt = $sql->prepareStatementForSqlObject( $select );
            //$results = $stmt->execute();
            //var_dump(get_class($results));

            $r = new ResultSet($results);
            $r->setSource($this);
            $r->setHydrationOptions($options->getHydrationOptions());

            if ($options->hasLimit() && $options->getLimit() > 0) {
                //$row = $this->adapter->query('select FOUND_ROWS() as total_count')->execute()->current();
                $row = $this->adapter->createStatement('select FOUND_ROWS() as total_count')->execute()->current();
                $r->setTotalRows($row['total_count']);
            } else {
                $r->setTotalRows($r->count());
            }
        } catch (\Exception $e) {
            throw new Exception\ErrorException(__METHOD__ . ': Cannot retrieve data (' . $e->getMessage() . ')');
        }

        return $r;
    }
535226
public function withJson($data, int $status = null, int $options = 0)
        {
            $json = json_encode($data, $options);
            if ($json === false) {
                throw new \RuntimeException(json_last_error_msg(), json_last_error());
            }
            
            $response = $this->write($json);
            $response = $response->withHeader('Content-Type', 'application/json;charset=utf-8');
            
            if (isset($status)) {
                return $response->withStatus($status);
            }
            return $response;
        }
582203
private function preBuild($result)
    {
        $container = $this->preBuild->handle(new BuilderContainer($this, $result));

        if ($container instanceof BuilderContainer) {
            return $container->getValue();
        }

        throw new \RuntimeException();
    }
514633
final public function get($options = []) {
		// process parameters
		$parameters = [];
		$options['where'] = $options['where'] ?? [];
		if (!empty($this->parameters)) {
			$this->parameters = \Object\Data\Common::processDomainsAndTypes($this->parameters);
			foreach ($this->parameters as $k => $v) {
				// if we have a parameter
				if (array_key_exists($k, $options['where'])) {
					if (!empty($v['multiple_column'])) {
						if (!is_array($options['where'][$k])) $options['where'][$k] = [$options['where'][$k]];
						$parameters[$k] = [];
						foreach ($options['where'][$k] as $v2) {
							$result = \Object\Table\Columns::validateSingleColumn($k, $v, $v2);
							if (!$result['success']) {
								Throw new \Exception("Datasource: " . get_called_class() . " parameter: {$k} error" . implode(', ', $result['error']));
							} else {
								$parameters[$k][] = $result['data'][$k];
							}
						}
					} else {
						$result = \Object\Table\Columns::validateSingleColumn($k, $v, $options['where'][$k]);
						if (!$result['success']) {
							Throw new \Exception("Datasource: " . get_called_class() . " parameter: {$k} error" . implode(', ', $result['error']));
						} else {
							$parameters[$k] = $result['data'][$k];
						}
					}
				}
				// required
				if (!empty($v['required']) && empty($parameters[$k])) {
					return [];
					//Throw new \Exception("Datasource: " . get_called_class() . " parameter: {$k} error" . i18n(null, \Object\Content\Messages::required_field));
				}
			}
		}
		// we need to push existing values to parameters
		if (!empty($options['existing_values']) && !empty($this->parameters['existing_values'])) {
			$parameters['existing_values'] = $options['existing_values'];
		}
		$where = $options['where'] ?? [];
		unset($options['where']);
		// process primary model
		if (!empty($this->primary_model)) {
			$model = new $this->primary_model();
			$this->db_link = $model->db_link;
			if (empty($this->pk)) $this->pk = $model->pk;
			$this->cache_tags = array_merge($this->cache_tag ?? [], $model->cache_tags);
			if (!empty($this->primary_params)) {
				$options = array_merge_hard($options, $this->primary_params);
			}
			$options['where'] = $where[$this->primary_model] ?? [];
			unset($where[$this->primary_model]);
			foreach ($where as $k => $v) {
				if (strpos($k, '\\') === 0) {
					$options['where'][$k] = $v;
				}
			}
			// query
			$this->query = call_user_func_array([$this->primary_model, 'queryBuilderStatic'], [$options])->select();
		}
		// we need to determine db link
		if (empty($this->db_link)) {
			// get from flags first
			if (!empty($this->db_link_flag)) {
				$this->db_link = \Application::get($this->db_link_flag);
			}
			// get default link
			if (empty($this->db_link)) {
				$this->db_link = \Application::get('flag.global.default_db_link');
			}
			// if we could not determine the link we throw exception
			if (empty($this->db_link)) {
				Throw new \Exception('Could not determine db link in datasource!');
			}
		}
		// create empty query object
		if (empty($this->query)) {
			$this->query = new \Object\Query\Builder($this->db_link, $options);
			$this->query->select();
		}
		// add settings to query
		$query_settings = [];
		foreach (['pk', 'columns', 'limit', 'orderby', 'single_row', 'single_value'] as $v) {
			if (array_key_exists($v, $options)) {
				$query_settings[$v] = $options[$v];
			} else if (isset($this->{$v})) {
				$query_settings[$v] = $this->{$v};
			}
		}
		if (isset($query_settings['columns'])) $this->query->columns($query_settings['columns']);
		if (isset($query_settings['limit'])) $this->query->limit($query_settings['limit']);
		if (isset($query_settings['orderby'])) $this->query->limit($query_settings['orderby']);
		if (!empty($query_settings['single_row']) || !empty($query_settings['single_value'])) $this->query->limit(1);
		// fix variables
		$query_settings['pk'] = $query_settings['pk'] ?? null;
		if (empty($this->cache_tags)) $this->cache_tags = [];
		// check if we have query method
		if (!method_exists($this, 'query')) {
			Throw new \Exception('You must specify sql in query method!');
		}
		// process query
		$sql = $this->query($parameters, $options);
		if (!empty($sql)) {
			$db_object = new \Db($this->db_link);
			$this->sql_last_query = $sql;
		} else {
			$db_object = $this->query->db_object;
			$this->sql_last_query = $this->query->sql();
			// grab cache tags from query object
			if (!empty($this->query->cache_tags)) {
				$this->cache_tags = array_unique(array_merge($this->cache_tags, $this->query->cache_tags));
			}
		}
		// determine caching strategy
		if (method_exists($this, 'process')) {
			// retrive data from the cache
			if ($this->cache && !empty($db_object->object->options['cache_link'])) {
				$cache_id = !empty($options['cache_id']) ? $options['cache_id'] : 'Db_DataSource_' . trim(sha1($this->sql_last_query . serialize($query_settings['pk'])));
				// if we cache this query
				$cache_object = new \Cache($db_object->object->options['cache_link']);
				$cached_result = $cache_object->get($cache_id, true);
				if ($cached_result !== false) {
					// if we are debugging
					if (\Debug::$debug) {
						\Debug::$data['sql'][] = $cached_result;
					}
					return $cached_result['rows'];
				}
			} else {
				$this->cache = false;
			}
		}
		$query_options = [
			'cache' => $this->cache,
			'cache_tags' => array_unique($this->cache_tags)
		];
		// if we need to return a query
		if (!empty($options['return_query_only'])) {
			if (empty($sql)) {
				$sql = $this->query->sql();
			}
			// wrap into tabs
			if ($options['return_query_only'] == 'wrap') {
				$object = new \Object\Query\Builder($this->db_link, []);
				$sql = '(' . $object->wrapSqlIntoTabs($sql) . ')';
			}
			return [
				'sql' => $sql,
				'cache_tags' => array_unique($this->cache_tags)
			];
		}
		// if we have SQL
		if (!empty($sql)) {
			$result = $db_object->query($sql, $query_settings['pk'], $query_options);
		} else { // query builder
			$result = $this->query->query($query_settings['pk'], $query_options);
		}
		if (!$result['success']) {
			Throw new \Exception(implode(", ", $result['error']));
		}
		// put parameters beck into options
		$options['parameters'] = $parameters;
		// process data
		if (method_exists($this, 'process')) {
			$data = $this->process($result['rows'], $options);
			// if we are caching
			if ($this->cache) {
				// the same cache structure as in Db classes
				$cache_data = [
					'success' => true,
					'error' => [],
					'errno' => 0,
					'rows' => $data,
					'num_rows' => is_bool($data) ? 0 : count($data),
					'affected_rows' => 0,
					'structure' => [],
					// debug attributes
					'cache' => true,
					'cache_tags' => [],
					'time' => microtime(true),
					'sql' => $this->sql_last_query,
					'key' => $query_settings['pk'],
					'backtrace' => null
				];
				if (\Debug::$debug) {
					$cache_data['backtrace']  = implode("\n", \Object\Error\Base::debugBacktraceString());
					$cache_data['cache_tags'] = $this->cache_tags;
				}
				$cache_object->set($cache_id, $cache_data, null, $this->cache_tags);
			}
		} else {
			$data = $result['rows'];
		}
		// process not cached
		if (method_exists($this, 'processNotCached')) {
			$data = $this->processNotCached($data, $options);
		}
		// single row
		if (!empty($query_settings['single_row']) && !empty($data)) {
			$data = current($data);
		}
		// single value
		if (!empty($query_settings['single_value']) && !empty($data)) {
			$data = current($data);
			if (!empty($data)) {
				$data = current($data);
			}
		}
		return $data;
	}
731581
public function deserialize(array $data)
    {
        $this->assertHasKey('name', $data);
        $this->assertHasKey('conditions', $data);

        if ( ! is_array($data['conditions'])) {
            throw new RuntimeException('Key "conditions" should be an array.');
        }

        $toggle = new Toggle(
            $data['name'],
            $this->deserializeConditions($data['conditions']),
            isset($data['strategy']) ? $this->deserializeStrategy($data['strategy']) : Toggle::STRATEGY_AFFIRMATIVE
        );

        if (isset($data['status'])) {
            $this->deserializeStatus($toggle, $data['status']);
        }

        return $toggle;
    }
61707
public function createFormBuilder($data = null, array $options = array())
    {
        return $this->getContainer()->get('form.factory')->createBuilder('form', $data, $options);
    }
324835
public function stringToObject($data, array $options=[])
  {
    $data = trim($data);
    if ( substr($data, 0, 1) !== '{' && substr($data, -1, 1) !== '}' ){
      return Format::getInstance('Yaml')->stringToObject($data, $options);
    }
    
    $decoded = json_decode($data);
    
    if ( $decoded === null ){
      throw new \RuntimeException(sprintf('Error decoding JSON data: %s', json_last_error_msg()));
    }
    
    return (object)$decoded;
  }
1054481
public function generate($options = array()) {
		
		// double-checks options was properly set
		if (empty($options)) {
			Console::writeError("need to pass options to generate...");
		}
		
		// set the default vars
		$moveStatic    = (isset($options["moveStatic"]))    ? $options["moveStatic"] : true;
		$noCacheBuster = (isset($options["noCacheBuster"])) ? $options["noCacheBuster"] : false;
		$exportFiles   = (isset($options["exportFiles"]))   ? $options["exportFiles"] : false;
		$exportClean   = (isset($options["exportClean"]))   ? $options["exportClean"] : false;
		$watchMessage  = (isset($options["watchMessage"]))  ? $options["watchMessage"] : false;
		$watchVerbose  = (isset($options["watchVerbose"]))  ? $options["watchVerbose"] : false;
		
		if ($noCacheBuster) {
			Config::setOption("cacheBuster",0);
		}
		
		// gather up all of the data to be used in patterns
		Data::gather();
		
		// gather all of the various pattern info
		$options = array();
		$options["exportClean"] = $exportClean;
		$options["exportFiles"] = $exportFiles;
		PatternData::gather($options);
		
		// gather the annotations
		Annotations::gather();
		
		// clean the public directory to remove old files
		if ((Config::getOption("cleanPublic") == "true") && $moveStatic) {
			FileUtil::cleanPublic();
		}
		
		// render out the index and style guide
		$this->generateIndex();
		$this->generateStyleguide();
		$this->generateViewAllPages();
		
		// render out the patterns and move them to public/patterns
		$options = array();
		$options["exportFiles"] = $exportFiles;
		$this->generatePatterns($options);
		
		// render the annotations as a js file
		$this->generateAnnotations();
		
		// move all of the files unless pattern only is set
		if ($moveStatic) {
			$this->moveStatic();
		}
		
		// update the change time so the auto-reload will fire (doesn't work for the index and style guide)
		Util::updateChangeTime();
		
		if ($watchVerbose && $watchMessage) {
			Console::writeLine($watchMessage);
		} else {
			Console::writeLine("your site has been generated...");
			Timer::stop();
		}
		
	}