tripal_chado.variables.api.inc

This API generates objects containing the full details of a record(s) in chado.

File

tripal_chado/api/tripal_chado.variables.api.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * This API generates objects containing the full details of a record(s) in chado.
  5. *
  6. * @ingroup tripal_chado
  7. */
  8. /**
  9. * @defgroup tripal_chado_variables_api Semantic Web
  10. * @ingroup tripal_chado_api
  11. *
  12. * @{
  13. * This API generates objects containing the full details of a record(s) in chado.
  14. * @}
  15. */
  16. /**
  17. * Generates an object containing the full details of a record(s) in Chado.
  18. *
  19. * The object returned contains key/value pairs where the keys are the fields
  20. * in the Chado table.
  21. *
  22. * The returned object differs from the array returned by chado_select_record()
  23. * as all foreign key relationships in the Chado table have been followed and
  24. * those data are also included. This function automatically excludes some
  25. * fields and tables. Fields that are extremely long, such as text fields are
  26. * automatically excluded to prevent long page loads. Linking tables that have
  27. * a many-to-one relationship with the record are also excluded. Use the
  28. * chado_expand_var() to manually add in excluded fields and data from linker
  29. * tables.
  30. *
  31. * Example Usage:
  32. * @code
  33. * $values = array(
  34. * 'name' => 'Medtr4g030710'
  35. * );
  36. * $feature = chado_generate_var('feature', $values);
  37. * @endcode
  38. *
  39. * The $values array passed to this fucntion can be of the same format used
  40. * by the chado_select_record() function.
  41. *
  42. * If a field is a foreign key then its value is an object that contains
  43. * key/value pairs for that record. The following code provides examples
  44. * for retrieving values associated with the record, either as columns in the
  45. * original Chado table or as columns in linked records through foreign keys:
  46. * @code
  47. * // Get the feature name.
  48. * $name = $feature->name;
  49. * // Get the feature unique name.
  50. * $uniquename = $feature->uniquename;
  51. * // Get the feature type. Because the type name is obtained via
  52. * // a foreign key with the cvterm table, the objects are nested
  53. * // and we can follow the foreign key fields to retrieve those values
  54. * $type = $feature->type_id->name;
  55. * // Get the name of the vocabulary.
  56. * $cv = $feature->type_id->cv_id->name;
  57. * // Get the vocabulary id.
  58. * $cv_id = $feature->type_id->cv_id->cv_id;
  59. * @endcode
  60. *
  61. *
  62. * This will return an object if there is only one feature with the name
  63. * Medtr4g030710 or it will return an array of feature objects if more than one
  64. * feature has that name.
  65. *
  66. * Note to Module Designers: Fields can be excluded by default from these
  67. * objects by implementing one of the following hooks:
  68. * - hook_exclude_field_from_tablename_by_default (where tablename is the
  69. * name of the table): This hook allows you to add fields to be excluded
  70. * on a per table basis. Simply implement this hook to return an array of
  71. * fields to be excluded. The following example will ensure that
  72. * feature.residues is excluded from a feature object by default:
  73. * @code
  74. * mymodule_exclude_field_from_feature_by_default() {
  75. * return array('residues' => TRUE);
  76. * }
  77. * @endcode
  78. * - hook_exclude_type_by_default:
  79. * This hook allows you to exclude fields using conditional. This
  80. * function should return an array of postgresql types mapped to criteria.
  81. * If the field types of any table match the criteria then the field
  82. * is excluded. Tokens available in criteria are &gt;field_value&lt;
  83. * and &gt;field_name&lt;. The following example will exclude all text
  84. * fields with a length > 50. Thus if $feature.residues is longer than
  85. * 50 it will be excluded, otherwise it will be added.
  86. * @code
  87. * mymodule_exclude_type_by_default() {
  88. * return array('text' => 'length(&gt;field_value&lt; ) > 50');
  89. * }
  90. * @endcode
  91. *
  92. *
  93. * @param $table
  94. * The name of the base table to generate a variable for
  95. * @param $values
  96. * A select values array that selects the records you want from the base table
  97. * (this has the same form as chado_select_record)
  98. * @param $base_options
  99. * An array containing options for the base table. For example, an
  100. * option of 'order_by' may be used to sort results in the base table
  101. * if more than one are returned. The options must be compatible with
  102. * the options accepted by the chado_select_record() function.
  103. * Additionally, These options are available for this function:
  104. * -return_array:
  105. * can be provided to force the function to always return an array. Default
  106. * behavior is to return a single record if only one record exists or to
  107. * return an array if multiple records exist.
  108. * - include_fk:
  109. * an array of FK relationships to follow. By default, the
  110. * chado_select_record function will follow all FK relationships but this
  111. * may generate more queries then is desired slowing down this function
  112. * call when there are lots of FK relationships to follow. Provide an
  113. * array specifying the fields to include. For example, if expanding a
  114. * property table (e.g. featureprop) and you want the CV and accession
  115. * but do not want the DB the following array would work:
  116. *
  117. * $table_options = array(
  118. * 'include_fk' => array(
  119. * 'type_id' => array(
  120. * 'cv_id' => 1,
  121. * 'dbxref_id' => 1,
  122. * )
  123. * )
  124. * );
  125. *
  126. * The above array will expand the 'type_id' of the property table but only
  127. * further expand the cv_id and the dbxref_id and will go no further.
  128. * - pager:
  129. * Use this option if it is desired to return only a subset of results
  130. * so that they may be shown within a Drupal-style pager. This should be
  131. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  132. * should specify the number of records to return and 'element' is a
  133. * unique integer to differentiate between pagers when more than one
  134. * appear on a page. The 'element' should start with zero and increment by
  135. * one for each pager.
  136. * @return
  137. * Either an object (if only one record was selected from the base table)
  138. * or an array of objects (if more than one record was selected from the
  139. * base table). If the option 'return_array' is provided the function
  140. * always returns an array.
  141. *
  142. * @ingroup tripal_chado_variables_api
  143. */
  144. function chado_generate_var($table, $values, $base_options = array()) {
  145. $all = new stdClass();
  146. $return_array = 0;
  147. if (array_key_exists('return_array', $base_options)) {
  148. $return_array = 1;
  149. }
  150. $include_fk = FALSE;
  151. if (array_key_exists('include_fk', $base_options)) {
  152. $include_fk = $base_options['include_fk'];
  153. }
  154. $pager = array();
  155. if (array_key_exists('pager', $base_options)) {
  156. $pager = $base_options['pager'];
  157. }
  158. // get description for the current table-------------------------------------
  159. $table_desc = chado_get_schema($table);
  160. if (!$table_desc or count($table_desc) == 0) {
  161. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  162. "chado_generate_var: The table '%table' has not been defined " .
  163. "and cannot be expanded. If this is a custom table, please add it using the Tripal " .
  164. "custom table interface. Values: %values",
  165. array('%table' => $table, '%values' => print_r($values, TRUE)));
  166. if ($return_array) {
  167. return array();
  168. }
  169. return FALSE;
  170. }
  171. $table_primary_key = $table_desc['primary key'][0];
  172. $table_columns = array_keys($table_desc['fields']);
  173. // Expandable fields without value needed for criteria-----------------------
  174. // Add in the default expandable arrays
  175. // These are used for later expanding fields, tables, foreign keys and nodes
  176. $all->expandable_fields = array();
  177. $all->expandable_foreign_keys = array();
  178. if (array_key_exists('referring_tables', $table_desc) and $table_desc['referring_tables']) {
  179. $all->expandable_tables = $table_desc['referring_tables'];
  180. }
  181. else {
  182. $all->expandable_tables = array();
  183. }
  184. $all->expandable_nodes = array();
  185. // Get fields to be removed by name.................................
  186. // This gets all implementations of hook_exclude_field_from_<table>_by_default()
  187. // where <table> is the current table a variable is being created for.
  188. // This allows modules to specify that some fields should be excluded by default
  189. // For example, tripal core provides a tripal_chado_exclude_field_from_feature_by_default()
  190. // which says that we usually don't want to include the residues field by
  191. // default since it can be very large and cause performance issues.
  192. // If a field is excluded by default it can always be expanded at a later
  193. // point by calling chado_expand_var($chado_var, 'field',
  194. // <field name as shown in expandable_fields array>);
  195. // First get an array of all the fields to be removed for the current table
  196. // module_invoke_all() is drupal's way of invoking all implementations of the
  197. // specified hook and merging all of the results.
  198. // $fields_to_remove should be an array with the keys matching field names
  199. // and the values being strings to be executed using php_eval() to determine
  200. // whether to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
  201. $fields_to_remove = module_invoke_all('exclude_field_from_' . $table . '_by_default');
  202. // Now, for each field to be removed
  203. foreach ($fields_to_remove as $field_name => $criteria) {
  204. //Replace <field_name> with the current field name
  205. $field_name_safe = preg_replace("/\'\"\\\/", '\\1', $field_name);
  206. $criteria = preg_replace('/<field_name> /', $field_name_safe, $criteria);
  207. // If field_value needed we can't deal with this field yet.
  208. if (preg_match('/<field_value> /', $criteria)) {
  209. break;
  210. }
  211. // If criteria then remove from query
  212. // @coder-ignore: only module designers can populate $criteria -not a
  213. // security risk.
  214. $success = php_eval('<?php return ' . $criteria . '; ?>');
  215. if ($success) {
  216. unset($table_columns[array_search($field_name, $table_columns)]);
  217. unset($fields_to_remove[$field_name]);
  218. $all->expandable_fields[] = $table . '.' . $field_name;
  219. }
  220. }
  221. // Get fields to be removed by type................................
  222. // This gets all implementations of hook_exclude_type_by_default().
  223. // This allows modules to specify that some types of fields should be excluded
  224. // by default For example, tripal core provides a
  225. // tripal_chado_exclude_type_by_default() which says that text fields are
  226. // often very large and if they are longer than 250 characters then
  227. // we want to exclude them by default
  228. // If a field is excluded by default it can always be expanded at a later
  229. // point by calling chado_expand_var($chado_var, 'field',
  230. //<field name as shown in expandable_fields array>);
  231. // First get an array of all the types of fields to be removed for the current
  232. // table module_invoke_all() is drupal's way of invoking all implementations
  233. // of the specified hook and merging all of the results.
  234. // $types_to_remove should be an array with the keys matching field names
  235. // and the values being strings to be executed using php_eval() to determine
  236. // whether to exclude the field (evaluates to TRUE) or not (evaluates to FALSE)
  237. // (ie: array('text' => 'strlen("<field_value> ") > 100');
  238. $types_to_remove = module_invoke_all('exclude_type_by_default');
  239. // Get a list of all the types of fields
  240. // the key is the type of field and the value is an array of fields of this
  241. // type.
  242. $field_types = array();
  243. foreach ($table_desc['fields'] as $field_name => $field_array) {
  244. $field_types[$field_array['type']][] = $field_name;
  245. }
  246. // We want to use the types to remove in conjunction with our table field
  247. // descriptions to determine which fields might need to be removed.
  248. foreach ($types_to_remove as $field_type => $criteria) {
  249. // If there are fields of that type to remove.
  250. if (isset($field_types[$field_type])) {
  251. // Do any processing needed on the php criteria
  252. //replace <field_name> with the current field name.
  253. $field_name_safe = preg_replace('/\'|"|\\\/', '\\1', $field_name);
  254. $criteria = preg_replace('/<field_name> /', $field_name_safe, $criteria);
  255. foreach ($field_types[$field_type] as $field_name) {
  256. // if field_value needed we can't deal with this field yet
  257. if (preg_match('/<field_value>/', $criteria)) {
  258. $fields_to_remove[$field_name] = $criteria;
  259. continue;
  260. }
  261. // If criteria then remove from query
  262. // (as long as <field_value> is not needed for the criteria to be
  263. // evaluated) @coder-ignore: only module designers can populate
  264. //$criteria -not a security risk.
  265. $success = php_eval('<?php return ' . $criteria . '; ?>');
  266. if ($success) {
  267. unset($table_columns[array_search($field_name, $table_columns)]);
  268. $all->expandable_fields[] = $table . '.' . $field_name;
  269. }
  270. } // End of foreach field of that type.
  271. }
  272. } // End of foreach type to be removed.
  273. // Get the values for the record in the current table-------------------------
  274. $results = chado_select_record($table, $table_columns, $values, $base_options);
  275. if ($results) {
  276. // Iterate through each result.
  277. foreach ($results as $key => $object) {
  278. // Add empty expandable_x arrays.
  279. $object->expandable_fields = $all->expandable_fields;
  280. $object->expandable_foreign_keys = $all->expandable_foreign_keys;
  281. $object->expandable_tables = $all->expandable_tables;
  282. $object->expandable_nodes = $all->expandable_nodes;
  283. // add curent table
  284. $object->tablename = $table;
  285. // For Tripal v2 compatibility
  286. // check if the current table maps to a node type-------------------------
  287. // If this table is connected to a node there will be a chado_tablename
  288. // table in drupal.
  289. if (module_exists('tripal_core') and db_table_exists('chado_' . $table)) {
  290. // That has a foreign key to this one ($table_desc['primary key'][0]
  291. // and to the node table (nid).
  292. $sql = "
  293. SELECT $table_primary_key, nid
  294. FROM {chado_$table}
  295. WHERE $table_primary_key = :$table_primary_key
  296. ";
  297. $mapping = db_query($sql, array(":$table_primary_key" => $object->{$table_primary_key}))->fetchObject();
  298. if ($mapping and $mapping->$table_primary_key) {
  299. $object->nid = $mapping->nid;
  300. $object->expandable_nodes[] = $table;
  301. }
  302. }
  303. // Check to see if the current record maps to an entity. Because
  304. // multiple bundles can map to the same table we have to check
  305. // all bundles for this table.
  306. $entity_id = chado_get_record_entity_by_table($table, $object->{$table_primary_key});
  307. if ($entity_id) {
  308. $object->entity_id = $entity_id;
  309. }
  310. // Remove any fields where criteria needs to be evalulated----------------
  311. // The fields to be removed can be populated by implementing either
  312. // hook_exclude_field_from_<table>_by_default() where <table> is the
  313. // current table OR hook_exclude_type_by_default() where there are fields
  314. // of the specified type in the current table It only reaches this point
  315. // if the criteria specified for whether or not to exclude the field
  316. // includes <field_value> which means it has to be evaluated after
  317. // the query has been executed.
  318. foreach ($fields_to_remove as $field_name => $criteria) {
  319. // If the field is an object then we don't support exclusion of it
  320. // For example, if the field is a foreign key
  321. if (!isset($object->{$field_name})) {
  322. break;
  323. }
  324. // Replace <field_value> with the actual value of the field from the
  325. // query.
  326. $field_name_safe = preg_replace('/\'|"|\\\/', '\\1', $object->{$field_name});
  327. $criteria = preg_replace('/<field_value>/', $field_name_safe, $criteria);
  328. // evaluate the criteria, if TRUE is returned then exclude the field
  329. // excluded fields can be expanded later by calling
  330. // chado_expand_var($var, 'field', <field name as shown in expandable_fields array>);
  331. $success = php_eval('<?php return ' . $criteria . '; ?>');
  332. if ($success) {
  333. unset($object->{$field_name});
  334. $object->expandable_fields[] = $table . '.' . $field_name;
  335. }
  336. }
  337. // Recursively follow foreign key relationships nesting objects as we go------------------------
  338. if (array_key_exists('foreign keys', $table_desc) and $table_desc['foreign keys']) {
  339. foreach ($table_desc['foreign keys'] as $foreign_key_array) {
  340. $foreign_table = $foreign_key_array['table'];
  341. foreach ($foreign_key_array['columns'] as $foreign_key => $primary_key) {
  342. // Note: Foreign key is the field in the current table whereas
  343. // primary_key is the field in the table referenced by the foreign
  344. // key, don't do anything if the foreign key is empty
  345. if (empty($object->{$foreign_key})) {
  346. continue;
  347. }
  348. if (is_array($include_fk)) {
  349. // Don't recurse if the callee has supplied an $fk_include list
  350. // and this FK table is not in the list.
  351. if (is_array($include_fk) and !array_key_exists($foreign_key, $include_fk)) {
  352. $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
  353. continue;
  354. }
  355. }
  356. // If we have the option but it is not an array then we don't
  357. // recurse any further.
  358. if ($include_fk === TRUE) {
  359. $object->expandable_foreign_keys[] = $table . '.' . $foreign_key . ' => ' . $foreign_table;
  360. continue;
  361. }
  362. // Get the record from the foreign table.
  363. $foreign_values = array($primary_key => $object->{$foreign_key});
  364. $options = array();
  365. if (is_array($include_fk)) {
  366. $options['include_fk'] = $include_fk[$foreign_key];
  367. }
  368. $foreign_object = chado_generate_var($foreign_table, $foreign_values, $options);
  369. // Add the foreign record to the current object in a nested manner.
  370. $object->{$foreign_key} = $foreign_object;
  371. // Flatten expandable_x arrays so only in the bottom object.
  372. if (property_exists($object->{$foreign_key}, 'expandable_fields') and
  373. is_array($object->{$foreign_key}->expandable_fields)) {
  374. $object->expandable_fields = array_merge(
  375. $object->expandable_fields,
  376. $object->{$foreign_key}->expandable_fields
  377. );
  378. unset($object->{$foreign_key}->expandable_fields);
  379. }
  380. if (property_exists($object->{$foreign_key}, 'expandable_foreign_keys') and
  381. is_array($object->{$foreign_key}->expandable_foreign_keys)) {
  382. $object->expandable_foreign_keys = array_merge(
  383. $object->expandable_foreign_keys,
  384. $object->{$foreign_key}->expandable_foreign_keys
  385. );
  386. unset($object->{$foreign_key}->expandable_foreign_keys);
  387. }
  388. if (property_exists($object->{$foreign_key}, 'expandable_tables') and
  389. is_array($object->{$foreign_key}->expandable_tables)) {
  390. $object->expandable_tables = array_merge(
  391. $object->expandable_tables,
  392. $object->{$foreign_key}->expandable_tables
  393. );
  394. unset($object->{$foreign_key}->expandable_tables);
  395. }
  396. if (property_exists($object->{$foreign_key}, 'expandable_nodes') and
  397. is_array($object->{$foreign_key}->expandable_nodes)) {
  398. $object->expandable_nodes = array_merge(
  399. $object->expandable_nodes,
  400. $object->{$foreign_key}->expandable_nodes
  401. );
  402. unset($object->{$foreign_key}->expandable_nodes);
  403. }
  404. }
  405. }
  406. $results[$key] = $object;
  407. }
  408. }
  409. }
  410. // Convert the results into an array.
  411. $results_arr = array();
  412. foreach ($results as $record) {
  413. $results_arr[] = $record;
  414. }
  415. // Check only one result returned.
  416. if (!$return_array) {
  417. if (sizeof($results_arr) == 1) {
  418. // Add results to object.
  419. return $results_arr[0];
  420. }
  421. elseif (!empty($results_arr)) {
  422. return $results_arr;
  423. }
  424. else {
  425. // No results returned.
  426. }
  427. }
  428. // The caller has requested results are always returned as
  429. // an array.
  430. else {
  431. if (!$results_arr) {
  432. return array();
  433. }
  434. else {
  435. return $results_arr;
  436. }
  437. }
  438. }
  439. /**
  440. * Retrieves fields, or tables that were excluded by default from a variable.
  441. *
  442. * The chado_generate_var() function automatically excludes some
  443. * fields and tables from the default form of a variable. Fields that are
  444. * extremely long, such as text fields are automatically excluded to prevent
  445. * long page loads. Linking tables that have a many-to-one relationship with
  446. * the record are also excluded. This function allows for custom expansion
  447. * of the record created by chado_generate_var() by specifyin the field and
  448. * tables that should be added.
  449. *
  450. * Example Usage:
  451. * @code
  452. * // Get a chado object to be expanded
  453. * $values = array(
  454. * 'name' => 'Medtr4g030710'
  455. * );
  456. * $features = chado_generate_var('feature', $values);
  457. * // Expand the feature.residues field
  458. * $feature = chado_expand_var($feature, 'field', 'feature.residues');
  459. * // Expand the feature properties (featureprop table)
  460. * $feature = chado_expand_var($feature, 'table', 'featureprop');
  461. * @endcode
  462. *
  463. * If a field is requested, it's value is added where it normally is expected
  464. * in the record. If a table is requested then a new key/value element is
  465. * added to the record. The key is the table's name and the value is an
  466. * array of records (of the same type created by chado_generate_var()). For
  467. * example, expanding a 'feature' record to include a 'pub' record via the
  468. * 'feature_pub' table. The following provides a simple example for how
  469. * the 'feature_pub' table is added.
  470. *
  471. * @code
  472. * array(
  473. * 'feature_id' => 1
  474. * 'name' => 'blah',
  475. * 'uniquename' => 'blah',
  476. * ....
  477. * 'feature_pub => array(
  478. * [pub object],
  479. * [pub object],
  480. * [pub object],
  481. * [pub object],
  482. * )
  483. * )
  484. * @endcode
  485. *
  486. * where [pub object] is a record of a publication as created by
  487. * chado_generate_var().
  488. *
  489. * If the requested table has multiple foreign keys, such as the 'featureloc'
  490. * or 'feature_genotype' tables, then an additional level is added to the
  491. * array where the foreign key column names are added. An example feature
  492. * record with an expanded featureloc table is shown below:
  493. *
  494. * @code
  495. * array(
  496. * 'feature_id' => 1
  497. * 'name' => 'blah',
  498. * 'uniquename' => 'blah',
  499. * ....
  500. * 'featureloc => array(
  501. * 'srcfeature_id' => array(
  502. * [feature object],
  503. * ...
  504. * )
  505. * 'feature_id' => array(
  506. * [feature object],
  507. * ...
  508. * )
  509. * )
  510. * )
  511. * @endcode
  512. *
  513. * @param $object
  514. * This must be an object generated using chado_generate_var()
  515. * @param $type
  516. * Indicates what is being expanded. Must be one of 'field', 'foreign_key',
  517. * 'table', 'node'. While field and node are self-explanitory, it might help
  518. * to note that 'table' refers to tables that have a foreign key pointing to
  519. * the current table (ie: featureprop is a table that can be expanded for
  520. * features) and 'foreign_key' expands a foreign key in the current table
  521. * that might have been excluded (ie: feature.type_id for features).
  522. * @param $to_expand
  523. * The name of the field/foreign_key/table/node to be expanded
  524. * @param $table_options
  525. * - order_by:
  526. * An array containing options for the base table. For example, an
  527. * option of 'order_by' may be used to sort results in the base table
  528. * if more than one are returned. The options must be compatible with
  529. * the options accepted by the chado_select_record() function.
  530. * - return_array:
  531. * Additionally, The option 'return_array' can be provided to force
  532. * the function to expand tables as an array. Default behavior is to expand
  533. * a table as single record if only one record exists or to expand as an
  534. * array if multiple records exist.
  535. * - include_fk:
  536. * an array of FK relationships to follow. By default, the
  537. * chado_expand_var function will follow all FK relationships but this
  538. * may generate more queries then is desired slowing down this function call
  539. * when there are lots of FK relationships to follow. Provide an array
  540. * specifying the fields to include. For example, if expanding a property
  541. * table (e.g. featureprop) and you want the CV and accession but do not
  542. * want the DB the following array would work:
  543. * $table_options = array(
  544. * 'include_fk' => array(
  545. * 'type_id' => array(
  546. * 'cv_id' => 1,
  547. * 'dbxref_id' => 1,
  548. * )
  549. * )
  550. * );
  551. *
  552. * The above array will expand the 'type_id' of the property table but only
  553. * further expand the cv_id and the dbxref_id and will go no further.
  554. * - pager:
  555. * Use this option if it is desired to return only a subset of results
  556. * so that they may be shown within a Drupal-style pager. This should be
  557. * an array with two keys: 'limit' and 'element'. The value of 'limit'
  558. * should specify the number of records to return and 'element' is a
  559. * unique integer to differentiate between pagers when more than one
  560. * appear on a page. The 'element' should start with zero and increment by
  561. * one for each pager. This only works when type is a 'table'.
  562. * - filter:
  563. * This options is only used where type=table and allows you to
  564. * expand only a subset of results based on the given criteria. Criteria
  565. * should provided as an array of [field name] => [value] similar to the
  566. * values array provided to chado_generate_var(). For example, when
  567. * expanding the featureprop table for a feature, you will already get only
  568. * properties for that feature, this option allows you to further get only
  569. * properties of a given type by passing in
  570. * array('type_id' => array('name' => [name of type]))
  571. * @return
  572. * A chado object supplemented with the field/table/node requested to be
  573. * expanded. If the type is a table and it has already been expanded no
  574. * changes is made to the returned object
  575. *
  576. *
  577. * @ingroup tripal_chado_variables_api
  578. */
  579. function chado_expand_var($object, $type, $to_expand, $table_options = array()) {
  580. // Make sure we have a value.
  581. if (!$object) {
  582. tripal_report_error('tripal_chado',
  583. TRIPAL_ERROR,
  584. 'Cannot pass non array as argument, $object, to chado_expand_var function.',
  585. array());
  586. return $object;
  587. }
  588. // Check to see if we are expanding an array of objects.
  589. if (is_array($object)) {
  590. foreach ($object as $index => $o) {
  591. $object[$index] = chado_expand_var($o, $type, $to_expand);
  592. }
  593. return $object;
  594. }
  595. // Get the base table name.
  596. $base_table = $object->tablename;
  597. switch ($type) {
  598. case "field": //------------------------------------------------------------
  599. if (preg_match('/(\w+)\.(\w+)/', $to_expand, $matches)) {
  600. $tablename = $matches[1];
  601. $fieldname = $matches[2];
  602. $table_desc = chado_get_schema($tablename);
  603. // BASE CASE: the field is from the current table.
  604. if ($base_table == $tablename) {
  605. // Use the table description to fully describe the current object
  606. // in a $values array to be used to select the field from chado.
  607. $values = array();
  608. foreach ($table_desc['primary key'] as $key) {
  609. if(property_exists($object, $key)) {
  610. $values[$key] = $object->{$key};
  611. }
  612. }
  613. // Retrieve the field from Chado.
  614. $results = chado_select_record($tablename, array($fieldname), $values);
  615. // Check that the field was retrieved correctly.
  616. if (isset($results[0])) {
  617. $object->{$fieldname} = $results[0]->{$fieldname};
  618. $object->expanded = $to_expand;
  619. }
  620. // If it wasn't retrieved correctly, we need to warn the administrator.
  621. }
  622. // RECURSIVE CASE: the field is in a nested object.
  623. else {
  624. // We want to look at each field and if it's an object then we want to
  625. // attempt to expand the field in it via recursion.
  626. foreach ((array) $object as $field_name => $field_value) {
  627. if (is_object($field_value)) {
  628. $object->{$field_name} = chado_expand_var(
  629. $field_value,
  630. 'field',
  631. $to_expand
  632. );
  633. }
  634. } // End of for each field in the current object.
  635. }
  636. }
  637. // Otherwise we weren't able to extract the parts of the field to expand
  638. // Thus we will warn the administrator.
  639. else {
  640. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  641. 'chado_expand_var: Field (%field) not in the right format. " .
  642. "It should be <tablename>.<fieldname>', array('%field' => $to_expand));
  643. }
  644. break;
  645. case "foreign_key": //-----------------------------------------------------
  646. if (preg_match('/(\w+)\.(\w+) => (\w+)/', $to_expand, $matches)) {
  647. $table_name = $matches[1];
  648. $field_name = $matches[2];
  649. $foreign_table = $matches[3];
  650. $table_desc = chado_get_schema($table_name);
  651. // BASE CASE: The foreign key is from the current table.
  652. if ($base_table == $table_name) {
  653. // Get the value of the foreign key from the object
  654. $field_value = $object->{$field_name};
  655. // Get the name of the field in the foreign table using the table
  656. // description For example, with the
  657. // feature.type_id => cvterm.cvterm_id we need cvterm_id
  658. $foreign_field_name = FALSE;
  659. foreach ($table_desc['foreign keys'][$foreign_table]['columns'] as $left => $right) {
  660. if ($right == $field_name) {
  661. $foreign_field_name = $left;
  662. }
  663. }
  664. // Check that we were able to determine the field name in the foreign
  665. // table.
  666. if ($foreign_field_name) {
  667. // Generate a chado variable of the foreign key
  668. // For example, if the foreign key to expand is feature.type_id
  669. // then we want to generate a chado cvterm variable that matches the
  670. // feature.type_id.
  671. $foreign_var = chado_generate_var(
  672. $foreign_table, // thus in the example above, generate a cvterm var
  673. array($foreign_field_name => $field_value), // where the cvterm.cvterm_id = feature.type_id value
  674. $table_options //pass in the same options given to this function
  675. );
  676. // Check that the foreign object was returned.
  677. if ($foreign_var) {
  678. // It was so now we can add this chado variable to our current
  679. // object in place of the key value.
  680. $object->{$field_name} = $foreign_var;
  681. $object->expanded = $to_expand;
  682. }
  683. // Otherwise we weren't able to expand the foreign key
  684. else {
  685. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  686. 'chado_expand_var: unable to retrieve the object desribed by the foreign key
  687. while trying to expand %fk.',
  688. array('%fk' => $to_expand));
  689. }
  690. }
  691. // Else we were unable to determine the field name in the foreign table.
  692. else {
  693. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  694. 'chado_expand_var: unable to determine the field name in the table the foreign
  695. key points to while trying to expand %fk.',
  696. array('%fk' => $to_expand));
  697. }
  698. }
  699. // RECURSIVE CASE: Check any nested objects.
  700. else {
  701. foreach ((array) $object as $field_name => $field_value) {
  702. if (is_object($field_value)) {
  703. $object->{$field_name} = chado_expand_var(
  704. $field_value,
  705. 'foreign_key',
  706. $to_expand
  707. );
  708. }
  709. } //End of for each field in the current object.
  710. }
  711. }
  712. // Otherwise we weren't able to extract the parts of the foreign key to
  713. // expand thus we will warn the administrator.
  714. else {
  715. tripal_report_error('tripal_chado', TRIPAL_ERROR,
  716. 'chado_expand_var: foreign_key (%fk) not in the right format. " .
  717. "It should be <tablename>.<fieldname>', array('%fk' => $to_expand));
  718. }
  719. break;
  720. case "table": //------------------------------------------------------------
  721. $foreign_table = $to_expand;
  722. // BASE CASE: don't expand the table it already is expanded
  723. if (array_key_exists($foreign_table, $object)) {
  724. return $object;
  725. }
  726. $foreign_table_desc = chado_get_schema($foreign_table);
  727. // TODO: if we don't get a foreign_table (which could happen of a custom
  728. // table is not correctly defined or the table name is mispelled then we
  729. // should return gracefully.
  730. // BASE CASE: If it's connected to the base table via a FK constraint
  731. // then we have all the information needed to expand it now.
  732. if (array_key_exists($base_table, $foreign_table_desc['foreign keys'])) {
  733. foreach ($foreign_table_desc['foreign keys'][$base_table]['columns'] as $left => $right) {
  734. // if the FK value in the base table is not there then we can't expand
  735. // it, so just skip it.
  736. if (!$object->{$right}) {
  737. continue;
  738. }
  739. // If the user wants to limit the results they expand, make sure
  740. // those criteria are taken into account.
  741. if (isset($table_options['filter'])) {
  742. if (is_array($table_options['filter'])) {
  743. $filter_criteria = $table_options['filter'];
  744. $filter_criteria[$left] = $object->{$right};
  745. }
  746. else {
  747. // If they supplied criteria but it's not in the correct format
  748. // then warn them but proceed as though criteria was not supplied.
  749. $filter_criteria = array($left => $object->{$right});
  750. tripal_report_error('tripal_chado', TRIPAL_WARNING,
  751. 'chado_expand_var: unable to apply supplied filter criteria
  752. since it should be an array. You supplied %criteria',
  753. array('%criteria' => print_r($table_options['filter'], TRUE))
  754. );
  755. }
  756. }
  757. else {
  758. $filter_criteria = array($left => $object->{$right});
  759. }
  760. // Generate a new object for this table using the FK values in the
  761. // base table.
  762. $new_options = $table_options;
  763. $foreign_object = chado_generate_var($foreign_table, $filter_criteria, $new_options);
  764. // If the generation of the object was successful, update the base
  765. // object to include it.
  766. if ($foreign_object) {
  767. // In the case where the foreign key relationship exists more
  768. // than once with the same table we want to alter the array
  769. // structure to include the field name.
  770. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  771. if (!property_exists($object, $foreign_table)) {
  772. $object->{$foreign_table} = new stdClass();
  773. }
  774. $object->{$foreign_table}->{$left} = $foreign_object;
  775. $object->expanded = $to_expand;
  776. }
  777. else {
  778. if (!property_exists($object, $foreign_table)) {
  779. $object->{$foreign_table} = new stdClass();
  780. }
  781. $object->{$foreign_table} = $foreign_object;
  782. $object->expanded = $to_expand;
  783. }
  784. }
  785. // If the object returned is NULL then handle that.
  786. else {
  787. // In the case where the foreign key relationship exists more
  788. // than once with the same table we want to alter the array
  789. // structure to include the field name.
  790. if (count($foreign_table_desc['foreign keys'][$base_table]['columns']) > 1) {
  791. if (!property_exists($object, $foreign_table)) {
  792. $object->{$foreign_table} = new stdClass();
  793. }
  794. $object->{$foreign_table}->{$left} = NULL;
  795. }
  796. else {
  797. $object->{$foreign_table} = NULL;
  798. }
  799. }
  800. }
  801. }
  802. // RECURSIVE CASE: if the table is not connected directly to the current
  803. // base table through a foreign key relationship, then maybe it has a
  804. // relationship to one of the nested objects.
  805. else {
  806. // We need to recurse -the table has a relationship to one of the nested
  807. // objects. We assume it's a nested object if the value of the field is
  808. // an object.
  809. $did_expansion = 0;
  810. foreach ((array) $object as $field_name => $field_value) {
  811. // CASE #1: This field is an already expanded foreign key and the
  812. // table to be expanded is in the table referenced by the foreign key.
  813. // First of all it can only be expanded if it's an object
  814. // And if it's a foreign key it should have a tablename property.
  815. if (is_object($field_value) AND property_exists($field_value, 'tablename')) {
  816. $object->{$field_name} = chado_expand_var($field_value, 'table', $foreign_table);
  817. }
  818. // CASE #2: This field is an already expanded object (ie: the field is
  819. // actually the expanded table name) and the table to be expanded is
  820. // related to it.
  821. // Check to see if the $field_name is a valid chado table, we don't
  822. // need to call chado_expand_var on fields that aren't tables.
  823. $check = chado_get_schema($field_name);
  824. if ($check) {
  825. $did_expansion = 1;
  826. $object->{$field_name} = chado_expand_var($field_value, 'table', $foreign_table);
  827. }
  828. }
  829. // If we did not expand this table we should return a message that the
  830. // foreign tabl could not be expanded.
  831. if (!$did_expansion) {
  832. tripal_report_error('tripal_chado', TRIPAL_ERROR, 'chado_expand_var: Could not expand %table. ' .
  833. 'The table is either not related to the base object through a foreign key relationships or ' .
  834. 'it is already expanded. First check the object to ensure it doesn’t already contain the ' .
  835. 'data needed and otherwise check the table definition using chado_get_schema() to ensure ' .
  836. 'a proper foreign key relationship is present.',
  837. array('%table' => $foreign_table));
  838. }
  839. }
  840. break;
  841. case "node": //-------------------------------------------------------------
  842. // BASE CASE: if the node to be expanded is for our base table, then just
  843. // expand it.
  844. if ($object->tablename == $to_expand) {
  845. // Load the node based on the current objects nid (node primary key).
  846. $node = NULL;
  847. if (property_exists($object, 'nid')) {
  848. $node = node_load($object->nid);
  849. }
  850. // Try to get the nid based on the tablename.
  851. else {
  852. // Invoke all hook_node_info to avoid hard-coding the chado_$table
  853. // assumption..
  854. foreach (module_invoke_all('node_info') as $node_info) {
  855. if (array_key_exists('chado_node_api', $node_info)) {
  856. if ($node_info['chado_node_api']['base_table'] == $object->tablename) {
  857. $key_name = $node_info['chado_node_api']['base_table'] . '_id';
  858. $nid = chado_get_nid_from_id(
  859. $node_info['chado_node_api']['base_table'],
  860. $object->{$key_name},
  861. $node_info['base']);
  862. if ($nid > 0) {
  863. $object->nid = $nid;
  864. $node = node_load($nid);
  865. break;
  866. }
  867. }
  868. }
  869. }
  870. }
  871. // If we have successfully loaded the node...
  872. if ($node) {
  873. // Move expandable arrays from the object into the node.
  874. $object->expanded = $to_expand;
  875. $node->expandable_fields = $object->expandable_fields;
  876. unset($object->expandable_fields);
  877. $node->expandable_tables = $object->expandable_tables;
  878. unset($object->expandable_tables);
  879. $node->expandable_nodes = $object->expandable_nodes;
  880. unset($object->expandable_nodes);
  881. // The node becomes the base object with the obejct added to it.
  882. // For example, we may start with a feature object with a name,
  883. // uniquename , type, etc. After expanding we will return the node and
  884. // at $node->feature you will find the original object.
  885. $node->{$base_table} = $object;
  886. $object = $node;
  887. }
  888. // Else we were unable to load the node.
  889. else {
  890. // Warn the administrator
  891. if (isset($object->nid)) {
  892. tripal_report_error('tripal_chado', TRIPAL_ERROR, 'chado_expand_var: No node matches the nid (%nid) supplied.',
  893. array('%nid' => $object->nid));
  894. }
  895. else {
  896. tripal_report_error('tripal_chado', TRIPAL_NOTICE, 'chado_expand_var: There is no node for the current object: <pre>%object</pre>', array('%object' => print_r($object,TRUE)));
  897. }
  898. } //End of if node.
  899. }
  900. // RECURSIVE CASE: check to see if the node to be expanded associates with
  901. // a chado table within one of the nested objects.
  902. else {
  903. // We need to recurse -the node to expand is one of the nested objects
  904. // We assume it's a nested object if the field value is an object.
  905. foreach ((array) $object as $field_name => $field_value) {
  906. if (is_object($field_value)) {
  907. $object->{$field_name} = chado_expand_var(
  908. $field_value,
  909. 'node',
  910. $to_expand
  911. );
  912. }
  913. } // End of for each field in the current object.
  914. }
  915. break;
  916. // The $type to be expanded is not yet supported.
  917. default:
  918. tripal_report_error('tripal_chado', TRIPAL_ERROR, 'chado_expand_var: Unrecognized type (%type). Should be one of "field", "table", "node".',
  919. array('%type' => $type));
  920. return FALSE;
  921. }
  922. // Move expandable arrays downwards -------------------------------
  923. // If the type was either table or foreign key then a new chado variable was
  924. // generated this variable will have it's own expandable array's which need to
  925. // be moved down and merged with the base objects expandable arrays.
  926. // Thus, check all nested objects for expandable arrays
  927. // and if they have them, move them downwards.
  928. foreach ( (array)$object as $field_name => $field_value) {
  929. if (is_object($field_value)) {
  930. // The current nested object has expandable arrays.
  931. if (isset($field_value->expandable_fields)) {
  932. // Move expandable fields downwards.
  933. if (isset($field_value->expandable_fields) and is_array($field_value->expandable_fields)) {
  934. // If the current object has it's own expandable fields then merge them.
  935. if (isset($object->expandable_fields)) {
  936. $object->expandable_fields = array_merge(
  937. $object->expandable_fields,
  938. $object->{$field_name}->expandable_fields
  939. );
  940. unset($object->{$field_name}->expandable_fields);
  941. }
  942. // Otherwise, just move the expandable fields downwards.
  943. else {
  944. $object->expandable_fields = $object->{$field_name}->expandable_fields;
  945. unset($object->{$field_name}->expandable_fields);
  946. }
  947. }
  948. // Move expandable foreign keys downwards.
  949. if (isset($field_value->expandable_foreign_keys) and is_array($field_value->expandable_foreign_keys)) {
  950. // If the current object has it's own expandable foreign keys then
  951. // merge them.
  952. if (isset($object->expandable_foreign_keys)) {
  953. $object->expandable_foreign_keys = array_merge(
  954. $object->expandable_foreign_keys,
  955. $object->{$field_name}->expandable_foreign_keys
  956. );
  957. unset($object->{$field_name}->expandable_foreign_keys);
  958. }
  959. // Otherwise, just move the expandable foreign keys downwards.
  960. else {
  961. $object->expandable_foreign_keys = $object->{$field_name}->expandable_foreign_keys;
  962. unset($object->{$field_name}->expandable_foreign_keys);
  963. }
  964. }
  965. // Move expandable tables downwards.
  966. if (isset($field_value->expandable_tables) and is_array($field_value->expandable_tables)) {
  967. // If the current object has it's own expandable tables then merge them.
  968. if (isset($object->expandable_tables)) {
  969. $object->expandable_tables = array_merge(
  970. $object->expandable_tables,
  971. $object->{$field_name}->expandable_tables
  972. );
  973. unset($object->{$field_name}->expandable_tables);
  974. }
  975. // Otherwise, just move the expandable tables downwards.
  976. else {
  977. $object->expandable_tables = $object->{$field_name}->expandable_tables;
  978. unset($object->{$field_name}->expandable_tables);
  979. }
  980. }
  981. // Move expandable nodes downwards.
  982. if (isset($field_value->expandable_nodes) and is_array($field_value->expandable_nodes)) {
  983. // If the current object has it's own expandable tables then merge them.
  984. if (isset($object->expandable_nodes)) {
  985. $object->expandable_nodes = array_merge(
  986. $object->expandable_nodes,
  987. $object->{$field_name}->expandable_nodes
  988. );
  989. unset($object->{$field_name}->expandable_nodes);
  990. }
  991. // Otherwise, just move the expandable tables downwards.
  992. else {
  993. $object->expandable_nodes = $object->{$field_name}->expandable_nodes;
  994. unset($object->{$field_name}->expandable_nodes);
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. // Move extended array downwards ----------------------------------
  1001. // This tells us what we have expanded (ie: that we succeeded)
  1002. // and is needed to remove the entry from the expandable array.
  1003. // If there is no expanded field in the current object then check any of the
  1004. // nested objects and move it down.
  1005. if (!property_exists($object, 'expanded')) {
  1006. // It's a nested object if the value is an object.
  1007. foreach ( (array)$object as $field_name => $field_value) {
  1008. if (is_object($field_value)) {
  1009. // Check if the current nested object has an expanded array.
  1010. if (isset($field_value->expanded)) {
  1011. // If so, then move it downwards.
  1012. $object->expanded = $field_value->expanded;
  1013. unset($field_value->expanded);
  1014. }
  1015. }
  1016. }
  1017. }
  1018. // Check again if there is an expanded field in the current object
  1019. // We check again because it might have been moved downwards above.
  1020. if (property_exists($object, 'expanded')) {
  1021. // If so, then remove the expanded identifier from the correct expandable
  1022. // array..
  1023. $expandable_name = 'expandable_' . $type . 's';
  1024. if (property_exists($object, $expandable_name) and $object->{$expandable_name}) {
  1025. $key_to_remove = array_search($object->expanded, $object->{$expandable_name});
  1026. unset($object->{$expandable_name}[$key_to_remove]);
  1027. unset($object->expanded);
  1028. }
  1029. }
  1030. // Finally, Return the object!
  1031. return $object;
  1032. }

Related topics