SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/ColModifierSubRecordCount.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16.  
  17. /**
  18.  * Counts records in a subtable.
  19.  *
  20.  * E.g. count the records in a gallery_images table associated with records in a galleries table
  21.  * The database query isn't done until the first record lookup
  22.  */
  23. class ColModifierSubRecordCount extends ColModifier
  24. {
  25. private $data = null;
  26. private $table;
  27. private $column;
  28.  
  29.  
  30. /**
  31.   * @param string $table The table that contains the records
  32.   * @param string $column The column in $table that links to the main table, which by convention is the table's
  33.   * singular name followed by _id, e.g. if $table is 'galleries' then $column is usually 'gallery_id'
  34.   */
  35. public function __construct($table, $column)
  36. {
  37. Pdb::validateIdentifier($table);
  38. Pdb::validateIdentifier($column);
  39. $this->table = $table;
  40. $this->column = $column;
  41. }
  42.  
  43.  
  44. /**
  45.   * Modify a column value
  46.   * This value will be html/csv/etc encoded afterwards.
  47.   *
  48.   * @param string $val The incoming value
  49.   * @param string $field_name The name of the field being modified
  50.   * @return string The modified value
  51.   */
  52. public function modify($val, $field_name)
  53. {
  54. if ($val == '') return '';
  55.  
  56. if ($this->data === null) {
  57. $q = "SELECT `{$this->column}`, COUNT(*) FROM ~{$this->table} GROUP BY `{$this->column}`";
  58. $this->data = Pdb::q($q, [], 'map');
  59. }
  60.  
  61. return (int) @$this->data[$val];
  62. }
  63.  
  64. }
  65.