/** * Initialization of the cookie adapter. * * @return void */ protected function _init() { parent::_init(); if (!$this->_config['name']) { $this->_config['name'] = Inflector::slug(basename(LITHIUM_APP_PATH)) . 'cookie'; } }
/** * Get content of file, parse it with lessc and return formatted css * * @todo allow for css-file name only, and search it in all avail. webroots * @param string $file full path to file * @param array $options Additional options to control flow of method * - header - controls, whether to prepend a header * - cache - controls, whether to cache the result * - cachePath - Where to cache files, defaults to * resources/tmp/cache * @return string|boolean generated css, false in case of error */ public static function file($file, array $options = array()) { $defaults = array('header' => true, 'cache' => true, 'cachePath' => Libraries::get(true, 'resources') . '/tmp/cache', 'cacheKey' => Inflector::slug(str_replace(array(LITHIUM_APP_PATH, '.less'), array('', '.css'), $file))); $options += $defaults; $css_file = $options['cachePath'] . '/' . $options['cacheKey']; if (file_exists($css_file) && filemtime($css_file) >= filemtime($file)) { return file_get_contents($css_file); } if (!file_exists($file)) { return false; } try { $less = static::_getLess($file); $output = $less->parse(); } catch (Exception $e) { $output = "/* less compiler exception: {$e->getMessage()} */"; } if ($options['header']) { $output = static::_prependHeader($output); } if ($options['cache']) { file_put_contents($css_file, $output); } return $output; }
public function render($data, $contents = array(), array $options = array()) { $this->_mustache(); $defaults = array('id' => '', 'class' => '', 'hash' => true, 'right' => ''); $options += $defaults; $tabs = $panes = array(); foreach ($data as $slug => $tab) { if (!is_array($tab)) { $tab = array('name' => $tab); } $slug = is_numeric($slug) ? strtolower(Inflector::slug($tab['name'])) : $slug; $tab = $this->_tab($tab, array('id' => $slug)); if (empty($tab['url'])) { $tab['url'] = $options['hash'] ? sprintf('#%s', $slug) : $slug; } else { $slug = str_replace('#', '', $tab['url']); } if (isset($tab['content'])) { $panes[] = $this->_pane($tab['content'], $tab); unset($tab['content']); } $tabs[] = $tab; } $params = $options += compact('tabs', 'panes'); return $this->mustache->render('tabs', $params, array('library' => 'li3_bootstrap')); }
/** * Prepare `Aco` and `Aro` identifiers to be used for finding Acos and Aros nodes */ protected function _prepareAcl() { $request = $this->request->params; $user = $this->_user; $guest = $this->_guest; $buildAroPath = function ($group = null, $path = array()) use(&$buildAroPath) { $parent = null; $path[] = Inflector::pluralize($group['slug']); if ($group['parent_id']) { $parent = UserGroups::first(array('conditions' => array('parent_id' => $group['parent_id']))); } if ($parent) { return $buildAroPath($parent, $path); } return join('/', $path); }; $prepareAco = function () use($request) { extract($request); $library = isset($library) ? $library . '/' : ''; return $library . 'controllers/' . $controller; }; $prepareAro = function () use($user, $guest, $buildAroPath) { if ($guest) { return 'guests'; } return 'users/' . $buildAroPath($user['user_group']); }; $this->_aco = $prepareAco(); $this->_aro = $prepareAro(); }
/** * Override the save method to handle view specific params. * * @param array $params * @return mixed */ protected function _save(array $params = array()) { $params['path'] = Inflector::underscore($this->request->action); $params['file'] = $this->request->args(0); $contents = $this->_template(); $result = String::insert($contents, $params); if (!empty($this->_library['path'])) { $path = $this->_library['path'] . "/views/{$params['path']}/{$params['file']}"; $file = str_replace('//', '/', "{$path}.php"); $directory = dirname($file); if (!is_dir($directory)) { if (!mkdir($directory, 0755, true)) { return false; } } $directory = str_replace($this->_library['path'] . '/', '', $directory); if (file_exists($file)) { $prompt = "{$file} already exists. Overwrite?"; $choices = array('y', 'n'); if ($this->in($prompt, compact('choices')) !== 'y') { return "{$params['file']} skipped."; } } if (is_int(file_put_contents($file, $result))) { return "{$params['file']}.php created in {$directory}."; } } return false; }
public function testIndexScaffold() { $this->_controller->index(); $scaffold = $this->_controller->access('scaffold'); $expected = array('base' => '/radium/configurations', 'controller' => 'Configurations', 'library' => 'radium', 'class' => 'MockConfigurations', 'model' => 'radium\\tests\\mocks\\data\\MockConfigurations', 'slug' => Inflector::underscore('MockConfigurations'), 'singular' => Inflector::singularize('MockConfigurations'), 'plural' => Inflector::pluralize('MockConfigurations'), 'table' => Inflector::tableize('MockConfigurations'), 'human' => Inflector::humanize('MockConfigurations')); $this->assertEqual($expected, $scaffold); }
public static function add($name, array $config = array()) { $session = static::$_classes['session']; $name = strtolower(Inflector::slug($name)); $defaults = array('adapter' => '', 'name' => $name); return static::$_configurations[$name] = $config + $defaults; }
/** * Get DB table name for the migration * Table name is pluralized (tableized) class name by default * * @param $request * @return string */ protected function _source($request) { if ($request->source) { return $request->source; } return Inflector::tableize($request->action); }
public static function library($name, array $options = array()) { $defaults = array('docs' => 'config/docs/index.json', 'language' => 'en'); $options += $defaults; if (!($config = Libraries::get($name))) { return array(); } if (file_exists($file = "{$config['path']}/{$options['docs']}")) { $config += (array) json_decode(file_get_contents($file), true); } if (isset($config['languages']) && in_array($options['language'], $config['languages'])) { $config += $config[$options['language']]; foreach ($config['languages'] as $language) { unset($config[$language]); } } $docConfig = Libraries::get('li3_docs'); $category = 'libraries'; if (isset($docConfig['categories']) && is_array($docConfig['categories'])) { if (isset($config['category'])) { unset($config['category']); } foreach ($docConfig['categories'] as $key => $include) { if ($include === true || !in_array($name, array_values((array) $include))) { continue; } $category = $key; } } return $config + array('title' => Inflector::humanize($name), 'category' => $category); }
public function testTransliteration() { $data = array( 'transliteration' => array( '\$' => 'dollar', '&' => 'and' ) ); Catalog::write('runtime', 'inflection', 'en', $data); Inflector::rules( 'transliteration', Catalog::read('runtime', 'inflection.transliteration', 'en') ); $result = Inflector::slug('this & that'); $expected = 'this-and-that'; $this->assertEqual($expected, $result); $data = array( 'transliteration' => array( 't' => 'd', '&' => 'und' ) ); Catalog::write('runtime', 'inflection', 'de', $data); Inflector::rules( 'transliteration', Catalog::read('runtime', 'inflection.transliteration', 'de') ); $result = Inflector::slug('this & that'); $expected = 'dhis-und-dhad'; $this->assertEqual($expected, $result); }
public function relationship($class, $type, $name, array $options = array()) { $keys = Inflector::underscore($type == 'belongsTo' ? $name : $class::meta('name')) . '_id'; $options += compact('name', 'type', 'keys'); $options['from'] = $class; $relationship = $this->_classes['relationship']; return new $relationship($options); }
public function path($entity) { $resource = Inflector::tableize(basename(str_replace('\\', '/', $entity->model()))); if ($entity->exists()) { return '/' . $resource . '/' . $entity->_id; } else { return '/' . $resource; } }
/** * Get the class name for the mock. * * @param string $request * @return string */ protected function _class($request) { $name = $request->action; $type = $request->command; if ($command = $this->_instance($type)) { $request->params['action'] = $name; $name = $command->invokeMethod('_class', array($request)); } return Inflector::classify("Mock{$name}"); }
/** * Growl logger constructor. Accepts an array of settings which are merged with the default * settings and used to create the connection and handle notifications. * * @see lithium\analysis\Logger::write() * @param array $config The settings to configure the logger. Available settings are as follows: * - `'name`' _string_: The name of the application as it should appear in Growl's * system settings. Defaults to the directory name containing your application. * - `'host'` _string_: The Growl host with which to communicate, usually your * local machine. Use this setting to send notifications to another machine on * the network. Defaults to `'127.0.0.1'`. * - `'port'` _integer_: Port of the host machine. Defaults to the standard Growl * port, `9887`. * - `'password'` _string_: Only required if the host machine requires a password. * If notification or registration fails, check this against the host machine's * Growl settings. * - '`protocol'` _string_: Protocol to use when opening socket communication to * Growl. Defaults to `'udp'`. * - `'title'` _string_: The default title to display when showing Growl messages. * The default value is the same as `'name'`, but can be changed on a per-message * basis by specifying a `'title'` key in the `$options` parameter of * `Logger::write()`. * - `'notification'` _array_: A list of message types you wish to register with * Growl to be able to send. Defaults to `array('Errors', 'Messages')`. * @return void */ public function __construct(array $config = array()) { $name = basename(LITHIUM_APP_PATH); $defaults = array('name' => $name, 'host' => '127.0.0.1', 'port' => 9887, 'password' => null, 'protocol' => 'udp', 'title' => Inflector::humanize($name), 'notifications' => array('Errors', 'Messages'), 'connection' => function ($host, $port) { if ($conn = fsockopen($host, $port, $message, $code)) { return $conn; } throw new NetworkException("Growl connection failed: ({$code}) {$message}"); }); parent::__construct($config + $defaults); }
public static function __init($options = array()) { $self = static::_instance(); if (!isset($self->_meta['source'])) { $model = get_class($self); $tmp = explode('\\', $model); $modelName = end($tmp); $self->_meta['source'] = \lithium\util\Inflector::tableize($modelName); } parent::__init($options); }
/** * Data source READ operation. * * @param string $query * @param array $options * @return mixed */ public function read($query, array $options = array()) { $params = $query->export($this); list($path, $data) = $this->_request($params); $source = $params['source']; $name = Inflector::singularize($source); $data = str_replace("\n", '', $this->_render("{$name}.list")); $result = $this->connection->post('xml-in', $data, array('type' => 'xml')); $result = $data = json_decode(json_encode(simplexml_load_string($result)), true); return $this->item($query->model(), array($result[$source]), array('class' => 'set')); }
public function run($name = null, $null = null) { $library = Libraries::get($this->library); if (empty($library['prefix'])) { return false; } $model = Inflector::classify($name); $use = "\\{$library['prefix']}models\\{$model}"; $params = array('namespace' => "{$library['prefix']}controllers", 'use' => $use, 'class' => "{$name}Controller", 'model' => $model, 'singular' => Inflector::singularize(Inflector::underscore($name)), 'plural' => Inflector::pluralize(Inflector::underscore($name))); if ($this->_save($this->template, $params)) { $this->out("{$params['class']} created in {$params['namespace']}."); return true; } return false; }
public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); $filtered = $testable->findAll(array(T_VARIABLE)); foreach ($filtered as $id) { $token = $tokens[$id]; $isntSuperGlobal = !isset($this->_superglobals[$token['content']]); if ($isntSuperGlobal) { $name = preg_replace('/(\\$_?|_+$)/', '', $token['content']); if ($name !== Inflector::camelize($name, false)) { $this->addViolation(array('message' => "Variable {$name} is not camelBack style", 'line' => $token['line'])); } } } }
/** * Will iterate the tokens looking for a T_CLASS which should be * in CamelCase and match the file name * * @param Testable $testable The testable object * @return void */ public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); $pathinfo = pathinfo($testable->config('path')); if ($pathinfo['extension'] !== 'php') { return; } $filtered = $testable->findAll(array(T_CLASS)); foreach ($filtered as $key) { $token = $tokens[$key]; $className = $tokens[$key + 2]['content']; if ($className !== Inflector::camelize($className)) { $this->addViolation(array('message' => 'Class name is not in CamelCase style', 'line' => $token['line'])); } elseif ($className !== $pathinfo['filename']) { $this->addViolation(array('message' => 'Class name and file name should match', 'line' => $token['line'])); } } }
protected function _init() { parent::_init(); $config = $this->_config; $singularName = $config['name']; if ($config['type'] == 'hasMany') { $singularName = Inflector::singularize($config['name']); } if (!$config['to']) { $assoc = preg_replace("/\\w+\$/", "", $config['from']) . $singularName; $config['to'] = class_exists($assoc) ? $assoc : Libraries::locate('models', $assoc); } if (!$config['fieldName']) { $config['fieldName'] = lcfirst($config['name']); } $config['keys'] = $this->_keys($config['keys'], $config); $this->_config = $config; }
public function relationship($class, $type, $name, array $config = array()) { $field = Inflector::underscore(Inflector::singularize($name)); $key = "{$field}_id"; $primary = $class::meta('key'); if (is_array($primary)) { $key = array_combine($primary, $primary); } elseif ($type === 'hasMany' || $type === 'hasOne') { if ($type === 'hasMany') { $field = Inflector::pluralize($field); } $secondary = Inflector::underscore(Inflector::singularize($class::meta('name'))); $key = array($primary => "{$secondary}_id"); } $from = $class; $fieldName = $field; $config += compact('type', 'name', 'key', 'from', 'fieldName'); return $this->_instance('relationship', $config); }
/** * Will iterate the tokens looking for functions validating they have the * correct camelBack naming style. * * @param Testable $testable The testable object * @return void */ public function apply($testable, array $config = array()) { $tokens = $testable->tokens(); $filtered = $testable->findAll(array(T_FUNCTION)); foreach ($filtered as $key) { $token = $tokens[$key]; $label = Parser::label($key, $tokens); $modifiers = Parser::modifiers($key, $tokens); $isClosure = Parser::closure($key, $tokens); if (in_array($label, $this->_magicMethods)) { continue; } if ($testable->findNext(array(T_PROTECTED), $modifiers) !== false) { $label = preg_replace('/^_/', '', $label); } if (!$isClosure && $label !== Inflector::camelize($label, false)) { $this->addViolation(array('message' => 'Function "' . $label . '" is not in camelBack style', 'line' => $tokens[$tokens[$key]['parent']]['line'])); } } }
/** * Returns a list of links to model types' actions (Page types, User types, etc.) * By default, with no options specified, this returns a list of links to create any type of page (except core page). * * @param $model_name String The model name (can be lowercase, the Util class corrects it) * @param $action String The controller action * @param $options Array Various options that get passed to Util::list_types() and the key "link_options" can contain an array of options for the $this->html->link() * @return String HTML list of links * @see minerva\libraries\util\Util::list_types() */ public function link_types($model_name='Page', $action='create', $options=array()) { $options += array('exclude_minerva' => true, 'link_options' => array()); $libraries = Util::list_types($model_name, $options); $output = ''; (count($libraries) > 0) ? $output .= '<ul>':$output .= ''; foreach($libraries as $library) { if(substr($library, 0, 7) == 'minerva') { $model = $library; } else { $model = 'minerva\libraries\\' . $library; } $type = current(explode('\\', $library)); if(strtolower($type) == 'minerva') { $type = null; } $output .= '<li>' . $this->link($model::display_name(), '/' . Inflector::pluralize($model_name) . '/' . $action . '/' . $type, $options['link_options']) . '</li>'; } (count($libraries) > 0) ? $output .= '</ul>':$output .= ''; return $output; }
/** * Override the save method to handle view specific params. * * @param array $params */ protected function _save(array $params = array()) { $params['path'] = Inflector::underscore($this->request->action); $params['file'] = $this->request->args(0); $contents = $this->_template(); $result = String::insert($contents, $params); if (!empty($this->_library['path'])) { $path = $this->_library['path'] . "/views/{$params['path']}/{$params['file']}"; $file = str_replace('//', '/', "{$path}.php"); $directory = dirname($file); if (!is_dir($directory)) { if (!mkdir($directory, 0755, true)) { return false; } } $directory = str_replace($this->_library['path'] . '/', '', $directory); if (file_put_contents($file, "<?php\n\n{$result}\n\n?>")) { return "{$params['file']}.php created in {$directory}."; } } return false; }
/** * must be called with an array with the following fields to create an asset: * * Array ( * 'name' => 'foobar' // Name of file to be humanized for records name * 'type' => 'jpg' // file-extension, will be adapted to correct asset type * 'tmp_name' => '/dir/some-file.jpg' // FQDN of file, to be retrieved * 'size' => 44 // optional, size in bytes of file * ), * * @param array $file array as described above * @param array $options additional options * - `type`: overwrite type of file, if you want to disable automatic detection * - `delete`: triggers deletion of retrieved temporary file, defaults to true * - `keep`: triggers keeping temporary files in case of errors, defaults to true * @return array parsed content of Assets bytes */ public static function init($file, array $options = array()) { $defaults = array('type' => 'default', 'delete' => true, 'keep' => true); $options += $defaults; // fetch file, if remote // determine size of file on its own // determine md5 of file // find by md5, first $md5 = md5_file($file['tmp_name']); $asset = static::findByMd5($md5, array('fields' => '_id')); if ($asset) { if ($options['delete']) { unlink($file['tmp_name']); } $error = 'Asset already present'; return compact('error', 'asset'); } $mime = Mime::type($file['type']); if (is_array($mime)) { $mime = reset($mime); } $data = array('name' => Inflector::humanize($file['name']), 'filename' => sprintf('%s.%s', $file['name'], $file['type']), 'slug' => strtolower(sprintf('%s.%s', $file['name'], $file['type'])), 'md5' => $md5, 'extension' => $file['type'], 'type' => static::mimetype($mime), 'mime' => $mime, 'size' => $file['size'], 'file' => file_get_contents($file['tmp_name'])); try { $asset = static::create($data); if ($asset->validates()) { $file['success'] = (bool) $asset->save(); $file['asset'] = $asset; } else { $file['errors'] = $asset->errors(); } } catch (Exception $e) { // return array('error' => 'asset could not be saved.'); $file = array('error' => $e->getMessage()); } if (!empty($file['success']) && empty($file['error']) && !$options['keep']) { unlink($file['tmp_name']); } return $file; }
/** * Initialize location * Apply method filters */ public static function __init() { static::config(); static::applyFilter('mkdir', function ($self, $params, $chain) { $name = explode('/', $params['name']); foreach ($name as $i => $s) { $name[$i] = Inflector::slug($s); } $params['name'] = join('/', $name); return $chain->next($self, $params, $chain); }); static::applyFilter('upload', function ($self, $params, $chain) { $file = explode('.', $params['file']['name']); $end = count($file) - 1; $extension = $file[$end]; unset($file[$end]); $name = join($file); $params['file']['name'] = Inflector::slug($name) . ".{$extension}"; return $chain->next($self, $params, $chain); }); static::applyFilter('copy', function ($self, $params, $chain) { $source = trim($params['source'], '/'); $dest = trim($params['dest'], '/'); if (substr($dest, 0, strlen($source)) === $source) { return false; } return $chain->next($self, $params, $chain); }); static::applyFilter('move', function ($self, $params, $chain) { $source = trim($params['oldname'], '/'); $dest = trim($params['newname'], '/'); if (substr($dest, 0, strlen($source)) === $source) { return false; } return $chain->next($self, $params, $chain); }); }
/** * Return meta information, for compatibility with LI3. * * @param string $key - name of property to return, e.g. * 'name' or 'source' * @param string $val - ignored */ public static function meta($key = null, $val = null) { $class = get_called_class(); $parts = explode("\\", $class); $name = $parts[count($parts) - 1]; if ($key == 'name') { return strtolower($name); } else { if ($key == 'source') { return static::$sourceName ? static::$sourceName : strtolower(Inflector::tableize($name)); } } }
<?php use lithium\util\Inflector; if (!isset($object) || !$object) { return; } $makeTitle = function ($value) { if (strpos($value, '.md') === false) { return $value; } $value = str_replace('.md', '', $value); $value = str_replace('-', '_', $value); if (strlen($value) <= 3) { return strtoupper($value); } return Inflector::humanize($value); }; ?> <nav class="crumbs"> <?php echo $this->html->link('Documentation', ['library' => 'li3_docs', 'controller' => 'ApiBrowser']); ?> > <ul> <?php foreach (array_slice($this->docs->crumbs($object), 1) as $crumb) { ?> <li class="<?php echo $crumb['class']; ?>
/** * Document relationships. * * @param string $class * @param string $type Relationship type, e.g. `belongsTo`. * @param string $name * @param array $config * @return array */ public function relationship($class, $type, $name, array $config = array()) { $key = Inflector::camelize($type == 'belongsTo' ? $class::meta('name') : $name, false); $config += compact('name', 'type', 'key'); $config['from'] = $class; $relationship = $this->_classes['relationship']; $defaultLinks = array('hasOne' => $relationship::LINK_EMBEDDED, 'hasMany' => $relationship::LINK_EMBEDDED, 'belongsTo' => $relationship::LINK_CONTAINED); $config += array('link' => $defaultLinks[$type]); return new $relationship($config); }
/** * Uses results (typically coming from a controller action) to generate content and headers for * a `Response` object. * * @see lithium\action\Controller::$_render * @param array $options An array of options, as follows: * - `'data'`: An associative array of variables to be assigned to the template. These * are merged on top of any variables set in `Controller::set()`. * - `'head'`: If true, only renders the headers of the response, not the body. Defaults * to `false`. * - `'template'`: The name of a template, which usually matches the name of the action. * By default, this template is looked for in the views directory of the current * controller, i.e. given a `PostsController` object, if template is set to `'view'`, * the template path would be `views/posts/view.html.php`. Defaults to the name of the * action being rendered. * * The options specified here are merged with the values in the `Controller::$_render` * property. You may refer to it for other options accepted by this method. * @return object Returns the `Response` object associated with this `Controller` instance. */ public function render(array $options = array()) { $media = $this->_classes['media']; $class = get_class($this); $name = preg_replace('/Controller$/', '', substr($class, strrpos($class, '\\') + 1)); $key = key($options); if (isset($options['data'])) { $this->set($options['data']); unset($options['data']); } $defaults = array('status' => null, 'location' => false, 'data' => null, 'head' => false, 'controller' => Inflector::underscore($name), 'library' => Libraries::get($class)); $options += $this->_render + $defaults; if ($key && $media::type($key)) { $options['type'] = $key; $this->set($options[$key]); unset($options[$key]); } $this->_render['hasRendered'] = true; $this->response->type($options['type']); $this->response->status($options['status']); $this->response->headers('Location', $options['location']); if ($options['head']) { return; } $response = $media::render($this->response, $this->_render['data'], $options + array('request' => $this->request)); return $this->response = $response ?: $this->response; }