Example #1
0
 public function register()
 {
     $di = $this->getContainer();
     $connections = $di->get('config')['connections'];
     $first = true;
     foreach ($connections as $connection) {
         $di->add('spot.config.' . $connection['name'], function ($logger) use($connection) {
             $cfg = new Config();
             $param = isset($connection['dsn']) ? $connection['dsn'] : $connection;
             $conn = $cfg->addConnection($connection['name'], $param);
             $sqlLogger = new \Laasti\SpotProvider\MonologSqlLogger($logger);
             $conn->getConfiguration()->setSQLLogger($sqlLogger);
             return $cfg;
         }, true)->withArgument('Psr\\Log\\LoggerInterface');
         $di->add('spot.locator.' . $connection['name'], function () use($di, $connection) {
             $spot = new Locator($di->get('spot.config.' . $connection['name']));
             return $spot;
         }, true);
         if ($first) {
             $di->add('Spot\\Config', function () use($di, $connection) {
                 return $di->get('spot.config.' . $connection['name']);
             }, true);
             $di->add('Spot\\Locator', function ($config = null) use($di, $connection) {
                 return $di->get('spot.locator.' . $connection['name'], [$config]);
             }, true);
             $first = false;
         }
     }
 }
Example #2
0
 public function register()
 {
     $this->app['spot'] = function () {
         $config = new Config();
         $config->addConnection('default', $this->config);
         return new Locator($config);
     };
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function register(Application $app)
 {
     $app['spot'] = $app->share(function ($app) {
         $config = new SpotConfig();
         $config->addConnection('mysql', ['dbname' => $app->config('database.database'), 'user' => $app->config('database.user'), 'password' => $app->config('database.password'), 'host' => $app->config('database.host'), 'driver' => 'pdo_mysql']);
         return new SpotLocator($config);
     });
 }
 /**
  * Register this provider.
  *
  * The spot2.connections array can have an arbitrary number of connections in
  * it. The array should use the following format:
  *
  * <code>
  * $connections = [
  *      'my_sqlite' => 'sqlite://path/to/my_database.sqlite',
  *      'my_sqlite' => [
  *          'dbname'   => 'my_database',
  *          'user'     => 'username',
  *          'password' => 'sshhh-secret',
  *          'host'     => 'localhost',
  *          'drivers'  => 'pdo_mysql'
  *      ]
  * ];
  * </code>
  *
  * @param Silex\Application $app
  *
  * @author Ronan Chilvers <*****@*****.**>
  */
 public function register(Application $app)
 {
     $app['spot2.connections'] = [];
     $app['spot2.connections.default'] = null;
     $app['spot2.config'] = $app->share(function (Application $app) {
         $config = new Config();
         foreach ($app['spot2.connections'] as $name => $data) {
             $default = $app['spot2.connections.default'] === $name ? true : false;
             $config->addConnection($name, $data, $default);
         }
         return $config;
     });
     $app['spot2.locator'] = $app->share(function (Application $app) {
         return new Locator($app['spot2.config']);
     });
 }
Example #5
0
 /**
  * Syntax for each column in CREATE TABLE command
  *
  * @param string $fieldName Field name
  * @param array $fieldInfo Array of field settings
  * @return string SQL syntax
  */
 public function migrateSyntaxFieldCreate($fieldName, array $fieldInfo)
 {
     // Get adapter options and type from typeHandler
     $typeHandler = Config::typeHandler($fieldInfo['type']);
     $fieldInfo = array_merge($fieldInfo, $typeHandler::adapterOptions());
     $adapterType = $this->_fieldTypeMap[$fieldInfo['type']]['adapter_type'];
     $syntax = "`" . $fieldName . "` " . $adapterType;
     // Column type and length
     $syntax .= $fieldInfo['length'] ? '(' . $fieldInfo['length'] . ')' : '';
     // Unsigned
     $syntax .= $fieldInfo['unsigned'] ? ' unsigned' : '';
     // Collate
     $syntax .= $fieldInfo['type'] == 'string' || $fieldInfo['type'] == 'text' ? ' COLLATE ' . $this->_collate : '';
     // Nullable
     $isNullable = true;
     if ($fieldInfo['required'] || !$fieldInfo['null']) {
         $syntax .= ' NOT NULL';
         $isNullable = false;
     }
     // Default value
     if ($fieldInfo['default'] === null && $isNullable) {
         $syntax .= " DEFAULT NULL";
     } elseif ($fieldInfo['default'] !== null) {
         $default = $fieldInfo['default'];
         // If it's a boolean and $default is boolean then it should be 1 or 0
         if (is_bool($default) && $fieldInfo['type'] == "boolean") {
             $default = $default ? 1 : 0;
         }
         if (is_scalar($default)) {
             $syntax .= " DEFAULT '" . $default . "'";
         }
     }
     // Extra
     $syntax .= $fieldInfo['primary'] && $fieldInfo['serial'] ? ' AUTO_INCREMENT' : '';
     return $syntax;
 }
Example #6
0
spl_autoload_register(function ($className) {
    if (substr($className, 0, 4) === 'Spot') {
        $filename = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, trim($className, '\\_')) . '.php';
        require_once $filename;
    }
});
// Setup cache manager
#$cache = new \CacheCache\Cache(new \CacheCache\Backends\Dummy());
#$cacheManager = new \CacheCache\CacheManager();
#$cacheManager->set('cacheDummy', $cache);
// Setup available adapters for testing
$options = array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_CASE => \PDO::CASE_LOWER, \PDO::ATTR_PERSISTENT => true);
$db = new \Pdo('mysql:host=localhost;dbname=test', 'test', 'test', $options);
#$db = new \Pdo('sqlite::memory:', $options);
// Setup config
$cfg = \Spot\Config::getInstance(true);
$adapter = new \Spot\Adapter\Mysql($db);
$adapter->database('test');
$cfg->addConnection('db', $adapter);
// Return Spot mapper for use
$mapper = new \Spot\Mapper($cfg);
function test_spot_mapper()
{
    global $mapper;
    return $mapper;
}
/**
 * Debug function, dont die after output
 */
function d()
{
Example #7
0
 /**
  * Get formatted fields with all neccesary array keys and values.
  * Merges defaults with defined field values to ensure all options exist for each field.
  *
  * @param string $entityName Name of the entity class
  * @return array Defined fields plus all defaults for full array of all possible options
  */
 public function fields($entityName)
 {
     if (!is_string($entityName)) {
         throw new \Spot\Exception(__METHOD__ . " only accepts a string. Given (" . gettype($entityName) . ")");
     }
     if (!is_subclass_of($entityName, '\\Spot\\Entity')) {
         throw new \Spot\Exception($entityName . " must be subclass of '\\Spot\\Entity'.");
     }
     if (isset(self::$_fields[$entityName])) {
         $returnFields = self::$_fields[$entityName];
     } else {
         // Datasource info
         $entityDatasource = null;
         $entityDatasource = $entityName::datasource();
         if (null === $entityDatasource || !is_string($entityDatasource)) {
             echo "\n\n" . $entityName . "::datasource() = " . var_export($entityName::datasource(), true) . "\n\n";
             throw new \InvalidArgumentException("Entity must have a datasource defined. Please define a protected property named '_datasource' on your '" . $entityName . "' entity class.");
         }
         self::$_datasource[$entityName] = $entityDatasource;
         // Datasource Options
         $entityDatasourceOptions = $entityName::datasourceOptions();
         self::$_datasourceOptions[$entityName] = $entityDatasourceOptions;
         // Connection info
         $entityConnection = $entityName::connection();
         // If no adapter specified, Spot will use default one from config object (or first one set if default is not explicitly set)
         self::$_connection[$entityName] = $entityConnection ? $entityConnection : false;
         // Default settings for all fields
         $fieldDefaults = array('type' => 'string', 'default' => null, 'length' => null, 'required' => false, 'null' => true, 'unsigned' => false, 'fulltext' => false, 'primary' => false, 'index' => false, 'unique' => false, 'serial' => false);
         // Type default overrides for specific field types
         $fieldTypeDefaults = array('string' => array('length' => 255), 'float' => array('length' => array(10, 2)), 'int' => array('length' => 10, 'unsigned' => true));
         // Get entity fields from entity class
         $entityFields = false;
         $entityFields = $entityName::fields();
         if (!is_array($entityFields) || count($entityFields) < 1) {
             throw new \InvalidArgumentException($entityName . " Must have at least one field defined.");
         }
         $returnFields = array();
         self::$_fieldDefaultValues[$entityName] = array();
         foreach ($entityFields as $fieldName => $fieldOpts) {
             // Store field definition exactly how it is defined before modifying it below
             if ($fieldOpts['type'] != 'relation') {
                 self::$_fieldsDefined[$entityName][$fieldName] = $fieldOpts;
             }
             // Get adapter options and type from typeHandler
             $typeHandler = Config::typeHandler($fieldOpts['type']);
             $typeOptions = $typeHandler::adapterOptions();
             // Use typeOptions as base, merge field options, but keep 'type' from typeOptions
             $fieldOpts = array_merge($typeOptions, $fieldOpts, array('type' => $typeOptions['type']));
             // Format field will full set of default options
             if (isset($fieldOpts['type']) && isset($fieldTypeDefaults[$fieldOpts['type']])) {
                 // Include type defaults
                 $fieldOpts = array_merge($fieldDefaults, $fieldTypeDefaults[$fieldOpts['type']], $fieldOpts);
             } else {
                 // Merge with defaults
                 $fieldOpts = array_merge($fieldDefaults, $fieldOpts);
             }
             // Store primary key
             if (true === $fieldOpts['primary']) {
                 self::$_primaryKeyField[$entityName] = $fieldName;
             }
             // Store default value
             if (null !== $fieldOpts['default']) {
                 self::$_fieldDefaultValues[$entityName][$fieldName] = $fieldOpts['default'];
             } else {
                 self::$_fieldDefaultValues[$entityName][$fieldName] = null;
             }
             $returnFields[$fieldName] = $fieldOpts;
         }
         self::$_fields[$entityName] = $returnFields;
         // Relations
         $entityRelations = array();
         $entityRelations = $entityName::relations();
         if (!is_array($entityRelations)) {
             throw new \InvalidArgumentException($entityName . " Relation definitons must be formatted as an array.");
         }
         foreach ($entityRelations as $relationAlias => $relationOpts) {
             self::$_relations[$entityName][$relationAlias] = $relationOpts;
         }
     }
     return $returnFields;
 }
Example #8
0
 /**
  * Retrieve data from the data store
  */
 public function loadEntity($entityName, $data)
 {
     $loadedData = array();
     $fields = $entityName::fields();
     $entityData = array_intersect_key($data, $fields);
     foreach ($data as $field => $value) {
         // Field is in the Entity definitions
         if (isset($entityData[$field])) {
             $typeHandler = \Spot\Config::typeHandler($fields[$field]['type']);
             $loadedData[$field] = $typeHandler::_load($value);
             // Extra data returned with query (like calculated valeus, etc.)
         } else {
             $loadedData[$field] = $value;
         }
     }
     return $loadedData;
 }
Example #9
0
 public function testConfigCanUnserialize()
 {
     $cfg = \Spot\Config::getInstance(true);
     $adapter = $cfg->addConnection('test_adapter', new \Spot\Adapter\Mock());
     $this->assertInstanceOf('\\Spot\\Config', unserialize(serialize($cfg)));
 }
Example #10
0
/**
 * Created by PhpStorm.
 * User: kayladaniels
 * Date: 3/24/15
 * Time: 9:46 PM
 */
use GuzzleHttp\Client;
use Spot\Config;
use Spot\Locator;
require_once __DIR__ . '/vendor/autoload.php';
Dotenv::load(__DIR__);
session_start();
$app = new \Slim\Slim(array('templates.path' => './views', 'debug' => true));
$loader = new Twig_Loader_Filesystem(__DIR__ . '/views');
$twig = new Twig_Environment($loader);
$cfg = new Config();
// MySQL
$cfg->addConnection('mysql', 'mysql://' . $_ENV['DATABASE_USER'] . ':' . $_ENV['DATABASE_PASSWORD'] . '@localhost/helpmeabstract');
$spot = new Locator($cfg);
$volunteerMapper = $spot->mapper('Kayladnls\\Entity\\Volunteer');
$proposalMapper = $spot->mapper('Kayladnls\\Entity\\Proposal');
$app->notFound(function () use($app) {
    $app->redirect('/error');
});
$app->get('/', function () use($twig, $volunteerMapper) {
    $volunteers = $volunteerMapper->getForHomePage();
    echo $twig->render('index.php', array('volunteers' => $volunteers));
});
$app->get('/volunteer', function () use($twig) {
    echo $twig->render('volunteer.php');
});