public function test_pluralize_singulars()
 {
     $ar = (require __DIR__ . '/cases/singular_to_plural.php');
     foreach ($ar as $singular => $plural) {
         $this->assertEquals($plural, self::$inflector->pluralize($singular));
         $this->assertEquals($plural, self::$inflector->pluralize($plural));
         $this->assertEquals(ucfirst($plural), self::$inflector->pluralize(ucfirst($singular)));
         $this->assertEquals(ucfirst($plural), self::$inflector->pluralize(ucfirst($plural)));
     }
 }
예제 #2
0
 /**
  * main
  *
  * @return void
  */
 public function main()
 {
     $model = $this->in('Model name:');
     $controller = Inflector::pluralize($model);
     $controllerActions = $this->in('Do you want to bake the controller with admin prefix: yes/no', 'y/n', 'n');
     $usePlugin = $this->in("Do you want to bake in plugin: yes/no", 'y/n', 'n');
     if ($usePlugin == 'y') {
         $pluginName = $this->in('Name of your plugin:', null, '');
         if ($pluginName == '') {
             $usePlugin = 'n';
         }
     }
     if ($controllerActions == 'y') {
         $controllerActions = '--admin';
     } else {
         $controllerActions = '--public';
     }
     $theme = 'fuelux';
     $modelCommand = "ajax_template.ext_bake model {$model}";
     $controllerCommand = "ajax_template.ext_bake controller {$controller} {$controllerActions}";
     $viewCommand = "ajax_template.ext_bake view {$controller}";
     $postfix = " --theme {$theme}";
     if ($usePlugin == 'y') {
         $postfix .= " --plugin {$pluginName}";
     }
     $this->dispatchShell($modelCommand . $postfix);
     $this->dispatchShell($controllerCommand . $postfix);
     $this->dispatchShell($viewCommand . $postfix);
 }
예제 #3
0
	function __find_all ($class)
	{
		$query_string = "";

		if (count($class->attributes) > 0)
			$query_string = "?" . join('&', array_map(create_function('$a,$b', 'return "$a=$b";'), array_keys($class->attributes), array_values($class->attributes)));
		
		$response = $this->__request($class, 'GET', $query_string);
		
		$parser = new XMLParser();
		
		$array = $parser->parse_into_array($response->body);
		
		$class_name = "SS" . $class->class_name();
		$singular = Inflector::underscore($class->class_name());
		$plural = Inflector::pluralize($singular);
		
		$records = $array[$plural][$singular];
		
		if (ArrayHelper::is_associative($records))
			$records = array($records);
		
		$objects = array();
		foreach ($records as $attrs)
			$objects[] = new $class_name($attrs);

		return $objects;
	}
예제 #4
0
 /**
  * Override loadTasks() to handle paths
  *
  * @access public
  */
 function loadTasks()
 {
     parent::loadTasks();
     $task = Inflector::classify($this->command);
     if (isset($this->{$task}) && !in_array($task, array('Project', 'DbConfig'))) {
         if (empty($this->{$task}->path)) {
             $path = Inflector::underscore(Inflector::pluralize($this->command));
             $this->{$task}->path = $this->params['working'] . DS . $path . DS;
         }
         if (isset($this->params['connection'])) {
             $this->{$task}->connection = $this->params['connection'];
         }
         foreach ($this->args as $i => $arg) {
             if (strpos($arg, '.')) {
                 list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg);
                 break;
             }
         }
         if (isset($this->params['plugin'])) {
             $this->{$task}->plugin = $this->params['plugin'];
         }
         if (!is_dir($this->{$task}->path)) {
             $this->err(sprintf(__("%s directory could not be found.\nBe sure you have created %s", true), $task, $this->{$task}->path));
             $this->_stop();
         }
     }
 }
예제 #5
0
파일: generate.php 프로젝트: ralf57/fuel
	public function model($args)
	{
		$singular = strtolower(array_shift($args));

		$plural = \Inflector::pluralize($singular);

		$filepath = APPPATH . 'classes/model/' . $singular .'.php';

		$class_name = ucfirst($singular);

		$model = <<<MODEL
<?php

class Model_{$class_name} extends ActiveRecord\Model { }

/* End of file $singular.php */
MODEL;

		if (self::write($filepath, $model))
		{
			\Cli::write('Created model: ' . \Fuel::clean_path($filepath));
		}

		if ( ! empty($args))
		{
			array_unshift($args, 'create_'.$plural);
			static::migration($args);
		}
	}
예제 #6
0
 /**
  * beforeRender is used for pre-render processing.
  * Search the model schema for enum fields and transform
  * them to use selects instead of text-input boxes
  *
  * During the model loop, we also check for form validation
  * errors, and add them to an array, so that we can consolidate
  * errors at the top of the page.
  *
  * This code is probably Mysql specific.
  */
 function beforeRender()
 {
     $this->_persistValidation();
     $validationErrors = array();
     foreach ($this->modelNames as $model) {
         // add validationerrors to view
         if (is_array($this->{$model}->validationErrors)) {
             $validationErrors = array_merge($validationErrors, array_values($this->{$model}->validationErrors));
         }
         // enum fixer
         foreach ($this->{$model}->_schema as $var => $field) {
             // === used here because 0 != FALSE
             if (strpos($field['type'], 'enum') === FALSE) {
                 continue;
             }
             preg_match_all("/\\'([^\\']+)\\'/", $field['type'], $strEnum);
             if (is_array($strEnum[1])) {
                 $varName = Inflector::camelize(Inflector::pluralize($var));
                 $varName[0] = strtolower($varName[0]);
                 // make nice cases in <selects>
                 $names = array();
                 foreach ($strEnum[1] as $name) {
                     $names[] = ucwords(strtolower($name));
                 }
                 $this->set($varName, array_combine($strEnum[1], $names));
             }
         }
     }
     $this->set('validationErrors', $validationErrors);
 }
예제 #7
0
 /**
  * Sets the views meta data, if available
  *
  * @param array $data
  * @return void
  */
 public function set($data = array())
 {
     $Model = $this->__controller->{$this->__controller->modelClass};
     // assign the meta title variable, starting with data assigned
     // directly to MetaData, falling back next to the Model displayField
     // variable before falling again to the Model displayName variable
     if (!empty($data['MetaData']['title'])) {
         $metaTitle = $data['MetaData']['title'];
     } elseif (!empty($data[$Model->alias][$Model->displayField])) {
         $metaTitle = $data[$Model->alias][$Model->displayField];
     } else {
         $metaTitle = Inflector::pluralize($data[$Model->alias][$Model->displayName]);
     }
     if (!empty($metaTitle)) {
         $this->Controller->set(compact('metaTitle'));
     }
     // assign the meta description variable, starting with data
     // assigned directly to MetaData, falling back to content
     // and then body fields from within the supplied data
     if (!empty($data['MetaData']['description'])) {
         $metaDescription = $data['MetaData']['description'];
     } elseif (!empty($data[$Model->alias]['body'])) {
         // truncate the content variable to a max of 160 characters
         // ref: https://moz.com/learn/seo/meta-description
         $metaDescription = CakeText::truncate($data['MetaData']['description'], 160, array('html' => false));
     } elseif (!empty($data[$Model->alias]['content'])) {
         // truncate the content variable to a max of 160 characters
         // ref: https://moz.com/learn/seo/meta-description
         $metaDescription = CakeText::truncate($data[$Model->alias]['content'], 160, array('html' => false));
     }
     if (!empty($metaDescription)) {
         $this->Controller->set(compact('metaDescription'));
     }
     return;
 }
예제 #8
0
 public function chart($model = 'Payment', $interval = array('from' => '0001-01-01', 'to' => false))
 {
     if ($this->request->is('post')) {
         $model = $this->request->data['Chart']['model'];
         if (!empty($this->request->data['Chart']['from']) && !empty($this->request->data['Chart']['to'])) {
             $interval = array('from' => $this->request->data['Chart']['from'], 'to' => $this->request->data['Chart']['to']);
         } elseif (!empty($this->request->data['Chart']['from']) && empty($this->request->data['Chart']['to'])) {
             $interval = array('from' => $this->request->data['Chart']['from'], 'to' => date('Y-m-d'));
         } elseif (empty($this->request->data['Chart']['from']) && !empty($this->request->data['Chart']['to'])) {
             $interval = array('from' => '0001-01-01', 'to' => $this->request->data['Chart']['to']);
         }
     }
     if (!$interval['to']) {
         $interval['to'] = date('Y-m-d');
     }
     $chartName = 'chart';
     $pieChart = $this->HighCharts->create($chartName, 'pie');
     $data = array();
     $results = $this->{$model}->find('all', array('fields' => array('sum(value) as total', 'concat(IFNULL(concat(ParentCategory.name, " - "), ""), ChildCategory.name) as name', $model . '.description'), 'conditions' => array($model . '.date BETWEEN ? and ?' => $interval, 'or' => array($model . '.user_id' => $this->Authorization->User->id(), $model . '.team_id' => $this->Authorization->User->Team->id())), 'group' => $model . '.category_id', 'order' => 'total'));
     if (!$results) {
         $data = array(array('name' => __('No data available'), 'y' => 100.0, 'description' => 'descr'));
     }
     foreach ($results as $result) {
         $data[] = array('name' => $result[0]['name'], 'y' => (double) $result[0]['total'], 'description' => $result[$model]['description']);
     }
     if ($interval['from'] == '0001-01-01') {
         $interval['from'] = __('the beginning of time');
     }
     array_unshift($interval, Inflector::pluralize($model));
     $this->HighCharts->setChartParams($chartName, array('renderTo' => 'chart', 'tooltipEnabled' => true, 'tooltipFormatter' => "function() { return '<b>' + this.point.name + '</b>: '+ parseFloat(this.percentage).toFixed(2) +' %';}", 'chartMarginTop' => 40));
     $series = $this->HighCharts->addChartSeries();
     $series->addData($data);
     $pieChart->addSeries($series);
     $this->set('title', __('<strong>%s</strong> by category statistics from <strong>%s</strong> to <strong>%s</strong>', $interval));
 }
예제 #9
0
 public function api_index()
 {
     //$this->{$this->modelClass}->recursive = 0;
     $name = Inflector::pluralize($this->modelKey);
     $items = $this->{$this->modelClass}->find('all');
     $this->set(array($name => $items, '_serialize' => array($name)));
 }
예제 #10
0
 public static function generate($args, $subfolder = 'default')
 {
     $subfolder = trim($subfolder, '/');
     if (!is_dir(PKGPATH . 'oil/views/' . $subfolder)) {
         throw new Exception('The subfolder for scaffolding templates doesn\'t exist or is spelled wrong: ' . $subfolder . ' ');
     }
     // Do this first as there is the largest chance of error here
     Generate::model($args, false);
     // Go through all arguments after the first and make them into field arrays
     $fields = array();
     foreach (array_slice($args, 1) as $arg) {
         // Parse the argument for each field in a pattern of name:type[constraint]
         preg_match('/([a-z0-9_]+):([a-z0-9_]+)(\\[([0-9]+)\\])?/i', $arg, $matches);
         $fields[] = array('name' => strtolower($matches[1]), 'type' => isset($matches[2]) ? $matches[2] : 'string', 'constraint' => isset($matches[4]) ? $matches[4] : null);
     }
     $data['singular'] = $singular = strtolower(array_shift($args));
     $data['model'] = $model_name = 'Model_' . Generate::class_name($singular);
     $data['plural'] = $plural = \Inflector::pluralize($singular);
     $data['fields'] = $fields;
     $filepath = APPPATH . 'classes/controller/' . trim(str_replace(array('_', '-'), DS, $plural), DS) . '.php';
     $controller = \View::factory($subfolder . '/scaffold/controller', $data);
     $controller->actions = array(array('name' => 'index', 'params' => '', 'code' => \View::factory($subfolder . '/scaffold/actions/index', $data)), array('name' => 'view', 'params' => '$id = null', 'code' => \View::factory($subfolder . '/scaffold/actions/view', $data)), array('name' => 'create', 'params' => '$id = null', 'code' => \View::factory($subfolder . '/scaffold/actions/create', $data)), array('name' => 'edit', 'params' => '$id = null', 'code' => \View::factory($subfolder . '/scaffold/actions/edit', $data)), array('name' => 'delete', 'params' => '$id = null', 'code' => \View::factory($subfolder . '/scaffold/actions/delete', $data)));
     // Write controller
     Generate::create($filepath, $controller, 'controller');
     // Create each of the views
     foreach (array('index', 'view', 'create', 'edit', '_form') as $view) {
         Generate::create(APPPATH . 'views/' . $plural . '/' . $view . '.php', \View::factory($subfolder . '/scaffold/views/' . $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/default/template.php'), 'view');
     }
     Generate::build();
 }
예제 #11
0
    public static function model($args, $build = true)
    {
        $singular = strtolower(array_shift($args));
        if (empty($args)) {
            throw new Exception('No fields have been provided, the model will not know how to build the table.');
        }
        $plural = \Inflector::pluralize($singular);
        $filepath = APPPATH . 'classes/model/' . trim(str_replace(array('_', '-'), DS, $singular), DS) . '.php';
        // Uppercase each part of the class name and remove hyphens
        $class_name = static::class_name($singular);
        $model = <<<MODEL
<?php

class Model_{$class_name} extends Orm\\Model { }

/* End of file {$singular}.php */
MODEL;
        // Build the model
        static::create($filepath, $model, 'model');
        if (!empty($args)) {
            array_unshift($args, 'create_' . $plural);
            static::migration($args, false);
        } else {
            throw new Exception('Not enough arguments to create this migration.');
        }
        $build and static::build();
    }
예제 #12
0
파일: Hydrator.php 프로젝트: atijust/mappa
 /**
  * @param callable $convertClassToTableCallback
  */
 public function __construct(callable $convertClassToTableCallback = null)
 {
     $defaultCallback = function ($class) {
         return Inflector::snakecase(Inflector::pluralize(Inflector::basename($class)));
     };
     $this->convertClassToTableCallback = $convertClassToTableCallback ?: $defaultCallback;
 }
예제 #13
0
파일: menu.php 프로젝트: hadzi/brekfarm
 /**
  * beforeRender callback
  *
  * @return void
  * @access public
  */
 public function beforeRender()
 {
     parent::beforeRender();
     $this->Jquery->uses('jquery', 'ui', 'potato.menu');
     $this->_categoryModel = $this->params['menu']['model'];
     $this->_categoryController = Inflector::underscore(Inflector::pluralize($this->_categoryModel));
 }
예제 #14
0
파일: flag.php 프로젝트: rcrowe/fuel-flags
 /**
  * Check method against the flag.
  *
  * To check user id against feature `google_analytics`
  *
  * DB
  * --
  *   user_ids : 2,40,3
  *
  * Controller
  * ----------
  *   Feature::flag('google_analytics')->ip_address(40) -> TRUE
  *
  * @param  $flag       Name of method to check user can access feature flag. Signalised version of column name.
  * @param  $arguments  String or Array to match against.
  * @return Bool        Whether user can access feature
  */
 public function __call($flag, $arguments)
 {
     // If feature flag is enabled, all users can access it
     if ($this->row->get('enabled') === 'Y') {
         return TRUE;
     }
     // User didnt pass in anything to check against
     // Dont give user access to feature by default
     if (count($arguments) < 1) {
         return FALSE;
     }
     // Change name to plural version
     // Table can store multiple values per match item on flag
     $flag = \Inflector::pluralize($flag);
     $value = $arguments[0];
     $match = $this->row->get($flag);
     $match = explode(',', $match);
     if (is_array($value)) {
         foreach ($value as $item) {
             if (in_array($item, $match)) {
                 return TRUE;
             }
         }
     }
     return in_array($value, $match) ? TRUE : FALSE;
 }
 /**
  * REST api dispatcher
  */
 public function disparador()
 {
     # Load the appropriate version of the api
     $api['version'] = $this->params['version'];
     # Detect method: get/post/put/delete
     $api['method'] = strtolower($_SERVER['REQUEST_METHOD']);
     # Override the method when it is explicitly set
     if (isset($this->params->query['method'])) {
         $api['method'] = strtolower($this->params->query['method']);
         unset($this->params->query['method']);
     }
     # Define the noun
     $api['modelo'] = ucwords(Inflector::singularize($this->params['noun']));
     $api['controller'] = Inflector::pluralize($this->params['noun']);
     $this->loadModel($api['modelo']);
     # Check if we have a passed argument we should use
     if (isset($this->request->params['pass'][1])) {
         $api['id'] = $this->request->params['pass'][1];
         if ($api['id'] === 0) {
             return $this->_apiFallo('ID inválido');
         }
     }
     # Define possible parameters
     $api['parameters'] = $this->request->query;
     # If the header has signature and key, override the api['parameters']-value
     #if (isset($header['HTTP_KEY']))
     #	$api['parameters']['key'] = $header['HTTP_KEY'];
     if (isset($header['HTTP_SIGNATURE'])) {
         $api['parameters']['signature'] = $header['HTTP_SIGNATURE'];
     }
     # Check if we need to suppress the response codes
     if (isset($api['parameters']['suppress_response_code'])) {
         unset($api['parameters']['suppress_response_code']);
         $api['suppress_response_code'] = true;
     }
     # Check if we are debugging: ?debug should be set (or debug should be defined in header)
     if (isset($api['parameters']['debug']) || isset($header['HTTP_DEBUG'])) {
         unset($api['parameters']['debug']);
         $api['debug'] = true;
         $result['call'] = $api;
     }
     if (empty($this->request->params['pass'][0])) {
         return $this->_apiFallo('Metodo no encontrado');
     }
     $action = 'api_' . $this->request->params['pass'][0];
     if (!method_exists($this, $action)) {
         return $this->_apiFallo('Metodo no encontrado');
     }
     if (empty($api['parameters']['key'])) {
         $api['key'] = 'id';
     } else {
         $api['key'] = $api['parameters']['key'];
         unset($api['parameters']['key']);
         if (!ClassRegistry::init($api['controller'])->hasField($api['key'])) {
             return $this->_apiFallo('Key no encontrado');
         }
     }
     $this->setAction($action, $api);
 }
 public function export_csv()
 {
     $this->autoRender = false;
     //__ Authentication + Authorization __
     $user = $this->_ap_right_check();
     if (!$user) {
         return;
     }
     //Build query
     $user_id = $user['id'];
     $c = $this->_build_common_query($user);
     $q_r = $this->{$this->modelClass}->find('all', $c);
     //Create file
     $this->ensureTmp();
     $tmpFilename = TMP . $this->tmpDir . DS . strtolower(Inflector::pluralize($this->modelClass)) . '-' . date('Ymd-Hms') . '.csv';
     $fp = fopen($tmpFilename, 'w');
     //Headings
     $heading_line = array();
     if (isset($this->request->query['columns'])) {
         $columns = json_decode($this->request->query['columns']);
         foreach ($columns as $c) {
             array_push($heading_line, $c->name);
         }
     }
     fputcsv($fp, $heading_line, ';', '"');
     foreach ($q_r as $i) {
         $columns = array();
         $csv_line = array();
         if (isset($this->request->query['columns'])) {
             $columns = json_decode($this->request->query['columns']);
             foreach ($columns as $c) {
                 $column_name = $c->name;
                 if ($column_name == 'notes') {
                     $notes = '';
                     foreach ($i['UserNote'] as $n) {
                         if (!$this->_test_for_private_parent($n['Note'], $user)) {
                             $notes = $notes . '[' . $n['Note']['note'] . ']';
                         }
                     }
                     array_push($csv_line, $notes);
                 } elseif ($column_name == 'owner') {
                     $owner_id = $i['User']['parent_id'];
                     $owner_tree = $this->_find_parents($owner_id);
                     array_push($csv_line, $owner_tree);
                 } else {
                     array_push($csv_line, $i['User']["{$column_name}"]);
                 }
             }
             fputcsv($fp, $csv_line, ';', '"');
         }
     }
     //Return results
     fclose($fp);
     $data = file_get_contents($tmpFilename);
     $this->cleanupTmp($tmpFilename);
     $this->RequestHandler->respondAs('csv');
     $this->response->download(strtolower(Inflector::pluralize($this->modelClass)) . '.csv');
     $this->response->body($data);
 }
예제 #17
0
파일: plural.php 프로젝트: stripthis/donate
 /**
  * undocumented function
  *
  * @param string $string 
  * @param string $count 
  * @param string $showCount 
  * @return void
  * @access public
  */
 function ize($string, $count, $showCount = true)
 {
     if ($count != 1) {
         $inflect = new Inflector();
         return ($showCount ? $count . ' ' : '') . $inflect->pluralize($string);
     }
     return ($showCount ? $count . ' ' : '') . $string;
 }
예제 #18
0
 /**
  * Read configured Translate.models and hook the appropriate behaviors
  */
 public static function translateModels()
 {
     $path = 'admin:true/plugin:translate/controller:translate/action:index/:id/';
     foreach (Configure::read('Translate.models') as $model => $config) {
         Croogo::hookBehavior($model, 'Translate.CroogoTranslate', $config);
         Croogo::hookAdminRowAction(Inflector::pluralize($model) . '/admin_index', __d('croogo', 'Translate'), array($path . $model => array('title' => false, 'options' => array('icon' => 'translate', 'data-title' => __d('croogo', 'Translate')))));
     }
 }
예제 #19
0
	/**
	 * Gets the path for output.  Checks the plugin property
	 * and returns the correct path.
	 *
	 * @return string Path to output.
	 * @access public
	 */
	function getPath() {
		$path = $this->path;
		if (isset($this->plugin)) {
			$name = substr($this->name, 0, strlen($this->name) - 4);
			$path = $this->_pluginPath($this->plugin) . Inflector::pluralize(Inflector::underscore($name)) . DS;
		}
		return $path;
	}
예제 #20
0
 function test_singularize_and_pluralize()
 {
     $plurals = array("cow" => "kine", "news" => "news", "person" => "people", "fish" => "fish", "attachment" => "attachments");
     foreach ($plurals as $singular => $plural) {
         $this->assertEqual($singular, Inflector::singularize($plural));
         $this->assertEqual(Inflector::pluralize($singular), $plural);
     }
 }
예제 #21
0
 private function create_labels($raw_name)
 {
     $name = H_Elper::to_title($raw_name);
     $plural = Inflector::pluralize($name);
     $singular = $name;
     $labels = array('name' => $plural, 'singular_name' => $singular, 'all_items' => 'All ' . $plural, 'add_new_item' => 'Add New ' . $singular, 'edit_item' => 'Edit ' . $singular, 'new_item' => 'New ' . $singular, 'view_item' => 'View ' . $singular, 'search_items' => 'Search ' . $plural, 'not_found' => 'No ' . strtolower($plural) . ' found', 'not_found_in_trash' => 'No ' . strtolower($plural) . ' found in Trash', 'parent_item_colon' => 'Parent ' . $singular . ':');
     return $labels;
 }
예제 #22
0
 public function references($ref_table, $ref_column = 'id', $options = array('on_update' => 'CASCADE', 'on_delete' => 'CASCADE'))
 {
     $column_name = Inflector::singularize($ref_table) . '_' . Inflector::singularize($ref_column);
     $ref_table = Inflector::pluralize($ref_table);
     $this->add_column($column_name, 'integer', array('null' => false));
     $this->add_index($column_name);
     $this->add_foreign_key($column_name, $ref_table, $ref_column, $options);
 }
예제 #23
0
파일: bake.php 프로젝트: robotarmy/Phog
 /**
  * Gets the path for output.  Checks the plugin property
  * and returns the correct path.
  *
  * @return string Path to output.
  */
 public function getPath()
 {
     $path = $this->path;
     if (isset($this->plugin)) {
         $path = $this->_pluginPath($this->plugin) . Inflector::pluralize(Inflector::underscore($this->name)) . DS;
     }
     return $path;
 }
예제 #24
0
 private function create_labels($label, $name)
 {
     $plural = Inflector::pluralize($label);
     $singular = $label;
     $title = H_Elper::to_title($name);
     $title_plural = Inflector::pluralize($title);
     $labels = array('name' => $title_plural, 'singular_name' => $title, 'menu_name' => $plural, 'all_items' => 'All ' . $plural, 'edit_item' => 'Edit ' . $singular, 'view_item' => 'View ' . $singular, 'update_item' => 'Update ' . $singular, 'add_new_item' => 'Add New ' . $singular, 'parent_item' => 'Parent ' . $singular, 'search_items' => 'Search ' . $plural, 'popular_items' => NULL, 'add_or_remove_items' => 'Add or remove ' . strtolower($plural), 'choose_from_most_used' => 'Choose from the most used ' . strtolower($plural), 'not_found' => 'No ' . strtolower($plural) . ' found');
     return $labels;
 }
예제 #25
0
 /**
  * Setup
  *
  * @param object AppModel
  * @param array $config
  */
 public function setup(Model $model, $config = array())
 {
     $global = Configure::read('PublishableBehavior');
     $defaults = $global ? array_merge($this->_defaults, $global) : $this->_defaults;
     $settings = array_merge($defaults, $config);
     $this->settings[$model->alias] = $settings;
     $namespace = '/' . strtolower(Inflector::pluralize($model->alias));
     $model->websocket = new WebSocket(array_merge($settings['server'], array('namespace' => $namespace, 'silent' => true)));
 }
예제 #26
0
 function index()
 {
     if (isset($this->params['alt_content']) && $this->params['alt_content'] != 'Rss') {
         $this->viewPath = 'errors';
         $this->render('not_found');
     }
     $this->set('products', $this->Product->findall("Product.draft=0", null, 'Product.modified DESC', 20));
     $this->pageTitle = Inflector::pluralize(Configure::read('Product.alias'));
 }
예제 #27
0
 public static function pluralize($word)
 {
     foreach (self::$_exceptions as $exception) {
         if ($exception['singular'] == $word) {
             return $exception['plural'];
         }
     }
     return parent::pluralize($word);
 }
예제 #28
0
 static function pluralize($str = '')
 {
     $str = strtolower($str);
     if (array_key_exists($str, $tmp = self::GetPluralizeExceptions())) {
         return $tmp[$str];
     } else {
         return parent::pluralize($str);
     }
 }
예제 #29
0
 /**
  * Cette fonction permet le chargement d'un model
  * 
  * Appel possible dans un contrôleur : 
  * 
  * 		$databaseConfigs = array(
  * 			'host' => "localhost",
  * 			'login' => "root",
  * 			'password' => "",
  * 			'database' => "koezion_madatabase",
  * 			'prefix' => "",
  * 			'socket' => "",
  * 			'port' => "",
  * 			'source' => "mysql"
  * 		);
  * 		$externalSlider = $this->load_model('Slider', true, $databaseConfigs);
  * 		pr($externalSlider->find());
  *
  * @param varchar 	$name 				Nom du model à charger
  * @param boolean 	$return 			Indique si il faut ou non retourner l'objet
  * @param array 	$databaseConfigs 	Configuration de connexion différentes de celles par défaut
  * @return Objet ou rien
  * @access public
  * @author koéZionCMS
  * @version 0.1 - 23/12/2011 by FI
  * @version 0.2 - 18/03/2014 by FI - Reprise du chargement des modèles des plugins
  * @version 0.3 - 03/06/2014 by FI - Rajout de la variable $databaseConfigs permettant la connexion à une autre BDD
  * @version 0.4 - 08/08/2014 by FI - Modification des données envoyées au constructeur, création de la variable $modelParams
  */
 public function load_model($name, $return = false, $databaseConfigs = null)
 {
     //En premier lieu on test si le model n'est pas déjà instancié
     //et si il ne l'est pas on procède à son intenciation
     if (!isset($this->{$name})) {
         $file_path = '';
         $file_name = Inflector::underscore($name) . '.php';
         //Nom du fichier à charger
         $file_path_default = ROOT . DS . 'models' . DS . $file_name;
         //Chemin vers le fichier à charger
         //Pour déterminer le dossier du plugin nous devons transformer le nom du model à charger
         //Etape 1 : passage au pluriel
         //Etape 2 : transformation du camelCased en _
         $pluginPluralizeName = Inflector::pluralize($name);
         $pluginUnderscoreName = Inflector::underscore($pluginPluralizeName);
         //////////////////////////////////////////////
         //   RECUPERATION DES CONNECTEURS PLUGINS   //
         $pluginsConnectors = get_plugins_connectors();
         if (isset($pluginsConnectors[$pluginUnderscoreName])) {
             $connectorModel = $pluginsConnectors[$pluginUnderscoreName];
             $file_path_plugin = PLUGINS . DS . $connectorModel . DS . 'models' . DS . $file_name;
             //Chargement de l'éventuel fichier supplémentaire pour les models
             $pluginModelBoostrap = PLUGINS . DS . $connectorModel . DS . 'model.php';
             if (file_exists($pluginModelBoostrap)) {
                 require_once $pluginModelBoostrap;
             }
         }
         //////////////////////////////////////////////
         if (isset($file_path_plugin) && file_exists($file_path_plugin)) {
             $file_path = $file_path_plugin;
         } else {
             if (file_exists($file_path_default)) {
                 $file_path = $file_path_default;
             }
         }
         //Sinon on test si le model par défaut existe
         //On va tester l'existence de ce fichier
         if (!file_exists($file_path)) {
             Session::write('redirectMessage', "Impossible de charger le modèle " . $name . " dans le fichier controller");
             $this->redirect('home/e404');
             die;
         }
         require_once $file_path;
         //Inclusion du fichier
         $modelParams = null;
         if (isset($this->request)) {
             $modelParams['url'] = $this->request->fullUrl;
             $modelParams['controller_action'] = isset($this->request->controller) && isset($this->request->action) ? $this->request->controller . '/' . $this->request->action : '';
         }
         if ($return) {
             return new $name($modelParams, $databaseConfigs);
         } else {
             $this->{$name} = new $name($modelParams, $databaseConfigs);
         }
         //Création d'un objet Model de type $name que l'on va instancier dans la classe
     }
 }
예제 #30
0
 public function testPlurals()
 {
     $this->assertEqual(Inflector::pluralize('category'), 'categories');
     $this->assertEqual(Inflector::pluralize('person'), 'persons');
     $this->assertEqual(Inflector::pluralize('mouse'), 'mice');
     $this->assertEqual(Inflector::pluralize('search'), 'searches');
     $this->assertEqual(Inflector::pluralize('alias'), 'aliases');
     $this->assertEqual(Inflector::pluralize('monitor'), 'monitors');
 }