本文整理汇总了PHP中Datasource类的典型用法代码示例。如果您正苦于以下问题:PHP Datasource类的具体用法?PHP Datasource怎么用?PHP Datasource使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Datasource类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
public function execute(array &$param_pool = null)
{
$result = new XMLElement($this->dsParamROOTELEMENT);
$type_sql = $parent_sql = null;
if (trim($this->dsParamFILTERS['type']) != '') {
$type_sql = $this->__processNavigationTypeFilter($this->dsParamFILTERS['type'], Datasource::determineFilterType($this->dsParamFILTERS['type']));
}
if (trim($this->dsParamFILTERS['parent']) != '') {
$parent_sql = $this->__processNavigationParentFilter($this->dsParamFILTERS['parent']);
}
// Build the Query appending the Parent and/or Type WHERE clauses
$pages = Symphony::Database()->fetch(sprintf("SELECT DISTINCT p.id, p.title, p.handle, (SELECT COUNT(id) FROM `tbl_pages` WHERE parent = p.id) AS children\n FROM `tbl_pages` AS p\n LEFT JOIN `tbl_pages_types` AS pt ON (p.id = pt.page_id)\n WHERE 1 = 1\n %s\n %s\n ORDER BY p.`sortorder` ASC", !is_null($parent_sql) ? $parent_sql : " AND p.parent IS null ", !is_null($type_sql) ? $type_sql : ""));
if (!is_array($pages) || empty($pages)) {
if ($this->dsParamREDIRECTONEMPTY === 'yes') {
throw new FrontendPageNotFoundException();
}
$result->appendChild($this->__noRecordsFound());
} else {
// Build an array of all the types so that the page's don't have to do
// individual lookups.
$page_types = PageManager::fetchAllPagesPageTypes();
foreach ($pages as $page) {
$result->appendChild($this->__buildPageXML($page, $page_types));
}
}
return $result;
}
示例2: testExistingChildren
public function testExistingChildren()
{
// --- test load
$this->createModels(CustomerDetail::class, []);
$this->createModels(Customer::class, [['name' => 'Frank', 'surname' => 'Sinatra']]);
$details = new CustomerDetail();
$source = Datasource::make(new CustomerDetail());
$source['id'] = 1;
$source['biography'] = 'A nice life!';
$source['accepts_cookies'] = 0;
$source['customer_id'] = 1;
$details->id = 1;
$details->biography = 'A nice life!';
$details->accepts_cookies = 0;
$details->customer_id = 1;
$source->save();
assertTrue(isset($source['customer']));
assertInstanceOf(Customer::class, $source['customer']);
assertModelArrayEqual(Customer::all()->toArray(), [$source['customer']->toArray()]);
// compare with how eloquent behaves:
$this->createModels(CustomerDetail::class, []);
$details->save();
assertFalse(isset($details->customer));
// always false!
assertInstanceOf(Customer::class, $details->customer);
}
示例3: setDefaultValues
/**
* @uses EventPreSaveFilter
*/
public function setDefaultValues(&$context)
{
if (!isset($context['event']->eDefaultValues) || !is_array($context['event']->eDefaultValues)) {
return;
}
// Create a Datasource class, which has the logic for finding Parameters
// and turning them into the values.
$datasource = new Datasource(null, false);
// Fake an environment to find Parameters in
$env = array('env' => Frontend::instance()->Page()->Env(), 'param' => Frontend::instance()->Page()->Params());
// Loop over the Default Values, setting them in $_POST or `$context['fields']`
// as appropriate.
foreach ($context['event']->eDefaultValues as $field => $dv) {
$value = $datasource->__processParametersInString($dv['value'], $env);
// Custom field, this will set $_POST instead of the `$context['fields']`
// as `$context['fields']` only contains things inside $_POST['fields']
if ($dv['custom'] == 'yes') {
$matches = preg_split('/\\[/U', $field);
foreach ($matches as $key => $match) {
$matches[$key] = trim($match, ']');
}
if (count($matches) == 1) {
self::setArrayValue($_POST, $field, $value, $dv['override'] == 'yes');
} else {
$tree = self::addKey($matches, $value);
// If the DV is an override, set it regardless
// DV is not an override, so only set if it hasn't already been set
if ($dv['override'] == 'no' && !self::checkArrayForTree($_POST, $tree)) {
$_POST = array_merge_recursive($_POST, $tree);
} else {
if ($dv['override'] == 'yes') {
$_POST = array_replace_recursive($_POST, $tree);
}
}
}
continue;
}
self::setArrayValue($_POST['fields'], $field, $value, $dv['override'] == 'yes');
self::setArrayValue($context['fields'], $field, $value, $dv['override'] == 'yes');
}
}
示例4: query
/**
* Make a query into the datasource
*/
public static function query($sql)
{
if (Datasource::$_self == null) {
Datasource::$_self = Datasource::_create();
}
Datasource::$_self->_logQuery($sql);
try {
return Datasource::$_self->_query($sql);
} catch (Exception $e) {
throw $e;
}
}
示例5: testCreateChildren
public function testCreateChildren()
{
$this->createModels(Customer::class, []);
$this->createModels(Order::class, []);
// test creation
$customer = new Customer();
$source = Datasource::make($customer);
$source['name'] = 'Frank';
$source['surname'] = 'Sinatra';
$source['orders.0.code'] = 'a1';
$source['orders.0.shipping'] = 'home';
$source['orders.1.code'] = 'b1';
$source['orders.1.shipping'] = 'office';
$source->save();
assertModelArrayEqual([['name' => 'Frank', 'surname' => 'Sinatra']], Customer::all()->toArray());
assertModelArrayEqual([['code' => 'a1', 'shipping' => 'home', 'customer_id' => 1], ['code' => 'b1', 'shipping' => 'office', 'customer_id' => 1]], Order::all()->toArray());
}
示例6: sanitize
public function sanitize($fld, $value)
{
if (preg_match("#text\$#", $this->modelStructure[$fld]["type"]) || preg_match("#char\$#", $this->modelStructure[$fld]["type"]) || $this->modelStructure[$fld]["type"] == "enum" || $this->modelStructure[$fld]["type"] == "date" || $this->modelStructure[$fld]["type"] == "timestamp") {
$value = "'" . Datasource::escape($value) . "'";
} else {
if ($this->modelStructure[$fld]["type"] == "tinyint") {
if (!(intval($value) == 0 || intval($value) == 1)) {
SimpleMVCErrors::generalError("Given value ({$value}) is not a valid boolean value");
}
} else {
// Assume to be numeric
if (!is_numeric($value) && $value != 'NULL') {
SimpleMVCErrors::generalError("{$value} given as numeric database input (" . $this->modelSource . ".{$fld})");
}
}
}
return $value;
}
示例7: testCreateChildren
public function testCreateChildren()
{
$this->createModels(Order::class, []);
$this->createModels(Book::class, []);
// test creation
$order = new Order();
$source = Datasource::make($order);
$source['code'] = 'a1';
$source['shipping'] = 'home';
$source['customer_id'] = '1';
$source['books.0.title'] = 'Happiness';
$source['books.1.title'] = 'Delight';
$source->save();
assertModelArrayEqual([['code' => 'a1', 'shipping' => 'home', 'customer_id' => 1]], Order::all()->toArray());
assertModelArrayEqual([['title' => 'Happiness'], ['title' => 'Delight']], Book::all()->toArray());
// repeat
$source->save();
assertModelArrayEqual([['code' => 'a1', 'shipping' => 'home', 'customer_id' => 1]], Order::all()->toArray());
assertModelArrayEqual([['title' => 'Happiness'], ['title' => 'Delight']], Book::all()->toArray());
}
示例8: __processParametersInString
/**
* This function will replace any parameters in a string with their value.
* Parameters are defined by being prefixed by a $ character. In certain
* situations, the parameter will be surrounded by {}, which Symphony
* takes to mean, evaluate this parameter to a value, other times it will be
* omitted which is usually used to indicate that this parameter exists
*
* @param string $value
* The string with the parameters that need to be evaluated
* @param array $env
* The environment variables from the Frontend class which includes
* any params set by Symphony or Events or by other Datasources
* @param boolean $includeParenthesis
* Parameters will sometimes not be surrounded by {}. If this is the case
* setting this parameter to false will make this function automatically add
* them to the parameter. By default this is true, which means all parameters
* in the string already are surrounded by {}
* @param boolean $escape
* If set to true, the resulting value will be `urlencode`'d before being returned.
* By default this is false
* @return string
* The string will all parameters evaluated. If a parameter was not found, it will
* not be replaced at all.
*/
public function __processParametersInString($value, array $env, $includeParenthesis = true, $escape = false)
{
if (trim($value) == '') {
return null;
}
if (!$includeParenthesis) {
$value = '{' . $value . '}';
}
if (preg_match_all('@{([^}]+)}@i', $value, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
list($source, $cleaned) = $match;
$replacement = null;
$bits = preg_split('/:/', $cleaned, -1, PREG_SPLIT_NO_EMPTY);
foreach ($bits as $param) {
if ($param[0] != '$') {
$replacement = $param;
break;
}
$param = trim($param, '$');
$replacement = Datasource::findParameterInEnv($param, $env);
if (is_array($replacement)) {
$replacement = array_map(array('Datasource', 'escapeCommas'), $replacement);
if (count($replacement) > 1) {
$replacement = implode(',', $replacement);
} else {
$replacement = end($replacement);
}
}
if (!empty($replacement)) {
break;
}
}
if ($escape == true) {
$replacement = urlencode($replacement);
}
$value = str_replace($source, $replacement, $value);
}
}
return $value;
}
示例9: render
public function render(Register $Parameters, XMLDocument &$Document = NULL, DocumentHeaders &$Headers = NULL)
{
$ParameterOutput = new Register();
if (!is_null($Headers)) {
$Headers->append('Content-Type', $this->{'content-type'});
} else {
header('Content-Type: ' . $this->{'content-type'});
}
if (is_null($Document)) {
$Document = new XMLDocument();
$Document->appendChild($Document->createElement('data'));
}
$root = $Document->documentElement;
$datasources = $events = array();
$events_wrapper = $Document->createElement('events');
$root->appendChild($events_wrapper);
if (is_array($this->about()->{'events'}) && !empty($this->about()->{'events'})) {
$events = $this->about()->{'events'};
}
if (is_array($this->about()->{'data-sources'}) && !empty($this->about()->{'data-sources'})) {
$datasources = $this->about()->{'data-sources'};
}
####
# Delegate: FrontendEventsAppend
# Description: Append additional Events.
# Global: Yes
Extension::notify('FrontendEventsAppend', '/frontend/', array('events' => &$events));
if (!empty($events)) {
$postdata = General::getPostData();
$events_ordered = array();
foreach ($events as $handle) {
$events_ordered[] = Event::loadFromHandle($handle);
}
uasort($events_ordered, array($this, '__cbSortEventsByPriority'));
foreach ($events_ordered as $e) {
if (!$e->canTrigger($postdata)) {
continue;
}
$fragment = $e->trigger($ParameterOutput, $postdata);
if ($fragment instanceof DOMDocument && !is_null($fragment->documentElement)) {
$node = $Document->importNode($fragment->documentElement, true);
$events_wrapper->appendChild($node);
}
}
}
####
# Delegate: FrontendDataSourceAppend
# Description: Append additional DataSources.
# Global: Yes
Extension::notify('FrontendDataSourcesAppend', '/frontend/', array('datasources' => &$datasources));
// Find dependancies and order accordingly
$datasource_pool = array();
$dependency_list = array();
$datasources_ordered = array();
$all_dependencies = array();
foreach ($datasources as $handle) {
$datasource_pool[$handle] = Datasource::loadFromHandle($handle);
$dependency_list[$handle] = $datasource_pool[$handle]->parameters()->dependencies;
}
$datasources_ordered = $this->__sortByDependencies($dependency_list);
if (!empty($datasources_ordered)) {
foreach ($datasources_ordered as $handle) {
$ds = $datasource_pool[$handle];
try {
$fragment = $ds->render($ParameterOutput);
} catch (FrontendPageNotFoundException $e) {
FrontendPageNotFoundExceptionHandler::render($e);
}
if ($fragment instanceof DOMDocument && !is_null($fragment->documentElement)) {
$node = $Document->importNode($fragment->documentElement, true);
$root->appendChild($node);
}
}
}
if ($ParameterOutput->length() > 0) {
foreach ($ParameterOutput as $p) {
$Parameters->{$p->key} = $p->value;
}
}
####
# Delegate: FrontendParamsPostResolve
# Description: Access to the resolved param pool, including additional parameters provided by Data Source outputs
# Global: Yes
Extension::notify('FrontendParamsPostResolve', '/frontend/', array('params' => $Parameters));
$element = $Document->createElement('parameters');
$root->appendChild($element);
foreach ($Parameters as $key => $parameter) {
if (is_array($parameter->value) && count($parameter->value) > 1) {
$p = $Document->createElement($key);
$p->setAttribute('value', (string) $parameter);
foreach ($parameter->value as $v) {
$p->appendChild($Document->createElement('item', (string) $v));
}
$element->appendChild($p);
} else {
$element->appendChild($Document->createElement($key, (string) $parameter));
}
}
$template = $this->template;
####
//.........这里部分代码省略.........
示例10: delete
public function delete($datasource)
{
/*
TODO:
Upon deletion of the event, views need to be updated to remove
it's associated with the event
*/
if (!$datasource instanceof DataSource) {
$datasource = Datasource::loadFromHandle($datasource);
}
$handle = $datasource->handle;
if (!$datasource->allowEditorToParse()) {
throw new DataSourceException(__('Datasource cannot be deleted, the Editor does not have permission.'));
}
return General::deleteFile(DATASOURCES . "/{$handle}.php");
}
示例11: render
public function render(Register $ParameterOutput, $joins = NULL, array $where = array(), $filter_operation_type = self::FILTER_AND)
{
$execute = true;
$result = new XMLDocument();
$result->appendChild($result->createElement($this->parameters()->{'root-element'}));
$root = $result->documentElement;
// Conditions
// If any one condtion returns true (that is, do not execute), the DS will not execute at all
if (is_array($this->parameters()->conditions)) {
foreach ($this->parameters()->conditions as $condition) {
if (preg_match('/:/', $condition['parameter'])) {
$c = Datasource::replaceParametersInString($condition['parameter'], $ParameterOutput);
} else {
$c = Datasource::resolveParameter($condition['parameter'], $ParameterOutput);
}
// Is Empty
if ($condition['logic'] == 'empty' && (is_null($c) || strlen($c) == 0)) {
$execute = false;
} elseif ($condition['logic'] == 'set' && !is_null($c)) {
$execute = false;
}
if ($execute !== true) {
return NULL;
}
}
}
// Grab the section
try {
$section = Section::loadFromHandle($this->parameters()->section);
} catch (SectionException $e) {
} catch (Exception $e) {
}
$pagination = (object) array('total-entries' => NULL, 'entries-per-page' => max(1, (int) self::replaceParametersInString($this->parameters()->limit, $ParameterOutput)), 'total-pages' => NULL, 'current-page' => max(1, (int) self::replaceParametersInString($this->parameters()->page, $ParameterOutput)));
$pagination->{'record-start'} = max(0, ($pagination->{'current-page'} - 1) * $pagination->{'entries-per-page'});
$order = $sort = NULL;
// Apply the Sorting & Direction
if ($this->parameters()->{'sort-order'} == 'random') {
$order = 'RAND()';
} else {
$sort = strtolower($this->parameters()->{'sort-order'}) == 'asc' ? 'ASC' : 'DESC';
// System Field
if (preg_match('/^system:/i', $this->parameters()->{'sort-field'})) {
switch (preg_replace('/^system:/i', NULL, $this->parameters()->{'sort-field'})) {
case 'id':
$order = "e.id {$sort}";
break;
case 'creation-date':
$order = "e.creation_date {$sort}";
break;
case 'modification-date':
$order = "e.modification_date {$sort}";
break;
}
} else {
$join = NULL;
$sort_field = $section->fetchFieldByHandle($this->parameters()->{'sort-field'});
if ($sort_field instanceof Field && $sort_field->isSortable() && method_exists($sort_field, "buildSortingQuery")) {
$sort_field->buildSortingQuery($join, $order);
$joins .= sprintf($join, $sort_field->section, $sort_field->{'element-name'});
$order = sprintf($order, $sort);
}
}
}
// Process Datasource Filters for each of the Fields
if (is_array($this->parameters()->filters) && !empty($this->parameters()->filters)) {
foreach ($this->parameters()->filters as $k => $filter) {
if ($filter['element-name'] == 'system:id') {
$filter_value = $this->prepareFilterValue($filter['value'], $ParameterOutput);
if (!is_array($filter_value)) {
continue;
}
$filter_value = array_map('intval', $filter_value);
if (empty($filter_value)) {
continue;
}
$where[] = sprintf("(e.id %s IN (%s))", $filter['type'] == 'is-not' ? 'NOT' : NULL, implode(',', $filter_value));
} else {
$field = $section->fetchFieldByHandle($filter['element-name']);
if ($field instanceof Field) {
$field->buildFilterQuery($filter, $joins, $where, $ParameterOutput);
}
}
}
}
// Escape percent symbold:
$where = array_map(create_function('$string', 'return str_replace(\'%\', \'%%\', $string);'), $where);
$query = sprintf('SELECT DISTINCT SQL_CALC_FOUND_ROWS e.*
FROM `tbl_entries` AS `e`
%1$s
WHERE `section` = "%2$s"
%3$s
ORDER BY %4$s
LIMIT %5$d, %6$d', $joins, $section->handle, is_array($where) && !empty($where) ? 'AND (' . implode($filter_operation_type == self::FILTER_AND ? ' AND ' : ' OR ', $where) . ')' : NULL, $order, $pagination->{'record-start'}, $pagination->{'entries-per-page'});
try {
$entries = Symphony::Database()->query($query, array($section->handle, $section->{'publish-order-handle'}), 'EntryResult');
if (isset($this->parameters()->{'append-pagination'}) && $this->parameters()->{'append-pagination'} === true) {
$pagination->{'total-entries'} = (int) Symphony::Database()->query("SELECT FOUND_ROWS() AS `total`")->current()->total;
$pagination->{'total-pages'} = (int) ceil($pagination->{'total-entries'} * (1 / $pagination->{'entries-per-page'}));
// Pagination Element
$root->appendChild(General::buildPaginationElement($result, $pagination->{'total-entries'}, $pagination->{'total-pages'}, $pagination->{'entries-per-page'}, $pagination->{'current-page'}));
//.........这里部分代码省略.........
示例12: __actionDelete
protected function __actionDelete(array $datasources, $redirect = NULL)
{
$success = true;
foreach ($datasources as $handle) {
try {
Datasource::delete($handle);
} catch (DatasourceException $e) {
$success = false;
$this->alerts()->append($e->getMessage(), AlertStack::ERROR, $e);
} catch (Exception $e) {
$success = false;
$this->alerts()->append(__('An unknown error has occurred. <a class="more">Show trace information.</a>'), AlertStack::ERROR, $e);
}
// TODO: Delete reference from View XML
/*$sql = "SELECT * FROM `tbl_pages` WHERE `data_sources` REGEXP '[[:<:]]".$ds."[[:>:]]' ";
$pages = Symphony::Database()->fetch($sql);
if(is_array($pages) && !empty($pages)){
foreach($pages as $page){
$page['data_sources'] = preg_replace('/\b'.$ds.'\b/i', '', $page['data_sources']);
Symphony::Database()->update($page, 'tbl_pages', "`id` = '".$page['id']."'");
}
}*/
}
if ($success) {
redirect($redirect);
}
}
示例13: _getTables
/**
* _getTables
* @return array
*/
protected function _getTables()
{
$this->tables = array();
$tables = Set::extract('/TABLE_NAMES/.', $this->_db->query('SHOW TABLES'));
foreach ($tables as $table) {
$this->tables = array_merge($this->tables, array_values($table));
}
return $this->tables;
}
示例14: __construct
/**
* Initialise data source
*/
public function __construct(&$parent, $env = NULL, $process_params = true)
{
parent::__construct($parent, $env, $process_params);
$this->dsParamLANG = array();
// Load language codes from configuration
$languages = Symphony::Configuration()->get('datetime');
foreach ($languages as $name => $codes) {
$this->dsParamLANG[] = explode(', ', $codes);
}
}
示例15: __construct
/**
*
* Class constructor
* @param object $parent
* @param array $env
* @param boolean $process_params
*/
public function __construct(array $env = null, $process_params = true)
{
parent::__construct($env, $process_params);
// detect if multilangual field AND language redirect is enabled
$this->isMultiLangual = Symphony::ExtensionManager()->fetchStatus('page_lhandles') == EXTENSION_ENABLED && Symphony::ExtensionManager()->fetchStatus('language_redirect') == EXTENSION_ENABLED;
// add a ref to the Language redirect
if ($this->isMultiLangual) {
require_once EXTENSIONS . '/language_redirect/lib/class.languageredirect.php';
}
}