aboutsummaryrefslogtreecommitdiff
path: root/classes/CinisisDb.php
blob: ae80a002dc867a7a6b67ac12c5ed480875e7b5ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php

/**
 * CinisisDb main class.
 */
class CinisisDb {
  /**
   * @var $db
   *   Database resource.
   */  
  var $db;

  /**
   * @var $implementation
   *   Database implementation.
   */
  var $implementation;

  /**
   * Constructor.
   *
   * @param $config
   *   Optional parameter to set alternative config file or array
   *   with configuration.
   */   
  function __construct($config = 'config/config.yaml') {
    try {
      // Check main configuration.
      $config = $this->parse($config);

      // Check database schema.
      $schema = $this->parse('schemas/'. $config['database'] .'.yaml', 'schema');
    } catch (Exception $e) {
      echo '[cinisis] caught exception: ',  $e->getMessage(), "\n";
      return FALSE;
    }

    // Setup database connection.
    $this->implementation = $config['implementation'] .'Db';
    $this->db             = new $this->implementation($schema);
  }

  /**
   * Config file load.
   *
   * @param $file
   *   Config file.
   *
   * @return
   *   Array with configuration.
   */
  function load($file) {
    if (!file_exists($file)) {
      throw new Exception('Config '. $file .' not found.');
    }

    // Load configuration.
    return Spyc::YAMLLoad($file);
  }

  /**
   * Parse configuration.
   *
   * @param $config
   *   Config file or array with configuration.
   *
   * @param $type
   *   Configuration type (either 'cinisis' or 'schema').
   *
   * @return
   *   Array with configuration or FALSE on error.
   */
  function parse($config, $type = 'cinisis') {
    // Load configuration if needed.
    if (!is_array($config)) {
      $config = $this->load($config);
    }

    // Check configuration.
    $class = ucfirst($type) .'Db';
    return call_user_func(array($class, 'check'), $config);
  }

  /**
   * Check configuration.
   *
   * @param $config
   *   Config file or array with configuration.
   *
   * @return
   *   Array with configuration or FALSE on error.
   */  
  public function check($config) {
    // Set default database backend if needed.
    if (!isset($config['implementation'])) {
      $config['implementation'] = 'PhpIsis';
    }

    // Check database configuration.
    if (!isset($config['database'])) {
      throw new Exception('No database set on configuration.');
    }

    return $config;
  }
}