/** * Override startup of the Shell * * @return void */ public function startup() { parent::startup(); if (isset($this->params['connection'])) { $this->connection = $this->params['connection']; } $class = Configure::read('Acl.classname'); if (strpos($class, '\\') === false && strpos($class, '.') === false) { $className = App::classname('Acl.' . $class, 'Adapter'); } else { $className = App::classname($class, 'Adapter'); } if ($class !== 'DbAcl' && !is_subclass_of($className, 'Acl\\Adapter\\DbAcl')) { $out = "--------------------------------------------------\n"; $out .= __d('cake_acl', 'Error: Your current CakePHP configuration is set to an ACL implementation other than DB.') . "\n"; $out .= __d('cake_acl', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n"; $out .= "--------------------------------------------------\n"; $out .= __d('cake_acl', 'Current ACL Classname: {0}', [$class]) . "\n"; $out .= "--------------------------------------------------\n"; $this->err($out); $this->_stop(); } if ($this->command) { if (Configure::check('Datasource') === null) { $this->out(__d('cake_acl', 'Your database configuration was not found. Take a moment to create one.')); $this->args = null; $this->DbConfig->execute(); return; } try { TableRegistry::get('Aros')->schema(); TableRegistry::remove('Aros'); } catch (\Cake\Database\Exception $e) { $this->out(__d('cake_acl', 'Acl database tables not found. To create them, run:')); $this->out(); $this->out(' bin/cake Migrations.migrations migrate -p Acl'); $this->out(); $this->_stop(); return; } $registry = new ComponentRegistry(); $this->Acl = new AclComponent($registry); } }
/** * Create a controller for a given request/response * * @param \Cake\Network\Request $request The request to build a controller for. * @param \Cake\Network\Response $response The response to use. * @return \Cake\Controller\Controller */ public function create(Request $request, Response $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (isset($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if (isset($request->params['controller'])) { $controller = $request->params['controller']; } if (isset($request->params['prefix'])) { if (strpos($request->params['prefix'], '/') === false) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } else { $prefixes = array_map('Cake\\Utility\\Inflector::camelize', explode('/', $request->params['prefix'])); $namespace .= '/' . implode('/', $prefixes); } } $firstChar = substr($controller, 0, 1); if (strpos($controller, '\\') !== false || strpos($controller, '.') !== false || $firstChar === strtolower($firstChar)) { return $this->missingController($request); } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return $this->missingController($request); } $reflection = new ReflectionClass($className); if ($reflection->isAbstract() || $reflection->isInterface()) { return $this->missingController($request); } return $reflection->newInstance($request, $response, $controller); }
/** * Gets controller to use, either plugin or application controller. * * @param \Cake\Network\Request $request Request object * @param \Cake\Network\Response $response Response for the controller. * @return \Cake\Controller\Controller|false Object if loaded, boolean false otherwise. */ protected function _getController($request, $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if (!empty($request->params['controller'])) { $controller = $request->params['controller']; } if (!empty($request->params['prefix'])) { $namespace .= '/' . $request->params['prefix']; } $firstChar = substr($controller, 0, 1); if (strpos($controller, '\\') !== false || strpos($controller, '.') !== false || $firstChar === strtolower($firstChar)) { return false; } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return false; } $reflection = new ReflectionClass($className); if ($reflection->isAbstract() || $reflection->isInterface()) { return false; } return $reflection->newInstance($request, $response, $controller); }
/** * Resolve a logger classname. * * Part of the template method for Cake\Utility\ObjectRegistry::load() * * @param string $class Partial classname to resolve. * @return string|false Either the correct classname or false. */ protected function _resolveClassName($class) { if (is_object($class)) { return $class; } return App::classname($class, 'Log/Engine', 'Log'); }
/** * Get controller to use, either plugin controller or application controller * * @param \Cake\Network\Request $request Request object * @param \Cake\Network\Response $response Response for the controller. * @return mixed name of controller if not loaded, or object if loaded */ protected function _getController($request, $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if (!empty($request->params['controller'])) { $controller = $request->params['controller']; } if (!empty($request->params['prefix'])) { $prefixes = array_map('Cake\\Utility\\Inflector::camelize', explode('/', $request->params['prefix'])); $namespace .= '/' . implode('/', $prefixes); } if (strpos($controller, '\\') !== false || strpos($controller, '.') !== false) { return false; } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return false; } $reflection = new ReflectionClass($className); if ($reflection->isAbstract() || $reflection->isInterface()) { return false; } return $reflection->newInstance($request, $response, $controller); }
/** * Resolve a driver classname. * * Part of the template method for Cake\Utility\ObjectRegistry::load() * * @param string $class Partial classname to resolve. * @return string|false Either the correct classname or false. */ protected function _resolveClassName($class) { if (is_object($class)) { return $class; } return App::classname($class, 'Datasource'); }
/** * Override startup of the Shell * * @return void */ public function startup() { parent::startup(); if (isset($this->params['connection'])) { $this->connection = $this->params['connection']; } $class = Configure::read('Acl.classname'); $className = App::classname('Acl.' . $class, 'Adapter'); if ($class !== 'DbAcl' && !is_subclass_of($className, 'Acl\\Adapter\\DbAcl')) { $out = "--------------------------------------------------\n"; $out .= __d('cake_acl', 'Error: Your current CakePHP configuration is set to an ACL implementation other than DB.') . "\n"; $out .= __d('cake_acl', 'Please change your core config to reflect your decision to use DbAcl before attempting to use this script') . "\n"; $out .= "--------------------------------------------------\n"; $out .= __d('cake_acl', 'Current ACL Classname: %s', $class) . "\n"; $out .= "--------------------------------------------------\n"; $this->err($out); return $this->_stop(); } if ($this->command) { if (Configure::check('Datasource') === null) { $this->out(__d('cake_acl', 'Your database configuration was not found. Take a moment to create one.')); $this->args = null; return $this->DbConfig->execute(); } if (!in_array($this->command, ['initdb'])) { $registry = new ComponentRegistry(); $this->Acl = new AclComponent($registry); $controller = new Controller(); } } }
/** * Get controller to use, either plugin controller or application controller * * @param \Cake\Network\Request $request Request object * @param \Cake\Network\Response $response Response for the controller. * @return mixed name of controller if not loaded, or object if loaded */ protected function _getController($request, $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if ($pluginPath) { return parent::_getController($request, $response); } if (!empty($request->params['controller'])) { $controller = $request->params['controller']; } if (!empty($request->params['prefix'])) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return false; } $instance = PipingBag::get($className); if (method_exists($instance, 'viewBuilder')) { $instance->viewBuilder(); } else { $instance->viewPath = null; } $instance->name = $controller; $instance->setRequest($request); $instance->response = $response; return $instance; }
/** * Get controller to use, either plugin controller or application controller * * @param \Cake\Network\Request $request Request object * @param \Cake\Network\Response $response Response for the controller. * @return mixed name of controller if not loaded, or object if loaded */ protected function _getController($request, $response) { $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginPath = $request->params['plugin'] . '.'; } if (!empty($request->params['controller'])) { $controller = $request->params['controller']; } if (!empty($request->params['prefix'])) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } $className = false; if ($pluginPath . $controller) { $className = App::classname($pluginPath . $controller, $namespace, 'Controller'); } if (!$className) { return false; } $reflection = new \ReflectionClass($className); if ($reflection->isAbstract() || $reflection->isInterface()) { return false; } return $reflection->newInstance($request, $response); }
/** * Default Constructor * * ### Settings: * * - `engine` Class name to use to replace Cake\Utility\Number functionality * The class needs to be placed in the `Utility` directory. * * @param View $View The View this helper is being attached to. * @param array $config Configuration settings for the helper * @throws \Cake\Error\Exception When the engine class could not be found. */ public function __construct(View $View, array $config = array()) { parent::__construct($View, $config); $config = $this->_config; $engineClass = App::classname($config['engine'], 'Utility'); if ($engineClass) { $this->_engine = new $engineClass($config); } else { throw new Error\Exception(sprintf('Class for %s could not be found', $config['engine'])); } }
/** * Constructs the view class instance based on object properties. * * @param string $viewClass Optional namespaced class name of the View class to instantiate. * @return View */ public function createView($viewClass = null) { if ($viewClass === null) { $viewClass = $this->viewClass; if ($this->viewClass !== 'View') { list($plugin, $viewClass) = pluginSplit($viewClass, true); $viewClass = App::classname($viewClass, 'View', 'View'); } } $viewOptions = array_intersect_key(get_object_vars($this), array_flip($this->_validViewOptions)); return new $viewClass($this->request, $this->response, $this->getEventManager(), $viewOptions); }
/** * Constructor. Will return an instance of the correct ACL class as defined in `Configure::read('Acl.classname')` * * @param ComponentRegistry $collection * @param array $config * @throws \Cake\Error\Exception when Acl.classname could not be loaded. */ public function __construct(ComponentRegistry $collection, array $config = array()) { parent::__construct($collection, $config); $classname = $name = Configure::read('Acl.classname'); if (!class_exists($classname)) { $classname = App::classname($name, 'Controller/Component/Acl'); if (!$classname) { throw new Error\Exception(sprintf('Could not find %s.', $name)); } } $this->adapter($classname); }
protected function configure() { $this->bind('Cake\\Event\\EventManager'); $this->install(new AssistedModule()); array_map(function ($module) { if (!is_string($module)) { return $module; } $class = App::classname($module, 'Di/Module'); if (!$class) { throw new \InvalidArgumentException('Invalid Di module name: ' . $module); } $this->install(new $class()); }, $this->configuration); }
/** * Renders the given cell. * * Example: * * {{{ * // Taxonomy\View\Cell\TagCloudCell::smallList() * $cell = $this->cell('Taxonomy.TagCloud::smallList', ['limit' => 10]); * * // App\View\Cell\TagCloudCell::smallList() * $cell = $this->cell('TagCloud::smallList', ['limit' => 10]); * }}} * * The `display` action will be used by default when no action is provided: * * {{{ * // Taxonomy\View\Cell\TagCloudCell::display() * $cell = $this->cell('Taxonomy.TagCloud'); * }}} * * Cells are not rendered until they are echoed. * * @param string $cell You must indicate both cell name, and optionally a cell action. e.g.: `TagCloud::smallList` * will invoke `View\Cell\TagCloudCell::smallList()`, `display` action will be invoked by default when none is provided. * @param array $data Additional arguments for cell method. e.g.: * `cell('TagCloud::smallList', ['a1' => 'v1', 'a2' => 'v2'])` maps to `View\Cell\TagCloud::smallList(v1, v2)` * @param array $options Options for Cell's constructor * @return \Cake\View\Cell The cell instance * @throws \Cake\View\Error\MissingCellException If Cell class was not found */ public function cell($cell, $data = [], $options = []) { $parts = explode('::', $cell); if (count($parts) == 2) { list($pluginAndCell, $action) = [$parts[0], $parts[1]]; } else { list($pluginAndCell, $action) = [$parts[0], 'display']; } list($plugin, $cellName) = pluginSplit($pluginAndCell); $className = App::classname($pluginAndCell, 'View/Cell', 'Cell'); if (!$className) { throw new Error\MissingCellException(array('className' => $pluginAndCell . 'Cell')); } $cellInstance = new $className($this->request, $this->response, $this->getEventManager(), $options); $cellInstance->template = Inflector::underscore($action); $cellInstance->plugin = !empty($plugin) ? $plugin : null; $cellInstance->theme = !empty($this->theme) ? $this->theme : null; $length = count($data); if ($length) { $data = array_values($data); } call_user_func_array([$cellInstance, $action], $data); return $cellInstance; }
/** * Returns the class used to hydrate rows for this table or sets * a new one * * @param string $name the name of the class to use * @throws \RuntimeException when the entity class cannot be found * @return string */ public function entityClass($name = null) { if ($name === null && !$this->_documentClass) { $default = '\\Cake\\ElasticSearch\\Document'; $self = get_called_class(); $parts = explode('\\', $self); if ($self === __CLASS__ || count($parts) < 3) { return $this->_documentClass = $default; } $alias = Inflector::singularize(substr(array_pop($parts), 0, -4)); $name = implode('\\', array_slice($parts, 0, -1)) . '\\Document\\' . $alias; if (!class_exists($name)) { return $this->_documentClass = $default; } } if ($name !== null) { $class = App::classname($name, 'Model/Document'); $this->_documentClass = $class; } if (!$this->_documentClass) { throw new \RuntimeException(sprintf('Missing document class "%s"', $class)); } return $this->_documentClass; }
/** * Build and set all the view properties needed to render the templated emails. * If there is no template set, the $content will be returned in a hash * of the text content types for the email. * * @param string $content The content passed in from send() in most cases. * @return array The rendered content with html and text keys. */ protected function _renderTemplates($content) { $types = $this->_getTypes(); $rendered = array(); if (empty($this->_template)) { foreach ($types as $type) { $rendered[$type] = $this->_encodeString($content, $this->charset); } return $rendered; } $viewClass = $this->_viewRender; if ($viewClass === 'View') { $viewClass = App::classname('View', 'View'); } else { $viewClass = App::classname($viewClass, 'View', 'View'); } $viewClass = 'Cake\\View\\View'; $View = new $viewClass(null); $View->viewVars = $this->_viewVars; $View->helpers = $this->_helpers; if ($this->_theme) { $View->theme = $this->_theme; } $View->loadHelpers(); list($templatePlugin, $template) = pluginSplit($this->_template); list($layoutPlugin, $layout) = pluginSplit($this->_layout); if ($templatePlugin) { $View->plugin = $templatePlugin; } elseif ($layoutPlugin) { $View->plugin = $layoutPlugin; } if ($View->get('content') === null) { $View->set('content', $content); } // Convert null to false, as View needs false to disable // the layout. if ($this->_layout === null) { $this->_layout = false; } foreach ($types as $type) { $View->hasRendered = false; $View->viewPath = $View->layoutPath = 'Email/' . $type; $render = $View->render($this->_template, $this->_layout); $render = str_replace(array("\r\n", "\r"), "\n", $render); $rendered[$type] = $this->_encodeString($render, $this->charset); } foreach ($rendered as $type => $content) { $rendered[$type] = $this->_wrap($content); $rendered[$type] = implode("\n", $rendered[$type]); $rendered[$type] = rtrim($rendered[$type], "\n"); } return $rendered; }
/** * Load controller and return controller class name * * @param \Cake\Network\Request $request * @return string|bool Name of controller class name */ protected function _loadController($request) { $pluginName = $pluginPath = $controller = null; $namespace = 'Controller'; if (!empty($request->params['plugin'])) { $pluginName = Inflector::camelize($request->params['plugin']); $pluginPath = $pluginName . '.'; } if (!empty($request->params['controller'])) { $controller = Inflector::camelize($request->params['controller']); } if (!empty($request->params['prefix'])) { $namespace .= '/' . Inflector::camelize($request->params['prefix']); } if ($pluginPath . $controller) { return App::classname($pluginPath . $controller, $namespace, 'Controller'); } return false; }
/** * Generates a mocked controller and mocks any classes passed to `$mocks`. By * default, `stop()` is stubbed as is sending the response headers, so to not * interfere with testing. * * ### Mocks: * * - `methods` Methods to mock on the controller. * - `models` Models to mock. Models are added to the ClassRegistry so any * time they are instantiated the mock will be created. Pass as key value pairs * with the value being specific methods on the model to mock. If `true` or * no value is passed, the entire model will be mocked. * - `components` Components to mock. Components are only mocked on this controller * and not within each other (i.e., components on components) * * @param string $controller Controller name * @param array $mocks List of classes and methods to mock * @return \Cake\Controller\Controller Mocked controller * @throws \Cake\Controller\Error\MissingControllerException When controllers could not be created. * @throws \Cake\Controller\Error\MissingComponentException When components could not be created. */ public function generate($controller, array $mocks = array()) { $classname = App::classname($controller, 'Controller', 'Controller'); if (!$classname) { list($plugin, $controller) = pluginSplit($controller); throw new MissingControllerException(array('class' => $controller . 'Controller', 'plugin' => $plugin)); } $mocks = array_merge(array('methods' => null, 'models' => array(), 'components' => array()), $mocks); list(, $controllerName) = namespaceSplit($classname); $name = substr($controllerName, 0, -10); $request = $this->getMock('Cake\\Network\\Request'); $response = $this->getMock('Cake\\Network\\Response', array('_sendHeader', 'stop')); $controller = $this->getMock($classname, $mocks['methods'], array($request, $response, $name)); foreach ($mocks['models'] as $model => $methods) { if (is_string($methods)) { $model = $methods; $methods = true; } if ($methods === true) { $methods = array(); } $this->getMockForModel($model, $methods); } foreach ($mocks['components'] as $component => $methods) { if (is_string($methods)) { $component = $methods; $methods = true; } if ($methods === true) { $methods = array(); } $componentClass = App::classname($component, 'Controller/Component', 'Component'); list(, $name) = pluginSplit($component, true); if (!$componentClass) { throw new MissingComponentException(array('class' => $name . 'Component')); } $registry = $controller->components(); $config = isset($controller->components[$component]) ? $controller->components[$component] : array(); $component = $this->getMock($componentClass, $methods, array($registry, $config)); $registry->set($name, $component); } $controller->constructClasses(); $this->_dirtyController = false; $this->controller = $controller; return $this->controller; }
/** * Connects a new Route in the router. * * Routes are a way of connecting request URLs to objects in your application. * At their core routes are a set or regular expressions that are used to * match requests to destinations. * * Examples: * * `Router::connect('/:controller/:action/*');` * * The first parameter will be used as a controller name while the second is * used as the action name. The '/*' syntax makes this route greedy in that * it will match requests like `/posts/index` as well as requests * like `/posts/edit/1/foo/bar`. * * `Router::connect('/home-page', ['controller' => 'pages', 'action' => 'display', 'home']);` * * The above shows the use of route parameter defaults. And providing routing * parameters for a static route. * * {{{ * Router::connect( * '/:lang/:controller/:action/:id', * [], * ['id' => '[0-9]+', 'lang' => '[a-z]{3}'] * ); * }}} * * Shows connecting a route with custom route parameters as well as * providing patterns for those parameters. Patterns for routing parameters * do not need capturing groups, as one will be added for each route params. * * $options offers several 'special' keys that have special meaning * in the $options array. * * - `pass` is used to define which of the routed parameters should be shifted * into the pass array. Adding a parameter to pass will remove it from the * regular route array. Ex. `'pass' => array('slug')`. * - `routeClass` is used to extend and change how individual routes parse requests * and handle reverse routing, via a custom routing class. * Ex. `'routeClass' => 'SlugRoute'` * - `_name` is used to define a specific name for routes. This can be used to optimize * reverse routing lookups. If undefined a name will be generated for each * connected route. * - `_ext` is an array of filename extensions that will be parsed out of the url if present. * See {@link Route::parseExtensions()}. * * You can also add additional conditions for matching routes to the $defaults array. * The following conditions can be used: * * - `[type]` Only match requests for specific content types. * - `[method]` Only match requests with specific HTTP verbs. * - `[server]` Only match when $_SERVER['SERVER_NAME'] matches the given value. * * Example of using the `[method]` condition: * * `Router::connect('/tasks', array('controller' => 'tasks', 'action' => 'index', '[method]' => 'GET'));` * * The above route will only be matched for GET requests. POST requests will fail to match this route. * * @param string $route A string describing the template of the route * @param array $defaults An array describing the default route parameters. These parameters will be used by default * and can supply routing parameters that are not dynamic. See above. * @param array $options An array matching the named elements in the route to regular expressions which that * element should match. Also contains additional parameters such as which routed parameters should be * shifted into the passed arguments, supplying patterns for routing parameters and supplying the name of a * custom routing class. * @see routes * @return void * @throws \Cake\Error\Exception */ public static function connect($route, $defaults = [], $options = []) { static::$initialized = true; $defaults += ['plugin' => null]; if (empty($options['action'])) { $defaults += array('action' => 'index'); } if (empty($options['_ext'])) { $options['_ext'] = static::$_validExtensions; } $routeClass = static::$_routeClass; if (isset($options['routeClass'])) { $routeClass = App::classname($options['routeClass'], 'Routing/Route'); $routeClass = static::_validateRouteClass($routeClass); unset($options['routeClass']); } if ($routeClass === 'Cake\\Routing\\Route\\RedirectRoute' && isset($defaults['redirect'])) { $defaults = $defaults['redirect']; } static::$_routes->add(new $routeClass($route, $defaults, $options)); }
/** * Returns the class used to hydrate rows for this table or sets * a new one * * @param string $name the name of the class to use * @throws \Cake\ORM\Error\MissingEntityException when the entity class cannot be found * @return string */ public function entityClass($name = null) { if ($name === null && !$this->_entityClass) { $default = '\\Cake\\ORM\\Entity'; $self = get_called_class(); $parts = explode('\\', $self); if ($self === __CLASS__ || count($parts) < 3) { return $this->_entityClass = $default; } $alias = Inflector::singularize(substr(array_pop($parts), 0, -5)); $name = implode('\\', array_slice($parts, 0, -1)) . '\\Entity\\' . $alias; if (!class_exists($name)) { return $this->_entityClass = $default; } } if ($name !== null) { $class = App::classname($name, 'Model/Entity'); $this->_entityClass = $class; } if (!$this->_entityClass) { throw new MissingEntityException([$name]); } return $this->_entityClass; }
/** * Load a CrudAction instance. * * @param string $name The controller action name. * @return \Crud\Action\BaseAction * @throws \Crud\Error\Exception\ActionNotConfiguredException * @throws \Crud\Error\Exception\MissingActionException */ protected function _loadAction($name) { if (!isset($this->_actionInstances[$name])) { $config = $this->config('actions.' . $name); if (empty($config)) { throw new ActionNotConfiguredException(sprintf('Action "%s" has not been mapped', $name)); } $className = App::classname($config['className'], 'Action', 'Action'); if (empty($className)) { throw new MissingActionException('Could not find action class: ' . $config['className']); } $this->_actionInstances[$name] = new $className($this->_controller); unset($config['className']); $this->_actionInstances[$name]->config($config); } return $this->_actionInstances[$name]; }
/** * Get a table instance from the registry. * * Tables are only created once until the registry is flushed. * This means that aliases must be unique across your application. * This is important because table associations are resolved at runtime * and cyclic references need to be handled correctly. * * The options that can be passed are the same as in `Table::__construct()`, but the * key `className` is also recognized. * * If $options does not contain `className` CakePHP will attempt to construct the * class name based on the alias. For example 'Users' would result in * `App\Model\Table\UsersTable` being attempted. If this class does not exist, * then the default `Cake\ORM\Table` class will be used. By setting the `className` * option you can define the specific class to use. This className can * use a plugin short class reference. * * If you use a `$name` that uses plugin syntax only the name part will be used as * key in the registry. This means that if two plugins, or a plugin and app provide * the same alias, the registry will only store the first instance. * * If no `table` option is passed, the table name will be the underscored version * of the provided $alias. * * If no `connection` option is passed the table's defaultConnectionName() method * will be called to get the default connection name to use. * * @param string $name The alias name you want to get. * @param array $options The options you want to build the table with. * If a table has already been loaded the options will be ignored. * @return \Cake\ORM\Table * @throws RuntimeException When you try to configure an alias that already exists. */ public static function get($name, array $options = []) { list($plugin, $alias) = pluginSplit($name); $exists = isset(static::$_instances[$alias]); if ($exists && !empty($options)) { throw new RuntimeException(sprintf('You cannot configure "%s", it already exists in the registry.', $alias)); } if ($exists) { return static::$_instances[$alias]; } $options = ['alias' => $alias] + $options; if (empty($options['className'])) { $options['className'] = Inflector::camelize($name); } $className = App::classname($options['className'], 'Model/Table', 'Table'); $options['className'] = $className ?: 'Cake\\ORM\\Table'; if (isset(static::$_config[$alias])) { $options = array_merge(static::$_config[$alias], $options); } if (empty($options['connection'])) { $connectionName = $options['className']::defaultConnectionName(); $options['connection'] = ConnectionManager::get($connectionName); } return static::$_instances[$alias] = new $options['className']($options); }
/** * Return password hasher object * * @return AbstractPasswordHasher Password hasher instance * @throws \Cake\Error\Exception If password hasher class not found or * it does not extend AbstractPasswordHasher */ public function passwordHasher() { if ($this->_passwordHasher) { return $this->_passwordHasher; } $passwordHasher = $this->_config['passwordHasher']; $config = array(); if (is_string($passwordHasher)) { $class = $passwordHasher; } else { $class = $passwordHasher['className']; $config = $passwordHasher; unset($config['className']); } list($plugin, $class) = pluginSplit($class, true); $className = App::classname($class, 'Controller/Component/Auth', 'PasswordHasher'); if (!class_exists($className)) { throw new Error\Exception(sprintf('Password hasher class "%s" was not found.', $class)); } $this->_passwordHasher = new $className($config); if (!$this->_passwordHasher instanceof AbstractPasswordHasher) { throw new Error\Exception('Password hasher must extend AbstractPasswordHasher class.'); } return $this->_passwordHasher; }
/** * Displays an exception response body. * * @param \Exception $exception The exception to display * @return void * @throws \Exception When the chosen exception renderer is invalid. */ protected function _displayException($exception) { $renderer = App::classname($this->_options['exceptionRenderer'], 'Error'); try { if (!$renderer) { throw new \Exception("{$renderer} is an invalid class."); } $error = new $renderer($exception); $error->render(); } catch (\Exception $e) { // Disable trace for internal errors. $this->_options['trace'] = false; $message = sprintf("[%s] %s\n%s", get_class($e), $e->getMessage(), $e->getTraceAsString()); trigger_error($message, E_USER_ERROR); } }
/** * Resolve a component classname. * * Part of the template method for Cake\Utility\ObjectRegistry::load() * * @param string $class Partial classname to resolve. * @return string|false Either the correct classname or false. */ protected function _resolveClassName($class) { return App::classname($class, 'Controller/Component', 'Component'); }
/** * Loads the translation file and parses it. Returns an instance of a translations * package containing the messages loaded from the file. * * @return \Aura\Intl\Package * @throws \RuntimeException if no file parser class could be found for the specified * file extension. */ public function __invoke() { $package = new Package('default'); $folders = $this->translationsFolders(); $ext = $this->_extension; $file = false; $fileName = $this->_name; $pos = strpos($fileName, '/'); if ($pos !== false) { $fileName = substr($fileName, $pos + 1); } foreach ($folders as $folder) { $path = $folder . $fileName . ".{$ext}"; if (is_file($path)) { $file = $path; break; } } if (!$file) { return $package; } $name = ucfirst($ext); $class = App::classname($name, 'I18n\\Parser', 'FileParser'); if (!$class) { throw new RuntimeException(sprintf('Could not find class %s', "{$name}FileParser")); } $messages = (new $class())->parse($file); $package->setMessages($messages); return $package; }
/** * Resolve a behavior classname. * * Part of the template method for Cake\Utility\ObjectRegistry::load() * * @param string $class Partial classname to resolve. * @return string|false Either the correct classname or false. */ protected function _resolveClassName($class) { return App::classname($class, 'Model/Behavior', 'Behavior'); }
/** * Resolve a task classname. * * Part of the template method for Cake\Utility\ObjectRegistry::load() * * @param string $class Partial classname to resolve. * @return string|false Either the correct classname or false. */ protected function _resolveClassName($class) { return App::classname($class, 'Console/Command/Task', 'Task'); }
/** * Mock a model, maintain fixtures and table association * * @param string $alias * @param array $methods * @param array $options * @throws \Cake\ORM\Error\MissingTableClassException * @return Model */ public function getMockForModel($alias, array $methods = array(), array $options = array()) { if (empty($options['className'])) { $class = Inflector::camelize($alias); $className = App::classname($class, 'Model/Table', 'Table'); if (!$className) { throw new \Cake\ORM\Error\MissingTableClassException(array($alias)); } $options['className'] = $className; } list($plugin, $baseClass) = pluginSplit($alias); $options += ['alias' => $baseClass] + TableRegistry::config($alias); $mock = $this->getMock($options['className'], $methods, array($options)); TableRegistry::set($alias, $mock); return $mock; }
/** * Synchronizes all controllers and existing actions to the database * * @param boolean/String $prefix * @param boolean/String $plugin * @param array $permission_ids * @return array $permission_ids */ public function synchronize($prefix = false, $plugin = false, array $permission_ids = []) { $classname = ''; if (!$plugin) { $path = App::path('Controller/' . $prefix)[0]; } else { if ($plugin && is_string($prefix)) { $path = App::path('Controller/' . $prefix, $plugin)[0]; $classname = $plugin . '.'; } } $type_prefix = $prefix === '/' || is_bool($prefix) ? '' : '/' . $prefix; $Permission = TableRegistry::get('Permission'); $files = scandir($path); $this->all_files = array_merge($this->all_files, $files); foreach ($files as $file) { if (in_array($file, $this->_sync_ignore_list['*']) || isset($this->_sync_ignore_list[$prefix]) && in_array($file, $this->_sync_ignore_list[$prefix])) { continue; } if (is_dir($path . $file)) { if ($prefix || !$plugin) { $permission_ids = $this->synchronize($file, $plugin, $permission_ids); } else { if ($plugin) { $permission_ids = $this->synchronize('/', $file, $permission_ids); } } continue; } $controller_name = str_replace('Controller', '', explode('.', $file)[0]); $class_name = App::classname($classname . $controller_name, 'Controller' . $type_prefix, 'Controller'); if (empty($class_name)) { continue; } $class = new ReflectionClass($class_name); $all_actions = $class->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($all_actions as $action) { $permission_prefix = ''; if ($plugin) { $permission_prefix .= $plugin . '.'; } if ($prefix) { $permission_prefix .= $prefix; } $class = new ReflectionClass($action->class); $file_name = explode('/', $class->getFileName()); $file_name = end($file_name); if (in_array($file_name, $this->_sync_ignore_list['*']) || $action->class != $class_name && !in_array($file_name, $this->all_files) || in_array($action->name, $this->_sync_ignore_list['*']['*']) || isset($this->_sync_ignore_list['*'][$controller_name]) && in_array($action->name, $this->_sync_ignore_list['*'][$controller_name]) || isset($this->_sync_ignore_list[$permission_prefix]['*']) && in_array($action->name, $this->_sync_ignore_list[$permission_prefix]['*']) || isset($this->_sync_ignore_list[$permission_prefix][$controller_name]) && in_array($action->name, $this->_sync_ignore_list[$permission_prefix][$controller_name])) { continue; } $unique_string = $this->getUniqueString($controller_name, $action->name, $prefix, $plugin); $permission_id = $Permission->find()->select(['id'])->where(['unique_string' => $unique_string])->first(); if (is_null($permission_id)) { $new_permission = $Permission->newEntity(); $new_permission->action = $action->name; $new_permission->controller = $controller_name; $new_permission->prefix = $permission_prefix; $new_permission->unique_string = $unique_string; if ($Permission->save($new_permission)) { array_push($permission_ids, $new_permission->id); } } else { array_push($permission_ids, $permission_id->id); } } } if (!$plugin && !$prefix) { foreach ($this->_plugins as $plugin) { $permission_ids = $this->synchronize('/', $plugin, $permission_ids); } $Permission->deleteAll(['id NOT IN' => $permission_ids]); } return $permission_ids; }