CRM-14885 - CRM_Core_CodeGen_DAO - Use checksum to avoid recomputation
[civicrm-core.git] / CRM / Core / CodeGen / DAO.php
1 <?php
2
3 /**
4 * Create DAO ORM classes.
5 */
6 class CRM_Core_CodeGen_DAO extends CRM_Core_CodeGen_BaseTask {
7
8 /**
9 * @var string
10 */
11 public $name;
12
13 /**
14 * @var string
15 */
16 private $checksum;
17
18 public function __construct($config, $name) {
19 parent::__construct($config);
20 $this->name = $name;
21 }
22
23 /**
24 * @return bool
25 * TRUE if an update is needed.
26 */
27 public function needsUpdate() {
28 if (!file_exists($this->getAbsFileName())) {
29 return TRUE;
30 }
31 return $this->getChecksum() !== self::extractChecksum($this->getAbsFileName(), ';\(GenCodeChecksum:([a-z0-9]+)\);');
32 }
33
34 public function run() {
35 echo "Generating {$this->name} as " . $this->getRelFileName() . "\n";
36
37 if (empty($this->tables[$this->name]['base'])) {
38 echo "No base defined for {$this->name}, skipping output generation\n";
39 return;
40 }
41
42 $template = new CRM_Core_CodeGen_Util_Template('php');
43 $template->assign('table', $this->tables[$this->name]);
44 $template->assign('genCodeChecksum', $this->getChecksum());
45 $template->run('dao.tpl', $this->getAbsFileName());
46 }
47
48 public function getRelFileName() {
49 return $this->tables[$this->name]['fileName'];
50 }
51
52 /**
53 * @return string
54 */
55 public function getAbsFileName() {
56 $directory = $this->config->phpCodePath . $this->tables[$this->name]['base'];
57 CRM_Core_CodeGen_Util_File::createDir($directory);
58 $absFileName = $directory . $this->getRelFileName();
59 return $absFileName;
60 }
61
62 protected static function extractChecksum($file, $regex) {
63 $content = file_get_contents($file);
64 if (preg_match($regex, $content, $matches)) {
65 return $matches[1];
66 }
67 else {
68 return NULL;
69 }
70 }
71
72 protected function getChecksum() {
73 if (!$this->checksum) {
74 CRM_Utils_Array::flatten($this->tables[$this->name], $flat);
75 ksort($flat);
76 $this->checksum = md5($this->config->getSourceDigest() . json_encode($flat));
77 }
78 return $this->checksum;
79 }
80
81 }