/**
  * Initializes this fixture class
  *
  * @return boolean
  */
 public function init()
 {
     if (empty($this->file)) {
         $this->file = Inflector::tableize($this->name) . '.sql';
     }
     return parent::init();
 }
示例#2
0
 public function __construct($from, $name, array $config)
 {
     $this->name = $name;
     $this->model_from = $from;
     $this->model_to = array_key_exists('model_to', $config) ? $config['model_to'] : \Inflector::get_namespace($from) . 'Model_' . \Inflector::classify($name);
     $this->key_from = array_key_exists('key_from', $config) ? (array) $config['key_from'] : $this->key_from;
     $this->key_to = array_key_exists('key_to', $config) ? (array) $config['key_to'] : $this->key_to;
     $this->conditions = array_key_exists('conditions', $config) ? (array) $config['conditions'] : array();
     if (!empty($config['table_through'])) {
         $this->table_through = $config['table_through'];
     } else {
         $table_name = array($this->model_from, $this->model_to);
         natcasesort($table_name);
         $table_name = array_merge($table_name);
         $this->table_through = \Inflector::tableize($table_name[0]) . '_' . \Inflector::tableize($table_name[1]);
     }
     $this->key_through_from = !empty($config['key_through_from']) ? (array) $config['key_through_from'] : (array) \Inflector::foreign_key($this->model_from);
     $this->key_through_to = !empty($config['key_through_to']) ? (array) $config['key_through_to'] : (array) \Inflector::foreign_key($this->model_to);
     $this->cascade_save = array_key_exists('cascade_save', $config) ? $config['cascade_save'] : $this->cascade_save;
     $this->cascade_delete = array_key_exists('cascade_delete', $config) ? $config['cascade_delete'] : $this->cascade_delete;
     if (!class_exists($this->model_to)) {
         throw new \FuelException('Related model not found by Many_Many relation "' . $this->name . '": ' . $this->model_to);
     }
     $this->model_to = get_real_class($this->model_to);
 }
 function beforeFind(&$Model, $query)
 {
     if (!isset($query['sphinx'])) {
         return $query;
     }
     if (isset($query['limit'])) {
         $query['sphinx']['limit'] = $query['limit'];
     }
     if (isset($query['page'])) {
         $query['sphinx']['page'] = $query['page'];
     }
     if (isset($query['conditions'])) {
         if (!isset($query['sphinx']['filters'])) {
             $query['sphinx']['filters'] = array();
         }
         $query['sphinx']['filters'] = array_merge($query['sphinx']['filters'], $this->convertConditionsToFilters($query['conditions']));
     }
     if (!isset($query['sphinx']['index'])) {
         $query['sphinx']['index'] = Inflector::tableize($Model->alias);
     }
     $query['sphinx']['query'] = $this->replaceMappedFields($Model, $query['sphinx']['query']);
     $results = $this->sphinx->read($query['sphinx']);
     $this->runtime[$Model->alias]['results'] = $results;
     $query['conditions'] = Set::merge($query['conditions'], $this->getMatchedConditions($Model));
     unset($results);
     unset($query['limit']);
     unset($query['offset']);
     unset($query['page']);
     return $query;
 }
示例#4
0
文件: Privilege.php 项目: ayaou/Zuha
 /**
  * Write link permissions method
  * 
  */
 protected function _writeLinkPermissions()
 {
     $acos = array();
     $privileges = $this->find('all', array('conditions' => array('Privilege._create' => 1, 'Privilege._read' => 1, 'Privilege._update' => 1, 'Privilege._delete' => 1)));
     foreach ($privileges as $privilege) {
         if (!empty($acos[$privilege['Privilege']['aco_id']])) {
             $acos[$privilege['Privilege']['aco_id']] = $acos[$privilege['Privilege']['aco_id']] . ',' . $privilege['Privilege']['aro_id'];
         } else {
             $acos[$privilege['Privilege']['aco_id']] = $privilege['Privilege']['aro_id'];
         }
     }
     $settings = '';
     foreach ($acos as $aco => $aros) {
         $path = $this->Section->getPath($aco);
         // all of the acos parents
         if ($path === null) {
             // if path is null we need to delete the aros_acos that use that aco because it doesn't exist
             $this->deleteAll(array('Privilege.aco_id' => $aco));
         } else {
             $url = str_replace('controllers', '', Inflector::singularize(Inflector::tableize(ZuhaInflector::flatten(Set::extract('/Section/alias', $path), array('separator' => '/')))));
             $settings .= $url . ' = ' . $aros . PHP_EOL;
         }
     }
     App::uses('Setting', 'Model');
     $Setting = new Setting();
     $data['Setting']['type'] = 'APP';
     $data['Setting']['name'] = 'LINK_PERMISSIONS';
     $data['Setting']['value'] = trim($settings);
     $Setting->add($data);
 }
示例#5
0
 /**
  * If the storage backend is a database, this specified which table name 
  * should be used to store objects. If not defined, the Inflator will 
  * generate a plural, lower case variant of the class name.
  *
  * @param  string  PHP classname
  * @return string
  */
 public static function storageClass($class)
 {
     if (!isset(self::$storageClassCache[$class])) {
         self::$storageClassCache[$class] = Inflector::tableize($class);
     }
     return self::$storageClassCache[$class];
 }
示例#6
0
 /**
  * Class constructor
  *
  * @param bool|int|string|array $id Set this ID for this model on startup.
  * @param string $table Name of database table to use.
  * @param string $ds DataSource connection name.
  */
 public function __construct($id = false, $table = null, $ds = null)
 {
     if (is_array($id)) {
         $alias = Hash::get($id, 'alias') ?: (Hash::get($id, 'table') ?: $this->alias);
         $id['alias'] = Inflector::singularize(preg_replace('/Table$/', '', $alias));
         $this->name = $this->alias = $this->alias($id['alias']);
         $schema = Hash::get($id, 'schema');
         if ($schema !== null) {
             $this->_schema = $schema;
         }
     }
     if ($table === null) {
         if ($this->name === null) {
             $this->name = isset($name) ? $name : get_class($this);
         }
         if ($this->alias === null) {
             $this->alias = isset($alias) ? $alias : $this->name;
         }
         $table = Inflector::tableize(preg_replace('/Table$/', '', $this->alias));
     }
     parent::__construct($id, $table, $ds);
     $this->entityClass(Inflector::singularize($this->name) . 'Entity');
     $this->initialize([]);
     $this->entity(false);
 }
示例#7
0
 function test_tableize()
 {
     $tables = array("SimpleCow" => "simple_kine", "ChannelNews" => "channel_news", "Person" => "people", "Child" => "children", "MailAttachment" => "mail_attachments");
     foreach ($tables as $class => $table) {
         $this->assertEqual($table, Inflector::tableize($class));
     }
 }
示例#8
0
 public static function url($id, $options = array())
 {
     $options += array('full' => false, 'route' => true, 'slug' => true);
     $full = $options['full'];
     unset($options['full']);
     $slug = $options['slug'];
     unset($options['slug']);
     $route = $options['route'];
     unset($options['route']);
     if (!is_array($id)) {
         $node = self::read($id);
     } else {
         $node = isset($id['CmsNode']) ? $id : array('CmsNode' => $id);
         $id = $node['CmsNode']['id'];
     }
     if ($node['CmsNode']['model']) {
         $options += array('plugin' => $node['CmsNode']['plugin'], 'controller' => Inflector::tableize($node['CmsNode']['model']));
     } else {
         $options += array('plugin' => 'cms', 'controller' => 'cms_nodes');
     }
     $options += array('admin' => false, 'action' => 'view', $id);
     if ($slug && $node['CmsNode']['slug']) {
         $options[] = $node['CmsNode']['slug'];
     }
     return $route ? Sl::url($options, $full) : $options;
 }
示例#9
0
 public function get($id = null)
 {
     $request = CoreApp::getRequest();
     $selectTable = QueryBase::tableizeModelName($this->modelClass);
     $parsedResources = $this->parseResources($request->getResourceArray());
     $queryBase = new QueryBase($this->modelClass);
     $constraint = new Constraints();
     if (empty($id)) {
         $resourceArray = $request->getResourceArray();
         $id = $resourceArray[count($resourceArray) - 1];
     }
     $queryBase->Select();
     if (!empty($parsedResources['joins'])) {
         $joinsArray = array_map("core\\Inflector::tableize", $parsedResources['joins']);
         $queryBase->Join($joinsArray);
     }
     $constraint->term("{$selectTable}" . ".id", "=", $id);
     if (!empty($parsedResources['constraints'])) {
         foreach ($parsedResources['constraints'] as $kv) {
             $table = Inflector::tableize($kv->resource) . ".id";
             $value = $kv->value;
             $constraint->andTerm($table, "=", $value);
         }
     }
     $queryBase->Where($constraint);
     $sql = $queryBase->getSelect();
     $bindValues = $queryBase->getBindValues();
     if ($this->query($sql, $bindValues)) {
         return $this->getResultsSet();
     }
     return false;
 }
示例#10
0
 function initialize()
 {
     # setup database configuration
     if (!$this->_table_name) {
         if (!$this->_base_class) {
             $class = get_class($this);
             while (get_parent_class($class) && !preg_match('/_Base$/i', get_parent_class($class))) {
                 $class = get_parent_class($class);
             }
             $this->_base_class = $class;
         }
         $this->_table_name = Inflector::tableize($this->_base_class);
     }
     $this->_type_name = get_class($this);
     $this->_columns = AdoDBRecord_Tools::get_columns();
     # dynamically overload current class in PHP4 because it doesn't
     # propagate through the class hierarchy
     if (version_compare(PHP_VERSION, "5.0.0") < 0) {
         $const = "OVERLOADED_" . $this->_type_name;
         if (!defined($const)) {
             define($const, $const);
             overload($this->_type_name);
         }
     }
     # call the setup hook
     $this->setup();
 }
示例#11
0
 function __construct($attributes = null, $options = array())
 {
     if (empty($options['child_object'])) {
         // parse settings
         $this->parse_settings(isset($options['settings']) ? $options['settings'] : null);
         // start or reuse connection
         $this->establish_connection();
         // set table name
         $this->_class_name = get_class($this);
         if ($this->_table_name === null) {
             $this->_table_name = $this->_settings['table_prefix'] . Inflector::tableize($this->_class_name);
         }
         // set primary key
         if ($this->_primary_key === null) {
             $this->_primary_key = 'id';
         }
         $this->_settings_id = md5(implode('', $this->_settings) . $this->_table_name);
         self::$object_settings[$this->_settings_id] =& $this->_settings;
         // table info
         self::$table_info[$this->_connection_id][$this->_table_name] =& $this->_columns;
     } else {
         if (isset($options['new_record'])) {
             $this->_new_record = $options['new_record'];
         }
     }
     $this->update_attributes($attributes);
     $this->set_associations();
 }
示例#12
0
 /**
  * attachable_options[:view_permission] = options.delete(:view_permission) || "view_#{self.name.pluralize.underscore}".to_sym
  * attachable_options[:delete_permission] = options.delete(:delete_permission) || "edit_#{self.name.pluralize.underscore}".to_sym
  */
 function setup(&$Model, $config = array())
 {
     $defaults = array(':view_permission' => 'view_' . Inflector::tableize($Model->name), ':delete_permission' => 'edit_' . Inflector::tableize($Model->name));
     $settings = array_merge($defaults, $config);
     $this->settings[$Model->alias] = $settings;
     return true;
 }
示例#13
0
文件: Crud.php 项目: rdallasgray/bbx
 protected function _assign($model)
 {
     if ($this->getRequest()->isHead()) {
         Zend_Controller_Action_HelperBroker::getExistingHelper('viewRenderer')->setNoRender(true);
         return;
     }
     $request = $this->getRequest();
     $this->_setEtag($model->etag($this->_context));
     $modelName = $model instanceof Bbx_Model ? Inflector::underscore(get_class($model)) : Inflector::tableize($model->getModelName());
     if ($request->getParam('list') === 'true') {
         $model->renderAsList();
     }
     if ($this->_context === 'csv') {
         $this->_helper->authenticate();
     }
     if ($request->getParam('download') == 'true') {
         $this->_helper->authenticate();
         $this->_helper->download($model);
     }
     if ($this->_context === 'json') {
         $options = $this->_context === 'json' ? array('deep' => true) : null;
         $this->view->assign($model->toArray($options));
     } else {
         $this->view->{$modelName} = $model;
     }
 }
示例#14
0
文件: confirm.php 项目: styfle/core
 /**
  * Setup function
  *
  * @param object $Model The calling model
  */
 public function setup(&$Model, $settings = array())
 {
     $Model->RevisionModel = new Model(array('table' => Inflector::tableize($Model->name) . '_revs', 'name' => 'Revision', 'ds' => $Model->useDbConfig));
     $Model->RevisionModel->primaryKey = 'version_id';
     $default = array('fields' => array());
     $this->settings[$Model->alias] = array_merge_recursive($default, $settings);
 }
示例#15
0
	/**
	 * Log fields to disk if necessary. Important to do after save so
	 * we can also use the ->id in the filename.
	 *
	 * @param <type> $created
	 * @return <type>
	 */
	public function afterSave ($created) {
		if (!$created) {
			return parent::beforeSave($created);
		}

		$vars = @$this->restLogSettings['vars'] ? @$this->restLogSettings['vars'] : array();

		foreach ($this->filedata as $field => $val) {
			$vars['{' . $field . '}'] = $val;
		}
		foreach ($this->data[__CLASS__] as $field => $val) {
			$vars['{' . $field . '}'] = $val;
		}
		foreach (array('Y', 'm', 'd', 'H', 'i', 's', 'U') as $dp) {
			$vars['{date_' . $dp . '}'] = date($dp);
		}

		$vars['{LOGS}'] = LOGS;
		$vars['{id}'] = $this->id;
		$vars['{controller}'] = Inflector::tableize(@$this->restLogSettings['controller']);

		foreach ($this->filedata as $field => $val) {
			$vars['{field}'] = $field;
			$logfilepath     = $this->logpaths[$field];

			$logfilepath = str_replace(array_keys($vars), $vars, $logfilepath);
			$dir = dirname($logfilepath);
			if (!is_dir($dir)) {
				mkdir($dir, 0755, true);
			}
			file_put_contents($logfilepath, $val, FILE_APPEND);
		}

		return parent::beforeSave($created);
	}
 public function getRepresentation(Omeka_Record_AbstractRecord $comment)
 {
     $user = current_user();
     if ($user->role == 'admin' || $user->role == 'super') {
         $allowAll = true;
     } else {
         $allowAll = false;
     }
     $representation = array('id' => $comment->id, 'url' => self::getResourceUrl("/comments/{$comment->id}"), 'record_id' => $comment->record_id, 'record_type' => $comment->record_type, 'path' => $comment->path, 'added' => self::getDate($comment->added), 'body' => $comment->body, 'author_name' => $comment->author_name, 'author_url' => $comment->author_url, 'approved' => (bool) $comment->approved);
     if ($allowAll) {
         $representation['ip'] = $comment->ip;
         $representation['user_agent'] = $comment->user_agent;
         $representation['flagged'] = $comment->flagged;
         $representation['is_spam'] = $comment->is_spam;
     }
     if ($comment->parent_comment_id) {
         $representation['parent_comment'] = array('id' => $comment->parent_comment_id, 'resource' => 'comments', 'url' => self::getResourceUrl("/comments/{$comment->parent_comment_id}"));
     } else {
         $representation['parent_comment'] = null;
     }
     $typeResource = Inflector::tableize($comment->record_type);
     $representation['record_url'] = array('id' => $comment->record_id, 'resource' => $typeResource, 'url' => self::getResourceUrl("/{$typeResource}/{$comment->record_id}"));
     if ($comment->user_id) {
         $representation['user'] = array('id' => $comment->user_id, 'url' => self::getResourceUrl("/users/{$comment->user_id}"));
     } else {
         $representation['user'] = null;
     }
     if ($user && is_allowed('Commenting_Comment', 'update-approved')) {
         $representation['author_email'] = $comment->author_email;
     }
     return $representation;
 }
示例#17
0
 /**
  * Get the specified UniversalViewer.
  *
  * @param array $args Associative array of optional values:
  *   - (string) id: The unique main id.
  *   - (integer|Record) record: The record is the item if it's an integer.
  *   - (string) type: Type of record if record is integer (item by default).
  *   - (integer|Item) item
  *   - (integer|Collection) collection
  *   - (integer|File) file
  *   - (string) class
  *   - (string) width
  *   - (string) height
  *   - (string) locale
  * The only one record is defined according to the priority above.
  * @return string. The html string corresponding to the UniversalViewer.
  */
 public function universalViewer($args = array())
 {
     $record = $this->_getRecord($args);
     if (empty($record)) {
         return '';
     }
     // Some specific checks.
     switch (get_class($record)) {
         case 'Item':
             // Currently, item without files is unprocessable.
             if ($record->fileCount() == 0) {
                 return __('This item has no files and is not displayable.');
             }
             break;
         case 'Collection':
             if ($record->totalItems() == 0) {
                 return __('This collection has no item and is not displayable.');
             }
             break;
     }
     $class = isset($args['class']) ? $args['class'] : get_option('universalviewer_class');
     if (!empty($class)) {
         $class = ' ' . $class;
     }
     $width = isset($args['width']) ? $args['width'] : get_option('universalviewer_width');
     if (!empty($width)) {
         $width = ' width:' . $width . ';';
     }
     $height = isset($args['height']) ? $args['height'] : get_option('universalviewer_height');
     if (!empty($height)) {
         $height = ' height:' . $height . ';';
     }
     $locale = isset($args['locale']) ? $args['locale'] : get_option('universalviewer_locale');
     if (!empty($locale)) {
         $locale = ' data-locale="' . $locale . '"';
     }
     if (isset($args['only_images'])) {
         $manif = 'universalviewer_presentation_alternative_manifest';
     } else {
         $manif = 'universalviewer_presentation_manifest';
     }
     if (isset($args['current_image'])) {
         $currentImage = $args['current_image'];
     } else {
         $currentImage = 99999;
     }
     $urlManifest = absolute_url(array('recordtype' => Inflector::tableize(get_class($record)), 'id' => $record->id, 'image' => $currentImage), $manif);
     if (isset($args['only_images'])) {
         $config = src('config-images', 'universal-viewer', 'json');
     } else {
         $config = src('config', 'universal-viewer', 'json');
     }
     $urlJs = src('embed', 'javascripts/uv/lib', 'js');
     $imageClass = 'images';
     $html = sprintf('<div class="uv%s %s" data-config="%s" data-uri="%s"%s style="background-color: #000;%s%s"></div>', $class, $imageClass, $config, $urlManifest, $locale, $width, $height);
     $html .= sprintf('<script type="text/javascript" id="embedUV" src="%s"></script>', $urlJs);
     $html .= '<script type="text/javascript">/* wordpress fix */</script>';
     return $html;
 }
示例#18
0
	public function encode ($response) {
		require_once dirname(dirname(__FILE__)) . '/libs/BluntXml.php';
		$this->BluntXml = new BluntXml();
		return $this->BluntXml->encode(
			$response,
			Inflector::tableize($this->params['controller']) . '_response'
		);
	}
示例#19
0
 private function __clearTables()
 {
     foreach ($this->uses as $table) {
         $this->{$table}->deleteAll('1 = 1');
         $this->{$table}->query('ALTER TABLE ' . Inflector::tableize($table) . ' AUTO_INCREMENT = 1', false);
     }
     return true;
 }
 /**
  * Returns an empty array
  *
  * @param Object $model Model object to describe
  * @return array empty array
  */
 public function describe($model)
 {
     $table = Inflector::tableize($model->alias);
     if (isset($this->_schema[$table])) {
         return $this->_schema[$table];
     }
     return array();
 }
示例#21
0
文件: inflector.php 项目: nasumi/fuel
	public function test_tableize()
	{
		$this->assert_equal(Inflector::tableize('\\Model\\User'), 'users');
		$this->assert_equal(Inflector::tableize('\\Model\\Person'), 'people');
		$this->assert_equal(Inflector::tableize('\\Model\\Mouse'), 'mice');
		$this->assert_equal(Inflector::tableize('\\Model\\Ox'), 'oxen');
		$this->assert_equal(Inflector::tableize('\\Model\\Matrix'), 'matrices');
		// TODO: Write more tests
	}
示例#22
0
 /**
  * Initialization method. You may override configuration options from a controller
  *
  * @param $controller object
  * @param $config array
  */
 function initialize(&$controller, $config)
 {
     $this->controller = $controller;
     $model_prefix = Inflector::tableize($controller->modelClass);
     // lower case, studley caps -> underscores
     $prefix = Inflector::singularize($model_prefix);
     // make singular. 'GalleryImage' becomes 'gallery_image'
     $this->config = array_merge(array('default_col' => $prefix), $this->config, $config);
 }
示例#23
0
 /**
  * Takes model field names such as Registration.number
  * into table field names such as registrations.number
  */
 function modelFieldNamesToTableFieldNames($modelFieldNames)
 {
     foreach ($modelFieldNames as $i => &$modelFieldName) {
         $modelFieldName = explode('.', $modelFieldName);
         $modelFieldName[0] = Inflector::tableize($modelFieldName[0]);
         $modelFieldName = implode('.', $modelFieldName);
     }
     return $modelFieldNames;
 }
示例#24
0
 /**
  * Interpolates a string by substituting tokens in a string
  * 
  * Default interpolations:
  * - `:webroot` Path to the webroot folder
  * - `:model` The current model e.g images
  * - `:field` The database field
  * - `:filename` The filename
  * - `:extension` The extension of the file e.g png
  * - `:id` The record id
  * - `:style` The current style e.g thumb
  * - `:hash` Generates a hash based on the filename
  * 
  * @param string $string The string to be interpolated with data.
  * @param string $name The name of the model e.g. Image
  * @param int $id The id of the record e.g 1
  * @param string $field The name of the database field e.g file
  * @param string $style The style to use. Should be specified in the behavior settings.
  * @param array $options You can override the default interpolations by passing an array of key/value
  *              pairs or add extra interpolations. For example, if you wanted to change the hash method
  *              you could pass `array('hash' => sha1($id . Configure::read('Security.salt')))`
  * @return array Settings array containing interpolated strings along with the other settings for the field.
  */
 public static function run($string, $name, $id, $field, $filename, $style = 'original', $data = array())
 {
     $info = new SplFileInfo($filename);
     $data += array('webroot' => preg_replace('/\\/$/', '', WWW_ROOT), 'model' => Inflector::tableize($name), 'field' => strtolower($field), 'filename' => $info->getBasename($info->getExtension()), 'extension' => $info->getExtension(), 'id' => $id, 'style' => $style, 'hash' => md5($info->getFilename() . Configure::read('Security.salt')));
     foreach (static::$_interpolations as $name => $closure) {
         $data[$name] = $closure($info);
     }
     return String::insert($string, $data);
 }
 /**
  * 
  */
 public function admin_delete($id, $model, $image)
 {
     $data = ClassRegistry::init($model)->findById($id);
     $images = str_replace($image, '', $data[$model]['images']);
     $this->_save($id, $model, $images);
     $controller = Inflector::tableize($model);
     $action = 'edit';
     $this->redirect(array('controller' => $controller, 'action' => 'edit', 'id' => $id));
 }
示例#26
0
文件: CsvView.php 项目: ayaou/Zuha
 public function render($view = null, $layout = null)
 {
     $path = Inflector::tableize($this->viewPath);
     $arr = isset($this->viewVars[$path]) ? $this->viewVars[$path] : $this->request->data;
     if (empty($arr)) {
         return '';
     }
     $csv = $this->_array_to_csv($arr);
     return $csv;
 }
示例#27
0
 public function setup(&$model, array $settings)
 {
     $this->dir = Inflector::tableize($model->alias);
     $this->_fields[$model->alias] = $settings['fields'];
     if (!isset($settings['configs'])) {
         $settings['configs'] = array();
     }
     $this->configs = array_merge($this->configs, $settings['configs']);
     $this->settings[$model->name] = array_merge($this->configs, array('path_to_dir' => WWW_ROOT . 'files/' . $this->dir), $this->_fields[$model->alias]);
 }
示例#28
0
 /**
  * Forge
  *
  * @param   array   Fields mainly
  * @param   string  Subfolder (or admin "theme") where views are held
  * @return	mixed
  */
 public static function forge($args, $subfolder)
 {
     $data = array();
     $subfolder = trim($subfolder, '/');
     if (!is_dir(PKGPATH . 'oil/views/' . static::$view_subdir . $subfolder)) {
         throw new Exception('The subfolder for admin templates does not exist or is spelled wrong: ' . $subfolder . ' ');
     }
     // Go through all arguments after the first and make them into field arrays
     $data['fields'] = array();
     foreach (array_slice($args, 1) as $arg) {
         // Parse the argument for each field in a pattern of name:type[constraint]
         preg_match(static::$fields_regex, $arg, $matches);
         $data['fields'][] = array('name' => \Str::lower($matches[1]), 'type' => isset($matches[2]) ? $matches[2] : 'string', 'constraint' => isset($matches[4]) ? $matches[4] : null);
     }
     $name = array_shift($args);
     // Replace / with _ and classify the rest. DO NOT singularize
     $controller_name = \Inflector::classify(static::$controller_prefix . str_replace(DS, '_', $name), false);
     // Replace / with _ and classify the rest. Singularize
     $model_name = \Inflector::classify(static::$model_prefix . str_replace(DS, '_', $name));
     // Either foo or folder/foo
     $view_path = $controller_path = str_replace(array('_', '-'), DS, \Str::lower($controller_name));
     // Models are always singular, tough!
     $model_path = str_replace(array('_', '-'), DS, \Str::lower($model_name));
     // uri's have forward slashes, DS is a backslash on Windows
     $uri = str_replace(DS, '/', $controller_path);
     $data['include_timestamps'] = !\Cli::option('no-timestamp', false);
     // If a folder is used, the entity is the last part
     $name_parts = explode(DS, $name);
     $data['singular_name'] = \Inflector::singularize(end($name_parts));
     $data['plural_name'] = \Inflector::pluralize($data['singular_name']);
     $data['table'] = \Inflector::tableize($model_name);
     $data['controller_parent'] = static::$controller_parent;
     /** Generate the Migration **/
     $migration_args = $args;
     array_unshift($migration_args, 'create_' . \Inflector::pluralize(\Str::lower($name)));
     Generate::migration($migration_args, false);
     // Merge some other data in
     $data = array_merge(compact(array('controller_name', 'model_name', 'model_path', 'view_path', 'uri')), $data);
     /** Generate the Model **/
     $model = \View::forge(static::$view_subdir . $subfolder . '/model', $data);
     Generate::create(APPPATH . 'classes/model/' . $model_path . '.php', $model, 'model');
     /** Generate the Controller **/
     $controller = \View::forge(static::$view_subdir . $subfolder . '/controller', $data);
     $controller->actions = array(array('name' => 'index', 'params' => '', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/index', $data)), array('name' => 'view', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/view', $data)), array('name' => 'create', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/create', $data)), array('name' => 'edit', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/edit', $data)), array('name' => 'delete', 'params' => '$id = null', 'code' => \View::forge(static::$view_subdir . $subfolder . '/actions/delete', $data)));
     Generate::create(APPPATH . 'classes/controller/' . $controller_path . '.php', $controller, 'controller');
     // Create each of the views
     foreach (array('index', 'view', 'create', 'edit', '_form') as $view) {
         Generate::create(APPPATH . 'views/' . $controller_path . '/' . $view . '.php', \View::forge(static::$view_subdir . $subfolder . '/views/actions/' . $view, $data), 'view');
     }
     // Add the default template if it doesnt exist
     if (!file_exists($app_template = APPPATH . 'views/template.php')) {
         Generate::create($app_template, file_get_contents(PKGPATH . 'oil/views/' . static::$view_subdir . $subfolder . '/views/template.php'), 'view');
     }
     Generate::build();
 }
示例#29
0
 /**
  * create log table
  *
  * @param string $modelName
  */
 function _create($modelName)
 {
     $modelName = Inflector::classify($modelName);
     $logModelName = $modelName . 'Log';
     // TODO: read suffix option
     $logTableName = Inflector::tableize($logModelName);
     // -- load model
     $Model = ClassRegistry::init($modelName);
     $fieldPrefix = Inflector::singularize($Model->table) . '_';
     $modelSchema = $Model->schema();
     // == create log table schema
     // primaryKey
     if (!empty($modelSchema[$Model->primaryKey])) {
         $assocField = $fieldPrefix . $Model->primaryKey;
         $modelSchema[$assocField] = $modelSchema[$Model->primaryKey];
         $modelSchema[$assocField]['key'] = 'index';
         $modelSchema['indexes']['IX_' . $assocField] = array('column' => $assocField, 'unique' => 0);
         unset($modelSchema[$Model->primaryKey]);
     }
     foreach (array('created', 'modified', 'updated') as $field) {
         if (!empty($modelSchema[$field])) {
             $modelSchema[$fieldPrefix . $field] = $modelSchema[$field];
             unset($modelSchema[$field]);
         }
     }
     $modelSchema = am(array('id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 20, 'key' => 'primary'), 'created' => array('type' => 'datetime', 'null' => true, 'default' => NULL)), $modelSchema);
     $modelSchema['indexes']['PRIMARY'] = array('column' => 'id', 'unique' => 1);
     // == process
     $ds = $Model->getDataSource();
     /* @var $ds DboSource */
     $this->Schema->load(array($logTableName => $modelSchema));
     $dropStatement = $ds->dropSchema($this->Schema, $logTableName);
     $createStatement = $ds->createSchema($this->Schema, $logTableName);
     $this->out("\n" . __('The following table(s) will be dropped.', true));
     $this->out($logTableName);
     if ('y' == $this->in(__('Are you sure you want to drop the table(s)?', true), array('y', 'n'), 'n')) {
         $this->out(__('Dropping table(s).', true));
         if (!$ds->execute($dropStatement)) {
             $this->error($logTableName . ': ' . $ds->lastError());
         } else {
             $this->out(sprintf(__('%s updated.', true), $logTableName));
         }
     }
     $this->out("\n" . __('The following table(s) will be created.', true));
     $this->out($logTableName);
     if ('y' == $this->in(__('Are you sure you want to create the table(s)?', true), array('y', 'n'), 'y')) {
         $this->out(__('Creating table(s).', true));
         if (!$ds->execute($createStatement)) {
             $this->error($logTableName . ': ' . $ds->lastError());
         } else {
             $this->out(sprintf(__('%s updated.', true), $logTableName));
         }
     }
     $this->out(__('End create.', true));
 }
示例#30
0
 public static function find($value, $columnName = 'id')
 {
     $reflector = new \ReflectionClass(get_called_class());
     $inflector = new Inflector();
     $tableName = $inflector->tableize($reflector->getName());
     $stmt = self::$_connection->prepare("SELECT * FROM " . $tableName . " WHERE `" . $columnName . "` = :Value");
     $stmt->bindParam('Value', $value);
     $stmt->execute();
     $data = $stmt->fetch(\PDO::FETCH_ASSOC);
     return $data;
 }